From e19b5fc18ca403631433b637021eb07f89bab413 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sun, 13 Sep 2026 02:24:18 +0800 Subject: [PATCH] =?UTF-8?q?feat(order):=20=E5=8F=96=E6=B6=88=E5=8D=95?= =?UTF-8?q?=E6=8D=AE=E6=94=AF=E6=8C=81=20CK=20=E5=87=BA=E5=BA=93=E5=8D=95?= =?UTF-8?q?=E4=B8=8E=20RK=20=E5=85=A5=E5=BA=93=E5=8D=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 奇门 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)共享服务与文档,文件粒度无法拆分,一并纳入本次提交。 --- app/service/openapiMethods/order.js | 72 +- app/service/qimenMethods/order.js | 70 +- app/service/systemMethods/storage/stockout.js | 127 +-- app/service/systems/stockout_order.js | 557 +++++++++++++ app/service/systems/storage/entry.js | 300 +++++-- methods/changes/openapi.json | 71 ++ methods/changes/qimen.json | 59 ++ methods/changes/system.json | 113 +++ methods/openapi.json | 377 ++++++++- methods/qimen.json | 160 +++- methods/system.json | 136 +++- test/app/service/entry_order.cancel.test.js | 759 ++++++++++++++++++ .../app/service/stockout_order.cancel.test.js | 632 +++++++++++++++ 13 files changed, 3195 insertions(+), 238 deletions(-) create mode 100644 app/service/systems/stockout_order.js create mode 100644 test/app/service/entry_order.cancel.test.js create mode 100644 test/app/service/stockout_order.cancel.test.js diff --git a/app/service/openapiMethods/order.js b/app/service/openapiMethods/order.js index 6c28056..4999568 100644 --- a/app/service/openapiMethods/order.js +++ b/app/service/openapiMethods/order.js @@ -9,8 +9,14 @@ class OpenapiOrderService extends MainService { /** * 取消发货单。 * 上下文(storeId/warehouseId/appKey)已由 dispatchOpenapiMethod 统一注入。 - * 当前仅支持出库单类型(JYCK/HHCK/BFCK → ORDER),非出库单类型返回不支持。 - * 触发拦截时同步写入订单拦截时间 intercept_time(当前时间)。 + * 支持类型: + * - 出库单类型(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 数据。 @@ -22,9 +28,13 @@ class OpenapiOrderService extends MainService { const { orderCode } = body; const orderType = String(body.orderType || 'JYCK').trim().toUpperCase(); - // 出库单类型映射:JYCK / HHCK / BFCK → ORDER + // 出库单类型映射:JYCK / HHCK / BFCK → ORDER(wms_order_delivery 取消流程) const ORDER_TYPES = [ 'JYCK', 'HHCK', 'BFCK' ]; - if (!ORDER_TYPES.includes(orderType)) { + // 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('暂不支持该订单类型的取消操作'); } @@ -33,6 +43,45 @@ class OpenapiOrderService extends MainService { 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(); @@ -240,12 +289,19 @@ class OpenapiOrderService extends MainService { 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: 'order_cancelled', - data: { - orderCode, - status: 'cancelled', + event: 'deliveryorder.cancel', + request: { + deliveryOrder: { + deliveryOrderCode: normalizedOrderCode, + orderType, + status: 'CANCELED', + }, }, }).catch(err => { this.ctx.logger.warn('[OpenapiOrderCancel] 回调忽略失败: %s', err.message); diff --git a/app/service/qimenMethods/order.js b/app/service/qimenMethods/order.js index cb03402..03fd241 100644 --- a/app/service/qimenMethods/order.js +++ b/app/service/qimenMethods/order.js @@ -176,8 +176,14 @@ class orderServer extends MainService { /** * 取消奇门订单。 - * 订单未同步且未开始拣货/打印时直接取消;已同步或已开始拣货/打印时转入拦截处理: - * 写入订单拦截状态 intercept_status(intercepting/requested)并同步写入拦截时间 intercept_time。 + * 按 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} 取消结果,成功时返回成功消息,失败时返回错误信息。 @@ -550,24 +556,56 @@ class orderServer extends MainService { } case 'RK': { - const existingOrder = await ctx.model.EntryOrder.findOne({ - where: { - entry_order_code: data.request.orderCode, - warehouse_id: info.warehouseId, - store_id: info.storeId, - }, - }); - if (existingOrder) { - await existingOrder.update({ - order_status: 'CANCELLED', - updated_at: new Date(), - }); + // 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('未找到对应的入库单'); + return this.fail(result.message || '取消入库单失败'); } case 'CK': - return this.fail('取消出库单未开发完成'); + { + // 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': diff --git a/app/service/systemMethods/storage/stockout.js b/app/service/systemMethods/storage/stockout.js index 8b65ce7..bb18ef5 100644 --- a/app/service/systemMethods/storage/stockout.js +++ b/app/service/systemMethods/storage/stockout.js @@ -390,6 +390,11 @@ class StorageStockoutService extends MainService { /** * 写 wms_operation_log 操作日志(businessType=stockout),失败仅告警不影响主流程。 + * + * 委托到共享实现 `systems/stockout_order.js#_writeStockoutOperationLog`, + * 保持本入口的历史口径:操作人取自 ctx.user,仓库取自 ctx.user.store_id(缺失时 + * 回退出库单自身 warehouse_id)。 + * * @param {Object} order 出库单实例或行 * @param {string} operationCode 操作编码 * @param {string} message 日志内容 @@ -398,32 +403,20 @@ class StorageStockoutService extends MainService { */ async _writeStockoutOperationLog(order, operationCode, message, options = {}) { const { ctx } = this; - const opLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog; - if (!opLogService || typeof opLogService.createOperationLogs !== 'function') { - ctx.logger.warn('[stockout] 操作日志服务不可用,跳过记录'); + const stockoutOrderService = ctx.service && ctx.service.systems && ctx.service.systems.stockoutOrder; + if (!stockoutOrderService || typeof stockoutOrderService._writeStockoutOperationLog !== 'function') { + ctx.logger.warn('[stockout] 出库单领域服务不可用,跳过记录'); return; } const user = ctx.user || {}; - try { - await opLogService.createOperationLogs([ - { - businessType: 'stockout', - businessId: order.id, - operationCode, - operator: { - id: user.employees_id ?? user.id ?? null, - name: String(user.employees_name || user.real_name || user.name || 'system'), - }, - extras: { - warehouseId: Number(ctx.user && ctx.user.store_id) || order.warehouse_id || null, - message, - externalLogType: 'NONE', - }, - }, - ], { transaction: options.transaction }); - } catch (err) { - ctx.logger.warn(`[stockout] 写操作日志失败: ${err.message}`); - } + await stockoutOrderService._writeStockoutOperationLog(order, operationCode, message, { + transaction: options.transaction, + warehouseId: Number(ctx.user && ctx.user.store_id) || order.warehouse_id || null, + operator: { + id: user.employees_id ?? user.id ?? null, + name: String(user.employees_name || user.real_name || user.name || 'system'), + }, + }); } /** @@ -768,9 +761,9 @@ class StorageStockoutService extends MainService { /** * 出库单取消。 * - * 仅 CREATED / PENDING 状态允许取消;事务内释放创建时占用的库存锁定(QM_STOCKOUT, - * 写 UNLOCK 流水),状态置为 CANCELLED,并写 wms_operation_log 操作日志。 - * 已转订单(TRANSFERRED)与已完成(COMPLETED)状态禁止取消。 + * 委托到共享实现 `systems/stockout_order.js#cancel`(奇门 / openapi 同口径: + * 事务 + 行锁,释放 QM_STOCKOUT 库存锁定,状态置 CANCELLED 并写操作日志), + * 本入口负责入参校验与对外契约映射。 * * @param {Object} data 请求体 * @param {number} data.id 出库单ID(必填) @@ -789,77 +782,33 @@ class StorageStockoutService extends MainService { return this.fail('缺少仓库上下文'); } - const order = await ctx.model.OrderStockout.findOne({ - where: { id, warehouse_id: warehouseId, deleted_at: null }, - }); - if (!order) { - return this.fail('出库单不存在'); + const stockoutOrderService = ctx.service && ctx.service.systems && ctx.service.systems.stockoutOrder; + if (!stockoutOrderService || typeof stockoutOrderService.cancel !== 'function') { + return this.fail('出库单取消服务不可用'); } - if (!order.canCancel || !order.canCancel()) { - return this.fail(`出库单当前状态(${order.order_status})不允许取消`); - } - - const items = await ctx.model.OrderStockoutItems.findAll({ - where: { order_id: order.id }, - raw: true, - }); - - // 释放创建时占用的库存锁定 + 状态置 CANCELLED + 操作日志,同一事务 - const cancelTransaction = await ctx.model.transaction(); - try { - let releasedQty = 0; - for (const item of items) { - const qty = Number(item.plan_qty) || 0; - if (qty <= 0) continue; - const releaseResult = await ctx.service.systems.stockStore.lockItemStorages( - item.stock_id, - -qty, - cancelTransaction, - null, - { - orderType: 'QM_STOCKOUT', - orderNo: order.stockout_order_code, - orderId: order.id, - remark: '出库单取消释放锁定', - } - ); - if (!releaseResult.success) { - // 已释放过(锁定不足)视为幂等成功,避免阻断 - const alreadyReleased = String(releaseResult.error || '').includes('释放数量超过已锁定库存'); - if (alreadyReleased) { - ctx.logger.warn(`[stockout.cancel] 库存${item.stock_id}锁定已释放,跳过: ${releaseResult.error}`); - continue; - } - throw new Error(`库存${item.stock_id}释放锁定失败: ${releaseResult.error}`); - } - releasedQty += qty; + const result = await stockoutOrderService.cancel( + { id }, + { + storeId: null, + warehouseId, + operatorLabel: String( + (ctx.user && (ctx.user.employees_name || ctx.user.real_name || ctx.user.name)) || 'system' + ), } + ); - await ctx.model.OrderStockout.update( - { order_status: 'CANCELLED', sync_message: '已取消', updated_at: new Date() }, - { where: { id: order.id }, transaction: cancelTransaction } + if (result.flag !== 'success') { + // 契约文案映射:共享层「未找到对应的出库单」→ 本入口「出库单不存在」,其余文案原样透出 + return this.fail( + result.message === '未找到对应的出库单' ? '出库单不存在' : result.message ); - - await this._writeStockoutOperationLog( - order, - 'STOCKOUT_CANCEL', - `出库单已取消,释放锁定库存 ${releasedQty}`, - { transaction: cancelTransaction } - ); - - await cancelTransaction.commit(); - } catch (err) { - await cancelTransaction.rollback().catch(() => {}); - ctx.logger.error(`[stockout.cancel] 取消失败: ${order.stockout_order_code} - ${err.message}`); - return this.fail(`取消失败:${err.message}`); } - ctx.logger.info(`[stockout.cancel] 取消完成: ${order.stockout_order_code}`); return this.success('取消成功', { - id: order.id, - stockout_order_code: order.stockout_order_code, - order_status: 'CANCELLED', + id: result.id, + stockout_order_code: result.stockout_order_code, + order_status: result.order_status, }); } diff --git a/app/service/systems/stockout_order.js b/app/service/systems/stockout_order.js new file mode 100644 index 0000000..9f349da --- /dev/null +++ b/app/service/systems/stockout_order.js @@ -0,0 +1,557 @@ +'use strict'; + +const MainService = require('../main'); + +/** + * 非订单出库单(stockout)领域服务。 + * + * 抽离原 `qimenMethods/stockout.js` 的核心实现,供奇门(stockout.create/query) + * 与开放 API(openapi stockout.create/query)薄适配层共用: + * - 落库 `wms_order_stockout` 主表 + `wms_order_stockout_items` 明细表; + * - 创建时按明细计划数量锁定库存(库存锁标记 `QM_STOCKOUT`,与取消/确认/转单释放口径一致)。 + * + * 入参沿用奇门报文结构 `data.request.deliveryOrder` / `data.request.orderLines`, + * 上下文(storeId/warehouseId/warehouseCode/appKey/sourceType)由调用方通过 + * `options` 显式传入,避免领域服务实例依赖 setInfo 状态。 + */ +class StockoutOrderService extends MainService { + + /** + * 解析出库单快递编码(独立于订单兜底链)。 + * + * 口径: + * 1. 货主开启 enable_external_express_code 且传了 logisticsCode 时,按 + * wms_express_setting 映射 → 系统快递列表匹配; + * 2. 未传 / 未开启 / 匹配不到 → 使用出库单兜底快递编码 + * (stockout_default_express_code,默认 ZT 自提),不回退订单默认快递; + * 不走订单的快递策略漏斗(matchPolicy)。 + * 解析失败仅告警不阻断建单(快递为空,可在确认前手工补填)。 + * + * @param {Object} deliveryOrder 出库单头信息(奇门 deliveryOrder 节点)。 + * @param {Object} context 上下文,需包含 storeId / warehouseId。 + * @return {Promise<{ expressCode: string|null, expressName: string|null }>} 解析结果。 + */ + async resolveStockoutExpress(deliveryOrder = {}, context = {}) { + const { ctx } = this; + const { storeId, warehouseId } = context; + + let expressCode = null; + let expressName = null; + + try { + const deliveryOrderService = ctx.service.systems.deliveryOrder; + const policyConfig = await deliveryOrderService.getStoreWarehousePolicyConfig(storeId, warehouseId); + const expressList = await ctx.service.systems.express.getExpressList(); + const findExpress = code => { + const upperCode = String(code || '').trim().toUpperCase(); + if (!upperCode || !Array.isArray(expressList)) { + return null; + } + return expressList.find(item => item + && String(item.code || item.value || '').trim().toUpperCase() === upperCode) || null; + }; + const externalCode = String(deliveryOrder.logisticsCode || '').trim(); + const enableExternal = deliveryOrderService.normalizePolicyFlag( + policyConfig && policyConfig.enable_external_express_code + ); + + if (enableExternal && externalCode) { + // 1) wms_express_setting 外部编码映射 → 系统快递编码 + const settingSnapshot = await deliveryOrderService.resolveExpressSettingSnapshot(externalCode, warehouseId); + if (settingSnapshot && settingSnapshot.expressCode) { + const sysCode = String(settingSnapshot.expressCode).trim(); + const sysItem = findExpress(sysCode); + expressCode = sysCode; + expressName = sysItem + ? String(sysItem.name || sysItem.label || sysCode).trim() + : String(settingSnapshot.name || sysCode).trim(); + } else { + // 2) 系统快递列表直接匹配 + const matched = findExpress(externalCode); + if (matched) { + expressCode = String(matched.code || matched.value || externalCode).trim(); + expressName = String(matched.name || matched.label || expressCode).trim(); + } + } + } + + if (!expressCode) { + // 兜底:出库单兜底快递编码(货主配置,默认 ZT 自提),不回退订单默认快递 + const fallbackCode = String(policyConfig && policyConfig.stockout_default_express_code || '').trim() || 'ZT'; + const fallbackItem = findExpress(fallbackCode); + expressCode = fallbackItem + ? String(fallbackItem.code || fallbackItem.value || fallbackCode).trim() + : fallbackCode; + expressName = fallbackItem + ? String(fallbackItem.name || fallbackItem.label || fallbackCode).trim() + : fallbackCode; + } + } catch (err) { + ctx.logger.warn(`[stockout.create] 快递编码解析失败,保持为空: ${err.message}`); + } + + return { expressCode, expressName }; + } + + /** + * 创建出库单。 + * + * 将请求的 deliveryOrder / orderLines 写入 `wms_order_stockout` 主表和 + * `wms_order_stockout_items` 明细表,并库存锁定,整个过程在一个数据库事务内完成, + * 失败自动回滚。 + * + * @param {Object} data 请求体,遵循奇门报文结构。 + * @param {Object} data.request 请求数据。 + * @param {Object} data.request.deliveryOrder 出库单头信息。 + * @param {Object} data.request.orderLines 出库单明细。 + * @param {Object|Object[]} data.request.orderLines.orderLine 明细行(单条为对象,多条为数组)。 + * @param {Object} options 上下文与来源。 + * @param {number} options.storeId 货主ID。 + * @param {number} options.warehouseId 仓库ID。 + * @param {string} [options.warehouseCode] 仓库编码。 + * @param {string} [options.appKey] 开放接口 app_key(用于 StockStore 降级匹配)。 + * @param {string} [options.sourceType='QM'] 来源类型(QM / API / WMS)。 + * @return {Promise} 返回 success / fail 结果。 + */ + async create(data, options = {}) { + const { app, ctx } = this; + const { storeId, warehouseId, warehouseCode, appKey } = options; + const sourceType = options.sourceType || 'QM'; + const { deliveryOrder, orderLines } = data.request; + + // 单条 orderLine 转为数组 + let orderLine = orderLines && orderLines.orderLine; + if (orderLine && orderLine.orderLineNo) { + orderLine = [ orderLine ]; + } + + if (!orderLine || !Array.isArray(orderLine) || orderLine.length === 0) { + return this.fail('创建出库单失败,失败原因:\n没有有效的订单明细数据'); + } + + const totalOrderLines = deliveryOrder.totalOrderLines || orderLine.length; + + // 快递编码解析 + const { expressCode, expressName } = await this.resolveStockoutExpress(deliveryOrder, { + storeId, + warehouseId, + }); + + // 收件人信息解析(receiverInfo 13 个标准字段落库,供转订单与确认回传使用) + const receiver = deliveryOrder.receiverInfo && typeof deliveryOrder.receiverInfo === 'object' + ? deliveryOrder.receiverInfo + : {}; + const receiverFields = { + receiver_company: receiver.company, + receiver_name: receiver.name, + receiver_zip_code: receiver.zipCode, + receiver_tel: receiver.tel, + receiver_mobile: receiver.mobile, + receiver_email: receiver.email, + receiver_country_code: receiver.countryCode, + receiver_province: receiver.province, + receiver_city: receiver.city, + receiver_area: receiver.area, + receiver_town: receiver.town, + receiver_detail_address: receiver.detailAddress, + receiver_id: receiver.id, + }; + for (const key of Object.keys(receiverFields)) { + const rawValue = receiverFields[key]; + receiverFields[key] = rawValue === undefined || rawValue === null + ? null + : String(rawValue).trim() || null; + } + + // 第一步:校验所有商品是否在 StockStore 中存在,并收集有效明细 + const errors = []; + const items = []; + for (let i = 0; i < orderLine.length; i++) { + const line = orderLine[i]; + let wmsStock = await app.model.StockStore.findByPk(line.itemId); + // 校验 StockStore 记录的 store_id 与当前上下文一致,防止跨货主越权 + if (wmsStock && Number(wmsStock.store_id) !== Number(storeId)) { + wmsStock = null; + } + // 外部渠道 itemId 可能是平台商品标识或条码而非 WMS 主键, + // 主键查不到或跨货主时降级按 item_code + 仓库货主维度查找 + if (!wmsStock && line.itemCode) { + const stockWhere = { + item_code: line.itemCode, + warehouse_id: warehouseId, + store_id: storeId, + }; + if (appKey) { + stockWhere.app_key = appKey; + } + wmsStock = await app.model.StockStore.findOne({ where: stockWhere }); + } + if (!wmsStock) { + errors.push( + `SKU${line.itemId}商品《${line.itemName}》编码《${line.itemCode}》\n未同步推送到仓库` + ); + continue; + } + if (!wmsStock.stock_id) { + errors.push( + `SKU${line.itemId}商品《${line.itemName}》编码《${line.itemCode}》wms无对应关系\n请联系仓库关联创建商品` + ); + continue; + } + const planQty = parseInt(line.planQty) || 0; + if (planQty <= 0) { + errors.push( + `SKU${line.itemId}商品《${line.itemName}》编码《${line.itemCode}》\n计划数量必须大于0` + ); + continue; + } + items.push({ + orderLineNo: line.orderLineNo, + ownerCode: line.ownerCode, + itemCode: line.itemCode, + itemId: line.itemId, + itemName: line.itemName, + planQty, + inventoryType: line.inventoryType, + stockId: wmsStock.stock_id, + }); + } + + if (errors.length > 0) { + return this.fail(`创建出库单失败,失败原因:\n${errors.join('\n')}`); + } + + // 预取超卖配置,避免每次 lockItemStorages 在锁内回退查 DB + const oversellConfig = await ctx.service.systems.stockStore + .getStoreWarehousePolicyByStoreAndWarehouse(storeId, warehouseId); + + // 第二步:在事务中写入主表 + 库存锁定 + 明细表 + const transaction = await ctx.model.transaction(); + try { + const order = await ctx.model.OrderStockout.create( + { + stockout_order_code: deliveryOrder.deliveryOrderCode, + order_type: deliveryOrder.orderType, + total_order_lines: totalOrderLines, + order_create_time: deliveryOrder.createTime + ? new Date(deliveryOrder.createTime) + : null, + remark: deliveryOrder.remark || null, + express_code: expressCode, + express_name: expressName, + ...receiverFields, + warehouse_id: warehouseId, + store_id: storeId, + qimen_owner_code: items[0].ownerCode, + qimen_warehouse_code: warehouseCode, + source_type: sourceType, + created_at: new Date(), + updated_at: new Date(), + }, + { transaction } + ); + + const orderId = order.id; + + // 库存锁定:按 stockId 升序排序后逐个加锁,避免死锁 + const sortedItems = [ ...items ].sort((a, b) => a.stockId - b.stockId); + for (const item of sortedItems) { + const lockResult = await ctx.service.systems.stockStore.lockItemStorages( + item.stockId, + item.planQty, + transaction, + oversellConfig, + { orderType: 'QM_STOCKOUT', orderNo: deliveryOrder.deliveryOrderCode, orderId } + ); + if (!lockResult.success) { + throw new Error( + `SKU${item.itemId}商品《${item.itemName}》编码《${item.itemCode}》\n库存锁定失败: ${lockResult.error}` + ); + } + } + + // 批量创建明细 + const now = new Date(); + const itemRecords = items.map(item => ({ + order_id: orderId, + order_line_no: item.orderLineNo, + owner_code: item.ownerCode, + item_code: item.itemCode, + item_id: item.itemId, + item_name: item.itemName, + plan_qty: item.planQty, + inventory_type: item.inventoryType, + stock_id: item.stockId, + created_at: now, + updated_at: now, + })); + + await ctx.model.OrderStockoutItems.bulkCreate(itemRecords, { + transaction, + validate: true, + }); + + await transaction.commit(); + + return this.success('出库单创建成功', { + stockoutOrderId: order.id, + stockoutOrderCode: order.stockout_order_code, + }); + } catch (err) { + await transaction.rollback(); + ctx.logger.error('[stockout.create] 事务写入失败:', err); + return this.fail(`创建出库单失败,失败原因:\n${err.message}`); + } + } + + /** + * 查询出库单。 + * + * 根据 deliveryOrderCode 查 `wms_order_stockout` 主表, + * 然后关联查 `wms_order_stockout_items` 明细,返回标准结构。 + * + * @param {Object} data 请求体,遵循奇门报文结构。 + * @param {Object} data.request 请求数据。 + * @param {Object} data.request.deliveryOrder 出库单查询条件。 + * @param {string} data.request.deliveryOrder.deliveryOrderCode 出库单号。 + * @return {Promise} 返回 success / fail 结果。 + */ + async query(data) { + const { app, ctx } = this; + const { deliveryOrderCode } = data.request.deliveryOrder; + + // 查主表 + const order = await ctx.model.OrderStockout.findOne({ + where: { stockout_order_code: deliveryOrderCode }, + }); + if (!order) { + return this.fail('未找到出库单'); + } + + // 查明细 + const items = await ctx.model.OrderStockoutItems.findAll({ + where: { order_id: order.id }, + order: [[ 'order_line_no', 'ASC' ]], + }); + + return this.success('成功', { + totalLines: items.length, + deliveryOrder: { + deliveryOrderCode: order.stockout_order_code, + deliveryOrderId: order.id, + warehouseCode: order.qimen_warehouse_code, + orderType: order.order_type, + status: order.order_status, + createTime: order.order_create_time ? app.formatDate(order.order_create_time) : null, + remark: order.remark || '', + }, + orderLines: { + orderLine: items.map(item => ({ + orderLineNo: item.order_line_no, + ownerCode: item.owner_code, + itemCode: item.item_code, + itemId: item.item_id, + itemName: item.item_name, + planQty: item.plan_qty, + inventoryType: item.inventory_type, + })), + }, + }); + } + + /** + * 取消出库单(奇门 / openapi / systemMethods 共用)。 + * + * 定位方式:优先按 stockoutOrderCode,其次按 id;上下文(storeId / warehouseId / + * operatorLabel)一律由 options 显式传入,不读取 ctx.user。仅 CREATED / PENDING + * 状态允许取消:事务内(行锁)释放创建时占用的库存锁定(QM_STOCKOUT,写 UNLOCK + * 流水),状态置 CANCELLED 并写操作日志;已 CANCELLED 幂等返回成功; + * COMPLETED / TRANSFERRED 等其他状态拒绝取消。 + * 取消成功后不需要向奇门 / 开放平台回传任何事件。 + * + * @param {Object} data 请求体。 + * @param {string} [data.stockoutOrderCode] 出库单号(优先)。 + * @param {number} [data.id] 出库单ID。 + * @param {Object} options 上下文。 + * @param {number|null} [options.storeId] 货主ID(有值时参与定位条件)。 + * @param {number} options.warehouseId 仓库ID。 + * @param {string} [options.operatorLabel] 操作人标识(写入操作日志,如 qimen:xxx / openapi:xxx)。 + * @return {Promise} 统一成功/失败包装响应,成功时返回 id / stockout_order_code / order_status。 + */ + async cancel(data = {}, options = {}) { + const { ctx } = this; + const { storeId, warehouseId, operatorLabel } = options; + const stockoutOrderCode = String(data.stockoutOrderCode || '').trim(); + const id = Number(data.id || 0); + const normalizedWarehouseId = Number(warehouseId) || 0; + + if (normalizedWarehouseId <= 0) { + return this.fail('缺少仓库上下文'); + } + + if (!stockoutOrderCode && !(id > 0)) { + return this.fail('出库单号不能为空'); + } + + // 定位条件:仓库 + 货主(有值时)+ 软删除过滤;单号优先,否则按 ID + const where = { + warehouse_id: normalizedWarehouseId, + deleted_at: null, + }; + if (storeId !== undefined && storeId !== null && storeId !== '') { + where.store_id = Number(storeId); + } + if (stockoutOrderCode) { + where.stockout_order_code = stockoutOrderCode; + } else { + where.id = id; + } + + const transaction = await ctx.model.transaction(); + let order; + try { + // 行锁防并发取消 / 确认 / 转单 + order = await ctx.model.OrderStockout.findOne({ + where, + transaction, + lock: transaction.LOCK.UPDATE, + }); + if (!order) { + await transaction.rollback(); + return this.fail('未找到对应的出库单'); + } + + // 幂等:已取消直接返回成功,不重复释放库存 + if (String(order.order_status || '').trim() === 'CANCELLED') { + await transaction.rollback(); + return this.success('取消出库单成功', { + id: order.id, + stockout_order_code: order.stockout_order_code, + order_status: 'CANCELLED', + }); + } + + // 状态守卫:仅 CREATED / PENDING 允许取消(与 storage.stockout.cancel 同口径) + if (!order.canCancel || !order.canCancel()) { + await transaction.rollback(); + return this.fail(`出库单当前状态(${order.order_status})不允许取消`); + } + + const items = await ctx.model.OrderStockoutItems.findAll({ + where: { order_id: order.id }, + raw: true, + transaction, + }); + + // 释放创建时占用的库存锁定(口径与 storage.stockout.cancel 完全一致) + let releasedQty = 0; + for (const item of items) { + const qty = Number(item.plan_qty) || 0; + if (qty <= 0) continue; + const releaseResult = await ctx.service.systems.stockStore.lockItemStorages( + item.stock_id, + -qty, + transaction, + null, + { + orderType: 'QM_STOCKOUT', + orderNo: order.stockout_order_code, + orderId: order.id, + remark: '出库单取消释放锁定', + } + ); + if (!releaseResult.success) { + // 已释放过(锁定不足)视为幂等成功,避免阻断重试 + const alreadyReleased = String(releaseResult.error || '').includes('释放数量超过已锁定库存'); + if (alreadyReleased) { + ctx.logger.warn(`[stockout.cancel] 库存${item.stock_id}锁定已释放,跳过: ${releaseResult.error}`); + continue; + } + throw new Error(`库存${item.stock_id}释放锁定失败: ${releaseResult.error}`); + } + releasedQty += qty; + } + + await ctx.model.OrderStockout.update( + { order_status: 'CANCELLED', sync_message: '已取消', updated_at: new Date() }, + { where: { id: order.id }, transaction } + ); + + await this._writeStockoutOperationLog( + order, + 'STOCKOUT_CANCEL', + `出库单已取消,释放锁定库存 ${releasedQty}`, + { + transaction, + warehouseId: normalizedWarehouseId, + operator: { id: null, name: operatorLabel || 'system' }, + } + ); + + await transaction.commit(); + } catch (err) { + try { + await transaction.rollback(); + } catch (rollbackErr) { + ctx.logger.error('[stockout.cancel] 事务回滚失败:', rollbackErr); + } + ctx.logger.error(`[stockout.cancel] 取消失败: ${err.message}`); + return this.fail(`取消失败:${err.message}`); + } + + ctx.logger.info(`[stockout.cancel] 取消完成: ${order.stockout_order_code}`); + return this.success('取消出库单成功', { + id: order.id, + stockout_order_code: order.stockout_order_code, + order_status: 'CANCELLED', + }); + } + + /** + * 写 wms_operation_log 操作日志(businessType=stockout),失败仅告警不影响主流程。 + * + * 与 systemMethods/storage/stockout 历史日志口径一致;操作人 / 仓库信息由 + * options 显式传入,不读取 ctx.user(供奇门 / openapi 等无登录用户上下文渠道复用)。 + * + * @param {Object} order 出库单实例或行。 + * @param {string} operationCode 操作编码(如 STOCKOUT_CANCEL)。 + * @param {string} message 日志内容。 + * @param {Object} [options={}] 选项。 + * @param {Object} [options.transaction] 数据库事务对象。 + * @param {number|null} [options.warehouseId] 仓库ID,缺省回退出库单自身 warehouse_id。 + * @param {Object} [options.operator={}] 操作人信息,含 id / name。 + * @return {Promise} 无返回值。 + */ + async _writeStockoutOperationLog(order, operationCode, message, options = {}) { + const { ctx } = this; + const opLogService = ctx.service && ctx.service.systems && ctx.service.systems.operationLog; + if (!opLogService || typeof opLogService.createOperationLogs !== 'function') { + ctx.logger.warn('[stockout] 操作日志服务不可用,跳过记录'); + return; + } + const operator = options.operator || {}; + try { + await opLogService.createOperationLogs([ + { + businessType: 'stockout', + businessId: order.id, + operationCode, + operator: { + id: operator.id ?? null, + name: String(operator.name || 'system'), + }, + extras: { + warehouseId: options.warehouseId ?? order.warehouse_id ?? null, + message, + externalLogType: 'NONE', + }, + }, + ], { transaction: options.transaction }); + } catch (err) { + ctx.logger.warn(`[stockout] 写操作日志失败: ${err.message}`); + } + } + +} + +module.exports = StockoutOrderService; diff --git a/app/service/systems/storage/entry.js b/app/service/systems/storage/entry.js index 8546d85..e0f523b 100644 --- a/app/service/systems/storage/entry.js +++ b/app/service/systems/storage/entry.js @@ -978,15 +978,18 @@ class EntryService extends Service { /** * 查询当前仓库可访问的入库单。 + * 默认仓库取 ctx.user.store_id,外部渠道可通过 warehouseId 显式覆盖。 * @param {number} id 入库单ID + * @param {number} [warehouseId] 仓库ID,缺省取 ctx.user.store_id * @return {Promise} 入库单实例 */ - async getOwnedEntryOrderById(id) { + async getOwnedEntryOrderById(id, warehouseId = null) { const { ctx } = this; + const normalizedWarehouseId = Number(warehouseId) || Number(ctx.user?.store_id) || 0; return await ctx.model.EntryOrder.findOne({ where: { id, - warehouse_id: ctx.user.store_id, + warehouse_id: normalizedWarehouseId, is_enabled: 1, deleted_at: null, }, @@ -994,14 +997,88 @@ class EntryService extends Service { } /** - * 作废入库单。 + * 作废入库单(系统方法入口与奇门 / openapi 外部渠道共用)。 + * + * 定位方式: + * - 传 data.entryOrderCode(或 data.entry_order_code)时按单号定位,定位条件带 + * is_enabled / deleted_at / warehouse_id,有 storeId 时追加货主条件; + * - 否则回退 data.id / data.ids(系统方法入口口径不变)。 + * + * options 为外部渠道扩展,系统方法入口不传时行为与文案与历史版本完全一致: + * - warehouseId:覆盖仓库上下文(默认 ctx.user.store_id); + * - storeId:有值时参与定位; + * - operatorLabel:覆盖操作人(写入回传与操作日志); + * - skipExternalSync:true 时跳过 QM 来源的 qimenEntrySync 取消回传; + * - idempotent:true 时已作废(CANCELLED)按幂等成功处理; + * - notFoundMessage:未找到时的错误文案(默认「入库单不存在或无权访问」)。 + * * @param {Object} data 请求体 - * @return {Promise} code/data/message 结构 + * @param {number} [data.id] 单个入库单ID + * @param {number[]} [data.ids] 批量入库单ID数组 + * @param {string} [data.entryOrderCode] 入库单号(外部渠道按单号定位,优先) + * @param {Object} [options] 可选上下文(外部渠道扩展,系统方法入口不传) + * @return {Promise} { code, message, data } 结构 */ - async cancel(data = {}) { + async cancel(data = {}, options = {}) { const { ctx } = this; - const normalizedResult = this.normalizeCancelEntryOrderIds(data); + const { + warehouseId: optWarehouseId, + storeId: optStoreId, + operatorLabel, + skipExternalSync = false, + idempotent = false, + notFoundMessage, + } = options; + // 仓库上下文:外部渠道通过 options.warehouseId 覆盖,系统方法入口取 ctx.user.store_id + const warehouseId = Number(optWarehouseId) || Number(ctx.user?.store_id) || 0; + + // 操作人:外部渠道通过 options.operatorLabel 覆盖,系统方法入口取 ctx.user + const operator = String(operatorLabel || '').trim() + ? { id: null, name: String(operatorLabel).trim() } + : { + id: ctx.user?.employees_id || ctx.user?.id || '', + name: ctx.user?.employees_name || '', + }; + + const notFoundText = String(notFoundMessage || '').trim() || '入库单不存在或无权访问'; + + // 按单号定位(外部渠道),优先于 id / ids + const entryOrderCode = String(data.entryOrderCode || data.entry_order_code || '').trim(); + if (entryOrderCode) { + const where = { + entry_order_code: entryOrderCode, + warehouse_id: warehouseId, + is_enabled: 1, + deleted_at: null, + }; + if (optStoreId !== undefined && optStoreId !== null && optStoreId !== '') { + where.store_id = Number(optStoreId); + } + + const entryOrder = await ctx.model.EntryOrder.findOne({ where }); + if (!entryOrder) { + return { + code: 404, + message: notFoundText, + data: null, + }; + } + + const guard = this._guardCancelEntryOrder(entryOrder, idempotent); + if (guard) { + return { + code: guard.code, + message: guard.message, + data: guard.code === 200 ? { ids: [ entryOrder.id ] } : null, + }; + } + + return await this._doCancelEntryOrder(entryOrder, { operator, skipExternalSync }); + } + + // 按 id / ids 定位(系统方法入口,行为与文案保持不变) + const normalizedResult = this.normalizeCancelEntryOrderIds(data); if (!normalizedResult.ok) { return { code: normalizedResult.code || 400, @@ -1013,101 +1090,29 @@ class EntryService extends Service { const orderIds = normalizedResult.ids || []; for (const orderId of orderIds) { - const entryOrder = await this.getOwnedEntryOrderById(orderId); + const entryOrder = await this.getOwnedEntryOrderById(orderId, warehouseId); if (!entryOrder) { return { code: 404, - message: '入库单不存在或无权访问', + message: notFoundText, data: null, }; } - // 6b: sync_status=SUCCESS 不可取消 - if (entryOrder.sync_status === 'SUCCESS') { + const guard = this._guardCancelEntryOrder(entryOrder, idempotent); + if (guard) { + if (guard.code === 200) continue; // 幂等:已作废跳过,继续处理剩余单据 return { - code: 400, - message: '入库单已完成回传,不可取消', + code: guard.code, + message: guard.message, data: null, }; } - if (entryOrder.order_status === 'COMPLETED') { - return { - code: 400, - message: '已完成入库单不允许作废', - data: null, - }; + const cancelResult = await this._doCancelEntryOrder(entryOrder, { operator, skipExternalSync }); + if (cancelResult.code !== 200) { + return cancelResult; } - - if (entryOrder.order_status === 'CANCELLED') { - return { - code: 400, - message: '入库单已作废', - data: null, - }; - } - - // 6a: QM 来源需发送取消同步 - if (String(entryOrder.source_type) === 'QM') { - const entryItems = await ctx.model.EntryItems.findAll({ - where: { order_id: entryOrder.id }, - attributes: [ 'item_code', 'item_id', 'count', 'inventory_type', 'owner_code' ], - raw: true, - }); - - const orderLines = (entryItems || []).map((item, idx) => ({ - orderLineNo: idx + 1, - ownerCode: item.owner_code || '', - itemCode: item.item_code || '', - itemId: item.item_id || '', - inventoryType: item.inventory_type || 'ZP', - planQty: item.count || 0, - actualQty: 0, // 全部为 0,通知 ERP 关闭 - })); - - const syncResult = await ctx.service.systems.inboundDirectLog.qimenEntrySync({ - entryOrder, - orderLines, - outBizCode: `CANCEL_${Date.now()}`, - remark: '入库单取消', - operator: { - id: ctx.user?.employees_id || ctx.user?.id || '', - name: ctx.user?.employees_name || '', - }, - }); - - if (!syncResult.success) { - return { - code: 500, - message: `取消失败: ${syncResult.message}`, - data: null, - }; - } - } - - // 更新状态 - await entryOrder.update({ - order_status: 'CANCELLED', - updated_at: new Date(), - }); - - // 回退关联收货单的入库状态,避免死锁 - await this._rollbackReceivingStorageStatus(entryOrder.id); - - // 写操作日志 - await ctx.service.systems.operationLog.createOperationLog({ - businessType: 'entry_order', - businessId: entryOrder.id, - operationCode: 'ENTRY_ORDER_CANCEL', - operator: { - id: ctx.user?.employees_id || ctx.user?.id || '', - name: ctx.user?.employees_name || '', - }, - extras: { - warehouseId: entryOrder.warehouse_id, - message: '入库单已取消', - }, - }); } return { @@ -1117,6 +1122,125 @@ class EntryService extends Service { }; } + /** + * 作废入库单的状态守卫校验。 + * 返回 null 表示允许继续作废;返回 { code, message } 表示拦截; + * 幂等模式下已作废返回 { code: 200 }(由调用方决定跳过或直接成功), + * 且幂等判定优先于回传状态判定(已作废单据的回传状态不影响重试幂等)。 + * @param {Object} entryOrder 入库单实例 + * @param {boolean} idempotent 是否幂等模式(已作废视为成功) + * @return {{ code: number, message: string }|null} 守卫结果 + */ + _guardCancelEntryOrder(entryOrder, idempotent = false) { + // 幂等模式:已作废优先按成功处理(外部渠道重试口径) + if (idempotent && entryOrder.order_status === 'CANCELLED') { + return { + code: 200, + message: '作废成功', + }; + } + + // sync_status=SUCCESS 不可取消 + if (entryOrder.sync_status === 'SUCCESS') { + return { + code: 400, + message: '入库单已完成回传,不可取消', + }; + } + + if (entryOrder.order_status === 'COMPLETED') { + return { + code: 400, + message: '已完成入库单不允许作废', + }; + } + + if (entryOrder.order_status === 'CANCELLED') { + return { + code: 400, + message: '入库单已作废', + }; + } + + return null; + } + + /** + * 执行单个入库单的作废动作:QM 来源发送取消同步(actualQty 全 0)、 + * 状态置 CANCELLED、回退收货单占用、写 ENTRY_ORDER_CANCEL 操作日志。 + * @param {Object} entryOrder 入库单实例 + * @param {Object} [context] 上下文 + * @param {Object} [context.operator] 操作人信息 { id, name } + * @param {boolean} [context.skipExternalSync] 是否跳过 QM 取消同步回传 + * @return {Promise} { code, message, data } 结构 + */ + async _doCancelEntryOrder(entryOrder, context = {}) { + const { ctx } = this; + const { operator = {}, skipExternalSync = false } = context; + + // QM 来源需发送取消同步(外部渠道不回传时跳过) + if (String(entryOrder.source_type) === 'QM' && !skipExternalSync) { + const entryItems = await ctx.model.EntryItems.findAll({ + where: { order_id: entryOrder.id }, + attributes: [ 'item_code', 'item_id', 'count', 'inventory_type', 'owner_code' ], + raw: true, + }); + + const orderLines = (entryItems || []).map((item, idx) => ({ + orderLineNo: idx + 1, + ownerCode: item.owner_code || '', + itemCode: item.item_code || '', + itemId: item.item_id || '', + inventoryType: item.inventory_type || 'ZP', + planQty: item.count || 0, + actualQty: 0, // 全部为 0,通知 ERP 关闭 + })); + + const syncResult = await ctx.service.systems.inboundDirectLog.qimenEntrySync({ + entryOrder, + orderLines, + outBizCode: `CANCEL_${Date.now()}`, + remark: '入库单取消', + operator, + }); + + if (!syncResult.success) { + return { + code: 500, + message: `取消失败: ${syncResult.message}`, + data: null, + }; + } + } + + // 更新状态 + await entryOrder.update({ + order_status: 'CANCELLED', + updated_at: new Date(), + }); + + // 回退关联收货单的入库状态,避免死锁 + await this._rollbackReceivingStorageStatus(entryOrder.id); + + // 写操作日志 + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'entry_order', + businessId: entryOrder.id, + operationCode: 'ENTRY_ORDER_CANCEL', + operator, + extras: { + warehouseId: entryOrder.warehouse_id, + message: '入库单已取消', + }, + }); + + return { + code: 200, + message: '作废成功', + data: { ids: [ entryOrder.id ] }, + }; + } + /** * 回退入库单关联收货单的入库状态(入库单作废时调用)。 * 按绑定行数量台账逐单回收本入库单在收货单上的占用(不影响其他入库单的占用), diff --git a/methods/changes/openapi.json b/methods/changes/openapi.json index 920c880..3603be9 100644 --- a/methods/changes/openapi.json +++ b/methods/changes/openapi.json @@ -1,4 +1,75 @@ [ + { + "version": "2026.09.12-openapi-order-cancel-rk-entry-order-support", + "date": "2026-09-12", + "type": "updated", + "module": "order", + "summary": "openapi order.cancel 支持范围扩展新增 RK 组(B2BRK/SCRK/LYRK/CCRK/CGRK/DBRK/QTRK):按 orderCode 查入库单号,复用 ctx.service.systems.storage.entry.cancel 完整作废流程(状态守卫 + 回退收货单占用 + ENTRY_ORDER_CANCEL 操作日志),取消成功后不回传开放平台回调事件,已作废按幂等成功;其他类型仍返回暂不支持该订单类型的取消操作。", + "methods": [ + "order.cancel" + ], + "notes": [ + "app/service/openapiMethods/order.js cancel:新增 RK_TYPES=[B2BRK,SCRK,LYRK,CCRK,CGRK,DBRK,QTRK];orderType 经 trim().toUpperCase() 归一化,不在 ORDER/CK/RK 集合内返回「暂不支持该订单类型的取消操作」", + "RK 组分支:委托 ctx.service.systems.storage.entry.cancel({ entryOrderCode }, { storeId, warehouseId, operatorLabel=openapi:xxx, skipExternalSync=true, idempotent=true, notFoundMessage=未找到对应的入库单 });成功返回「取消入库单成功」(code=1),失败透传 message(code=0)", + "RK 组错误文案:未找到对应的入库单 / 已完成入库单不允许作废(order_status=COMPLETED)/ 入库单已完成回传,不可取消(sync_status=SUCCESS);已 CANCELLED 幂等成功;skipExternalSync=true 不回传开放平台回调事件", + "methods/openapi.json:order.cancel 的 description、params/requestBody 的 orderCode 与 orderType 描述(RK 组 7 枚举中文名与奇门 this.orderType 一致:B2BRK=B2B入库、SCRK=生产入库、LYRK=领用入库、CCRK=残次品入库、CGRK=采购入库、DBRK=调拨入库、QTRK=其他入库)、errors(新增 3 条 RK 文案,code=0)、notes(新增 RK 组语义与复现口径 orderCode=RK_2, orderType=CGRK)", + "文档版本 1.2.2 -> 1.2.3(docMeta.version),updatedAt 保持 2026-09-12", + "本次仅同步文档,未修改任何业务代码;写入通过 script/update-api-doc.cjs(先 --dry-run 校验)" + ] + }, + { + "version": "2026.09.12-openapi-order-cancel-ck-stockout-support", + "date": "2026-09-12", + "type": "updated", + "module": "order", + "summary": "openapi order.cancel 支持范围由 JYCK/HHCK/BFCK 扩展为 JYCK/HHCK/BFCK + CK 组(PTCK/DBCK/B2BCK/QTCK/CGTH):CK 组按 orderCode 查出库单号取消 wms_order_stockout(仅 CREATED/PENDING 可取消,委托共享实现 systems/stockout_order.js#cancel),JYCK/HHCK/BFCK 仍操作 wms_order_delivery(行为不变),其他类型返回暂不支持该订单类型的取消操作;同步补充 CK 组文案与 notes。", + "methods": [ + "order.cancel" + ], + "notes": [ + "app/service/openapiMethods/order.js cancel:ORDER_TYPES=[JYCK,HHCK,BFCK]、CK_TYPES=[PTCK,DBCK,B2BCK,QTCK,CGTH];orderType 经 trim().toUpperCase() 归一化,不在两集合内返回「暂不支持该订单类型的取消操作」", + "CK 组分支:orderCode 缺省返回「orderCode 参数缺失」;委托 ctx.service.systems.stockoutOrder.cancel({ stockoutOrderCode }, { storeId, warehouseId, operatorLabel=openapi:xxx });成功「取消出库单成功」,不回传开放平台回调事件", + "出库单状态枚举 CREATING/CREATED/PENDING/COMPLETED/CANCELLED/TRANSFERRED;仅 CREATED/PENDING 可取消,已 CANCELLED 幂等返回成功;未找到返回「未找到对应的出库单」,状态不允许返回「出库单当前状态(xxx)不允许取消」,异常返回「取消失败:xxx」", + "methods/openapi.json:order.cancel 的 description、params/requestBody 的 orderCode 与 orderType 描述、response.data 描述、errors(「订单号不能为空」修正为「orderCode 参数缺失」,新增未找到对应的出库单/出库单当前状态(xxx)不允许取消/取消失败:xxx)、notes(新增 CK 组路由差异与回传口径)", + "文档版本 1.2.1 -> 1.2.2(docMeta.version),updatedAt 保持 2026-09-12", + "本次仅同步文档,未修改任何业务代码;写入通过 script/update-api-doc.cjs(先 --dry-run 校验)" + ] + }, + { + "version": "2026.09.12-openapi-order-cancel-orderType-normalize", + "date": "2026-09-12", + "type": "updated", + "module": "order", + "summary": "openapi order.cancel 的 orderType 参数说明小幅补充大小写不敏感归一化(内部 trim 后转大写,jyck/Jyck/JYCK 等价),枚举 JYCK/HHCK/BFCK 及默认值 JYCK 保持不变(代码依据 openapiMethods/order.js cancel:String(body.orderType || 'JYCK').trim().toUpperCase())。", + "methods": [ + "order.cancel" + ], + "notes": [ + "app/service/openapiMethods/order.js cancel:orderType 取 JYCK(默认)/HHCK/BFCK,内部 trim().toUpperCase() 归一化,三者均映射为出库单 ORDER;其他值返回暂不支持该订单类型的取消操作", + "methods/openapi.json:order.cancel 的 params.orderType 与 requestBody.orderType description 追加大小写不敏感说明;notes 新增一行归一化说明,其余字段未改动", + "文档版本 1.2.0 -> 1.2.1(docMeta.version),updatedAt 保持 2026-09-12", + "本次仅同步文档,未修改任何业务代码;写入通过 script/update-api-doc.cjs(先 --dry-run 校验)" + ] + }, + { + "version": "2026.09.12-openapi-stockout-create-query", + "date": "2026-09-12", + "summary": "新增开放 API 出库单接口 stockout.create / stockout.query,与奇门 stockout 共用同一份实现(抽离到 systems/stockout_order.js),开放 API 来源落库 source_type=API。", + "methods": [ + "stockout.create", + "stockout.query" + ], + "notes": [ + "app/service/systems/stockout_order.js 新增:抽离原 qimenMethods/stockout.js 的 create/query 核心实现,入参沿用奇门报文结构(request.deliveryOrder / request.orderLines),上下文(storeId/warehouseId/warehouseCode/appKey/sourceType)由调用方显式传入", + "app/service/qimenMethods/stockout.js 改为薄适配层:create 委托 systems.stockoutOrder.create(sourceType=QM),query 委托 systems.stockoutOrder.query,行为与重构前一致", + "app/service/openapiMethods/stockout.js 新增薄适配层:入参为开放 API 扁平结构(body.deliveryOrder / body.orderLines / body.deliveryOrderCode),创建时 sourceType=API,出库单回传走 OpenAPI 回调 event=stockout_completed", + "methods/openapi.json 新增「出库单模块」(module=stockout),文档版本升至 1.2.0", + "库存锁标记沿用 QM_STOCKOUT,与 storage.stockout.cancel / confirm / toOrder 的释放口径保持一致", + "文档生成:node ./script/update-api-doc.cjs --spec=temp/api-doc-update-openapi-stockout.json(先 --dry-run 校验)" + ], + "type": "added", + "module": "stockout" + }, { "version": "2026.08.30-openapi-entryorder-create-item-match-fix", "date": "2026-08-30", diff --git a/methods/changes/qimen.json b/methods/changes/qimen.json index 11388bd..57221a2 100644 --- a/methods/changes/qimen.json +++ b/methods/changes/qimen.json @@ -1,4 +1,63 @@ [ + { + "version": "2026.09.12-qimen-order-cancel-rk-entry-order-support", + "date": "2026-09-12", + "type": "updated", + "module": "order", + "summary": "qimen order.cancel 的 RK 组(B2BRK/SCRK/LYRK/CCRK/CGRK/DBRK/QTRK)取消入库单语义升级:由「直接置 order_status=CANCELLED」升级为委托 ctx.service.systems.storage.entry.cancel 完整作废流程(守卫 sync_status=SUCCESS/COMPLETED + 回退收货单占用 + ENTRY_ORDER_CANCEL 操作日志),取消成功后不回传任何奇门事件(skipExternalSync=true),已作废按幂等成功;同步修正上一轮「RK 组将入库单 order_status 置 CANCELLED」的过时措辞。", + "methods": [ + "order.cancel" + ], + "notes": [ + "app/service/qimenMethods/order.js cancel 的 case RK:空单号返回「入库单号不能为空」;委托 ctx.service.systems.storage.entry.cancel({ entryOrderCode }, { storeId, warehouseId, operatorLabel=qimen:xxx, skipExternalSync=true, idempotent=true, notFoundMessage=未找到对应的入库单 })", + "守卫口径(systems/storage/entry.js _guardCancelEntryOrder):sync_status=SUCCESS 返回「入库单已完成回传,不可取消」,order_status=COMPLETED 返回「已完成入库单不允许作废」;幂等模式下已 CANCELLED 优先按成功处理(幂等判定优先于回传状态判定)", + "作废动作(_doCancelEntryOrder):状态置 CANCELLED + 按台账回退关联收货单占用(重算 storage_status)+ 写 ENTRY_ORDER_CANCEL 操作日志;skipExternalSync=true 跳过 QM 来源的 qimenEntrySync 取消回传,取消成功不回传奇门事件", + "共享实现 QM 回传失败分支文案为「取消失败: xxx」(RK 渠道 skipExternalSync=true 不触发回传,该分支不会出现)", + "methods/qimen.json:order.cancel 的 description(RK 组改为委托共享作废流程)、request.orderType(RK 组改为已实现并注明完整作废语义)、errors(新增入库单号不能为空/已完成入库单不允许作废/入库单已完成回传,不可取消)、notes(RK 组 note 重写为完整实现语义)", + "order.pending 的 request.orderType 枚举描述仅列枚举名,无「将入库单 order_status 置 CANCELLED」过时措辞,保持不动", + "文档版本 0.3.9 -> 0.3.10(docMeta.version),updatedAt 保持 2026-09-12", + "本次仅同步文档,未修改任何业务代码;写入通过 script/update-api-doc.cjs(先 --dry-run 校验)" + ] + }, + { + "version": "2026.09.12-qimen-order-cancel-ck-stockout-support", + "date": "2026-09-12", + "type": "updated", + "module": "order", + "summary": "qimen order.cancel 的 CK 组(PTCK/DBCK/B2BCK/QTCK/CGTH)由「取消出库单未开发完成」改为已支持:按出库单号查 wms_order_stockout,仅 CREATED/PENDING 允许取消(COMPLETED/TRANSFERRED 拒绝),委托共享实现 systems/stockout_order.js#cancel(单事务 + 行锁,释放 QM_STOCKOUT 锁定并写 STOCKOUT_CANCEL 操作日志,已 CANCELLED 幂等返回成功);同步修正上一轮遗留的「CK 组(未开发)」过时措辞与 errors/notes。", + "methods": [ + "order.cancel" + ], + "notes": [ + "app/service/qimenMethods/order.js cancel 的 case CK:空单号返回「出库单号不能为空」,否则委托 ctx.service.systems.stockoutOrder.cancel({ stockoutOrderCode }, { storeId, warehouseId, operatorLabel=qimen:xxx })", + "出库单状态枚举 CREATING/CREATED/PENDING/COMPLETED/CANCELLED/TRANSFERRED;仅 CREATED/PENDING 可取消(canCancel),已 CANCELLED 幂等返回成功,COMPLETED/TRANSFERRED 返回「出库单当前状态(xxx)不允许取消」", + "取消成功不向奇门回传任何事件;释放 QM_STOCKOUT 库存锁定(写 UNLOCK 流水),「释放数量超过已锁定库存」视为幂等跳过;写 wms_operation_log(business_type=stockout,operation_code=STOCKOUT_CANCEL)", + "methods/qimen.json:order.cancel 的 description、request.orderCode(补充 CK 组为出库单号)、request.orderType(CK 组改为已实现并标注状态约束)、response.message(补充取消出库单成功)、errors(移除「取消出库单未开发完成」,新增出库单号不能为空/未找到对应的出库单/出库单当前状态(xxx)不允许取消/取消失败:xxx)、notes(新增 CK 组实现语义)", + "order.pending 的 CK 组枚举名称(PTCK=普通出库单、DBCK=调拨出库、B2BCK=B2B出库、QTCK=其他出库、CGTH=采购退货出库单)保持不变,order.cancel 沿用同一口径", + "文档版本 0.3.8 -> 0.3.9(docMeta.version),updatedAt 保持 2026-09-12", + "本次仅同步文档,未修改任何业务代码;写入通过 script/update-api-doc.cjs(先 --dry-run 校验)" + ] + }, + { + "version": "2026.09.12-qimen-order-cancel-pending-orderType-enum", + "date": "2026-09-12", + "type": "updated", + "module": "order", + "summary": "qimen order.cancel / order.pending 补齐 request.orderType 作业类型枚举说明(原为占位文本):全量枚举 ORDER(JYCK/HHCK/BFCK,取消发货单已实现)/ RK(B2BRK/SCRK/LYRK/CCRK/CGRK/DBRK/QTRK,入库单 order_status 置 CANCELLED)/ CK(PTCK/DBCK/B2BCK/QTCK/CGTH,未开发)/ JG(CNJG,未开发)/ BACKORDER(XTRK/THRK/HHRK,未开发);同步补全 order.cancel 取消逻辑说明(直接取消/拦截/幂等)、response 与 errors。", + "methods": [ + "order.cancel", + "order.pending" + ], + "notes": [ + "app/service/qimenMethods/order.js:构造函数 this.orderType 定义 orderType→{method,name} 全量映射,cancel/pending 均按 orderType.method switch 分发", + "order.cancel 的 request.orderType 参数 description 由占位文本补齐为全量枚举(含各组的取消支持情况);request.orderCode description 补充 ORDER 组为发货单号、RK 组为入库单号", + "order.cancel 补齐 response(flag/code/message,code=1 成功/0 失败)与 errors(订单号不能为空/未找到对应的订单/未找到对应的入库单/取消失败,已通知拦截执行/订单已同步,不可取消,已转为拦截处理/取消出库单未开发完成/取消加工单未开发完成/取消退货单未开发完成)", + "order.cancel notes 补充取消逻辑:未拣货且未打印直接取消(status=cancel, outbound_status=fin, step=4);已拣货/已打印拦截(intercept_status=intercepting);已同步转拦截(intercept_status=requested);已取消幂等返回取消订单成功", + "order.pending 的 request.orderType 参数 description 同步补齐为同一套枚举(pending 当前所有类型分支均未开发完成,返回锁定XX未开发完成),response/errors 同步补齐", + "文档版本 0.3.7 -> 0.3.8(docMeta.version),updatedAt 2026-09-12", + "本次仅同步文档,未修改任何业务代码;写入通过 script/update-api-doc.cjs(先 --dry-run 校验)" + ] + }, { "version": "2026.08.30-entryorder-create-item-match-fix", "date": "2026-08-30", diff --git a/methods/changes/system.json b/methods/changes/system.json index 5ecdb36..daa93b9 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,117 @@ [ + { + "version": "2026.09.12-storage-entry-cancel-entryOrderCode-doc", + "date": "2026-09-12", + "type": "updated", + "module": "storage.entry", + "summary": "storage.entry.cancel 文档小幅补充(对外契约不变):description 末尾注明另支持按 entryOrderCode(兼容别名 entry_order_code)按单号定位、供奇门/openapi 外部渠道复用;params 新增可选 entryOrderCode(内部复用口径,优先于 id/ids)。id/ids 入参、响应结构 { code, message, data } 与全部失败文案(入库单不存在或无权访问 / 入库单已作废 / 已完成入库单不允许作废 / 入库单已完成回传,不可取消 / 作废成功)逐一不变。", + "methods": [ + "storage.entry.cancel" + ], + "notes": [ + "app/service/systems/storage/entry.js cancel:新增 data.entryOrderCode(或 data.entry_order_code)按单号定位(定位条件带 is_enabled/deleted_at/warehouse_id,有 storeId 时追加货主条件),优先于 id/ids;options 为外部渠道扩展(warehouseId/storeId/operatorLabel/skipExternalSync/idempotent/notFoundMessage),系统方法入口不传时行为与文案与历史版本完全一致", + "奇门 order.cancel 与 openapi order.cancel 的 RK 组经此共用作废流程(skipExternalSync=true、idempotent=true、notFoundMessage=未找到对应的入库单)", + "methods/system.json:storage.entry.cancel 的 description 末尾补一句按 entryOrderCode 定位说明,params 新增可选 entryOrderCode;id/ids、response、errors 文案未动", + "文档版本 0.3.114 -> 0.3.115(docMeta.version),updatedAt 保持 2026-09-12", + "本次仅同步文档,未修改任何业务代码;写入通过 script/update-api-doc.cjs(先 --dry-run 校验)" + ] + }, + { + "version": "2026.09.12-storage-stockout-cancel-shared-impl", + "date": "2026-09-12", + "type": "updated", + "module": "storage.stockout", + "summary": "storage.stockout.cancel 内部实现改为委托共享 app/service/systems/stockout_order.js#cancel(奇门 / openapi 同口径:单事务 + 行锁);对外契约完全不变(缺少出库单ID / 缺少仓库上下文 / 出库单不存在 / 出库单当前状态(xxx)不允许取消 / 成功返回取消成功 + data 含 id、stockout_order_code、order_status);由「先查单再开事务」改为「单事务 + 行锁」,并发取消/确认/转单更安全。", + "methods": [ + "storage.stockout.cancel" + ], + "notes": [ + "app/service/systemMethods/storage/stockout.js cancel 改为薄适配层:校验 id(缺少出库单ID)与仓库上下文(缺少仓库上下文),委托 systems.stockoutOrder.cancel({ id }, { storeId: null, warehouseId, operatorLabel }),将共享层「未找到对应的出库单」映射为「出库单不存在」,成功映射为「取消成功」并透传 id / stockout_order_code / order_status", + "app/service/systems/stockout_order.js cancel:定位优先 stockoutOrderCode 其次 id;单事务 + 行锁(防止并发取消/确认/转单),仅 CREATED/PENDING 可取消(canCancel),已 CANCELLED 幂等返回成功,COMPLETED/TRANSFERRED 返回「出库单当前状态(xxx)不允许取消」", + "对外契约与实现变更前一致,调用方无需改动", + "methods/system.json:storage.stockout.cancel 的 description 补充共享实现说明;errors 由单条 description 文本改为逐条 code/message(与仓库统一格式),文案不变;docMeta.version 0.3.113 -> 0.3.114,updatedAt 保持 2026-09-12", + "本次仅同步文档,未修改任何业务代码;写入通过 script/update-api-doc.cjs(先 --dry-run 校验)" + ] + }, + { + "version": "2026.09.12-storage.inventory.listBySpaceId", + "date": "2026-09-12", + "type": "added", + "summary": "新增 storage.inventory.listBySpaceId 接口:传入 space_id,先判断该库位是否为当前仓库的库位(不存在返回 404、存在但不属于当前仓库返回 400),是则返回该库位下有量库存(quantity > 0)的商品列表。列表按商品(stock_id)汇总为一条(汇总 quantity/locked_quantity/intercept_locked_quantity/available_quantity,含 batch_count 与最早/最晚入库时间);商品信息统一走 stock_warehouse 通用链路(getStockDetails)返回 stock_warehouse 通用属性。", + "methods": [ + "storage.inventory.listBySpaceId" + ], + "notes": [ + "app/service/systemMethods/storage/inventory.js 新增 listBySpaceId 包装方法(透传 data.space_id,返回结构沿用 this.success('ok', result)),并加入 _noNeedRight/_noNeedLog/_noNeedAuth 豁免列表(与 listByStockId 一致)", + "app/service/systems/storage/inventory.js 新增 getStorageListBySpaceId:校验 space_id 为正整数与当前仓库上下文(ctx.user.store_id);先查 wms_location_space(id + warehouse_id + deleted_at=null)判断库位归属,未命中再查全局记录以区分「库位不存在」(404)与「库位不属于当前仓库」(400)", + "库存查询条件:wms_storage where warehouse_id + space_id + quantity > 0 + is_enabled=1 + delete_at=null,按 id 倒序取出库位明细行(仅取汇总所需列,不返回批次/效期明细)", + "商品通用属性:收集明细行 stock_id 去重后调用 ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { warehouseId })(带缓存通用链路),stock 对象即 stock_warehouse 通用属性(id/item_code/item_name/sku_property/quantity/locked_quantity/is_batch_mgmt/is_shelf_life_mgmt/is_images/need_recheck/store_id/packing_requirements/stock_unit/barcodes/image_url);该链路异常时降级为 stock=null 且不中断主流程", + "app/service/systems/storage/inventory.js 新增 _aggregateStorageRowsByStock:按 stock_id 在内存汇总数量与批次数、取最早/最晚入库时间(app.formatDate 格式化),并平铺 space_code/space_name(custom_name 优先,否则 space_code)与 store_name(wms_store_warehouse.store_remask,按 warehouse_id + store_id 收敛,查询异常降级为 null)", + "响应结构:data.space(id/warehouse_id/space_code/custom_name/space_status)+ data.list(按商品汇总行,无有量库存时为空数组)", + "错误码:400「space_id 必填且必须为正整数」、400「无法获取当前仓库信息」、400「库位 {space_id} 不属于当前仓库」、404「库位不存在: space_id={space_id}」", + "methods/system.json 新增 storage.inventory.listBySpaceId 条目(追加于 storage.inventory.listByStockId 之后;isNeedAuth=false、isNeedLogin=true、isNeedRight=false),version 0.3.112 -> 0.3.113,updatedAt 2026-09-12", + "AI_METHOD_ROUTING.md 第 6 节按文件内维护说明刷新(node .\\script\\tmp-gen-service-method-inventory.cjs → node .\\script\\tmp-update-ai-method-routing.cjs):systemMethods/storage/inventory.js 14 -> 15、systems/storage/inventory.js 13 -> 15(新增 getStorageListBySpaceId、_aggregateStorageRowsByStock)", + "验证:ESLint(npx eslint app/service/systems/storage/inventory.js app/service/systemMethods/storage/inventory.js)0 error;未执行任何部署/回退脚本,未改动数据库与 Redis 数据" + ], + "module": "storage.inventory" + }, + { + "version": "2026.09.11-shops-edit-shop-name-doc-sync", + "date": "2026-09-11", + "type": "updated", + "summary": "同步 shops.edit 文档:补入 shop_name 入参(修改店铺名称),修正「仅允许修改 platform_code 或 custom_name」的过时描述与错误文案。", + "methods": [ + "shops.edit" + ], + "notes": [ + "实现依据:app/service/systemMethods/shops.js 的 edit 已透传 shop_name/shopName(与 custom_name/platform_code 同样兼容 camelCase),app/service/systems/shops.js 的 edit 已支持 updates.shop_name。", + "字段语义区分:shop_name 为平台真实店铺名(shops.add 时写入 PENDING_* 占位名,授权回调后同步真实名称);custom_name 为自定义名称,仅作标签展示。", + "校验行为:三者至少传一个,否则抛 400「仅允许修改 platform_code、custom_name 或 shop_name」;shop_name 走 normalizeText(required, maxLength=100),为空抛 400「shop_name 不能为空」、超长抛 400「shop_name 长度不能超过 100」。", + "唯一性:改名与改平台合并后按「当前仓库 + next platform_code + next shop_name」调用 ensureShopNameUnique(排除自身,软删除店铺名以 DELETED_SHOP_NAME_PREFIX 前缀排除),冲突抛 409「同仓同平台下 shop_name 已存在」。", + "文档更新:methods/system.json 的 shops.edit description 改为 platform_code/custom_name/shop_name 三选一,params 新增 shop_name(兼容 shopName),errors 补入 shop_name 相关 400 文案、id 与仓库校验 400、店铺不存在 404,并修正 400「仅允许修改 platform_code 或 custom_name」为「仅允许修改 platform_code、custom_name 或 shop_name」;version 0.3.111 -> 0.3.112,updatedAt 2026-09-11。", + "仅文档同步,未修改任何业务代码;未执行部署/回退脚本,未改动生产数据。" + ], + "module": "shops" + }, + { + "version": "2026.09.11-wave-batch-list-where-operator", + "date": "2026-09-11", + "type": "changed", + "summary": "order.wave.batchList(波次管理列表)的 where 新增操作符传参支持:白名单字段统一支持裸值与 {operator,value,type} 标准结构(eq/ne/gt/lt/ge/le/in/notin/between/notbetween/like/contains/notlike/startswith/endswith/isnull/isnotnull,按字段分组限制),value 支持数组(like/contains 多值 OR、notlike 多值 AND、in/notin 要求非空数组、eq 传数组等价 in);未显式传 operator 时保持历史默认语义(wave_no/creator/logistics_name/item_part/item_snapshot_key/item_detail_machine 默认模糊,其余默认等值),裸数组按 in。新增 total_orders / processed_orders 两个数值字段,store_id 新增 ne/notin 排除语义。修复前端通用筛选器下发 {operator,value:[...]} 时 wave_id 等整数字段报「参数不合法」、wave_no 等文本字段被 String([...]) 拼成 'A,B' 导致恒空的问题。", + "methods": [ + "order.wave.batchList" + ], + "module": "order.wave", + "notes": [ + "app/service/systemMethods/order/wave.js:buildBatchListWhereClause 由「逐字段手写 if 取 .value」改为通用条件构建,新增 isEmptyBatchListWhereValue(空值跳过,isnull/isnotnull 例外)、resolveBatchListFieldCondition(区分标准结构与裸值,仅标准结构读取 operator,裸值回落字段默认操作符)、buildBatchListFieldConditionSql(操作符 → SQL 片段 + 命名占位符)、normalizeBatchListDistinguishExpressValue(布尔归一 0/1)、normalizeBatchListStoreIdCondition(货主条件归一 in/notin)。", + "默认语义与历史完全对齐:wave_no/creator/logistics_name/item_part/item_snapshot_key/item_detail_machine 未传 operator 时 LIKE '%值%';wave_id/wave_type/wave_status/source/distinguish_express 默认等值;total_orders_min/max、processed_orders_min/max 默认 ge/le;裸数组按 in(此前会被 String(arr) 拼成 'A,B' 恒空)。", + "新增数值字段 total_orders / processed_orders(默认 eq,支持 between 等数值操作符);原有 *_min/*_max 保留范围语义,也接受标准结构覆盖默认操作符(如 {operator:'between',value:[1,20]})。", + "store_id:默认 eq/in(返回包含任一筛选货主订单的波次,含混合货主波次);新增 ne/notin 排除语义——外层 WHERE 追加 wb.wave_id NOT IN (SELECT DISTINCT od.wave_id FROM <订单分表> od WHERE od.wave_id IS NOT NULL AND od.store_id IN (:whereStoreIds)),子查询显式排除 NULL 波次号,避免 NOT IN 三值逻辑把整表过滤为空。", + "分配/复核状态类(storage/express/print/review_assignment_status)仍只支持等值(内部按聚合统计判定):改为先解构 {operator,value} 再校验,显式传非 eq 操作符直接报错「仅支持: eq」,不再被 String({...}) 静默拼成非法枚举值。", + "根因:batchList 走原生 SQL 拼条件(列表查询路线 B),只读 .value 不读 operator——整数字段 Number({operator,value}) → NaN → 抛「参数不合法」;文本字段 String([...]) → 'A,B' → LIKE '%A,B%' 恒空(无报错难以定位)。", + "验证:run/check-wave-batch-where-operator.cjs(egg-mock 起真实 service,只读、不写库、不清理数据)33/33 通过——基线 274;wave_no eq/like/裸值/startswith/notlike/数组 contains/数组 eq;wave_id 裸值/in/裸数组/gt/between/notbetween;creator 裸值/eq/ne;wave_type in;source in;distinguish_express 裸 true/in;total_orders between、total_orders_min/max 历史回归;logistics_name isnotnull;storage_assignment_status {operator:eq} 与裸值结果一致;store_id 裸值/数组/notin(= baseline - positive)/不存在货主(notin 直通基线,验证 NULL 安全);5 个错误用例(不支持操作符、store_id 不支持操作符、分配状态仅 eq、where 禁止 warehouse_id、不支持的字段)。期望值均由本地开发库现算(含货主覆盖数),不依赖硬编码总量。", + "methods/system.json:order.wave.batchList 方法描述与 where 参数说明同步操作符契约、字段分组允许集合、新增 total_orders/processed_orders 与 store_id ne/notin 语义;version 0.3.110 -> 0.3.111,updatedAt 2026-09-11。", + "兼容性:未显式传 operator 的既有调用语义完全不变,包括 delivery_order.findAutoGroupingWaveId 传入的 wave_status/item_part_type/item_part/item_snapshot_key/distinguish_express/logistics_name 裸值,以及分页 page/pageSize 顶层写法。", + "未执行任何部署/回退脚本,未改动生产数据;ESLint(npx eslint app/service/systemMethods/order/wave.js)0 error。" + ] + }, + { + "version": "2026.09.10-packing-where-waybill-wave-contains", + "date": "2026-09-10", + "type": "changed", + "summary": "order.packing.list / order.packing.export 的 where.waybill_code 与 where.wave_no 新增 operator 支持:operator=contains(兼容 like)时按 LIKE '%值%' 模糊匹配;两字段 value 均支持字符串数组(多值取并集)。修复前端通用筛选器下发 {operator:'contains', value:[...]} 时因数组被整体字符串化(String(['A','B']) → 'A,B')导致恒返回空列表的问题。", + "methods": [ + "order.packing.list", + "order.packing.export" + ], + "module": "order.packing", + "notes": [ + "app/service/systems/order_packing.js:_buildListWhere 的 waybill_code 分支改为逐单号展开条件——operator=contains/like 下发 { waybill_code: { [Op.like]: '%单号%' } }(escapeLikeWildcards 转义通配符);缺省/eq 保持原「完整单号等值 + 剥离 -1-1- 分段后缀主体等值 + 主体前缀 LIKE '主体-%'」三件套,仍不落入 %短串% 模糊分支。所有条件合并为一次 OrderExpress.findAll({ [Op.or]: ... }) 解析 order_id,无命中仍走 queryWhere.id = -1 强制空结果。", + "app/service/systems/order_packing.js:wave_no 分支支持 operator——eq/in 精确(单值等值、多值 Op.in)、ne 不等、contains/like/缺省为模糊 LIKE '%值%'(缺省保持历史模糊语义),多值模糊通过 queryWhere[Op.and] 追加 { [Op.or]: [...] } 合并。", + "list 与 export 复用同一 _buildListWhere,导出同步生效;未改任何 SQL 结构,仅条件组装方式变化。", + "验证:run/check-packing-where-contains.cjs(egg-mock 启动真实 service,只读)10/10 通过——数组+contains 命中 2 条(原上报场景原为 0 条)、单值无 operator 回归 1 条、数组+eq 2 条、不存在单号+contains 0 条、空数组等同无筛选 13 条、wave_no contains 单值 3 条/数组 4 条、wave_no in 4 条、wave_no eq 精确不模糊 0 条。" + ] + }, { "version": "2026.09.10-report-filename-time-placeholder", "date": "2026-09-10", diff --git a/methods/openapi.json b/methods/openapi.json index bb47a08..5bbc7ae 100644 --- a/methods/openapi.json +++ b/methods/openapi.json @@ -1,8 +1,8 @@ { "module": "openapi", "description": "开放 API 统一入口,独立链路,HTTP POST /openapi,记录入口校验/鉴权规则与返回格式。", - "version": "1.1.1", - "updatedAt": "2026-08-30", + "version": "1.2.3", + "updatedAt": "2026-09-12", "http": { "path": "/openapi", "method": "POST" @@ -983,7 +983,7 @@ "list": [ { "method": "order.cancel", - "description": "order 模块 取消发货单接口,支持直接取消未拣货/未打印的订单;已拣货或已打印的订单改为拦截状态", + "description": "order 模块 取消单据接口,按 orderType 分发:JYCK/HHCK/BFCK 取消发货单(wms_order_delivery,未拣货/未打印直接取消,已拣货/已打印改拦截);CK 组(PTCK/DBCK/B2BCK/QTCK/CGTH)按 orderCode 查出库单号取消出库单(wms_order_stockout,仅 CREATED/PENDING 可取消);RK 组(B2BRK/SCRK/LYRK/CCRK/CGRK/DBRK/QTRK)按 orderCode 查入库单号作废入库单(复用 ctx.service.systems.storage.entry.cancel,状态守卫 + 回退收货单占用 + 操作日志,不回传开放平台回调事件);其他类型返回暂不支持该订单类型的取消操作", "isNeedAuth": false, "isNeedLogin": false, "headers": [], @@ -993,14 +993,14 @@ "type": "string", "required": true, "source": "body", - "description": "发货单编码(必填),要取消的订单号" + "description": "单据编码(必填):JYCK/HHCK/BFCK 为发货单编码(delivery_order_code);CK 组(PTCK/DBCK/B2BCK/QTCK/CGTH)为出库单号(stockout_order_code);RK 组(B2BRK/SCRK/LYRK/CCRK/CGRK/DBRK/QTRK)为入库单号(entry_order_code)" }, { "name": "orderType", "type": "string", "required": false, "source": "body", - "description": "订单类型,默认 JYCK(一般交易出库单);当前支持 JYCK(一般交易出库)、HHCK(换货出库)、BFCK(补发出库)" + "description": "订单类型,默认 JYCK(一般交易出库单);支持 JYCK(一般交易出库)/HHCK(换货出库)/BFCK(补发出库)+ CK 组 PTCK(普通出库单)/DBCK(调拨出库)/B2BCK(B2B出库)/QTCK(其他出库)/CGTH(采购退货出库单)+ RK 组 B2BRK(B2B入库)/SCRK(生产入库)/LYRK(领用入库)/CCRK(残次品入库)/CGRK(采购入库)/DBRK(调拨入库)/QTRK(其他入库);大小写不敏感(内部 trim 后转大写)" } ], "requestBody": [ @@ -1009,14 +1009,14 @@ "type": "string", "required": true, "source": "body", - "description": "发货单编码(必填),要取消的订单号" + "description": "单据编码(必填):JYCK/HHCK/BFCK 为发货单编码(delivery_order_code);CK 组(PTCK/DBCK/B2BCK/QTCK/CGTH)为出库单号(stockout_order_code);RK 组(B2BRK/SCRK/LYRK/CCRK/CGRK/DBRK/QTRK)为入库单号(entry_order_code)" }, { "name": "orderType", "type": "string", "required": false, "source": "body", - "description": "订单类型,默认 JYCK(一般交易出库单);当前支持 JYCK(一般交易出库)、HHCK(换货出库)、BFCK(补发出库)" + "description": "订单类型,默认 JYCK(一般交易出库单);支持 JYCK(一般交易出库)/HHCK(换货出库)/BFCK(补发出库)+ CK 组 PTCK(普通出库单)/DBCK(调拨出库)/B2BCK(B2B出库)/QTCK(其他出库)/CGTH(采购退货出库单)+ RK 组 B2BRK(B2B入库)/SCRK(生产入库)/LYRK(领用入库)/CCRK(残次品入库)/CGRK(采购入库)/DBRK(调拨入库)/QTRK(其他入库);大小写不敏感(内部 trim 后转大写)" } ], "response": [ @@ -1036,13 +1036,13 @@ "name": "data", "type": "object", "required": false, - "description": "取消成功时可能包含订单状态信息" + "description": "取消成功时可能包含订单状态信息;CK 组取消成功返回 id / stockout_order_code / order_status" } ], "errors": [ { "code": 400, - "message": "订单号不能为空" + "message": "orderCode 参数缺失" }, { "code": 400, @@ -1052,16 +1052,44 @@ "code": 404, "message": "未找到对应的订单" }, + { + "code": 404, + "message": "未找到对应的出库单" + }, + { + "code": 400, + "message": "出库单当前状态(xxx)不允许取消(仅 CREATED/PENDING 可取消)" + }, + { + "code": 400, + "message": "取消失败:xxx(CK 组释放库存锁定等异常)" + }, { "code": 409, "message": "取消失败,已通知拦截执行(订单已拣货或已打印,改为拦截状态)" + }, + { + "code": 0, + "message": "未找到对应的入库单" + }, + { + "code": 0, + "message": "已完成入库单不允许作废" + }, + { + "code": 0, + "message": "入库单已完成回传,不可取消" } ], "notes": [ "模块:order 模块", "方法部署位置:openapiMethods/order.cancel", - "取消逻辑:未拣货且未打印的订单直接取消(status=cancel, outbound_status=fin, step=4);已拣货或已打印的订单标记为拦截状态(intercept_status=intercepting),不直接取消", - "订单类型映射:JYCK/HHCK/BFCK → 出库单取消;其他类型暂不支持", + "JYCK/HHCK/BFCK 取消逻辑:未拣货且未打印的订单直接取消(status=cancel, outbound_status=fin, step=4);已拣货或已打印的订单标记为拦截状态(intercept_status=intercepting),不直接取消", + "订单类型映射:JYCK/HHCK/BFCK → wms_order_delivery 发货单取消(行为与历史完全一致);PTCK/DBCK/B2BCK/QTCK/CGTH(CK 组)→ wms_order_stockout 出库单取消(按 orderCode 查出库单号);B2BRK/SCRK/LYRK/CCRK/CGRK/DBRK/QTRK(RK 组)→ 入库单作废(按 orderCode 查入库单号,复用 ctx.service.systems.storage.entry.cancel);其他类型返回暂不支持该订单类型的取消操作", + "CK 组委托 ctx.service.systems.stockoutOrder.cancel(单事务 + 行锁):仅 CREATED/PENDING 允许取消(COMPLETED/TRANSFERRED 拒绝),释放 QM_STOCKOUT 库存锁定,状态置 CANCELLED 并写 wms_operation_log(STOCKOUT_CANCEL);已 CANCELLED 幂等返回成功;取消成功不回传开放平台回调事件", + "RK 组委托 ctx.service.systems.storage.entry.cancel({ entryOrderCode }, { storeId, warehouseId, operatorLabel=openapi:xxx, skipExternalSync=true, idempotent=true, notFoundMessage=未找到对应的入库单 }):守卫 sync_status=SUCCESS(入库单已完成回传,不可取消)、order_status=COMPLETED(已完成入库单不允许作废);已 CANCELLED 幂等返回成功;作废动作 = 状态置 CANCELLED + 按台账回退关联收货单占用 + 写 ENTRY_ORDER_CANCEL 操作日志;skipExternalSync=true 不回传开放平台回调事件", + "复现口径:orderCode=RK_2、orderType=CGRK 现在可正常取消(此前返回暂不支持该订单类型的取消操作)", + "orderType 大小写不敏感:内部 trim 后转大写,jyck/Jyck/JYCK 等价", "使用事务 + 行锁保证并发安全", "取消操作为不可逆操作,请谨慎调用", "timestamp 时间戳时效校验:与服务器时间差不得超过 ±10 分钟(600 秒),否则返回 400" @@ -1915,6 +1943,333 @@ ] } ] + }, + { + "groupName": "出库单模块", + "module": "stockout", + "list": [ + { + "method": "stockout.create", + "description": "stockout 模块 创建非订单出库单接口,支持传入出库单主信息、收件人信息和出库明细;创建时按计划数量锁定库存", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "deliveryOrder", + "type": "object", + "required": true, + "source": "body", + "description": "出库单主信息对象" + }, + { + "name": "deliveryOrder.deliveryOrderCode", + "type": "string", + "required": true, + "source": "body", + "description": "出库单号(必填),外部系统唯一单号,落库 wms_order_stockout.stockout_order_code" + }, + { + "name": "deliveryOrder.orderType", + "type": "string", + "required": true, + "source": "body", + "description": "业务类型(必填):JYCK 一般交易出库 / HHCK 换货出库 / BFCK 补发出库 / QTCK 其他出库" + }, + { + "name": "deliveryOrder.warehouseCode", + "type": "string", + "required": false, + "source": "body", + "description": "仓库编码,不传时使用 app_key 合约绑定的仓库编码" + }, + { + "name": "deliveryOrder.createTime", + "type": "string", + "required": false, + "source": "body", + "description": "单据创建时间,落库 order_create_time" + }, + { + "name": "deliveryOrder.totalOrderLines", + "type": "integer", + "required": false, + "source": "body", + "description": "单据总行数,不传时取明细行数" + }, + { + "name": "deliveryOrder.remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注" + }, + { + "name": "deliveryOrder.logisticsCode", + "type": "string", + "required": false, + "source": "body", + "description": "外部快递编码;货主开启 enable_external_express_code 时按快递设置表 → 系统快递列表匹配,匹配不到使用出库单兜底快递编码(stockout_default_express_code,默认 ZT 自提)" + }, + { + "name": "deliveryOrder.receiverInfo", + "type": "object", + "required": false, + "source": "body", + "description": "收件人信息对象,13 个标准字段落库 receiver_* 列,供转订单与确认回传使用" + }, + { + "name": "deliveryOrder.receiverInfo.name", + "type": "string", + "required": false, + "source": "body", + "description": "收件人姓名(receiver_name)" + }, + { + "name": "deliveryOrder.receiverInfo.company", + "type": "string", + "required": false, + "source": "body", + "description": "收件人公司名称(receiver_company)" + }, + { + "name": "deliveryOrder.receiverInfo.zipCode", + "type": "string", + "required": false, + "source": "body", + "description": "收件人邮编(receiver_zip_code)" + }, + { + "name": "deliveryOrder.receiverInfo.tel", + "type": "string", + "required": false, + "source": "body", + "description": "收件人固定电话(receiver_tel)" + }, + { + "name": "deliveryOrder.receiverInfo.mobile", + "type": "string", + "required": false, + "source": "body", + "description": "收件人移动电话(receiver_mobile)" + }, + { + "name": "deliveryOrder.receiverInfo.email", + "type": "string", + "required": false, + "source": "body", + "description": "收件人邮箱(receiver_email)" + }, + { + "name": "deliveryOrder.receiverInfo.countryCode", + "type": "string", + "required": false, + "source": "body", + "description": "国家编码(receiver_country_code)" + }, + { + "name": "deliveryOrder.receiverInfo.province", + "type": "string", + "required": false, + "source": "body", + "description": "省(receiver_province)" + }, + { + "name": "deliveryOrder.receiverInfo.city", + "type": "string", + "required": false, + "source": "body", + "description": "市(receiver_city)" + }, + { + "name": "deliveryOrder.receiverInfo.area", + "type": "string", + "required": false, + "source": "body", + "description": "区/县(receiver_area)" + }, + { + "name": "deliveryOrder.receiverInfo.town", + "type": "string", + "required": false, + "source": "body", + "description": "镇/街道(receiver_town)" + }, + { + "name": "deliveryOrder.receiverInfo.detailAddress", + "type": "string", + "required": false, + "source": "body", + "description": "详细地址(receiver_detail_address)" + }, + { + "name": "deliveryOrder.receiverInfo.id", + "type": "string", + "required": false, + "source": "body", + "description": "收件人证件号(receiver_id)" + }, + { + "name": "orderLines", + "type": "object", + "required": true, + "source": "body", + "description": "出库单明细对象" + }, + { + "name": "orderLines.orderLine", + "type": "object/array", + "required": true, + "source": "body", + "description": "明细行(单条为对象,多条为数组)" + }, + { + "name": "orderLines.orderLine.orderLineNo", + "type": "string", + "required": true, + "source": "body", + "description": "订单行号(必填)" + }, + { + "name": "orderLines.orderLine.ownerCode", + "type": "string", + "required": false, + "source": "body", + "description": "货主编码,落库 qimen_owner_code(取首行)" + }, + { + "name": "orderLines.orderLine.itemCode", + "type": "string", + "required": true, + "source": "body", + "description": "商品编码(必填),itemId 主键查不到时按此编码 + 仓库货主维度降级匹配" + }, + { + "name": "orderLines.orderLine.itemId", + "type": "string", + "required": true, + "source": "body", + "description": "WMS 商品ID(必填),优先按 StockStore 主键直查(校验货主一致)" + }, + { + "name": "orderLines.orderLine.itemName", + "type": "string", + "required": false, + "source": "body", + "description": "商品名称,仅用于错误提示与明细展示" + }, + { + "name": "orderLines.orderLine.planQty", + "type": "integer", + "required": true, + "source": "body", + "description": "计划数量(必填,需大于 0),创建时按此数量锁定库存" + }, + { + "name": "orderLines.orderLine.inventoryType", + "type": "string", + "required": false, + "source": "body", + "description": "库存类型(ZP 正品 / CC 残次等)" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:1=成功,0=失败" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示消息" + }, + { + "name": "data", + "type": "object", + "required": false, + "description": "创建成功时返回 stockoutOrderId(出库单ID)、stockoutOrderCode(出库单号)" + } + ], + "errors": [ + { + "code": 400, + "message": "deliveryOrder 参数缺失或不完整 / orderLines 参数缺失" + }, + { + "code": 400, + "message": "创建出库单失败,失败原因:没有有效的订单明细数据 / 商品未同步推送到仓库 / wms无对应关系 / 计划数量必须大于0 / 库存锁定失败" + } + ], + "notes": [ + "模块:出库单模块", + "方法部署位置:openapiMethods/stockout.create → systems/stockout_order.create", + "与奇门 stockout.create 共用同一份实现(systems/stockout_order.js),差异仅在来源:开放 API 落库 source_type=API,奇门落库 source_type=QM", + "出库单落库 wms_order_stockout + wms_order_stockout_items,创建时在事务内按 planQty 锁定库存(锁标记 QM_STOCKOUT,与取消/确认/转单释放口径一致)", + "商品匹配:itemId 按 StockStore 主键直查(校验货主一致),查不到或跨货主时按 itemCode + 仓库 + 货主降级匹配", + "快递解析:货主开启 enable_external_express_code 且传 logisticsCode 时按快递设置表 → 系统快递列表匹配;未传/未开启/匹配不到使用出库单兜底快递编码 stockout_default_express_code(默认 ZT 自提),不回退订单默认快递", + "orderLines.orderLine 支持单对象或数组格式", + "收货信息(name / tel|mobile / 省市区镇详细地址)在转订单或一键出库确认时校验必填,创建时不强制", + "timestamp 时间戳时效校验:与服务器时间差不得超过 ±10 分钟(600 秒),否则返回 400" + ] + }, + { + "method": "stockout.query", + "description": "stockout 模块 查询非订单出库单接口,按出库单号返回主表信息与商品明细", + "isNeedAuth": false, + "isNeedLogin": false, + "headers": [], + "params": [ + { + "name": "deliveryOrderCode", + "type": "string", + "required": true, + "source": "body", + "description": "出库单号(必填),要查询的出库单 stockout_order_code;兼容 deliveryOrder.deliveryOrderCode 传法" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:1=成功,0=失败" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示消息" + }, + { + "name": "data", + "type": "object", + "required": false, + "description": "查询成功时返回 totalLines、deliveryOrder(deliveryOrderCode/deliveryOrderId/warehouseCode/orderType/status/createTime/remark)、orderLines.orderLine[](orderLineNo/ownerCode/itemCode/itemId/itemName/planQty/inventoryType)" + } + ], + "errors": [ + { + "code": 400, + "message": "deliveryOrderCode 参数缺失" + }, + { + "code": 404, + "message": "未找到出库单" + } + ], + "notes": [ + "模块:出库单模块", + "方法部署位置:openapiMethods/stockout.query → systems/stockout_order.query", + "与奇门 stockout.query 共用同一份实现(systems/stockout_order.js)", + "按 stockout_order_code 查 wms_order_stockout 主表,再按 order_id 关联 wms_order_stockout_items 明细(按 order_line_no 升序)", + "deliveryOrder.status 为出库单状态:CREATED 已创建 / PENDING 已审核 / COMPLETED 已完成 / CANCELLED 已作废 / TRANSFERRED 已转订单", + "timestamp 时间戳时效校验:与服务器时间差不得超过 ±10 分钟(600 秒),否则返回 400" + ] + } + ] } ] } diff --git a/methods/qimen.json b/methods/qimen.json index 5dd6cee..ea7ec7e 100644 --- a/methods/qimen.json +++ b/methods/qimen.json @@ -1,8 +1,8 @@ { "module": "qimen", "description": "奇门接口标准入口,method 对应 qimenMethods 异步方法,全部使用 POST 请求,参数包含 query 与 XML body(request 节点)", - "version": "0.3.7", - "updatedAt": "2026-08-30", + "version": "0.3.10", + "updatedAt": "2026-09-12", "headers": [], "methods": { "groups": [ @@ -593,7 +593,7 @@ "list": [ { "method": "order.cancel", - "description": "order.cancel 接口", + "description": "取消单据接口。按 request.orderType 匹配作业类型分发:ORDER 组(JYCK/HHCK/BFCK)取消发货单(未拣货且未打印直接取消,已拣货/已打印/已同步转拦截);RK 组(B2BRK/SCRK/LYRK/CCRK/CGRK/DBRK/QTRK)委托 ctx.service.systems.storage.entry.cancel 完整作废流程取消入库单(状态守卫 + 状态置 CANCELLED + 按台账回退关联收货单占用 + 写 ENTRY_ORDER_CANCEL 操作日志,不回传奇门事件);CK 组(PTCK/DBCK/B2BCK/QTCK/CGTH)按出库单号取消出库单(wms_order_stockout,仅 CREATED/PENDING 可取消,释放 QM_STOCKOUT 锁定);JG/BACKORDER 组均未开发完成,返回对应提示", "isNeedAuth": false, "isNeedLogin": false, "headers": [], @@ -652,29 +652,116 @@ "type": "object", "required": true, "source": "body", - "description": "request XML 节点" + "description": "request XML 节点,包含 orderCode 与 orderType 字段" }, { "name": "request.orderCode", "type": "string", "required": false, "source": "body", - "description": "request.orderCode 参数" + "description": "单据编码:ORDER 组为发货单号(delivery_order_code),RK 组为入库单号(entry_order_code),CK 组为出库单号(stockout_order_code)" }, { "name": "request.orderType", "type": "string", "required": false, "source": "body", - "description": "request.orderType 参数" + "description": "作业类型枚举(按 orderType → 作业类型分发):ORDER 组(取消发货单,已实现):JYCK=一般交易出库单、HHCK=换货出库、BFCK=补发出库;RK 组(取消入库单,已实现,委托 ctx.service.systems.storage.entry.cancel 完整作废流程:守卫 COMPLETED/sync_status=SUCCESS、状态置 CANCELLED、按台账回退关联收货单占用、写 ENTRY_ORDER_CANCEL 操作日志,不回传奇门事件):B2BRK=B2B入库、SCRK=生产入库、LYRK=领用入库、CCRK=残次品入库、CGRK=采购入库、DBRK=调拨入库、QTRK=其他入库;CK 组(取消出库单,已实现,按出库单号查 wms_order_stockout,仅 CREATED/PENDING 可取消):PTCK=普通出库单、DBCK=调拨出库、B2BCK=B2B出库、QTCK=其他出库、CGTH=采购退货出库单;JG 组(未开发,返回取消加工单未开发完成):CNJG=仓内加工单;BACKORDER 组(未开发,返回取消退货单未开发完成):XTRK=销退入库、THRK=退货入库、HHRK=换货入库。枚举之外的值无法匹配作业类型,接口返回失败" } ], - "response": [], - "errors": [] + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "success=成功,failure=失败" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "1=成功,0=失败" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息(如:取消订单成功、取消入库单成功、取消出库单成功、取消失败,已通知拦截执行)" + } + ], + "errors": [ + { + "code": 0, + "message": "订单号不能为空" + }, + { + "code": 0, + "message": "未找到对应的订单" + }, + { + "code": 0, + "message": "入库单号不能为空" + }, + { + "code": 0, + "message": "未找到对应的入库单" + }, + { + "code": 0, + "message": "已完成入库单不允许作废" + }, + { + "code": 0, + "message": "入库单已完成回传,不可取消" + }, + { + "code": 0, + "message": "取消失败,已通知拦截执行" + }, + { + "code": 0, + "message": "订单已同步,不可取消,已转为拦截处理" + }, + { + "code": 0, + "message": "出库单号不能为空" + }, + { + "code": 0, + "message": "未找到对应的出库单" + }, + { + "code": 0, + "message": "出库单当前状态(xxx)不允许取消(仅 CREATED/PENDING 可取消)" + }, + { + "code": 0, + "message": "取消失败:xxx(释放库存锁定等异常)" + }, + { + "code": 0, + "message": "取消加工单未开发完成" + }, + { + "code": 0, + "message": "取消退货单未开发完成" + } + ], + "notes": [ + "入口:app/service/qimenMethods/order.js cancel,通过 switch (orderType.method) 分发;入参 request.orderCode(单据编码)+ request.orderType(作业类型枚举)", + "ORDER 组取消逻辑与 openapi 一致:未拣货且未打印直接取消(status=cancel, outbound_status=fin, step=4);已拣货或已打印改为拦截(intercept_status=intercepting),返回取消失败,已通知拦截执行", + "已同步订单(sync_status=fin)转拦截(intercept_status=requested),返回订单已同步,不可取消,已转为拦截处理", + "团购单已复核/散单已称重时不写入拦截请求状态,返回订单已复核/已称重,无法拦截(取消)执行,已转快递拦截", + "RK 组:空单号返回入库单号不能为空;委托 ctx.service.systems.storage.entry.cancel({ entryOrderCode }, { storeId, warehouseId, operatorLabel=qimen:xxx, skipExternalSync=true, idempotent=true, notFoundMessage=未找到对应的入库单 });守卫 sync_status=SUCCESS 返回入库单已完成回传,不可取消、order_status=COMPLETED 返回已完成入库单不允许作废;已 CANCELLED 幂等返回取消入库单成功(外部渠道重试口径);作废动作 = 状态置 CANCELLED + 按台账回退关联收货单占用(重算 storage_status)+ 写 ENTRY_ORDER_CANCEL 操作日志;skipExternalSync=true 全程不触发 qimenEntrySync,取消成功不回传奇门事件;未找到返回未找到对应的入库单;共享实现的 QM 回传失败分支文案为取消失败: xxx(RK 渠道 skipExternalSync=true 不触发回传,该分支不会出现)", + "CK 组:委托 ctx.service.systems.stockoutOrder.cancel(共享实现,单事务 + 行锁),按出库单号查 wms_order_stockout;仅 CREATED/PENDING 允许取消(COMPLETED/TRANSFERRED 拒绝),释放 QM_STOCKOUT 库存锁定(写 UNLOCK 流水,「释放数量超过已锁定库存」视为幂等跳过),状态置 CANCELLED 并写 wms_operation_log(business_type=stockout,operation_code=STOCKOUT_CANCEL);已 CANCELLED 幂等返回取消出库单成功;取消成功不向奇门回传任何事件", + "JG/BACKORDER 组:分别返回取消加工单未开发完成、取消退货单未开发完成", + "已取消订单(status=cancel)走幂等分支返回取消订单成功;未找到订单返回未找到对应的订单", + "响应为奇门 XML 结构(flag/code/message),code=1 成功、code=0 失败" + ] }, { "method": "order.pending", - "description": "order.pending 接口", + "description": "锁定单据接口(占位)。按 request.orderType 匹配作业类型分发,当前所有作业类型(ORDER/RK/CK/JG/BACKORDER)均未开发完成,统一返回锁定XX未开发完成", "isNeedAuth": false, "isNeedLogin": false, "headers": [], @@ -733,25 +820,70 @@ "type": "object", "required": true, "source": "body", - "description": "request XML 节点" + "description": "request XML 节点,包含 orderCode 与 orderType 字段" }, { "name": "request.orderCode", "type": "string", "required": false, "source": "body", - "description": "request.orderCode 参数" + "description": "单据编码(发货单号/入库单号,视 orderType 作业类型而定)" }, { "name": "request.orderType", "type": "string", "required": false, "source": "body", - "description": "request.orderType 参数" + "description": "作业类型枚举(与 order.cancel 一致):ORDER 组:JYCK=一般交易出库单、HHCK=换货出库、BFCK=补发出库;RK 组:B2BRK=B2B入库、SCRK=生产入库、LYRK=领用入库、CCRK=残次品入库、CGRK=采购入库、DBRK=调拨入库、QTRK=其他入库;CK 组:PTCK=普通出库单、DBCK=调拨出库、B2BCK=B2B出库、QTCK=其他出库、CGTH=采购退货出库单;JG 组:CNJG=仓内加工单;BACKORDER 组:XTRK=销退入库、THRK=退货入库、HHRK=换货入库。当前所有类型均未开发完成,返回锁定XX未开发完成" } ], - "response": [], - "errors": [] + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "success=成功,failure=失败(当前所有分支均返回 failure)" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "1=成功,0=失败" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息(锁定订单/入库单/出库单/加工单/退货单未开发完成)" + } + ], + "errors": [ + { + "code": 0, + "message": "锁定订单未开发完成" + }, + { + "code": 0, + "message": "锁定入库单未开发完成" + }, + { + "code": 0, + "message": "锁定出库单未开发完成" + }, + { + "code": 0, + "message": "锁定加工单未开发完成" + }, + { + "code": 0, + "message": "锁定退货单未开发完成" + } + ], + "notes": [ + "入口:app/service/qimenMethods/order.js pending,通过 switch (orderType.method) 分发;入参 request.orderCode + request.orderType(枚举同 order.cancel)", + "当前所有作业类型分支均未实现,统一返回锁定XX未开发完成(flag=failure、code=0)", + "枚举之外的值无法匹配作业类型,接口返回失败" + ] } ] }, diff --git a/methods/system.json b/methods/system.json index d53be91..ba5be3f 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,8 +1,8 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.110", - "updatedAt": "2026-09-10", + "version": "0.3.115", + "updatedAt": "2026-09-12", "headers": [ { "name": "platform", @@ -7097,13 +7097,13 @@ "name": "waybill_code", "type": "string", "required": false, - "description": "运单号。通过 wms_order_express 表解析 order_id 后按订单过滤(wms_pack_task.waybill_code 通常为空)。匹配规则(不再支持部分单号模糊匹配):①完整单号等值匹配;②剥离一单多件包裹序号分段后缀(如 -1-1-)后的主体单号等值匹配;③主体单号前缀匹配(LIKE '主体-%',同主体不同分段序号,通配符已转义)。无任何匹配时返回空列表" + "description": "运单号。通过 wms_order_express 表解析 order_id 后按订单过滤(wms_pack_task.waybill_code 通常为空)。支持 {operator,value} 标准结构,value 支持字符串或字符串数组(多单号取并集):operator=contains/like 时按 LIKE '%单号%' 模糊匹配(通配符已转义,可命中 '主体-1-1-' 等分段单号);缺省或 operator=eq 时按①完整单号等值匹配;②剥离一单多件包裹序号分段后缀(如 -1-1-)后的主体单号等值匹配;③主体单号前缀匹配(LIKE '主体-%',同主体不同分段序号,通配符已转义)。无任何匹配时返回空列表" }, { "name": "wave_no", "type": "string", "required": false, - "description": "波次号(模糊匹配)" + "description": "波次号。支持 {operator,value} 标准结构,value 支持字符串或字符串数组(多值取并集):operator=eq/in 精确匹配(单值等值、多值 IN),operator=ne 不等于,operator=contains/like 与缺省(不传 operator)为模糊匹配(LIKE '%值%',通配符已转义)" }, { "name": "order_id", @@ -23189,7 +23189,7 @@ }, { "method": "storage.entry.cancel", - "description": "作废入库单(支持单条或批量作废)。CREATED(已创建待审核)和 PENDING(已审核)状态的入库单可以直接作废;已完成(COMPLETED)入库单不允许作废,sync_status=SUCCESS(已完成回传)的入库单也不允许作废;QM 来源入库单作废前先发送奇门取消同步。作废成功后按绑定行数量台账(wms_entry_order_receiving.allocated_quantity,旧数据按收货侧累计量兜底)逐绑定回收本入库单在收货单上的 stored_quantity 占用、重算各收货单 storage_status、清空台账(绑定行保留不软删),并同步重算入库单明细 received_quantity;同一收货单上其他入库单的占用不受影响(不再整体清零共享收货单);回滚失败不阻塞作废主流程(仅记录日志)。", + "description": "作废入库单(支持单条或批量作废)。CREATED(已创建待审核)和 PENDING(已审核)状态的入库单可以直接作废;已完成(COMPLETED)入库单不允许作废,sync_status=SUCCESS(已完成回传)的入库单也不允许作废;QM 来源入库单作废前先发送奇门取消同步。作废成功后按绑定行数量台账(wms_entry_order_receiving.allocated_quantity,旧数据按收货侧累计量兜底)逐绑定回收本入库单在收货单上的 stored_quantity 占用、重算各收货单 storage_status、清空台账(绑定行保留不软删),并同步重算入库单明细 received_quantity;同一收货单上其他入库单的占用不受影响(不再整体清零共享收货单);回滚失败不阻塞作废主流程(仅记录日志)。另支持按 entryOrderCode(兼容别名 entry_order_code)按单号定位入库单,供奇门/openapi 外部渠道复用(外部渠道经此复用同一作废流程并透传 skipExternalSync/idempotent/notFoundMessage 等内部选项);本渠道 id/ids 入参、响应结构与失败文案不变。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -23214,6 +23214,13 @@ "required": false, "source": "body", "description": "入库单ID数组(number[]),用于批量作废;必须为非空数组,建议批量操作使用 ids,优先于 id。" + }, + { + "name": "entryOrderCode", + "type": "string", + "required": false, + "source": "body", + "description": "入库单号(可选,内部复用口径):传入时按 entry_order_code 定位(兼容别名 entry_order_code,定位条件含 warehouse_id + is_enabled=1 + deleted_at=null),优先于 id/ids;供奇门/openapi 外部渠道复用,系统方法入口可继续使用 id/ids,行为与文案不变" } ], "response": [ @@ -25041,7 +25048,7 @@ { "method": "storage.stockout.cancel", "name": "出库单取消", - "description": "取消出库单:仅 CREATED/PENDING 状态允许取消;事务内释放创建时占用的库存锁定(QM_STOCKOUT,写 UNLOCK 流水),状态置为 CANCELLED,并写 wms_operation_log 操作日志(STOCKOUT_CANCEL)。TRANSFERRED(已转订单)与 COMPLETED(已完成)状态禁止取消。", + "description": "取消出库单:仅 CREATED/PENDING 状态允许取消;事务内释放创建时占用的库存锁定(QM_STOCKOUT,写 UNLOCK 流水),状态置为 CANCELLED,并写 wms_operation_log 操作日志(STOCKOUT_CANCEL)。TRANSFERRED(已转订单)与 COMPLETED(已完成)状态禁止取消。实现委托共享服务 systems/stockout_order.js#cancel(奇门 / openapi 同口径:单事务 + 行锁,并发取消/确认/转单更安全,已 CANCELLED 幂等返回成功)。", "isNeedAuth": true, "isNeedLogin": true, "isNeedRight": false, @@ -25084,8 +25091,20 @@ ], "errors": [ { - "code": "400", - "description": "缺少出库单ID / 出库单不存在 / 状态不允许取消 / 释放锁定失败" + "code": 400, + "message": "缺少出库单ID" + }, + { + "code": 400, + "message": "缺少仓库上下文" + }, + { + "code": 404, + "message": "出库单不存在" + }, + { + "code": 400, + "message": "出库单当前状态(xxx)不允许取消(仅 CREATED/PENDING 可取消)" } ] } @@ -26202,6 +26221,72 @@ "message": "系统异常" } ] + }, + { + "method": "storage.inventory.listBySpaceId", + "name": "按库位查询有量库存商品列表", + "description": "按库位查询库存商品列表:传入 space_id,先判断该库位是否为当前仓库的库位(不存在返回 404,存在但不属于当前仓库返回 400),是则返回该库位下有量库存(quantity > 0)的商品列表。列表按商品(stock_id)汇总为一条:每项含 warehouse_id/store_id/space_id/space_code/space_name/stock_id/quantity/locked_quantity/intercept_locked_quantity/available_quantity(汇总数量)/batch_count(批次数)/first_inbound_time(最早入库时间)/last_inbound_time(最晚入库时间)。商品信息使用 stock_warehouse 通用属性返回(stock 对象,由 getStockDetails 通用链路提供:id/item_code/item_name/sku_property/quantity/locked_quantity/is_batch_mgmt/is_shelf_life_mgmt/is_images/need_recheck/store_id/packing_requirements/stock_unit/barcodes(条码数组)/image_url(图片数组);未命中时为 null);顶层 store_name 为货主名称(当前仓库签约表 store_remask,未命中为 null)。该库位无有量库存时 list 为空数组。仓库上下文来自当前登录用户(ctx.user.store_id)。", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "headers": [], + "params": [ + { + "name": "space_id", + "type": "number", + "required": true, + "source": "body", + "description": "库位ID(wms_location_space.id,必填)" + } + ], + "response": [ + { + "name": "code", + "type": "number", + "required": true, + "description": "状态码,200=成功" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "结果说明" + }, + { + "name": "data.space", + "type": "object", + "required": true, + "description": "库位信息:id(库位ID)、warehouse_id(所属仓库ID)、space_code(库位编码)、custom_name(自定义名称)、space_status(库位状态)" + }, + { + "name": "data.list", + "type": "array", + "required": true, + "description": "该库位下有量库存(quantity > 0,按 id 倒序查询后汇总)的商品数组,每项字段:warehouse_id、store_id、space_id、stock_id、quantity(汇总数量)、locked_quantity(汇总锁定数量)、intercept_locked_quantity(汇总拦截锁定数量)、available_quantity(汇总可用数量)、batch_count(批次数)、first_inbound_time(最早入库时间,空为 '')、last_inbound_time(最晚入库时间,空为 '')、space_code(库位编码)、space_name(custom_name 优先,否则 space_code)、store_name(货主名称)、stock(stock_warehouse 通用属性对象:id/item_code/item_name/sku_property/quantity/locked_quantity/is_batch_mgmt/is_shelf_life_mgmt/is_images/need_recheck/store_id/packing_requirements/stock_unit/barcodes/image_url;商品详情未命中时为 null)。该库位无有量库存时为空数组 []" + } + ], + "errors": [ + { + "code": 400, + "message": "space_id 必填且必须为正整数" + }, + { + "code": 400, + "message": "无法获取当前仓库信息" + }, + { + "code": 400, + "message": "库位 {space_id} 不属于当前仓库" + }, + { + "code": 404, + "message": "库位不存在: space_id={space_id}" + }, + { + "code": 500, + "message": "系统异常" + } + ] } ] }, @@ -30333,7 +30418,7 @@ "list": [ { "method": "order.wave.batchList", - "description": "波次列表查询。仅使用当前登录操作者仓库上下文(禁止传入 warehouse_id/warehouseId)。支持 where 白名单过滤,固定查询 wave_status=0/1;返回波次基础信息及分配状态汇总(storage_assignment_status / express_assignment_status / print_assignment_status / pick_assignment_status / review_assignment_status)。支持 only_todo=1 仅返回仍有未复核订单的波次,并返回复核状态汇总(review_assignment_status)与未复核数量(unreviewed_order_count)。列表每条记录返回货主信息 store_name:当波次内所有订单均为同一货主(store_id)时返回货主名称,否则返回“混合”。货主名称优先取合约表 wms_store_warehouse.store_remask(货主备注名称),无合约或备注为空时回退 wms_store.company_name(公司全称)。", + "description": "波次列表查询。仅使用当前登录操作者仓库上下文(禁止传入 warehouse_id/warehouseId)。支持 where 白名单过滤,固定查询 wave_status=0/1;返回波次基础信息及分配状态汇总(storage_assignment_status / express_assignment_status / print_assignment_status / pick_assignment_status / review_assignment_status)。支持 only_todo=1 仅返回仍有未复核订单的波次,并返回复核状态汇总(review_assignment_status)与未复核数量(unreviewed_order_count)。列表每条记录返回货主信息 store_name:当波次内所有订单均为同一货主(store_id)时返回货主名称,否则返回“混合”。货主名称优先取合约表 wms_store_warehouse.store_remask(货主备注名称),无合约或备注为空时回退 wms_store.company_name(公司全称)。where 中各字段支持裸值与 {operator,value,type} 标准结构(eq/ne/gt/lt/ge/le/in/notin/between/notbetween/like/contains/notlike/startswith/endswith/isnull/isnotnull;未显式传 operator 时保持历史默认语义:wave_no/creator/logistics_name/item_part/item_snapshot_key/item_detail_machine 默认模糊,其余默认等值),详见 where 参数说明。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -30364,7 +30449,7 @@ "type": "object", "required": false, "source": "body", - "description": "筛选白名单字段(object,可选)。仅支持下列字段过滤,且禁止传入 warehouse_id / warehouseId:\n- wave_id(等值)\n- wave_no(模糊)\n- wave_type(等值)\n- wave_status(等值,接口固定叠加状态 0/1)\n- creator(模糊)\n- logistics_name(模糊)\n- item_part_type(等值)\n- item_part(模糊)\n- item_snapshot_key(模糊)\n- item_detail_machine(模糊)\n- distinguish_express(等值)\n- total_orders_min / total_orders_max(范围)\n- processed_orders_min / processed_orders_max(范围)\n- express_assignment_status(等值,string,可选,英文枚举,取值:unassigned、partially_assigned、assigned;语义:按快递分配聚合判断,assigned 表示聚合后全部 fin,partially_assigned 表示部分已分配且不含 error,unassigned 表示全 none 或包含 error(异常并入未分配集合))。\n- print_assignment_status(等值,string,可选,英文枚举,取值:unprinted、partially_printed、printed;语义:按打印分配聚合判断,printed 表示聚合后全部已打印)。\n- storage_assignment_status(等值,string,可选,取值:未分配、部分分配、已分配;默认不传不做限制)。过滤语义:已分配=聚合后全部 fin;部分分配=不含 error,且既不是全 none,也不是全 fin;未分配=全 none 或包含 error(异常并入未分配筛选集合)。说明:返回字段 storage_assignment_status 的展示值保持不变,包含 error 时仍可显示“分配异常”;此处 where 的过滤语义会把异常计入“未分配”,以避免把过滤语义与展示值混淆。\n- source(可选,number)来源过滤:0=普通波次(正常后台操作),1=管理后台策略任务,2=PDA策略任务;不传则不过滤。\n说明:express_assignment_status 与 print_assignment_status 要求使用英文枚举值;storage_assignment_status 仍向后兼容中文展示值。若传入的枚举值不在允许集合内,接口会返回 400(参数校验失败),并在 message 中说明错误字段与允许取值。\n- review_assignment_status(等值,string,可选,英文枚举:unreviewed、partially_reviewed、reviewed;分别表示未复核、部分复核、已复核)。\n- store_id(货主ID,可选,正整数,支持单值/数组/{operator,value} 结构,如 {\"operator\":\"\",\"value\":[1000281,1000000]};语义:返回包含任一筛选货主订单的波次,含混合货主波次;单值与数组均按 in 匹配)。" + "description": "筛选白名单字段(object,可选)。仅支持下列字段过滤,且禁止传入 warehouse_id / warehouseId。\n【操作符传参】每个字段均支持「裸值」或「标准结构 {'operator':'eq','value':'...','type':'text'}」两种写法;未显式传 operator 时按该字段默认语义(见下方括号)。支持的操作符:eq、ne、gt、lt、ge、le、in、notin、between、notbetween、like、contains、notlike、startswith、endswith、isnull、isnotnull,按字段分组允许:\n- 数值类(wave_id、wave_type、wave_status、source、total_orders、processed_orders 及 total_orders_min/max、processed_orders_min/max):eq/ne/gt/lt/ge/le/in/notin/between/notbetween/isnull/isnotnull;\n- 文本类(wave_no、creator、logistics_name、item_part_type、item_part、item_snapshot_key、item_detail_machine):eq/ne/like/contains/notlike/startswith/endswith/in/notin/isnull/isnotnull;\n- 布尔类(distinguish_express):eq/ne/in/notin;\n- 分配/复核状态类(storage_assignment_status、express_assignment_status、print_assignment_status、review_assignment_status):仅 eq;\n- 货主(store_id):eq/in/ne/notin。\nvalue 支持数组:like/contains/startswith/endswith 多值按 OR 展开,notlike 多值按 AND 展开;in/notin 要求 value 为非空数组;eq 传数组等价于 in;between/notbetween 要求 value 为长度 2 的数组(也接受 {start,end} / {from,to})。\n【字段清单】(括号内为未显式传 operator 时的默认语义)\n- wave_id(等值)\n- wave_no(模糊)\n- wave_type(等值)\n- wave_status(等值,接口固定叠加状态 0/1)\n- creator(模糊)\n- logistics_name(模糊)\n- item_part_type(等值)\n- item_part(模糊)\n- item_snapshot_key(模糊)\n- item_detail_machine(模糊)\n- distinguish_express(等值,value 兼容 true/false/1/0)\n- total_orders / processed_orders(等值,新增:波次订单总数/已处理数,可直接用 between 等操作符)\n- total_orders_min / total_orders_max(范围,等价于 total_orders 的 ge / le)\n- processed_orders_min / processed_orders_max(范围,等价于 processed_orders 的 ge / le)\n- express_assignment_status(等值,string,可选,英文枚举,取值:unassigned、partially_assigned、assigned;语义:按快递分配聚合判断,assigned 表示聚合后全部 fin,partially_assigned 表示部分已分配且不含 error,unassigned 表示全 none 或包含 error(异常并入未分配集合))。\n- print_assignment_status(等值,string,可选,英文枚举,取值:unprinted、partially_printed、printed;语义:按打印分配聚合判断,printed 表示聚合后全部已打印)。\n- storage_assignment_status(等值,string,可选,取值:未分配、部分分配、已分配;默认不传不做限制)。过滤语义:已分配=聚合后全部 fin;部分分配=不含 error,且既不是全 none,也不是全 fin;未分配=全 none 或包含 error(异常并入未分配筛选集合)。说明:返回字段 storage_assignment_status 的展示值保持不变,包含 error 时仍可显示“分配异常”;此处 where 的过滤语义会把异常计入“未分配”,以避免把过滤语义与展示值混淆。\n- source(可选,number)来源过滤:0=普通波次(正常后台操作),1=管理后台策略任务,2=PDA策略任务;不传则不过滤。\n说明:express_assignment_status 与 print_assignment_status 要求使用英文枚举值;storage_assignment_status 仍向后兼容中文展示值。若传入的枚举值不在允许集合内,接口会返回 400(参数校验失败),并在 message 中说明错误字段与允许取值。\n- review_assignment_status(等值,string,可选,英文枚举:unreviewed、partially_reviewed、reviewed;分别表示未复核、部分复核、已复核)。\n- store_id(货主ID,可选,正整数,支持单值/数组/{operator,value} 结构,如 {\"operator\":\"\",\"value\":[1000281,1000000]};语义:默认 eq/in 返回包含任一筛选货主订单的波次,含混合货主波次;ne/notin 返回不包含所选货主订单的波次;不支持 like 等文本操作符)。" } ], "response": [ @@ -31141,7 +31226,7 @@ }, { "method": "shops.edit", - "description": "编辑店铺,仅允许修改 platform_code 或 custom_name;至少传入其中一个。platform_code 会校验平台存在且为 ACTIVE;custom_name 必填且长度<=100;服务端兼容 snake_case/camelCase。", + "description": "编辑店铺,仅允许修改 platform_code、custom_name 或 shop_name,至少传入其中一个。platform_code 会校验平台存在且为 ACTIVE(未匹配返回 400);custom_name/shop_name 传入时需非空且长度<=100;shop_name 修改需满足同仓同平台唯一(同时改 platform_code 时按新平台校验,冲突返回 409);服务端兼容 snake_case/camelCase 入参。", "isNeedAuth": true, "isNeedLogin": true, "headers": [ @@ -31173,6 +31258,13 @@ "required": false, "source": "body", "description": "自定义名称,兼容 customName,若传入需非空且 <=100 字符" + }, + { + "name": "shop_name", + "type": "string", + "required": false, + "source": "body", + "description": "店铺名称(平台真实店铺名),兼容 shopName,若传入需非空且 <=100 字符,且同仓同平台下不可重复" } ], "response": [ @@ -31210,7 +31302,7 @@ "errors": [ { "code": 400, - "message": "仅允许修改 platform_code 或 custom_name" + "message": "仅允许修改 platform_code、custom_name 或 shop_name" }, { "code": 400, @@ -31220,6 +31312,26 @@ "code": 400, "message": "custom_name 不能为空" }, + { + "code": 400, + "message": "shop_name 不能为空" + }, + { + "code": 400, + "message": "shop_name 长度不能超过 100" + }, + { + "code": 400, + "message": "shop_id 参数不合法" + }, + { + "code": 400, + "message": "未识别到当前仓库" + }, + { + "code": 404, + "message": "店铺不存在" + }, { "code": 409, "message": "同仓同平台下 shop_name 已存在" diff --git a/test/app/service/entry_order.cancel.test.js b/test/app/service/entry_order.cancel.test.js new file mode 100644 index 0000000..0bcd24f --- /dev/null +++ b/test/app/service/entry_order.cancel.test.js @@ -0,0 +1,759 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const StorageEntryService = require('../../../app/service/systems/storage/entry'); +const QimenOrderService = require('../../../app/service/qimenMethods/order'); +const OpenapiOrderService = require('../../../app/service/openapiMethods/order'); + +/** RK 组入库单类型(与奇门 orderType 枚举中 method=RK 的类型完全一致) */ +const RK_TYPES = [ 'B2BRK', 'SCRK', 'LYRK', 'CCRK', 'CGRK', 'DBRK', 'QTRK' ]; + +/** + * 构造 storage.entry.cancel 共享实现测试桩。 + * @param {Object} options 桩配置。 + * @param {Object|null} [options.order] 入库单桩(null 表示查询不到)。 + * @param {Object} [options.orderMap] 按 id 映射的入库单桩(批量场景)。 + * @param {Array} [options.items] 入库单明细。 + * @param {Object} [options.qimenEntrySyncResult] qimenEntrySync 返回结果。 + * @param {Object} [options.rollbackResult] rollbackEntryOrderBindings 返回结果。 + * @param {Object} [options.user] ctx.user 桩(缺省为测试仓管)。 + * @return {Object} service / calls。 + */ +function createEntryCancelHarness(options = {}) { + const calls = { + findOne: [], + update: [], + findAllItems: [], + qimenEntrySync: [], + rollbackBindings: [], + createOperationLog: [], + }; + + const makeOrder = overrides => ({ + id: 1, + entry_order_code: 'RK-001', + order_status: 'CREATED', + sync_status: null, + source_type: 'SYSTEM', + warehouse_id: 100000, + store_id: 1000000, + ...overrides, + async update(values) { + calls.update.push({ values, order: this }); + return this; + }, + }); + + const defaultOrder = options.order === null ? null : makeOrder(options.order || {}); + + // 批量场景:按 id 映射的入库单桩(null 表示查询不到) + const orderMap = options.orderMap + ? Object.fromEntries( + Object.entries(options.orderMap).map(([ orderId, stub ]) => [ + orderId, + stub === null || stub === undefined ? null : makeOrder(stub), + ]) + ) + : null; + + const ctx = { + app: { config: {} }, + logger: { info() {}, warn() {}, error() {}, debug() {} }, + user: options.user === undefined + ? { store_id: 100000, employees_id: 9, employees_name: '测试仓管' } + : options.user, + model: { + EntryOrder: { + async findOne(query) { + calls.findOne.push(query); + const whereId = query && query.where ? query.where.id : undefined; + if (orderMap && whereId !== undefined && whereId !== null) { + return orderMap[whereId] === undefined ? null : orderMap[whereId]; + } + return defaultOrder; + }, + }, + EntryItems: { + async findAll(query) { + calls.findAllItems.push(query); + return options.items === undefined ? [] : options.items; + }, + }, + }, + service: { + systems: { + inboundDirectLog: { + async qimenEntrySync(params) { + calls.qimenEntrySync.push(params); + return options.qimenEntrySyncResult || { success: true, message: 'ok' }; + }, + }, + receivingEntryMatch: { + async rollbackEntryOrderBindings(params) { + calls.rollbackBindings.push(params); + return options.rollbackResult || { rolled_back: [] }; + }, + }, + operationLog: { + async createOperationLog(params) { + calls.createOperationLog.push(params); + return {}; + }, + }, + }, + }, + }; + + const service = new StorageEntryService(ctx); + return { service, calls }; +} + +/** + * 构造奇门 order 服务测试桩(提供 storage.entry.cancel 与 stockoutOrder.cancel 委托桩)。 + * @param {Object} options 桩配置。 + * @return {Object} service / calls / stockoutCalls。 + */ +function createQimenOrderHarness(options = {}) { + const calls = []; + const stockoutCalls = []; + const ctx = { + app: { config: {} }, + logger: { info() {}, warn() {}, error() {}, debug() {} }, + service: { + systems: { + storage: { + entry: { + async cancel(data, opts) { + calls.push({ data, opts }); + return options.entryCancelResult || { code: 200, message: '作废成功', data: { ids: [ 1 ] } }; + }, + }, + }, + stockoutOrder: { + async cancel(data, opts) { + stockoutCalls.push({ data, opts }); + return { flag: 'success', code: 1, message: '取消出库单成功' }; + }, + }, + }, + }, + model: { + // RK 取消不得再直接访问 EntryOrder 模型(旧实现才会命中此处) + EntryOrder: { + async findOne() { + throw new Error('RK 取消不应直接访问 EntryOrder 模型'); + }, + }, + }, + }; + + const service = new QimenOrderService(ctx); + service.setInfo(1000000, 100000, 'app-key', 'customer-id', 'warehouse-code'); + return { service, calls, stockoutCalls }; +} + +/** + * 构造 openapi order 服务测试桩(提供 storage.entry.cancel 与 stockoutOrder.cancel 委托桩)。 + * @param {Object} options 桩配置。 + * @return {Object} service / calls / stockoutCalls。 + */ +function createOpenapiOrderHarness(options = {}) { + const calls = []; + const stockoutCalls = []; + const ctx = { + app: { config: {} }, + logger: { info() {}, warn() {}, error() {}, debug() {} }, + service: { + systems: { + storage: { + entry: { + async cancel(data, opts) { + calls.push({ data, opts }); + return options.entryCancelResult || { code: 200, message: '作废成功', data: { ids: [ 1 ] } }; + }, + }, + }, + stockoutOrder: { + async cancel(data, opts) { + stockoutCalls.push({ data, opts }); + return { flag: 'success', code: 1, message: '取消出库单成功' }; + }, + }, + }, + }, + model: options.model || { + // RK / CK 取消不应访问 delivery 模型 + OrderDeliveryFactory: { + async getCurrentModel() { + throw new Error('RK/CK 取消不应访问 delivery 模型'); + }, + }, + }, + }; + + const service = new OpenapiOrderService(ctx); + service.setInfo(1000000, 100000, 'APP-KEY', null, '100000'); + return { service, calls, stockoutCalls }; +} + +describe('test/app/service/entry_order.cancel.test.js', () => { + describe('systems.storage.entry.cancel 系统方法入口(不传 options,回归)', () => { + it('{ id } 取消成功:置 CANCELLED、回退收货单占用、写操作日志,非 QM 不回传', async () => { + const { service, calls } = createEntryCancelHarness(); + + const result = await service.cancel({ id: 1 }); + + assert.equal(result.code, 200); + assert.equal(result.message, '作废成功'); + assert.deepEqual(result.data, { ids: [ 1 ] }); + + assert.equal(calls.findOne.length, 1); + assert.deepEqual(calls.findOne[0].where, { + id: 1, + warehouse_id: 100000, + is_enabled: 1, + deleted_at: null, + }); + + assert.equal(calls.update.length, 1); + assert.equal(calls.update[0].values.order_status, 'CANCELLED'); + assert.equal(calls.rollbackBindings.length, 1); + assert.equal(calls.rollbackBindings[0].entryOrderId, 1); + assert.equal(calls.qimenEntrySync.length, 0); + + assert.equal(calls.createOperationLog.length, 1); + assert.equal(calls.createOperationLog[0].businessType, 'entry_order'); + assert.equal(calls.createOperationLog[0].operationCode, 'ENTRY_ORDER_CANCEL'); + assert.equal(calls.createOperationLog[0].operator.id, 9); + assert.equal(calls.createOperationLog[0].operator.name, '测试仓管'); + assert.equal(calls.createOperationLog[0].extras.message, '入库单已取消'); + }); + + it('{ id } 未找到 → 入库单不存在或无权访问', async () => { + const { service, calls } = createEntryCancelHarness({ order: null }); + + const result = await service.cancel({ id: 999 }); + + assert.equal(result.code, 404); + assert.equal(result.message, '入库单不存在或无权访问'); + assert.equal(result.data, null); + assert.equal(calls.update.length, 0); + }); + + it('COMPLETED 守卫拦截,不写库', async () => { + const { service, calls } = createEntryCancelHarness({ + order: { order_status: 'COMPLETED' }, + }); + + const result = await service.cancel({ id: 1 }); + + assert.equal(result.code, 400); + assert.equal(result.message, '已完成入库单不允许作废'); + assert.equal(calls.update.length, 0); + assert.equal(calls.qimenEntrySync.length, 0); + }); + + it('sync_status=SUCCESS 守卫拦截,不写库', async () => { + const { service, calls } = createEntryCancelHarness({ + order: { sync_status: 'SUCCESS' }, + }); + + const result = await service.cancel({ id: 1 }); + + assert.equal(result.code, 400); + assert.equal(result.message, '入库单已完成回传,不可取消'); + assert.equal(calls.update.length, 0); + }); + + it('已 CANCELLED 非幂等返回「入库单已作废」', async () => { + const { service, calls } = createEntryCancelHarness({ + order: { order_status: 'CANCELLED' }, + }); + + const result = await service.cancel({ id: 1 }); + + assert.equal(result.code, 400); + assert.equal(result.message, '入库单已作废'); + assert.equal(calls.update.length, 0); + }); + + it('{ ids } 批量作废:逐单处理并返回 ids 列表', async () => { + const { service, calls } = createEntryCancelHarness({ + orderMap: { + 1: { + id: 1, + entry_order_code: 'RK-1', + order_status: 'CREATED', + sync_status: null, + source_type: 'SYSTEM', + warehouse_id: 100000, + store_id: 1000000, + }, + 2: { + id: 2, + entry_order_code: 'RK-2', + order_status: 'CREATED', + sync_status: null, + source_type: 'SYSTEM', + warehouse_id: 100000, + store_id: 1000000, + }, + }, + }); + + const result = await service.cancel({ ids: [ 1, 2 ] }); + + assert.equal(result.code, 200); + assert.deepEqual(result.data, { ids: [ 1, 2 ] }); + assert.equal(calls.update.length, 2); + assert.equal(calls.update[0].values.order_status, 'CANCELLED'); + assert.equal(calls.update[1].values.order_status, 'CANCELLED'); + assert.equal(calls.rollbackBindings.length, 2); + assert.equal(calls.createOperationLog.length, 2); + }); + + it('QM 来源不传 options:发送取消同步(actualQty 全 0)', async () => { + const { service, calls } = createEntryCancelHarness({ + order: { source_type: 'QM' }, + items: [ + { item_code: 'A', item_id: '11', count: 5, inventory_type: 'ZP', owner_code: 'OC1' }, + ], + }); + + const result = await service.cancel({ id: 1 }); + + assert.equal(result.code, 200); + assert.equal(calls.qimenEntrySync.length, 1); + const syncParams = calls.qimenEntrySync[0]; + assert.equal(syncParams.remark, '入库单取消'); + assert.equal(syncParams.operator.id, 9); + assert.equal(syncParams.operator.name, '测试仓管'); + assert.equal(typeof syncParams.outBizCode, 'string'); + assert.equal(syncParams.outBizCode.startsWith('CANCEL_'), true); + assert.equal(syncParams.orderLines.length, 1); + assert.equal(syncParams.orderLines[0].actualQty, 0); + assert.equal(syncParams.orderLines[0].planQty, 5); + assert.equal(calls.update.length, 1); + }); + + it('QM 取消同步失败 → 500 取消失败,不写库', async () => { + const { service, calls } = createEntryCancelHarness({ + order: { source_type: 'QM' }, + items: [{ item_code: 'A', item_id: '11', count: 5 }], + qimenEntrySyncResult: { success: false, message: '奇门同步失败' }, + }); + + const result = await service.cancel({ id: 1 }); + + assert.equal(result.code, 500); + assert.equal(result.message, '取消失败: 奇门同步失败'); + assert.equal(calls.update.length, 0); + }); + + it('缺 id/ids → id 或 ids 必填', async () => { + const { service, calls } = createEntryCancelHarness(); + + const result = await service.cancel({}); + + assert.equal(result.code, 400); + assert.equal(result.message, 'id 或 ids 必填'); + assert.equal(calls.findOne.length, 0); + }); + }); + + describe('systems.storage.entry.cancel 外部渠道(options 扩展)', () => { + it('entryOrderCode 定位成功:where 带 is_enabled/deleted_at/warehouse_id/store_id', async () => { + const { service, calls } = createEntryCancelHarness(); + + const result = await service.cancel( + { entryOrderCode: 'RK-001' }, + { + storeId: 1000000, + warehouseId: 100000, + operatorLabel: 'openapi:APP-KEY', + skipExternalSync: true, + idempotent: true, + notFoundMessage: '未找到对应的入库单', + } + ); + + assert.equal(result.code, 200); + assert.deepEqual(result.data, { ids: [ 1 ] }); + assert.equal(calls.findOne.length, 1); + assert.deepEqual(calls.findOne[0].where, { + entry_order_code: 'RK-001', + warehouse_id: 100000, + is_enabled: 1, + deleted_at: null, + store_id: 1000000, + }); + }); + + it('entry_order_code 别名兼容定位', async () => { + const { service, calls } = createEntryCancelHarness(); + + const result = await service.cancel( + { entry_order_code: 'RK-001' }, + { warehouseId: 100000, skipExternalSync: true } + ); + + assert.equal(result.code, 200); + assert.equal(calls.findOne[0].where.entry_order_code, 'RK-001'); + }); + + it('storeId 为空不参与定位条件', async () => { + const { service, calls } = createEntryCancelHarness(); + + await service.cancel( + { entryOrderCode: 'RK-001' }, + { storeId: null, warehouseId: 100000, skipExternalSync: true } + ); + + assert.deepEqual(calls.findOne[0].where, { + entry_order_code: 'RK-001', + warehouse_id: 100000, + is_enabled: 1, + deleted_at: null, + }); + }); + + it('未找到 → notFoundMessage 文案', async () => { + const { service } = createEntryCancelHarness({ order: null }); + + const result = await service.cancel( + { entryOrderCode: 'RK-NOT-FOUND' }, + { warehouseId: 100000, notFoundMessage: '未找到对应的入库单' } + ); + + assert.equal(result.code, 404); + assert.equal(result.message, '未找到对应的入库单'); + }); + + it('幂等:已 CANCELLED 外部渠道返回成功且不重复写库', async () => { + const { service, calls } = createEntryCancelHarness({ + order: { order_status: 'CANCELLED' }, + }); + + const result = await service.cancel( + { entryOrderCode: 'RK-001' }, + { warehouseId: 100000, idempotent: true, skipExternalSync: true } + ); + + assert.equal(result.code, 200); + assert.equal(result.message, '作废成功'); + assert.deepEqual(result.data, { ids: [ 1 ] }); + assert.equal(calls.update.length, 0); + assert.equal(calls.qimenEntrySync.length, 0); + }); + + it('幂等:已 CANCELLED 且 sync_status=SUCCESS 仍幂等成功(不触发回传守卫)', async () => { + const { service, calls } = createEntryCancelHarness({ + order: { order_status: 'CANCELLED', sync_status: 'SUCCESS' }, + }); + + const result = await service.cancel( + { entryOrderCode: 'RK-001' }, + { warehouseId: 100000, idempotent: true, skipExternalSync: true } + ); + + assert.equal(result.code, 200); + assert.equal(calls.update.length, 0); + }); + + it('skipExternalSync:QM 来源不触发 qimenEntrySync 回传', async () => { + const { service, calls } = createEntryCancelHarness({ + order: { source_type: 'QM' }, + items: [{ item_code: 'A', item_id: '11', count: 5 }], + }); + + const result = await service.cancel( + { entryOrderCode: 'RK-001' }, + { warehouseId: 100000, skipExternalSync: true } + ); + + assert.equal(result.code, 200); + assert.equal(calls.qimenEntrySync.length, 0); + assert.equal(calls.update.length, 1); + }); + + it('operatorLabel 覆盖操作日志操作人', async () => { + const { service, calls } = createEntryCancelHarness(); + + await service.cancel( + { entryOrderCode: 'RK-001' }, + { warehouseId: 100000, operatorLabel: 'openapi:APP-KEY', skipExternalSync: true } + ); + + assert.equal(calls.createOperationLog.length, 1); + assert.equal(calls.createOperationLog[0].operator.id, null); + assert.equal(calls.createOperationLog[0].operator.name, 'openapi:APP-KEY'); + }); + + it('COMPLETED / sync_status=SUCCESS 守卫在外部门径同样拦截', async () => { + const completedHarness = createEntryCancelHarness({ order: { order_status: 'COMPLETED' } }); + const completedResult = await completedHarness.service.cancel( + { entryOrderCode: 'RK-001' }, + { warehouseId: 100000, idempotent: true, skipExternalSync: true } + ); + assert.equal(completedResult.code, 400); + assert.equal(completedResult.message, '已完成入库单不允许作废'); + assert.equal(completedHarness.calls.update.length, 0); + + const syncedHarness = createEntryCancelHarness({ order: { sync_status: 'SUCCESS' } }); + const syncedResult = await syncedHarness.service.cancel( + { entryOrderCode: 'RK-001' }, + { warehouseId: 100000, idempotent: true, skipExternalSync: true } + ); + assert.equal(syncedResult.code, 400); + assert.equal(syncedResult.message, '入库单已完成回传,不可取消'); + assert.equal(syncedHarness.calls.update.length, 0); + }); + }); + + describe('奇门 order.cancel RK 组路由', () => { + for (const rkType of RK_TYPES) { + it(`orderType=${rkType} 路由到入库单作废而非直接改模型`, async () => { + const { service, calls } = createQimenOrderHarness(); + + const result = await service.cancel({ + request: { orderType: rkType, orderCode: 'RK-1' }, + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.message, '取消入库单成功'); + assert.equal(calls.length, 1); + assert.deepEqual(calls[0].data, { entryOrderCode: 'RK-1' }); + assert.equal(calls[0].opts.storeId, 1000000); + assert.equal(calls[0].opts.warehouseId, 100000); + assert.equal(calls[0].opts.operatorLabel, 'qimen:customer-id'); + assert.equal(calls[0].opts.skipExternalSync, true); + assert.equal(calls[0].opts.idempotent, true); + assert.equal(calls[0].opts.notFoundMessage, '未找到对应的入库单'); + }); + } + + it('CGRK 复现用例:RK_2 可正常取消', async () => { + const { service, calls } = createQimenOrderHarness(); + + const result = await service.cancel({ + request: { orderType: 'CGRK', orderCode: 'RK_2' }, + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.message, '取消入库单成功'); + assert.deepEqual(calls[0].data, { entryOrderCode: 'RK_2' }); + }); + + it('缺 orderCode → 入库单号不能为空', async () => { + const { service, calls } = createQimenOrderHarness(); + + const result = await service.cancel({ + request: { orderType: 'CGRK', orderCode: ' ' }, + }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.message, '入库单号不能为空'); + assert.equal(calls.length, 0); + }); + + it('未找到 → 未找到对应的入库单', async () => { + const { service } = createQimenOrderHarness({ + entryCancelResult: { code: 404, message: '未找到对应的入库单', data: null }, + }); + + const result = await service.cancel({ + request: { orderType: 'CGRK', orderCode: 'RK-NOT-FOUND' }, + }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.message, '未找到对应的入库单'); + }); + + it('守卫文案原样透出', async () => { + const { service } = createQimenOrderHarness({ + entryCancelResult: { code: 400, message: '已完成入库单不允许作废', data: null }, + }); + + const result = await service.cancel({ + request: { orderType: 'CGRK', orderCode: 'RK-1' }, + }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.message, '已完成入库单不允许作废'); + }); + + it('回传失败文案原样透出', async () => { + const { service } = createQimenOrderHarness({ + entryCancelResult: { code: 500, message: '取消失败: 奇门同步失败', data: null }, + }); + + const result = await service.cancel({ + request: { orderType: 'CGRK', orderCode: 'RK-1' }, + }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.message, '取消失败: 奇门同步失败'); + }); + + it('CK 组(PTCK)仍路由到出库单取消,不受 RK 改动影响', async () => { + const { service, calls, stockoutCalls } = createQimenOrderHarness(); + + const result = await service.cancel({ + request: { orderType: 'PTCK', orderCode: 'SO-CK-001' }, + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.message, '取消出库单成功'); + assert.equal(calls.length, 0); + assert.equal(stockoutCalls.length, 1); + }); + }); + + describe('openapi order.cancel RK 组路由', () => { + for (const rkType of RK_TYPES) { + it(`orderType=${rkType.toLowerCase()}(大小写归一化)路由到入库单作废`, async () => { + const { service, calls } = createOpenapiOrderHarness(); + + const result = await service.cancel({ + body: { orderType: rkType.toLowerCase(), orderCode: 'RK-1' }, + query: {}, + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.code, 1); + assert.equal(result.message, '取消入库单成功'); + assert.equal(calls.length, 1); + assert.deepEqual(calls[0].data, { entryOrderCode: 'RK-1' }); + assert.equal(calls[0].opts.storeId, 1000000); + assert.equal(calls[0].opts.warehouseId, 100000); + assert.equal(calls[0].opts.operatorLabel, 'openapi:APP-KEY'); + assert.equal(calls[0].opts.skipExternalSync, true); + assert.equal(calls[0].opts.idempotent, true); + assert.equal(calls[0].opts.notFoundMessage, '未找到对应的入库单'); + }); + } + + it('CGRK 复现用例:RK_2 可正常取消', async () => { + const { service, calls } = createOpenapiOrderHarness(); + + const result = await service.cancel({ + body: { orderType: 'CGRK', orderCode: 'RK_2' }, + query: {}, + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.message, '取消入库单成功'); + assert.deepEqual(calls[0].data, { entryOrderCode: 'RK_2' }); + }); + + it('缺 orderCode → orderCode 参数缺失', async () => { + const { service, calls } = createOpenapiOrderHarness(); + + const result = await service.cancel({ + body: { orderType: 'CGRK', orderCode: ' ' }, + query: {}, + }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.code, 0); + assert.equal(result.message, 'orderCode 参数缺失'); + assert.equal(calls.length, 0); + }); + + it('未找到 → 未找到对应的入库单', async () => { + const { service } = createOpenapiOrderHarness({ + entryCancelResult: { code: 404, message: '未找到对应的入库单', data: null }, + }); + + const result = await service.cancel({ + body: { orderType: 'CGRK', orderCode: 'RK-NOT-FOUND' }, + query: {}, + }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.code, 0); + assert.equal(result.message, '未找到对应的入库单'); + }); + + it('守卫文案原样透出(code=0)', async () => { + const { service } = createOpenapiOrderHarness({ + entryCancelResult: { code: 400, message: '入库单已完成回传,不可取消', data: null }, + }); + + const result = await service.cancel({ + body: { orderType: 'CGRK', orderCode: 'RK-1' }, + query: {}, + }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.code, 0); + assert.equal(result.message, '入库单已完成回传,不可取消'); + }); + + it('非支持类型(XTRK)仍返回「暂不支持该订单类型的取消操作」', async () => { + const { service, calls } = createOpenapiOrderHarness(); + + const result = await service.cancel({ + body: { orderType: 'XTRK', orderCode: 'RK-1' }, + query: {}, + }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.message, '暂不支持该订单类型的取消操作'); + assert.equal(calls.length, 0); + }); + + it('CK 组(PTCK)仍路由到出库单取消,不受 RK 改动影响', async () => { + const { service, calls, stockoutCalls } = createOpenapiOrderHarness(); + + const result = await service.cancel({ + body: { orderType: 'PTCK', orderCode: 'SO-CK-001' }, + query: {}, + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.message, '取消出库单成功'); + assert.equal(calls.length, 0); + assert.equal(stockoutCalls.length, 1); + }); + + it('ORDER 组(JYCK)仍走 delivery 取消分支,不受 RK 改动影响', async () => { + const modelCalls = { deliveryFindOne: 0 }; + const transaction = { + LOCK: { UPDATE: 'UPDATE' }, + async commit() { + modelCalls.commit += 1; + }, + async rollback() { + modelCalls.rollback += 1; + }, + }; + const { service, calls, stockoutCalls } = createOpenapiOrderHarness({ + model: { + async transaction() { return transaction; }, + OrderDeliveryFactory: { + async getCurrentModel() { + return { + async findOne() { + modelCalls.deliveryFindOne += 1; + return null; + }, + }; + }, + }, + }, + }); + + const result = await service.cancel({ + body: { orderType: 'JYCK', orderCode: 'OD-1' }, + query: {}, + }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.message, '未找到对应的订单'); + assert.equal(modelCalls.deliveryFindOne, 1); + assert.equal(calls.length, 0); + assert.equal(stockoutCalls.length, 0); + }); + }); +}); diff --git a/test/app/service/stockout_order.cancel.test.js b/test/app/service/stockout_order.cancel.test.js new file mode 100644 index 0000000..a0c2609 --- /dev/null +++ b/test/app/service/stockout_order.cancel.test.js @@ -0,0 +1,632 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const StockoutOrderService = require('../../../app/service/systems/stockout_order'); +const QimenOrderService = require('../../../app/service/qimenMethods/order'); +const OpenapiOrderService = require('../../../app/service/openapiMethods/order'); +const StorageStockoutService = require('../../../app/service/systemMethods/storage/stockout'); + +/** + * 构造最小出库单实例桩。 + * @param {Object} overrides 覆盖字段。 + * @return {Object} 出库单桩对象。 + */ +function createStockoutOrder(overrides = {}) { + return { + id: 1, + stockout_order_code: 'SO-CK-001', + order_status: 'CREATED', + warehouse_id: 100000, + store_id: 1000000, + canCancel() { + return [ 'CREATED', 'PENDING' ].includes(this.order_status); + }, + ...overrides, + }; +} + +/** + * 构造共享取消服务(systems/stockout_order.js)测试桩。 + * @param {Object} options 桩配置。 + * @param {Object|null} [options.order] 出库单桩(null 表示查询不到)。 + * @param {Array} [options.items] 出库单明细。 + * @param {Array} [options.lockResults] 依次返回的 lockItemStorages 结果。 + * @return {Object} service / calls / transaction。 + */ +function createStockoutCancelHarness(options = {}) { + const calls = { + findOne: [], + findAll: [], + update: [], + lockItemStorages: [], + createOperationLogs: [], + commit: 0, + rollback: 0, + }; + + const transaction = { + LOCK: { UPDATE: 'UPDATE' }, + async commit() { calls.commit += 1; }, + async rollback() { calls.rollback += 1; }, + }; + + const ctx = { + app: { config: {} }, + logger: { info() {}, warn() {}, error() {}, debug() {} }, + model: { + async transaction() { return transaction; }, + OrderStockout: { + async findOne(query) { + calls.findOne.push(query); + return options.order === null ? null : (options.order || createStockoutOrder()); + }, + async update(values, query) { + calls.update.push({ values, query }); + return [ 1 ]; + }, + }, + OrderStockoutItems: { + async findAll(query) { + calls.findAll.push(query); + return options.items === undefined ? [] : options.items; + }, + }, + }, + service: { + systems: { + stockStore: { + async lockItemStorages(stockId, qty, tx, oversell, meta) { + calls.lockItemStorages.push({ stockId, qty, tx, oversell, meta }); + return options.lockResults && options.lockResults.length > 0 + ? options.lockResults.shift() + : { success: true }; + }, + }, + operationLog: { + async createOperationLogs(list, opts) { + calls.createOperationLogs.push({ list, opts }); + return []; + }, + }, + }, + }, + }; + + const service = new StockoutOrderService(ctx); + return { service, calls, transaction }; +} + +/** + * 构造奇门 order 服务测试桩(仅提供 stockoutOrder.cancel 委托桩)。 + * @param {Object} options 桩配置。 + * @return {Object} service / calls。 + */ +function createQimenOrderHarness(options = {}) { + const calls = []; + const ctx = { + app: { config: {} }, + logger: { info() {}, warn() {}, error() {}, debug() {} }, + service: { + systems: { + stockoutOrder: { + async cancel(data, opts) { + calls.push({ data, opts }); + return options.stockoutCancelResult || { flag: 'success', code: 1, message: '取消出库单成功' }; + }, + }, + }, + }, + model: { + OrderDeliveryFactory: { + async getCurrentModel() { + throw new Error('CK 取消不应访问 delivery 模型'); + }, + }, + }, + }; + + const service = new QimenOrderService(ctx); + service.setInfo(1000000, 100000, 'app-key', 'customer-id', 'warehouse-code'); + return { service, calls }; +} + +/** + * 构造 openapi order 服务测试桩(仅提供 stockoutOrder.cancel 委托桩与可选模型桩)。 + * @param {Object} options 桩配置。 + * @return {Object} service / calls。 + */ +function createOpenapiOrderHarness(options = {}) { + const calls = []; + const ctx = { + app: { config: {} }, + logger: { info() {}, warn() {}, error() {}, debug() {} }, + service: { + systems: { + stockoutOrder: { + async cancel(data, opts) { + calls.push({ data, opts }); + return options.stockoutCancelResult || { flag: 'success', code: 1, message: '取消出库单成功' }; + }, + }, + }, + }, + model: options.model || {}, + }; + + const service = new OpenapiOrderService(ctx); + service.setInfo(1000000, 100000, 'APP-KEY', null, '100000'); + return { service, calls }; +} + +/** + * 构造 systemMethods/storage/stockout 服务测试桩。 + * @param {Object} options 桩配置。 + * @return {Object} service / calls。 + */ +function createStorageStockoutHarness(options = {}) { + const calls = []; + const ctx = { + app: { config: {} }, + logger: { info() {}, warn() {}, error() {}, debug() {} }, + user: options.user === undefined + ? { store_id: 100000, employees_id: 9, employees_name: '测试仓管' } + : options.user, + service: { + systems: { + stockoutOrder: { + async cancel(data, opts) { + calls.push({ data, opts }); + return options.stockoutCancelResult === undefined + ? { + flag: 'success', + code: 1, + message: '取消出库单成功', + id: 11, + stockout_order_code: 'SO-1', + order_status: 'CANCELLED', + } + : options.stockoutCancelResult; + }, + }, + }, + }, + }; + + const service = new StorageStockoutService(ctx); + return { service, calls }; +} + +describe('test/app/service/stockout_order.cancel.test.js', () => { + describe('systems.stockoutOrder.cancel 共享取消实现', () => { + it('出库单不存在时失败且不释放库存', async () => { + const { service, calls } = createStockoutCancelHarness({ order: null }); + + const result = await service.cancel( + { stockoutOrderCode: 'SO-NOT-FOUND' }, + { storeId: 1000000, warehouseId: 100000, operatorLabel: 'qimen:customer-id' } + ); + + assert.equal(result.flag, 'failure'); + assert.equal(result.message, '未找到对应的出库单'); + assert.equal(calls.findOne.length, 1); + assert.equal(calls.rollback, 1); + assert.equal(calls.lockItemStorages.length, 0); + assert.equal(calls.update.length, 0); + assert.equal(calls.commit, 0); + }); + + it('已 CANCELLED 出库单幂等返回成功,不重复释放库存', async () => { + const { service, calls } = createStockoutCancelHarness({ + order: createStockoutOrder({ order_status: 'CANCELLED' }), + items: [{ stock_id: 11, plan_qty: 5 }], + }); + + const result = await service.cancel( + { stockoutOrderCode: 'SO-CK-001' }, + { storeId: 1000000, warehouseId: 100000, operatorLabel: 'qimen:customer-id' } + ); + + assert.equal(result.flag, 'success'); + assert.equal(result.message, '取消出库单成功'); + assert.equal(result.order_status, 'CANCELLED'); + assert.equal(calls.rollback, 1); + assert.equal(calls.lockItemStorages.length, 0); + assert.equal(calls.update.length, 0); + assert.equal(calls.commit, 0); + }); + + it('CREATED 出库单取消成功:按单号定位、释放 QM_STOCKOUT 锁定、置 CANCELLED 并写操作日志', async () => { + const { service, calls, transaction } = createStockoutCancelHarness({ + items: [ + { stock_id: 11, plan_qty: 5 }, + { stock_id: 12, plan_qty: 0 }, + ], + }); + + const result = await service.cancel( + { stockoutOrderCode: 'SO-CK-001' }, + { storeId: 1000000, warehouseId: 100000, operatorLabel: 'qimen:customer-id' } + ); + + assert.equal(result.flag, 'success'); + assert.equal(result.message, '取消出库单成功'); + assert.equal(result.id, 1); + assert.equal(result.stockout_order_code, 'SO-CK-001'); + assert.equal(result.order_status, 'CANCELLED'); + + // 定位条件:仓库 + 货主 + 软删除过滤 + 行锁 + assert.deepEqual(calls.findOne[0].where, { + warehouse_id: 100000, + store_id: 1000000, + deleted_at: null, + stockout_order_code: 'SO-CK-001', + }); + assert.equal(calls.findOne[0].lock, 'UPDATE'); + assert.equal(calls.findOne[0].transaction, transaction); + + // 库存锁定释放:负数量 + QM_STOCKOUT 标记 + assert.equal(calls.lockItemStorages.length, 1); + assert.equal(calls.lockItemStorages[0].stockId, 11); + assert.equal(calls.lockItemStorages[0].qty, -5); + assert.deepEqual(calls.lockItemStorages[0].meta, { + orderType: 'QM_STOCKOUT', + orderNo: 'SO-CK-001', + orderId: 1, + remark: '出库单取消释放锁定', + }); + + // 状态更新 + 操作日志同事务 + assert.equal(calls.update.length, 1); + assert.equal(calls.update[0].values.order_status, 'CANCELLED'); + assert.equal(calls.update[0].values.sync_message, '已取消'); + assert.equal(calls.update[0].query.transaction, transaction); + assert.equal(calls.createOperationLogs.length, 1); + assert.equal(calls.createOperationLogs[0].list[0].businessType, 'stockout'); + assert.equal(calls.createOperationLogs[0].list[0].operationCode, 'STOCKOUT_CANCEL'); + assert.equal(calls.createOperationLogs[0].list[0].operator.name, 'qimen:customer-id'); + assert.equal(calls.createOperationLogs[0].list[0].extras.message, '出库单已取消,释放锁定库存 5'); + assert.equal(calls.commit, 1); + }); + + it('仅传 id 时按 id + warehouse 定位(storeId 为空不参与定位条件)', async () => { + const { service, calls } = createStockoutCancelHarness({ + order: createStockoutOrder({ id: 11 }), + }); + + const result = await service.cancel( + { id: 11 }, + { storeId: null, warehouseId: 100000, operatorLabel: 'system' } + ); + + assert.equal(result.flag, 'success'); + assert.deepEqual(calls.findOne[0].where, { + warehouse_id: 100000, + deleted_at: null, + id: 11, + }); + }); + + it('COMPLETED 状态守卫拦截,不释放库存', async () => { + const { service, calls } = createStockoutCancelHarness({ + order: createStockoutOrder({ order_status: 'COMPLETED' }), + items: [{ stock_id: 11, plan_qty: 5 }], + }); + + const result = await service.cancel( + { stockoutOrderCode: 'SO-CK-001' }, + { storeId: 1000000, warehouseId: 100000 } + ); + + assert.equal(result.flag, 'failure'); + assert.equal(result.message, '出库单当前状态(COMPLETED)不允许取消'); + assert.equal(calls.lockItemStorages.length, 0); + assert.equal(calls.update.length, 0); + assert.equal(calls.commit, 0); + assert.equal(calls.rollback, 1); + }); + + it('TRANSFERRED 状态守卫拦截,不释放库存', async () => { + const { service, calls } = createStockoutCancelHarness({ + order: createStockoutOrder({ order_status: 'TRANSFERRED' }), + items: [{ stock_id: 11, plan_qty: 5 }], + }); + + const result = await service.cancel( + { stockoutOrderCode: 'SO-CK-001' }, + { storeId: 1000000, warehouseId: 100000 } + ); + + assert.equal(result.flag, 'failure'); + assert.equal(result.message, '出库单当前状态(TRANSFERRED)不允许取消'); + assert.equal(calls.lockItemStorages.length, 0); + assert.equal(calls.update.length, 0); + }); + + it('锁定已释放(释放数量超过已锁定库存)视为幂等跳过,仍取消成功', async () => { + const { service, calls } = createStockoutCancelHarness({ + items: [{ stock_id: 11, plan_qty: 5 }], + lockResults: [{ success: false, error: '释放数量超过已锁定库存' }], + }); + + const result = await service.cancel( + { stockoutOrderCode: 'SO-CK-001' }, + { storeId: 1000000, warehouseId: 100000 } + ); + + assert.equal(result.flag, 'success'); + assert.equal(calls.update.length, 1); + assert.equal(calls.update[0].values.order_status, 'CANCELLED'); + assert.equal(calls.createOperationLogs[0].list[0].extras.message, '出库单已取消,释放锁定库存 0'); + assert.equal(calls.commit, 1); + }); + + it('库存释放硬失败时取消失败并回滚', async () => { + const { service, calls } = createStockoutCancelHarness({ + items: [{ stock_id: 11, plan_qty: 5 }], + lockResults: [{ success: false, error: '库存不足' }], + }); + + const result = await service.cancel( + { stockoutOrderCode: 'SO-CK-001' }, + { storeId: 1000000, warehouseId: 100000 } + ); + + assert.equal(result.flag, 'failure'); + assert.equal(result.message, '取消失败:库存11释放锁定失败: 库存不足'); + assert.equal(calls.rollback, 1); + assert.equal(calls.update.length, 0); + assert.equal(calls.commit, 0); + }); + + it('缺少仓库上下文与出库单号时分别返回对应文案', async () => { + const { service } = createStockoutCancelHarness(); + + const noWarehouse = await service.cancel({ stockoutOrderCode: 'SO-CK-001' }, {}); + assert.equal(noWarehouse.flag, 'failure'); + assert.equal(noWarehouse.message, '缺少仓库上下文'); + + const noCode = await service.cancel({}, { storeId: 1000000, warehouseId: 100000 }); + assert.equal(noCode.flag, 'failure'); + assert.equal(noCode.message, '出库单号不能为空'); + }); + }); + + describe('奇门 order.cancel CK 组路由', () => { + const CK_TYPES = [ 'PTCK', 'DBCK', 'B2BCK', 'QTCK', 'CGTH' ]; + + for (const ckType of CK_TYPES) { + it(`orderType=${ckType} 路由到出库单取消而非 delivery 取消`, async () => { + const { service, calls } = createQimenOrderHarness(); + + const result = await service.cancel({ + request: { orderType: ckType, orderCode: 'SO-CK-001' }, + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.message, '取消出库单成功'); + assert.equal(calls.length, 1); + assert.deepEqual(calls[0].data, { stockoutOrderCode: 'SO-CK-001' }); + assert.equal(calls[0].opts.storeId, 1000000); + assert.equal(calls[0].opts.warehouseId, 100000); + assert.equal(calls[0].opts.operatorLabel, 'qimen:customer-id'); + }); + } + + it('CK 组缺 orderCode 时返回「出库单号不能为空」', async () => { + const { service, calls } = createQimenOrderHarness(); + + const result = await service.cancel({ + request: { orderType: 'PTCK', orderCode: ' ' }, + }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.message, '出库单号不能为空'); + assert.equal(calls.length, 0); + }); + + it('ORDER 组(JYCK)仍走 delivery 取消分支', async () => { + // 复用真实 ORDER 分支桩:delivery 查询不到订单时返回「未找到对应的订单」 + const modelCalls = { findOne: 0, stockoutCancel: 0 }; + const transaction = { + LOCK: { UPDATE: 'UPDATE' }, + async commit() { + modelCalls.commit += 1; + }, + async rollback() { + modelCalls.rollback += 1; + }, + }; + const ctx = { + app: { config: {} }, + logger: { info() {}, warn() {}, error() {}, debug() {} }, + service: { + systems: { + stockoutOrder: { + async cancel() { + modelCalls.stockoutCancel += 1; + return { flag: 'success' }; + }, + }, + }, + }, + model: { + async transaction() { return transaction; }, + OrderDeliveryFactory: { + async getCurrentModel() { + return { + async findOne() { + modelCalls.findOne += 1; + return null; + }, + }; + }, + async getDispatchModel() { + return { + async findOne() { + return null; + }, + }; + }, + }, + }, + }; + const service = new QimenOrderService(ctx); + service.setInfo(1000000, 100000, 'app-key', 'customer-id', 'warehouse-code'); + + const result = await service.cancel({ + request: { orderType: 'JYCK', orderCode: 'OD-001' }, + }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.message, '未找到对应的订单'); + assert.equal(modelCalls.findOne, 1); + assert.equal(modelCalls.stockoutCancel, 0); + }); + }); + + describe('openapi order.cancel CK 组路由', () => { + const CK_TYPES = [ 'PTCK', 'DBCK', 'B2BCK', 'QTCK', 'CGTH' ]; + + for (const ckType of CK_TYPES) { + it(`orderType=${ckType}(含小写归一化)路由到出库单取消`, async () => { + const { service, calls } = createOpenapiOrderHarness(); + + const result = await service.cancel({ + body: { orderType: ckType.toLowerCase(), orderCode: 'SO-CK-001' }, + query: {}, + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.message, '取消出库单成功'); + assert.equal(calls.length, 1); + assert.deepEqual(calls[0].data, { stockoutOrderCode: 'SO-CK-001' }); + assert.equal(calls[0].opts.storeId, 1000000); + assert.equal(calls[0].opts.warehouseId, 100000); + assert.equal(calls[0].opts.operatorLabel, 'openapi:APP-KEY'); + }); + } + + it('非支持类型仍返回「暂不支持该订单类型的取消操作」', async () => { + const { service, calls } = createOpenapiOrderHarness(); + + const result = await service.cancel({ + body: { orderType: 'XTRK', orderCode: 'SO-CK-001' }, + query: {}, + }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.message, '暂不支持该订单类型的取消操作'); + assert.equal(calls.length, 0); + }); + + it('ORDER 组(JYCK)缺 orderCode 仍返回原「orderCode 参数缺失」', async () => { + const { service, calls } = createOpenapiOrderHarness(); + + const result = await service.cancel({ + body: { orderType: 'JYCK', orderCode: ' ' }, + query: {}, + }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.message, 'orderCode 参数缺失'); + assert.equal(calls.length, 0); + }); + + it('ORDER 组(JYCK)仍走 delivery 取消分支', async () => { + const modelCalls = { deliveryFindOne: 0 }; + const transaction = { + LOCK: { UPDATE: 'UPDATE' }, + async commit() { + modelCalls.commit += 1; + }, + async rollback() { + modelCalls.rollback += 1; + }, + }; + const { service, calls } = createOpenapiOrderHarness({ + model: { + async transaction() { return transaction; }, + OrderDeliveryFactory: { + async getCurrentModel() { + return { + async findOne() { + modelCalls.deliveryFindOne += 1; + return null; + }, + }; + }, + }, + }, + }); + + const result = await service.cancel({ + body: { orderType: 'JYCK', orderCode: 'OD-1' }, + query: {}, + }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.message, '未找到对应的订单'); + assert.equal(modelCalls.deliveryFindOne, 1); + assert.equal(calls.length, 0); + }); + }); + + describe('systemMethods storage.stockout.cancel 委托契约', () => { + it('缺 id / 缺仓库上下文保持原契约', async () => { + const { service, calls } = createStorageStockoutHarness(); + + const noId = await service.cancel({}); + assert.equal(noId.flag, 'failure'); + assert.equal(noId.message, '缺少出库单ID'); + + const { service: noWhService, calls: noWhCalls } = createStorageStockoutHarness({ + user: { store_id: 0 }, + }); + const noWarehouse = await noWhService.cancel({ id: 11 }); + assert.equal(noWarehouse.flag, 'failure'); + assert.equal(noWarehouse.message, '缺少仓库上下文'); + + assert.equal(calls.length, 0); + assert.equal(noWhCalls.length, 0); + }); + + it('共享层「未找到对应的出库单」映射为「出库单不存在」', async () => { + const { service, calls } = createStorageStockoutHarness({ + stockoutCancelResult: { flag: 'failure', code: 0, message: '未找到对应的出库单' }, + }); + + const result = await service.cancel({ id: 11 }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.message, '出库单不存在'); + assert.equal(calls.length, 1); + assert.deepEqual(calls[0].data, { id: 11 }); + assert.equal(calls[0].opts.warehouseId, 100000); + assert.equal(calls[0].opts.storeId, null); + assert.equal(calls[0].opts.operatorLabel, '测试仓管'); + }); + + it('状态守卫文案原样透出', async () => { + const { service } = createStorageStockoutHarness({ + stockoutCancelResult: { flag: 'failure', code: 0, message: '出库单当前状态(COMPLETED)不允许取消' }, + }); + + const result = await service.cancel({ id: 11 }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.message, '出库单当前状态(COMPLETED)不允许取消'); + }); + + it('成功时保持「取消成功」契约并返回 id / 单号 / 状态', async () => { + const { service } = createStorageStockoutHarness(); + + const result = await service.cancel({ id: 11 }); + + assert.equal(result.flag, 'success'); + assert.equal(result.message, '取消成功'); + assert.equal(result.id, 11); + assert.equal(result.stockout_order_code, 'SO-1'); + assert.equal(result.order_status, 'CANCELLED'); + }); + }); +});