Files
ssp/services/orderservice.cpp
T

644 lines
19 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 "orderservice.h"
#include "../db/databasemanager.h"
#include "../repositories/logrepository.h"
#include "../repositories/orderrepository.h"
#include "../repositories/productionrepository.h"
#include "../repositories/trayrepository.h"
#include "../repositories/workpiecerepository.h"
#include <QDateTime>
#include <QSet>
#include <QStringList>
namespace {
bool recordLog(const QString &action, const QString &content, const QString &status,
QString *error)
{
LogRecord record;
record.type = "操作日志";
record.module = "订单管理";
record.action = action;
record.content = content;
record.status = status;
return LogRepository().insertLog(record, error);
}
bool containsState(const QStringList &states, const QString &state)
{
return states.contains(state);
}
QString workpieceBarcode(const QString &orderNo, int sequence)
{
return QString("%1-%2").arg(orderNo).arg(sequence, 6, 10, QChar('0'));
}
}
OrderService &OrderService::instance()
{
static OrderService service;
return service;
}
QList<Order> OrderService::listOrders(QString *error, int limit)
{
return OrderRepository().listOrders(error, limit);
}
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) {
if (error) {
*error = "Order pointer is null";
}
return false;
}
if (order->no.trimmed().isEmpty()) {
if (error) {
*error = "Order number cannot be empty";
}
return false;
}
if (order->planNum <= 0) {
if (error) {
*error = "Order plan quantity must be greater than 0";
}
return false;
}
if (order->inspectionMode != "BEFORE_PLATING"
&& order->inspectionMode != "AFTER_PLATING") {
if (error) {
*error = "Inspection mode must be BEFORE_PLATING or AFTER_PLATING";
}
return false;
}
if (order->startTrayNo <= 0
|| order->startSlotNo < 1 || order->startSlotNo > 49) {
if (error) {
*error = "Start tray or slot is invalid";
}
return false;
}
order->no = order->no.trimmed();
order->status = "NOT_START";
order->qualified = 0;
order->unqualified = 0;
DatabaseManager &database = DatabaseManager::instance();
QString transactionError;
if (!database.transaction(&transactionError)) {
if (error) {
*error = transactionError;
}
return false;
}
OrderRepository repository;
Order unfinishedOrder;
if (!repository.findUnfinishedOrder(&unfinishedOrder, &transactionError)) {
database.rollback();
if (error) {
*error = transactionError;
}
return false;
}
if (unfinishedOrder.id > 0) {
database.rollback();
if (error) {
*error = QString("Unfinished order already exists: %1")
.arg(unfinishedOrder.no);
}
return false;
}
WorkpieceRepository workpieceRepository;
TrayRepository trayRepository;
QList<int> affectedTrayIds;
int removedCount = 0;
if (!workpieceRepository.removeUninspected(
0, &affectedTrayIds, &removedCount, &transactionError)) {
database.rollback();
if (error) {
*error = "新建订单前清理未测量工件失败:" + transactionError;
}
return false;
}
for (const int trayId : affectedTrayIds) {
if (!trayRepository.refreshStats(trayId, &transactionError)) {
database.rollback();
if (error) {
*error = "重新统计料盘占用失败:" + transactionError;
}
return false;
}
}
if (!repository.insertOrder(order, &transactionError)) {
database.rollback();
if (error) {
*error = "写入新订单失败:" + transactionError;
}
return false;
}
if (removedCount > 0
&& !recordLog("清理未测量工件",
QString("新建订单前清理 %1 个未测量工件")
.arg(removedCount),
"成功", &transactionError)) {
database.rollback();
if (error) {
*error = "记录清理日志失败:" + transactionError;
}
return false;
}
if (!recordLog("新建订单", "创建订单:" + order->no,
"成功", &transactionError)) {
database.rollback();
if (error) {
*error = "记录新建订单日志失败:" + transactionError;
}
return false;
}
if (!database.commit(&transactionError)) {
database.rollback();
if (error) {
*error = "提交新建订单事务失败:" + transactionError;
}
return false;
}
return true;
}
bool OrderService::generateWorkpiecesAndAssign(int orderId, QString *error)
{
if (orderId <= 0) {
if (error) {
*error = "Order id must be greater than 0";
}
return false;
}
DatabaseManager &database = DatabaseManager::instance();
QString transactionError;
if (!database.transaction(&transactionError)) {
if (error) {
*error = transactionError;
}
return false;
}
OrderRepository orderRepository;
Order order;
if (!orderRepository.findOrderForUpdate(orderId, &order, &transactionError)) {
database.rollback();
if (error) {
*error = transactionError;
}
return false;
}
if (order.status != "NOT_START") {
database.rollback();
if (error) {
*error = "Only not-started orders can generate workpieces";
}
return false;
}
WorkpieceRepository workpieceRepository;
TrayRepository trayRepository;
QList<Workpiece> workpieces =
workpieceRepository.listByOrder(orderId, &transactionError);
if (!transactionError.isEmpty()) {
database.rollback();
if (error) {
*error = transactionError;
}
return false;
}
if (workpieces.size() > order.planNum) {
database.rollback();
if (error) {
*error = "Existing workpieces exceed order plan quantity";
}
return false;
}
const QList<Tray> trays = trayRepository.listTrays(&transactionError);
if (!transactionError.isEmpty()) {
database.rollback();
if (error) {
*error = transactionError;
}
return false;
}
for (const Tray &tray : trays) {
if (!trayRepository.initializeSlots(tray.id, 7, 7, &transactionError)) {
database.rollback();
if (error) {
*error = transactionError;
}
return false;
}
}
QSet<QString> existingBarcodes;
int assignedCount = 0;
for (const Workpiece &workpiece : workpieces) {
existingBarcodes.insert(workpiece.barcode);
if (workpiece.trayId > 0) {
++assignedCount;
}
}
const int missingCount = order.planNum - workpieces.size();
int nextSequence = 1;
for (int index = 0; index < missingCount; ++index) {
while (existingBarcodes.contains(workpieceBarcode(order.no, nextSequence))) {
++nextSequence;
}
Workpiece workpiece;
workpiece.barcode = workpieceBarcode(order.no, nextSequence);
workpiece.orderId = order.id;
workpiece.state = "PENDING";
if (!workpieceRepository.insertWorkpiece(&workpiece, &transactionError)) {
database.rollback();
if (error) {
*error = transactionError;
}
return false;
}
workpieces.append(workpiece);
existingBarcodes.insert(workpiece.barcode);
++nextSequence;
}
const int requiredSlotCount = order.planNum - assignedCount;
QList<TraySlot> emptySlots;
if (requiredSlotCount > 0) {
const int startTrayIndex = order.startTrayNo - 1;
if (startTrayIndex < 0 || startTrayIndex >= trays.size()) {
database.rollback();
if (error) {
*error = QString("Start tray %1 is outside the configured tray range")
.arg(order.startTrayNo);
}
return false;
}
for (int trayIndex = startTrayIndex;
trayIndex < trays.size() && emptySlots.size() < requiredSlotCount;
++trayIndex) {
const Tray &tray = trays.at(trayIndex);
if (!tray.present) {
continue;
}
const QList<TraySlot> traySlots =
trayRepository.listSlots(tray.id, &transactionError);
if (!transactionError.isEmpty()) {
database.rollback();
if (error) {
*error = transactionError;
}
return false;
}
for (const TraySlot &slot : traySlots) {
const int position = (slot.rowNo - 1) * 7 + slot.columnNo;
if (trayIndex == startTrayIndex && position < order.startSlotNo) {
continue;
}
if (slot.workpieceId == 0 && slot.state == "EMPTY") {
emptySlots.append(slot);
if (emptySlots.size() >= requiredSlotCount) {
break;
}
}
}
}
}
if (!transactionError.isEmpty()) {
database.rollback();
if (error) {
*error = transactionError;
}
return false;
}
if (emptySlots.size() < requiredSlotCount) {
database.rollback();
if (error) {
*error = QString("Not enough empty slots: required %1, available %2")
.arg(requiredSlotCount).arg(emptySlots.size());
}
return false;
}
QList<int> touchedTrayIds;
int slotIndex = 0;
for (const Workpiece &workpiece : workpieces) {
if (workpiece.trayId > 0) {
continue;
}
const TraySlot &slot = emptySlots.at(slotIndex++);
if (!workpieceRepository.assignToSlot(workpiece.id, slot.trayId,
(slot.rowNo - 1) * 7 + slot.columnNo,
slot.rowNo, slot.columnNo,
&transactionError)
|| !trayRepository.assignSlot(slot.trayId, slot.rowNo, slot.columnNo,
workpiece.id, "PENDING",
&transactionError)) {
database.rollback();
if (error) {
*error = transactionError;
}
return false;
}
if (!touchedTrayIds.contains(slot.trayId)) {
touchedTrayIds.append(slot.trayId);
}
}
for (const int trayId : touchedTrayIds) {
if (!trayRepository.refreshStats(trayId, &transactionError)) {
database.rollback();
if (error) {
*error = transactionError;
}
return false;
}
}
if (!orderRepository.refreshProgress(orderId, &transactionError)
|| !recordLog("生成工件", QString("订单 %1 生成并分配 %2 个工件")
.arg(order.no).arg(workpieces.size()), "成功",
&transactionError)
|| !database.commit(&transactionError)) {
database.rollback();
if (error) {
*error = transactionError;
}
return false;
}
return true;
}
bool OrderService::startOrder(int id, QString *error)
{
return transition(id, QStringList() << "NOT_START", "RUNNING", "开始订单", error);
}
bool OrderService::pauseOrder(int id, QString *error)
{
return transition(id, QStringList() << "RUNNING", "PAUSED", "暂停订单", error);
}
bool OrderService::resumeOrder(int id, QString *error)
{
return transition(id, QStringList() << "PAUSED", "RUNNING", "恢复订单", error);
}
bool OrderService::completeOrder(int id, QString *error)
{
DatabaseManager &database = DatabaseManager::instance();
QString transactionError;
if (!database.transaction(&transactionError)) {
if (error) {
*error = transactionError;
}
return false;
}
OrderRepository repository;
if (!repository.refreshProgress(id, &transactionError)) {
database.rollback();
if (error) {
*error = transactionError;
}
return false;
}
Order order;
if (!repository.findOrder(id, &order, &transactionError)) {
database.rollback();
if (error) {
*error = transactionError;
}
return false;
}
if (!containsState(QStringList() << "RUNNING" << "PAUSED", order.status)) {
database.rollback();
if (error) {
*error = "Only running or paused orders can be completed";
}
return false;
}
if (order.qualified + order.unqualified < order.planNum) {
database.rollback();
if (error) {
*error = "Order is not fully processed";
}
return false;
}
if (!repository.updateOrderLifecycle(id, "FINISHED", order.beginTime,
QDateTime::currentDateTime(), &transactionError)
|| !recordLog("完成订单", "完成订单:" + order.no, "成功", &transactionError)
|| !database.commit(&transactionError)) {
database.rollback();
if (error) {
*error = transactionError;
}
return false;
}
return true;
}
bool OrderService::cancelOrder(int id, QString *error)
{
return transition(id, QStringList() << "NOT_START" << "PAUSED",
"CANCELED", "取消订单", error);
}
bool OrderService::terminateOrder(int id, QString *error)
{
return transition(id, QStringList() << "NOT_START" << "RUNNING" << "PAUSED",
"FINISHED", "终止订单(剩余工件不再执行)", error);
}
bool OrderService::deleteOrder(int id, QString *error)
{
DatabaseManager &database = DatabaseManager::instance();
QString transactionError;
if (!database.transaction(&transactionError)) {
if (error) {
*error = transactionError;
}
return false;
}
OrderRepository repository;
Order order;
if (!repository.findOrderForUpdate(id, &order, &transactionError)) {
database.rollback();
if (error) {
*error = transactionError;
}
return false;
}
QString latestRunState;
bool hasActiveRun = false;
if (!ProductionRepository().lockOrderRuns(
id, &latestRunState, &hasActiveRun, &transactionError)) {
database.rollback();
if (error) {
*error = transactionError;
}
return false;
}
if (hasActiveRun) {
database.rollback();
if (error) {
*error = "订单存在活动生产任务,请先在控制面板终止订单;终止完成后,无测量记录的订单会自动删除";
}
return false;
}
const bool manuallyStopped = order.status == "FINISHED"
&& latestRunState == "STOPPED";
if (order.status == "COMPLETED"
|| (order.status == "FINISHED" && !manuallyStopped)) {
database.rollback();
if (error) {
*error = "已完成订单不能删除";
}
return false;
}
if (order.status != "NOT_START" && order.status != "CANCELED"
&& !manuallyStopped) {
database.rollback();
if (error) {
*error = "当前订单不能直接删除,请先在控制面板安全终止订单";
}
return false;
}
WorkpieceRepository workpieceRepository;
bool hasInspectionRecords = false;
if (!workpieceRepository.orderHasInspectionRecords(
id, &hasInspectionRecords, &transactionError)) {
database.rollback();
if (error) {
*error = transactionError;
}
return false;
}
if (hasInspectionRecords) {
database.rollback();
if (error) {
*error = "订单已有测量记录,必须保留检测追溯,不能删除";
}
return false;
}
QList<int> affectedTrayIds;
int removedCount = 0;
if (!workpieceRepository.removeUninspected(
id, &affectedTrayIds, &removedCount, &transactionError)) {
database.rollback();
if (error) {
*error = transactionError;
}
return false;
}
TrayRepository trayRepository;
for (const int trayId : affectedTrayIds) {
if (!trayRepository.refreshStats(trayId, &transactionError)) {
database.rollback();
if (error) {
*error = transactionError;
}
return false;
}
}
if (!repository.removeOrder(id, &transactionError)
|| !recordLog("删除订单",
QString("删除订单:%1,释放 %2 个未测量工件")
.arg(order.no).arg(removedCount),
"成功", &transactionError)
|| !database.commit(&transactionError)) {
database.rollback();
if (error) {
*error = transactionError;
}
return false;
}
return true;
}
bool OrderService::transition(int id, const QStringList &allowedStates,
const QString &targetState, const QString &action,
QString *error)
{
DatabaseManager &database = DatabaseManager::instance();
QString transactionError;
if (!database.transaction(&transactionError)) {
if (error) {
*error = transactionError;
}
return false;
}
OrderRepository repository;
Order order;
if (!repository.findOrder(id, &order, &transactionError)) {
database.rollback();
if (error) {
*error = transactionError;
}
return false;
}
if (!containsState(allowedStates, order.status)) {
database.rollback();
if (error) {
*error = QString("Invalid order state transition: %1 -> %2")
.arg(order.status, targetState);
}
return false;
}
const QDateTime beginTime = targetState == "RUNNING" && !order.beginTime.isValid()
? QDateTime::currentDateTime() : order.beginTime;
const QDateTime endTime = (targetState == "CANCELED" || targetState == "FINISHED")
? QDateTime::currentDateTime() : order.endTime;
if (!repository.updateOrderLifecycle(id, targetState, beginTime, endTime, &transactionError)
|| !recordLog(action, QString("%1:%2").arg(action, order.no),
"成功", &transactionError)
|| !database.commit(&transactionError)) {
database.rollback();
if (error) {
*error = transactionError;
}
return false;
}
return true;
}