diff --git a/db/schema.sql b/db/schema.sql index 12128b0..0f9fb3e 100644 --- a/db/schema.sql +++ b/db/schema.sql @@ -119,7 +119,7 @@ create table if not exists schema_version ( ); insert into schema_version (id, version, description) -values (1, 6, 'Inspection modes, order range, and production allocation constraints') +values (1, 7, 'Quality query indexes') on conflict (id) do update set version = excluded.version, description = excluded.description, @@ -255,6 +255,12 @@ on inspection_records(workpiece_id); create index if not exists ix_inspection_records_created_at on inspection_records(created_at); +create index if not exists ix_inspection_records_result +on inspection_records(result_state, completed_at); + +create index if not exists ix_inspection_records_order_side +on inspection_records(order_id, inspection_side, completed_at); + do $$ begin if exists ( @@ -318,6 +324,9 @@ on workpiece_process_records(process_step); create index if not exists ix_process_records_started_at on workpiece_process_records(started_at); +create index if not exists ix_workpieces_order_state +on workpieces(order_id, state); + -- Inspection mode migration for existing databases do $$ begin diff --git a/models/qualityrecord.h b/models/qualityrecord.h new file mode 100644 index 0000000..ba83a01 --- /dev/null +++ b/models/qualityrecord.h @@ -0,0 +1,77 @@ +#ifndef QUALITYRECORD_H +#define QUALITYRECORD_H + +#include "order.h" +#include "workpiece.h" + +#include +#include +#include + +struct InspectionRecord +{ + int id = 0; + int orderId = 0; + int workpieceId = 0; + QString orderNo; + QString barcode; + int trayId = 0; + QString trayCode; + int trayPos = 0; + QString inspectionSide; + QString inspectionMode; + int attemptNo = 0; + int rawResult = -1; + QString resultState; + QString inspectionState; + QString source; + int plcStep = 0; + QString message; + QDateTime startedAt; + QDateTime completedAt; + int durationMs = -1; + QDateTime createdAt; +}; + +struct QualityStatistics +{ + int planNum = 0; + int completedCount = 0; + int pendingCount = 0; + int okCount = 0; + int ngCount = 0; + int inspectionCount = 0; + int frontOkCount = 0; + int frontNgCount = 0; + int backOkCount = 0; + int backNgCount = 0; + + double qualifiedRate = 0.0; +}; + +struct QualityProcessRecord +{ + QString processStep; + int attemptNo = 0; + QString processState; + QString resultState; + int plcStep = 0; + QString source; + int durationMs = -1; + QDateTime startedAt; + QDateTime completedAt; +}; + +struct QualityStateHistory +{ + QString fromState; + QString toState; + QString processStep; + QString source; + QString reason; + QString message; + int elapsedMs = -1; + QDateTime changedAt; +}; + +#endif // QUALITYRECORD_H diff --git a/models/workpiece.h b/models/workpiece.h index 199c3f1..8cf6c9b 100644 --- a/models/workpiece.h +++ b/models/workpiece.h @@ -10,6 +10,7 @@ struct Workpiece QString barcode; int orderId = 0; int trayId = 0; + QString trayCode; int trayPos = 0; int rowNo = 0; int columnNo = 0; diff --git a/pages/dashboardpage.cpp b/pages/dashboardpage.cpp index b19b5da..40bc4c0 100644 --- a/pages/dashboardpage.cpp +++ b/pages/dashboardpage.cpp @@ -8,7 +8,6 @@ #include "uihelpers.h" #include -#include #include #include #include @@ -16,7 +15,7 @@ #include #include #include -#include +#include #include #include #include @@ -73,15 +72,27 @@ QString displayProcessStatus(const QString &status) return status.isEmpty() ? "未采集" : status; } -void updateStatusCell(QLabel *cell, const QString &text, const QString &color) +QString displayOrderStatus(const QString &status) +{ + if (status == "NOT_START") return "待启动"; + if (status == "RUNNING") return "加工中"; + if (status == "PAUSED") return "已暂停"; + if (status == "FINISHED" || status == "COMPLETED") return "已完成"; + if (status == "CANCELED") return "已取消"; + return status.isEmpty() ? "未采集" : status; +} + +void updateStatusCell(QLabel *cell, const QString &text, const QString &color, + bool highlighted = false) { if (!cell) { return; } cell->setText(text); - cell->setStyleSheet(QString("QLabel { background: %1; border: 1px solid #ffffff; " + cell->setStyleSheet(QString("QLabel { background: %1; border: %2; " "border-radius: 3px; color: white; font-size: 11px; }") - .arg(color)); + .arg(color) + .arg(highlighted ? "3px solid #ffb300" : "1px solid #ffffff")); } QString boolStatus(bool valid, bool value, const QString &yes, const QString &no) @@ -94,7 +105,6 @@ QString boolStatus(bool valid, bool value, const QString &yes, const QString &no DashboardPage::DashboardPage(QWidget *parent) : QWidget(parent) , ui(new Ui::DashboardPage) - , orderCombo(new QComboBox(this)) , rackBox(nullptr) , deviceStatusLabel(new QLabel("PLC:未采集 | 机器人:未采集 | 安全回路:未采集", this)) , inspectionMachineCell(nullptr) @@ -119,6 +129,8 @@ DashboardPage::DashboardPage(QWidget *parent) , productionThread(new QThread(this)) , productionWorker(new ProductionWorker) , productionState(ProductionService::Idle) + , currentOrderId(0) + , currentOrderStartable(false) , productionTrayNo(0) , productionSlotNo(0) { @@ -151,11 +163,8 @@ DashboardPage::DashboardPage(QWidget *parent) stopButton->setObjectName("stopButton"); stopButton->setVisible(false); ui->buttonLayout->insertWidget(6, stopButton); - orderCombo->setObjectName("orderSelector"); - orderCombo->setMinimumWidth(220); - ui->taskLayout->insertWidget(0, orderCombo); deviceStatusLabel->setStyleSheet("color: #546e7a;"); - ui->taskLayout->insertWidget(1, deviceStatusLabel); + ui->taskLayout->insertWidget(0, deviceStatusLabel); QFormLayout *processSummaryLayout = new QFormLayout; processSummaryLayout->addRow("当前工序:", currentProcessLabel); @@ -246,9 +255,6 @@ DashboardPage::DashboardPage(QWidget *parent) this, &DashboardPage::retryRecovery); connect(markNgButton, &QPushButton::clicked, this, &DashboardPage::markWorkpieceNg); - connect(orderCombo, QOverload::of(&QComboBox::currentIndexChanged), - this, &DashboardPage::onOrderChanged); - connect(productionWorker, &ProductionWorker::stateChanged, this, &DashboardPage::onProductionStateChanged); connect(productionWorker, &ProductionWorker::currentWorkpieceChanged, @@ -278,10 +284,12 @@ DashboardPage::DashboardPage(QWidget *parent) QMetaObject::invokeMethod(productionWorker, "requestRestore", Qt::QueuedConnection); - loadOrderOptions(); + loadCurrentOrder(); processRefreshTimer->setInterval(1000); - connect(processRefreshTimer, &QTimer::timeout, - this, &DashboardPage::refreshProcessRecords); + connect(processRefreshTimer, &QTimer::timeout, this, [this]() { + refreshProcessRecords(); + loadCurrentOrder(); + }); processRefreshTimer->start(); refreshProcessRecords(); updateRackSummary(); @@ -350,12 +358,8 @@ void DashboardPage::startProduction() return; } - int selectedOrderId = orderCombo->currentData().toInt(); - if (selectedOrderId <= 0) { - loadOrderOptions(); - selectedOrderId = orderCombo->currentData().toInt(); - } - if (selectedOrderId <= 0) { + loadCurrentOrder(); + if (!currentOrderStartable || currentOrderId <= 0) { QMessageBox::information(this, "启动生产", "没有可生产的订单,请先生成工件。"); return; @@ -364,7 +368,7 @@ void DashboardPage::startProduction() ui->startButton->setEnabled(false); if (!QMetaObject::invokeMethod( productionWorker, "requestStart", Qt::QueuedConnection, - Q_ARG(int, selectedOrderId))) { + Q_ARG(int, currentOrderId))) { updateRecoveryButtons(); QMessageBox::warning(this, "启动生产", "提交生产启动请求失败。"); @@ -398,17 +402,13 @@ void DashboardPage::clearAlarm() "已请求 PLC 清除报警", "待处理"); } -void DashboardPage::onOrderChanged(int) -{ - updateOrderSummary(); -} - void DashboardPage::onProductionStateChanged(ProductionService::State state, const QString &name) { productionState = state; const QString stateText = displayState(name); ui->actionLabel->setText("生产状态:" + stateText); + loadCurrentOrder(); updateRecoveryButtons(); emit systemStateChanged(stateText); emit currentStepChanged(stateText); @@ -464,7 +464,7 @@ void DashboardPage::onProductionFinished(int orderId) { emit logRequested("生产日志", "生产流程", "订单完成", QString("订单 %1 已完成").arg(orderId), "成功"); - loadOrderOptions(); + loadCurrentOrder(); updateProductionStats(); updateRackSummary(); } @@ -535,8 +535,9 @@ void DashboardPage::updateRecoveryButtons() const bool running = state != ProductionService::Idle && state != ProductionService::Completed; const bool terminating = state == ProductionService::Terminating; - const bool canStart = state == ProductionService::Idle - || state == ProductionService::Completed; + const bool canStart = (state == ProductionService::Idle + || state == ProductionService::Completed) + && currentOrderStartable; ui->startButton->setEnabled(canStart); recoverButton->setVisible(recoveryRequired); retryButton->setVisible(recoveryRequired); @@ -722,6 +723,21 @@ void DashboardPage::updateRackSummary() { QString error; const QList trays = TrayService::instance().listTrays(&error); + QSet highlightedTrayIds; + if (error.isEmpty() && currentOrderId > 0) { + QString workpieceError; + const QList workpieces = + WorkpieceService::instance().listByOrder(currentOrderId, + &workpieceError); + if (workpieceError.isEmpty()) { + for (const Workpiece &workpiece : workpieces) { + if (workpiece.trayId > 0) { + highlightedTrayIds.insert(workpiece.trayId); + } + } + } + } + for (int index = 0; index < rackTrayCells.size(); ++index) { QLabel *cell = rackTrayCells.at(index); if (!error.isEmpty() || index >= trays.size()) { @@ -747,76 +763,56 @@ void DashboardPage::updateRackSummary() .arg(index + 1) .arg(statusText) .arg(tray.loadedCount), - color); + color, highlightedTrayIds.contains(tray.id)); } } -void DashboardPage::loadOrderOptions() +void DashboardPage::loadCurrentOrder() { QString error; - const QList orders = OrderService::instance().listOrders(&error); - if (!error.isEmpty()) { - orderCombo->clear(); - orderCombo->addItem("无订单数据", 0); + Order order; + if (!OrderService::instance().findUnfinishedOrder(&order, &error)) { + currentOrderId = 0; + currentOrderStartable = false; + ui->orderLabel->setText("当前订单:读取失败"); + updateProductionStats(); + updateRackSummary(); emit logRequested("操作日志", "控制面板", "加载订单", error, "失败"); return; } - const int previousOrderId = orderCombo->currentData().toInt(); - QSignalBlocker blocker(orderCombo); - orderCombo->clear(); - for (const Order &order : orders) { - if (order.status != "NOT_START") { - continue; - } - - QString workpieceError; - const QList workpieces = - WorkpieceService::instance().listByOrder(order.id, &workpieceError); - if (!workpieceError.isEmpty() || workpieces.isEmpty()) { - continue; - } - orderCombo->addItem(order.no, order.id); - } - - if (orderCombo->count() == 0) { - orderCombo->addItem("暂无可生产订单", 0); - } else { - const int previousIndex = orderCombo->findData(previousOrderId); - orderCombo->setCurrentIndex(previousIndex >= 0 ? previousIndex : 0); - } - updateOrderSummary(); -} - -void DashboardPage::updateOrderSummary() -{ - const int selectedOrderId = orderCombo->currentData().toInt(); - if (selectedOrderId <= 0) { - ui->orderLabel->setText("当前订单:-"); - ui->trayLabel->setText("当前托盘:-"); - ui->workpieceLabel->setText("当前工件:-"); + currentOrderId = order.id; + currentOrderStartable = false; + if (order.id <= 0) { + ui->orderLabel->setText("当前订单:暂无未完成订单"); emit currentOrderChanged("-"); updateProductionStats(); + updateRackSummary(); + updateRecoveryButtons(); return; } - Order order; - QString error; - if (!OrderService::instance().findOrder(selectedOrderId, &order, &error)) { - ui->orderLabel->setText("当前订单:-"); - emit currentOrderChanged("-"); - return; + QString workpieceError; + const QList workpieces = + WorkpieceService::instance().listByOrder(order.id, &workpieceError); + if (workpieceError.isEmpty()) { + currentOrderStartable = order.status == "NOT_START" + && !workpieces.isEmpty(); } - ui->orderLabel->setText("当前订单:" + order.no); + + ui->orderLabel->setText(QString("当前订单:%1(%2)") + .arg(order.no) + .arg(displayOrderStatus(order.status))); emit currentOrderChanged(order.no); updateProductionStats(); + updateRackSummary(); + updateRecoveryButtons(); } void DashboardPage::updateProductionStats() { - const int selectedOrderId = orderCombo->currentData().toInt(); - if (selectedOrderId <= 0) { + if (currentOrderId <= 0) { ui->planValue->setText("0"); ui->pendingValue->setText("0"); ui->frontValue->setText("0"); @@ -828,11 +824,11 @@ void DashboardPage::updateProductionStats() Order order; QString error; - if (!OrderService::instance().findOrder(selectedOrderId, &order, &error)) { + if (!OrderService::instance().findOrder(currentOrderId, &order, &error)) { return; } const QList workpieces = - WorkpieceService::instance().listByOrder(selectedOrderId, &error); + WorkpieceService::instance().listByOrder(currentOrderId, &error); if (!error.isEmpty()) { return; } diff --git a/pages/dashboardpage.h b/pages/dashboardpage.h index 72a6467..f71f805 100644 --- a/pages/dashboardpage.h +++ b/pages/dashboardpage.h @@ -6,7 +6,6 @@ #include #include -class QComboBox; class QTableWidget; class QGroupBox; class QResizeEvent; @@ -43,7 +42,6 @@ private slots: void stopProduction(); void resetProduction(); void clearAlarm(); - void onOrderChanged(int index); void onProductionStateChanged(ProductionService::State state, const QString &name); void onCurrentWorkpieceChanged(int workpieceId, const QString &barcode); @@ -63,8 +61,7 @@ protected: void resizeEvent(QResizeEvent *event) override; private: - void loadOrderOptions(); - void updateOrderSummary(); + void loadCurrentOrder(); void updateProductionStats(); void updateRackSummary(); void updateRackSize(); @@ -74,7 +71,6 @@ private: static QString formatDuration(int elapsedMs); Ui::DashboardPage *ui; - QComboBox *orderCombo; QGroupBox *rackBox; QVector rackTrayCells; QLabel *deviceStatusLabel; @@ -100,6 +96,8 @@ private: QThread *productionThread; ProductionWorker *productionWorker; ProductionService::State productionState; + int currentOrderId; + bool currentOrderStartable; Workpiece productionWorkpiece; int productionTrayNo; int productionSlotNo; diff --git a/pages/orderpage.cpp b/pages/orderpage.cpp index 4bca4d7..982a09c 100644 --- a/pages/orderpage.cpp +++ b/pages/orderpage.cpp @@ -23,7 +23,8 @@ QString displayOrderStatus(const QString &status) if (status == "NOT_START") return "未开始"; if (status == "RUNNING") return "加工中"; if (status == "PAUSED") return "已暂停"; - if (status == "COMPLETED") return "已完成"; + if (status == "FINISHED" || status == "COMPLETED") return "已完成"; + if (status == "CANCELED") return "已取消"; if (status == "ERROR") return "故障"; if (status == "STOPPING") return "终止中"; return status.isEmpty() ? "未采集" : status; @@ -48,6 +49,8 @@ OrderPage::OrderPage(QWidget *parent) ui->deleteButton->setObjectName("dangerButton"); QPushButton *generateButton = new QPushButton("生成工件", this); ui->toolbarLayout->insertWidget(5, generateButton); + QPushButton *cancelButton = new QPushButton("取消订单", this); + ui->toolbarLayout->insertWidget(8, cancelButton); QTableWidget *table = ui->orderTable; table->setColumnCount(14); @@ -66,6 +69,8 @@ OrderPage::OrderPage(QWidget *parent) connect(ui->refreshButton, &QPushButton::clicked, this, &OrderPage::loadOrders); connect(generateButton, &QPushButton::clicked, this, &OrderPage::generateSelectedWorkpieces); + connect(cancelButton, &QPushButton::clicked, + this, &OrderPage::cancelSelectedOrder); connect(ui->deleteButton, &QPushButton::clicked, this, &OrderPage::deleteSelectedOrder); connect(table, &QTableWidget::itemSelectionChanged, this, &OrderPage::updateSelectedOrderDetail); @@ -297,3 +302,30 @@ void OrderPage::deleteSelectedOrder() emit logRequested("操作日志", "订单管理", "删除订单", "删除订单:" + orderNo, "成功"); } + +void OrderPage::cancelSelectedOrder() +{ + const int row = ui->orderTable->currentRow(); + if (row < 0 || row >= orderIds.size()) { + QMessageBox::information(this, "取消订单", "请先选择要取消的订单"); + return; + } + + const QString orderNo = ui->orderTable->item(row, 0) + ? ui->orderTable->item(row, 0)->text() : QString::number(orderIds.at(row)); + if (QMessageBox::question(this, "取消订单", + "确认取消订单:" + orderNo + "?") != QMessageBox::Yes) { + return; + } + + QString error; + if (!OrderService::instance().cancelOrder(orderIds.at(row), &error)) { + QMessageBox::warning(this, "取消订单失败", error); + emit logRequested("操作日志", "订单管理", "取消订单", error, "失败"); + return; + } + + loadOrders(); + emit logRequested("操作日志", "订单管理", "取消订单", + "取消订单:" + orderNo, "成功"); +} diff --git a/pages/orderpage.h b/pages/orderpage.h index d1aa9c5..6184c01 100644 --- a/pages/orderpage.h +++ b/pages/orderpage.h @@ -26,6 +26,7 @@ private: void updateSelectedOrderDetail(); void createOrder(); void generateSelectedWorkpieces(); + void cancelSelectedOrder(); void deleteSelectedOrder(); Ui::OrderPage *ui; diff --git a/pages/qualitypage.cpp b/pages/qualitypage.cpp new file mode 100644 index 0000000..4e14663 --- /dev/null +++ b/pages/qualitypage.cpp @@ -0,0 +1,515 @@ +#include "qualitypage.h" + +#include "uihelpers.h" +#include "../models/qualityrecord.h" +#include "../services/qualityservice.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { + +QString formatTime(const QDateTime &dateTime) +{ + return dateTime.isValid() + ? dateTime.toString("yyyy-MM-dd HH:mm:ss") : "-"; +} + +QString formatDuration(int durationMs) +{ + if (durationMs < 0) { + return "-"; + } + if (durationMs >= 1000) { + return QString::number(durationMs / 1000.0, 'f', 2) + " s"; + } + return QString::number(durationMs) + " ms"; +} + +QString modeText(const QString &mode) +{ + if (mode == "BEFORE_PLATING") { + return "镀金前"; + } + if (mode == "AFTER_PLATING") { + return "镀金后"; + } + return mode.isEmpty() ? "-" : mode; +} + +QString sideText(const QString &side) +{ + if (side == "FRONT") { + return "正面"; + } + if (side == "BACK") { + return "反面"; + } + if (side == "FINAL") { + return "最终"; + } + return side.isEmpty() ? "-" : side; +} + +QString resultText(const QString &result) +{ + if (result == "OK") { + return "合格"; + } + if (result == "NG") { + return "不合格"; + } + if (result == "ERROR") { + return "错误"; + } + if (result == "UNKNOWN") { + return "未知"; + } + return result.isEmpty() ? "-" : result; +} + +QString sourceText(const QString &source) +{ + if (source == "PLC") { + return "PLC"; + } + if (source == "MANUAL") { + return "手动"; + } + if (source == "RECOVERY") { + return "恢复"; + } + return source.isEmpty() ? "-" : source; +} + +QString rawResultText(int rawResult) +{ + return rawResult < 0 ? "-" : QString::number(rawResult); +} + +QLabel *makeValueLabel() +{ + QLabel *label = new QLabel("-"); + label->setMinimumWidth(90); + label->setStyleSheet("QLabel { font-size: 16px; font-weight: bold; color: #00695c; }"); + return label; +} + +void addTableRow(QTableWidget *table, const QStringList &values) +{ + const int row = table->rowCount(); + table->insertRow(row); + for (int column = 0; column < values.size(); ++column) { + table->setItem(row, column, new QTableWidgetItem(values.at(column))); + } +} + +} + +QualityPage::QualityPage(QWidget *parent) + : QWidget(parent) + , inspectionOrderEdit(nullptr) + , inspectionBarcodeEdit(nullptr) + , inspectionTrayEdit(nullptr) + , inspectionSlotEdit(nullptr) + , inspectionModeCombo(nullptr) + , inspectionSideCombo(nullptr) + , inspectionResultCombo(nullptr) + , inspectionTable(nullptr) + , inspectionMessageLabel(nullptr) + , statisticsOrderEdit(nullptr) + , planValueLabel(nullptr) + , completedValueLabel(nullptr) + , pendingValueLabel(nullptr) + , okValueLabel(nullptr) + , ngValueLabel(nullptr) + , rateValueLabel(nullptr) + , inspectionCountValueLabel(nullptr) + , statisticsMessageLabel(nullptr) + , sideStatisticsTable(nullptr) + , traceBarcodeEdit(nullptr) + , traceInfoLabel(nullptr) + , traceMessageLabel(nullptr) + , traceInspectionTable(nullptr) + , traceProcessTable(nullptr) + , traceHistoryTable(nullptr) +{ + QVBoxLayout *layout = new QVBoxLayout(this); + layout->setContentsMargins(14, 14, 14, 14); + layout->setSpacing(10); + + QTabWidget *tabs = new QTabWidget(this); + layout->addWidget(tabs); + setupInspectionTab(); + setupStatisticsTab(); + setupTraceTab(); + + QWidget *inspectionTab = new QWidget; + QVBoxLayout *inspectionLayout = new QVBoxLayout(inspectionTab); + inspectionLayout->setContentsMargins(8, 8, 8, 8); + inspectionLayout->setSpacing(8); + + QGridLayout *filters = new QGridLayout; + filters->setHorizontalSpacing(8); + filters->setVerticalSpacing(6); + filters->addWidget(new QLabel("订单号"), 0, 0); + filters->addWidget(inspectionOrderEdit, 0, 1); + filters->addWidget(new QLabel("工件条码"), 0, 2); + filters->addWidget(inspectionBarcodeEdit, 0, 3); + filters->addWidget(new QLabel("托盘"), 0, 4); + filters->addWidget(inspectionTrayEdit, 0, 5); + filters->addWidget(new QLabel("位置号"), 0, 6); + filters->addWidget(inspectionSlotEdit, 0, 7); + filters->addWidget(new QLabel("检测模式"), 1, 0); + filters->addWidget(inspectionModeCombo, 1, 1); + filters->addWidget(new QLabel("检测面"), 1, 2); + filters->addWidget(inspectionSideCombo, 1, 3); + filters->addWidget(new QLabel("结果"), 1, 4); + filters->addWidget(inspectionResultCombo, 1, 5); + QPushButton *inspectionQueryButton = new QPushButton("查询"); + filters->addWidget(inspectionQueryButton, 1, 7); + inspectionLayout->addLayout(filters); + inspectionLayout->addWidget(inspectionMessageLabel); + inspectionLayout->addWidget(inspectionTable, 1); + tabs->addTab(inspectionTab, "检测记录"); + + QWidget *statisticsTab = new QWidget; + QVBoxLayout *statisticsLayout = new QVBoxLayout(statisticsTab); + statisticsLayout->setContentsMargins(8, 8, 8, 8); + statisticsLayout->setSpacing(8); + QHBoxLayout *statisticsFilters = new QHBoxLayout; + statisticsFilters->addWidget(new QLabel("订单号")); + statisticsFilters->addWidget(statisticsOrderEdit); + QPushButton *statisticsQueryButton = new QPushButton("查询"); + statisticsFilters->addWidget(statisticsQueryButton); + statisticsFilters->addStretch(); + statisticsLayout->addLayout(statisticsFilters); + statisticsLayout->addWidget(statisticsMessageLabel); + QGroupBox *summaryBox = new QGroupBox("订单质量汇总"); + QGridLayout *summaryLayout = new QGridLayout(summaryBox); + summaryLayout->addWidget(new QLabel("计划数量"), 0, 0); + summaryLayout->addWidget(planValueLabel, 0, 1); + summaryLayout->addWidget(new QLabel("已完成"), 0, 2); + summaryLayout->addWidget(completedValueLabel, 0, 3); + summaryLayout->addWidget(new QLabel("未完成"), 0, 4); + summaryLayout->addWidget(pendingValueLabel, 0, 5); + summaryLayout->addWidget(new QLabel("合格"), 1, 0); + summaryLayout->addWidget(okValueLabel, 1, 1); + summaryLayout->addWidget(new QLabel("不合格"), 1, 2); + summaryLayout->addWidget(ngValueLabel, 1, 3); + summaryLayout->addWidget(new QLabel("合格率"), 1, 4); + summaryLayout->addWidget(rateValueLabel, 1, 5); + summaryLayout->addWidget(new QLabel("检测记录数"), 2, 0); + summaryLayout->addWidget(inspectionCountValueLabel, 2, 1); + statisticsLayout->addWidget(summaryBox); + statisticsLayout->addWidget(sideStatisticsTable, 1); + tabs->addTab(statisticsTab, "合格率统计"); + + QWidget *traceTab = new QWidget; + QVBoxLayout *traceLayout = new QVBoxLayout(traceTab); + traceLayout->setContentsMargins(8, 8, 8, 8); + traceLayout->setSpacing(8); + QHBoxLayout *traceFilters = new QHBoxLayout; + traceFilters->addWidget(new QLabel("工件条码")); + traceFilters->addWidget(traceBarcodeEdit); + QPushButton *traceQueryButton = new QPushButton("查询"); + traceFilters->addWidget(traceQueryButton); + traceFilters->addStretch(); + traceLayout->addLayout(traceFilters); + traceLayout->addWidget(traceInfoLabel); + traceLayout->addWidget(traceMessageLabel); + + QGroupBox *traceInspectionBox = new QGroupBox("检测记录"); + QVBoxLayout *traceInspectionLayout = new QVBoxLayout(traceInspectionBox); + traceInspectionLayout->addWidget(traceInspectionTable); + QGroupBox *traceProcessBox = new QGroupBox("工序记录"); + QVBoxLayout *traceProcessLayout = new QVBoxLayout(traceProcessBox); + traceProcessLayout->addWidget(traceProcessTable); + QGroupBox *traceHistoryBox = new QGroupBox("状态历史"); + QVBoxLayout *traceHistoryLayout = new QVBoxLayout(traceHistoryBox); + traceHistoryLayout->addWidget(traceHistoryTable); + QSplitter *traceSplitter = new QSplitter(Qt::Vertical); + traceSplitter->addWidget(traceInspectionBox); + traceSplitter->addWidget(traceProcessBox); + traceSplitter->addWidget(traceHistoryBox); + traceLayout->addWidget(traceSplitter, 1); + tabs->addTab(traceTab, "工件追溯"); + + connect(inspectionQueryButton, &QPushButton::clicked, + this, &QualityPage::loadInspectionRecords); + connect(inspectionSlotEdit, &QLineEdit::returnPressed, + this, &QualityPage::loadInspectionRecords); + connect(statisticsQueryButton, &QPushButton::clicked, + this, &QualityPage::loadStatistics); + connect(statisticsOrderEdit, &QLineEdit::returnPressed, + this, &QualityPage::loadStatistics); + connect(traceQueryButton, &QPushButton::clicked, + this, &QualityPage::loadTrace); + connect(traceBarcodeEdit, &QLineEdit::returnPressed, + this, &QualityPage::loadTrace); + + loadInspectionRecords(); + loadStatistics(); +} + +QualityPage::~QualityPage() +{ +} + +void QualityPage::setupInspectionTab() +{ + inspectionOrderEdit = new QLineEdit; + inspectionOrderEdit->setPlaceholderText("支持模糊查询"); + inspectionBarcodeEdit = new QLineEdit; + inspectionBarcodeEdit->setPlaceholderText("支持模糊查询"); + inspectionTrayEdit = new QLineEdit; + inspectionTrayEdit->setPlaceholderText("如 TRAY-1"); + inspectionSlotEdit = new QLineEdit; + inspectionSlotEdit->setPlaceholderText("1-49"); + + inspectionModeCombo = new QComboBox; + inspectionModeCombo->addItem("全部", ""); + inspectionModeCombo->addItem("镀金前", "BEFORE_PLATING"); + inspectionModeCombo->addItem("镀金后", "AFTER_PLATING"); + inspectionSideCombo = new QComboBox; + inspectionSideCombo->addItem("全部", ""); + inspectionSideCombo->addItem("正面", "FRONT"); + inspectionSideCombo->addItem("反面", "BACK"); + inspectionSideCombo->addItem("最终", "FINAL"); + inspectionResultCombo = new QComboBox; + inspectionResultCombo->addItem("全部", ""); + inspectionResultCombo->addItem("合格", "OK"); + inspectionResultCombo->addItem("不合格", "NG"); + inspectionResultCombo->addItem("错误", "ERROR"); + inspectionResultCombo->addItem("未知", "UNKNOWN"); + + inspectionTable = UiHelpers::makeTable( + QStringList() << "时间" << "订单号" << "工件条码" << "托盘" << "位置" + << "模式" << "检测面" << "结果" << "原始结果" + << "来源" << "耗时" << "次数"); + inspectionMessageLabel = new QLabel; +} + +void QualityPage::setupStatisticsTab() +{ + statisticsOrderEdit = new QLineEdit; + statisticsOrderEdit->setPlaceholderText("留空统计全部订单"); + planValueLabel = makeValueLabel(); + completedValueLabel = makeValueLabel(); + pendingValueLabel = makeValueLabel(); + okValueLabel = makeValueLabel(); + ngValueLabel = makeValueLabel(); + rateValueLabel = makeValueLabel(); + inspectionCountValueLabel = makeValueLabel(); + statisticsMessageLabel = new QLabel; + sideStatisticsTable = UiHelpers::makeTable( + QStringList() << "检测面" << "合格" << "不合格" << "记录数"); + addTableRow(sideStatisticsTable, QStringList() << "正面" << "-" << "-" << "-"); + addTableRow(sideStatisticsTable, QStringList() << "反面" << "-" << "-" << "-"); +} + +void QualityPage::setupTraceTab() +{ + traceBarcodeEdit = new QLineEdit; + traceBarcodeEdit->setPlaceholderText("输入完整工件条码"); + traceInfoLabel = new QLabel("请输入工件条码查询生产追溯信息"); + traceInfoLabel->setWordWrap(true); + traceMessageLabel = new QLabel; + traceInspectionTable = UiHelpers::makeTable( + QStringList() << "时间" << "模式" << "检测面" << "结果" << "原始结果" + << "来源" << "耗时" << "次数"); + traceProcessTable = UiHelpers::makeTable( + QStringList() << "开始时间" << "工序" << "状态" << "结果" << "来源" + << "PLC步骤" << "耗时" << "次数"); + traceHistoryTable = UiHelpers::makeTable( + QStringList() << "时间" << "状态变化" << "工序" << "来源" + << "原因" << "耗时" << "说明"); +} + +void QualityPage::loadInspectionRecords() +{ + bool slotOk = true; + const int trayPos = inspectionSlotEdit->text().trimmed().isEmpty() + ? 0 : inspectionSlotEdit->text().trimmed().toInt(&slotOk); + if (!slotOk || trayPos < 1 || trayPos > 49) { + setMessage(inspectionMessageLabel, "位置号必须是 1 到 49", true); + return; + } + + QString error; + const QList records = QualityService::instance().listInspectionRecords( + inspectionOrderEdit->text(), inspectionBarcodeEdit->text(), + inspectionTrayEdit->text(), trayPos, + inspectionModeCombo->currentData().toString(), + inspectionSideCombo->currentData().toString(), + inspectionResultCombo->currentData().toString(), &error); + clearTable(inspectionTable); + if (!error.isEmpty()) { + setMessage(inspectionMessageLabel, "查询失败: " + error, true); + return; + } + for (const InspectionRecord &record : records) { + addTableRow(inspectionTable, QStringList() + << formatTime(record.completedAt.isValid() + ? record.completedAt : record.createdAt) + << record.orderNo + << record.barcode + << record.trayCode + << QString::number(record.trayPos) + << modeText(record.inspectionMode) + << sideText(record.inspectionSide) + << resultText(record.resultState) + << rawResultText(record.rawResult) + << sourceText(record.source) + << formatDuration(record.durationMs) + << QString::number(record.attemptNo)); + } + setMessage(inspectionMessageLabel, + QString("共 %1 条检测记录").arg(records.size()), false); +} + +void QualityPage::loadStatistics() +{ + QualityStatistics statistics; + QString error; + if (!QualityService::instance().queryStatistics( + statisticsOrderEdit->text(), &statistics, &error)) { + planValueLabel->setText("-"); + completedValueLabel->setText("-"); + pendingValueLabel->setText("-"); + okValueLabel->setText("-"); + ngValueLabel->setText("-"); + rateValueLabel->setText("-"); + inspectionCountValueLabel->setText("-"); + setMessage(statisticsMessageLabel, "查询失败: " + error, true); + return; + } + + planValueLabel->setText(QString::number(statistics.planNum)); + completedValueLabel->setText(QString::number(statistics.completedCount)); + pendingValueLabel->setText(QString::number(statistics.pendingCount)); + okValueLabel->setText(QString::number(statistics.okCount)); + ngValueLabel->setText(QString::number(statistics.ngCount)); + rateValueLabel->setText(QString::number(statistics.qualifiedRate, 'f', 2) + "%"); + inspectionCountValueLabel->setText(QString::number(statistics.inspectionCount)); + sideStatisticsTable->setItem(0, 1, + new QTableWidgetItem(QString::number(statistics.frontOkCount))); + sideStatisticsTable->setItem(0, 2, + new QTableWidgetItem(QString::number(statistics.frontNgCount))); + sideStatisticsTable->setItem(0, 3, + new QTableWidgetItem(QString::number( + statistics.frontOkCount + statistics.frontNgCount))); + sideStatisticsTable->setItem(1, 1, + new QTableWidgetItem(QString::number(statistics.backOkCount))); + sideStatisticsTable->setItem(1, 2, + new QTableWidgetItem(QString::number(statistics.backNgCount))); + sideStatisticsTable->setItem(1, 3, + new QTableWidgetItem(QString::number( + statistics.backOkCount + statistics.backNgCount))); + setMessage(statisticsMessageLabel, "统计完成", false); +} + +void QualityPage::loadTrace() +{ + const QString barcode = traceBarcodeEdit->text().trimmed(); + if (barcode.isEmpty()) { + setMessage(traceMessageLabel, "请输入工件条码", true); + return; + } + + Workpiece workpiece; + Order order; + QList inspections; + QList processRecords; + QList stateHistory; + QString error; + if (!QualityService::instance().findWorkpieceTrace( + barcode, &workpiece, &order, &inspections, &processRecords, + &stateHistory, &error)) { + traceInfoLabel->setText("未找到工件追溯信息"); + clearTable(traceInspectionTable); + clearTable(traceProcessTable); + clearTable(traceHistoryTable); + setMessage(traceMessageLabel, "查询失败: " + error, true); + return; + } + + traceInfoLabel->setText( + QString("工件:%1 订单:%2 托盘:%3 位置:%4 状态:%5 当前工序:%6 检测模式:%7") + .arg(workpiece.barcode) + .arg(order.no) + .arg(workpiece.trayCode.isEmpty() + ? QString::number(workpiece.trayId) : workpiece.trayCode) + .arg(workpiece.trayPos) + .arg(resultText(workpiece.state)) + .arg(workpiece.processStep.isEmpty() ? "-" : workpiece.processStep) + .arg(modeText(order.inspectionMode))); + + clearTable(traceInspectionTable); + for (const InspectionRecord &record : inspections) { + addTableRow(traceInspectionTable, QStringList() + << formatTime(record.completedAt.isValid() + ? record.completedAt : record.createdAt) + << modeText(record.inspectionMode) + << sideText(record.inspectionSide) + << resultText(record.resultState) + << rawResultText(record.rawResult) + << sourceText(record.source) + << formatDuration(record.durationMs) + << QString::number(record.attemptNo)); + } + + clearTable(traceProcessTable); + for (const QualityProcessRecord &record : processRecords) { + addTableRow(traceProcessTable, QStringList() + << formatTime(record.startedAt) + << record.processStep + << record.processState + << resultText(record.resultState) + << sourceText(record.source) + << QString::number(record.plcStep) + << formatDuration(record.durationMs) + << QString::number(record.attemptNo)); + } + + clearTable(traceHistoryTable); + for (const QualityStateHistory &history : stateHistory) { + addTableRow(traceHistoryTable, QStringList() + << formatTime(history.changedAt) + << (history.fromState.isEmpty() + ? history.toState + : history.fromState + " -> " + history.toState) + << history.processStep + << sourceText(history.source) + << history.reason + << formatDuration(history.elapsedMs) + << history.message); + } + setMessage(traceMessageLabel, + QString("检测记录 %1 条,工序记录 %2 条,状态历史 %3 条") + .arg(inspections.size()).arg(processRecords.size()).arg(stateHistory.size()), + false); +} + +void QualityPage::setMessage(QLabel *label, const QString &message, bool error) +{ + label->setText(message); + label->setStyleSheet(error + ? "QLabel { color: #c62828; }" + : "QLabel { color: #546e7a; }"); +} + +void QualityPage::clearTable(QTableWidget *table) +{ + table->setRowCount(0); +} diff --git a/pages/qualitypage.h b/pages/qualitypage.h new file mode 100644 index 0000000..856bc44 --- /dev/null +++ b/pages/qualitypage.h @@ -0,0 +1,56 @@ +#ifndef QUALITYPAGE_H +#define QUALITYPAGE_H + +#include + +class QComboBox; +class QLabel; +class QLineEdit; +class QTableWidget; + +class QualityPage : public QWidget +{ +public: + explicit QualityPage(QWidget *parent = nullptr); + ~QualityPage(); + +private: + void setupInspectionTab(); + void setupStatisticsTab(); + void setupTraceTab(); + void loadInspectionRecords(); + void loadStatistics(); + void loadTrace(); + void setMessage(QLabel *label, const QString &message, bool error); + void clearTable(QTableWidget *table); + + QLineEdit *inspectionOrderEdit; + QLineEdit *inspectionBarcodeEdit; + QLineEdit *inspectionTrayEdit; + QLineEdit *inspectionSlotEdit; + QComboBox *inspectionModeCombo; + QComboBox *inspectionSideCombo; + QComboBox *inspectionResultCombo; + QTableWidget *inspectionTable; + QLabel *inspectionMessageLabel; + + QLineEdit *statisticsOrderEdit; + QLabel *planValueLabel; + QLabel *completedValueLabel; + QLabel *pendingValueLabel; + QLabel *okValueLabel; + QLabel *ngValueLabel; + QLabel *rateValueLabel; + QLabel *inspectionCountValueLabel; + QLabel *statisticsMessageLabel; + QTableWidget *sideStatisticsTable; + + QLineEdit *traceBarcodeEdit; + QLabel *traceInfoLabel; + QLabel *traceMessageLabel; + QTableWidget *traceInspectionTable; + QTableWidget *traceProcessTable; + QTableWidget *traceHistoryTable; +}; + +#endif // QUALITYPAGE_H diff --git a/repositories/qualityrepository.cpp b/repositories/qualityrepository.cpp new file mode 100644 index 0000000..f348208 --- /dev/null +++ b/repositories/qualityrepository.cpp @@ -0,0 +1,356 @@ +#include "qualityrepository.h" + +#include "../db/databasemanager.h" + +#include +#include +#include + +namespace { + +bool ensureOpen(QString *error) +{ + return DatabaseManager::instance().open(error); +} + +void setError(const QSqlQuery &query, QString *error) +{ + if (error) { + *error = query.lastError().text(); + } +} + +void readInspectionRecord(QSqlQuery &query, InspectionRecord *record) +{ + record->id = query.value("id").toInt(); + record->orderId = query.value("order_id").toInt(); + record->workpieceId = query.value("workpiece_id").toInt(); + record->orderNo = query.value("order_no").toString(); + record->barcode = query.value("barcode").toString(); + record->trayId = query.value("tray_id").toInt(); + record->trayCode = query.value("tray_code").toString(); + record->trayPos = query.value("tray_pos").toInt(); + record->inspectionSide = query.value("inspection_side").toString(); + record->inspectionMode = query.value("inspection_mode").toString(); + record->attemptNo = query.value("attempt_no").toInt(); + record->rawResult = query.value("raw_result").isNull() + ? -1 : query.value("raw_result").toInt(); + record->resultState = query.value("result_state").toString(); + record->inspectionState = query.value("inspection_state").toString(); + record->source = query.value("source").toString(); + record->plcStep = query.value("plc_step").toInt(); + record->message = query.value("message").toString(); + record->startedAt = query.value("started_at").toDateTime(); + record->completedAt = query.value("completed_at").toDateTime(); + record->durationMs = query.value("duration_ms").isNull() + ? -1 : query.value("duration_ms").toInt(); + record->createdAt = query.value("created_at").toDateTime(); +} + +} + +QList QualityRepository::listInspectionRecords( + const QString &orderNo, const QString &barcode, const QString &trayCode, + int trayPos, const QString &inspectionMode, const QString &inspectionSide, + const QString &resultState, QString *error) +{ + QList records; + if (!ensureOpen(error)) { + return records; + } + + QString sql = + "select ir.id, ir.order_id, ir.workpiece_id, o.no as order_no, " + "w.barcode, w.tray_id, t.code as tray_code, w.tray_pos, " + "ir.inspection_side, ir.inspection_mode, ir.attempt_no, ir.raw_result, " + "ir.result_state, ir.inspection_state, ir.source, ir.plc_step, " + "ir.message, ir.started_at, ir.completed_at, ir.duration_ms, ir.created_at " + "from inspection_records ir " + "join workpieces w on w.id = ir.workpiece_id " + "left join orders o on o.id = ir.order_id " + "left join trays t on t.id = w.tray_id " + "where 1 = 1"; + + QSqlQuery query(DatabaseManager::instance().database()); + if (!orderNo.trimmed().isEmpty()) { + sql += " and o.no ilike :order_no"; + } + if (!barcode.trimmed().isEmpty()) { + sql += " and w.barcode ilike :barcode"; + } + if (!trayCode.trimmed().isEmpty()) { + sql += " and t.code ilike :tray_code"; + } + if (trayPos > 0) { + sql += " and w.tray_pos = :tray_pos"; + } + if (!inspectionMode.isEmpty()) { + sql += " and ir.inspection_mode = :inspection_mode"; + } + if (!inspectionSide.isEmpty()) { + sql += " and ir.inspection_side = :inspection_side"; + } + if (!resultState.isEmpty()) { + sql += " and ir.result_state = :result_state"; + } + sql += " order by ir.created_at desc, ir.id desc"; + + query.prepare(sql); + if (!orderNo.trimmed().isEmpty()) { + query.bindValue(":order_no", "%" + orderNo.trimmed() + "%"); + } + if (!barcode.trimmed().isEmpty()) { + query.bindValue(":barcode", "%" + barcode.trimmed() + "%"); + } + if (!trayCode.trimmed().isEmpty()) { + query.bindValue(":tray_code", "%" + trayCode.trimmed() + "%"); + } + if (trayPos > 0) { + query.bindValue(":tray_pos", trayPos); + } + if (!inspectionMode.isEmpty()) { + query.bindValue(":inspection_mode", inspectionMode); + } + if (!inspectionSide.isEmpty()) { + query.bindValue(":inspection_side", inspectionSide); + } + if (!resultState.isEmpty()) { + query.bindValue(":result_state", resultState); + } + + if (!query.exec()) { + setError(query, error); + return records; + } + + while (query.next()) { + InspectionRecord record; + readInspectionRecord(query, &record); + records.append(record); + } + return records; +} + +bool QualityRepository::queryStatistics(const QString &orderNo, + QualityStatistics *statistics, + QString *error) +{ + if (!statistics || !ensureOpen(error)) { + return false; + } + *statistics = QualityStatistics(); + + int orderId = 0; + if (!orderNo.trimmed().isEmpty()) { + QSqlQuery orderQuery(DatabaseManager::instance().database()); + orderQuery.prepare("select id, plan_num from orders where no = :no"); + orderQuery.bindValue(":no", orderNo.trimmed()); + if (!orderQuery.exec()) { + setError(orderQuery, error); + return false; + } + if (!orderQuery.next()) { + if (error) { + *error = "订单不存在: " + orderNo.trimmed(); + } + return false; + } + orderId = orderQuery.value("id").toInt(); + statistics->planNum = orderQuery.value("plan_num").toInt(); + } else { + QSqlQuery planQuery(DatabaseManager::instance().database()); + if (!planQuery.exec("select coalesce(sum(plan_num), 0) from orders")) { + setError(planQuery, error); + return false; + } + if (planQuery.next()) { + statistics->planNum = planQuery.value(0).toInt(); + } + } + + QSqlQuery workpieceQuery(DatabaseManager::instance().database()); + const QString workpieceSql = + "select count(*) filter (where state in ('OK', 'NG')) as completed_count, " + "count(*) filter (where state = 'OK') as ok_count, " + "count(*) filter (where state = 'NG') as ng_count " + "from workpieces " + "where (:order_id = 0 or order_id = :order_id)"; + workpieceQuery.prepare(workpieceSql); + workpieceQuery.bindValue(":order_id", orderId); + if (!workpieceQuery.exec() || !workpieceQuery.next()) { + setError(workpieceQuery, error); + return false; + } + statistics->completedCount = workpieceQuery.value("completed_count").toInt(); + statistics->okCount = workpieceQuery.value("ok_count").toInt(); + statistics->ngCount = workpieceQuery.value("ng_count").toInt(); + statistics->pendingCount = qMax(0, statistics->planNum - statistics->completedCount); + + QSqlQuery inspectionQuery(DatabaseManager::instance().database()); + inspectionQuery.prepare( + "select count(*) as inspection_count, " + "count(*) filter (where inspection_side = 'FRONT' and result_state = 'OK') as front_ok, " + "count(*) filter (where inspection_side = 'FRONT' and result_state = 'NG') as front_ng, " + "count(*) filter (where inspection_side = 'BACK' and result_state = 'OK') as back_ok, " + "count(*) filter (where inspection_side = 'BACK' and result_state = 'NG') as back_ng " + "from inspection_records " + "where (:order_id = 0 or order_id = :order_id)"); + inspectionQuery.bindValue(":order_id", orderId); + if (!inspectionQuery.exec() || !inspectionQuery.next()) { + setError(inspectionQuery, error); + return false; + } + statistics->inspectionCount = inspectionQuery.value("inspection_count").toInt(); + statistics->frontOkCount = inspectionQuery.value("front_ok").toInt(); + statistics->frontNgCount = inspectionQuery.value("front_ng").toInt(); + statistics->backOkCount = inspectionQuery.value("back_ok").toInt(); + statistics->backNgCount = inspectionQuery.value("back_ng").toInt(); + statistics->qualifiedRate = statistics->completedCount > 0 + ? statistics->okCount * 100.0 / statistics->completedCount : 0.0; + return true; +} + +bool QualityRepository::findWorkpieceTrace( + const QString &barcode, Workpiece *workpiece, Order *order, + QList *inspections, + QList *processRecords, + QList *stateHistory, QString *error) +{ + if (!workpiece || !order || !inspections || !processRecords || !stateHistory + || !ensureOpen(error)) { + return false; + } + *workpiece = Workpiece(); + *order = Order(); + inspections->clear(); + processRecords->clear(); + stateHistory->clear(); + + QSqlQuery workpieceQuery(DatabaseManager::instance().database()); + workpieceQuery.prepare( + "select w.id, w.barcode, w.order_id, w.tray_id, t.code as tray_code, " + "w.tray_pos, w.row_no, " + "w.column_no, w.state, w.process_step, w.created_at, w.updated_at, " + "o.no as order_no, o.production_no, o.drawing_no, o.batch_no, " + "o.plan_num, o.qualified, o.unqualified, o.status as order_status, " + "o.inspection_mode, o.start_tray_no, o.start_slot_no, o.begin_time, " + "o.end_time, o.remark, o.created_at as order_created_at, " + "o.updated_at as order_updated_at " + "from workpieces w left join orders o on o.id = w.order_id " + "left join trays t on t.id = w.tray_id " + "where w.barcode = :barcode"); + workpieceQuery.bindValue(":barcode", barcode.trimmed()); + if (!workpieceQuery.exec()) { + setError(workpieceQuery, error); + return false; + } + if (!workpieceQuery.next()) { + if (error) { + *error = "工件不存在: " + barcode.trimmed(); + } + return false; + } + + workpiece->id = workpieceQuery.value("id").toInt(); + workpiece->barcode = workpieceQuery.value("barcode").toString(); + workpiece->orderId = workpieceQuery.value("order_id").toInt(); + workpiece->trayId = workpieceQuery.value("tray_id").toInt(); + workpiece->trayCode = workpieceQuery.value("tray_code").toString(); + workpiece->trayPos = workpieceQuery.value("tray_pos").toInt(); + workpiece->rowNo = workpieceQuery.value("row_no").toInt(); + workpiece->columnNo = workpieceQuery.value("column_no").toInt(); + workpiece->state = workpieceQuery.value("state").toString(); + workpiece->processStep = workpieceQuery.value("process_step").toString(); + workpiece->createdAt = workpieceQuery.value("created_at").toDateTime(); + workpiece->updatedAt = workpieceQuery.value("updated_at").toDateTime(); + + order->id = workpieceQuery.value("order_id").toInt(); + order->no = workpieceQuery.value("order_no").toString(); + order->productionNo = workpieceQuery.value("production_no").toString(); + order->drawingNo = workpieceQuery.value("drawing_no").toString(); + order->batchNo = workpieceQuery.value("batch_no").toString(); + order->planNum = workpieceQuery.value("plan_num").toInt(); + order->qualified = workpieceQuery.value("qualified").toInt(); + order->unqualified = workpieceQuery.value("unqualified").toInt(); + order->status = workpieceQuery.value("order_status").toString(); + order->inspectionMode = workpieceQuery.value("inspection_mode").toString(); + order->startTrayNo = workpieceQuery.value("start_tray_no").toInt(); + order->startSlotNo = workpieceQuery.value("start_slot_no").toInt(); + order->beginTime = workpieceQuery.value("begin_time").toDateTime(); + order->endTime = workpieceQuery.value("end_time").toDateTime(); + order->remark = workpieceQuery.value("remark").toString(); + order->createdAt = workpieceQuery.value("order_created_at").toDateTime(); + order->updatedAt = workpieceQuery.value("order_updated_at").toDateTime(); + + QSqlQuery inspectionQuery(DatabaseManager::instance().database()); + inspectionQuery.prepare( + "select ir.id, ir.order_id, ir.workpiece_id, o.no as order_no, " + "w.barcode, w.tray_id, t.code as tray_code, w.tray_pos, " + "ir.inspection_side, ir.inspection_mode, ir.attempt_no, ir.raw_result, " + "ir.result_state, ir.inspection_state, ir.source, ir.plc_step, " + "ir.message, ir.started_at, ir.completed_at, ir.duration_ms, ir.created_at " + "from inspection_records ir join workpieces w on w.id = ir.workpiece_id " + "left join orders o on o.id = ir.order_id left join trays t on t.id = w.tray_id " + "where ir.workpiece_id = :workpiece_id order by ir.created_at, ir.id"); + inspectionQuery.bindValue(":workpiece_id", workpiece->id); + if (!inspectionQuery.exec()) { + setError(inspectionQuery, error); + return false; + } + while (inspectionQuery.next()) { + InspectionRecord record; + readInspectionRecord(inspectionQuery, &record); + inspections->append(record); + } + + QSqlQuery processQuery(DatabaseManager::instance().database()); + processQuery.prepare( + "select process_step, attempt_no, process_state, result_state, plc_step, " + "source, duration_ms, started_at, completed_at " + "from workpiece_process_records where workpiece_id = :workpiece_id " + "order by started_at, id"); + processQuery.bindValue(":workpiece_id", workpiece->id); + if (!processQuery.exec()) { + setError(processQuery, error); + return false; + } + while (processQuery.next()) { + QualityProcessRecord record; + record.processStep = processQuery.value("process_step").toString(); + record.attemptNo = processQuery.value("attempt_no").toInt(); + record.processState = processQuery.value("process_state").toString(); + record.resultState = processQuery.value("result_state").toString(); + record.plcStep = processQuery.value("plc_step").toInt(); + record.source = processQuery.value("source").toString(); + record.durationMs = processQuery.value("duration_ms").isNull() + ? -1 : processQuery.value("duration_ms").toInt(); + record.startedAt = processQuery.value("started_at").toDateTime(); + record.completedAt = processQuery.value("completed_at").toDateTime(); + processRecords->append(record); + } + + QSqlQuery historyQuery(DatabaseManager::instance().database()); + historyQuery.prepare( + "select from_state, to_state, process_step, source, reason, message, " + "elapsed_ms, changed_at from production_state_history " + "where workpiece_id = :workpiece_id order by changed_at, id"); + historyQuery.bindValue(":workpiece_id", workpiece->id); + if (!historyQuery.exec()) { + setError(historyQuery, error); + return false; + } + while (historyQuery.next()) { + QualityStateHistory history; + history.fromState = historyQuery.value("from_state").toString(); + history.toState = historyQuery.value("to_state").toString(); + history.processStep = historyQuery.value("process_step").toString(); + history.source = historyQuery.value("source").toString(); + history.reason = historyQuery.value("reason").toString(); + history.message = historyQuery.value("message").toString(); + history.elapsedMs = historyQuery.value("elapsed_ms").isNull() + ? -1 : historyQuery.value("elapsed_ms").toInt(); + history.changedAt = historyQuery.value("changed_at").toDateTime(); + stateHistory->append(history); + } + return true; +} diff --git a/repositories/qualityrepository.h b/repositories/qualityrepository.h new file mode 100644 index 0000000..e048bce --- /dev/null +++ b/repositories/qualityrepository.h @@ -0,0 +1,32 @@ +#ifndef QUALITYREPOSITORY_H +#define QUALITYREPOSITORY_H + +#include "../models/qualityrecord.h" + +#include +#include + +class QualityRepository +{ +public: + QList listInspectionRecords( + const QString &orderNo = QString(), + const QString &barcode = QString(), + const QString &trayCode = QString(), + int trayPos = 0, + const QString &inspectionMode = QString(), + const QString &inspectionSide = QString(), + const QString &resultState = QString(), + QString *error = nullptr); + + bool queryStatistics(const QString &orderNo, QualityStatistics *statistics, + QString *error = nullptr); + + bool findWorkpieceTrace(const QString &barcode, Workpiece *workpiece, + Order *order, QList *inspections, + QList *processRecords, + QList *stateHistory, + QString *error = nullptr); +}; + +#endif // QUALITYREPOSITORY_H diff --git a/services/orderservice.cpp b/services/orderservice.cpp index c19b81a..b120219 100644 --- a/services/orderservice.cpp +++ b/services/orderservice.cpp @@ -52,6 +52,11 @@ bool OrderService::findOrder(int id, Order *order, QString *error) return OrderRepository().findOrder(id, order, error); } +bool OrderService::findUnfinishedOrder(Order *order, QString *error) +{ + return OrderRepository().findUnfinishedOrder(order, error); +} + bool OrderService::createOrder(Order *order, QString *error) { if (!order) { diff --git a/services/orderservice.h b/services/orderservice.h index d6f635f..024263a 100644 --- a/services/orderservice.h +++ b/services/orderservice.h @@ -12,6 +12,7 @@ public: QList listOrders(QString *error = nullptr, int limit = 100); bool findOrder(int id, Order *order, QString *error = nullptr); + bool findUnfinishedOrder(Order *order, QString *error = nullptr); bool createOrder(Order *order, QString *error = nullptr); bool generateWorkpiecesAndAssign(int orderId, QString *error = nullptr); bool startOrder(int id, QString *error = nullptr); diff --git a/services/productionservice.cpp b/services/productionservice.cpp index 356d386..3bc51b3 100644 --- a/services/productionservice.cpp +++ b/services/productionservice.cpp @@ -403,6 +403,13 @@ bool ProductionService::stop(QString *error) return; } + if ((order.status == "RUNNING" || order.status == "PAUSED") + && !OrderService::instance().cancelOrder( + m_orderId, &orderError)) { + failTermination(orderError); + return; + } + QString persistenceError; if (m_runId > 0 && !ProductionRepository().finishRun( diff --git a/services/qualityservice.cpp b/services/qualityservice.cpp new file mode 100644 index 0000000..4fff933 --- /dev/null +++ b/services/qualityservice.cpp @@ -0,0 +1,37 @@ +#include "qualityservice.h" + +#include "../repositories/qualityrepository.h" + +QualityService &QualityService::instance() +{ + static QualityService service; + return service; +} + +QList QualityService::listInspectionRecords( + const QString &orderNo, const QString &barcode, const QString &trayCode, + int trayPos, const QString &inspectionMode, const QString &inspectionSide, + const QString &resultState, QString *error) +{ + return QualityRepository().listInspectionRecords( + orderNo, barcode, trayCode, trayPos, inspectionMode, inspectionSide, + resultState, error); +} + +bool QualityService::queryStatistics(const QString &orderNo, + QualityStatistics *statistics, + QString *error) +{ + return QualityRepository().queryStatistics(orderNo, statistics, error); +} + +bool QualityService::findWorkpieceTrace( + const QString &barcode, Workpiece *workpiece, Order *order, + QList *inspections, + QList *processRecords, + QList *stateHistory, QString *error) +{ + return QualityRepository().findWorkpieceTrace( + barcode, workpiece, order, inspections, processRecords, stateHistory, + error); +} diff --git a/services/qualityservice.h b/services/qualityservice.h new file mode 100644 index 0000000..de96e81 --- /dev/null +++ b/services/qualityservice.h @@ -0,0 +1,39 @@ +#ifndef QUALITYSERVICE_H +#define QUALITYSERVICE_H + +#include "../models/qualityrecord.h" + +#include +#include + +class QualityService +{ +public: + static QualityService &instance(); + + QList listInspectionRecords( + const QString &orderNo = QString(), + const QString &barcode = QString(), + const QString &trayCode = QString(), + int trayPos = 0, + const QString &inspectionMode = QString(), + const QString &inspectionSide = QString(), + const QString &resultState = QString(), + QString *error = nullptr); + + bool queryStatistics(const QString &orderNo, QualityStatistics *statistics, + QString *error = nullptr); + + bool findWorkpieceTrace(const QString &barcode, Workpiece *workpiece, + Order *order, QList *inspections, + QList *processRecords, + QList *stateHistory, + QString *error = nullptr); + +private: + QualityService() = default; + QualityService(const QualityService &) = delete; + QualityService &operator=(const QualityService &) = delete; +}; + +#endif // QUALITYSERVICE_H diff --git a/ssp.pro b/ssp.pro index a034595..e85e5ba 100644 --- a/ssp.pro +++ b/ssp.pro @@ -27,12 +27,14 @@ SOURCES += \ pages/devicepage.cpp \ pages/logpage.cpp \ pages/orderpage.cpp \ + pages/qualitypage.cpp \ pages/rackpage.cpp \ pages/squaretraybutton.cpp \ pages/uihelpers.cpp \ repositories/logrepository.cpp \ repositories/orderrepository.cpp \ repositories/productionrepository.cpp \ + repositories/qualityrepository.cpp \ repositories/trayrepository.cpp \ repositories/workpiecerepository.cpp \ services/deviceservice.cpp \ @@ -40,6 +42,7 @@ SOURCES += \ services/orderservice.cpp \ services/productionservice.cpp \ services/productionworker.cpp \ + services/qualityservice.cpp \ services/trayservice.cpp \ services/workpieceservice.cpp \ widget.cpp @@ -53,18 +56,21 @@ HEADERS += \ modbus/modbustcpmanager.h \ models/logrecord.h \ models/order.h \ + models/qualityrecord.h \ models/tray.h \ models/workpiece.h \ pages/dashboardpage.h \ pages/devicepage.h \ pages/logpage.h \ pages/orderpage.h \ + pages/qualitypage.h \ pages/rackpage.h \ pages/squaretraybutton.h \ pages/uihelpers.h \ repositories/logrepository.h \ repositories/orderrepository.h \ repositories/productionrepository.h \ + repositories/qualityrepository.h \ repositories/trayrepository.h \ repositories/workpiecerepository.h \ services/deviceservice.h \ @@ -72,6 +78,7 @@ HEADERS += \ services/orderservice.h \ services/productionservice.h \ services/productionworker.h \ + services/qualityservice.h \ services/trayservice.h \ services/workpieceservice.h \ widget.h diff --git a/ssp.pro.user b/ssp.pro.user index 7365e90..f5a87cc 100644 --- a/ssp.pro.user +++ b/ssp.pro.user @@ -1,6 +1,6 @@ - + EnvironmentId @@ -63,249 +63,6 @@ ProjectExplorer.Project.Target.0 - - Desktop Qt 5.14.1 MinGW 64-bit - Desktop Qt 5.14.1 MinGW 64-bit - qt.qt5.5141.win64_mingw73_kit - 0 - 0 - 0 - - E:/QTCode/ssp/build-ssp-Desktop_Qt_5_14_1_MinGW_64_bit-Debug - - - true - QtProjectManager.QMakeBuildStep - true - - false - false - false - - - true - Qt4ProjectManager.MakeStep - - false - - - false - - 2 - Build - Build - ProjectExplorer.BuildSteps.Build - - - - true - Qt4ProjectManager.MakeStep - - true - clean - - false - - 1 - Clean - Clean - ProjectExplorer.BuildSteps.Clean - - 2 - false - - Debug - Qt4ProjectManager.Qt4BuildConfiguration - 2 - - - E:/QTCode/ssp/build-ssp-Desktop_Qt_5_14_1_MinGW_64_bit-Release - - - true - QtProjectManager.QMakeBuildStep - false - - false - false - true - - - true - Qt4ProjectManager.MakeStep - - false - - - false - - 2 - Build - Build - ProjectExplorer.BuildSteps.Build - - - - true - Qt4ProjectManager.MakeStep - - true - clean - - false - - 1 - Clean - Clean - ProjectExplorer.BuildSteps.Clean - - 2 - false - - Release - Qt4ProjectManager.Qt4BuildConfiguration - 0 - - - E:/QTCode/ssp/build-ssp-Desktop_Qt_5_14_1_MinGW_64_bit-Profile - - - true - QtProjectManager.QMakeBuildStep - true - - false - true - true - - - true - Qt4ProjectManager.MakeStep - - false - - - false - - 2 - Build - Build - ProjectExplorer.BuildSteps.Build - - - - true - Qt4ProjectManager.MakeStep - - true - clean - - false - - 1 - Clean - Clean - ProjectExplorer.BuildSteps.Clean - - 2 - false - - Profile - Qt4ProjectManager.Qt4BuildConfiguration - 0 - - 3 - - - 0 - Deploy - Deploy - ProjectExplorer.BuildSteps.Deploy - - 1 - ProjectExplorer.DefaultDeployConfiguration - - 1 - - - dwarf - - cpu-cycles - - - 250 - - -e - cpu-cycles - --call-graph - dwarf,4096 - -F - 250 - - -F - true - 4096 - false - false - 1000 - - true - - false - false - false - false - true - 0.01 - 10 - true - kcachegrind - 1 - 25 - - 1 - true - false - true - valgrind - - 0 - 1 - 2 - 3 - 4 - 5 - 6 - 7 - 8 - 9 - 10 - 11 - 12 - 13 - 14 - - 2 - - Qt4ProjectManager.Qt4RunConfiguration:E:/QTCode/ssp/ssp/ssp.pro - E:/QTCode/ssp/ssp/ssp.pro - - false - - false - true - true - false - false - true - - E:/QTCode/ssp/build-ssp-Desktop_Qt_5_14_1_MinGW_64_bit-Debug - - 1 - - - - ProjectExplorer.Project.Target.1 Desktop Qt 5.14.1 MinGW 32-bit Desktop Qt 5.14.1 MinGW 32-bit @@ -470,6 +227,249 @@ 1 + + dwarf + + cpu-cycles + + + 250 + + -e + cpu-cycles + --call-graph + dwarf,4096 + -F + 250 + + -F + true + 4096 + false + false + 1000 + + true + + false + false + false + false + true + 0.01 + 10 + true + kcachegrind + 1 + 25 + + 1 + true + false + true + valgrind + + 0 + 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10 + 11 + 12 + 13 + 14 + + 2 + + Qt4ProjectManager.Qt4RunConfiguration:E:/QTCode/ssp/ssp/ssp.pro + E:/QTCode/ssp/ssp/ssp.pro + + false + + false + true + true + false + false + true + + E:/QTCode/ssp/build-ssp-Desktop_Qt_5_14_1_MinGW_32_bit-Debug + + 1 + + + + ProjectExplorer.Project.Target.1 + + Desktop Qt 5.14.1 MinGW 64-bit + Desktop Qt 5.14.1 MinGW 64-bit + qt.qt5.5141.win64_mingw73_kit + 0 + 0 + 0 + + E:/QTCode/ssp/build-ssp-Desktop_Qt_5_14_1_MinGW_64_bit-Debug + + + true + QtProjectManager.QMakeBuildStep + true + + false + false + false + + + true + Qt4ProjectManager.MakeStep + + false + + + false + + 2 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + true + Qt4ProjectManager.MakeStep + + true + clean + + false + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Debug + Qt4ProjectManager.Qt4BuildConfiguration + 2 + + + E:/QTCode/ssp/build-ssp-Desktop_Qt_5_14_1_MinGW_64_bit-Release + + + true + QtProjectManager.QMakeBuildStep + false + + false + false + true + + + true + Qt4ProjectManager.MakeStep + + false + + + false + + 2 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + true + Qt4ProjectManager.MakeStep + + true + clean + + false + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Release + Qt4ProjectManager.Qt4BuildConfiguration + 0 + + + E:/QTCode/ssp/build-ssp-Desktop_Qt_5_14_1_MinGW_64_bit-Profile + + + true + QtProjectManager.QMakeBuildStep + true + + false + true + true + + + true + Qt4ProjectManager.MakeStep + + false + + + false + + 2 + Build + Build + ProjectExplorer.BuildSteps.Build + + + + true + Qt4ProjectManager.MakeStep + + true + clean + + false + + 1 + Clean + Clean + ProjectExplorer.BuildSteps.Clean + + 2 + false + + Profile + Qt4ProjectManager.Qt4BuildConfiguration + 0 + + 3 + + + 0 + Deploy + Deploy + ProjectExplorer.BuildSteps.Deploy + + 1 + ProjectExplorer.DefaultDeployConfiguration + + 1 + dwarf diff --git a/widget.cpp b/widget.cpp index b485eeb..4974d93 100644 --- a/widget.cpp +++ b/widget.cpp @@ -5,6 +5,7 @@ #include "pages/devicepage.h" #include "pages/logpage.h" #include "pages/orderpage.h" +#include "pages/qualitypage.h" #include "pages/rackpage.h" #include "pages/uihelpers.h" #include "services/logservice.h" @@ -24,6 +25,7 @@ Widget::Widget(QWidget *parent) , pageStack(nullptr) , dashboardPage(nullptr) , logPage(nullptr) + , qualityPage(nullptr) , systemStateLabel(nullptr) , currentOrderLabel(nullptr) , currentWorkpieceLabel(nullptr) @@ -110,7 +112,8 @@ void Widget::setupMainArea(QVBoxLayout *rootLayout) navList = new QListWidget; navList->setFixedWidth(170); - navList->addItems(QStringList() << "控制面板" << "订单管理" << "料架/托盘" << "设备状态" << "日志"); + navList->addItems(QStringList() << "控制面板" << "订单管理" << "料架/托盘" + << "设备状态" << "日志" << "质量管理"); navList->setCurrentRow(0); bodyLayout->addWidget(navList); @@ -119,6 +122,7 @@ void Widget::setupMainArea(QVBoxLayout *rootLayout) RackPage *rackPage = new RackPage(this); DevicePage *devicePage = new DevicePage(this); logPage = new LogPage(this); + qualityPage = new QualityPage(this); pageStack = new QStackedWidget; pageStack->addWidget(dashboardPage); @@ -126,6 +130,7 @@ void Widget::setupMainArea(QVBoxLayout *rootLayout) pageStack->addWidget(rackPage); pageStack->addWidget(devicePage); pageStack->addWidget(logPage); + pageStack->addWidget(qualityPage); bodyLayout->addWidget(pageStack, 1); rootLayout->addLayout(bodyLayout, 1); diff --git a/widget.h b/widget.h index 6bd6e8e..a987ef0 100644 --- a/widget.h +++ b/widget.h @@ -11,6 +11,7 @@ class DashboardPage; class QLabel; class QListWidget; class LogPage; +class QualityPage; class QStackedWidget; class QVBoxLayout; @@ -34,6 +35,7 @@ private: QStackedWidget *pageStack; DashboardPage *dashboardPage; LogPage *logPage; + QualityPage *qualityPage; QLabel *systemStateLabel; QLabel *currentOrderLabel; QLabel *currentWorkpieceLabel;