liufumingren e19b5fc18c feat(order): 取消单据支持 CK 出库单与 RK 入库单
- 奇门 order.cancel:CK 组(PTCK/DBCK/B2BCK/QTCK/CGTH)委托 systems.stockoutOrder.cancel 取消出库单(仅 CREATED/PENDING 可取消,释放 QM_STOCKOUT 锁定,不回传);RK 组由裸改状态升级为复用 systems.storage.entry.cancel 完整作废流程(状态守卫 + 回退收货单占用 + 操作日志,已作废幂等成功)。

- openapi order.cancel:新增 CK 组与 RK 组路由,成功/失败文案与奇门口径一致。

- storage.stockout.cancel 改为委托共享实现,对外契约与文案不变,改为单事务 + 行锁。

- storage.entry.cancel 扩展入参能力(entryOrderCode 定位 / skipExternalSync / idempotent / notFoundMessage),系统方法入口行为不变。

- 文档:methods/{qimen,openapi,system}.json 及对应 changes 同步。

注:app/service/systems/stockout_order.js 与 methods/openapi.json 同时承载此前未提交的出库单(stockout)共享服务与文档,文件粒度无法拆分,一并纳入本次提交。
2026-09-13 02:24:18 +08:00

785 lines
29 KiB
JavaScript
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.

