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 System.ComponentModel;
using System.Data.OleDb;
using System.Diagnostics;
using System.Reflection;
@@ -226,7 +227,6 @@ namespace AiQ_GUI
await TestPassed(PCTime);
}
public void Stats(string TypeOfTest)
{
Stats([TypeOfTest]);
@@ -234,7 +234,7 @@ namespace AiQ_GUI
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
{
conn.Open(); // Opens DB
@@ -263,7 +263,7 @@ namespace AiQ_GUI
public void StatsDiags(string redDiagLabels, string RhTxBxActionsText, string IsRMA, int RMA)
{
using OleDbConnection conn = new(connString);
using OleDbConnection conn = new(Access.connString);
conn.Open();
// Null checks
@@ -288,8 +288,6 @@ namespace AiQ_GUI
cmd.ExecuteNonQuery();
}
private async void BtnPreTest_Click(object sender, EventArgs e)
{
// Show user test has started
@@ -337,6 +335,8 @@ namespace AiQ_GUI
await AllocateSerial();
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");
// 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
await AllocateSerial();
@@ -348,8 +348,8 @@ namespace AiQ_GUI
{
await PreTestFailed("Diagnostic Failure");
}
}
// ***** Pass/Fails *****
@@ -415,25 +415,23 @@ namespace AiQ_GUI
Btn.BackColor = Color.Maroon;
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
.OfType<Label>()
.Where(lbl => lbl.ForeColor == Color.Red) // Only include red labels
.Select(lbl => lbl.Text)); // Extract text
string FullFailureValues = RhTxBxActions.Text + Environment.NewLine + RedLbls;
// 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);
}
Access.StatsDiags(RedLbls, RhTxBxActions.Text, CamOnTest.Model); // Log to Access database
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
Logging.LogErrorMessage(FullFailureValues);
IList<IList<object>> values = GoogleAPI.service.Spreadsheets.Values.Get(GoogleAPI.spreadsheetId_ModelInfo, "'Approval'!A1:A").Execute().Values;
if (values?.Count > 0)
@@ -526,12 +522,23 @@ namespace AiQ_GUI
BtnNo.Visible = false;
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
.OfType<Label>()
.Where(lbl => lbl.ForeColor == Color.Red) // Only include red labels
.Select(lbl => lbl.Text)); // Extract text
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
{
Stats(["Pre Tests Failed", ErrMssg]);
@@ -543,10 +550,6 @@ namespace AiQ_GUI
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."))
Helper.RestartApp();
}
@@ -746,7 +749,7 @@ namespace AiQ_GUI
Access.Stats("Please Get A Valid Vaxtor Product Key Before Continuing", CamOnTest.Model);
await TestFailed(BtnStartTest, "Please get a valid Vaxtor Product Key before continuing");
}
DiagsAPI.licenses.raptorKeyID = TxBxProductKey.Text;
lblVaxtor.Text += DiagsAPI.licenses.raptorKeyID;
@@ -1127,7 +1130,6 @@ namespace AiQ_GUI
PnlInputValue.Visible = true;
while (Flags.Done == false) // Waiting for user input in RMA Num panel
{
await Task.Delay(100); // Check every 100ms
Flags.Done = false; // Reset flag
@@ -1786,41 +1788,9 @@ namespace AiQ_GUI
{
Stopwatch stopWatchTest = Stopwatch.StartNew();
//StatsExcel excelExporter = new();
//excelExporter.ExportDatabaseToExcel();
StatsExcel excelExporter = new();
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();
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 readonly string exportPath =
@"C:\Users\BradleyBorn\OneDrive - MAV Systems Ltd\Desktop\AiQ_Test_Stats.xlsx";
public void ExportDatabaseToExcel()
{
try
{
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();
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))
{
using (var cmdPeriod = new OleDbCommand("SELECT LastStatsRun FROM UniversalData", conn))
{
object res = cmdPeriod.ExecuteScalar();
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}");
object res = cmdPeriod.ExecuteScalar();
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}");
}
// ==================== MAIN STATS EXPORT ====================
string selectColumns = @"
// ==================== MAIN STATS EXPORT ====================
string selectColumns = @"
ModelNumber,
[Total Tests Run],
[Pre Tests Passed],
@@ -65,71 +61,71 @@ namespace AiQ_GUI
[Visual Test Fail - Not All Rear Screws Fitted],
[Visual Test Fail - Unit rattles]";
string query = $@"
string query = $@"
SELECT
{selectColumns}
FROM AiQ";
OleDbDataAdapter adapter = new(query, conn);
DataTable dataTable = new();
adapter.Fill(dataTable);
OleDbDataAdapter adapter = new(query, conn);
DataTable dataTable = new();
adapter.Fill(dataTable);
if (dataTable.Rows.Count == 0)
{
MainForm.Instance.AddToActionsList("No data found in AiQ table.");
return;
}
if (dataTable.Rows.Count == 0)
{
MainForm.Instance.AddToActionsList("No data found in AiQ table.");
return;
}
string monthName = now.ToString("MMMM");
string sheetName = $"{monthName} Stats";
string monthName = now.ToString("MMMM");
string sheetName = $"{monthName} Stats";
MainForm.Instance.AddToActionsList($"Adding sheet: {sheetName}");
MainForm.Instance.AddToActionsList($"Adding sheet: {sheetName}");
XLWorkbook workbook;
if (File.Exists(exportPath))
{
workbook = new XLWorkbook(exportPath);
MainForm.Instance.AddToActionsList("Opened existing workbook.");
}
else
{
workbook = new XLWorkbook();
MainForm.Instance.AddToActionsList("Created new workbook (file not found).");
}
XLWorkbook workbook;
if (File.Exists(exportPath))
{
workbook = new XLWorkbook(exportPath);
MainForm.Instance.AddToActionsList("Opened existing workbook.");
}
else
{
workbook = new XLWorkbook();
MainForm.Instance.AddToActionsList("Created new workbook (file not found).");
}
if (workbook.Worksheets.Contains(sheetName))
{
workbook.Worksheet(sheetName).Delete();
MainForm.Instance.AddToActionsList($"Deleted old sheet: {sheetName}");
}
if (workbook.Worksheets.Contains(sheetName))
{
workbook.Worksheet(sheetName).Delete();
MainForm.Instance.AddToActionsList($"Deleted old sheet: {sheetName}");
}
IXLWorksheet ws = workbook.Worksheets.Add(sheetName);
ws.Cell(1, 1).InsertTable(dataTable, "AiQ_Stats", true);
ws.Columns().AdjustToContents();
IXLWorksheet ws = workbook.Worksheets.Add(sheetName);
ws.Cell(1, 1).InsertTable(dataTable, "AiQ_Stats", true);
ws.Columns().AdjustToContents();
// Write Data Period label and computed period string to the right of the table
int infoCol = dataTable.Columns.Count + 2;
ws.Cell(1, infoCol).Value = "Data Period";
// Write Data Period label and computed period string to the right of the table
int infoCol = dataTable.Columns.Count + 2;
ws.Cell(1, infoCol).Value = "Data Period";
string periodText;
if (lastStatsRun.HasValue)
{
periodText = $"{lastStatsRun.Value:yyyy-MM-dd HH:mm:ss} - {now:yyyy-MM-dd HH:mm:ss}";
}
else
{
periodText = $"Up to {now:yyyy-MM-dd HH:mm:ss}";
}
string periodText;
if (lastStatsRun.HasValue)
{
periodText = $"{lastStatsRun.Value:yyyy-MM-dd HH:mm:ss} - {now:yyyy-MM-dd HH:mm:ss}";
}
else
{
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) ====================
MainForm.Instance.AddToActionsList("Exporting DiagsStats for current month...");
// ==================== DIAGS STATS EXPORT (CURRENT MONTH ONLY) ====================
MainForm.Instance.AddToActionsList("Exporting DiagsStats for current month...");
DateTime monthStart = new(now.Year, now.Month, 1);
DateTime nextMonth = monthStart.AddMonths(1);
DateTime monthStart = new(now.Year, now.Month, 1);
DateTime nextMonth = monthStart.AddMonths(1);
string diagsQuery = @"
string diagsQuery = @"
SELECT
[Date],
[Model],
@@ -140,70 +136,70 @@ namespace AiQ_GUI
FROM DiagsStats
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 });
diagsCmd.Parameters.Add(new OleDbParameter { OleDbType = OleDbType.Date, Value = nextMonth });
DataTable diagsTable = new();
diagsAdapter.Fill(diagsTable);
using (var diagsAdapter = new OleDbDataAdapter(diagsCmd))
if (diagsTable.Rows.Count > 0)
{
DataTable diagsTable = new();
diagsAdapter.Fill(diagsTable);
int startRow = (ws.LastRowUsed()?.RowNumber() ?? 0) + 3;
if (diagsTable.Rows.Count > 0)
{
int startRow = (ws.LastRowUsed()?.RowNumber() ?? 0) + 3;
ws.Cell(startRow, 1).Value = "Diags Stats (Current Month)";
ws.Cell(startRow, 1).Style.Font.Bold = true;
ws.Cell(startRow, 1).Style.Font.FontSize = 12;
ws.Cell(startRow, 1).Value = "Diags Stats (Current Month)";
ws.Cell(startRow, 1).Style.Font.Bold = true;
ws.Cell(startRow, 1).Style.Font.FontSize = 12;
ws.Cell(startRow + 1, 1).InsertTable(diagsTable, "Diags_Stats", true);
ws.Columns().AdjustToContents();
ws.Cell(startRow + 1, 1).InsertTable(diagsTable, "Diags_Stats", true);
ws.Columns().AdjustToContents();
MainForm.Instance.AddToActionsList($"Added DiagsStats ({diagsTable.Rows.Count} rows) starting at row {startRow}.");
}
MainForm.Instance.AddToActionsList($"Added DiagsStats ({diagsTable.Rows.Count} rows) starting at row {startRow}.");
}
}
}
// ==================== SAVE MAIN SHEET ====================
workbook.SaveAs(exportPath);
MainForm.Instance.AddToActionsList($"Added {sheetName} to workbook: {exportPath}");
// ==================== SAVE MAIN SHEET ====================
workbook.SaveAs(exportPath);
MainForm.Instance.AddToActionsList($"Added {sheetName} to workbook: {exportPath}");
workbook.Dispose();
workbook.Dispose();
// ==================== BACKUP TABLE (ALWAYS, BEFORE RESET) ====================
string ts = now.ToString("yyyyMMdd_HHmmss");
string backupTableName = $"Ztats_{ts}";
// ==================== BACKUP TABLE (ALWAYS, BEFORE RESET) ====================
string ts = now.ToString("yyyyMMdd_HHmmss");
string backupTableName = $"Ztats_{ts}";
if (backupTableName.Length > 64)
backupTableName = backupTableName.Substring(0, 64);
if (backupTableName.Length > 64)
backupTableName = backupTableName.Substring(0, 64);
string backupSql = $@"
string backupSql = $@"
SELECT
{selectColumns}
INTO [{backupTableName}]
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
{
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
{
string resetSql = @"
string resetSql = @"
UPDATE AiQ SET
[Total Tests Run] = 0,
[Pre Tests Passed] = 0,