- 奇门 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)共享服务与文档,文件粒度无法拆分,一并纳入本次提交。
480 lines
18 KiB
JavaScript
480 lines
18 KiB
JavaScript
'use strict';
|
||
|
||
const MainService = require('../main');
|
||
|
||
const { getInterceptRequestBlockReason, resolveInterceptRequestGuardInfo } = require('../../lib/intercept_guard');
|
||
const { buildNoticeTimePatch } = require('../../lib/intercept_time');
|
||
|
||
class OpenapiOrderService extends MainService {
|
||
/**
|
||
* 取消发货单。
|
||
* 上下文(storeId/warehouseId/appKey)已由 dispatchOpenapiMethod 统一注入。
|
||
* 支持类型:
|
||
* - 出库单类型(JYCK/HHCK/BFCK → ORDER):操作 wms_order_delivery 主表,
|
||
* 触发拦截时同步写入订单拦截时间 intercept_time(当前时间);
|
||
* - CK 组出库单(PTCK/DBCK/B2BCK/QTCK/CGTH):走独立出库单表 wms_order_stockout 取消,
|
||
* 取消成功后不需要向开放平台回传任何事件;
|
||
* - RK 组入库单(B2BRK/SCRK/LYRK/CCRK/CGRK/DBRK/QTRK):走入库单作废流程(状态守卫、
|
||
* 回退收货单占用),取消成功后不需要向开放平台回传任何事件。
|
||
* 其余类型返回不支持。
|
||
* @param {Object} payload 调用参数。
|
||
* @param {Object} payload.body 请求体数据,包含 orderCode、orderType。
|
||
* @param {Object} payload.query 请求 query 数据。
|
||
* @return {Promise<Object>} 取消结果,成功时返回成功消息,失败时返回错误信息。
|
||
*/
|
||
async cancel(payload = {}) {
|
||
const { ctx } = this;
|
||
const { body = {}, query = {} } = payload;
|
||
const { orderCode } = body;
|
||
const orderType = String(body.orderType || 'JYCK').trim().toUpperCase();
|
||
|
||
// 出库单类型映射:JYCK / HHCK / BFCK → ORDER(wms_order_delivery 取消流程)
|
||
const ORDER_TYPES = [ 'JYCK', 'HHCK', 'BFCK' ];
|
||
// CK 组出库单:走独立出库单表 wms_order_stockout 取消流程
|
||
const CK_TYPES = [ 'PTCK', 'DBCK', 'B2BCK', 'QTCK', 'CGTH' ];
|
||
// RK 组入库单:走入库单作废流程(与奇门 orderType 枚举 method=RK 完全一致)
|
||
const RK_TYPES = [ 'B2BRK', 'SCRK', 'LYRK', 'CCRK', 'CGRK', 'DBRK', 'QTRK' ];
|
||
if (!ORDER_TYPES.includes(orderType) && !CK_TYPES.includes(orderType) && !RK_TYPES.includes(orderType)) {
|
||
return this.fail('暂不支持该订单类型的取消操作');
|
||
}
|
||
|
||
const normalizedOrderCode = String(orderCode || '').trim();
|
||
if (!normalizedOrderCode) {
|
||
return this.fail('orderCode 参数缺失');
|
||
}
|
||
|
||
// CK 组:委托共享出库单取消实现,取消成功后不回传任何开放平台事件
|
||
if (CK_TYPES.includes(orderType)) {
|
||
const info = this.getInfo();
|
||
return ctx.service.systems.stockoutOrder.cancel(
|
||
{ stockoutOrderCode: normalizedOrderCode },
|
||
{
|
||
storeId: info.storeId,
|
||
warehouseId: info.warehouseId,
|
||
operatorLabel: String(info.appKey || '').trim()
|
||
? `openapi:${String(info.appKey).trim()}`
|
||
: 'openapi',
|
||
}
|
||
);
|
||
}
|
||
|
||
// RK 组:委托共享入库单作废实现(守卫 + 回退收货单占用 + 操作日志),
|
||
// 取消成功后不回传任何开放平台事件;已作废按幂等成功处理
|
||
if (RK_TYPES.includes(orderType)) {
|
||
const info = this.getInfo();
|
||
const result = await ctx.service.systems.storage.entry.cancel(
|
||
{ entryOrderCode: normalizedOrderCode },
|
||
{
|
||
storeId: info.storeId,
|
||
warehouseId: info.warehouseId,
|
||
operatorLabel: String(info.appKey || '').trim()
|
||
? `openapi:${String(info.appKey).trim()}`
|
||
: 'openapi',
|
||
skipExternalSync: true,
|
||
idempotent: true,
|
||
notFoundMessage: '未找到对应的入库单',
|
||
}
|
||
);
|
||
|
||
if (result.code === 200) {
|
||
return this.success('取消入库单成功');
|
||
}
|
||
return this.fail(result.message || '取消入库单失败');
|
||
}
|
||
|
||
try {
|
||
const { storeId, warehouseId, appKey: ctxAppKey } = this.getInfo();
|
||
|
||
const DeliveryModel = await ctx.model.OrderDeliveryFactory.getCurrentModel(warehouseId);
|
||
const transaction = await ctx.model.transaction();
|
||
try {
|
||
const existingOrder = await DeliveryModel.findOne({
|
||
where: {
|
||
delivery_order_code: normalizedOrderCode,
|
||
warehouse_id: warehouseId,
|
||
store_id: storeId,
|
||
},
|
||
transaction,
|
||
lock: transaction.LOCK.UPDATE,
|
||
});
|
||
|
||
if (!existingOrder) {
|
||
await transaction.rollback();
|
||
return this.fail('未找到对应的订单');
|
||
}
|
||
|
||
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,
|
||
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 {
|
||
const { ctx: ctxExpress } = this;
|
||
const expressWarehouseId = ctxExpress.user && ctxExpress.user.store_id ? Number(ctxExpress.user.store_id) : 0;
|
||
if (expressWarehouseId > 0) {
|
||
await ctxExpress.model.OrderExpress.update(
|
||
{ is_intercept: 'Y' },
|
||
{ where: { order_id: existingOrder.id, warehouse_id: expressWarehouseId }, transaction }
|
||
);
|
||
}
|
||
} catch (expressErr) {
|
||
this.ctx.logger.warn(
|
||
`[openapi order cancel] 更新运单拦截标记失败, orderId=${existingOrder.id}, error=${expressErr.message}`
|
||
);
|
||
}
|
||
} else {
|
||
this.ctx.logger.info(
|
||
`[openapi order cancel] 订单${blockReason},跳过写入拦截请求状态, orderId=${existingOrder.id}`
|
||
);
|
||
}
|
||
|
||
await transaction.commit();
|
||
|
||
// 写入拦截操作日志(失败不影响主流程;未写入拦截请求状态时不记录)
|
||
if (!blockReason) {
|
||
try {
|
||
const { ctx: ctx2 } = this;
|
||
if (ctx2.model && ctx2.model.OperationLog) {
|
||
const whId2 = ctx2.user && ctx2.user.store_id ? Number(ctx2.user.store_id) : 0;
|
||
await ctx2.model.OperationLog.create({
|
||
business_type: 'order',
|
||
business_id: String(existingOrder.id),
|
||
operation_code: 'ORDER_INTERCEPT_REQUEST',
|
||
operator_id: ctx2.user?.employees_id || ctx2.user?.id || null,
|
||
operator_name: ctx2.user?.employees_name || 'OpenAPI',
|
||
external_log_type: 'NONE',
|
||
warehouse_id: whId2 || null,
|
||
platform_code: 'OPENAPI',
|
||
message: 'OpenAPI取消订单-触发拦截',
|
||
});
|
||
}
|
||
} catch (logErr) {
|
||
this.ctx.logger.warn('[OpenAPIOrderCancel] 写入拦截操作日志失败,不影响主流程', logErr);
|
||
}
|
||
}
|
||
|
||
// 创建售后工单 + 通知快递群(失败不影响主流程)
|
||
try {
|
||
const { ctx: ctxWorkOrder } = this;
|
||
const whId = ctxWorkOrder.user && ctxWorkOrder.user.store_id ? Number(ctxWorkOrder.user.store_id) : 0;
|
||
if (whId > 0) {
|
||
await ctxWorkOrder.service.systems.afterSale.createInterceptWorkOrdersAndNotify({
|
||
orderIds: [ existingOrder.id ],
|
||
warehouseId: whId,
|
||
creatorLabel: ctxWorkOrder.user?.employees_name || 'OpenAPI系统',
|
||
});
|
||
}
|
||
} catch (workOrderErr) {
|
||
this.ctx.logger.warn(
|
||
`[openapi order cancel] 创建工单/通知失败, orderId=${existingOrder.id}, error=${workOrderErr.message}`
|
||
);
|
||
}
|
||
|
||
return this.fail(blockReason
|
||
? `订单${blockReason},无法拦截执行,已转快递拦截`
|
||
: '取消失败,已通知拦截执行');
|
||
}
|
||
|
||
// 检查是否在波次中,若在波次中需清除波次关联
|
||
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,
|
||
orderIds: [ existingOrder.id ],
|
||
transaction,
|
||
});
|
||
|
||
await ctx.service.systemMethods.order.wave.replaceOrderWaveIndexByWaveIds({
|
||
warehouseId,
|
||
waveIds: [ existingWaveId ],
|
||
orderModel: DeliveryModel,
|
||
transaction,
|
||
});
|
||
|
||
const WaveBatch = ctx.model.WaveBatch;
|
||
if (WaveBatch) {
|
||
const wave = await WaveBatch.findOne({
|
||
where: { wave_id: existingWaveId, warehouse_id: 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: warehouseId }, transaction }
|
||
);
|
||
}
|
||
}
|
||
}
|
||
}
|
||
|
||
// 释放储位分配锁定库存
|
||
await this.releaseStockLockForCancel({
|
||
orderId: existingOrder.id,
|
||
warehouseId,
|
||
transaction,
|
||
});
|
||
|
||
await transaction.commit();
|
||
|
||
// 写入取消操作日志(不影响主流程)
|
||
try {
|
||
if (this.ctx.model && this.ctx.model.OperationLog) {
|
||
const appKey = String(query.app_key || ctxAppKey || '').trim();
|
||
await this.ctx.model.OperationLog.create({
|
||
business_type: 'order',
|
||
business_id: String(existingOrder.id),
|
||
operation_code: 'ORDER_CANCEL',
|
||
operator_id: null,
|
||
operator_name: appKey ? `openapi:${appKey}` : 'openapi',
|
||
external_log_type: 'NONE',
|
||
warehouse_id: warehouseId || null,
|
||
platform_code: appKey || 'SYSTEM',
|
||
message: 'OpenAPI 取消订单',
|
||
});
|
||
}
|
||
} catch (logErr) {
|
||
this.ctx.logger.warn('[OpenapiOrderCancel] 写入取消操作日志失败,不影响主流程', logErr);
|
||
}
|
||
|
||
// 取消成功后触发 OpenAPI 回调通知(fire-and-forget,不阻塞主流程)
|
||
try {
|
||
const callbackService = this.ctx.service.openapi && this.ctx.service.openapi.callback;
|
||
if (callbackService && typeof callbackService.sendByAppKey === 'function') {
|
||
const appKey = String(query.app_key || ctxAppKey || '').trim();
|
||
if (appKey) {
|
||
// 出站回调事件名 deliveryorder.cancel:与入站方法 order.cancel 区分,
|
||
// 避免 callback_url 误指向 /openapi 时被路由到取消单据接口
|
||
// 报文对齐奇门 request 层级:deliveryOrder 节点约定(无奇门对应接口,
|
||
// status 使用 CANCELED 与奇门 deliveryOrder.status 家族枚举风格一致)
|
||
callbackService.sendByAppKey({
|
||
appKey,
|
||
event: 'deliveryorder.cancel',
|
||
request: {
|
||
deliveryOrder: {
|
||
deliveryOrderCode: normalizedOrderCode,
|
||
orderType,
|
||
status: 'CANCELED',
|
||
},
|
||
},
|
||
}).catch(err => {
|
||
this.ctx.logger.warn('[OpenapiOrderCancel] 回调忽略失败: %s', err.message);
|
||
});
|
||
}
|
||
}
|
||
} catch (err) {
|
||
this.ctx.logger.warn('[OpenapiOrderCancel] 触发回调异常,不影响主流程: %s', err.message);
|
||
}
|
||
|
||
return this.success('取消订单成功');
|
||
} catch (error) {
|
||
try {
|
||
await transaction.rollback();
|
||
} catch (rollbackError) {
|
||
ctx.logger.error(`取消订单回滚失败: ${rollbackError.message}`);
|
||
}
|
||
ctx.logger.error(`取消订单失败: ${error.message}`);
|
||
return this.fail(error.message || '取消订单失败');
|
||
}
|
||
} catch (error) {
|
||
return this.fail(`取消订单失败: ${error.message}`);
|
||
}
|
||
}
|
||
|
||
/**
|
||
* 取消订单时释放储位分配锁定库存。
|
||
* - 有 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 releaseStockLockForCancel({ 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('[openapi order.cancel releaseStockLockForCancel] 模型不可用,跳过库存释放');
|
||
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('[openapi order.cancel releaseStockLockForCancel] 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: 'OpenAPI取消订单-释放创建锁',
|
||
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(`[openapi order.cancel] 库存记录不存在,跳过: storageId=${storageId}`);
|
||
continue;
|
||
}
|
||
|
||
const stockId = Number(storageRow.stock_id || 0);
|
||
if (stockId <= 0) {
|
||
ctx.logger.warn(`[openapi 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: 'OpenAPI取消订单-释放储位锁',
|
||
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,
|
||
});
|
||
}
|
||
}
|
||
}
|
||
|
||
module.exports = OpenapiOrderService;
|