Files
ssp/repositories/productionrepository.cpp
T
lidg 6e22fe5672 feat(layout): 导航菜单自动刷新
-点击导航菜单对应页面自动刷新
-设备布局示意,添加背景图片及显示修改
2026-11-11 10:44:12 +08:00

737 lines
31 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#include "productionrepository.h"
#include "../db/databasemanager.h"
#include <QSqlError>
#include <QSqlQuery>
#include <QVariant>
#include <QMap>
#include <QRegularExpression>
namespace {
bool ensureOpen(QString *error)
{
return DatabaseManager::instance().open(error);
}
void setError(const QSqlQuery &query, QString *error)
{
if (error) {
*error = query.lastError().text();
}
}
QVariant nullableId(int id)
{
return id > 0 ? QVariant(id) : QVariant(QVariant::Int);
}
}
int ProductionRepository::createRun(int orderId, const QString &productionState,
const QString &processStep,
const QString &inspectionMode,
int startTrayNo, int startSlotNo, int planNum,
QString *error)
{
if (!ensureOpen(error)) {
return 0;
}
QSqlQuery query(DatabaseManager::instance().database());
query.prepare("insert into production_runs "
"(order_id, run_state, production_state, process_step, inspection_mode, "
"start_tray_no, start_slot_no, plan_num) "
"values (:order_id, 'RUNNING', :production_state, :process_step, "
":inspection_mode, :start_tray_no, :start_slot_no, :plan_num) "
"returning id");
query.bindValue(":order_id", orderId);
query.bindValue(":production_state", productionState);
query.bindValue(":process_step", processStep);
query.bindValue(":inspection_mode", inspectionMode);
query.bindValue(":start_tray_no", startTrayNo);
query.bindValue(":start_slot_no", startSlotNo);
query.bindValue(":plan_num", planNum);
if (!query.exec() || !query.next()) {
setError(query, error);
return 0;
}
return query.value(0).toInt();
}
bool ProductionRepository::updateRun(int runId, const QString &runState,
const QString &productionState,
const QString &processStep,
int currentWorkpieceId,
const QString &timeoutState,
int recoveryRetryCount,
const QString &lastError,
QString *error)
{
if (runId <= 0 || !ensureOpen(error)) {
return false;
}
QSqlQuery query(DatabaseManager::instance().database());
query.prepare("update production_runs set "
"run_state = :run_state, "
"production_state = :production_state, "
"process_step = :process_step, "
"current_workpiece_id = :current_workpiece_id, "
"timeout_state = :timeout_state, "
"recovery_retry_count = :recovery_retry_count, "
"last_error = :last_error, "
"last_heartbeat_at = now(), updated_at = now() "
"where id = :id");
query.bindValue(":run_state", runState);
query.bindValue(":production_state", productionState);
query.bindValue(":process_step", processStep);
query.bindValue(":current_workpiece_id", nullableId(currentWorkpieceId));
query.bindValue(":timeout_state", timeoutState);
query.bindValue(":recovery_retry_count", recoveryRetryCount);
query.bindValue(":last_error", lastError);
query.bindValue(":id", runId);
if (!query.exec()) {
setError(query, error);
return false;
}
if (query.numRowsAffected() != 1) {
if (error) *error = "生产运行记录不存在或已改变,请重新核对";
return false;
}
return true;
}
bool ProductionRepository::finishRun(int runId, const QString &runState,
const QString &lastError, QString *error)
{
if (!ensureOpen(error)) {
return false;
}
QSqlQuery query(DatabaseManager::instance().database());
query.prepare("update production_runs set run_state = :run_state, "
"last_error = :last_error, ended_at = now(), "
"last_heartbeat_at = now(), updated_at = now() "
"where id = :id");
query.bindValue(":run_state", runState);
query.bindValue(":last_error", lastError);
query.bindValue(":id", runId);
if (!query.exec()) {
setError(query, error);
return false;
}
if (query.numRowsAffected() != 1) {
if (error) *error = "生产运行记录不存在或已改变,请重新核对";
return false;
}
return true;
}
bool ProductionRepository::heartbeatRun(int runId, QString *error)
{
if (runId <= 0 || !ensureOpen(error)) {
return false;
}
QSqlQuery query(DatabaseManager::instance().database());
query.prepare("update production_runs set "
"last_heartbeat_at = now(), updated_at = now() "
"where id = :id "
"and run_state in ('RUNNING', 'PAUSED', 'RECOVERY', 'STOPPING')");
query.bindValue(":id", runId);
if (!query.exec()) {
setError(query, error);
return false;
}
return query.numRowsAffected() == 1;
}
bool ProductionRepository::findActiveRun(ProductionRunSnapshot *run, QString *error)
{
if (!run || !ensureOpen(error)) {
return false;
}
QSqlQuery query(DatabaseManager::instance().database());
query.prepare("select * from production_runs "
"where run_state in ('RUNNING', 'PAUSED', 'RECOVERY', 'STOPPING') "
"order by id desc limit 2");
if (!query.exec()) {
setError(query, error);
return false;
}
if (!query.next()) {
*run = ProductionRunSnapshot();
return true;
}
run->id = query.value("id").toInt();
run->orderId = query.value("order_id").toInt();
run->currentWorkpieceId = query.value("current_workpiece_id").toInt();
run->planNum = query.value("plan_num").toInt();
run->startTrayNo = query.value("start_tray_no").toInt();
run->startSlotNo = query.value("start_slot_no").toInt();
run->inspectionMode = query.value("inspection_mode").toString();
run->runState = query.value("run_state").toString();
run->productionState = query.value("production_state").toString();
run->processStep = query.value("process_step").toString();
run->timeoutState = query.value("timeout_state").toString();
run->recoveryRetryCount = query.value("recovery_retry_count").toInt();
run->lastError = query.value("last_error").toString();
run->action.token = query.value("action_token").toString();
run->action.type = query.value("action_type").toString();
run->action.phase = query.value("action_phase").toString();
run->action.nextStep = query.value("action_next_step").toString();
run->action.attempt = query.value("action_attempt").toInt();
run->action.version = query.value("action_lock_version").toInt();
run->action.command = query.value("action_command_value");
run->action.feedback = query.value("action_feedback_value");
run->action.manualDecision = query.value("manual_decision").toString();
run->action.manualOperator = query.value("manual_operator").toString();
run->action.manualDecidedAt = query.value("manual_decided_at").toDateTime();
if (query.next()) {
if (error) *error = "发现多个活动生产任务,请先核对运行记录,不能自动选择订单";
return false;
}
return true;
}
bool ProductionRepository::findRun(int runId, ProductionRunSnapshot *run, QString *error)
{
if (!run || !ensureOpen(error)) return false;
QSqlQuery query(DatabaseManager::instance().database());
query.prepare("select * from production_runs where id = :id");
query.bindValue(":id", runId);
if (!query.exec()) { setError(query, error); return false; }
if (!query.next()) { if (error) *error = "Production run no longer exists"; return false; }
run->id = query.value("id").toInt();
run->orderId = query.value("order_id").toInt();
run->currentWorkpieceId = query.value("current_workpiece_id").toInt();
run->planNum = query.value("plan_num").toInt();
run->startTrayNo = query.value("start_tray_no").toInt();
run->startSlotNo = query.value("start_slot_no").toInt();
run->inspectionMode = query.value("inspection_mode").toString();
run->runState = query.value("run_state").toString();
run->productionState = query.value("production_state").toString();
run->processStep = query.value("process_step").toString();
run->timeoutState = query.value("timeout_state").toString();
run->recoveryRetryCount = query.value("recovery_retry_count").toInt();
run->lastError = query.value("last_error").toString();
run->action.token = query.value("action_token").toString();
run->action.type = query.value("action_type").toString();
run->action.phase = query.value("action_phase").toString();
run->action.nextStep = query.value("action_next_step").toString();
run->action.attempt = query.value("action_attempt").toInt();
run->action.version = query.value("action_lock_version").toInt();
run->action.command = query.value("action_command_value");
run->action.feedback = query.value("action_feedback_value");
run->action.manualDecision = query.value("manual_decision").toString();
run->action.manualOperator = query.value("manual_operator").toString();
run->action.manualDecidedAt = query.value("manual_decided_at").toDateTime();
return true;
}
bool ProductionRepository::lockOrderRuns(int orderId, QString *latestRunState,
bool *hasActiveRun, QString *error)
{
if (!latestRunState || !hasActiveRun || !ensureOpen(error)) {
return false;
}
latestRunState->clear();
*hasActiveRun = false;
QSqlQuery query(DatabaseManager::instance().database());
query.prepare("select run_state from production_runs "
"where order_id = :order_id order by id desc for update");
query.bindValue(":order_id", orderId);
if (!query.exec()) {
setError(query, error);
return false;
}
bool first = true;
while (query.next()) {
const QString runState = query.value(0).toString();
if (first) {
*latestRunState = runState;
first = false;
}
if (runState == "RUNNING" || runState == "PAUSED"
|| runState == "RECOVERY" || runState == "STOPPING") {
*hasActiveRun = true;
}
}
return true;
}
bool ProductionRepository::checkActionSchema(QString *error)
{
if (!ensureOpen(error)) return false;
QSqlQuery query(DatabaseManager::instance().database());
query.prepare("select action_token, action_type, action_phase, action_next_step, "
"action_attempt, action_lock_version, action_command_value, action_feedback_value, "
"manual_decision, manual_operator, manual_decided_at, action_updated_at "
"from production_runs where 1 = 0");
if (!query.exec()) {
if (error) *error = "请先执行 db/migrations/2026-10-29-production-action-checkpoints.sql:" + query.lastError().text();
return false;
}
if (DatabaseManager::instance().database().driverName() != "QPSQL") return true;
const QMap<QString, QString> expectedTypes = {
{"action_token", "character varying(64)"},
{"action_type", "character varying(32)"},
{"action_phase", "character varying(32)"},
{"action_next_step", "character varying(64)"},
{"action_attempt", "integer"},
{"action_lock_version", "integer"},
{"action_command_value", "boolean"},
{"action_feedback_value", "boolean"},
{"manual_decision", "character varying(32)"},
{"manual_operator", "character varying(64)"},
{"manual_decided_at", "timestamp without time zone"},
{"action_updated_at", "timestamp without time zone"}
};
query.prepare("select a.attname, format_type(a.atttypid,a.atttypmod), a.attnotnull, "
"pg_get_expr(d.adbin,d.adrelid) from pg_attribute a "
"left join pg_attrdef d on d.adrelid=a.attrelid and d.adnum=a.attnum "
"where a.attrelid='production_runs'::regclass and a.attnum>0 and not a.attisdropped");
if (!query.exec()) { setError(query, error); return false; }
int checked = 0;
while (query.next()) {
const QString name = query.value(0).toString();
if (!expectedTypes.contains(name)) continue;
const bool counter = name == "action_attempt" || name == "action_lock_version";
if (query.value(1).toString() != expectedTypes.value(name)
|| query.value(2).toBool() != counter
|| (counter && query.value(3).toString() != "0")) {
if (error) *error = "动作恢复字段类型、空值或默认值不匹配:" + name;
return false;
}
++checked;
}
if (checked != expectedTypes.size()) {
if (error) *error = "动作恢复数据库字段不完整";
return false;
}
const QMap<QString, QString> expectedChecks = {
{"ck_production_runs_action_type", "CHECK (action_type IS NULL OR action_type = ANY ARRAY['PHOTO_MOVE','VISION','RACK_PICK','FRONT_LOAD','INSPECT','FRONT_UNLOAD','FLIP','BACK_LOAD','BACK_UNLOAD','REVERSE_FLIP','RACK_PLACE'])"},
{"ck_production_runs_action_phase", "CHECK (action_phase IS NULL OR action_phase = ANY ARRAY['NOT_SENT','SENDING','COMMAND_CONFIRMED','FEEDBACK_RECEIVED','SIGNALS_CLEARED','STEP_COMMITTED','RESULT_WRITING','RESULT_CONFIRMED','MODE_WRITING','MODE_CONFIRMED'])"},
{"ck_production_runs_manual_decision", "CHECK (manual_decision IS NULL OR manual_decision = ANY ARRAY['ACTION_COMPLETED','ACTION_NOT_EXECUTED','RETRY_VISION','NORMAL_PICK'])"},
{"ck_production_runs_action_attempt", "CHECK (action_attempt >= 0)"},
{"ck_production_runs_action_lock_version", "CHECK (action_lock_version >= 0)"}
};
auto normalizedCheck = [](QString definition) {
definition.remove(QRegularExpression("::(?:character varying|text)(?:\\[\\])?"));
definition.remove(QRegularExpression("[\\s()\\[\\]]"));
return definition;
};
query.prepare("select conname, pg_get_constraintdef(oid) from pg_constraint "
"where conrelid='production_runs'::regclass and contype='c' and convalidated");
if (!query.exec()) { setError(query, error); return false; }
checked = 0;
while (query.next()) {
const QString name = query.value(0).toString();
if (!expectedChecks.contains(name)) continue;
if (normalizedCheck(query.value(1).toString()) != normalizedCheck(expectedChecks.value(name))) {
if (error) *error = name == "ck_production_runs_action_type"
? "动作类型约束不匹配,请先执行 db/migrations/2026-11-06-production-plc-flow.sql"
: "动作恢复约束定义不匹配:" + name;
return false;
}
++checked;
}
if (checked != expectedChecks.size()) {
if (error) *error = "动作恢复数据库约束不完整,请执行检查点升级 SQL";
return false;
}
query.prepare("select count(*) from pg_index i join pg_attribute a "
"on a.attrelid=i.indrelid and a.attnum=i.indkey[0] "
"where i.indrelid='production_runs'::regclass and i.indisunique and i.indisvalid "
"and i.indnatts=1 and a.attname='action_token' "
"and pg_get_expr(i.indpred,i.indrelid)='(action_token IS NOT NULL)'");
if (!query.exec() || !query.next() || query.value(0).toInt() < 1) {
if (error) *error = "动作恢复唯一索引不完整,请执行检查点升级 SQL";
return false;
}
return true;
}
bool ProductionRepository::saveActionCheckpoint(int runId, int orderId, int workpieceId,
ProductionActionCheckpoint *action, QString *error)
{
if (!action || !ensureOpen(error)) return false;
QSqlQuery query(DatabaseManager::instance().database());
query.prepare("update production_runs set action_token=:token, action_type=:type, "
"action_phase=:phase, action_next_step=:next, action_attempt=:attempt, "
"action_lock_version=action_lock_version+1, action_command_value=:command, "
"action_feedback_value=:feedback, manual_decision=:decision, manual_operator=:operator, "
"manual_decided_at=:decided, action_updated_at=now(), updated_at=now() "
"where id=:id and order_id=:order_id and current_workpiece_id is not distinct from :workpiece "
"and action_lock_version=:version");
query.bindValue(":token", action->token);
query.bindValue(":type", action->type);
query.bindValue(":phase", action->phase);
query.bindValue(":next", action->nextStep);
query.bindValue(":attempt", action->attempt);
query.bindValue(":command", action->command.isNull() ? QVariant(QVariant::Bool) : action->command);
query.bindValue(":feedback", action->feedback.isNull() ? QVariant(QVariant::Bool) : action->feedback);
query.bindValue(":decision", action->manualDecision);
query.bindValue(":operator", action->manualOperator);
query.bindValue(":decided", action->manualDecidedAt.isValid() ? QVariant(action->manualDecidedAt) : QVariant(QVariant::DateTime));
query.bindValue(":id", runId);
query.bindValue(":order_id", orderId);
query.bindValue(":workpiece", nullableId(workpieceId));
query.bindValue(":version", action->version);
if (!query.exec()) { setError(query, error); return false; }
if (query.numRowsAffected() != 1) {
if (error) *error = "动作检查点已改变,请重新读取恢复状态";
return false;
}
++action->version;
return true;
}
bool ProductionRepository::findInspectionResult(int workpieceId, const QString &side,
int *rawResult, QString *resultState, QString *error,
const QString &actionToken, int actionAttempt)
{
if (!rawResult || !resultState || (side != "FRONT" && side != "BACK")) {
if (error) *error = "Invalid inspection result request";
return false;
}
if (!ensureOpen(error)) return false;
QSqlQuery query(DatabaseManager::instance().database());
QString sql = "select raw_result, result_state from inspection_records "
"where workpiece_id=:id and inspection_side=:side and inspection_state='COMPLETED' "
"and created_at >= (select started_at from workpiece_process_records "
"where workpiece_id=:id and process_step=:step order by attempt_no desc limit 1) ";
if (!actionToken.isEmpty()) sql += "and message=:action_message ";
sql += "order by attempt_no desc limit 1";
query.prepare(sql);
query.bindValue(":id", workpieceId);
query.bindValue(":side", side);
query.bindValue(":step", side == "FRONT" ? "FRONT_CHECKING" : "BACK_CHECKING");
if (!actionToken.isEmpty())
query.bindValue(":action_message", "action=" + actionToken + ";attempt=" + QString::number(actionAttempt));
if (!query.exec()) { setError(query, error); return false; }
if (!query.next()) { if (error) *error = "检测结果尚未持久化,不能认定检测完成"; return false; }
if (query.value(0).isNull()) {
if (error) *error = "检测结果为空,不能认定检测完成";
return false;
}
*rawResult = query.value(0).toInt();
*resultState = query.value(1).toString();
return *resultState == "OK" || *resultState == "NG";
}
bool ProductionRepository::insertStateHistory(
int runId, int orderId, int workpieceId, const QString &fromState,
const QString &toState, const QString &processStep, const QString &source,
const QString &reason, const QString &message, QString *error,
const QString &operatorName)
{
if (!ensureOpen(error)) {
return false;
}
QSqlQuery query(DatabaseManager::instance().database());
query.prepare("insert into production_state_history "
"(production_run_id, order_id, workpiece_id, from_state, "
"to_state, process_step, source, reason, message, operator_name) "
"values (:run_id, :order_id, :workpiece_id, :from_state, "
":to_state, :process_step, :source, :reason, :message, :operator)");
query.bindValue(":run_id", nullableId(runId));
query.bindValue(":order_id", nullableId(orderId));
query.bindValue(":workpiece_id", nullableId(workpieceId));
query.bindValue(":from_state", fromState);
query.bindValue(":to_state", toState);
query.bindValue(":process_step", processStep);
query.bindValue(":source", source);
query.bindValue(":reason", reason);
query.bindValue(":message", message);
query.bindValue(":operator", operatorName);
if (!query.exec()) {
setError(query, error);
return false;
}
return true;
}
bool ProductionRepository::startWorkpieceProcess(
int orderId, int workpieceId, const QString &processStep,
const QString &inspectionMode, int plcStep, const QString &source,
QString *error)
{
if (!ensureOpen(error)) {
return false;
}
QSqlQuery attemptQuery(DatabaseManager::instance().database());
attemptQuery.prepare("select coalesce(max(attempt_no), 0) + 1 "
"from workpiece_process_records "
"where workpiece_id = :workpiece_id "
"and process_step = :process_step");
attemptQuery.bindValue(":workpiece_id", workpieceId);
attemptQuery.bindValue(":process_step", processStep);
if (!attemptQuery.exec() || !attemptQuery.next()) {
setError(attemptQuery, error);
return false;
}
QSqlQuery query(DatabaseManager::instance().database());
query.prepare("insert into workpiece_process_records "
"(order_id, workpiece_id, process_step, inspection_mode, attempt_no, "
"process_state, plc_step, source) "
"values (:order_id, :workpiece_id, :process_step, :inspection_mode, "
":attempt_no, 'RUNNING', :plc_step, :source)");
query.bindValue(":order_id", nullableId(orderId));
query.bindValue(":workpiece_id", workpieceId);
query.bindValue(":process_step", processStep);
query.bindValue(":inspection_mode", inspectionMode);
query.bindValue(":attempt_no", attemptQuery.value(0).toInt());
query.bindValue(":plc_step", plcStep);
query.bindValue(":source", source);
if (!query.exec()) {
setError(query, error);
return false;
}
return true;
}
bool ProductionRepository::finishWorkpieceProcess(
int workpieceId, const QString &processStep, const QString &resultState,
int durationMs, QString *error)
{
if (!ensureOpen(error)) {
return false;
}
QSqlQuery query(DatabaseManager::instance().database());
query.prepare("update workpiece_process_records set "
"process_state = 'COMPLETED', result_state = :result_state, "
"completed_at = now(), duration_ms = :duration_ms "
"where id = (select id from workpiece_process_records "
"where workpiece_id = :workpiece_id "
"and process_step = :process_step "
"and process_state = 'RUNNING' "
"order by id desc limit 1)");
query.bindValue(":result_state", resultState);
query.bindValue(":duration_ms", durationMs >= 0 ? QVariant(durationMs)
: QVariant(QVariant::Int));
query.bindValue(":workpiece_id", workpieceId);
query.bindValue(":process_step", processStep);
if (!query.exec()) {
setError(query, error);
return false;
}
return true;
}
QList<WorkpieceProcessRecord> ProductionRepository::listProcessRecords(
int workpieceId, QString *error)
{
QList<WorkpieceProcessRecord> records;
if (workpieceId <= 0 || !ensureOpen(error)) {
return records;
}
QSqlQuery query(DatabaseManager::instance().database());
query.prepare("select process_step, attempt_no, process_state, "
"result_state, duration_ms, started_at, completed_at "
"from workpiece_process_records "
"where workpiece_id = :workpiece_id "
"order by started_at desc, id desc");
query.bindValue(":workpiece_id", workpieceId);
if (!query.exec()) {
setError(query, error);
return records;
}
while (query.next()) {
WorkpieceProcessRecord record;
record.processStep = query.value("process_step").toString();
record.attemptNo = query.value("attempt_no").toInt();
record.processState = query.value("process_state").toString();
record.resultState = query.value("result_state").toString();
record.durationMs = query.value("duration_ms").isNull()
? -1 : query.value("duration_ms").toInt();
record.startedAt = query.value("started_at").toDateTime();
record.completedAt = query.value("completed_at").toDateTime();
records.append(record);
}
return records;
}
bool ProductionRepository::insertInspection(
int orderId, int workpieceId, const QString &side, int rawResult,
const QString &resultState, const QString &inspectionMode, int plcStep,
const QString &source, const QString &message, QString *error)
{
if (!ensureOpen(error)) {
return false;
}
QSqlQuery attemptQuery(DatabaseManager::instance().database());
attemptQuery.prepare("select coalesce(max(attempt_no), 0) + 1 "
"from inspection_records "
"where workpiece_id = :workpiece_id "
"and inspection_side = :side");
attemptQuery.bindValue(":workpiece_id", workpieceId);
attemptQuery.bindValue(":side", side);
if (!attemptQuery.exec() || !attemptQuery.next()) {
setError(attemptQuery, error);
return false;
}
QSqlQuery query(DatabaseManager::instance().database());
query.prepare("insert into inspection_records "
"(order_id, workpiece_id, inspection_side, inspection_mode, attempt_no, "
"raw_result, result_state, inspection_state, source, "
"plc_step, message, started_at, completed_at) "
"values (:order_id, :workpiece_id, :side, :inspection_mode, :attempt_no, "
":raw_result, :result_state, 'COMPLETED', :source, "
":plc_step, :message, now(), now())");
query.bindValue(":order_id", nullableId(orderId));
query.bindValue(":workpiece_id", workpieceId);
query.bindValue(":side", side);
query.bindValue(":inspection_mode", inspectionMode);
query.bindValue(":attempt_no", attemptQuery.value(0).toInt());
query.bindValue(":raw_result", rawResult);
query.bindValue(":result_state", resultState);
query.bindValue(":source", source);
query.bindValue(":plc_step", plcStep);
query.bindValue(":message", message);
if (!query.exec()) {
setError(query, error);
return false;
}
return true;
}
bool ProductionRepository::insertAlarm(
const QString &code, const QString &message, int orderId,
int workpieceId, const QString &fallbackLevel,
const QString &fallbackSource, QString *error)
{
if (!ensureOpen(error)) {
return false;
}
QSqlQuery duplicateQuery(DatabaseManager::instance().database());
duplicateQuery.prepare("select id from alarm_records "
"where code = :code "
"and alarm_state <> 'CLEARED' "
"and order_id is not distinct from :order_id "
"and workpiece_id is not distinct from :workpiece_id "
"limit 1");
duplicateQuery.bindValue(":code", code);
duplicateQuery.bindValue(":order_id", nullableId(orderId));
duplicateQuery.bindValue(":workpiece_id", nullableId(workpieceId));
if (!duplicateQuery.exec()) {
setError(duplicateQuery, error);
return false;
}
if (duplicateQuery.next()) {
return true;
}
QSqlQuery definitionQuery(DatabaseManager::instance().database());
definitionQuery.prepare("select id, level, source from alarm_definitions "
"where code = :code");
definitionQuery.bindValue(":code", code);
if (!definitionQuery.exec()) {
setError(definitionQuery, error);
return false;
}
QVariant definitionId(QVariant::Int);
QString level = fallbackLevel;
QString source = fallbackSource;
if (definitionQuery.next()) {
definitionId = definitionQuery.value("id");
level = definitionQuery.value("level").toString();
source = definitionQuery.value("source").toString();
}
QSqlQuery query(DatabaseManager::instance().database());
query.prepare("insert into alarm_records "
"(definition_id, code, level, source, order_id, workpiece_id, message) "
"values (:definition_id, :code, :level, :source, "
":order_id, :workpiece_id, :message)");
query.bindValue(":definition_id", definitionId);
query.bindValue(":code", code);
query.bindValue(":level", level);
query.bindValue(":source", source);
query.bindValue(":order_id", nullableId(orderId));
query.bindValue(":workpiece_id", nullableId(workpieceId));
query.bindValue(":message", message);
if (!query.exec()) {
setError(query, error);
return false;
}
return true;
}
bool ProductionRepository::clearActiveAlarms(const QString &code,
const QString &clearedBy,
QString *error)
{
if (!ensureOpen(error)) {
return false;
}
QSqlQuery query(DatabaseManager::instance().database());
query.prepare(code.trimmed().isEmpty()
? "update alarm_records set alarm_state = 'CLEARED', "
"cleared_at = now(), cleared_by = :cleared_by "
"where alarm_state <> 'CLEARED'"
: "update alarm_records set alarm_state = 'CLEARED', "
"cleared_at = now(), cleared_by = :cleared_by "
"where alarm_state <> 'CLEARED' and code = :code");
query.bindValue(":cleared_by", clearedBy);
if (!code.trimmed().isEmpty()) {
query.bindValue(":code", code);
}
if (!query.exec()) {
setError(query, error);
return false;
}
return true;
}
bool ProductionRepository::insertDeviceStatus(
const QString &deviceCode, bool plcConnected, bool plcReady,
bool robotReady, bool safetyDoorClosed, bool emergencyStop,
int currentStep, int checkResult, int errorCode, QString *error)
{
if (!ensureOpen(error)) {
return false;
}
QSqlQuery query(DatabaseManager::instance().database());
query.prepare("insert into device_status_history "
"(device_code, plc_connected, plc_ready, robot_ready, "
"safety_door_closed, emergency_stop, current_step, "
"check_result, error_code) "
"values (:device_code, :plc_connected, :plc_ready, "
":robot_ready, :safety_door_closed, :emergency_stop, "
":current_step, :check_result, :error_code)");
query.bindValue(":device_code", deviceCode);
query.bindValue(":plc_connected", plcConnected);
query.bindValue(":plc_ready", plcReady);
query.bindValue(":robot_ready", robotReady);
query.bindValue(":safety_door_closed", safetyDoorClosed);
query.bindValue(":emergency_stop", emergencyStop);
query.bindValue(":current_step", currentStep);
query.bindValue(":check_result", checkResult);
query.bindValue(":error_code", errorCode);
if (!query.exec()) {
setError(query, error);
return false;
}
return true;
}