V4.1 with excel stats changes

This commit is contained in:
2025-10-28 16:13:05 +00:00
parent 95fb5d6ab8
commit f95e958ffb
2 changed files with 144 additions and 178 deletions

View File

@@ -1,5 +1,6 @@
using Newtonsoft.Json; using Newtonsoft.Json;
using System.ComponentModel; using System.ComponentModel;
using System.Data.OleDb;
using System.Diagnostics; using System.Diagnostics;
using System.Reflection; using System.Reflection;
@@ -226,7 +227,6 @@ namespace AiQ_GUI
await TestPassed(PCTime); await TestPassed(PCTime);
} }
public void Stats(string TypeOfTest) public void Stats(string TypeOfTest)
{ {
Stats([TypeOfTest]); Stats([TypeOfTest]);
@@ -234,7 +234,7 @@ namespace AiQ_GUI
public void Stats(string[] TypeOfTest) public void Stats(string[] TypeOfTest)
{ {
using OleDbConnection conn = new(connString); // Opens connection to Access database using OleDbConnection conn = new(Access.connString); // Opens connection to Access database
try try
{ {
conn.Open(); // Opens DB conn.Open(); // Opens DB
@@ -263,7 +263,7 @@ namespace AiQ_GUI
public void StatsDiags(string redDiagLabels, string RhTxBxActionsText, string IsRMA, int RMA) public void StatsDiags(string redDiagLabels, string RhTxBxActionsText, string IsRMA, int RMA)
{ {
using OleDbConnection conn = new(connString); using OleDbConnection conn = new(Access.connString);
conn.Open(); conn.Open();
// Null checks // Null checks
@@ -288,8 +288,6 @@ namespace AiQ_GUI
cmd.ExecuteNonQuery(); cmd.ExecuteNonQuery();
} }
private async void BtnPreTest_Click(object sender, EventArgs e) private async void BtnPreTest_Click(object sender, EventArgs e)
{ {
// Show user test has started // Show user test has started
@@ -337,6 +335,8 @@ namespace AiQ_GUI
await AllocateSerial(); await AllocateSerial();
else if (GoogleAPI.UpdateSpreadSheetRePreTest(CameraAccessInfo.SpreadsheetID, Vers) != "OK") // If rerun might be different values so update SS else if (GoogleAPI.UpdateSpreadSheetRePreTest(CameraAccessInfo.SpreadsheetID, Vers) != "OK") // If rerun might be different values so update SS
AddToActionsList("Failed to write to spreadsheet, please check manually"); AddToActionsList("Failed to write to spreadsheet, please check manually");
// else if (Excel.UpdateSpreadSheetPreTest(CameraAccessInfo.SpreadsheetID, Vers, CamOnTest.GetCamDesc(), CamOnTest.Model) != "OK")
// AddToActionsList("Failed to write to spreadsheet, please check manually");
} }
else // No serial or model so allocate one else // No serial or model so allocate one
await AllocateSerial(); await AllocateSerial();
@@ -415,25 +415,23 @@ namespace AiQ_GUI
Btn.BackColor = Color.Maroon; Btn.BackColor = Color.Maroon;
Btn.Text = "Test Failed"; Btn.Text = "Test Failed";
if (!(CamOnTest.RMANum != 0)) // Yap to check if it is not a RMA
{
Access.Stats(["Final Tests Failed", ErrMssg], CamOnTest.Model);
}
else
{
Access.Stats("RMA Final Tests Failed", CamOnTest.Model);
}
AddToActionsList(ErrMssg);
string RedLbls = string.Join(Environment.NewLine, PnlLbls.Controls string RedLbls = string.Join(Environment.NewLine, PnlLbls.Controls
.OfType<Label>() .OfType<Label>()
.Where(lbl => lbl.ForeColor == Color.Red) // Only include red labels .Where(lbl => lbl.ForeColor == Color.Red) // Only include red labels
.Select(lbl => lbl.Text)); // Extract text .Select(lbl => lbl.Text)); // Extract text
string FullFailureValues = RhTxBxActions.Text + Environment.NewLine + RedLbls; string FullFailureValues = RhTxBxActions.Text + Environment.NewLine + RedLbls;
Access.StatsDiags(RedLbls, RhTxBxActions.Text, CamOnTest.Model); // Log to Access database
// Database logging \\
if (!(CamOnTest.RMANum != 0)) // Yap to check if it is not a RMA
{
Stats(["Final Tests Failed", ErrMssg]);
StatsDiags(RedLbls, RhTxBxActions.Text, "FALSE", CamOnTest.RMANum);
}
else
{
Stats("RMA Final Tests Failed");
StatsDiags(RedLbls, RhTxBxActions.Text, "TRUE", CamOnTest.RMANum);
}
if (await DisplayQuestion("Test failed, appeal?" + Environment.NewLine + "See Actions textbox for details.")) if (await DisplayQuestion("Test failed, appeal?" + Environment.NewLine + "See Actions textbox for details."))
{ {
@@ -451,8 +449,6 @@ namespace AiQ_GUI
// Joins the actions box to any red labels to use as a full failed text // Joins the actions box to any red labels to use as a full failed text
Logging.LogErrorMessage(FullFailureValues); Logging.LogErrorMessage(FullFailureValues);
IList<IList<object>> values = GoogleAPI.service.Spreadsheets.Values.Get(GoogleAPI.spreadsheetId_ModelInfo, "'Approval'!A1:A").Execute().Values; IList<IList<object>> values = GoogleAPI.service.Spreadsheets.Values.Get(GoogleAPI.spreadsheetId_ModelInfo, "'Approval'!A1:A").Execute().Values;
if (values?.Count > 0) if (values?.Count > 0)
@@ -526,12 +522,23 @@ namespace AiQ_GUI
BtnNo.Visible = false; BtnNo.Visible = false;
Logging.LogMessage("Pre Test Failed"); Logging.LogMessage("Pre Test Failed");
if (CamOnTest.RMANum == 0) // Yap to check if it is not a RMA
{
Access.Stats(["Pre Tests Failed", ErrMssg], CamOnTest.Model);
}
else
{
Access.Stats("RMA Pre Tests Failed", CamOnTest.Model);
}
string RedLbls = string.Join(Environment.NewLine, PnlLbls.Controls string RedLbls = string.Join(Environment.NewLine, PnlLbls.Controls
.OfType<Label>() .OfType<Label>()
.Where(lbl => lbl.ForeColor == Color.Red) // Only include red labels .Where(lbl => lbl.ForeColor == Color.Red) // Only include red labels
.Select(lbl => lbl.Text)); // Extract text .Select(lbl => lbl.Text)); // Extract text
string FullFailureValues = RhTxBxActions.Text + Environment.NewLine + RedLbls; string FullFailureValues = RhTxBxActions.Text + Environment.NewLine + RedLbls;
Access.StatsDiags(RedLbls, RhTxBxActions.Text, CamOnTest.Model); // Log to Access database
if (CamOnTest.RMANum == 0) // Yap to check if it is not a RMA if (CamOnTest.RMANum == 0) // Yap to check if it is not a RMA
{ {
Stats(["Pre Tests Failed", ErrMssg]); Stats(["Pre Tests Failed", ErrMssg]);
@@ -543,10 +550,6 @@ namespace AiQ_GUI
StatsDiags(RedLbls, RhTxBxActions.Text, "TRUE", CamOnTest.RMANum); StatsDiags(RedLbls, RhTxBxActions.Text, "TRUE", CamOnTest.RMANum);
} }
// Log to Access database
Access.StatsDiags(RedLbls, RhTxBxActions.Text, CamOnTest.Model); // Log to Access database
if (await DisplayQuestion("Test failed, restart?" + Environment.NewLine + "See Actions textbox for details.")) if (await DisplayQuestion("Test failed, restart?" + Environment.NewLine + "See Actions textbox for details."))
Helper.RestartApp(); Helper.RestartApp();
} }
@@ -1127,7 +1130,6 @@ namespace AiQ_GUI
PnlInputValue.Visible = true; PnlInputValue.Visible = true;
while (Flags.Done == false) // Waiting for user input in RMA Num panel while (Flags.Done == false) // Waiting for user input in RMA Num panel
{
await Task.Delay(100); // Check every 100ms await Task.Delay(100); // Check every 100ms
Flags.Done = false; // Reset flag Flags.Done = false; // Reset flag
@@ -1786,41 +1788,9 @@ namespace AiQ_GUI
{ {
Stopwatch stopWatchTest = Stopwatch.StartNew(); Stopwatch stopWatchTest = Stopwatch.StartNew();
//StatsExcel excelExporter = new();
//excelExporter.ExportDatabaseToExcel();
StatsExcel excelExporter = new(); StatsExcel excelExporter = new();
excelExporter.ExportDatabaseToExcel(); excelExporter.ExportDatabaseToExcel();
// FakeCamera fakeCamera = new FakeCamera(80); // Create an instance of FakeCamera
// //CamOnTest.IP = CbBxFoundCams.Text;
// _ = fakeCamera.StartAsync(CAMTYPE.BAD).ContinueWith(task =>
// {
// //Network.Initialize("developer", "Pass123");
// if (task.IsFaulted)
// {
// AddToActionsList("Error starting FakeCamera: " + task.Exception?.Message);
// }
// else
// {
// AddToActionsList($"FakeCamera started successfully. IP: {fakeCamera}", false);
// }
// });
// await Task.Delay(3000); // Wait for server to start
// CbBxFoundCams.Text = "localhost"; // Should force update in creds an network reinit
// CmBoFoundCams_TextChanged(sender, e);
// CbBxCameraType.SelectedIndex = CbBxCameraType.Items.Count - 1; // Selects AB12CD as model number
// await Task.Delay(3000); // Wait for server to start
//BtnPreTest_Click(sender, e);
stopWatchTest.Stop(); stopWatchTest.Stop();
AddToActionsList("RunTime " + stopWatchTest.Elapsed.ToString(@"hh\:mm\:ss\.ff")); AddToActionsList("RunTime " + stopWatchTest.Elapsed.ToString(@"hh\:mm\:ss\.ff"));
} }

View File

@@ -8,40 +8,36 @@ namespace AiQ_GUI
{ {
private const string exportPath = @"G:\Shared drives\MAV Production GUI's\AiQ\GUI's\AiQ_Test_Stats.xlsx"; private const string exportPath = @"G:\Shared drives\MAV Production GUI's\AiQ\GUI's\AiQ_Test_Stats.xlsx";
private readonly string exportPath =
@"C:\Users\BradleyBorn\OneDrive - MAV Systems Ltd\Desktop\AiQ_Test_Stats.xlsx";
public void ExportDatabaseToExcel() public void ExportDatabaseToExcel()
{ {
try try
{ {
MainForm.Instance.AddToActionsList("=== ExportDatabaseToExcel START ==="); MainForm.Instance.AddToActionsList("=== ExportDatabaseToExcel START ===");
using (OleDbConnection conn = new(Access.connString)) using OleDbConnection conn = new(Access.connString);
conn.Open();
MainForm.Instance.AddToActionsList("Connected to Access database.");
DateTime now = DateTime.Now;
// Read LastStatsRun from UniversalData (if any)
DateTime? lastStatsRun = null;
try
{ {
conn.Open(); using (var cmdPeriod = new OleDbCommand("SELECT LastStatsRun FROM UniversalData", conn))
MainForm.Instance.AddToActionsList("Connected to Access database.");
DateTime now = DateTime.Now;
// Read LastStatsRun from UniversalData (if any)
DateTime? lastStatsRun = null;
try
{ {
using (var cmdPeriod = new OleDbCommand("SELECT LastStatsRun FROM UniversalData", conn)) object res = cmdPeriod.ExecuteScalar();
{ if (res != null && res != DBNull.Value)
object res = cmdPeriod.ExecuteScalar(); lastStatsRun = (DateTime)res;
if (res != null && res != DBNull.Value)
lastStatsRun = (DateTime)res;
}
MainForm.Instance.AddToActionsList($"Fetched LastStatsRun: {(lastStatsRun.HasValue ? lastStatsRun.Value.ToString("yyyy-MM-dd HH:mm:ss") : "none")}");
}
catch (Exception periodEx)
{
MainForm.Instance.AddToActionsList($"Warning: could not read LastStatsRun. Details: {periodEx.Message}");
} }
MainForm.Instance.AddToActionsList($"Fetched LastStatsRun: {(lastStatsRun.HasValue ? lastStatsRun.Value.ToString("yyyy-MM-dd HH:mm:ss") : "none")}");
}
catch (Exception periodEx)
{
MainForm.Instance.AddToActionsList($"Warning: could not read LastStatsRun. Details: {periodEx.Message}");
}
// ==================== MAIN STATS EXPORT ==================== // ==================== MAIN STATS EXPORT ====================
string selectColumns = @" string selectColumns = @"
ModelNumber, ModelNumber,
[Total Tests Run], [Total Tests Run],
[Pre Tests Passed], [Pre Tests Passed],
@@ -65,71 +61,71 @@ namespace AiQ_GUI
[Visual Test Fail - Not All Rear Screws Fitted], [Visual Test Fail - Not All Rear Screws Fitted],
[Visual Test Fail - Unit rattles]"; [Visual Test Fail - Unit rattles]";
string query = $@" string query = $@"
SELECT SELECT
{selectColumns} {selectColumns}
FROM AiQ"; FROM AiQ";
OleDbDataAdapter adapter = new(query, conn); OleDbDataAdapter adapter = new(query, conn);
DataTable dataTable = new(); DataTable dataTable = new();
adapter.Fill(dataTable); adapter.Fill(dataTable);
if (dataTable.Rows.Count == 0) if (dataTable.Rows.Count == 0)
{ {
MainForm.Instance.AddToActionsList("No data found in AiQ table."); MainForm.Instance.AddToActionsList("No data found in AiQ table.");
return; return;
} }
string monthName = now.ToString("MMMM"); string monthName = now.ToString("MMMM");
string sheetName = $"{monthName} Stats"; string sheetName = $"{monthName} Stats";
MainForm.Instance.AddToActionsList($"Adding sheet: {sheetName}"); MainForm.Instance.AddToActionsList($"Adding sheet: {sheetName}");
XLWorkbook workbook; XLWorkbook workbook;
if (File.Exists(exportPath)) if (File.Exists(exportPath))
{ {
workbook = new XLWorkbook(exportPath); workbook = new XLWorkbook(exportPath);
MainForm.Instance.AddToActionsList("Opened existing workbook."); MainForm.Instance.AddToActionsList("Opened existing workbook.");
} }
else else
{ {
workbook = new XLWorkbook(); workbook = new XLWorkbook();
MainForm.Instance.AddToActionsList("Created new workbook (file not found)."); MainForm.Instance.AddToActionsList("Created new workbook (file not found).");
} }
if (workbook.Worksheets.Contains(sheetName)) if (workbook.Worksheets.Contains(sheetName))
{ {
workbook.Worksheet(sheetName).Delete(); workbook.Worksheet(sheetName).Delete();
MainForm.Instance.AddToActionsList($"Deleted old sheet: {sheetName}"); MainForm.Instance.AddToActionsList($"Deleted old sheet: {sheetName}");
} }
IXLWorksheet ws = workbook.Worksheets.Add(sheetName); IXLWorksheet ws = workbook.Worksheets.Add(sheetName);
ws.Cell(1, 1).InsertTable(dataTable, "AiQ_Stats", true); ws.Cell(1, 1).InsertTable(dataTable, "AiQ_Stats", true);
ws.Columns().AdjustToContents(); ws.Columns().AdjustToContents();
// Write Data Period label and computed period string to the right of the table // Write Data Period label and computed period string to the right of the table
int infoCol = dataTable.Columns.Count + 2; int infoCol = dataTable.Columns.Count + 2;
ws.Cell(1, infoCol).Value = "Data Period"; ws.Cell(1, infoCol).Value = "Data Period";
string periodText; string periodText;
if (lastStatsRun.HasValue) if (lastStatsRun.HasValue)
{ {
periodText = $"{lastStatsRun.Value:yyyy-MM-dd HH:mm:ss} - {now:yyyy-MM-dd HH:mm:ss}"; periodText = $"{lastStatsRun.Value:yyyy-MM-dd HH:mm:ss} - {now:yyyy-MM-dd HH:mm:ss}";
} }
else else
{ {
periodText = $"Up to {now:yyyy-MM-dd HH:mm:ss}"; periodText = $"Up to {now:yyyy-MM-dd HH:mm:ss}";
} }
ws.Cell(2, infoCol).Value = periodText; ws.Cell(2, infoCol).Value = periodText;
// ==================== DIAGS STATS EXPORT (CURRENT MONTH ONLY) ==================== // ==================== DIAGS STATS EXPORT (CURRENT MONTH ONLY) ====================
MainForm.Instance.AddToActionsList("Exporting DiagsStats for current month..."); MainForm.Instance.AddToActionsList("Exporting DiagsStats for current month...");
DateTime monthStart = new(now.Year, now.Month, 1); DateTime monthStart = new(now.Year, now.Month, 1);
DateTime nextMonth = monthStart.AddMonths(1); DateTime nextMonth = monthStart.AddMonths(1);
string diagsQuery = @" string diagsQuery = @"
SELECT SELECT
[Date], [Date],
[Model], [Model],
@@ -140,70 +136,70 @@ namespace AiQ_GUI
FROM DiagsStats FROM DiagsStats
WHERE [Date] >= ? AND [Date] < ?"; WHERE [Date] >= ? AND [Date] < ?";
using (var diagsCmd = new OleDbCommand(diagsQuery, conn)) using (var diagsCmd = new OleDbCommand(diagsQuery, conn))
{
diagsCmd.Parameters.Add(new OleDbParameter { OleDbType = OleDbType.Date, Value = monthStart });
diagsCmd.Parameters.Add(new OleDbParameter { OleDbType = OleDbType.Date, Value = nextMonth });
using (var diagsAdapter = new OleDbDataAdapter(diagsCmd))
{ {
diagsCmd.Parameters.Add(new OleDbParameter { OleDbType = OleDbType.Date, Value = monthStart }); DataTable diagsTable = new();
diagsCmd.Parameters.Add(new OleDbParameter { OleDbType = OleDbType.Date, Value = nextMonth }); diagsAdapter.Fill(diagsTable);
using (var diagsAdapter = new OleDbDataAdapter(diagsCmd)) if (diagsTable.Rows.Count > 0)
{ {
DataTable diagsTable = new(); int startRow = (ws.LastRowUsed()?.RowNumber() ?? 0) + 3;
diagsAdapter.Fill(diagsTable);
if (diagsTable.Rows.Count > 0) ws.Cell(startRow, 1).Value = "Diags Stats (Current Month)";
{ ws.Cell(startRow, 1).Style.Font.Bold = true;
int startRow = (ws.LastRowUsed()?.RowNumber() ?? 0) + 3; ws.Cell(startRow, 1).Style.Font.FontSize = 12;
ws.Cell(startRow, 1).Value = "Diags Stats (Current Month)"; ws.Cell(startRow + 1, 1).InsertTable(diagsTable, "Diags_Stats", true);
ws.Cell(startRow, 1).Style.Font.Bold = true; ws.Columns().AdjustToContents();
ws.Cell(startRow, 1).Style.Font.FontSize = 12;
ws.Cell(startRow + 1, 1).InsertTable(diagsTable, "Diags_Stats", true); MainForm.Instance.AddToActionsList($"Added DiagsStats ({diagsTable.Rows.Count} rows) starting at row {startRow}.");
ws.Columns().AdjustToContents();
MainForm.Instance.AddToActionsList($"Added DiagsStats ({diagsTable.Rows.Count} rows) starting at row {startRow}.");
}
} }
} }
}
// ==================== SAVE MAIN SHEET ==================== // ==================== SAVE MAIN SHEET ====================
workbook.SaveAs(exportPath); workbook.SaveAs(exportPath);
MainForm.Instance.AddToActionsList($"Added {sheetName} to workbook: {exportPath}"); MainForm.Instance.AddToActionsList($"Added {sheetName} to workbook: {exportPath}");
workbook.Dispose(); workbook.Dispose();
// ==================== BACKUP TABLE (ALWAYS, BEFORE RESET) ==================== // ==================== BACKUP TABLE (ALWAYS, BEFORE RESET) ====================
string ts = now.ToString("yyyyMMdd_HHmmss"); string ts = now.ToString("yyyyMMdd_HHmmss");
string backupTableName = $"Ztats_{ts}"; string backupTableName = $"Ztats_{ts}";
if (backupTableName.Length > 64) if (backupTableName.Length > 64)
backupTableName = backupTableName.Substring(0, 64); backupTableName = backupTableName.Substring(0, 64);
string backupSql = $@" string backupSql = $@"
SELECT SELECT
{selectColumns} {selectColumns}
INTO [{backupTableName}] INTO [{backupTableName}]
FROM AiQ"; FROM AiQ";
try
{
using (OleDbCommand cmdBackup = new(backupSql, conn))
{
cmdBackup.ExecuteNonQuery();
}
MainForm.Instance.AddToActionsList($"Created backup table: [{backupTableName}]");
}
catch (Exception backupEx)
{
MainForm.Instance.AddToActionsList($"ERROR creating backup table [{backupTableName}]. Aborting reset to protect data. Details: {backupEx.Message}");
MainForm.Instance.AddToActionsList("=== ExportDatabaseToExcel END (backup failed, no reset) ===");
return;
}
using (var tx = conn.BeginTransaction())
{
try try
{ {
using (OleDbCommand cmdBackup = new(backupSql, conn)) string resetSql = @"
{
cmdBackup.ExecuteNonQuery();
}
MainForm.Instance.AddToActionsList($"Created backup table: [{backupTableName}]");
}
catch (Exception backupEx)
{
MainForm.Instance.AddToActionsList($"ERROR creating backup table [{backupTableName}]. Aborting reset to protect data. Details: {backupEx.Message}");
MainForm.Instance.AddToActionsList("=== ExportDatabaseToExcel END (backup failed, no reset) ===");
return;
}
using (var tx = conn.BeginTransaction())
{
try
{
string resetSql = @"
UPDATE AiQ SET UPDATE AiQ SET
[Total Tests Run] = 0, [Total Tests Run] = 0,
[Pre Tests Passed] = 0, [Pre Tests Passed] = 0,