'use strict';
const MainService = require('../main');
const { getInterceptRequestBlockReason, resolveInterceptRequestGuardInfo } = require('../../lib/intercept_guard');
const { buildNoticeTimePatch } = require('../../lib/intercept_time');
class orderServer extends MainService {
constructor(ctx) {
super(ctx);
// 初始化公共变量
this.orderType = {
JYCK: {
method: 'ORDER',
name: '一般交易出库单',
},
HHCK: {
method: 'ORDER',
name: '换货出库',
},
BFCK: {
method: 'ORDER',
name: '补发出库',
},
PTCK: {
method: 'CK',
name: '普通出库单',
},
DBCK: {
method: 'CK',
name: '调拨出库',
},
B2BCK: {
method: 'CK',
name: 'B2B出库',
},
QTCK: {
method: 'CK',
name: '其他出库',
},
CGTH: {
method: 'CK',
name: '采购退货出库单',
},
B2BRK: {
method: 'RK',
name: 'B2B入库',
},
SCRK: {
method: 'RK',
name: '生产入库',
},
LYRK: {
method: 'RK',
name: '领用入库',
},
CCRK: {
method: 'RK',
name: '残次品入库',
},
CGRK: {
method: 'RK',
name: '采购入库',
},
DBRK: {
method: 'RK',
name: '调拨入库',
},
QTRK: {
method: 'RK',
name: '其他入库',
},
XTRK: {
method: 'BACKORDER',
name: '销退入库',
},
THRK: {
method: 'BACKORDER',
name: '退货入库',
},
HHRK: {
method: 'BACKORDER',
name: '换货入库',
},
CNJG: {
method: 'JG',
name: '仓内加工单',
},
};
}
/**
* 查询订单关联的拦截运单信息。
*
* 强制同仓校验:读取 wms_order_express 必须同时带订单ID与仓库ID,
* 禁止仅凭订单ID跨仓串读运单号;仓库ID缺失时拒绝读取。
*
* @param {number|string} orderId 订单ID。
* @param {number|string|null|undefined} warehouseId 仓库ID,必须为订单所属仓库。
* @return {Promise<Array<Object>>} 运单信息列表。
*/
async getInterceptExpressInfo(orderId, warehouseId) {
const { ctx } = this;
const normalizedOrderId = Number(orderId || 0);
const normalizedWarehouseId = warehouseId !== null && warehouseId !== undefined && warehouseId !== ''
? Number(warehouseId)
: 0;
if (!Number.isFinite(normalizedOrderId) || normalizedOrderId <= 0) {
return [];
}
if (!Number.isFinite(normalizedWarehouseId) || normalizedWarehouseId <= 0) {
return [];
}
const orderExpressModel = ctx.model && ctx.model.OrderExpress;
if (!orderExpressModel || typeof orderExpressModel.findAll !== 'function') {
return [];
}
const rows = await orderExpressModel.findAll({
where: {
order_id: normalizedOrderId,
warehouse_id: normalizedWarehouseId,
},
attributes: [ 'waybill_code', 'logistics_code', 'logistics_name', 'logistics_interface_id' ],
order: [[ 'id', 'DESC' ]],
raw: true,
});
return (Array.isArray(rows) ? rows : []).map(row => ({
waybill_code: String(row && row.waybill_code || '').trim(),
logistics_code: String(row && row.logistics_code || '').trim(),
logistics_name: String(row && row.logistics_name || '').trim(),
logistics_interface_id: row && row.logistics_interface_id == null ? null : Number(row.logistics_interface_id),
}));
}
async sendCancelInterceptNotice({ orderCode, existingOrder, info }) {
const { ctx } = this;
try {
const express = await this.getInterceptExpressInfo(existingOrder && existingOrder.id, info.warehouseId);
await ctx.service.systems.notice.send({
event: 'order_cancel_intercepted',
businessName: 'order',
warehouseId: info.warehouseId,
storeId: info.storeId,
subject: {
id: info.storeId,
type: 'store',
},
businessId: orderCode,
messageType: 'text',
title: `订单取消触发拦截:${orderCode}`,
content: `订单 ${orderCode} 因拣货/打印状态未完成,已标记为拦截执行。`,
sender: {
id: ctx.user?.employees_id || ctx.user?.id,
name: ctx.user?.employees_name || '',
},
metadata: {
orderCode,
orderId: existingOrder.id,
pickStatus: String(existingOrder.pick_status || 'none').trim(),
printStatus: String(existingOrder.print_status || 'none').trim(),
interceptStatus: String(existingOrder.intercept_status || 'none').trim(),
express,
},
});
} catch (error) {
ctx.logger.warn(`取消订单拦截通知发送失败: ${error.message}`);
}
}
/**
* 取消奇门订单。
* 按 orderType 分发:
* - ORDER(JYCK/HHCK/BFCK):订单未同步且未开始拣货/打印时直接取消;已同步或已开始
* 拣货/打印时转入拦截处理:写入订单拦截状态 intercept_status(intercepting/requested)
* 并同步写入拦截时间 intercept_time。
* - RK(B2BRK/SCRK/LYRK/CCRK/CGRK/DBRK/QTRK):走入库单作废流程(状态守卫、
* 回退收货单占用、写操作日志),取消成功后不需要向奇门回传任何事件。
* - CK(PTCK/DBCK/B2BCK/QTCK/CGTH):走独立出库单表 wms_order_stockout 取消,
* 取消成功后不需要向奇门回传任何事件。
* @param {Object} data 奇门请求数据。
* @param {Object} data.request 请求体,包含 orderCode、orderType 等字段。
* @return {Promise<Object>} 取消结果,成功时返回成功消息,失败时返回错误信息。
*/
async cancel(data) {
const { ctx } = this;
const info = this.getInfo();
const orderType = this.orderType[data.request.orderType];
switch (orderType.method) {
case 'ORDER':
{
const orderCode = String(data?.request?.orderCode || '').trim();
if (!orderCode) {
return this.fail('订单号不能为空');
}
const DeliveryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(info.warehouseId);
const transaction = await ctx.model.transaction();
try {
const existingOrder = await DeliveryModel.findOne({
where: {
delivery_order_code: orderCode,
warehouse_id: info.warehouseId,
store_id: info.storeId,
},
transaction,
lock: transaction.LOCK.UPDATE,
});
if (!existingOrder) {
// current 表未命中时回退查询配送域表(dispatch):
// 订单已流转到配送表中且已取消,视为取消成功(幂等),直接返回
const DispatchModel = await ctx.model.OrderDeliveryFactory.getDispatchModel(info.warehouseId);
const dispatchOrder = await DispatchModel.findOne({
where: {
delivery_order_code: orderCode,
warehouse_id: info.warehouseId,
store_id: info.storeId,
},
transaction,
lock: transaction.LOCK.UPDATE,
});
if (dispatchOrder && String(dispatchOrder.status || '').trim() === 'cancel') {
await transaction.rollback();
return this.success('取消订单成功');
}
await transaction.rollback();
return this.fail('未找到对应的订单');
}
// 幂等处理:订单在配送表中且已取消,直接返回取消成功
const currentStatus = String(existingOrder.status || '').trim();
if (currentStatus === 'cancel') {
await transaction.rollback();
return this.success('取消订单成功');
}
const pickStatus = String(existingOrder.pick_status || 'none').trim();
const printStatus = String(existingOrder.print_status || 'none').trim();
if (pickStatus !== 'none' || printStatus !== 'none') {
// 拦截前置校验:团购单已复核 / 散单已称重后不允许写入拦截请求状态
const guardInfo = await resolveInterceptRequestGuardInfo(ctx, {
orderId: existingOrder.id,
waveId: existingOrder.wave_id,
warehouseId: info.warehouseId,
transaction,
});
const blockReason = getInterceptRequestBlockReason({
waveType: guardInfo.waveType,
inspectionStatus: String(existingOrder.inspection_status || '').trim(),
weighingWeight: guardInfo.weighingWeight,
});
if (!blockReason) {
// 通知拦截时间只在首次发起时写入(重复发起不覆盖已有值)
const noticeNow = new Date();
await existingOrder.update({
intercept_status: 'intercepting',
...buildNoticeTimePatch(existingOrder.intercept_time, noticeNow),
updated_at: noticeNow,
}, {
transaction,
});
// 同步更新运单表拦截标记
try {
await ctx.model.OrderExpress.update(
{ is_intercept: 'Y' },
{ where: { order_id: existingOrder.id, warehouse_id: info.warehouseId }, transaction }
);
} catch (expressErr) {
ctx.logger.warn(
`[qimen order cancel] 更新运单拦截标记失败, orderId=${existingOrder.id}, error=${expressErr.message}`
);
}
} else {
ctx.logger.info(
`[qimen order cancel] 订单${blockReason},跳过写入拦截请求状态, orderId=${existingOrder.id}`
);
}
await transaction.commit();
// 写入拦截操作日志(失败不影响主流程;未写入拦截请求状态时不记录)
if (!blockReason) {
try {
if (ctx.model && ctx.model.OperationLog) {
const customerId2 = String(info.customerId || '').trim();
await ctx.model.OperationLog.create({
business_type: 'order',
business_id: String(existingOrder.id),
operation_code: 'ORDER_INTERCEPT_REQUEST',
operator_id: null,
operator_name: customerId2 ? `qimen:${customerId2}` : 'qimen',
external_log_type: 'NONE',
warehouse_id: info.warehouseId || null,
platform_code: customerId2 || 'SYSTEM',
message: '奇门取消订单-触发拦截',
});
}
} catch (logErr) {
ctx.logger.warn('[QimenOrderCancel] 写入拦截操作日志失败,不影响主流程', logErr);
}
}
// 创建售后工单 + 通知快递群(仅限有运单的订单,与正常货主发起拦截一致;失败不影响主流程)
try {
const interceptExpress = await this.getInterceptExpressInfo(existingOrder.id, info.warehouseId);
if (Array.isArray(interceptExpress) && interceptExpress.length > 0) {
await ctx.service.systems.afterSale.createInterceptWorkOrdersAndNotify({
orderIds: [ existingOrder.id ],
warehouseId: info.warehouseId,
creatorLabel: ctx.user?.employees_name || '奇门系统',
});
}
} catch (workOrderErr) {
ctx.logger.warn(
`[qimen order cancel] 创建工单/通知失败, orderId=${existingOrder.id}, error=${workOrderErr.message}`
);
}
if (!blockReason) {
await this.sendCancelInterceptNotice({
orderCode,
existingOrder,
info,
});
}
return this.fail(blockReason
? `订单${blockReason},无法拦截执行,已转快递拦截`
: '取消失败,已通知拦截执行');
}
// 已同步订单不允许取消,转为拦截处理
const syncStatus = String(existingOrder.sync_status || '').trim();
if (syncStatus === 'fin') {
// 拦截前置校验:团购单已复核 / 散单已称重后不允许写入拦截请求状态
const syncGuardInfo = await resolveInterceptRequestGuardInfo(ctx, {
orderId: existingOrder.id,
waveId: existingOrder.wave_id,
warehouseId: info.warehouseId,
transaction,
});
const syncBlockReason = getInterceptRequestBlockReason({
waveType: syncGuardInfo.waveType,
inspectionStatus: String(existingOrder.inspection_status || '').trim(),
weighingWeight: syncGuardInfo.weighingWeight,
});
if (!syncBlockReason) {
// 通知拦截时间只在首次发起时写入(重复发起不覆盖已有值)
const noticeNow = new Date();
await existingOrder.update({
intercept_status: 'requested',
...buildNoticeTimePatch(existingOrder.intercept_time, noticeNow),
updated_at: noticeNow,
}, {
transaction,
});
// 同步更新运单表拦截标记
try {
await ctx.model.OrderExpress.update(
{ is_intercept: 'Y' },
{ where: { order_id: existingOrder.id, warehouse_id: info.warehouseId }, transaction }
);
} catch (expressErr) {
ctx.logger.warn(
`[qimen order cancel] 更新运单拦截标记失败(sync), orderId=${existingOrder.id}, error=${expressErr.message}`
);
}
} else {
ctx.logger.info(
`[qimen order cancel] 订单${syncBlockReason},跳过写入拦截请求状态(sync), orderId=${existingOrder.id}`
);
}
await transaction.commit();
// 写入拦截操作日志(失败不影响主流程;未写入拦截请求状态时不记录)
if (!syncBlockReason) {
try {
if (ctx.model && ctx.model.OperationLog) {
const customerId2 = String(info.customerId || '').trim();
await ctx.model.OperationLog.create({
business_type: 'order',
business_id: String(existingOrder.id),
operation_code: 'ORDER_INTERCEPT_REQUEST',
operator_id: null,
operator_name: customerId2 ? `qimen:${customerId2}` : 'qimen',
external_log_type: 'NONE',
warehouse_id: info.warehouseId || null,
platform_code: customerId2 || 'SYSTEM',
message: '奇门取消订单-触发拦截(已同步订单转拦截)',
});
}
} catch (logErr) {
ctx.logger.warn('[QimenOrderCancel] 写入拦截操作日志失败(sync),不影响主流程', logErr);
}
}
// 创建售后工单 + 通知快递群(仅限有运单的订单,与正常货主发起拦截一致;失败不影响主流程)
try {
const interceptExpress = await this.getInterceptExpressInfo(existingOrder.id, info.warehouseId);
if (Array.isArray(interceptExpress) && interceptExpress.length > 0) {
await ctx.service.systems.afterSale.createInterceptWorkOrdersAndNotify({
orderIds: [ existingOrder.id ],
warehouseId: info.warehouseId,
creatorLabel: ctx.user?.employees_name || '奇门系统',
});
}
} catch (workOrderErr) {
ctx.logger.warn(
`[qimen order cancel] 创建工单/通知失败(sync), orderId=${existingOrder.id}, error=${workOrderErr.message}`
);
}
if (!syncBlockReason) {
await this.sendCancelInterceptNotice({
orderCode,
existingOrder,
info,
});
}
return this.fail(syncBlockReason
? `订单${syncBlockReason},无法取消,已转快递拦截`
: '订单已同步,不可取消,已转为拦截处理');
}
// 检查是否在波次中,若在波次中需清除波次关联
const existingWaveId = Number(existingOrder.wave_id || 0);
const updateValues = {
status: 'cancel',
outbound_status: 'fin',
step: 4,
updated_at: new Date(),
};
if (existingWaveId > 0) {
updateValues.wave_id = 0;
updateValues.wave_no = '';
}
await existingOrder.update(updateValues, { transaction });
// 波次清理:删除波次索引、重建波次索引、更新波次统计
if (existingWaveId > 0) {
await ctx.service.systemMethods.order.wave.deleteOrderWaveIndexByOrderIds({
warehouseId: info.warehouseId,
orderIds: [ existingOrder.id ],
transaction,
});
// 重建受影响波次的订单索引(wave_index 重新排序)
await ctx.service.systemMethods.order.wave.replaceOrderWaveIndexByWaveIds({
warehouseId: info.warehouseId,
waveIds: [ existingWaveId ],
orderModel: DeliveryModel,
transaction,
});
const { Op } = this.app.Sequelize;
const WaveBatch = ctx.model.WaveBatch;
if (WaveBatch) {
await WaveBatch.decrement('total_orders', {
by: 1,
where: {
wave_id: existingWaveId,
warehouse_id: info.warehouseId,
total_orders: { [Op.gt]: 0 },
},
transaction,
});
const wave = await WaveBatch.findOne({
where: { wave_id: existingWaveId, warehouse_id: info.warehouseId },
attributes: [ 'wave_id', 'total_orders', 'wave_status' ],
raw: true,
transaction,
});
if (wave) {
const totalOrders = Number(wave.total_orders);
const normalizedTotalOrders = Number.isFinite(totalOrders) ? totalOrders : 0;
if (normalizedTotalOrders <= 0) {
await WaveBatch.update(
{ total_orders: 0, wave_status: -1, update_time: new Date() },
{ where: { wave_id: existingWaveId, warehouse_id: info.warehouseId }, transaction }
);
}
}
}
}
// 释放储位分配锁定库存(wms_storage / wms_stock_warehouse)
await this.releaseStorageLockForCancel({
orderId: existingOrder.id,
warehouseId: info.warehouseId,
transaction,
});
await transaction.commit();
// 波次策略扫描清理(不影响主流程)
if (existingWaveId > 0) {
try {
ctx.service.systemMethods.order.wave.enqueueWaveStrategyQuickScanPostOrderChange(
info.warehouseId,
[ existingOrder.id ],
{ triggerScan: true, source: 'qimenCancel' }
);
} catch (scanErr) {
ctx.logger.warn('[QimenOrderCancel] 波次策略扫描触发失败,不影响主流程', scanErr);
}
}
// 写入取消操作日志(不影响主流程)
try {
if (ctx.model && ctx.model.OperationLog) {
const customerId = String(info.customerId || '').trim();
await ctx.model.OperationLog.create({
business_type: 'order',
business_id: String(existingOrder.id),
operation_code: 'ORDER_CANCEL',
operator_id: null,
operator_name: customerId ? `qimen:${customerId}` : 'qimen',
external_log_type: 'NONE',
warehouse_id: info.warehouseId || null,
platform_code: customerId || 'SYSTEM',
message: '奇门取消订单',
});
}
} catch (logErr) {
ctx.logger.warn('[QimenOrderCancel] 写入取消操作日志失败,不影响主流程', logErr);
}
return this.success('取消订单成功');
} catch (error) {
try {
await transaction.rollback();
} catch (rollbackError) {
ctx.logger.error('取消订单回滚失败', rollbackError);
}
ctx.logger.error(`取消订单失败: ${error.message}`);
return this.fail(error.message || '取消订单失败');
}
}
case 'RK':
{
// RK 组入库单(B2BRK/SCRK/LYRK/CCRK/CGRK/DBRK/QTRK):委托共享入库单作废实现
// (守卫 sync_status/COMPLETED、回退收货单占用、写操作日志),
// 取消成功后不需要向奇门回传任何事件;已作废按幂等成功处理。
const orderCode = String(data?.request?.orderCode || '').trim();
if (!orderCode) {
return this.fail('入库单号不能为空');
}
const rkInfo = this.getInfo();
const result = await ctx.service.systems.storage.entry.cancel(
{ entryOrderCode: orderCode },
{
storeId: rkInfo.storeId,
warehouseId: rkInfo.warehouseId,
operatorLabel: String(rkInfo.customerId || '').trim()
? `qimen:${String(rkInfo.customerId).trim()}`
: 'qimen',
skipExternalSync: true,
idempotent: true,
notFoundMessage: '未找到对应的入库单',
}
);
if (result.code === 200) {
return this.success('取消入库单成功');
}
return this.fail(result.message || '取消入库单失败');
}
case 'CK':
{
// CK 组出库单(PTCK/DBCK/B2BCK/QTCK/CGTH):走独立出库单表 wms_order_stockout 取消,
// 共享实现 systems/stockout_order.js#cancel(事务 + 行锁,释放 QM_STOCKOUT 锁定)。
// 取消成功后不需要向奇门回传任何事件。
const orderCode = String(data?.request?.orderCode || '').trim();
if (!orderCode) {
return this.fail('出库单号不能为空');
}
const ckInfo = this.getInfo();
return ctx.service.systems.stockoutOrder.cancel(
{ stockoutOrderCode: orderCode },
{
storeId: ckInfo.storeId,
warehouseId: ckInfo.warehouseId,
operatorLabel: String(ckInfo.customerId || '').trim()
? `qimen:${String(ckInfo.customerId).trim()}`
: 'qimen',
}
);
}
case 'JG':
return this.fail('取消加工单未开发完成');
case 'BACKORDER':
return this.fail('取消退货单未开发完成');
default:
return this.fail(`未识别的作业类型${orderType.method}`, {});
}
}
/**
* 取消订单时释放储位分配锁定库存。
* - 有 wms_picking 记录时:释放 wms_storage.locked_quantity 与 wms_stock_warehouse.locked_quantity,
* 并删除对应的 wms_picking 分配记录。
* - 无 wms_picking 记录时:从 wms_order_items 查询该订单的 stock_id 与 plan_qty,
* 只释放 wms_stock_warehouse.locked_quantity。
*
* @param {Object} options - 释放参数。
* @param {number} options.orderId - 订单ID。
* @param {number} options.warehouseId - 仓库ID。
* @param {Object} options.transaction - 数据库事务对象。
* @return {Promise<void>}
*/
async releaseStorageLockForCancel({ orderId, warehouseId, transaction } = {}) {
const { ctx, app } = this;
const { Op } = app.Sequelize;
if (!orderId || !warehouseId) {
return;
}
const pickingModel = ctx.model.Picking;
const storageModel = ctx.model.Storage;
const stockModel = ctx.model.StockWarehouse;
if (!pickingModel || !storageModel || !stockModel) {
ctx.logger.warn('[qimen order.cancel releaseStorageLockForCancel] 模型不可用,跳过库存释放');
return;
}
// 查找该订单的有效分配记录
const pickingRows = await pickingModel.findAll({
where: {
order_id: orderId,
status: { [Op.ne]: 'cancel' },
},
transaction,
lock: transaction.LOCK.UPDATE,
raw: true,
});
if (!Array.isArray(pickingRows) || pickingRows.length === 0) {
// 无储位分配记录:从订单明细获取锁定信息,只释放 stock_warehouse 锁
const orderItemsModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId);
if (!orderItemsModel) {
ctx.logger.warn('[qimen order.cancel releaseStorageLockForCancel] OrderItems 模型不可用,跳过库存释放');
return;
}
const orderItems = await orderItemsModel.findAll({
where: { order_id: orderId },
attributes: [ 'stock_id', 'plan_qty' ],
raw: true,
transaction,
});
for (const item of orderItems) {
const stockId = Number(item.stock_id || 0);
const qty = Number(item.plan_qty || 0);
if (stockId <= 0 || qty <= 0) continue;
await ctx.service.systems.stockStore.updateLockedQuantity(stockId, -qty, transaction, {
remark: '奇门取消订单-释放创建锁',
orderType: 'ORDER_CANCEL',
orderNo: String(orderId),
orderId,
});
}
return;
}
// 按 storage_id 汇总释放数量
const storageQuantityMap = new Map();
for (const row of pickingRows) {
const storageId = Number(row.storage_id || 0);
const quantity = Number(row.quantity || 0);
if (storageId > 0 && quantity > 0) {
storageQuantityMap.set(storageId, (storageQuantityMap.get(storageId) || 0) + quantity);
}
}
if (storageQuantityMap.size === 0) {
return;
}
// 查出关联的 wms_storage 记录,获取 stock_id
const storageIds = Array.from(storageQuantityMap.keys());
const storageRows = await storageModel.findAll({
where: {
id: { [Op.in]: storageIds },
},
transaction,
lock: transaction.LOCK.UPDATE,
raw: true,
});
const storageMap = new Map();
for (const row of storageRows) {
storageMap.set(Number(row.id), row);
}
// 依次释放 wms_storage 与 wms_stock_warehouse 锁定数量
for (const [ storageId, quantity ] of storageQuantityMap.entries()) {
const storageRow = storageMap.get(storageId);
if (!storageRow) {
ctx.logger.warn(`[qimen order.cancel] 库存记录不存在,跳过: storageId=${storageId}`);
continue;
}
const stockId = Number(storageRow.stock_id || 0);
if (stockId <= 0) {
ctx.logger.warn(`[qimen order.cancel] 库存记录缺少 stock_id,跳过: storageId=${storageId}`);
continue;
}
// 释放 wms_storage.locked_quantity
await ctx.service.systems.storage.index.unlockQuantity(storageId, quantity, { transaction });
// 释放 wms_stock_warehouse.locked_quantity
const releaseResult = await ctx.service.systems.stockStore.updateLockedQuantity(
stockId, -Number(quantity), transaction, {
remark: '奇门取消订单-释放储位锁',
orderType: 'ORDER_CANCEL',
orderNo: String(orderId),
orderId,
}
);
if (!releaseResult.success) {
throw new Error(`库存主记录释放失败: stockId=${stockId}, ${releaseResult.error}`);
}
}
// 删除已释放的分配记录
const pickingIds = pickingRows
.map(row => Number(row.id || 0))
.filter(id => id > 0);
if (pickingIds.length > 0) {
await pickingModel.destroy({
where: {
id: { [Op.in]: pickingIds },
},
transaction,
});
}
}
async pending(data) {
const orderType = this.orderType[data.request.orderType];
switch (orderType.method) {
case 'ORDER':
return this.fail('锁定订单未开发完成');
case 'RK':
return this.fail('锁定入库单未开发完成');
case 'CK':
return this.fail('锁定出库单未开发完成');
case 'JG':
return this.fail('锁定加工单未开发完成');
case 'BACKORDER':
return this.fail('锁定退货单未开发完成');
default:
return this.fail(`未识别的作业类型${orderType.method}`, {});
}
}
}
module.exports = orderServer;