From 9845a239e269d338d9e19df9e9a8877f7cd9b23d Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 16 May 2026 02:44:53 +0800 Subject: [PATCH] 1 --- app/lib/express_print_payload_builder.js | 241 ++ app/lib/printer_data_builder.js | 8 +- app/model/permission.js | 5 +- app/model/platform.js | 10 + app/model/stock_transaction.js | 6 +- app/service/system.js | 2 +- app/service/systemMethods/order/wave.js | 320 +- app/service/systemMethods/print.js | 832 +++- app/service/systemMethods/storage/report.js | 298 ++ app/service/systems/auth/role_permission.js | 30 +- app/service/systems/auth/user.js | 76 +- app/service/systems/order_async.js | 37 +- app/service/systems/order_print.js | 96 +- app/service/systems/setting/permission.js | 7 +- app/service/systems/stock_store.js | 165 +- app/service/systems/stock_transaction.js | 128 +- app/service/systems/storage/inventory.js | 137 +- app/service/systems/storage/report.js | 1232 ++++++ ...d-last-login-time-to-wms_print_computer.js | 4 +- ...60513113000-create-wms_order_wave_index.js | 4 +- ...dd-subject-config-to-wms_print_stations.js | 4 +- ...14123000-drop-wms_print_station_express.js | 4 +- ...kerstation-pages-to-wms_permission-type.js | 52 + ...514173000-add-component-to-wms_platform.js | 46 + ...ansaction-order-no-and-transaction-type.js | 61 + methods/changes/system.json | 3403 +++++++++-------- methods/system.json | 1324 ++++++- printer_data_template/kuaishou.json | 5 +- .../system.storage.inventory.list.test.js | 141 - test/app/model/print_stations.test.js | 4 +- .../order/wave.batchAutoGrouping.test.js | 242 ++ .../order/wave.batchCancel.test.js | 126 + .../order/wave.batchRemoveOrders.test.js | 126 +- .../systemMethods/order/wave.fetch.test.js | 21 +- .../systemMethods/print.savePrinters.test.js | 2 +- .../service/systemMethods/print.send.test.js | 496 ++- .../systems/order_async.syncOrderIds.test.js | 28 +- ...der_print.getWavePlatformPrintData.test.js | 220 +- .../stock_store.outbound.picking.test.js | 145 + .../systems/stock_transaction.create.test.js | 221 ++ .../storage.inventory.transfer.test.js | 374 ++ .../service/systems/storage.report.test.js | 764 ++++ 42 files changed, 9307 insertions(+), 2140 deletions(-) create mode 100644 app/lib/express_print_payload_builder.js create mode 100644 app/service/systemMethods/storage/report.js create mode 100644 app/service/systems/storage/report.js create mode 100644 database/migrations/20260514150000-add-workerstation-pages-to-wms_permission-type.js create mode 100644 database/migrations/20260514173000-add-component-to-wms_platform.js create mode 100644 database/migrations/20260516093000-alter-wms-stock-transaction-order-no-and-transaction-type.js delete mode 100644 test/app/controller/system.storage.inventory.list.test.js create mode 100644 test/app/service/systemMethods/order/wave.batchAutoGrouping.test.js create mode 100644 test/app/service/systemMethods/order/wave.batchCancel.test.js create mode 100644 test/app/service/systems/stock_store.outbound.picking.test.js create mode 100644 test/app/service/systems/storage.inventory.transfer.test.js create mode 100644 test/app/service/systems/storage.report.test.js diff --git a/app/lib/express_print_payload_builder.js b/app/lib/express_print_payload_builder.js new file mode 100644 index 0000000..9b12989 --- /dev/null +++ b/app/lib/express_print_payload_builder.js @@ -0,0 +1,241 @@ +'use strict'; + +const fs = require('node:fs'); +const path = require('node:path'); +const PrinterDataBuilder = require('./printer_data_builder'); + +const TEMPLATE_CACHE = new Map(); + +/** + * 判断是否为普通对象。 + * @param {any} value 待判断值。 + * @return {boolean} 判断结果。 + */ +function isPlainObject(value) { + return value !== null && typeof value === 'object' && !Array.isArray(value); +} + +/** + * 以 JSON 方式做深拷贝,避免污染模板缓存对象。 + * @param {Object} source 原对象。 + * @return {Object} 深拷贝结果。 + */ +function deepClone(source) { + return JSON.parse(JSON.stringify(source)); +} + +/** + * 请求内 ID 生成器。 + */ +class RequestScopedPrintIdGenerator { + /** + * @param {string} requestCode 前端请求参数码。 + */ + constructor(requestCode) { + this.requestCode = String(requestCode || '').trim(); + this.sequence = 0; + } + + /** + * 生成请求 ID。 + * @return {string} 唯一请求 ID。 + */ + nextRequestId() { + return this.next('request'); + } + + /** + * 生成任务 ID。 + * @return {string} 唯一任务 ID。 + */ + nextTaskId() { + return this.next('task'); + } + + /** + * 生成文档 ID。 + * @return {string} 唯一文档 ID。 + */ + nextDocumentId() { + return this.next('document'); + } + + /** + * 生成带前缀的递增 ID。 + * @param {string} prefix ID 前缀。 + * @return {string} 生成结果。 + */ + next(prefix) { + this.sequence += 1; + return `${this.requestCode}_${prefix}_${this.sequence}`; + } +} + +/** + * 快递打印请求组装器。 + */ +class ExpressPrintPayloadBuilder { + /** + * @param {Object} options 初始化参数。 + * @param {string} options.baseDir 项目根目录。 + */ + constructor(options = {}) { + const requestOptions = isPlainObject(options) ? options : {}; + this.baseDir = String(requestOptions.baseDir || process.cwd()); + this.templateDir = path.join(this.baseDir, 'printer_data_template'); + } + + /** + * 组装平台快递打印 payload。 + * @param {Object} options 组装参数。 + * @param {string} options.platform 平台编码。 + * @param {string} options.printerName 打印机名称。 + * @param {Array} options.orders 外部传入的订单打印数据数组。 + * @param {RequestScopedPrintIdGenerator} options.idGenerator 请求内 ID 生成器。 + * @return {Object} 可直接发送给打印服务的 payload。 + */ + buildPayload(options = {}) { + const requestOptions = isPlainObject(options) ? options : {}; + const platform = String(requestOptions.platform || '').trim(); + if (!platform) { + throw new Error('快递打印缺少平台标识'); + } + + const idGenerator = requestOptions.idGenerator; + if (!idGenerator || typeof idGenerator.nextRequestId !== 'function') { + throw new Error('快递打印缺少请求 ID 生成器'); + } + + const printerName = String(requestOptions.printerName || '').trim(); + if (!printerName) { + throw new Error('快递打印缺少打印机名称'); + } + + const orders = Array.isArray(requestOptions.orders) ? requestOptions.orders : []; + if (orders.length === 0) { + throw new Error('快递打印缺少订单数据'); + } + + const payload = this.loadTemplate(platform); + if (!isPlainObject(payload.task)) { + payload.task = {}; + } + + const requestId = idGenerator.nextRequestId(); + this.applyRequestId(payload, requestId); + payload.task.taskID = idGenerator.nextTaskId(); + payload.task.printer = printerName; + payload.task.documents = this.buildDocumentsFromOrders(orders, idGenerator); + + return payload; + } + + /** + * 将 orders 映射为 documents。 + * @param {Array} orders 订单数组。 + * @param {RequestScopedPrintIdGenerator} idGenerator 请求内 ID 生成器。 + * @return {Array} documents 数组。 + */ + buildDocumentsFromOrders(orders, idGenerator) { + return orders.map((order, index) => { + const sourceDocument = this.resolveOrderDocument(order, index); + const document = deepClone(sourceDocument); + if (!Array.isArray(document.contents)) { + document.contents = []; + } + document.documentID = idGenerator.nextDocumentId(); + return document; + }); + } + + /** + * 解析单个订单对应的 document。 + * @param {Object} order 订单对象。 + * @param {number} index 订单索引。 + * @return {Object} document 对象。 + */ + resolveOrderDocument(order, index) { + if (!isPlainObject(order)) { + throw new Error(`orders[${index}] 必须是对象`); + } + + const printData = isPlainObject(order.print_data) ? order.print_data : order; + if (!isPlainObject(printData)) { + throw new Error(`orders[${index}] 缺少 print_data`); + } + + const hasDocumentShape = Object.prototype.hasOwnProperty.call(printData, 'documentID') + || Array.isArray(printData.contents); + if (!hasDocumentShape) { + throw new Error(`orders[${index}] 的 print_data 不是有效 document 结构`); + } + + return printData; + } + + /** + * 写入请求 ID,兼容 requestID / requetID 两种字段。 + * @param {Object} payload 请求 payload。 + * @param {string} requestId 请求 ID。 + */ + applyRequestId(payload, requestId) { + const hasRequestId = Object.prototype.hasOwnProperty.call(payload, 'requestID'); + const hasRequetId = Object.prototype.hasOwnProperty.call(payload, 'requetID'); + + if (hasRequestId) { + payload.requestID = requestId; + } + if (hasRequetId) { + payload.requetID = requestId; + } + if (!hasRequestId && !hasRequetId) { + payload.requestID = requestId; + } + } + + /** + * 加载并缓存平台模板,然后返回深拷贝对象。 + * @param {string} platform 平台编码。 + * @return {Object} 模板拷贝。 + */ + loadTemplate(platform) { + const normalizedPlatform = this.normalizePlatform(platform); + const templatePath = path.join(this.templateDir, `${normalizedPlatform}.json`); + if (!TEMPLATE_CACHE.has(templatePath)) { + let templateContent = ''; + try { + templateContent = fs.readFileSync(templatePath, 'utf8'); + } catch (error) { + throw new Error(`未找到平台模板: ${normalizedPlatform}.json`); + } + + let templateData; + try { + templateData = JSON.parse(templateContent); + } catch (error) { + throw new Error(`平台模板 JSON 解析失败: ${normalizedPlatform}.json`); + } + TEMPLATE_CACHE.set(templatePath, templateData); + } + + return deepClone(TEMPLATE_CACHE.get(templatePath)); + } + + /** + * 规范化平台编码。 + * @param {string} platform 平台编码或别名。 + * @return {string} 规范化平台编码。 + */ + normalizePlatform(platform) { + const normalized = PrinterDataBuilder.normalizePlatformAlias(platform); + if (normalized && normalized.platform) { + return normalized.platform; + } + return String(platform || '').trim().toLowerCase(); + } +} + +module.exports = { + ExpressPrintPayloadBuilder, + RequestScopedPrintIdGenerator, +}; diff --git a/app/lib/printer_data_builder.js b/app/lib/printer_data_builder.js index d9f1539..bb55deb 100644 --- a/app/lib/printer_data_builder.js +++ b/app/lib/printer_data_builder.js @@ -454,6 +454,7 @@ function resolveItemQuantity(item) { * @param {Array} items 商品列表。 * @param {Object} policyConfig 策略配置。 * @param {string} lineBreak 换行符。 + * @param options * @return {string} 自定义区文本。 */ function buildWaybillCustomProductInfoLines(items, policyConfig = {}, options = {}) { @@ -751,6 +752,7 @@ function buildBaseData(input, platform, platformMeta) { * 清洗模板样例,保留结构并裁切样例噪声。 * @param {any} value 原始对象。 * @param {string[]} warnings 警告列表。 + * @param currentKey * @return {any} 清洗后的对象。 */ function sanitizeTemplatePrivateFields(value, warnings, currentKey = '') { @@ -819,6 +821,7 @@ function sanitizeTemplatePrivateFields(value, warnings, currentKey = '') { * @param {string} platform 归一化平台编码。 * @param {Object} skeleton 打印请求骨架。 * @param {Object} orderExpress 快递单对象。 + * @param orderDelivery * @param {string[]} warnings 风险提示列表。 * @param {Object} policyConfig 策略配置对象。 * @param {string} customDataTemplateURL 自定义区模板地址默认值。 @@ -960,6 +963,7 @@ function applyKuaishouExpressFieldMapping(platform, skeleton, orderExpress, orde * @param {string} platform 归一化平台编码。 * @param {Object} skeleton 打印请求骨架。 * @param {Object} orderExpress 快递单对象。 + * @param orderDelivery * @param {Object} policyConfig 策略配置对象。 */ function applyPddExpressFieldMapping(platform, skeleton, orderExpress, orderDelivery, policyConfig) { @@ -1033,13 +1037,13 @@ function applyPddExpressFieldMapping(platform, skeleton, orderExpress, orderDeli templateURL: toTrimmedString(templateURL || DEFAULT_PDD_CUSTOM_TEMPLATE_URL), data: { height: 240, - list: [ { + list: [{ fontSize: 28, left: 2.08, text: customProductInfo, top: 2.08, width: 550, - } ], + }], waterdata: { text: '', }, diff --git a/app/model/permission.js b/app/model/permission.js index 9d0ee55..63dfb2e 100644 --- a/app/model/permission.js +++ b/app/model/permission.js @@ -108,10 +108,10 @@ module.exports = app => { comment: '更新时间', }, type: { - type: ENUM('web_pages', 'pda_pages', 'btns', 'api', 'miniprogram_pages', 'block'), + type: ENUM('web_pages', 'pda_pages', 'btns', 'api', 'miniprogram_pages', 'block', 'workerstation_pages'), allowNull: false, defaultValue: 'web_pages', - comment: '权限类型(web_pages:电脑端页面,pda_pages:PDA页面,btns:按钮权限,api:接口权限,miniprogram_pages:小程序页面,block:功能模块)', + comment: '权限类型(web_pages:电脑端页面,pda_pages:PDA页面,btns:按钮权限,api:接口权限,miniprogram_pages:小程序页面,block:功能模块,workerstation_pages:工作台菜单)', }, }, { tableName: 'wms_permission', @@ -163,6 +163,7 @@ module.exports = app => { api: '接口权限', miniprogram_pages: '小程序页面', block: '功能模块', + workerstation_pages: '工作台菜单', }; return typeMap[this.type] || this.type; }; diff --git a/app/model/platform.js b/app/model/platform.js index f3d326f..5b19330 100644 --- a/app/model/platform.js +++ b/app/model/platform.js @@ -1,5 +1,10 @@ 'use strict'; +/** + * 平台表模型定义。 + * @param {import('egg').Application} app Egg 应用实例 + * @return {import('sequelize').ModelCtor} 平台模型 + */ module.exports = app => { const { STRING, INTEGER } = app.Sequelize; @@ -60,6 +65,11 @@ module.exports = app => { allowNull: true, comment: '订单来源', }, + component: { + type: STRING(255), + allowNull: true, + comment: '打印组件标识', + }, }, { tableName: 'wms_platform', freezeTableName: true, diff --git a/app/model/stock_transaction.js b/app/model/stock_transaction.js index 996d3ab..ff98c37 100644 --- a/app/model/stock_transaction.js +++ b/app/model/stock_transaction.js @@ -1,7 +1,7 @@ 'use strict'; module.exports = app => { - const { STRING, INTEGER, BIGINT, ENUM, DATE } = app.Sequelize; + const { STRING, INTEGER, BIGINT, ENUM, DATE, TEXT } = app.Sequelize; const StockTransaction = app.model.define('stock_transaction', { id: { @@ -11,7 +11,7 @@ module.exports = app => { comment: '主键ID', }, transaction_type: { - type: ENUM('INBOUND', 'OUTBOUND'), + type: ENUM('INBOUND', 'OUTBOUND', 'TRANSFER_OUT', 'TRANSFER_IN'), allowNull: false, comment: '出入库类型', }, @@ -81,7 +81,7 @@ module.exports = app => { comment: '关联单据类型(如 SCRK=收货入库, MATCH=匹配入库, CGTH=采购退货等)', }, order_no: { - type: STRING(100), + type: TEXT, allowNull: true, comment: '关联单据号', }, diff --git a/app/service/system.js b/app/service/system.js index 67e5b69..41834a0 100644 --- a/app/service/system.js +++ b/app/service/system.js @@ -2,7 +2,7 @@ const Service = require('egg').Service; -const ALLOWED_PLATFORMS = new Set([ 'web', 'pda', 'app', 'wx', 'miniprogram', 'other' ]); +const ALLOWED_PLATFORMS = new Set([ 'web', 'pda', 'app', 'wx', 'miniprogram', 'other', 'workerstation', 'workstation' ]); // project: all=全部, warehouse=仓库, store=货主, tms=物流 const ALLOWED_PROJECTS = new Set([ 'all', 'warehouse', 'store', 'tms', 'wms', 'scm', 'other' ]); diff --git a/app/service/systemMethods/order/wave.js b/app/service/systemMethods/order/wave.js index 541c13a..a361ef8 100644 --- a/app/service/systemMethods/order/wave.js +++ b/app/service/systemMethods/order/wave.js @@ -770,6 +770,245 @@ class WaveService extends OrderBaseService { }; } + /** + * 按订单ID清理波次索引记录。 + * + * @param {Object} params 清理参数。 + * @param {number|string} params.warehouseId 仓库ID。 + * @param {Array|number|string} params.orderIds 订单ID集合。 + * @param {Object} params.transaction Sequelize 事务。 + * @return {Promise} 无返回值。 + */ + async deleteOrderWaveIndexByOrderIds({ warehouseId, orderIds, transaction } = {}) { + const normalizedWarehouseId = Number(warehouseId || 0); + const normalizedOrderIds = this.normalizeIdsInput(orderIds); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0 || normalizedOrderIds.length === 0) { + return; + } + + const deleteSql = ` + DELETE FROM wms_order_wave_index + WHERE warehouse_id = :warehouseId + AND order_id IN (:orderIds) + `; + + await this.ctx.model.query(deleteSql, { + replacements: { + warehouseId: normalizedWarehouseId, + orderIds: normalizedOrderIds, + }, + transaction, + }); + } + + /** + * 按波次ID清理波次索引记录(用于兜底)。 + * + * @param {Object} params 清理参数。 + * @param {number|string} params.warehouseId 仓库ID。 + * @param {Array|number|string} params.waveIds 波次ID集合。 + * @param {Object} params.transaction Sequelize 事务。 + * @return {Promise} 无返回值。 + */ + async deleteOrderWaveIndexByWaveIds({ warehouseId, waveIds, transaction } = {}) { + const normalizedWarehouseId = Number(warehouseId || 0); + const normalizedWaveIds = this.normalizeIdsInput(waveIds); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0 || normalizedWaveIds.length === 0) { + return; + } + + const deleteSql = ` + DELETE FROM wms_order_wave_index + WHERE warehouse_id = :warehouseId + AND wave_id IN (:waveIds) + `; + + await this.ctx.model.query(deleteSql, { + replacements: { + warehouseId: normalizedWarehouseId, + waveIds: normalizedWaveIds, + }, + transaction, + }); + } + + /** + * 重建订单波次索引。 + * + * 兼容历史入参校验后,统一委托按波次整批覆盖索引, + * 避免与重排流程存在两套排序规则。 + * + * @param {Object} params 重建参数。 + * @param {number|string} params.warehouseId 仓库ID。 + * @param {number|string} params.waveId 波次ID。 + * @param {Array|number|string} params.orderIds 订单ID集合。 + * @param {Object} [params.orderModel] 订单模型(可复用外层已获取模型)。 + * @param {Object} params.transaction Sequelize 事务。 + * @return {Promise} 无返回值。 + */ + async rebuildOrderWaveIndex({ warehouseId, waveId, orderIds, orderModel, transaction } = {}) { + const normalizedWarehouseId = Number(warehouseId || 0); + const normalizedWaveId = Number(waveId || 0); + const normalizedOrderIds = this.normalizeIdsInput(orderIds); + if ( + !Number.isInteger(normalizedWarehouseId) + || normalizedWarehouseId <= 0 + || !Number.isInteger(normalizedWaveId) + || normalizedWaveId <= 0 + || normalizedOrderIds.length === 0 + ) { + return; + } + await this.replaceOrderWaveIndexByWaveIds({ + warehouseId: normalizedWarehouseId, + waveIds: [ normalizedWaveId ], + orderModel, + transaction, + }); + } + + /** + * 按波次整批覆盖订单索引并返回各波次当前订单数。 + * + * 处理流程: + * 1. 查询目标波次下当前订单(按 wave_id ASC, id ASC)。 + * 2. 先按波次批量删除 wms_order_wave_index。 + * 3. 按每个波次内订单顺序重建 wave_index;platforms_index 按平台内顺序重建(同平台按 id ASC,从 1 开始)。 + * + * @param {Object} params 覆盖参数。 + * @param {number|string} params.warehouseId 仓库ID。 + * @param {Array|number|string} params.waveIds 波次ID集合。 + * @param {Object} [params.orderModel] 订单模型(可复用外层已获取模型)。 + * @param {Object} params.transaction Sequelize 事务。 + * @return {Promise>} 波次当前订单数映射。 + */ + async replaceOrderWaveIndexByWaveIds({ warehouseId, waveIds, orderModel, transaction } = {}) { + const normalizedWarehouseId = Number(warehouseId || 0); + const normalizedWaveIds = this.normalizeIdsInput(waveIds); + const currentOrderModel = orderModel || await this.getOrderModel('pendingOrder', normalizedWarehouseId); + + if ( + !Number.isInteger(normalizedWarehouseId) + || normalizedWarehouseId <= 0 + || normalizedWaveIds.length === 0 + || !currentOrderModel + || typeof currentOrderModel.findAll !== 'function' + ) { + return new Map(); + } + + const orderRows = await currentOrderModel.findAll({ + attributes: [ 'id', 'wave_id', 'sys_platform_code', 'source_platform_code' ], + where: { + wave_id: { + [Op.in]: normalizedWaveIds, + [Op.gt]: 0, + }, + }, + order: [[ 'wave_id', 'ASC' ], [ 'id', 'ASC' ]], + raw: true, + transaction, + }); + + const orderRowsList = Array.isArray(orderRows) ? orderRows : []; + const waveOrderRowsMap = new Map(normalizedWaveIds.map(waveId => [ waveId, []])); + for (const row of orderRowsList) { + const waveId = Number(row && row.wave_id || 0); + const orderId = Number(row && row.id || 0); + if (!Number.isInteger(waveId) || waveId <= 0 || !waveOrderRowsMap.has(waveId)) { + continue; + } + if (!Number.isInteger(orderId) || orderId <= 0) { + continue; + } + + waveOrderRowsMap.get(waveId).push({ + id: orderId, + sys_platform_code: String(row && row.sys_platform_code || ''), + source_platform_code: String(row && row.source_platform_code || ''), + }); + } + + await this.deleteOrderWaveIndexByWaveIds({ + warehouseId: normalizedWarehouseId, + waveIds: normalizedWaveIds, + transaction, + }); + + const valueSqlList = []; + const replacements = { + warehouseId: normalizedWarehouseId, + }; + + let rowIndex = 0; + for (const waveId of normalizedWaveIds) { + const orderRowsByWave = waveOrderRowsMap.get(waveId) || []; + const platformsIndexMap = new Map(); + const platformSequenceMap = new Map(); + for (const orderRow of orderRowsByWave) { + const currentOrderId = Number(orderRow && orderRow.id || 0); + if (!Number.isInteger(currentOrderId) || currentOrderId <= 0) { + continue; + } + + const platformKey = String( + (orderRow && orderRow.sys_platform_code) + || (orderRow && orderRow.source_platform_code) + || '' + ).trim().toLowerCase(); + const nextPlatformSequence = Number(platformSequenceMap.get(platformKey) || 0) + 1; + platformSequenceMap.set(platformKey, nextPlatformSequence); + platformsIndexMap.set(currentOrderId, nextPlatformSequence); + } + + for (const [ orderIndex, orderRow ] of orderRowsByWave.entries()) { + const orderId = Number(orderRow && orderRow.id || 0); + if (!Number.isInteger(orderId) || orderId <= 0) { + continue; + } + const waveSequence = orderIndex + 1; + const platformsSequence = Number(platformsIndexMap.get(orderId) || waveSequence); + valueSqlList.push( + `(:warehouseId, :orderId_${rowIndex}, :waveId_${rowIndex}, :waveIndex_${rowIndex}, :platformsIndex_${rowIndex}, NOW())` + ); + replacements[`orderId_${rowIndex}`] = orderId; + replacements[`waveId_${rowIndex}`] = waveId; + replacements[`waveIndex_${rowIndex}`] = waveSequence; + replacements[`platformsIndex_${rowIndex}`] = platformsSequence; + rowIndex += 1; + } + } + + if (valueSqlList.length > 0) { + const insertSql = ` + INSERT INTO wms_order_wave_index + ( + warehouse_id, + order_id, + wave_id, + wave_index, + platforms_index, + create_at + ) + VALUES + ${valueSqlList.join(',\n ')} + `; + + await this.ctx.model.query(insertSql, { + replacements, + transaction, + }); + } + + const totalOrdersMap = new Map(); + for (const waveId of normalizedWaveIds) { + const orderRowsByWave = waveOrderRowsMap.get(waveId) || []; + totalOrdersMap.set(waveId, orderRowsByWave.length); + } + + return totalOrdersMap; + } + /** * 构建抓取候选订单筛选条件。 * @@ -951,6 +1190,14 @@ class WaveService extends OrderBaseService { }); } + await this.rebuildOrderWaveIndex({ + warehouseId, + waveId, + orderIds: grabbedOrderIds, + orderModel: model, + transaction, + }); + allWaveIds.push(waveId); allOrderIds.push(...grabbedOrderIds); fetchedOrderLogItems.push(...grabbedOrderIds.map(orderId => ({ @@ -1753,7 +2000,6 @@ class WaveService extends OrderBaseService { } - /** * 归一化拣货任务列表请求参数。 * @@ -1942,7 +2188,7 @@ class WaveService extends OrderBaseService { replacements, }; } - + buildItemSnapshotKey(itemDetails = []) { if (!Array.isArray(itemDetails) || itemDetails.length === 0) { return ''; @@ -5321,6 +5567,14 @@ class WaveService extends OrderBaseService { }); } + await this.rebuildOrderWaveIndex({ + warehouseId, + waveId, + orderIds: grabbedOrderIds, + orderModel, + transaction, + }); + await transaction.commit(); await this.batchCreateOrderOperationLogs(grabbedOrderIds.map(orderId => ({ @@ -5446,33 +5700,13 @@ class WaveService extends OrderBaseService { const updatedOrderCount = Number(Array.isArray(orderUpdateResult) ? orderUpdateResult[0] : orderUpdateResult || 0); - const remainingRows = await orderModel.findAll({ - attributes: [ - 'wave_id', - [ this.ctx.model.fn('COUNT', this.ctx.model.col('id')), 'remaining_count' ], - ], - where: { - wave_id: { - [Op.in]: affectedWaveIds, - [Op.gt]: 0, - }, - }, - group: [ 'wave_id' ], - raw: true, + const remainingCountMap = await this.replaceOrderWaveIndexByWaveIds({ + warehouseId, + waveIds: affectedWaveIds, + orderModel, transaction, }); - const remainingCountMap = new Map(); - for (const row of (Array.isArray(remainingRows) ? remainingRows : [])) { - const waveId = Number(row && row.wave_id || 0); - const remainingCount = Number(row && row.remaining_count || 0); - if (!Number.isInteger(waveId) || waveId <= 0) { - continue; - } - - remainingCountMap.set(waveId, Number.isInteger(remainingCount) && remainingCount > 0 ? remainingCount : 0); - } - const updatedWaveIds = []; const emptiedWaveIds = []; @@ -6312,6 +6546,9 @@ class WaveService extends OrderBaseService { }; }) .filter(Boolean); + const affectedOrderIds = [ ...new Set((Array.isArray(affectedOrderRows) ? affectedOrderRows : []) + .map(row => Number(row && row.id || 0)) + .filter(orderId => Number.isInteger(orderId) && orderId > 0)) ]; const orderUpdateResult = await orderModel.update({ wave_id: 0, @@ -6322,6 +6559,21 @@ class WaveService extends OrderBaseService { }, transaction, }); + + if (affectedOrderIds.length > 0) { + await this.deleteOrderWaveIndexByOrderIds({ + warehouseId, + orderIds: affectedOrderIds, + transaction, + }); + } else { + await this.deleteOrderWaveIndexByWaveIds({ + warehouseId, + waveIds: [ waveId ], + transaction, + }); + } + const currentAffectedOrderCount = Number( Array.isArray(orderUpdateResult) ? orderUpdateResult[0] : orderUpdateResult || 0 ); @@ -7464,6 +7716,14 @@ class WaveService extends OrderBaseService { transaction, }); + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + await this.replaceOrderWaveIndexByWaveIds({ + warehouseId, + waveIds: updatableWaveIds, + orderModel, + transaction, + }); + const updateMeta = Array.isArray(updateResult) ? updateResult[1] : null; const updatedWaveCount = Number( updateMeta && (updateMeta.affectedRows || updateMeta.affectedCount || updateMeta.rowCount) @@ -7573,6 +7833,14 @@ class WaveService extends OrderBaseService { transaction, }); + const orderModel = await this.getOrderModel('pendingOrder', warehouseId); + await this.replaceOrderWaveIndexByWaveIds({ + warehouseId, + waveIds: updatedWaveIds, + orderModel, + transaction, + }); + const updateMeta = Array.isArray(updateResult) ? updateResult[1] : null; const updatedWaveCount = Number( updateMeta && (updateMeta.affectedRows || updateMeta.affectedCount || updateMeta.rowCount) diff --git a/app/service/systemMethods/print.js b/app/service/systemMethods/print.js index 114b342..d4cc9d8 100644 --- a/app/service/systemMethods/print.js +++ b/app/service/systemMethods/print.js @@ -2,6 +2,10 @@ // 打印相关 Service const MainService = require('../main'); +const { + ExpressPrintPayloadBuilder, + RequestScopedPrintIdGenerator, +} = require('../../lib/express_print_payload_builder'); /** * 打印 Service @@ -29,50 +33,210 @@ class PrintService extends MainService { } + /** + * 构建 print.send 入参摘要,避免打印超大对象。 + * @param {Object} payload 原始入参。 + * @return {Object} 安全摘要信息。 + */ + buildPrintSendInputSummary(payload = {}) { + const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; + const data = normalizedPayload.data && typeof normalizedPayload.data === 'object' ? normalizedPayload.data : {}; + const waveGroups = Array.isArray(data.waveGroups) ? data.waveGroups : []; + const firstWavePlatforms = Array.isArray(waveGroups[0] && waveGroups[0].platforms) ? waveGroups[0].platforms : []; + const firstPlatformOrders = Array.isArray(firstWavePlatforms[0] && firstWavePlatforms[0].orders) + ? firstWavePlatforms[0].orders + : []; + return { + type: normalizedPayload.type || '', + printer: normalizedPayload.printer || '', + computerId: normalizedPayload.computerId || '', + printStationId: normalizedPayload.printStationId || '', + hasTemplate: Boolean(normalizedPayload.template), + requestCode: normalizedPayload.requestCode ? String(normalizedPayload.requestCode) : '', + waveGroupsCount: waveGroups.length, + firstWavePlatformsCount: firstWavePlatforms.length, + firstGroupOrdersCount: firstPlatformOrders.length, + dataKeys: Object.keys(data).slice(0, 20), + }; + } + + /** + * 统计快递 payload 摘要,避免输出完整文档对象。 + * @param {Object} payload 快递发送 payload。 + * @return {{documentCount:number}} 文档数量摘要。 + */ + summarizeExpressPayload(payload = {}) { + const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; + let documentCount = 0; + if (normalizedPayload.task && Array.isArray(normalizedPayload.task.documents)) { + documentCount = normalizedPayload.task.documents.length; + } else if (Array.isArray(normalizedPayload.documents)) { + documentCount = normalizedPayload.documents.length; + } else if (Array.isArray(normalizedPayload.document_list)) { + documentCount = normalizedPayload.document_list.length; + } else if (Array.isArray(normalizedPayload.data)) { + documentCount = normalizedPayload.data.length; + } else if (normalizedPayload.document || normalizedPayload.print_data) { + documentCount = 1; + } + return { documentCount }; + } + /** * 发送打印任务到打印电脑。 - * 仅在 type=customize 时要求 printer、template、page_width、page_height、template_content。 + * 仅在 type=customize 时要求 printer、template、page_width、page_height、template_content。 * @param {Object} _data 打印请求参数 - * @param {string} [_data.printer] 打印机名称(type=customize 必填,type=express 可不传) + * @param {string} [_data.printer] 打印机名称(type=customize 必填,type=express 忽略) * @param {string} _data.type 打印类型,支持 customize/express * @param {Object} [_data.template] 打印模板对象(customize 必填) - * @param {Object} _data.data 打印业务数据 - * @param {string} _data.computerId 打印电脑 ID - * @param {string} [_data.timestamp] 业务时间戳 - * @param {number} [_data.count] 打印份数 - * @returns {Promise} 统一返回结构 + * @param {Object} _data.data 打印业务数据(express 场景要求 data.waveGroups) + * @param {string|number} [_data.printStationId] 打印台 ID(express 必填) + * @param {string} [_data.requestCode] 请求参数码(express 必填,用于本次请求内 ID 唯一化) + * @param {string} [_data.computerId] 打印电脑 ID(customize 必填,express 忽略) + * @param {string} [_data.timestamp] 业务时间戳(express 忽略) + * @param {number} [_data.count] 打印份数(express 忽略) + * @return {Promise} 统一返回结构 */ async send(_data) { const { ctx } = this; const warehouseId = ctx.user.store_id; - const { printer, type, template, data, computerId, timestamp, count } = _data; - // 生成打印编号并记录到数据库 - const printRecord = await ctx.model.PrintRecord.create({ - warehouse_id: warehouseId, - computer_id: computerId, + const { printer, type, - data: { template, data }, - status: 'pending', + template, + data, + computerId, + timestamp, + count, + printStationId, + requestCode, + } = _data; + this.ctx.logger.info('[print.send] 入参接收', { + warehouseId, + inputSummary: this.buildPrintSendInputSummary(_data), }); + this.ctx.logger.info('[print.send] 分支判定', { + warehouseId, + type, + isExpress: type === 'express', + isCustomize: type === 'customize', + }); + if (type === 'express') { + const expressValidationResult = this.validateExpressSendInput({ data, printStationId, requestCode }); + if (expressValidationResult) { + this.ctx.logger.warn('[print.send] express 参数校验失败', { + warehouseId, + printStationId, + requestCode: requestCode ? String(requestCode) : '', + waveGroupsCount: Array.isArray(data && data.waveGroups) ? data.waveGroups.length : 0, + }); + this.ctx.logger.error('[print.send] 最终返回 failure', { + warehouseId, + type, + reason: 'express 参数校验失败', + }); + return expressValidationResult; + } + this.ctx.logger.info('[print.send] express 参数校验通过', { + warehouseId, + printStationId, + waveGroupsCount: Array.isArray(data && data.waveGroups) ? data.waveGroups.length : 0, + }); + } + let printRecord = null; + if (type !== 'express') { + // 生成打印编号并记录到数据库 + try { + printRecord = await ctx.model.PrintRecord.create({ + warehouse_id: warehouseId, + computer_id: computerId, + printer, + type, + data: { template, data }, + status: 'pending', + }); + this.ctx.logger.info('[print.send] PrintRecord 创建成功', { + warehouseId, + type, + printId: printRecord.id, + computerId, + printer, + }); + } catch (error) { + this.ctx.logger.error('[print.send] PrintRecord 创建失败', { + warehouseId, + type, + computerId, + printer, + error: error && error.message ? error.message : `${error}`, + stack: error && error.stack ? error.stack : '', + }); + throw error; + } + } // 处理后的数据 let processedData = {}; switch (type) { case 'customize': { if (printer === undefined || printer === null || printer === '') { + this.ctx.logger.warn('[print.send] customize 参数校验失败-printer 为空', { + warehouseId, + type, + }); + this.ctx.logger.error('[print.send] 最终返回 failure', { + warehouseId, + type, + reason: 'printer 参数不能为空', + }); return this.fail('type=customize 时 printer 参数不能为空', { code: 400 }); } if (!template || typeof template !== 'object' || Array.isArray(template)) { + this.ctx.logger.warn('[print.send] customize 参数校验失败-template 非对象', { + warehouseId, + type, + }); + this.ctx.logger.error('[print.send] 最终返回 failure', { + warehouseId, + type, + reason: 'template 参数不合法', + }); return this.fail('type=customize 时 template 参数不能为空', { code: 400 }); } const { page_width, page_height, template_content } = template; if (page_width === undefined || page_width === null || page_width === '') { + this.ctx.logger.warn('[print.send] customize 参数校验失败-page_width 为空', { + warehouseId, + type, + }); + this.ctx.logger.error('[print.send] 最终返回 failure', { + warehouseId, + type, + reason: 'page_width 参数不能为空', + }); return this.fail('type=customize 时 page_width 参数不能为空', { code: 400 }); } if (page_height === undefined || page_height === null || page_height === '') { + this.ctx.logger.warn('[print.send] customize 参数校验失败-page_height 为空', { + warehouseId, + type, + }); + this.ctx.logger.error('[print.send] 最终返回 failure', { + warehouseId, + type, + reason: 'page_height 参数不能为空', + }); return this.fail('type=customize 时 page_height 参数不能为空', { code: 400 }); } if (!Array.isArray(template_content)) { + this.ctx.logger.warn('[print.send] customize 参数校验失败-template_content 非数组', { + warehouseId, + type, + }); + this.ctx.logger.error('[print.send] 最终返回 failure', { + warehouseId, + type, + reason: 'template_content 参数不合法', + }); return this.fail('type=customize 时 template_content 必须是数组', { code: 400 }); } let htm = ``; @@ -176,12 +340,119 @@ class PrintService extends MainService { htm, lodopkey: [ '', '13528A153BAEE3A0254B9507DCDE2839', 'EDE92F75B6A3D917F65910', 'D60BC84D7CF2DE18156A6F88987304CB6D8' ], }; + this.ctx.logger.info('[print.send] customize payload 组装完成', { + warehouseId, + type, + pageWidth: page_width, + pageHeight: page_height, + templateItemCount: template_content.length, + }); break; } - case 'express': - - break; + case 'express': { + const expressPrintStation = await this.loadExpressPrintStation({ printStationId, warehouseId }); + if (!expressPrintStation.success) { + this.ctx.logger.error('[print.send] 最终返回 failure', { + warehouseId, + type, + reason: expressPrintStation.error, + }); + return this.fail(expressPrintStation.error, { code: 400 }); + } + const expressRecordFields = this.buildExpressPrintRecordFields(expressPrintStation.data); + if (!expressRecordFields.success) { + this.ctx.logger.error('[print.send] 最终返回 failure', { + warehouseId, + type, + reason: expressRecordFields.error, + }); + return this.fail(expressRecordFields.error, { code: 400 }); + } + + const platformCodes = this.collectExpressPlatformCodes(data.waveGroups); + const platformComponentsResult = await this.loadExpressPlatformComponents({ platformCodes }); + if (!platformComponentsResult.success) { + this.ctx.logger.error('[print.send] 最终返回 failure', { + warehouseId, + type, + reason: platformComponentsResult.error, + }); + return this.fail(platformComponentsResult.error, { code: 400 }); + } + const componentOnlineResult = await this.validateExpressComponentsOnline({ + computerId: expressRecordFields.data.computer_id, + platformComponents: platformComponentsResult.data, + }); + if (!componentOnlineResult.success) { + this.ctx.logger.error('[print.send] 最终返回 failure', { + warehouseId, + type, + reason: componentOnlineResult.error, + }); + return this.fail(componentOnlineResult.error, { code: 400 }); + } + try { + printRecord = await ctx.model.PrintRecord.create({ + warehouse_id: warehouseId, + computer_id: expressRecordFields.data.computer_id, + printer: expressRecordFields.data.printer, + type, + data: { template, data }, + status: 'pending', + }); + this.ctx.logger.info('[print.send] PrintRecord 创建成功', { + warehouseId, + type, + printId: printRecord.id, + computerId: expressRecordFields.data.computer_id, + printer: expressRecordFields.data.printer, + }); + } catch (error) { + this.ctx.logger.error('[print.send] PrintRecord 创建失败', { + warehouseId, + type, + computerId: expressRecordFields.data.computer_id, + printer: expressRecordFields.data.printer, + error: error && error.message ? error.message : `${error}`, + stack: error && error.stack ? error.stack : '', + }); + throw error; + } + const payloadBuilder = new ExpressPrintPayloadBuilder({ baseDir: this.app.baseDir }); + const idGenerator = new RequestScopedPrintIdGenerator(requestCode); + const expressSendResult = await this.sendExpressWaveGroups({ + warehouseId, + waveGroups: data.waveGroups, + printStation: expressPrintStation.data, + payloadBuilder, + idGenerator, + printRecordId: printRecord.id, + platformComponents: platformComponentsResult.data, + }); + if (!expressSendResult.success) { + await printRecord.update({ status: 'failed', error_message: expressSendResult.error }); + this.ctx.logger.error('[print.send] 最终返回 failure', { + warehouseId, + type, + printId: printRecord.id, + reason: expressSendResult.error, + }); + return this.fail(expressSendResult.error, { code: 504, printId: printRecord.id }); + } + await printRecord.update({ status: 'sent' }); + this.ctx.logger.info('[print.send] 最终返回 success', { + warehouseId, + type, + printId: printRecord.id, + }); + return this.success('发送打印任务成功', { code: 200, printId: printRecord.id }); + } default: + this.ctx.logger.error('[print.send] 最终返回 failure', { + warehouseId, + type, + reason: '不支持的打印类型', + }); return this.fail('不支持的打印类型', 1001); } @@ -194,15 +465,531 @@ class PrintService extends MainService { count, printId: printRecord.id, }; + const sendStartAt = Date.now(); const res = await this.service.systems.print.index.sendToComputer({ warehouse: warehouseId, computerId, data: printData }); + const sendDurationMs = Date.now() - sendStartAt; + if (res.status === 'success') { + this.ctx.logger.info('[print.send] sendToComputer 调用成功', { + warehouseId, + type, + printId: printRecord.id, + computerId, + durationMs: sendDurationMs, + }); + } else { + this.ctx.logger.error('[print.send] sendToComputer 调用失败', { + warehouseId, + type, + printId: printRecord.id, + computerId, + durationMs: sendDurationMs, + error: res && res.error ? res.error : '打印服务返回失败', + }); + } // 发送成功后更新打印记录状态 if (res.status === 'success') { await printRecord.update({ status: 'sent' }); + this.ctx.logger.info('[print.send] 最终返回 success', { + warehouseId, + type, + printId: printRecord.id, + }); return this.success('发送打印任务成功', { code: 200, printId: printRecord.id }); } await printRecord.update({ status: 'failed', error_message: res.error }); + this.ctx.logger.error('[print.send] 最终返回 failure', { + warehouseId, + type, + printId: printRecord.id, + reason: res.error || '打印服务返回失败', + }); return this.fail(res.error, { code: 504, printId: printRecord.id }); } + + /** + * 校验快递打印请求的必要参数。 + * @param {Object} payload 校验参数。 + * @param {Object} payload.data 请求 data。 + * @param {number|string} payload.printStationId 打印台 ID。 + * @param {string} payload.requestCode 请求参数码。 + * @return {Object|null} 失败时返回 fail 响应,成功返回 null。 + */ + validateExpressSendInput(payload = {}) { + const requestData = payload && typeof payload === 'object' ? payload : {}; + const waveGroups = Array.isArray(requestData.data && requestData.data.waveGroups) + ? requestData.data.waveGroups + : []; + if (waveGroups.length === 0) { + this.ctx.logger.warn('[print.send] express 参数校验失败-data.waveGroups 为空', { + printStationId: requestData.printStationId || '', + requestCode: requestData.requestCode ? String(requestData.requestCode) : '', + }); + return this.fail('type=express 时 data.waveGroups 必须是非空数组', { code: 400 }); + } + + const normalizedPrintStationId = String(requestData.printStationId || '').trim(); + if (!normalizedPrintStationId) { + this.ctx.logger.warn('[print.send] express 参数校验失败-printStationId 为空', { + requestCode: requestData.requestCode ? String(requestData.requestCode) : '', + waveGroupsCount: waveGroups.length, + }); + return this.fail('type=express 时 printStationId 参数不能为空', { code: 400 }); + } + + const normalizedRequestCode = String(requestData.requestCode || '').trim(); + if (!normalizedRequestCode) { + this.ctx.logger.warn('[print.send] express 参数校验失败-requestCode 为空', { + printStationId: normalizedPrintStationId, + waveGroupsCount: waveGroups.length, + }); + return this.fail('type=express 时 requestCode 参数不能为空', { code: 400 }); + } + + return null; + } + + /** + * 查询并校验快递打印台。 + * @param {Object} payload 查询参数。 + * @param {number|string} payload.printStationId 打印台 ID。 + * @param {number|string} payload.warehouseId 仓库 ID。 + * @return {Promise<{success:boolean,data?:Object,error?:string}>} 查询结果。 + */ + async loadExpressPrintStation(payload = {}) { + const { ctx } = this; + const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; + const printStation = await ctx.model.PrintStations.findOne({ + where: { + id: normalizedPayload.printStationId, + warehouse_id: normalizedPayload.warehouseId, + deleted: 0, + }, + raw: true, + }); + if (!printStation) { + this.ctx.logger.warn('[print.send] 打印台查询失败', { + printStationId: normalizedPayload.printStationId, + warehouseId: normalizedPayload.warehouseId, + }); + return { + success: false, + error: '打印台不存在', + }; + } + + this.ctx.logger.info('[print.send] 打印台查询成功', { + printStationId: printStation.id, + warehouseId: normalizedPayload.warehouseId, + computerId: printStation.computer_id || '', + defaultPrinterName: printStation.default_printer_name || '', + }); + + return { + success: true, + data: printStation, + }; + } + + /** + * 组装快递打印记录的必填字段,避免写入 null。 + * @param {Object} printStation 打印台配置。 + * @return {{success:boolean,data?:{computer_id:string,printer:string},error?:string}} 组装结果。 + */ + buildExpressPrintRecordFields(printStation = {}) { + const normalizedStation = printStation && typeof printStation === 'object' ? printStation : {}; + const computerId = String(normalizedStation.computer_id || '').trim(); + if (!computerId) { + return { + success: false, + error: '打印台未配置打印电脑', + }; + } + + const defaultPrinterName = String(normalizedStation.default_printer_name || '').trim(); + return { + success: true, + data: { + computer_id: computerId, + printer: defaultPrinterName || 'EXPRESS_DYNAMIC_PRINTER', + }, + }; + } + + /** + * 收集 express 请求中涉及的平台编码列表。 + * @param {Array} waveGroups 波次分组数据。 + * @return {Array} 去重后的平台编码列表。 + */ + collectExpressPlatformCodes(waveGroups = []) { + const normalizedWaveGroups = Array.isArray(waveGroups) ? waveGroups : []; + const platformCodeSet = new Set(); + for (const waveGroup of normalizedWaveGroups) { + const platforms = Array.isArray(waveGroup && waveGroup.platforms) ? waveGroup.platforms : []; + for (const platformGroup of platforms) { + const orders = Array.isArray(platformGroup && platformGroup.orders) ? platformGroup.orders : []; + if (orders.length === 0) { + continue; + } + const platformCode = String(platformGroup && platformGroup.platform ? platformGroup.platform : '').trim(); + if (platformCode) { + platformCodeSet.add(platformCode); + } + } + } + return Array.from(platformCodeSet); + } + + /** + * 加载并校验 express 请求涉及平台的打印组件配置。 + * @param {Object} payload 查询参数。 + * @param {Array} payload.platformCodes 平台编码列表。 + * @return {Promise<{success:boolean,data?:Object,error?:string}>} 查询与校验结果。 + */ + async loadExpressPlatformComponents(payload = {}) { + const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; + const platformCodes = Array.isArray(normalizedPayload.platformCodes) + ? normalizedPayload.platformCodes.filter(item => String(item || '').trim()) + : []; + if (platformCodes.length === 0) { + return { + success: false, + error: 'type=express 时未识别到有效平台编码', + }; + } + + const platformRows = await this.ctx.model.Platform.findAll({ + attributes: [ 'code', 'component' ], + where: { + code: platformCodes, + }, + raw: true, + }); + const platformComponentMap = {}; + for (const row of platformRows) { + const platformCode = String(row && row.code ? row.code : '').trim(); + if (!platformCode) { + continue; + } + platformComponentMap[platformCode] = String(row && row.component ? row.component : '').trim(); + } + + for (const platformCode of platformCodes) { + const component = String(platformComponentMap[platformCode] || '').trim(); + if (!component) { + return { + success: false, + error: `平台 ${platformCode} 未配置打印组件`, + }; + } + } + + return { + success: true, + data: platformComponentMap, + }; + } + + /** + * 校验 express 请求涉及组件是否全部在线。 + * @param {Object} payload 校验参数。 + * @param {string} payload.computerId 打印电脑 ID。 + * @param {Object} payload.platformComponents 平台到组件映射。 + * @return {Promise<{success:boolean,error?:string}>} 校验结果。 + */ + async validateExpressComponentsOnline(payload = {}) { + const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; + const computerId = String(normalizedPayload.computerId || '').trim(); + const platformComponents = normalizedPayload.platformComponents && typeof normalizedPayload.platformComponents === 'object' + ? normalizedPayload.platformComponents + : {}; + if (!computerId) { + return { + success: false, + error: '打印台未配置打印电脑', + }; + } + + const redisPrinter = this.app.redis.get('printer'); + const entries = Object.entries(platformComponents); + for (const entry of entries) { + const platformCode = String(entry[0] || '').trim(); + const component = String(entry[1] || '').trim(); + const statusKey = `printer:${computerId}:name:${component}:status`; + const componentStatus = await redisPrinter.get(statusKey); + if (componentStatus !== 'connected') { + return { + success: false, + error: `平台 ${platformCode} 打印组件 ${component} 未在线`, + }; + } + } + + return { success: true }; + } + + /** + * 根据平台快递编码解析打印机名称。 + * @param {Object} payload 解析参数。 + * @param {Object} payload.printStation 打印台配置。 + * @param {string} payload.sysLogisticsCode 系统快递编码。 + * @return {{success:boolean,data?:string,error?:string}} 解析结果。 + */ + resolveExpressPrinterName(payload = {}) { + const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; + const printStation = normalizedPayload.printStation && typeof normalizedPayload.printStation === 'object' + ? normalizedPayload.printStation + : {}; + let subjectConfig = printStation.subject_config; + if (typeof subjectConfig === 'string') { + try { + subjectConfig = JSON.parse(subjectConfig); + } catch (error) { + subjectConfig = {}; + } + } + if (!subjectConfig || typeof subjectConfig !== 'object' || Array.isArray(subjectConfig)) { + subjectConfig = {}; + } + + const expressBindPrinter = Array.isArray(subjectConfig.express_bind_printer) + ? subjectConfig.express_bind_printer + : []; + const sysLogisticsCode = String(normalizedPayload.sysLogisticsCode || '').trim(); + const matchedPrinter = expressBindPrinter.find(item => { + const sourceItem = item && typeof item === 'object' ? item : {}; + return String(sourceItem.express_code || '').trim() === sysLogisticsCode; + }); + const printerName = String( + matchedPrinter && matchedPrinter.printer_name + ? matchedPrinter.printer_name + : (printStation.default_printer_name || '') + ).trim(); + if (!printerName) { + return { + success: false, + error: '打印台未配置默认打印机', + }; + } + + this.ctx.logger.info('[print.send] resolveExpressPrinterName 成功', { + sysLogisticsCode, + printerName, + matched: Boolean(matchedPrinter), + matchSource: matchedPrinter ? '命中快递绑定' : '回退默认打印机', + }); + + return { + success: true, + data: printerName, + }; + } + + /** + * 串行发送快递打印任务(波次 -> 平台快递组)。 + * @param {Object} payload 发送参数。 + * @param {number|string} payload.warehouseId 仓库 ID。 + * @param {Array} payload.waveGroups 波次分组。 + * @param {Object} payload.printStation 打印台配置。 + * @param {Object} payload.payloadBuilder 快递模板组装器。 + * @param {Object} payload.idGenerator 本次请求 ID 生成器。 + * @param {number|string} payload.printRecordId 打印记录 ID。 + * @param {Object} payload.platformComponents 平台到打印组件映射。 + * @return {Promise<{success:boolean,error?:string}>} 发送结果。 + */ + async sendExpressWaveGroups(payload = {}) { + const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; + const waveGroups = Array.isArray(normalizedPayload.waveGroups) + ? normalizedPayload.waveGroups + : []; + for (const waveGroup of waveGroups) { + const platforms = Array.isArray(waveGroup && waveGroup.platforms) ? waveGroup.platforms : []; + for (const platformGroup of platforms) { + const orders = Array.isArray(platformGroup && platformGroup.orders) ? platformGroup.orders : []; + if (orders.length === 0) { + continue; + } + const groupSummary = { + waveNo: waveGroup && waveGroup.wave_no ? waveGroup.wave_no : '', + platform: platformGroup && platformGroup.platform ? platformGroup.platform : '', + sysLogisticsCode: platformGroup && platformGroup.sys_logistics_code ? platformGroup.sys_logistics_code : '', + ordersCount: orders.length, + printRecordId: normalizedPayload.printRecordId, + }; + this.ctx.logger.info('[print.send] 平台快递组发送开始', groupSummary); + + const platformCode = String(platformGroup && platformGroup.platform ? platformGroup.platform : '').trim(); + const component = String( + normalizedPayload.platformComponents + && normalizedPayload.platformComponents[platformCode] + ? normalizedPayload.platformComponents[platformCode] + : '' + ).trim(); + if (!component) { + this.ctx.logger.error('[print.send] 平台快递组发送失败-打印组件缺失', { + ...groupSummary, + reason: `平台 ${platformCode} 未配置打印组件`, + }); + this.ctx.logger.error('[print.send] 平台快递组发送结束', { + ...groupSummary, + status: 'failure', + reason: `平台 ${platformCode} 未配置打印组件`, + }); + return { + success: false, + error: `平台 ${platformCode} 未配置打印组件`, + }; + } + + const printerNameResult = this.resolveExpressPrinterName({ + printStation: normalizedPayload.printStation, + sysLogisticsCode: platformGroup && platformGroup.sys_logistics_code, + }); + if (!printerNameResult.success) { + this.ctx.logger.error('[print.send] 平台快递组发送失败-打印机解析失败', { + ...groupSummary, + reason: printerNameResult.error, + }); + this.ctx.logger.error('[print.send] 平台快递组发送结束', { + ...groupSummary, + status: 'failure', + reason: printerNameResult.error, + }); + return { + success: false, + error: printerNameResult.error, + }; + } + + const normalizedPlatformCode = String(platformGroup && platformGroup.platform ? platformGroup.platform : '').trim().toLowerCase(); + const isKuaishouPlatform = normalizedPlatformCode === 'kuaishou' || normalizedPlatformCode === 'ks'; + const orderBatches = []; + if (isKuaishouPlatform) { + for (let index = 0; index < orders.length; index += 10) { + orderBatches.push(orders.slice(index, index + 10)); + } + } else { + orderBatches.push(orders); + } + const totalDocumentCount = orders.length; + + for (let batchIndex = 0; batchIndex < orderBatches.length; batchIndex++) { + const batchOrders = orderBatches[batchIndex]; + const batchSummary = { + ...groupSummary, + batchIndex: batchIndex + 1, + batchCount: orderBatches.length, + batchOrdersCount: batchOrders.length, + }; + let requestPayload; + try { + requestPayload = normalizedPayload.payloadBuilder.buildPayload({ + platform: platformGroup && platformGroup.platform, + printerName: printerNameResult.data, + orders: batchOrders, + idGenerator: normalizedPayload.idGenerator, + }); + if (isKuaishouPlatform && requestPayload && requestPayload.task && typeof requestPayload.task === 'object' && !Array.isArray(requestPayload.task)) { + requestPayload.task.firstDocumentNumber = batchIndex * 10 + 1; + requestPayload.task.totalDocumentCount = totalDocumentCount; + } + const payloadSummary = this.summarizeExpressPayload(requestPayload); + this.ctx.logger.info('[print.send] 组装 payload 成功', { + ...batchSummary, + platform: platformGroup && platformGroup.platform ? platformGroup.platform : '', + ordersCount: batchOrders.length, + documentCount: payloadSummary.documentCount, + }); + } catch (error) { + this.ctx.logger.error('[print.send] 组装 payload 失败', { + ...batchSummary, + platform: platformGroup && platformGroup.platform ? platformGroup.platform : '', + ordersCount: batchOrders.length, + reason: error && error.message ? error.message : '快递打印任务组装失败', + }); + this.ctx.logger.error('[print.send] 平台快递组发送结束', { + ...batchSummary, + status: 'failure', + reason: error && error.message ? error.message : '快递打印任务组装失败', + }); + return { + success: false, + error: error && error.message ? error.message : '快递打印任务组装失败', + }; + } + + const printData = { + printer: printerNameResult.data, + component, + type: 'express', + data: requestPayload, + printId: normalizedPayload.printRecordId, + }; + const sendStartAt = Date.now(); + let sendResult; + try { + sendResult = await this.service.systems.print.index.sendToComputer({ + warehouse: normalizedPayload.warehouseId, + computerId: normalizedPayload.printStation.computer_id, + data: printData, + }); + } catch (error) { + const sendDurationMs = Date.now() - sendStartAt; + this.ctx.logger.error('[print.send] sendToComputer 调用失败', { + ...batchSummary, + computerId: normalizedPayload.printStation.computer_id, + durationMs: sendDurationMs, + reason: error && error.message ? error.message : `${error}`, + }); + this.ctx.logger.error('[print.send] 平台快递组发送结束', { + ...batchSummary, + computerId: normalizedPayload.printStation.computer_id, + status: 'failure', + reason: error && error.message ? error.message : `${error}`, + }); + return { + success: false, + error: error && error.message ? error.message : '打印服务调用失败', + }; + } + const sendDurationMs = Date.now() - sendStartAt; + if (sendResult.status !== 'success') { + this.ctx.logger.error('[print.send] sendToComputer 调用失败', { + ...batchSummary, + computerId: normalizedPayload.printStation.computer_id, + durationMs: sendDurationMs, + reason: sendResult.error || '打印服务返回失败', + }); + this.ctx.logger.error('[print.send] 平台快递组发送结束', { + ...batchSummary, + computerId: normalizedPayload.printStation.computer_id, + status: 'failure', + reason: sendResult.error || '打印服务返回失败', + }); + } else { + this.ctx.logger.info('[print.send] sendToComputer 调用成功', { + ...batchSummary, + computerId: normalizedPayload.printStation.computer_id, + durationMs: sendDurationMs, + }); + } + if (sendResult.status !== 'success') { + return { + success: false, + error: sendResult.error || '打印服务返回失败', + }; + } + this.ctx.logger.info('[print.send] 平台快递组发送结束', { + ...batchSummary, + computerId: normalizedPayload.printStation.computer_id, + status: 'success', + }); + } + } + } + + return { success: true }; + } + async getPrintResult(data) { const { ctx } = this; const warehouseId = ctx.user.store_id; @@ -317,6 +1104,7 @@ class PrintService extends MainService { /** * 2. 获取单个打印台 * @param {Object} data { id } + * @return {Promise} 返回打印台详情(不包含 warehouse_id) */ async getItem(data) { const { ctx } = this; @@ -324,12 +1112,14 @@ class PrintService extends MainService { if (!id) return this.fail('参数错误', 1001); const item = await ctx.model.PrintStations.findOne({ where: { id }, raw: true }); if (!item) return this.fail('打印台不存在', 1002); - return this.success('success', { ...item, code: 0 }); + const rest = { ...item }; + delete rest.warehouse_id; + return this.success('success', { ...rest, code: 0 }); } /** * 3. 添加打印台 * @param {Object} data { id, name, computer_id, custom_barcode } - * @returns {Promise} 返回新增结果。 + * @return {Promise} 返回新增结果。 */ async add(data) { const { ctx } = this; @@ -371,7 +1161,7 @@ class PrintService extends MainService { /** * 3. 修改打印台 * @param {Object} data { id, name, computer_id, custom_barcode } - * @returns {Promise} 返回更新结果。 + * @return {Promise} 返回更新结果。 */ async updateItem(data) { const { ctx } = this; @@ -444,7 +1234,7 @@ class PrintService extends MainService { * @param {string} data.defaultPrinter 默认打印机名称,必填。 * @param {Array} data.express 快递绑定数组,必填。 * @param {number|string} data.print_station_id 打印台 ID,必填。 - * @returns {Promise} 保存结果。 + * @return {Promise} 保存结果。 */ async savePrinters(data) { const { ctx } = this; diff --git a/app/service/systemMethods/storage/report.js b/app/service/systemMethods/storage/report.js new file mode 100644 index 0000000..8cb5669 --- /dev/null +++ b/app/service/systemMethods/storage/report.js @@ -0,0 +1,298 @@ +'use strict'; + +const MainService = require('../../main'); + +const STORAGE_REPORT_EXPORT_TASK_CACHE_KEY_PREFIX = 'storage_report_export_task_'; +const STORAGE_REPORT_EXPORT_TASK_CACHE_TTL_SECONDS = 1800; + +/** + * 系统方法层:storage.report(库存流水报表接口包装层)。 + */ +class StorageReportMethodService extends MainService { + constructor(ctx) { + super(ctx); + const _noNeedLogin = ''; + const _noNeedRight = 'search,export,exportTaskProgress'; + const _noNeedLog = 'search,export,exportTaskProgress'; + const _noNeedAuth = 'search,export,exportTaskProgress'; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 查询库存流水统计报表。 + * @param {Object} data 请求体 + * @param {Object} [data.where] 查询条件 + * @param {Object} [data.sort] 排序参数 + * @param {string} [data.sort.sortField] 排序字段(兼容:sort_field) + * @param {string} [data.sort.sortOrder] 排序顺序(兼容:sort_order) + * @param {string|Date} [data.where.start_time] 开始时间 + * @param {string|Date} [data.where.end_time] 结束时间 + * @param {boolean|string|number} [data.where.by_space=false] 是否按库位返回 + * @param {Array} [data.where.store_ids] 货主ID列表 + * @return {Promise} 统一 success 包装 + */ + async search(data = {}) { + const { service } = this; + const { whereValue = {} } = this.prepareWhereContext(data); + const { + start_time: startTime, + end_time: endTime, + by_space: bySpace, + store_ids: storeIds, + sort_field: whereSortField, + sortField: whereSortFieldCamel, + sort_order: whereSortOrder, + sortOrder: whereSortOrderCamel, + } = whereValue; + + const { sort = {} } = data; + const { + sort_field: sortFieldSnake, + sortField: sortFieldCamel, + sort_order: sortOrderSnake, + sortOrder: sortOrderCamel, + } = sort || {}; + + const result = await service.systems.storage.report.search(startTime, endTime, bySpace, storeIds, { + sortField: sortFieldCamel || sortFieldSnake || whereSortFieldCamel || whereSortField, + sortOrder: sortOrderCamel || sortOrderSnake || whereSortOrderCamel || whereSortOrder, + }); + return this.success('ok', result); + } + + /** + * 提交库存流水统计报表导出任务。 + * @param {Object} data 请求体 + * @param {Object} [data.where] 查询条件 + * @param {Object} [data.sort] 排序参数 + * @param {string} [data.sort.sortField] 排序字段(兼容:sort_field) + * @param {string} [data.sort.sortOrder] 排序顺序(兼容:sort_order) + * @param {string|Date} [data.where.start_time] 开始时间 + * @param {string|Date} [data.where.end_time] 结束时间 + * @param {boolean|string|number} [data.where.by_space=false] 是否按库位返回 + * @param {Array} [data.where.store_ids] 货主ID列表 + * @return {Promise} 统一 success 包装(返回任务ID) + */ + async export(data = {}) { + const { service } = this; + const { whereValue = {} } = this.prepareWhereContext(data); + const { + start_time: startTime, + end_time: endTime, + by_space: bySpace, + store_ids: storeIds, + sort_field: whereSortField, + sortField: whereSortFieldCamel, + sort_order: whereSortOrder, + sortOrder: whereSortOrderCamel, + } = whereValue; + + const { sort = {} } = data; + const { + sort_field: sortFieldSnake, + sortField: sortFieldCamel, + sort_order: sortOrderSnake, + sortOrder: sortOrderCamel, + } = sort || {}; + + const taskId = this.generateExportTaskId(); + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: 0, + message: '导出任务已提交', + result: null, + error: '', + }; + + await this.setExportTaskProgress(taskId, taskPayload); + + const sortOption = { + sortField: sortFieldCamel || sortFieldSnake || whereSortFieldCamel || whereSortField, + sortOrder: sortOrderCamel || sortOrderSnake || whereSortOrderCamel || whereSortOrder, + }; + + setImmediate(async () => { + try { + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: 10, + message: '导出任务执行中', + result: null, + error: '', + }); + + const result = await service.systems.storage.report.export(startTime, endTime, bySpace, storeIds, sortOption); + + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + message: '导出任务完成', + result, + error: '', + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + message: '导出任务失败', + result: null, + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } + + /** + * 查询库存流水统计报表导出任务进度。 + * @param {Object} data 请求体 + * @param {string} [data.task_id] 任务ID(下划线写法) + * @param {string} [data.taskId] 任务ID(驼峰写法) + * @return {Promise} 统一 success 包装 + */ + async exportTaskProgress(data = {}) { + const taskId = this.normalizeExportTaskId(data); + if (!taskId) { + return this.success('ok', { + task_id: '', + status: 'not_found', + progress: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const cachedTask = await this.getExportTaskProgress(taskId); + if (!cachedTask) { + return this.success('ok', { + task_id: taskId, + status: 'not_found', + progress: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {}; + const downloadUrl = String( + safeResult.url + || safeResult.cndUrl + || safeResult.cosUrl + || safeResult.fileKey + || '' + ); + + return this.success('ok', { + task_id: taskId, + ...cachedTask, + download_url: downloadUrl, + }); + } + + /** + * 生成导出任务ID。 + * @return {string} 导出任务ID + */ + generateExportTaskId() { + const warehouseId = this.ctx?.user?.store_id || 'unknown'; + const timestamp = Date.now(); + const randomToken = Math.random().toString(36).slice(2, 10); + return `storage_report_export_${warehouseId}_${timestamp}_${randomToken}`; + } + + /** + * 规范导出任务ID。 + * @param {Object} data 请求体 + * @param {string} [data.task_id] 任务ID(下划线写法) + * @param {string} [data.taskId] 任务ID(驼峰写法) + * @return {string} 归一化后的任务ID + */ + normalizeExportTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 获取导出任务缓存键。 + * @param {string} taskId 任务ID + * @return {string} 缓存键 + */ + getExportTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + + return `${STORAGE_REPORT_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入导出任务进度缓存。 + * @param {string} taskId 任务ID + * @param {Object} payload 任务状态载荷 + * @return {Promise} 无返回值 + */ + async setExportTaskProgress(taskId = '', payload = {}) { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.setCacheAsync !== 'function') { + return; + } + + const safePayload = this.isPlainObject(payload) ? payload : {}; + const progressPayload = { + task_id: String(taskId || '').trim(), + status: String(safePayload.status || 'submitted').trim() || 'submitted', + progress: Number.isFinite(Number(safePayload.progress)) ? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress)))) : 0, + message: String(safePayload.message || ''), + result: safePayload.result ?? null, + error: String(safePayload.error || ''), + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync(cacheKey, progressPayload, STORAGE_REPORT_EXPORT_TASK_CACHE_TTL_SECONDS); + } catch (error) { + this.ctx.logger.warn('[storage.report.export] 写入导出任务缓存失败: %s', error && error.message ? error.message : error); + } + } + + /** + * 读取导出任务进度缓存。 + * @param {string} taskId 任务ID + * @return {Promise} 任务缓存 + */ + async getExportTaskProgress(taskId = '') { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.getCacheAsync !== 'function') { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + return cached; + } catch (error) { + this.ctx.logger.warn('[storage.report.export] 读取导出任务缓存失败: %s', error && error.message ? error.message : error); + return null; + } + } +} + +module.exports = StorageReportMethodService; diff --git a/app/service/systems/auth/role_permission.js b/app/service/systems/auth/role_permission.js index 8ee5efc..6a7077d 100644 --- a/app/service/systems/auth/role_permission.js +++ b/app/service/systems/auth/role_permission.js @@ -3,6 +3,27 @@ const Service = require('egg').Service; class RolePermissionService extends Service { + /** + * 规范化权限类型过滤参数 + * @param {string|string[]|undefined|null} type 权限类型过滤值 + * @return {null|string|string[]} 可用于 where.type 的过滤值;null 表示不加过滤 + */ + normalizeTypeFilter(type) { + if (Array.isArray(type)) { + const normalizedTypes = Array.from(new Set(type + .map(item => (typeof item === 'string' ? item.trim() : '')) + .filter(Boolean))); + return normalizedTypes.length > 0 ? normalizedTypes : null; + } + + if (typeof type === 'string') { + const normalizedType = type.trim(); + return normalizedType || null; + } + + return null; + } + normalizePermissionSet(rawValue) { if (rawValue === undefined || rawValue === null) { return { allAccess: false, permissionIds: [] }; @@ -113,8 +134,13 @@ class RolePermissionService extends Service { status: options.includeDisabled === true ? { [Op.in]: [ 0, 1 ] } : 1, }; - if (options.type) { - permissionWhere.type = options.type; + const typeFilter = this.normalizeTypeFilter(options.type); + if (Array.isArray(typeFilter) && typeFilter.length > 0) { + permissionWhere.type = { + [Op.in]: typeFilter, + }; + } else if (typeFilter) { + permissionWhere.type = typeFilter; } if (allAccess) { diff --git a/app/service/systems/auth/user.js b/app/service/systems/auth/user.js index 2e40e1f..383e5a5 100644 --- a/app/service/systems/auth/user.js +++ b/app/service/systems/auth/user.js @@ -16,6 +16,67 @@ const WECHAT_LOGIN_EVENT_CHANNEL_PREFIX = 'user:wechat:login:event:'; const WECHAT_LOGIN_CACHE_TTL_SECONDS = 60; class UserService extends Service { + /** + * 根据平台解析菜单权限类型过滤条件 + * @param {string} platform 平台标识 + * @return {{ type: object }} 菜单权限类型过滤条件 + */ + getMenuTypeWhereByPlatform(platform) { + const { Op } = this.app.Sequelize; + const normalizedPlatform = String(platform || '').trim().toLowerCase(); + const platformTypeStrategy = { + web: { + mode: 'prefix', + values: [ 'web_' ], + }, + pda: { + mode: 'prefix', + values: [ 'pda_' ], + }, + miniprogram: { + mode: 'prefix', + values: [ 'miniprogram_' ], + }, + workerstation: { + mode: 'type', + values: [ 'workerstation_pages' ], + }, + workstation: { + mode: 'type', + values: [ 'workerstation_pages' ], + }, + }; + + const strategy = platformTypeStrategy[normalizedPlatform]; + if (!strategy) { + return { + type: { + [Op.like]: `${normalizedPlatform}_%`, + }, + }; + } + + if (strategy.mode === 'prefix') { + const likeConditions = strategy.values.map(prefix => ({ [Op.like]: `${prefix}%` })); + if (likeConditions.length === 1) { + return { + type: likeConditions[0], + }; + } + return { + type: { + [Op.or]: likeConditions, + }, + }; + } + + return { + type: strategy.values.length === 1 ? strategy.values[0] : { + [Op.in]: strategy.values, + }, + }; + } + getCurrentAccountId() { const { ctx } = this; const rawUserId = ctx.userId || (ctx.user && ctx.user.id); @@ -1987,7 +2048,7 @@ class UserService extends Service { [Op.in]: permissionIds, }, status: 1, - // 修正 like 查询 + // 页面权限(`*_pages`)仅用于菜单路由,不应出现在接口权限集合中,包含 workerstation_pages。 type: { [ctx.app.Sequelize.Op.notLike]: '%_pages', }, @@ -2008,6 +2069,11 @@ class UserService extends Service { } } + /** + * 获取当前员工菜单 + * @param {number} activeEmployeeId 员工ID + * @return {Promise} 菜单路由列表 + */ async getMenus(activeEmployeeId) { const { ctx, app } = this; const { Sequelize } = app; @@ -2053,17 +2119,15 @@ class UserService extends Service { return []; } - // 3. 获取权限对应的菜单(根据设备筛选) + // 3. 获取权限对应的菜单(根据平台权限类型策略筛选) + const menuTypeWhere = this.getMenuTypeWhereByPlatform(ctx.header.platform); const permissions = await ctx.model.Permission.findAll({ where: { id: { [Op.in]: permissionIds, }, status: 1, - // 修正 like 查询 - type: { - [Op.like]: `${ctx.header.platform}_%`, - }, + ...menuTypeWhere, }, order: [ [ 'sort', 'ASC' ], diff --git a/app/service/systems/order_async.js b/app/service/systems/order_async.js index c160760..11a8b14 100644 --- a/app/service/systems/order_async.js +++ b/app/service/systems/order_async.js @@ -453,7 +453,7 @@ async function markPendingExceptionInternal(service, orderModel, orderId, wareho }; } -async function finalizeSuccessfulQimenSyncInternal(service, orderModel, orderItemsModel, orderId, warehouseId) { +async function finalizeSuccessfulQimenSyncInternal(service, orderModel, orderItemsModel, orderId, warehouseId, orderRow = null) { const stockStoreService = service.ctx.service && service.ctx.service.systems && service.ctx.service.systems.stockStore; if (!service.ctx.model || typeof service.ctx.model.transaction !== 'function') { @@ -465,6 +465,21 @@ async function finalizeSuccessfulQimenSyncInternal(service, orderModel, orderIte } await runTransactionWithLockRetryInternal(service, 'finalizeSuccessfulQimenSync', async transaction => { + let resolvedOrderRow = orderRow; + if (!resolvedOrderRow && orderModel && typeof orderModel.findOne === 'function') { + resolvedOrderRow = await orderModel.findOne({ + where: { + id: orderId, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'delivery_order_code', 'order_type' ], + raw: true, + transaction, + }); + } + + const outboundMetaOrderId = Number(resolvedOrderRow && resolvedOrderRow.id) || Number(orderId) || null; + const outboundMetaOrderNo = String(resolvedOrderRow && resolvedOrderRow.delivery_order_code || '').trim() || null; const freshOrderItems = await orderItemsModel.findAll({ where: { order_id: orderId, @@ -481,7 +496,12 @@ async function finalizeSuccessfulQimenSyncInternal(service, orderModel, orderIte continue; } - const outboundResult = await stockStoreService.outbound(itemId, quantity, transaction); + const outboundOrderItemId = Number(orderItem && (orderItem.id || orderItem.order_item_id)) || null; + const outboundResult = await stockStoreService.outbound(itemId, quantity, transaction, { + orderId: outboundMetaOrderId, + orderNo: outboundMetaOrderNo, + orderItemId: outboundOrderItemId, + }); if (!outboundResult || outboundResult.success !== true) { throw new Error(String(outboundResult && outboundResult.error || `订单${orderId}库存扣减失败`).trim()); } @@ -530,7 +550,12 @@ async function processLocalChannelOrderInternal(service, createChannel, orderMod continue; } - const outboundResult = await service.ctx.service.systems.stockStore.outbound(itemId, quantity, transaction); + const outboundOrderItemId = Number(orderItem && (orderItem.id || orderItem.order_item_id)) || null; + const outboundResult = await service.ctx.service.systems.stockStore.outbound(itemId, quantity, transaction, { + orderId: Number(orderRow && orderRow.id) || Number(orderId) || null, + orderNo: String(orderRow && orderRow.delivery_order_code || '').trim() || null, + orderItemId: outboundOrderItemId, + }); if (!outboundResult || outboundResult.success !== true) { throw new Error(String(outboundResult && outboundResult.error || `订单${orderId}库存扣减失败`).trim()); } @@ -895,7 +920,7 @@ async function processQmOrderInternal(service, orderModel, orderItemsModel, qime if (isSuccess) { try { - await finalizeSuccessfulQimenSyncInternal(service, orderModel, orderItemsModel, orderId, warehouseId); + await finalizeSuccessfulQimenSyncInternal(service, orderModel, orderItemsModel, orderId, warehouseId, orderRow); } catch (error) { await orderModel.update({ sync_status: 'error', @@ -1080,8 +1105,8 @@ async function syncQmOrdersInternal(service, groupedOrder = {}, context = {}) { * 订单异步同步路由服务。 */ class OrderAsyncService extends MainService { - async finalizeSuccessfulQimenSync(orderModel, orderItemsModel, orderId, warehouseId) { - return await finalizeSuccessfulQimenSyncInternal(this, orderModel, orderItemsModel, orderId, warehouseId); + async finalizeSuccessfulQimenSync(orderModel, orderItemsModel, orderId, warehouseId, orderRow = null) { + return await finalizeSuccessfulQimenSyncInternal(this, orderModel, orderItemsModel, orderId, warehouseId, orderRow); } diff --git a/app/service/systems/order_print.js b/app/service/systems/order_print.js index 3195bf4..399b8f0 100644 --- a/app/service/systems/order_print.js +++ b/app/service/systems/order_print.js @@ -6,25 +6,6 @@ const { Op } = require('sequelize'); const OrderBaseService = require('../systemMethods/order/base'); const PrinterDataBuilder = require('../../lib/printer_data_builder'); -const SYS_PLATFORM_TO_PRINT_PLATFORM_MAP = Object.freeze({ - tb: 'cainiao', - taobao: 'cainiao', - cainiao: 'cainiao', - cn: 'cainiao', - jd: 'jd', - jingdong: 'jd', - dy: 'douyin', - douyin: 'douyin', - ks: 'kuaishou', - kuaishou: 'kuaishou', - pdd: 'pdd', - pinduoduo: 'pdd', - sph: 'sph', - shipinhao: 'sph', - xhs: 'xhs', - xiaohongshu: 'xhs', -}); - class OrderPrintSystemService extends OrderBaseService { /** * 判断当前配置是否需要补查拣货明细。 @@ -388,6 +369,9 @@ class OrderPrintSystemService extends OrderBaseService { } = this.filterFullyAssignedExpressWaves(hitWaveIds, orderRows); const validWaveIdSet = new Set(validWaveIds); const validOrderRows = orderRows.filter(order => validWaveIdSet.has(Number(order && order.wave_id || 0))); + const validOrderWaveIds = Array.from(new Set(validOrderRows + .map(row => Number(row && row.wave_id || 0)) + .filter(waveId => Number.isInteger(waveId) && waveId > 0))); if (validOrderRows.length === 0) { const waveGroups = this.groupOrderPrintItemsByWaveAndPlatform({ @@ -424,10 +408,12 @@ class OrderPrintSystemService extends OrderBaseService { return this.shouldLoadPickingDetails(policyConfig); }); const printOrderRowMap = await this.buildPrintOrderRowMapWithPicking(pickingCandidateRows, normalizedWarehouseId); - const waveOrderIndexMap = await this.queryWaveOrderIndexMapByOrderIds(orderIds, normalizedWarehouseId); - const waveIdsForCount = Array.from(new Set(Array.from(waveOrderIndexMap.values()) - .map(item => Number(item && item.wave_id || 0)) - .filter(waveId => Number.isInteger(waveId) && waveId > 0))); + const waveOrderIndexMap = await this.queryWaveOrderIndexMapByOrderIds( + orderIds, + normalizedWarehouseId, + validOrderWaveIds + ); + const waveIdsForCount = validOrderWaveIds; const waveTotalOrderCountMap = await this.queryWaveTotalOrderCountMap(waveIdsForCount, normalizedWarehouseId); const templateSampleCache = new Map(); const orderPrintList = []; @@ -441,7 +427,7 @@ class OrderPrintSystemService extends OrderBaseService { const orderExpress = orderExpressMap.get(orderId) || {}; const effectiveOrderRow = printOrderRowMap.get(orderId) || orderRow; const waveOrderIndexInfo = waveOrderIndexMap.get(orderId) || {}; - const waveIdForCount = Number(waveOrderIndexInfo.wave_id || effectiveOrderRow.wave_id || 0); + const waveIdForCount = Number(effectiveOrderRow.wave_id || orderRow.wave_id || waveOrderIndexInfo.wave_id || 0); const waveTotalOrders = Number(waveTotalOrderCountMap.get(waveIdForCount) || 0); const waveIndex = Number(waveOrderIndexInfo.wave_index || 0); const platformsIndex = Number(waveOrderIndexInfo.platforms_index || 0); @@ -604,6 +590,8 @@ class OrderPrintSystemService extends OrderBaseService { 'sys_platform_name', 'logistics_code', 'logistics_name', + 'sys_logistics_code', + 'sys_logistics_name', 'post_status', 'status', 'outbound_status', @@ -681,13 +669,17 @@ class OrderPrintSystemService extends OrderBaseService { * * @param {Array} orderIds 订单ID数组。 * @param {number} warehouseId 仓库ID。 + * @param {Array} [waveIds] 可选波次ID数组,用于限制查询范围。 * @return {Promise>} 订单顺序映射。 */ - async queryWaveOrderIndexMapByOrderIds(orderIds = [], warehouseId) { + async queryWaveOrderIndexMapByOrderIds(orderIds = [], warehouseId, waveIds = []) { const resultMap = new Map(); const normalizedOrderIds = Array.from(new Set((Array.isArray(orderIds) ? orderIds : []) .map(id => Number(id)) .filter(id => Number.isInteger(id) && id > 0))); + const normalizedWaveIds = Array.from(new Set((Array.isArray(waveIds) ? waveIds : []) + .map(id => Number(id)) + .filter(id => Number.isInteger(id) && id > 0))); if (normalizedOrderIds.length === 0) { return resultMap; @@ -698,11 +690,15 @@ class OrderPrintSystemService extends OrderBaseService { return resultMap; } + const waveFilterSql = normalizedWaveIds.length > 0 + ? ' AND wave_id IN (:waveIds)\n' + : ''; const querySql = ` SELECT order_id, wave_id, wave_index, platforms_index FROM wms_order_wave_index WHERE warehouse_id = :warehouseId AND order_id IN (:orderIds) +${waveFilterSql} `; try { @@ -710,6 +706,7 @@ class OrderPrintSystemService extends OrderBaseService { replacements: { warehouseId, orderIds: normalizedOrderIds, + ...(normalizedWaveIds.length > 0 ? { waveIds: normalizedWaveIds } : {}), }, type: this.ctx.model.QueryTypes && this.ctx.model.QueryTypes.SELECT, }); @@ -903,7 +900,7 @@ class OrderPrintSystemService extends OrderBaseService { } /** - * 解析订单平台编码并转换为打印平台别名。 + * 解析订单平台编码,保留原始平台值(仅去首尾空白)。 * * @param {Object} orderRow 订单行。 * @param {Object} orderExpress 快递行。 @@ -917,16 +914,12 @@ class OrderPrintSystemService extends OrderBaseService { ]; for (const candidate of candidates) { - const normalizedCandidate = String(candidate || '').trim().toLowerCase(); - if (!normalizedCandidate) { + const rawCandidate = String(candidate || '').trim(); + if (!rawCandidate) { continue; } - const mappedPlatform = SYS_PLATFORM_TO_PRINT_PLATFORM_MAP[normalizedCandidate] || normalizedCandidate; - const normalizedPlatform = PrinterDataBuilder.normalizePlatformAlias(mappedPlatform); - if (normalizedPlatform.platform) { - return normalizedPlatform.platform; - } + return rawCandidate; } return ''; @@ -990,6 +983,10 @@ class OrderPrintSystemService extends OrderBaseService { const waveId = Number(orderRow.wave_id || 0); const requestId = `wave_${waveId}_order_${orderId}`; const waybillCode = String(orderExpress.waybill_code || '').trim(); + const orderSysLogisticsCode = String(orderRow.sys_logistics_code || '').trim(); + const orderSysLogisticsName = String(orderRow.sys_logistics_name || '').trim(); + const expressSysLogisticsCode = String(orderExpress.sys_logistics_code || '').trim(); + const expressSysLogisticsName = String(orderExpress.sys_logistics_name || '').trim(); const documentId = waybillCode || `doc_${orderId}`; const printPayload = PrinterDataBuilder.buildPlatformRequestSkeleton({ platform: platformCode, @@ -1015,10 +1012,12 @@ class OrderPrintSystemService extends OrderBaseService { order_no: String(orderRow.delivery_order_code || orderRow.source_order_codes || '').trim(), store_id: Number(orderRow.store_id || 0), warehouse_id: Number(orderRow.warehouse_id || 0), - platform: String(printPayload.platform || '').trim(), + platform: platformCode, platform_name: printPayload.platform_meta && printPayload.platform_meta.name ? String(printPayload.platform_meta.name).trim() : '', + sys_logistics_code: orderSysLogisticsCode || expressSysLogisticsCode, + sys_logistics_name: orderSysLogisticsName || expressSysLogisticsName, waybill_code: String(orderExpress.waybill_code || '').trim(), print_data: printData, }; @@ -1088,13 +1087,13 @@ class OrderPrintSystemService extends OrderBaseService { } /** - * 将逐单打印中间态按波次分组,并在波次内按平台分组。 + * 将逐单打印中间态按波次分组,并在波次内按平台+系统快递分组。 * * @param {Object} payload 聚合输入。 * @param {Array} payload.waveRows 波次元数据列表。 * @param {Array} payload.hitWaveIds 命中的波次ID数组(已过滤)。 * @param {Array} payload.orderPrintList 逐单打印中间态列表。 - * @return {Array} 波次平台分组结果。 + * @return {Array} 波次平台分组结果(platforms 为扁平平台+系统快递项)。 */ groupOrderPrintItemsByWaveAndPlatform(payload = {}) { const { @@ -1145,17 +1144,24 @@ class OrderPrintSystemService extends OrderBaseService { } const platform = String(item && item.platform || '').trim() || 'unknown'; + const normalizedSysLogisticsCode = String(item && item.sys_logistics_code || '').trim(); + const normalizedSysLogisticsName = String(item && item.sys_logistics_name || '').trim(); + const normalizedSysLogisticsIdentity = normalizedSysLogisticsCode || normalizedSysLogisticsName || 'unknown'; + const platformSysKey = `${platform}@@${normalizedSysLogisticsIdentity}`; const platformMap = wavePlatformMap.get(waveId) || new Map(); - const platformGroup = platformMap.get(platform) || { + const platformGroup = platformMap.get(platformSysKey) || { platform, platform_name: String(item && item.platform_name || '').trim(), + sys_logistics_code: normalizedSysLogisticsCode || 'unknown', + sys_logistics_name: normalizedSysLogisticsName || 'unknown', order_count: 0, orders: [], }; platformGroup.orders.push(this.isPlainObject(item && item.print_data) ? item.print_data : {}); platformGroup.order_count = platformGroup.orders.length; - platformMap.set(platform, platformGroup); + + platformMap.set(platformSysKey, platformGroup); wavePlatformMap.set(waveId, platformMap); } @@ -1163,7 +1169,19 @@ class OrderPrintSystemService extends OrderBaseService { for (const waveGroup of waveGroups) { const platformMap = wavePlatformMap.get(Number(waveGroup.wave_id)) || new Map(); const platforms = Array.from(platformMap.values()); - platforms.sort((a, b) => String(a.platform || '').localeCompare(String(b.platform || ''))); + platforms.sort((a, b) => { + const platformCompare = String(a.platform || '').localeCompare(String(b.platform || '')); + if (platformCompare !== 0) { + return platformCompare; + } + + const sysCodeCompare = String(a.sys_logistics_code || '').localeCompare(String(b.sys_logistics_code || '')); + if (sysCodeCompare !== 0) { + return sysCodeCompare; + } + + return String(a.sys_logistics_name || '').localeCompare(String(b.sys_logistics_name || '')); + }); waveGroup.platforms = platforms; waveGroup.order_count = platforms.reduce((sum, platformGroup) => { return sum + Number(platformGroup && platformGroup.order_count || 0); diff --git a/app/service/systems/setting/permission.js b/app/service/systems/setting/permission.js index 1b5d03b..70027a0 100644 --- a/app/service/systems/setting/permission.js +++ b/app/service/systems/setting/permission.js @@ -71,13 +71,18 @@ class SettingPermissionService extends Service { return permission; } + /** + * 规范化并校验权限类型 + * @param {string} type 权限类型 + * @return {string} 规范化后的权限类型 + */ normalizePermissionType(type) { const normalized = typeof type === 'string' ? type.trim() : ''; if (!normalized) { throw this.createError('type 参数不能为空', 400); } - const allowedTypes = new Set([ 'web_pages', 'pda_pages', 'btns', 'api', 'miniprogram_pages', 'block' ]); + const allowedTypes = new Set([ 'web_pages', 'pda_pages', 'btns', 'api', 'miniprogram_pages', 'workerstation_pages', 'block' ]); if (!allowedTypes.has(normalized)) { throw this.createError('type 参数不合法', 400); } diff --git a/app/service/systems/stock_store.js b/app/service/systems/stock_store.js index 2028628..ecaec58 100644 --- a/app/service/systems/stock_store.js +++ b/app/service/systems/stock_store.js @@ -827,17 +827,143 @@ class stockStoreService extends Service { }; } } + + /** + * 规范化出库元信息,兼容驼峰与下划线字段。 + * + * @param {Object} meta 出库元信息。 + * @return {Object} 规范化后的订单上下文。 + */ + normalizeOutboundMeta(meta = {}) { + const normalized = meta && typeof meta === 'object' ? meta : {}; + const orderIdRaw = normalized.orderId + ?? normalized.order_id + ?? normalized.deliveryOrderId + ?? normalized.delivery_order_id + ?? normalized.id; + const orderItemIdRaw = normalized.orderItemId ?? normalized.order_item_id; + const sourceOrderCodesRaw = normalized.sourceOrderCodes ?? normalized.source_order_codes; + const orderNoRaw = normalized.orderNo + ?? sourceOrderCodesRaw + ?? normalized.order_no + ?? normalized.deliveryOrderCode + ?? normalized.delivery_order_code; + const orderId = Number(orderIdRaw); + const orderItemId = Number(orderItemIdRaw); + const orderNo = String(orderNoRaw || '').trim(); + const sourceOrderCodes = String(sourceOrderCodesRaw || '').trim(); + + return { + orderId: Number.isFinite(orderId) && orderId > 0 ? orderId : null, + orderItemId: Number.isFinite(orderItemId) && orderItemId > 0 ? orderItemId : null, + orderNo: orderNo || null, + sourceOrderCodes: sourceOrderCodes || null, + }; + } + + /** + * 查询订单明细对应的拣货分配记录。 + * + * @param {number|null} orderId 订单 ID。 + * @param {number|null} orderItemId 订单明细 ID。 + * @param {Object|null} transaction 事务对象。 + * @return {Promise>} 拣货分配列表。 + */ + async getPickingRowsForOutbound(orderId, orderItemId, transaction) { + const { ctx } = this; + const pickingModel = ctx.model && ctx.model.Picking; + + if (!pickingModel || typeof pickingModel.findAll !== 'function') { + return []; + } + + if (!orderId || !orderItemId) { + return []; + } + + const rows = await pickingModel.findAll({ + where: { + order_id: orderId, + order_item_id: orderItemId, + }, + attributes: [ 'storage_id', 'space_id', 'quantity' ], + order: [[ 'id', 'ASC' ]], + raw: true, + transaction, + }); + + return Array.isArray(rows) ? rows : []; + } + + /** + * 生成出库流水写入明细,优先按拣货分配逐条记录。 + * + * @param {Object} options 参数集合。 + * @param {number} options.outboundQty 本次出库总数量。 + * @param {Array} options.pickingRows 拣货分配记录。 + * @param {Object} options.basePayload 流水公共字段。 + * @return {Array} 待写入的出库流水列表。 + */ + buildOutboundTransactionPayloads({ outboundQty, pickingRows, basePayload }) { + const payloads = []; + const normalizedRows = Array.isArray(pickingRows) ? pickingRows : []; + let consumedQty = 0; + + for (const pickingRow of normalizedRows) { + const remainingQty = outboundQty - consumedQty; + if (remainingQty <= 0) { + break; + } + + const pickingQty = Number(pickingRow && pickingRow.quantity) || 0; + if (pickingQty <= 0) { + continue; + } + + const transactionQty = Math.min(pickingQty, remainingQty); + payloads.push({ + ...basePayload, + storage_id: pickingRow && pickingRow.storage_id ? Number(pickingRow.storage_id) : null, + space_id: pickingRow && pickingRow.space_id ? Number(pickingRow.space_id) : null, + quantity: transactionQty, + }); + consumedQty += transactionQty; + } + + if (payloads.length === 0) { + return [{ + ...basePayload, + storage_id: null, + space_id: null, + quantity: outboundQty, + }]; + } + + if (consumedQty < outboundQty) { + payloads.push({ + ...basePayload, + storage_id: null, + space_id: null, + quantity: outboundQty - consumedQty, + }); + } + + return payloads; + } + /** * 商品出库服务 * @param {number} itemId 商品ID (StockStore.id) * @param {number} quantity 出库数量(正数) * @param {Object} transaction 数据库事务 + * @param {Object} meta 出库元信息(订单、明细等) */ - async outbound(itemId, quantity, transaction) { + async outbound(itemId, quantity, transaction, meta = {}) { const { ctx, app, } = this; + const outboundMeta = this.normalizeOutboundMeta(meta); // 1. 参数验证 const outboundQty = parseInt(quantity); @@ -946,33 +1072,50 @@ class stockStoreService extends Service { const afterQuantity = Number(updatedRecord.quantity) || 0; const afterLockedQuantity = Number(updatedRecord.locked_quantity) || 0; - await ctx.service.systems.stockTransaction.create({ + let pickingRows = []; + if (outboundMeta.orderId && outboundMeta.orderItemId) { + try { + pickingRows = await this.getPickingRowsForOutbound(outboundMeta.orderId, outboundMeta.orderItemId, currentTransaction); + } catch (error) { + app.logger.warn(`[outbound] 读取拣货分配失败,降级为单条出库流水: ${error.message}`); + } + } + + const baseTransactionPayload = { transaction_type: 'OUTBOUND', warehouse_id: updatedRecord.warehouse_id || ctx.user.store_id, - store_id: ctx.user.store_id, + store_id: storage.storeId || updatedRecord.store_id || ctx.user.store_id, stock_id: storage.id, - storage_id: null, - space_id: null, - quantity: outboundQty, batch_no: null, inventory_type: 'ZP', order_type: 'STOCK_STORE_OUTBOUND', - order_no: null, - order_id: null, + order_no: outboundMeta.orderNo, + order_id: outboundMeta.orderId, + source_order_codes: outboundMeta.sourceOrderCodes, receiving_id: null, entry_order_id: null, operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), operator_name: ctx.user?.employees_name || '', - remark: '商品出库', + remark: '订单出库', before_quantity: beforeQuantity, after_quantity: afterQuantity, before_locked_quantity: beforeLockedQuantity, after_locked_quantity: afterLockedQuantity, created_at: new Date(), - }, { - transaction: currentTransaction, + }; + + const transactionPayloads = this.buildOutboundTransactionPayloads({ + outboundQty, + pickingRows, + basePayload: baseTransactionPayload, }); + for (const payload of transactionPayloads) { + await ctx.service.systems.stockTransaction.create(payload, { + transaction: currentTransaction, + }); + } + app.logger.info('[出库] 成功', { itemId, stockId: storage.id, diff --git a/app/service/systems/stock_transaction.js b/app/service/systems/stock_transaction.js index 144efa4..7272566 100644 --- a/app/service/systems/stock_transaction.js +++ b/app/service/systems/stock_transaction.js @@ -4,6 +4,115 @@ const Service = require('egg').Service; class StockTransactionService extends Service { + /** + * 规范化入库流水的单据字段。 + * + * 约束: + * 1) transaction_type=INBOUND 时,order_id 必须写 null; + * 2) 其他类型保持上游值不变。 + * + * @param {Object} data 流水数据。 + * @param {number|null|undefined} orderId 候选单据ID。 + * @return {number|null} 规范化后的单据ID。 + */ + normalizeInboundOrderId(data = {}, orderId) { + if (data.transaction_type === 'INBOUND') { + return null; + } + return orderId ?? null; + } + + /** + * 判断当前流水是否属于订单出库链路。 + * + * 说明: + * 1) 仅 OUTBOUND 才可能是订单出库; + * 2) 允许上游传入多种 order_type,只要具备订单出库特征均视为订单出库; + * 3) 订单ID合法性由 resolveOutboundOrderReference 统一校验。 + * + * @param {Object} data 流水数据。 + * @return {boolean} 是否为订单出库流水。 + */ + isOrderOutboundTransaction(data = {}) { + if (data.transaction_type !== 'OUTBOUND') { + return false; + } + + const normalizedOrderType = String(data.order_type || '').trim(); + const sourceOrderCodes = String(data.source_order_codes || '').trim(); + const remark = String(data.remark || '').trim(); + + return Boolean( + sourceOrderCodes + || normalizedOrderType === 'STOCK_STORE_OUTBOUND' + || normalizedOrderType === 'ORDER' + || remark === '订单出库' + ); + } + + /** + * 规范化订单出库流水的单据字段。 + * + * 约束: + * 1) order_id 必须是订单主键 ID; + * 2) order_no 必须写订单 source_order_codes。 + * 3) batch_no 必须以订单 wave_no 为准(无 wave_no 时写 null)。 + * + * @param {Object} data 流水数据。 + * @param {Object} options 写入选项。 + * @return {Promise<{orderId: number|null, orderNo: string|null, batchNo: string|null}>} 规范化后的单据字段。 + */ + async resolveOutboundOrderReference(data = {}, options = {}) { + const { ctx } = this; + const isOrderOutbound = this.isOrderOutboundTransaction(data); + + if (!isOrderOutbound) { + return { + orderId: data.order_id ?? null, + orderNo: data.order_no ?? null, + batchNo: data.batch_no ?? null, + }; + } + + const orderId = Number(data.order_id); + if (!Number.isFinite(orderId) || orderId <= 0) { + throw new Error('订单出库流水 order_id 必须为订单主键 id'); + } + + let sourceOrderCodes = String(data.source_order_codes || '').trim(); + let waveNo = null; + + const orderDeliveryModel = ctx.model && ctx.model.OrderDelivery; + if (orderDeliveryModel && typeof orderDeliveryModel.findOne === 'function') { + const orderRow = await orderDeliveryModel.findOne({ + where: { + id: orderId, + }, + attributes: [ 'id', 'source_order_codes', 'wave_no' ], + raw: true, + transaction: options.transaction, + }); + + if (orderRow) { + if (!sourceOrderCodes) { + sourceOrderCodes = String(orderRow.source_order_codes || '').trim(); + } + const normalizedWaveNo = String(orderRow.wave_no || '').trim(); + waveNo = normalizedWaveNo || null; + } + } + + if (!sourceOrderCodes) { + throw new Error(`订单出库流水 order_no 必须使用 source_order_codes,订单ID: ${orderId}`); + } + + return { + orderId, + orderNo: sourceOrderCodes, + batchNo: waveNo, + }; + } + /** * 统一写入库存流水记录。 * @@ -37,6 +146,10 @@ class StockTransactionService extends Service { async create(data = {}, options = {}) { const { ctx } = this; + if (!options.transaction) { + throw new Error('stockTransaction.create 缺少 transaction,库存流水写入必须在事务中执行'); + } + const quantity = Number(data.quantity); if (!data.transaction_type) { throw new Error('transaction_type 必填'); @@ -54,6 +167,13 @@ class StockTransactionService extends Service { throw new Error('quantity 必须为正数'); } + const isOrderOutbound = this.isOrderOutboundTransaction(data); + const normalizedOrderReference = await this.resolveOutboundOrderReference(data, options); + const normalizedOrderType = isOrderOutbound ? 'ORDER' : (data.order_type ?? null); + const normalizedBatchNo = isOrderOutbound ? normalizedOrderReference.batchNo : (data.batch_no ?? null); + + const normalizedOrderId = this.normalizeInboundOrderId(data, normalizedOrderReference.orderId); + const payload = { transaction_type: data.transaction_type, warehouse_id: data.warehouse_id, @@ -62,11 +182,11 @@ class StockTransactionService extends Service { storage_id: data.storage_id ?? null, space_id: data.space_id ?? null, quantity, - batch_no: data.batch_no ?? null, + batch_no: normalizedBatchNo, inventory_type: data.inventory_type || 'ZP', - order_type: data.order_type ?? null, - order_no: data.order_no ?? null, - order_id: data.order_id ?? null, + order_type: normalizedOrderType, + order_no: normalizedOrderReference.orderNo, + order_id: normalizedOrderId, receiving_id: data.receiving_id ?? null, entry_order_id: data.entry_order_id ?? null, operator_id: data.operator_id ?? null, diff --git a/app/service/systems/storage/inventory.js b/app/service/systems/storage/inventory.js index b62af65..b251fc3 100644 --- a/app/service/systems/storage/inventory.js +++ b/app/service/systems/storage/inventory.js @@ -563,7 +563,7 @@ class InventoryService extends Service { inventory_type: inventoryType, order_type: 'SCRK', order_no: entryOrderCode, - order_id: entryOrder.id, + order_id: null, receiving_id: receivingId, entry_order_id: entryOrder.id, operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), @@ -946,7 +946,7 @@ class InventoryService extends Service { inventory_type: inventoryType, order_type: 'MATCH', order_no: firstEntryOrder.entry_order_code, - order_id: firstEntryOrder.id, + order_id: null, receiving_id: firstRcv.id, entry_order_id: firstEntryOrder.id, operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), @@ -1185,6 +1185,82 @@ class InventoryService extends Service { } } + /** + * 写入移库双向库存流水(移库出/移库入)。 + * + * 说明: + * 1) before/after 与锁定字段均写同值快照,避免被识别为普通出入库数量变化; + * 2) 仅记录移库行为本身,不绑定订单字段。 + * + * @param {Object} data 入参 + * @param {Object} data.transaction 数据库事务 + * @param {Object} data.srcRecord 源库存记录 + * @param {number} data.transferQuantity 移库数量 + * @param {number} data.sourceSpaceId 源库位ID + * @param {number} data.targetSpaceId 目标库位ID + * @param {number|null} data.targetStorageId 目标库存记录ID + * @param {number} data.totalSnapshotQuantity stock_id 总库存快照数量 + * @param {number} data.totalSnapshotLockedQuantity stock_id 总锁定快照数量 + * @return {Promise} 无返回值 + */ + async createTransferStockTransactions(data = {}) { + const { ctx } = this; + + const operatorId = ctx.user?.employees_id || ctx.user?.id || null; + const operatorName = ctx.user?.employees_name || ''; + + const totalSnapshotQuantity = Number(data.totalSnapshotQuantity) || 0; + const totalSnapshotLockedQuantity = Number(data.totalSnapshotLockedQuantity) || 0; + + await ctx.service.systems.stockTransaction.create({ + transaction_type: 'TRANSFER_OUT', + warehouse_id: data.srcRecord.warehouse_id, + store_id: data.srcRecord.store_id, + stock_id: data.srcRecord.stock_id, + storage_id: data.srcRecord.id, + space_id: data.sourceSpaceId, + quantity: data.transferQuantity, + batch_no: data.srcRecord.batch_no, + inventory_type: data.srcRecord.inventory_type, + order_type: null, + order_no: null, + order_id: null, + operator_id: operatorId, + operator_name: operatorName, + remark: '移库出', + before_quantity: totalSnapshotQuantity, + after_quantity: totalSnapshotQuantity, + before_locked_quantity: totalSnapshotLockedQuantity, + after_locked_quantity: totalSnapshotLockedQuantity, + }, { + transaction: data.transaction, + }); + + await ctx.service.systems.stockTransaction.create({ + transaction_type: 'TRANSFER_IN', + warehouse_id: data.srcRecord.warehouse_id, + store_id: data.srcRecord.store_id, + stock_id: data.srcRecord.stock_id, + storage_id: data.targetStorageId, + space_id: data.targetSpaceId, + quantity: data.transferQuantity, + batch_no: data.srcRecord.batch_no, + inventory_type: data.srcRecord.inventory_type, + order_type: null, + order_no: null, + order_id: null, + operator_id: operatorId, + operator_name: operatorName, + remark: '移库入', + before_quantity: totalSnapshotQuantity, + after_quantity: totalSnapshotQuantity, + before_locked_quantity: totalSnapshotLockedQuantity, + after_locked_quantity: totalSnapshotLockedQuantity, + }, { + transaction: data.transaction, + }); + } + /** * 移库(库位转移):将单条库存从一个库位移动到另一个库位。 * 支持部分/全量移库、目标库位合并。 @@ -1239,6 +1315,17 @@ class InventoryService extends Service { const warehouseId = srcRecord.warehouse_id; + const stockWarehouseSnapshot = await ctx.model.StockWarehouse.findOne({ + where: { id: srcRecord.stock_id }, + attributes: [ 'id', 'quantity', 'locked_quantity' ], + lock: transaction.LOCK.UPDATE, + transaction, + }); + if (!stockWarehouseSnapshot) { + await transaction.rollback(); + return { code: 404, message: `商品SKU不存在: stock_id=${srcRecord.stock_id}`, data: null }; + } + // ────────── 4. 校验目标库位 ────────── const targetSpace = await ctx.model.LocationSpace.findOne({ where: { @@ -1322,6 +1409,7 @@ class InventoryService extends Service { }); let afterSnapshot; + let targetStorageId = null; // 原库位统计变化 const srcSpaceDelta = { skuDelta: 0, qtyDelta: 0 }; // 目标库位统计变化 @@ -1380,6 +1468,7 @@ class InventoryService extends Service { tgtSpaceDelta.qtyDelta += transferQty; // 目标库位该 SKU 之前已有记录,skuDelta 不变 + targetStorageId = existingTarget.id; afterSnapshot = { merged_into: existingTarget.id, target_space_id: targetSpaceId, @@ -1428,6 +1517,7 @@ class InventoryService extends Service { } tgtSpaceDelta.qtyDelta += srcRecord.quantity; + targetStorageId = storageId; afterSnapshot = { storage_id: storageId, target_space_id: targetSpaceId, @@ -1487,6 +1577,7 @@ class InventoryService extends Service { } tgtSpaceDelta.qtyDelta += transferQty; + targetStorageId = newRecord.id; afterSnapshot = { new_storage_id: newRecord.id, target_space_id: targetSpaceId, @@ -1495,6 +1586,17 @@ class InventoryService extends Service { }; } + await this.createTransferStockTransactions({ + transaction, + srcRecord, + transferQuantity: transferQty, + sourceSpaceId: srcRecord.space_id, + targetSpaceId, + targetStorageId, + totalSnapshotQuantity: Number(stockWarehouseSnapshot.quantity) || 0, + totalSnapshotLockedQuantity: Number(stockWarehouseSnapshot.locked_quantity) || 0, + }); + // ────────── 记录操作日志(事务内) ────────── try { await ctx.service.systems.operationLog.createOperationLog({ @@ -1697,6 +1799,17 @@ class InventoryService extends Service { const warehouseId = srcRecords[0].warehouse_id; + const stockWarehouseSnapshot = await ctx.model.StockWarehouse.findOne({ + where: { id: stockId }, + attributes: [ 'id', 'quantity', 'locked_quantity' ], + lock: transaction.LOCK.UPDATE, + transaction, + }); + if (!stockWarehouseSnapshot) { + await transaction.rollback(); + return { code: 404, message: `商品SKU不存在: stock_id=${stockId}`, data: null }; + } + // ────────── 6. 校验目标库位 ────────── const targetSpace = await ctx.model.LocationSpace.findOne({ where: { @@ -1750,6 +1863,7 @@ class InventoryService extends Service { affectedCount++; const isFullTransfer = (toTransfer === srcRecord.quantity); + let targetStorageId = null; // ── 在目标库位查找同 stock_id + batch_no + inventory_type 的记录 ── const existingTarget = await ctx.model.Storage.findOne({ @@ -1798,6 +1912,8 @@ class InventoryService extends Service { transaction, }); } + + targetStorageId = existingTarget.id; } else if (isFullTransfer) { // 全量移库 & 目标无同规格记录:直接改 space_id await ctx.model.Storage.update({ @@ -1807,6 +1923,8 @@ class InventoryService extends Service { where: { id: srcRecord.id }, transaction, }); + + targetStorageId = srcRecord.id; } else { // 部分移库 & 目标无同规格记录:减少原记录,新建目标记录 await ctx.model.Storage.update({ @@ -1818,7 +1936,7 @@ class InventoryService extends Service { transaction, }); - await ctx.model.Storage.create({ + const newRecord = await ctx.model.Storage.create({ warehouse_id: srcRecord.warehouse_id, store_id: srcRecord.store_id, space_id: targetSpaceId, @@ -1840,8 +1958,21 @@ class InventoryService extends Service { created_at: new Date(), updated_at: new Date(), }, { transaction }); + + targetStorageId = newRecord.id; } + await this.createTransferStockTransactions({ + transaction, + srcRecord, + transferQuantity: toTransfer, + sourceSpaceId: srcRecord.space_id, + targetSpaceId, + targetStorageId, + totalSnapshotQuantity: Number(stockWarehouseSnapshot.quantity) || 0, + totalSnapshotLockedQuantity: Number(stockWarehouseSnapshot.locked_quantity) || 0, + }); + srcSpaceDelta.qtyDelta -= toTransfer; tgtSpaceDelta.qtyDelta += toTransfer; remainingQty -= toTransfer; diff --git a/app/service/systems/storage/report.js b/app/service/systems/storage/report.js new file mode 100644 index 0000000..674b3ae --- /dev/null +++ b/app/service/systems/storage/report.js @@ -0,0 +1,1232 @@ +'use strict'; + +const Service = require('egg').Service; + +/** + * 将输入转换为时间戳。 + * @param {string|Date|number|null|undefined} value 时间值 + * @return {number|null} 时间戳,无法解析时返回 null + */ +function toTimeMs(value) { + if (value === undefined || value === null || value === '') { + return null; + } + + const date = value instanceof Date ? value : new Date(value); + const time = date.getTime(); + return Number.isNaN(time) ? null : time; +} + +/** + * 归一化布尔值。 + * @param {boolean|string|number|null|undefined} value 原始值 + * @return {boolean} 归一化后的布尔值 + */ +function normalizeBoolean(value) { + if (typeof value === 'boolean') { + return value; + } + + if (typeof value === 'number') { + return value === 1; + } + + if (typeof value === 'string') { + const normalized = value.trim().toLowerCase(); + return [ '1', 'true', 'y', 'yes' ].includes(normalized); + } + + return false; +} + +/** + * 归一化货主ID数组。 + * @param {Array|number|string|null|undefined} rawStoreIds 原始货主ID + * @return {number[]} 归一化后的货主ID数组 + */ +function normalizeStoreIds(rawStoreIds) { + const list = Array.isArray(rawStoreIds) ? rawStoreIds : [ rawStoreIds ]; + return [ ...new Set( + list + .map(item => Number(item)) + .filter(item => Number.isInteger(item) && item > 0) + ) ]; +} + +/** + * 数值安全转换。 + * @param {unknown} value 原始值 + * @return {number} 数值 + */ +function toNumber(value) { + const num = Number(value); + return Number.isFinite(num) ? num : 0; +} + +/** + * 将时间值格式化为日期令牌。 + * @param {string|Date|number|null|undefined} value 时间值 + * @return {string} yyyymmdd 格式日期,无法解析时返回空字符串 + */ +function formatDateToken(value) { + const timeMs = toTimeMs(value); + if (timeMs === null) { + return ''; + } + + const date = new Date(timeMs); + const year = String(date.getFullYear()); + const month = String(date.getMonth() + 1).padStart(2, '0'); + const day = String(date.getDate()).padStart(2, '0'); + return `${year}${month}${day}`; +} + +/** + * 将时间值格式化为统一可读字符串。 + * @param {string|Date|number|null|undefined} value 时间值 + * @return {string} yyyy-mm-dd hh:mm:ss 格式字符串 + */ +function formatDateTime(value) { + const timeMs = toTimeMs(value); + if (timeMs === null) { + return ''; + } + + const date = new Date(timeMs); + const year = String(date.getFullYear()); + const month = String(date.getMonth() + 1).padStart(2, '0'); + const day = String(date.getDate()).padStart(2, '0'); + const hour = String(date.getHours()).padStart(2, '0'); + const minute = String(date.getMinutes()).padStart(2, '0'); + const second = String(date.getSeconds()).padStart(2, '0'); + return `${year}-${month}-${day} ${hour}:${minute}:${second}`; +} + +/** + * 将库存流水类型转换为中文显示。 + * @param {string|null|undefined} transactionType 流水类型 + * @return {string} 中文类型,未知值返回去除前后空白后的原始内容 + */ +function formatTransactionType(transactionType) { + const rawType = typeof transactionType === 'string' ? transactionType.trim() : String(transactionType || '').trim(); + const normalizedType = rawType.toUpperCase(); + + if (normalizedType === 'INBOUND') { + return '入库'; + } + + if (normalizedType === 'OUTBOUND') { + return '出库'; + } + + if (normalizedType === 'TRANSFER_OUT') { + return '移库出'; + } + + if (normalizedType === 'TRANSFER_IN') { + return '移库入'; + } + + return rawType; +} + +const SORT_FIELD_WHITE_LIST = new Set([ 'begin_total', 'inbound_total', 'outbound_total', 'end_total' ]); + +/** + * 归一化排序参数。 + * @param {Object|null|undefined} sort 排序入参 + * @param {string} [sort.sortField] 排序字段 + * @param {string} [sort.sortOrder] 排序顺序 + * @return {{sortField: string, sortOrder: 'ASC'|'DESC'}|null} 合法排序参数 + */ +function normalizeSort(sort) { + if (!sort || typeof sort !== 'object') { + return null; + } + + const rawSortField = typeof sort.sortField === 'string' ? sort.sortField.trim() : ''; + const rawSortOrder = typeof sort.sortOrder === 'string' ? sort.sortOrder.trim().toUpperCase() : ''; + if (!SORT_FIELD_WHITE_LIST.has(rawSortField)) { + return null; + } + + if (rawSortOrder !== 'ASC' && rawSortOrder !== 'DESC') { + return null; + } + + return { + sortField: rawSortField, + sortOrder: rawSortOrder, + }; +} + +/** + * 默认排序比较器。 + * @param {Object} a 列表项A + * @param {Object} b 列表项B + * @param {boolean} isBySpace 是否按库位输出 + * @return {number} 比较结果 + */ +function compareByDefaultOrder(a, b, isBySpace) { + if (a.store_id !== b.store_id) { + return a.store_id - b.store_id; + } + + if (a.stock_id !== b.stock_id) { + return a.stock_id - b.stock_id; + } + + if (!isBySpace) { + return 0; + } + + return Number(a.space_id || 0) - Number(b.space_id || 0); +} + +/** + * 对最终结果做统一排序。 + * @param {Object[]} list 原始结果列表 + * @param {boolean} isBySpace 是否按库位输出 + * @param {Object|null|undefined} sort 排序参数 + * @return {Object[]} 排序后的结果列表 + */ +function sortReportList(list, isBySpace, sort) { + const normalizedSort = normalizeSort(sort); + if (!normalizedSort) { + return list.sort((a, b) => compareByDefaultOrder(a, b, isBySpace)); + } + + const { sortField, sortOrder } = normalizedSort; + const direction = sortOrder === 'DESC' ? -1 : 1; + + return list.sort((a, b) => { + const aValue = toNumber(a[sortField]); + const bValue = toNumber(b[sortField]); + if (aValue !== bValue) { + return (aValue - bValue) * direction; + } + return compareByDefaultOrder(a, b, isBySpace); + }); +} + +/** + * 根据区间流水构建“首条before、末条after”的快照映射。 + * @param {Object[]} rows 区间流水列表 + * @param {(row: Object) => string|null} resolveKey 键解析函数 + * @return {Map} 快照映射 + */ +function buildIntervalEdgeMap(rows, resolveKey) { + const edgeMap = new Map(); + const safeRows = Array.isArray(rows) ? rows : []; + + for (const row of safeRows) { + const key = resolveKey(row); + if (!key) { + continue; + } + + const beforeQuantity = toNumber(row.before_quantity); + const afterQuantity = toNumber(row.after_quantity); + + if (!edgeMap.has(key)) { + edgeMap.set(key, { + begin_total: beforeQuantity, + end_total: afterQuantity, + has_snapshot: true, + }); + continue; + } + + const snapshot = edgeMap.get(key); + snapshot.end_total = afterQuantity; + } + + return edgeMap; +} + +/** + * 根据 start_time 之前流水构建“最近一条 after”的期初快照映射。 + * @param {Object[]} rows start_time 之前流水列表 + * @param {(row: Object) => string|null} resolveKey 键解析函数 + * @return {Map} 期初快照映射 + */ +function buildPreStartAfterMap(rows, resolveKey) { + const latestSnapshotMap = new Map(); + const safeRows = Array.isArray(rows) ? rows : []; + + for (const row of safeRows) { + const key = resolveKey(row); + if (!key) { + continue; + } + + const createdAtMs = toTimeMs(row.created_at); + const rowId = toNumber(row.id); + const current = latestSnapshotMap.get(key); + if (!current) { + latestSnapshotMap.set(key, { + after_quantity: toNumber(row.after_quantity), + created_at_ms: createdAtMs, + id: rowId, + }); + continue; + } + + const currentCreatedAtMs = current.created_at_ms; + const shouldReplace = (createdAtMs !== null && currentCreatedAtMs === null) + || (createdAtMs !== null && currentCreatedAtMs !== null && createdAtMs > currentCreatedAtMs) + || (createdAtMs === currentCreatedAtMs && rowId > current.id); + + if (shouldReplace) { + current.after_quantity = toNumber(row.after_quantity); + current.created_at_ms = createdAtMs; + current.id = rowId; + } + } + + const snapshotMap = new Map(); + for (const [ key, value ] of latestSnapshotMap.entries()) { + snapshotMap.set(key, toNumber(value.after_quantity)); + } + + return snapshotMap; +} + +class StorageReportService extends Service { + /** + * 加载库存报表导出所需的名称映射。 + * @param {Object} options 参数 + * @param {number[]} [options.stockIds=[]] 商品库存ID列表 + * @param {number[]} [options.storeIds=[]] 货主ID列表 + * @param {number[]} [options.spaceIds=[]] 库位ID列表 + * @param {boolean} [options.includeBarcode=false] 是否加载条码映射 + * @return {Promise} 映射对象 + */ + async loadReportReferenceMaps({ + stockIds = [], + storeIds = [], + spaceIds = [], + includeBarcode = false, + } = {}) { + const { ctx } = this; + const normalizedStockIds = [ ...new Set((stockIds || []).map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)) ]; + const normalizedStoreIds = [ ...new Set((storeIds || []).map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)) ]; + const normalizedSpaceIds = [ ...new Set((spaceIds || []).map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0)) ]; + + const [ stockRows, storeRows, spaceRows, barcodeRows ] = await Promise.all([ + normalizedStockIds.length > 0 + ? ctx.model.StockWarehouse.findAll({ + where: { + id: normalizedStockIds, + }, + attributes: [ 'id', 'item_name', 'item_code' ], + raw: true, + }) + : [], + normalizedStoreIds.length > 0 + ? ctx.model.Store.findAll({ + where: { + id: normalizedStoreIds, + }, + attributes: [ 'id', 'company_name' ], + raw: true, + }) + : [], + normalizedSpaceIds.length > 0 + ? ctx.model.LocationSpace.findAll({ + where: { + id: normalizedSpaceIds, + }, + attributes: [ 'id', 'custom_name', 'space_code' ], + raw: true, + }) + : [], + includeBarcode && normalizedStockIds.length > 0 + ? ctx.model.StockBarcode.findAll({ + where: { + stock_id: normalizedStockIds, + }, + attributes: [ 'stock_id', 'barcode' ], + raw: true, + }) + : [], + ]); + + const stockMap = new Map((stockRows || []).map(item => [ Number(item.id), item ])); + const storeMap = new Map((storeRows || []).map(item => [ Number(item.id), item ])); + const spaceMap = new Map((spaceRows || []).map(item => [ Number(item.id), item ])); + const barcodeMap = new Map(); + + for (const row of barcodeRows || []) { + const stockId = Number(row.stock_id); + const barcode = row.barcode ? String(row.barcode).trim() : ''; + if (!stockId || !barcode) { + continue; + } + + if (!barcodeMap.has(stockId)) { + barcodeMap.set(stockId, new Set()); + } + barcodeMap.get(stockId).add(barcode); + } + + return { + stockMap, + storeMap, + spaceMap, + barcodeMap, + }; + } + + /** + * 构建库存报表导出文件名。 + * @param {string|Date|null|undefined} startTime 开始时间 + * @param {string|Date|null|undefined} endTime 结束时间 + * @return {string} 导出文件名 + */ + buildExportFilename(startTime, endTime) { + const startToken = formatDateToken(startTime); + const endToken = formatDateToken(endTime); + const todayToken = formatDateToken(new Date()); + + if (startToken && endToken) { + return `库存报表_${startToken}_${endToken}.xlsx`; + } + + if (startToken) { + return `库存报表_${startToken}.xlsx`; + } + + if (endToken) { + return `库存报表_${endToken}.xlsx`; + } + + return `库存报表_${todayToken}.xlsx`; + } + + /** + * 导出库存流水统计报表。 + * @param {string|Date|null} startTime 开始时间(闭区间下限) + * @param {string|Date|null} endTime 结束时间(闭区间上限) + * @param {boolean|string|number} [bySpace=false] 是否按库位返回 + * @param {Array|number|string|null} [storeIds=[]] 货主ID列表 + * @param {Object} [sort] 排序参数 + * @param {string} [sort.sortField] 排序字段 + * @param {string} [sort.sortOrder] 排序顺序 + * @return {Promise} excel 上传结果 + */ + async export(startTime, endTime, bySpace = false, storeIds = [], sort = null) { + const { ctx, app } = this; + const searchResult = await this.search(startTime, endTime, bySpace, storeIds, sort); + if (!searchResult || searchResult.code !== 200) { + return searchResult; + } + + const summaryList = Array.isArray(searchResult.data && searchResult.data.list) + ? searchResult.data.list + : []; + const warehouseId = Number(ctx.user && ctx.user.store_id); + const startTimeMs = toTimeMs(startTime); + const endTimeMs = toTimeMs(endTime); + const normalizedStoreIds = normalizeStoreIds(storeIds); + const isBySpace = normalizeBoolean(bySpace); + + const whereClauses = [ 't.warehouse_id = :warehouseId' ]; + const replacements = { + warehouseId, + }; + + if (startTimeMs !== null) { + whereClauses.push('t.created_at >= :startTime'); + replacements.startTime = startTime; + } + + if (endTimeMs !== null) { + whereClauses.push('t.created_at <= :endTime'); + replacements.endTime = endTime; + } + + if (normalizedStoreIds.length > 0) { + whereClauses.push('t.store_id IN (:storeIds)'); + replacements.storeIds = normalizedStoreIds; + } + + const detailRows = await ctx.model.query(` + SELECT + t.id, + t.created_at, + t.transaction_type, + t.store_id, + t.stock_id, + COALESCE(t.space_id, 0) AS space_id, + t.quantity, + t.before_quantity, + t.after_quantity, + t.before_locked_quantity, + t.after_locked_quantity, + t.batch_no, + t.inventory_type, + t.order_type, + t.order_no, + t.order_id, + t.receiving_id, + t.entry_order_id, + t.operator_name, + t.remark + FROM wms_stock_transaction t + WHERE ${whereClauses.join(' AND ')} + ORDER BY t.created_at ASC, t.id ASC + `, { + replacements, + type: app.Sequelize.QueryTypes.SELECT, + }); + + const safeDetailRows = Array.isArray(detailRows) ? detailRows : []; + const detailStockIds = [ ...new Set(safeDetailRows.map(item => Number(item.stock_id)).filter(item => Number.isInteger(item) && item > 0)) ]; + const detailStoreIds = [ ...new Set(safeDetailRows.map(item => Number(item.store_id)).filter(item => Number.isInteger(item) && item > 0)) ]; + const detailSpaceIds = [ ...new Set(safeDetailRows.map(item => Number(item.space_id)).filter(item => Number.isInteger(item) && item > 0)) ]; + + const summaryStockIds = [ ...new Set(summaryList.map(item => Number(item.stock_id)).filter(item => Number.isInteger(item) && item > 0)) ]; + const summaryStoreIds = [ ...new Set(summaryList.map(item => Number(item.store_id)).filter(item => Number.isInteger(item) && item > 0)) ]; + const summarySpaceIds = isBySpace + ? [ ...new Set(summaryList.map(item => Number(item.space_id)).filter(item => Number.isInteger(item) && item > 0)) ] + : []; + + const maps = await this.loadReportReferenceMaps({ + stockIds: [ ...new Set([ ...summaryStockIds, ...detailStockIds ]) ], + storeIds: [ ...new Set([ ...summaryStoreIds, ...detailStoreIds ]) ], + spaceIds: [ ...new Set([ ...summarySpaceIds, ...detailSpaceIds ]) ], + includeBarcode: true, + }); + + const summaryColumns = [ + { header: '开始时间', key: 'start_time' }, + { header: '结束时间', key: 'end_time' }, + { header: '货主ID', key: 'store_id' }, + { header: '货主名称', key: 'store_name' }, + { header: '商品库存ID', key: 'stock_id' }, + { header: '商品编码', key: 'item_code' }, + { header: '商品名称', key: 'item_name' }, + { header: '条码', key: 'barcode' }, + ...(isBySpace + ? [ + { header: '库位ID', key: 'space_id' }, + { header: '库位名称', key: 'space_name' }, + ] + : []), + { header: '期初', key: 'begin_total' }, + { header: '入库', key: 'inbound_total' }, + { header: '出库', key: 'outbound_total' }, + { header: '期末', key: 'end_total' }, + ]; + + const summarySheetRows = summaryList.map(item => ({ + start_time: item.start_time || '', + end_time: item.end_time || '', + store_id: toNumber(item.store_id), + store_name: item.store_name || '', + stock_id: toNumber(item.stock_id), + item_code: item.item_code || '', + item_name: item.item_name || '', + barcode: item.barcode || '', + ...(isBySpace + ? { + space_id: toNumber(item.space_id), + space_name: item.space_name || '', + } + : {}), + begin_total: toNumber(item.begin_total), + inbound_total: toNumber(item.inbound_total), + outbound_total: toNumber(item.outbound_total), + end_total: toNumber(item.end_total), + })); + + const detailSheetRows = safeDetailRows.map(item => { + const stockId = toNumber(item.stock_id); + const storeId = toNumber(item.store_id); + const spaceId = toNumber(item.space_id); + const stock = maps.stockMap.get(stockId) || {}; + const store = maps.storeMap.get(storeId) || {}; + const space = maps.spaceMap.get(spaceId) || {}; + const barcodeSet = maps.barcodeMap.get(stockId); + + return { + created_at: formatDateTime(item.created_at), + transaction_type: formatTransactionType(item.transaction_type), + store_id: storeId, + store_name: store.company_name || '', + stock_id: stockId, + item_code: stock.item_code || '', + item_name: stock.item_name || '', + barcode: barcodeSet ? [ ...barcodeSet ].join(',') : '', + space_id: spaceId, + space_name: space.custom_name || space.space_code || '', + quantity: toNumber(item.quantity), + before_quantity: toNumber(item.before_quantity), + after_quantity: toNumber(item.after_quantity), + before_locked_quantity: toNumber(item.before_locked_quantity), + after_locked_quantity: toNumber(item.after_locked_quantity), + batch_no: item.batch_no || '', + inventory_type: item.inventory_type || '', + order_type: item.order_type || '', + order_no: item.order_no || '', + order_id: toNumber(item.order_id), + receiving_id: toNumber(item.receiving_id), + entry_order_id: toNumber(item.entry_order_id), + operator_name: item.operator_name || '', + remark: item.remark || '', + }; + }); + + const detailColumns = [ + { header: '时间', key: 'created_at' }, + { header: '类型', key: 'transaction_type' }, + { header: '货主名称', key: 'store_name' }, + { header: '商品库存ID', key: 'stock_id' }, + { header: '商品编码', key: 'item_code' }, + { header: '商品名称', key: 'item_name' }, + { header: '条码', key: 'barcode' }, + { header: '库位ID', key: 'space_id' }, + { header: '库位名称', key: 'space_name' }, + { header: '变动数量', key: 'quantity' }, + { header: '变更前库存', key: 'before_quantity' }, + { header: '变更后库存', key: 'after_quantity' }, + { header: '变更前锁定', key: 'before_locked_quantity' }, + { header: '变更后锁定', key: 'after_locked_quantity' }, + { header: '批次号', key: 'batch_no' }, + { header: '库存类型', key: 'inventory_type' }, + { header: '单据类型', key: 'order_type' }, + { header: '单据号', key: 'order_no' }, + { header: '单据ID', key: 'order_id' }, + { header: '收货单ID', key: 'receiving_id' }, + { header: '入库单ID', key: 'entry_order_id' }, + { header: '操作人', key: 'operator_name' }, + { header: '备注', key: 'remark' }, + ]; + + return await ctx.service.systems.excel.generateAndUpload({ + filename: this.buildExportFilename(startTime, endTime), + dir: `exports/storage/report/${warehouseId || 'common'}`, + category: 'document', + sheets: [ + { + name: '汇总', + columns: summaryColumns, + rows: summarySheetRows, + }, + { + name: '变更记录', + columns: detailColumns, + rows: detailSheetRows, + }, + ], + }); + } + + /** + * 查询库存流水统计报表。 + * 规则: + * 1) 期初优先取 start_time 之前最后一条流水的 after_quantity。 + * 2) 若 start_time 之前无流水,期初回退到区间内首条流水的 before_quantity。 + * 3) 期末取区间内末条流水的 after_quantity。 + * 4) 若维度键在区间内仍无流水,期初/期末统一回退为 0。 + * 5) by_space=false 时按 stock_id+store_id 维度输出;by_space=true 时按 stock_id+space_id+store_id 维度输出。 + * + * @param {string|Date|null} startTime 开始时间(闭区间下限) + * @param {string|Date|null} endTime 结束时间(闭区间上限) + * @param {boolean|string|number} [bySpace=false] 是否按库位返回 + * @param {Array|number|string|null} [storeIds=[]] 货主ID列表 + * @param {Object} [sort] 排序参数 + * @param {string} [sort.sortField] 排序字段(begin_total、inbound_total、outbound_total、end_total) + * @param {string} [sort.sortOrder] 排序顺序(ASC、DESC,大小写不敏感) + * @return {Promise} code/data/message 结构 + */ + async search(startTime, endTime, bySpace = false, storeIds = [], sort = null) { + const { ctx, app } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id); + if (!warehouseId) { + return { + code: 400, + message: '用户未绑定仓库', + data: { list: [] }, + }; + } + + const startTimeMs = toTimeMs(startTime); + const endTimeMs = toTimeMs(endTime); + + if (startTime !== undefined && startTime !== null && startTime !== '' && startTimeMs === null) { + return { + code: 400, + message: 'start_time 参数不合法', + data: { list: [] }, + }; + } + + if (endTime !== undefined && endTime !== null && endTime !== '' && endTimeMs === null) { + return { + code: 400, + message: 'end_time 参数不合法', + data: { list: [] }, + }; + } + + if (startTimeMs !== null && endTimeMs !== null && startTimeMs > endTimeMs) { + return { + code: 400, + message: 'start_time 不能大于 end_time', + data: { list: [] }, + }; + } + + const isBySpace = normalizeBoolean(bySpace); + const normalizedStoreIds = normalizeStoreIds(storeIds); + + let baseStockRows = []; + let baseStorageRows = []; + if (!isBySpace) { + const baseWhereClauses = [ 'sw.warehouse_id = :warehouseId' ]; + const baseReplacements = { + warehouseId, + }; + + if (normalizedStoreIds.length > 0) { + baseWhereClauses.push('sw.store_id IN (:storeIds)'); + baseReplacements.storeIds = normalizedStoreIds; + } + + baseStockRows = await ctx.model.query(` + SELECT + sw.id AS stock_id, + sw.store_id, + sw.quantity + FROM wms_stock_warehouse sw + WHERE ${baseWhereClauses.join(' AND ')} + `, { + replacements: baseReplacements, + type: app.Sequelize.QueryTypes.SELECT, + }); + + if (!Array.isArray(baseStockRows) || baseStockRows.length === 0) { + return { + code: 200, + message: '查询成功', + data: { list: [] }, + }; + } + } else { + const baseWhereClauses = [ 's.warehouse_id = :warehouseId', 's.delete_at IS NULL' ]; + const baseReplacements = { + warehouseId, + }; + + if (normalizedStoreIds.length > 0) { + baseWhereClauses.push('s.store_id IN (:storeIds)'); + baseReplacements.storeIds = normalizedStoreIds; + } + + baseStorageRows = await ctx.model.query(` + SELECT + s.stock_id, + COALESCE(s.space_id, 0) AS space_id, + s.store_id, + SUM(s.quantity) AS quantity + FROM wms_storage s + WHERE ${baseWhereClauses.join(' AND ')} + GROUP BY s.stock_id, COALESCE(s.space_id, 0), s.store_id + `, { + replacements: baseReplacements, + type: app.Sequelize.QueryTypes.SELECT, + }); + + baseStorageRows = Array.isArray(baseStorageRows) ? baseStorageRows : []; + } + + const rangeWhereClauses = [ 't.warehouse_id = :warehouseId' ]; + const rangeReplacements = { + warehouseId, + }; + + if (startTimeMs !== null) { + rangeWhereClauses.push('t.created_at >= :startTime'); + rangeReplacements.startTime = startTime; + } + + if (endTimeMs !== null) { + rangeWhereClauses.push('t.created_at <= :endTime'); + rangeReplacements.endTime = endTime; + } + + if (normalizedStoreIds.length > 0) { + rangeWhereClauses.push('t.store_id IN (:storeIds)'); + rangeReplacements.storeIds = normalizedStoreIds; + } + + if (!isBySpace) { + const baseStockIds = [ + ...new Set(baseStockRows.map(item => Number(item.stock_id)).filter(item => Number.isInteger(item) && item > 0)), + ]; + if (baseStockIds.length === 0) { + return { + code: 200, + message: '查询成功', + data: { list: [] }, + }; + } + + rangeWhereClauses.push('t.stock_id IN (:baseStockIds)'); + rangeReplacements.baseStockIds = baseStockIds; + } + + const rangeRowsSql = ` + SELECT + t.stock_id, + COALESCE(t.space_id, 0) AS space_id, + t.store_id, + SUM(CASE WHEN t.transaction_type = 'INBOUND' THEN t.quantity ELSE 0 END) AS inbound_total, + SUM(CASE WHEN t.transaction_type = 'OUTBOUND' THEN t.quantity ELSE 0 END) AS outbound_total + FROM wms_stock_transaction t + WHERE ${rangeWhereClauses.join(' AND ')} + GROUP BY t.stock_id, COALESCE(t.space_id, 0), t.store_id + `; + + const rangeRows = await ctx.model.query(rangeRowsSql, { + replacements: rangeReplacements, + type: app.Sequelize.QueryTypes.SELECT, + }); + + const safeRangeRows = Array.isArray(rangeRows) ? rangeRows : []; + + const intervalEdgeRows = await ctx.model.query(` + SELECT + t.id, + t.stock_id, + COALESCE(t.space_id, 0) AS space_id, + t.store_id, + t.before_quantity, + t.after_quantity, + t.created_at + FROM wms_stock_transaction t + WHERE ${rangeWhereClauses.join(' AND ')} + ORDER BY t.stock_id ASC, t.store_id ASC, t.created_at ASC, t.id ASC, COALESCE(t.space_id, 0) ASC + `, { + replacements: rangeReplacements, + type: app.Sequelize.QueryTypes.SELECT, + }); + + let preStartSnapshotRows = []; + if (startTimeMs !== null) { + const preStartWhereClauses = [ + 't.warehouse_id = :warehouseId', + 't.created_at < :startTime', + ]; + const preStartReplacements = { + warehouseId, + startTime, + }; + + if (normalizedStoreIds.length > 0) { + preStartWhereClauses.push('t.store_id IN (:storeIds)'); + preStartReplacements.storeIds = normalizedStoreIds; + } + + if (!isBySpace) { + preStartWhereClauses.push('t.stock_id IN (:baseStockIds)'); + preStartReplacements.baseStockIds = rangeReplacements.baseStockIds; + } + + preStartSnapshotRows = await ctx.model.query(` + SELECT + t.id, + t.stock_id, + COALESCE(t.space_id, 0) AS space_id, + t.store_id, + t.after_quantity, + t.created_at + FROM wms_stock_transaction t + WHERE ${preStartWhereClauses.join(' AND ')} + ORDER BY t.stock_id ASC, t.store_id ASC, COALESCE(t.space_id, 0) ASC, t.created_at DESC, t.id DESC + `, { + replacements: preStartReplacements, + type: app.Sequelize.QueryTypes.SELECT, + }); + } + + if (!isBySpace) { + const edgeByStockStore = buildIntervalEdgeMap(intervalEdgeRows, row => { + const stockId = Number(row.stock_id); + const storeId = Number(row.store_id); + if (!stockId || !storeId) { + return null; + } + return `${stockId}_${storeId}`; + }); + const preStartAfterByStockStore = buildPreStartAfterMap(preStartSnapshotRows, row => { + const stockId = Number(row.stock_id); + const storeId = Number(row.store_id); + if (!stockId || !storeId) { + return null; + } + return `${stockId}_${storeId}`; + }); + + const rangeSumByStockStore = new Map(); + for (const row of safeRangeRows) { + const stockId = Number(row.stock_id); + const storeId = Number(row.store_id); + if (!stockId || !storeId) { + continue; + } + const stockStoreKey = `${stockId}_${storeId}`; + if (!rangeSumByStockStore.has(stockStoreKey)) { + rangeSumByStockStore.set(stockStoreKey, { + inbound_total: 0, + outbound_total: 0, + }); + } + const current = rangeSumByStockStore.get(stockStoreKey); + current.inbound_total += toNumber(row.inbound_total); + current.outbound_total += toNumber(row.outbound_total); + } + + const groupedList = baseStockRows + .map(row => { + const stockId = Number(row.stock_id); + const storeId = Number(row.store_id); + const stockStoreKey = `${stockId}_${storeId}`; + const snapshot = edgeByStockStore.get(stockStoreKey); + const rangeSum = rangeSumByStockStore.get(stockStoreKey); + const preStartAfter = preStartAfterByStockStore.get(stockStoreKey); + const hasSnapshot = snapshot && snapshot.has_snapshot; + const hasPreStartSnapshot = preStartAfterByStockStore.has(stockStoreKey); + let beginTotal = 0; + if (hasPreStartSnapshot) { + beginTotal = toNumber(preStartAfter); + } else if (hasSnapshot) { + beginTotal = toNumber(snapshot && snapshot.begin_total); + } + + const endTotal = hasSnapshot ? toNumber(snapshot && snapshot.end_total) : 0; + + return { + start_time: startTime || null, + end_time: endTime || null, + stock_id: stockId, + store_id: storeId, + begin_total: beginTotal, + end_total: endTotal, + inbound_total: toNumber(rangeSum && rangeSum.inbound_total), + outbound_total: toNumber(rangeSum && rangeSum.outbound_total), + store_name: '', + item_name: '', + barcode: '', + item_code: '', + }; + }) + .filter(item => item.stock_id > 0 && item.store_id > 0); + + const stockIds = [ ...new Set(groupedList.map(item => item.stock_id).filter(Boolean)) ]; + const storeIdList = [ ...new Set(groupedList.map(item => item.store_id).filter(Boolean)) ]; + + const [ stockRows, barcodeRows, storeRows ] = await Promise.all([ + stockIds.length > 0 + ? ctx.model.StockWarehouse.findAll({ + where: { + id: stockIds, + }, + attributes: [ 'id', 'item_name', 'item_code' ], + raw: true, + }) + : [], + stockIds.length > 0 + ? ctx.model.StockBarcode.findAll({ + where: { + stock_id: stockIds, + }, + attributes: [ 'stock_id', 'barcode' ], + raw: true, + }) + : [], + storeIdList.length > 0 + ? ctx.model.Store.findAll({ + where: { + id: storeIdList, + }, + attributes: [ 'id', 'company_name' ], + raw: true, + }) + : [], + ]); + + const stockMap = new Map(stockRows.map(item => [ Number(item.id), item ])); + const storeMap = new Map(storeRows.map(item => [ Number(item.id), item ])); + const barcodesByStock = new Map(); + for (const row of barcodeRows) { + const stockId = Number(row.stock_id); + const barcode = row.barcode ? String(row.barcode).trim() : ''; + if (!stockId || !barcode) { + continue; + } + + if (!barcodesByStock.has(stockId)) { + barcodesByStock.set(stockId, new Set()); + } + barcodesByStock.get(stockId).add(barcode); + } + + const list = groupedList + .map(item => { + const stock = stockMap.get(item.stock_id) || {}; + const store = storeMap.get(item.store_id) || {}; + const barcodeSet = barcodesByStock.get(item.stock_id); + + return { + ...item, + store_name: store.company_name || '', + item_name: stock.item_name || '', + item_code: stock.item_code || '', + barcode: barcodeSet ? [ ...barcodeSet ].join(',') : '', + }; + }); + + sortReportList(list, false, sort); + + return { + code: 200, + message: '查询成功', + data: { + list, + }, + }; + } + + const baseEntryByKey = new Map(); + for (const row of baseStorageRows) { + const stockId = Number(row.stock_id); + const spaceId = Number(row.space_id) || 0; + const storeId = Number(row.store_id); + if (!stockId || !storeId) { + continue; + } + + const baseKey = `${stockId}_${spaceId}_${storeId}`; + baseEntryByKey.set(baseKey, { + stock_id: stockId, + space_id: spaceId, + store_id: storeId, + quantity: toNumber(row.quantity), + }); + } + + for (const row of safeRangeRows) { + const stockId = Number(row.stock_id); + const spaceId = Number(row.space_id) || 0; + const storeId = Number(row.store_id); + if (!stockId || !storeId) { + continue; + } + + const baseKey = `${stockId}_${spaceId}_${storeId}`; + if (!baseEntryByKey.has(baseKey)) { + baseEntryByKey.set(baseKey, { + stock_id: stockId, + space_id: spaceId, + store_id: storeId, + quantity: 0, + }); + } + } + + const baseEntries = [ ...baseEntryByKey.values() ]; + if (baseEntries.length === 0) { + return { + code: 200, + message: '查询成功', + data: { list: [] }, + }; + } + + const edgeByBaseKey = buildIntervalEdgeMap(intervalEdgeRows, row => { + const stockId = Number(row.stock_id); + const spaceId = Number(row.space_id) || 0; + const storeId = Number(row.store_id); + if (!stockId || !storeId) { + return null; + } + return `${stockId}_${spaceId}_${storeId}`; + }); + const preStartAfterByBaseKey = buildPreStartAfterMap(preStartSnapshotRows, row => { + const stockId = Number(row.stock_id); + const spaceId = Number(row.space_id) || 0; + const storeId = Number(row.store_id); + if (!stockId || !storeId) { + return null; + } + return `${stockId}_${spaceId}_${storeId}`; + }); + + const rangeByBaseKey = new Map(); + for (const row of safeRangeRows) { + const stockId = Number(row.stock_id); + const spaceId = Number(row.space_id) || 0; + const storeId = Number(row.store_id); + if (!stockId || !storeId) { + continue; + } + const baseKey = `${stockId}_${spaceId}_${storeId}`; + rangeByBaseKey.set(baseKey, { + inbound_total: toNumber(row.inbound_total), + outbound_total: toNumber(row.outbound_total), + }); + } + + const groupedMap = new Map(); + for (const row of baseEntries) { + const stockId = Number(row.stock_id); + const spaceId = Number(row.space_id) || 0; + const storeId = Number(row.store_id); + const baseKey = `${stockId}_${spaceId}_${storeId}`; + const snapshot = edgeByBaseKey.get(baseKey) || { + begin_total: 0, + end_total: 0, + has_snapshot: false, + }; + const preStartAfter = preStartAfterByBaseKey.get(baseKey); + const hasPreStartSnapshot = preStartAfterByBaseKey.has(baseKey); + const rangeSum = rangeByBaseKey.get(baseKey) || { + inbound_total: 0, + outbound_total: 0, + }; + + const targetKey = baseKey; + + if (!groupedMap.has(targetKey)) { + groupedMap.set(targetKey, { + start_time: startTime || null, + end_time: endTime || null, + stock_id: stockId, + store_id: storeId, + ...(isBySpace ? { space_id: spaceId } : {}), + begin_total: 0, + end_total: 0, + inbound_total: 0, + outbound_total: 0, + store_name: '', + item_name: '', + barcode: '', + item_code: '', + space_name: '', + }); + } + + const current = groupedMap.get(targetKey); + const beginTotal = hasPreStartSnapshot + ? toNumber(preStartAfter) + : snapshot.has_snapshot + ? toNumber(snapshot.begin_total) + : 0; + const endTotal = snapshot.has_snapshot ? toNumber(snapshot.end_total) : 0; + current.begin_total += beginTotal; + current.end_total += endTotal; + current.inbound_total += toNumber(rangeSum.inbound_total); + current.outbound_total += toNumber(rangeSum.outbound_total); + } + + const groupedList = [ ...groupedMap.values() ]; + const stockIds = [ ...new Set(groupedList.map(item => item.stock_id).filter(Boolean)) ]; + const storeIdList = [ ...new Set(groupedList.map(item => item.store_id).filter(Boolean)) ]; + const spaceIds = isBySpace + ? [ ...new Set(groupedList.map(item => item.space_id).filter(id => Number(id) > 0)) ] + : []; + + const [ stockRows, barcodeRows, storeRows, spaceRows ] = await Promise.all([ + stockIds.length > 0 + ? ctx.model.StockWarehouse.findAll({ + where: { + id: stockIds, + }, + attributes: [ 'id', 'item_name', 'item_code' ], + raw: true, + }) + : [], + stockIds.length > 0 + ? ctx.model.StockBarcode.findAll({ + where: { + stock_id: stockIds, + }, + attributes: [ 'stock_id', 'barcode' ], + raw: true, + }) + : [], + storeIdList.length > 0 + ? ctx.model.Store.findAll({ + where: { + id: storeIdList, + }, + attributes: [ 'id', 'company_name' ], + raw: true, + }) + : [], + isBySpace && spaceIds.length > 0 + ? ctx.model.LocationSpace.findAll({ + where: { + id: spaceIds, + }, + attributes: [ 'id', 'custom_name', 'space_code' ], + raw: true, + }) + : [], + ]); + + const stockMap = new Map(stockRows.map(item => [ Number(item.id), item ])); + const storeMap = new Map(storeRows.map(item => [ Number(item.id), item ])); + const spaceMap = new Map(spaceRows.map(item => [ Number(item.id), item ])); + const barcodesByStock = new Map(); + for (const row of barcodeRows) { + const stockId = Number(row.stock_id); + const barcode = row.barcode ? String(row.barcode).trim() : ''; + if (!stockId || !barcode) { + continue; + } + + if (!barcodesByStock.has(stockId)) { + barcodesByStock.set(stockId, new Set()); + } + barcodesByStock.get(stockId).add(barcode); + } + + const list = groupedList + .map(item => { + const stock = stockMap.get(item.stock_id) || {}; + const store = storeMap.get(item.store_id) || {}; + const barcodeSet = barcodesByStock.get(item.stock_id); + const space = isBySpace ? (spaceMap.get(Number(item.space_id)) || {}) : null; + + const merged = { + ...item, + store_name: store.company_name || '', + item_name: stock.item_name || '', + item_code: stock.item_code || '', + barcode: barcodeSet ? [ ...barcodeSet ].join(',') : '', + }; + + if (isBySpace) { + merged.space_name = space.custom_name || space.space_code || ''; + } + + return merged; + }); + + sortReportList(list, isBySpace, sort); + + return { + code: 200, + message: '查询成功', + data: { + list, + }, + }; + } +} + +module.exports = StorageReportService; diff --git a/database/migrations/20260513090000-add-last-login-time-to-wms_print_computer.js b/database/migrations/20260513090000-add-last-login-time-to-wms_print_computer.js index f71231d..984a5be 100644 --- a/database/migrations/20260513090000-add-last-login-time-to-wms_print_computer.js +++ b/database/migrations/20260513090000-add-last-login-time-to-wms_print_computer.js @@ -5,7 +5,7 @@ module.exports = { * 为打印台电脑表新增上次登录时间字段。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口 * @param {import('sequelize')} Sequelize Sequelize 实例 - * @returns {Promise} 无返回值 + * @return {Promise} 无返回值 */ async up(queryInterface, Sequelize) { await queryInterface.addColumn('wms_print_computer', 'last_login_time', { @@ -19,7 +19,7 @@ module.exports = { * 回滚删除打印台电脑表的上次登录时间字段。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口 * @param {import('sequelize')} Sequelize Sequelize 实例 - * @returns {Promise} 无返回值 + * @return {Promise} 无返回值 */ async down(queryInterface, Sequelize) { await queryInterface.removeColumn('wms_print_computer', 'last_login_time'); diff --git a/database/migrations/20260513113000-create-wms_order_wave_index.js b/database/migrations/20260513113000-create-wms_order_wave_index.js index 856bdd5..50ba5d6 100644 --- a/database/migrations/20260513113000-create-wms_order_wave_index.js +++ b/database/migrations/20260513113000-create-wms_order_wave_index.js @@ -5,7 +5,7 @@ module.exports = { * 创建订单波次顺序副表。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口 * @param {import('sequelize')} Sequelize Sequelize 实例 - * @returns {Promise} 无返回值 + * @return {Promise} 无返回值 */ async up(queryInterface, Sequelize) { await queryInterface.createTable('wms_order_wave_index', { @@ -78,7 +78,7 @@ module.exports = { * 回滚删除订单波次顺序副表。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口 * @param {import('sequelize')} Sequelize Sequelize 实例 - * @returns {Promise} 无返回值 + * @return {Promise} 无返回值 */ async down(queryInterface, Sequelize) { await queryInterface.dropTable('wms_order_wave_index'); diff --git a/database/migrations/20260514110000-add-subject-config-to-wms_print_stations.js b/database/migrations/20260514110000-add-subject-config-to-wms_print_stations.js index 58ca8d1..84c7224 100644 --- a/database/migrations/20260514110000-add-subject-config-to-wms_print_stations.js +++ b/database/migrations/20260514110000-add-subject-config-to-wms_print_stations.js @@ -5,7 +5,7 @@ module.exports = { * 为打印台表新增主体配置字段。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口 * @param {import('sequelize')} Sequelize Sequelize 实例 - * @returns {Promise} 无返回值 + * @return {Promise} 无返回值 */ async up(queryInterface, Sequelize) { const tableDefinition = await queryInterface.describeTable('wms_print_stations'); @@ -24,7 +24,7 @@ module.exports = { * 回滚删除打印台表主体配置字段。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口 * @param {import('sequelize')} Sequelize Sequelize 实例 - * @returns {Promise} 无返回值 + * @return {Promise} 无返回值 */ async down(queryInterface) { const tableDefinition = await queryInterface.describeTable('wms_print_stations'); diff --git a/database/migrations/20260514123000-drop-wms_print_station_express.js b/database/migrations/20260514123000-drop-wms_print_station_express.js index 48b61ba..eebd9c2 100644 --- a/database/migrations/20260514123000-drop-wms_print_station_express.js +++ b/database/migrations/20260514123000-drop-wms_print_station_express.js @@ -5,7 +5,7 @@ module.exports = { * 删除已弃用的打印台快递关联表。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口 * @param {import('sequelize')} Sequelize Sequelize 实例 - * @returns {Promise} 无返回值 + * @return {Promise} 无返回值 */ async up(queryInterface, Sequelize) { await queryInterface.sequelize.query( @@ -17,7 +17,7 @@ module.exports = { * 回滚重建打印台快递关联表(核心字段与唯一索引)。 * @param {import('sequelize').QueryInterface} queryInterface 查询接口 * @param {import('sequelize')} Sequelize Sequelize 实例 - * @returns {Promise} 无返回值 + * @return {Promise} 无返回值 */ async down(queryInterface, Sequelize) { await queryInterface.createTable('wms_print_station_express', { diff --git a/database/migrations/20260514150000-add-workerstation-pages-to-wms_permission-type.js b/database/migrations/20260514150000-add-workerstation-pages-to-wms_permission-type.js new file mode 100644 index 0000000..f966b74 --- /dev/null +++ b/database/migrations/20260514150000-add-workerstation-pages-to-wms_permission-type.js @@ -0,0 +1,52 @@ +'use strict'; + +module.exports = { + /** + * 扩展权限类型枚举,新增 workerstation_pages。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + await queryInterface.changeColumn('wms_permission', 'type', { + type: Sequelize.ENUM( + 'web_pages', + 'pda_pages', + 'btns', + 'api', + 'miniprogram_pages', + 'block', + 'workerstation_pages' + ), + allowNull: false, + defaultValue: 'web_pages', + comment: '权限类型(web_pages:电脑端页面,pda_pages:PDA页面,btns:按钮权限,api:接口权限,miniprogram_pages:小程序页面,block:功能模块,workerstation_pages:工作台菜单)', + }); + }, + + /** + * 回滚权限类型枚举,先将 workerstation_pages 转换为 web_pages。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async down(queryInterface, Sequelize) { + await queryInterface.sequelize.query( + "UPDATE `wms_permission` SET `type` = 'web_pages' WHERE `type` = 'workerstation_pages'" + ); + + await queryInterface.changeColumn('wms_permission', 'type', { + type: Sequelize.ENUM( + 'web_pages', + 'pda_pages', + 'btns', + 'api', + 'miniprogram_pages', + 'block' + ), + allowNull: false, + defaultValue: 'web_pages', + comment: '权限类型(web_pages:电脑端页面,pda_pages:PDA页面,btns:按钮权限,api:接口权限,miniprogram_pages:小程序页面,block:功能模块)', + }); + }, +}; diff --git a/database/migrations/20260514173000-add-component-to-wms_platform.js b/database/migrations/20260514173000-add-component-to-wms_platform.js new file mode 100644 index 0000000..c71ff28 --- /dev/null +++ b/database/migrations/20260514173000-add-component-to-wms_platform.js @@ -0,0 +1,46 @@ +'use strict'; + +/** + * 为 wms_platform 新增 component 字段。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移:新增 component 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + const tableName = 'wms_platform'; + const columns = await queryInterface.describeTable(tableName); + + if (columns.component) { + return; + } + + await queryInterface.addColumn(tableName, 'component', { + type: Sequelize.STRING(255), + allowNull: true, + comment: '打印组件标识', + }); + }, + + /** + * 回滚迁移:删除 component 字段(幂等)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @return {Promise} 无返回值 + */ + async down(queryInterface) { + const tableName = 'wms_platform'; + const columns = await queryInterface.describeTable(tableName); + + if (!columns.component) { + return; + } + + await queryInterface.removeColumn(tableName, 'component'); + }, +}; diff --git a/database/migrations/20260516093000-alter-wms-stock-transaction-order-no-and-transaction-type.js b/database/migrations/20260516093000-alter-wms-stock-transaction-order-no-and-transaction-type.js new file mode 100644 index 0000000..ac4d9b3 --- /dev/null +++ b/database/migrations/20260516093000-alter-wms-stock-transaction-order-no-and-transaction-type.js @@ -0,0 +1,61 @@ +'use strict'; + +/** + * 调整 wms_stock_transaction 的单据号字段类型并扩展出入库类型枚举。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ +module.exports = { + /** + * 执行迁移: + * 1. order_no 由 STRING(100) 调整为 TEXT; + * 2. transaction_type 增加 TRANSFER_OUT、TRANSFER_IN 枚举值。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async up(queryInterface, Sequelize) { + await queryInterface.changeColumn('wms_stock_transaction', 'order_no', { + type: Sequelize.TEXT, + allowNull: true, + comment: '关联单据号', + }); + + await queryInterface.changeColumn('wms_stock_transaction', 'transaction_type', { + type: Sequelize.ENUM('INBOUND', 'OUTBOUND', 'TRANSFER_OUT', 'TRANSFER_IN'), + allowNull: false, + comment: '出入库类型(含移库)', + }); + }, + + /** + * 回滚迁移: + * 1. 先将移库枚举值映射回原有枚举,避免收缩 ENUM 失败; + * 2. transaction_type 回退为仅 INBOUND、OUTBOUND; + * 3. order_no 回退为 STRING(100)。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口 + * @param {import('sequelize')} Sequelize Sequelize 实例 + * @return {Promise} 无返回值 + */ + async down(queryInterface, Sequelize) { + await queryInterface.sequelize.query( + "UPDATE wms_stock_transaction SET transaction_type = 'OUTBOUND' WHERE transaction_type = 'TRANSFER_OUT'" + ); + await queryInterface.sequelize.query( + "UPDATE wms_stock_transaction SET transaction_type = 'INBOUND' WHERE transaction_type = 'TRANSFER_IN'" + ); + + await queryInterface.changeColumn('wms_stock_transaction', 'transaction_type', { + type: Sequelize.ENUM('INBOUND', 'OUTBOUND'), + allowNull: false, + comment: '出入库类型', + }); + + await queryInterface.changeColumn('wms_stock_transaction', 'order_no', { + type: Sequelize.STRING(100), + allowNull: true, + comment: '关联单据号', + }); + }, +}; \ No newline at end of file diff --git a/methods/changes/system.json b/methods/changes/system.json index 166d8ff..bce9d9c 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,1645 +1,1762 @@ [ - { - "version": "2026.05.12-system-01", - "date": "2026-05-12", - "summary": "调整订单打印中间态返回结构为 waveGroups(波次 -> 平台 -> 订单)", - "methods": [ - "order.print.getWavePlatformPrintData" - ], - "notes": [ - "主要变更:将方法的主返回结构改为 waveGroups,按波次分组,波次内按平台分组,平台内为订单列表(波次 -> 平台 -> 订单)。", - "兼容性:保留旧字段 platform_groups 与 order_list 作为向后兼容字段,但文档主结构与推荐使用为 waveGroups。", - "返回结构说明:summary(total_waves/total_orders/total_platforms)、wave_ids(通过过滤的波次ID数组)、waveGroups(数组,项含 wave_id、wave_no、order_count、platforms[...],platforms项含 platform、platform_name、order_count、orders[...])、ext(missing_wave_ids、filtered_wave_ids)。", - "errors:保留 400 / 500 不变。" - ], - "type": "modified" - }, - { - "version": "2026.05.11-system-05", - "date": "2026-05-11", - "summary": "order.wave.batchList:支持 express/print 分配状态筛选,入参改为英文枚举(express/print)", - "methods": [ - "order.wave.batchList" - ], - "notes": [ - "修复 where.express_assignment_status 可按快递分配状态筛选。", - "新增 where.print_assignment_status 筛选(按打印分配聚合判断)。", - "express_assignment_status / print_assignment_status 要求使用英文枚举值:express=unassigned/partially_assigned/assigned,print=unprinted/partially_printed/printed;storage_assignment_status 继续兼容中文枚举(未分配/部分分配/已分配)。", - "若传入非法枚举值,接口返回 400(参数校验失败),message 中会说明允许取值。" - ], - "type": "updated" - }, - { - "version": "2026.05.11-system-04", - "date": "2026-05-11", - "summary": "调整 order.wave.waveStrategyFetchAdmin:由创建任务改为直接创建波次(不创建拣货任务)", - "methods": [ - "order.wave.waveStrategyFetchAdmin" - ], - "notes": [ - "接口行为变更:按策略直接抓取命中订单并创建波次,不再创建拣货任务(不返回 task_id/task_no 等任务字段)。", - "响应调整为建波结果:fetch_state(1=成功/2=失败)、wave_ids、wave_nos、created_wave_count、created_order_count、order_ids、(可选)wave_prefix、wave_prefix_source、tip/message。", - "错误调整:策略校验失败返回 400(并可能返回 validation_errors),缺少仓库上下文返回 400,建波失败返回 500 并在 message 中说明。" - ], - "type": "updated" - }, - { - "version": "2026.05.11-system-03", - "date": "2026-05-11", - "summary": "更新 pick.query:由查询拣货明细调整为按 keyword 获取/创建拣货任务", - "methods": [ - "pick.query" - ], - "notes": [ - "入参由 waybill_code/full_display 调整为 keyword(支持运单号或波次号)。", - "接口语义调整为任务化返回:命中活动任务则返回 existing 任务ID;无活动任务则创建并返回 created 任务ID。", - "新增任务归属冲突错误:当活动任务创建人非当前用户时返回冲突提示,并附带创建人及任务ID信息。" - ], - "type": "updated" - }, - { - "version": "2026.05.11-system-02", - "date": "2026-05-11", - "summary": "新增 pick.wavePickTaskCurrent:PDA 无参查询当前进行中拣货任务", - "methods": [ - "pick.wavePickTaskCurrent" - ], - "notes": [ - "新增 PDA 专用无参接口 pick.wavePickTaskCurrent。", - "按当前登录用户上下文(pick_user_id + warehouse_id)查询状态在 0/1/2 的最新任务。", - "命中返回 task_id,未命中返回 task_id=null。" - ], - "type": "added" - }, - { - "version": "2026.05.10-system-04", - "date": "2026-05-10", - "summary": "pick.wavePickTaskDetail 新增按任务类型区分的 picking_view 形态输出", - "methods": [ - "pick.wavePickTaskDetail" - ], - "notes": [ - "新增响应字段:picking_view(object),按 task.pick_mode 区分 5 种形态输出。", - "picking_view 字段说明:mode_code, mode_name, require_box_allocations, group_by, sort_by, items[](每项含 space_id、space_name、location_space、item_code、item_name、stock_id、total_qty、box_allocations[])。", - "当 pick_mode=1/3/4 时 require_box_allocations=true;当 pick_mode=2/5 时 require_box_allocations=false。" - ], - "type": "updated" - }, - { - "version": "2026.05.10-system-02", - "date": "2026-05-10", - "summary": "order.wave.waveStrategyFetchPda/Admin 返回新增 fetch_state 三态与简短 tip", - "methods": [ - "order.wave.waveStrategyFetchPda", - "order.wave.waveStrategyFetchAdmin" - ], - "notes": [ - "新增返回字段:fetch_state(number)、tip(string)、can_enter_pick_flow(boolean)", - "fetch_state 含义:1=创建成功(返回 task_id/task_no),2=普通失败(task_id=null),3=存在未完成任务(返回 existing task_id/task_no,前端可直接进入拣货流程)", - "当 fetch_state=3 时,字段 can_enter_pick_flow=true,表示前端可直接进入拣货流程;tip 为简短提示文本" - ], - "type": "updated" - }, - { - "version": "2026.05.10-system-03", - "date": "2026-05-10", - "summary": "裁剪 pick.wavePickTaskDetail 返回:移除 waves/orders,精简 task 并补充 boxes 拣货统计字段", - "methods": [ - "pick.wavePickTaskDetail" - ], - "notes": [ - "移除响应中的 waves 与 orders 子表,接口仅返回精简的 task、boxes、picking_details 与 picking_summary。", - "task 子字段裁剪为:task_id, task_no, status, pick_mode, start_at, finish_at, batch_no。", - "boxes 补充并明确返回:ref_label(箱参考标签)、required_qty(箱内需拣总数)、picked_qty(已拣数量)。", - "本次变更为文档层面的返回裁剪,前端应以新字段集合为准,旧字段可能不再返回。" - ], - "type": "updated" - }, - { - "version": "2026.05.10-system-01", - "date": "2026-05-10", - "summary": "order.wave.waveStrategyList 新增 strategy_type 最小过滤(散单/团购)", - "methods": [ - "order.wave.waveStrategyList" - ], - "notes": [ - "新增 strategy_type 过滤,仅 1/2", - "支持顶层 strategy_type 和 where.strategy_type,顶层优先", - "当前不引入其他 where 字段" - ], - "type": "updated" - }, - { - "version": "2026.05.09-system-02", - "date": "2026-05-09", - "summary": "新增 pick.wavePickTaskDetail:按任务ID解析拣货任务详情", - "methods": [ - "pick.wavePickTaskDetail" - ], - "notes": [ - "新增 pick.wavePickTaskDetail:传入 task_id 获取拣货任务完整信息,包含主表字段(task/pick_mode/status/wave_count/order_count/box_count 等)及三张子表数据(waves/orders/boxes)。", - "安全限制:接口会校验当前登录用户(operator_id/employees_id)与任务的 pick_user_id 是否一致;不一致时直接返回 403,不返回任何拣货信息。", - "鉴权配置:noNeedRight=true,noNeedAuth=true,isNeedLogin=true。" - ], - "type": "added" - }, - { - "version": "2026.05.08-system-05", - "date": "2026-05-08", - "summary": "order.wave.batchList:新增 source 字段并支持 where.source 过滤,返回 list item 中新增 source 字段", - "methods": [ - "order.wave.batchList" - ], - "notes": [ - "新增 where.source(可选,number)用于按来源过滤:0=普通波次(正常后台操作),1=管理后台策略任务,2=PDA策略任务;不传则不过滤。", - "响应 list 每条记录新增字段 source(number),用于区分波次来源。", - "仅更新文档,业务代码不在此变更范围。" - ], - "type": "updated" - }, - { - "version": "2026.05.08-system-04", - "date": "2026-05-08", - "summary": "完善 order.wave.wavePickTaskList 文档:补充入参、分页与返回字段兼容说明", - "methods": [ - "order.wave.wavePickTaskList", - "order.wave.wavePickTaskCancel" - ], - "notes": [ - "入参补充:warehouse_id(必填)、status(支持单值或数组,建议传数组)、source、keyword、page_no、page_size;保留 pagination 对象以兼容旧客户端。", - "兼容说明:接口同时支持历史 where 结构与顶层参数;当存在同名顶层参数时以顶层参数优先;pagination 支持 page/current 与 pageSize/size 别名。", - "返回格式:响应包含 total 与 list;list 每项包含字段:task_id、task_no、status、source、pick_mode、wave_count、order_count、box_count、operator_id、operator_name、start_at、finish_at、created_at。为兼容旧客户端,响应同时保留旧字段:pick_user_id、pick_user_name、start_time、finish_time、create_time。", - "入参 strategy_id 当前主表未存,接口会忽略该过滤,不建议使用。", - "默认排序:create_time desc.", - "文档变更:移除 order.wave.wavePickTaskCancel 的入参 operator_id 与 warehouse_id;入参改为仅支持 task_ids(数组,必填),不再兼容单个 task_id;操作人与仓库由请求上下文(例如当前登录用户上下文)自动获取;若上下文缺失接口将返回错误。响应补充批量结果字段:cancelled_count、task_ids、task_nos(若后端返回)。仅更新文档,未修改业务实现。" - ], - "type": "updated" - }, - { - "version": "2026.05.08-system-03", - "date": "2026-05-08", - "summary": "升级按策略抓取接口为创建任务主流程:order.wave.waveStrategyFetchPda / order.wave.waveStrategyFetchAdmin", - "methods": [ - "order.wave.waveStrategyFetchPda", - "order.wave.waveStrategyFetchAdmin" - ], - "notes": [ - "将 PDA/Admin 场景的按策略抓取接口由受理壳方法升级为 '创建任务主流程':接口会执行参数校验并在同步响应中创建任务记录(state=created),返回 task_id、task_no、plan 与 plan_summary 供前端展示与后续查询。", - "入参新增/扩展与创建流程相关字段:至少包含 cart_id(关联拣货车/作业车ID)、source(操作来源语义)并保留并透传 strategy_id 与 strategy_params(策略参数),以支持在创建阶段对策略进行局部覆盖或透传。", - "成功返回示例字段:state=created、task_id、task_no、plan(对象)和 plan_summary(字符串);失败场景会返回 validation_errors(数组,每项含 field/message)或 message 描述创建失败原因。", - "边界说明:当前为最小主流程(创建与计划预览),后续扫描/任务执行阶段(如实际抓取订单、写入 wave 等)将在后续版本中追加与完善。" - ], - "type": "updated" - }, - { - "version": "2026.05.08-system-02", - "date": "2026-05-08", - "summary": "调整按策略抓取壳方法:order.wave.waveStrategyFetch 更名为 order.wave.waveStrategyFetchPda,并新增 order.wave.waveStrategyFetchAdmin", - "methods": [ - "order.wave.waveStrategyFetch", - "order.wave.waveStrategyFetchPda", - "order.wave.waveStrategyFetchAdmin" - ], - "notes": [ - "waveStrategyFetchPda 仅用于 PDA 场景", - "waveStrategyFetchAdmin 仅用于后台管理场景", - "两者当前均为壳子受理方法,不执行真实抓取" - ], - "type": "updated" - }, - { - "version": "2026.05.08-system-01", - "date": "2026-05-08", - "summary": "新增 order.wave.waveStrategyFetch:按策略提交抓取任务(壳子方法)", - "methods": [ - "order.wave.waveStrategyFetch" - ], - "notes": [ - "当前方法为壳子方法:仅受理并返回任务受理信息,不执行真实抓取逻辑,后续补齐执行链路。" - ], - "type": "added" - }, - { - "version": "2026.05.07-system-05", - "date": "2026-05-07", - "summary": "新增 order.wave.waveStrategyCreate 与 order.wave.waveStrategyUpdate:波次策略创建与更新接口(含参数校验与版本推进)", - "methods": [ - "order.wave.waveStrategyCreate", - "order.wave.waveStrategyUpdate" - ], - "notes": [ - "仓库 ID 与创建人(creator_name)由当前登录仓库/操作者上下文获取,接口不接受外部覆盖。", - "入参 allowed_owners 与 allowed_expresses 会校验是否在系统可用范围内(基于仓库签约货主或系统快递列表),若存在非法值接口会直接报错(400)。", - "max_same_structure 受仓库配置 min_group_order_fetch_quantity 限制:若传入值 >= min_group_order_fetch_quantity,则自动下调为 min_group_order_fetch_quantity - 1(最小值为 1)。", - "新建/更新成功后会触发仓库的 wave_strategy_version 自增(+1)并失效相关仓库配置缓存,调用方可通过策略版本推进或缓存变化感知策略已生效。" - ], - "type": "added" - }, - { - "version": "2026.05.07-system-06", - "date": "2026-05-07", - "summary": "收敛 order.wave.waveStrategyFallbackOrderList 返回字段,限定 where 白名单,补充 order.wave.singleFetchByIds 别名与返回语义", - "methods": [ - "order.wave.waveStrategyFallbackOrderList", - "order.wave.singleFetchByIds" - ], - "notes": [ - "收敛 order.wave.waveStrategyFallbackOrderList response.list 字段为 id, delivery_no, tracking_no, items_count, items_total, sys_logistics_name, store_name, province, sys_platform_name, item_snapshot;item_snapshot 格式示例:商品名称*数量|...。", - "限制 order.wave.waveStrategyFallbackOrderList.where 白名单,禁止传入 warehouse_id / warehouseId;传入未列出字段或别名冲突将返回 400。", - "补充 order.wave.singleFetchByIds:明确支持 ids / order_ids / orderIds 三个别名(优先顺序 ids -> order_ids -> orderIds)并说明返回字段 fetched_order_ids、excluded_existing_wave_order_ids、skipped_order_ids、not_found_order_ids 的语义与兼容性。" - ], - "type": "updated" - }, - { - "version": "2026.05.07-system-04", - "date": "2026-05-07", - "summary": "更新 order.wave.waveStrategyFallbackOrderList,新增商品快照字段 item_snapshot", - "methods": [ - "order.wave.waveStrategyFallbackOrderList" - ], - "notes": [ - "item_snapshot 返回格式为 商品名称1*数量|商品名称2*数量" - ], - "type": "updated" - }, - { - "version": "2026.05.07-system-03", - "date": "2026-05-07", - "summary": "新增 order.wave.waveStrategyQuickScan 与进度查询接口", - "methods": [ - "order.wave.waveStrategyQuickScan", - "order.wave.waveStrategyQuickScanTaskProgress" - ], - "notes": [ - "同仓只允许一个扫描任务并使用缓存锁;扫描范围为当前表非待审核、未分配波次且订单策略版本与仓库当前版本不一致的订单;命中策略标记 wave_scan_result=1,否则=2" - ], - "type": "added" - }, - { - "version": "2026.05.07-system-02", - "date": "2026-05-07", - "summary": "新增 order.wave.waveStrategyList:查询当前仓库波次策略列表", - "methods": [ - "order.wave.waveStrategyList" - ], - "notes": [ - "从 wms_wave_strategy 拉取当前仓库的波次策略列表,分页返回" - ], - "type": "added" - }, - { - "version": "2026.05.07-system-01", - "date": "2026-05-07", - "summary": "移除 order.wave.singleOrderFetchDetailList,新增 order.wave.waveStrategyFallbackOrderList(内置固定筛选条件)", - "methods": [ - "order.wave.singleOrderFetchDetailList", - "order.wave.waveStrategyFallbackOrderList" - ], - "notes": [ - "移除 order.wave.singleOrderFetchDetailList。", - "新增 order.wave.waveStrategyFallbackOrderList。", - "新接口基于订单通用查询口径,固定内置筛选条件:step != 0、wave_id = 0、wave_scan_result = 2。" - ], - "type": "updated" - }, - { - "version": "2026.05.06-system-06", - "date": "2026-05-06", - "summary": "新增 order.wave.singleOrderFetchDetailList:订单级散单候选明细视图", - "methods": [ - "order.wave.singleOrderFetchDetailList" - ], - "notes": [ - "新增 order.wave.singleOrderFetchDetailList:提供订单级的散单候选明细列表,返回按订单聚合的明细(非分组级)。", - "返回订单级而非分组级;响应每项包含订单 id、group_count、item_detail_machine、item_detail_machine_snapshot、item_detail、item_snapshot、logistics_name、store_id、distinguish_express、create_at 与 status_summary 等关键字段。", - "仍沿用 same_order_quantity 阈值来排除团购命中分组(仅保留 group_count < same_order_quantity 的候选项)。", - "singleOrderFetchList 暂保留以兼容现有前端,前端可在切换到订单级视图后迁移到本接口。" - ], - "type": "added" - }, - { - "version": "2026.05.06-system-05", - "date": "2026-05-06", - "summary": "storage.receiving.get 返回扩展:data.details[*] 新增 box_remainder、box_weight", - "methods": [ - "storage.receiving.get" - ], - "notes": [ - "storage.receiving.get 的响应在 data.details[*] 中新增可选字段:box_remainder(箱内剩余数量/零散数量,number,默认 0)与 box_weight(实测箱重,number,默认 0)。", - "兼容性:新增字段为可选,旧客户端无需修改;建议前端在需要展示箱内余量/箱重时使用这些字段。" - ], - "type": "updated" - }, - { - "version": "2026.05.06-system-04", - "date": "2026-05-06", - "summary": "storage.receiving.getReceivingDetail 返回扩展:明细增加 box_remainder、box_weight;storage.receiving.completeReceiving 通知包含这两个字段", - "methods": [ - "storage.receiving.getReceivingDetail", - "storage.receiving.completeReceiving" - ], - "notes": [ - "为支持箱规统计与通知回传,getReceivingDetail 的明细项(receiving.details 或 data.details)在响应中新增可选字段:box_remainder(箱内剩余数量/零散数量,number)与 box_weight(实测箱重,number,单位同系统重量)。", - "completeReceiving 在完成收货后会发送通知(或回调),通知 payload/metadata 中将包含每条明细的 box_remainder 与 box_weight 字段,供下游系统/前端展示或审计使用。", - "兼容性:新增字段为可选,旧客户端在未使用这些字段时无需变更。" - ], - "type": "updated" - }, - { - "version": "2026.05.06-system-03", - "date": "2026-05-06", - "summary": "storage.receiving.detailChange:新增入参/出参字段 box_remainder、box_weight", - "methods": [ - "storage.receiving.detailChange" - ], - "notes": [ - "为支持箱规细化与回写,detailChange 新增可选入参 box_remainder(箱内余量/零散数量)和 box_weight(实测箱重,单位同系统重量),写入后会回写至明细并在响应 data 中返回对应字段。", - "兼容性:新增字段为可选,不传入则不影响现有调用;建议前端在需要回写箱余与箱重时一并传入。" - ], - "type": "updated" - }, - { - "version": "2026.05.06-system-02", - "date": "2026-05-06", - "summary": "新增 order.wave.singleFetchByIds:按订单ID抓取到一个散单波次", - "methods": [ - "order.wave.singleFetchByIds" - ], - "notes": [ - "新增 order.wave.singleFetchByIds:按入参 ids(兼容 order_ids/orderIds)去重后筛选当前仓库内待处理且不在波次中的订单,若存在可抓取订单则创建单个散单波次并把这些订单写入该波次(不区分快递);成功后批量写入订单操作日志;若无可抓取订单返回 wave_id=0。", - "接口行为严格对齐实现:过滤条件包含 step in [1,2,3]、status != 'cancel'、outbound_status != 'padding';已在波次的订单会被排除并返回 excluded_existing_wave_order_ids;响应包含 ids、wave_id、wave_no、fetched_order_ids、fetched_order_count、excluded_existing_wave_order_ids、skipped_order_ids、not_found_order_ids。" - ], - "type": "added" - }, - { - "version": "2026.05.06-system-01", - "date": "2026-05-06", - "summary": "新增 order.wave.groupFetch 与 order.wave.singleFetch;order.wave.fetch 保留兼容别名;抓取进度补充上限字段", - "methods": [ - "order.wave.groupFetch", - "order.wave.singleFetch", - "order.wave.fetch", - "order.wave.fetchTaskProgress" - ], - "notes": [ - "新增 order.wave.groupFetch:抓取团购接口(异步任务提交),参数 structure_list 与原 fetch 一致。", - "新增 order.wave.singleFetch:抓取散单接口(异步任务提交),在 structure_list 每项新增必填字段 max_fetch_quantity(最大抓取上限,订单数,正整数)。", - "order.wave.fetch 保留为兼容别名(等同 groupFetch),避免误导客户端。", - "groupFetch/singleFetch/fetch 的响应新增可选字段 fetch_mode;singleFetch 响应额外返回 max_fetch_quantity。", - "order.wave.fetchTaskProgress 的响应增加单模式相关字段:fetch_mode、max_fetch_quantity、limit_reached、stop_reason,用于描述散单抓取的上限与停止原因。" - ], - "type": "updated" - }, - { - "version": "2026.05.05-system-02", - "date": "2026-05-05", - "summary": "order.wave.batchList:新增 where.storage_assignment_status 的过滤语义说明", - "methods": [ - "order.wave.batchList" - ], - "notes": [ - "新增 where 字段 `storage_assignment_status`:类型 string,可选值:`未分配`、`部分分配`、`已分配`;默认不传:不做分配状态限制。", - "过滤语义:`已分配`:聚合后全部 fin;`部分分配`:不含 error,且既不是全 none,也不是全 fin;`未分配`:全 none 或包含 error(异常并入未分配筛选集合)。", - "说明:返回字段 `storage_assignment_status` 的展示值保持不变;包含 error 时仍可能展示“分配异常”,但 where 的过滤语义把异常算到“未分配”集合,避免把过滤语义与展示值混淆。" - ], - "type": "updated" - }, - { - "version": "2026.05.05-system-01", - "date": "2026-05-05", - "summary": "新增 order.wave.singleOrderFetchList:散单候选分组查询(排除团购命中分组)", - "methods": [ - "order.wave.singleOrderFetchList" - ], - "notes": [ - "新增 order.wave.singleOrderFetchList:返回按机器结构分组的散单候选列表,接口会排除已达团购阈值(同组订单数量 >= same_order_quantity 或仓库配置 min_group_order_fetch_quantity)的分组,仅返回同组订单数量 < 阈值 的分组(散单候选)。", - "与 order.wave.groupOrderFetchList 的关键差异:groupOrderFetchList 返回满足团购阈值(>=)的分组;singleOrderFetchList 返回未达阈值(<)的散单候选分组。", - "影响范围:订单波次抓取相关前端/调度服务。兼容性:不影响或修改现有 order.wave.groupOrderFetchList,两个接口可并行使用。" - ], - "type": "added" - }, - { - "version": "2026.05.04-system-04", - "date": "2026-05-04", - "summary": "完善商品编码唯一性校验接口文档,补充 item_id(排除自身)和 owner_id(货主ID)入参说明,新增 unique/isUnique 返回字段描述", - "methods": [ - "stock.warehouse.checkItemCodeUnique" - ], - "notes": [ - "完善商品编码唯一性校验接口文档,补充 item_id(排除自身)和 owner_id(货主ID)入参说明,新增 unique/isUnique 返回字段描述" - ], - "type": "modified" - }, - { - "version": "2026.05.04-system-03", - "date": "2026-05-04", - "summary": "新增订单打印模块:按波次IDs获取打印数据并自动过滤未完全分配波次", - "methods": [ - "order.print.getWavePrintData" - ], - "notes": [ - "按波次IDs获取订单打印数据,内部去重并规范化 wave_ids,自动过滤快递未完全分配的波次;返回通过过滤的波次订单明细,按 wave_no 排序分组,并在 ext 中返回 missing_wave_ids 与 filtered_wave_ids。" - ], - "type": "added" - }, - { - "version": "2026.05.04-system-02", - "date": "2026-05-04", - "summary": "修改 pick.query 入参:order_id -> waybill_code", - "methods": [ - "pick.query" - ], - "notes": [ - "入参从 order_id 改为 waybill_code(快递号),通过快递号查找订单后再查波次拣货信息" - ], - "type": "breaking_change" - }, - { - "version": "2026.05.04-system-01", - "date": "2026-05-04", - "summary": "新增 system method pick.query:按订单查询波次拣货信息", - "methods": [ - "pick.query" - ], - "notes": [ - "按订单查询该订单所属波次的拣货信息,支持 full/full_display/is_full 控制是否完整显示;接口按当前登录用户仓库上下文过滤,防止跨仓越界。" - ], - "type": "added" - }, - { - "version": "2026.05.03-system-09", - "date": "2026-05-03", - "summary": "新增按 request_id 查询分配状态/结果接口", - "methods": [ - "order.pendingOrder.allocateStorageProgress" - ], - "notes": [ - "新增按 request_id 查询储位分配异步任务状态/结果接口,支持 status:submitted/running/success/failed/not_found;success 返回 result(底层分配结果),failed 返回 error(错误信息);兼容 requestId 参数名。" - ], - "type": "updated" - }, - { - "version": "2026.05.03-system-07", - "date": "2026-05-03", - "summary": "新增抓取进度查询接口", - "methods": [ - "order.wave.fetch", - "order.wave.fetchTaskProgress" - ], - "notes": [ - "新增按 task_id 查询抓取任务进度的接口 order.wave.fetchTaskProgress,支持返回 status(submitted/running/success/failed/not_found)及进度相关字段:progress_percent、finished_structure_count、total_fetched_quantity、duration_ms、error、update_time 等;同时明确 order.wave.fetch 为异步任务提交接口,客户端可通过 task_id 调用 order.wave.fetchTaskProgress 查询进度和最终结果。" - ], - "type": "updated" - }, - { - "version": "2026.05.03-system-05", - "date": "2026-05-03", - "summary": "补齐仓库设置模块 setting.warehouse 的 methods 文档", - "methods": [ - "setting.warehouse.getSettings", - "setting.warehouse.getFieldMeta", - "setting.warehouse.saveSettings" - ], - "notes": [ - "补齐仓库配置 methods API 文档" - ], - "type": "updated" - }, - { - "version": "2026.05.03-system-04", - "date": "2026-05-03", - "summary": "order.wave:自动加团新增跳过规则并新增批量结束自动加团接口", - "methods": [ - "order.wave.batchAutoGrouping", - "order.wave.batchFinishAutoGrouping" - ], - "notes": [ - "开启自动加团新增“已打印/超最大波次容量”跳过规则并在响应中返回跳过明细;新增批量结束自动加团接口(将 wave_status=0 的波次批量置为 1)" - ], - "type": "updated" - }, - { - "version": "2026.05.03-system-03", - "date": "2026-05-03", - "summary": "裁剪 order_list 以轻量化返回", - "methods": [ - "order.wave.batchList" - ], - "notes": [ - "移除响应中的 order_list 字段,接口仅返回波次基础信息与状态汇总(order_count / storage_assignment_status / express_assignment_status / print_assignment_status)" - ], - "type": "updated" - }, - { - "version": "2026.05.03-system-02", - "date": "2026-05-03", - "summary": "新增 order.wave.batchAutoGrouping:批量改为自动加团中", - "methods": [ - "order.wave.batchAutoGrouping" - ], - "notes": [ - "新增批量改为自动加团中接口及返回字段" - ], - "type": "updated" - }, - { - "version": "2026.04.22-system-02", - "date": "2026-04-22", - "summary": "新增 order.pendingOrder.syncOrderIds:待处理订单同步透传入口", - "methods": [ - "order.pendingOrder.syncOrderIds" - ], - "notes": [ - "新增 order.pendingOrder.syncOrderIds:仅接收 order_ids 并转发到服务层,当前不做业务处理。", - "接口保留登录态校验,入参仅接受订单 ID 相关字段,响应以服务层返回值为准。", - "该方法用于预留同步链路,后续补齐业务逻辑时再扩展服务层实现。" - ], - "type": "updated" - }, - { - "version": "2026.04.22-system-01", - "date": "2026-04-22", - "summary": "补全订单工作台各模块 detail 方法文档", - "methods": [ - "order.detail", - "order.pendingOrder.detail", - "order.reviewOrder.detail", - "order.expectionOrder.detail", - "order.outboundOrder.detail", - "order.deliveryOrder.detail", - "order.deliveryExpectionOrder.detail", - "order.entrustOrder.detail", - "order.archiveOrder.detail" - ], - "notes": [ - "补全文档:detail 为订单工作台通用详情方法,入参支持 ids/id/order_id/orderId;可选 tableType/tablePosition/type/moduleName,支持 current/history/dispatch/outsourced/order/revieworder/pendingorder 等。", - "返回包含 order/detail(订单头)、orderItems/items(商品明细)、expresses(运单信息)、waybill_codes(去重运单号数组)。" - ], - "type": "updated" - }, - { - "version": "2026.04.19-system-01", - "date": "2026-04-19", - "summary": "新增方法 setting.expressInterface.listByWarehousePlatformCode:按 warehouse_id + platform_code 查询全字段列表并支持缓存", - "methods": [ - "setting.expressInterface.listByWarehousePlatformCode" - ], - "notes": [ - "新增 setting.expressInterface.listByWarehousePlatformCode:按 warehouse_id + platform_code 返回快递接口的全字段数组(不分页),每条记录包含 express 关联对象(id/code/name/platform 等)。", - "支持缓存,缓存键由 warehouse_id + platform_code 组成;缓存命中将直接返回缓存结果以提升查询性能。", - "在创建/更新/删除操作(setting.expressInterface.create/update/delete)后,会主动清理对应 warehouse_id + platform_code 的缓存以确保数据一致性。" - ], - "type": "added" - }, - { - "version": "2026.04.17-system-08", - "date": "2026-04-17", - "summary": "新增快递编码管理模块批量软删除接口 setting.express.delete", - "methods": [ - "setting.express.delete" - ], - "notes": [ - "新增批量软删除接口 setting.express.delete:接受 ids(数组、逗号字符串或单值),对属于当前仓库且未被删除的记录执行软删除(设置 deleted_at),并清理 express 列表缓存。", - "当任一目标记录的 code 被 wms_express_interface.express_code 引用时,接口会拒绝删除并返回 409,错误信息中包含被引用的编码列表。", - "响应包含 ids、deleted_ids、already_deleted_ids 与 status,已删除与未删除的 id 会明确分类。仅记录已实现行为。" - ], - "type": "added" - }, - { - "version": "2026.04.17-system-05", - "date": "2026-04-17", - "summary": "新增文档分组:平台编码管理模块(收口 index.getPlatformList 与 setting.platform.*)", - "methods": [ - "index.getPlatformList", - "setting.platform.list", - "setting.platform.create", - "setting.platform.update", - "setting.platform.delete" - ], - "notes": [ - "新增独立文档分组 '平台编码管理模块',将平台基础列表(index.getPlatformList)与平台设置管理接口(setting.platform.*)归并为单一分组以便维护;仅文档变更,不修改实现。", - "文档中仅包含已实现的方法与字段,未新增或推断不存在的参数/返回字段。" - ], - "type": "added" - }, - { - "version": "2026.04.17-system-04", - "date": "2026-04-17", - "summary": "新增独立平台设置模块 setting.platform(wms_platfrom_setting)及其 CRUD 接口:list/create/update/delete。", - "methods": [ - "setting.platform.list", - "setting.platform.create", - "setting.platform.update", - "setting.platform.delete" - ], - "notes": [ - "新增独立模块 setting.platform,映射数据表 wms_platfrom_setting;list 支持 where(id/code/name/platform_code/quickWhere)与 pagination(兼容 page/pageSize/page_size);create/update 要求 platform_code 必须存在于系统平台表(wms_platform),且禁止越权写入 warehouse_id;delete 需传入 id 并校验当前仓库范围。" - ], - "type": "added" - }, - { - "version": "2026.04.15-system-07", - "date": "2026-04-15", - "summary": "将 docs/order-workbench-list-api.md 引用统一为 window 链接格式", - "methods": [ - "order.list", - "order.reviewOrder.list", - "order.pendingOrder.list", - "order.outboundOrder.list", - "order.expectionOrder.list", - "order.entrustOrder.list", - "order.deliveryOrder.list", - "order.deliveryExpectionOrder.list" - ], - "notes": [ - "将所有 methods/system.json 中指向 docs/order-workbench-list-api.md 的说明统一替换为 docs/order-workbench-list-api.md 格式,以便 HTML 渲染识别为 window 链接。", - "仅修改 methods/system.json 的文档字段,不涉及任何业务代码或接口契约变化。" - ], - "type": "updated" - }, - { - "version": "2026.04.15-system-06", - "date": "2026-04-15", - "summary": "订单工作台列表文档补全 raw 字段字典与中文语义说明", - "methods": [ - "order.list", - "order.reviewOrder.list", - "order.pendingOrder.list", - "order.outboundOrder.list", - "order.expectionOrder.list", - "order.entrustOrder.list", - "order.deliveryOrder.list", - "order.deliveryExpectionOrder.list", - "order.archiveOrder.list" - ], - "notes": [ - "在 docs/order-workbench-list-api.md 中补充所有订单列表通用 raw 字段字典,明确每个字段的中文语义与 enum 取值。", - "补充 express_numbers / waybill_codes 两个服务层派生字段说明,便于前端直接渲染多个快递号。", - "methods/system.json 中所有订单 list 的 response.list 描述已指向该字段字典章节。" - ], - "type": "updated" - }, - { - "version": "2026.04.15-system-05", - "date": "2026-04-15", - "summary": "基础模块新增快递/平台列表查询接口并设置为不鉴权,复用缓存 service", - "methods": [ - "index.getExpressList", - "index.getPlatformList" - ], - "notes": [ - "新增 index.getExpressList,归属基础模块(module=index),对应 app/service/systems/express.js 中的 getExpressList。", - "index.getExpressList 设置为不鉴权,不需要 Authorization 头。", - "新增 index.getPlatformList,归属基础模块(module=index),对应 app/service/systems/platform.js 中的 getPlatformList。", - "index.getPlatformList 设置为不鉴权,不需要 Authorization 头。", - "快递列表与平台列表都支持缓存优先,缓存未命中时回源数据库并写入缓存。", - "平台列表支持缓存优先,缓存未命中时回源 wms_platform 并写入缓存。" - ], - "type": "added" - }, - { - "version": "2026.04.15-system-02", - "date": "2026-04-15", - "summary": "签约策略字段元信息新增 default_express_code / default_platform_code list 选项", - "methods": [ - "storeWarehouse.store.getPolicyConfigFields" - ], - "notes": [ - "getPolicyConfigFields 现在返回 default_express_code 与 default_platform_code 两个 list 字段,并从 wms_express / wms_platform 读取选项列表。", - "默认值仍保留为 default_express_code=STO、default_platform_code=TB。" - ], - "type": "updated" - }, - { - "version": "2026.04.15-system-03", - "date": "2026-04-15", - "summary": "签约策略字段移除 sku_visibility,receive_mode options 改为 value/label 结构", - "methods": [ - "storeWarehouse.store.savePolicyConfig", - "storeWarehouse.store.getPolicyConfigFields" - ], - "notes": [ - "策略字段定义不再包含 sku_visibility,历史值读取时仍会被归一化忽略。", - "receive_mode 的 options 改为 [{ value, label }] 格式,便于前端直接渲染。" - ], - "type": "updated" - }, - { - "version": "2026.04.15-system-04", - "date": "2026-04-15", - "summary": "按文件模块拆分 order 目录系统文档分组,覆盖订单工作台入口及各子模块方法", - "methods": [ - "order.list", - "order.manualOutboundOrder", - "order.badgeCount", - "order.outboundOrder.manualOutboundOrder", - "order.reviewOrder.list", - "order.reviewOrder.reviewOrder", - "order.pendingOrder.list", - "order.pendingOrder.reverseReviewOrder", - "order.pendingOrder.markPendingOutboundOrder", - "order.pendingOrder.cancelOrder", - "order.outboundOrder.list", - "order.expectionOrder.list", - "order.entrustOrder.list", - "order.deliveryOrder.list", - "order.deliveryExpectionOrder.list", - "order.archiveOrder.list" - ], - "notes": [ - "按 app/service/systemMethods/order 下的实际对外方法补全 methods/system.json 文档,只覆盖 system,不处理 qimen。", - "order 文档已按 index / reviewOrder / pendingOrder / outboundOrder / expectionOrder / entrustOrder / deliveryOrder / deliveryExpectionOrder / archiveOrder 拆成多个模块分组。", - "同步根据当前代码意图补充 params / response / errors,且不再把 index.js 已移除的兼容接口写回文档。" - ], - "type": "updated" - }, - { - "version": "2026.04.15-system-01", - "date": "2026-04-15", - "summary": "货主主体配置默认补齐 default_express_code / default_platform_code", - "methods": [ - "store.createStore", - "store.createWarehouse" - ], - "notes": [ - "当 subject_config 未传或缺少字段时,自动补齐 default_express_code=STO、default_platform_code=TB,并保留现有的 max_notice_webhook_count 默认值。", - "同步更新 methods/system.json 中 store.createStore 与 store.createWarehouse 的参数说明。" - ], - "type": "updated" - }, - { - "version": "2026.04.14-system-01", - "date": "2026-04-14", - "summary": "库存列表新增货主名称字段 stock.store_name", - "methods": [ - "storage.inventory.list" - ], - "notes": [ - "在 methods/system.json 的 storage.inventory.list response 中补充 stock.store_name:来源于签约表 store_remask,若无签约关系则为 null。", - "只同步文档,不修改业务代码。" - ], - "type": "updated" - }, - { - "version": "2026.04.13-system-01", - "date": "2026-04-13", - "summary": "补全 storage.receiving.detailChange 的入参/出参契约与错误码说明", - "methods": [ - "storage.receiving.detailChange" - ], - "notes": [ - "在 methods/system.json 中补充 storage.receiving.detailChange 的 params/response/errors,明确 id 与 receiving_id 必填。", - "说明 expiry_date 小于当前日期时返回 400 且 message 为 \"到期日期已过期,不能录入收货\"。", - "说明当传入 system_product_id 时会回填条码、重量、箱规、商品名称与 product_snapshot;未传时 barcode/product_name 也可单独更新。", - "同步补充文档:docs/storage-receiving-api.md 中新增 detailChange 段落。" - ], - "type": "updated" - }, - { - "version": "2026.04.07-system-01", - "date": "2026-04-07", - "summary": "修正 warehouse.getAreaRacks 的鉴权/权限链路文档,明确该接口需要 登录并走权限校验。", - "methods": [ - "warehouse.getAreaRacks" - ], - "notes": [ - "对齐当前 system 文档中的 isNeedAuth=true、isNeedLogin=true。", - "用于补充该接口权限链路修正文档的历史上下文,不改变 methods/system.json 的 SSOT 角色。" - ] - }, - { - "version": "2026.04.07-system-02", - "date": "2026-04-07", - "summary": "补充签约配置相关接口文档,覆盖策略字段元信息查询与面单数量人工调整。", - "methods": [ - "storeWarehouse.store.getPolicyConfigFields", - "storeWarehouse.store.adjustPrintQuantity" - ], - "notes": [ - "getPolicyConfigFields 说明为获取签约策略可配置字段元信息列表。", - "adjustPrintQuantity 说明为人工调整签约关系下的面单余额并记录变更日志,并 明确 id、change_quantity、reason 等关键入参。" - ] - }, - { - "version": "2026.04.07-system-03", - "date": "2026-04-07", - "summary": "对外命名从 qimenConfig 收口为 apiConfig,并在接口配置文档中强调 interface_type_id 校验。", - "methods": [ - "storeWarehouse.store.listApiConfig", - "storeWarehouse.store.saveApiConfig", - "storeWarehouse.store.deleteQimenConfig" - ], - "notes": [ - "文档对外统一使用 apiConfig / api_config 命名,减少 qimenConfig 历史别名歧义。", - "saveApiConfig 要求 interface_type_id 为必填且必须指向已存在的 wms_interface_type 记录。", - "listApiConfig / deleteQimenConfig 同步补充 interface_type_id 字段说明。" - ] - }, - { - "version": "2026.04.07-system-04", - "date": "2026-04-07", - "summary": "补充 /api/docs 文档体验增强说明,新增查看变更记录与查看原文 JSON 的入口说明。", - "methods": [ - "/api/docs", - "/api/docs/:docName", - "/api/docs/:docName/raw", - "/api/docs/:docName/changes" - ], - "notes": [ - "sidecar 变更数组用于承载文档历史说明,不替代 methods/system.json 作为 SSOT。", - "原文 JSON 入口继续用于直接查看当前生效文档。" - ] - }, - { - "version": "2026.04.07-system-05", - "date": "2026-04-07", - "summary": "修正 storeWarehouse.store.adjustPrintQuantity 的面单余额调整语义:由增减/累加改为覆盖设置目标余额。", - "methods": [ - "storeWarehouse.store.adjustPrintQuantity" - ], - "notes": [ - "adjustPrintQuantity 当前兼容 print_quantity、target_quantity、change_quantity、adjust_quantity 作为目标面单余额输入,不再按增减量解释。", - "变更日志中的 change_quantity 由 before/after 自动计算差值,以兼容历史审计与展示。" - ] - }, - { - "version": "2026.04.07-system-06", - "date": "2026-04-07", - "summary": "按接口类型分类限制必填字段,OPEN_API 创建时自动生成 self_app_key/self_app_secret", - "methods": [ - "storeWarehouse.store.saveApiConfig" - ], - "notes": [ - "QM_WMS 类型须填写 qimen_app_key/qimen_customer_id/qimen_warehouse_code;OPEN_API 类型三个奇门字段非必填,创建时自动生成 self_app_key(WMS+32位HEX)和 self_app_secret(64位HEX),更新时保留已有密钥。" - ], - "type": "changed" - }, - { - "version": "2026.04.07-system-07", - "date": "2026-04-07", - "summary": "新增接口类型列表查询接口,归属基础模块,无需权限", - "methods": [ - "index.listInterfaceTypes" - ], - "notes": [ - "返回所有已启用的接口类型(wms_interface_type),包含 id、interface_code、interface_name、interface_category、description 字段。设置 isNeedAuth: false, isNeedLogin: true。" - ], - "type": "added" - }, - { - "version": "2026.04.07-system-08", - "date": "2026-04-07", - "summary": "app_name 改为必传参数", - "methods": [ - "storeWarehouse.store.saveApiConfig" - ], - "notes": [ - "app_name 不再有默认值自动生成逻辑,调用方必须传入非空的 app_name,否则返 回 400 错误。" - ], - "type": "changed" - }, - { - "version": "2026.04.07-system-09", - "date": "2026-04-07", - "summary": "新增收货单快捷入库上架接口", - "methods": [ - "storage.inventory.quickPutaway" - ], - "notes": [ - "新建 storage.inventory 库存操作模块。quickPutaway 从收货单直接生成入库单 (SCRK)并写入 wms_storage 库存表,同时更新 wms_stock_warehouse 库存数量(悲观行锁),回填收货明细入库状态。要求收货单已完成且所有明细已匹配系统商品。" - ], - "type": "added" - }, - { - "version": "2026.04.08-system-01", - "date": "2026-04-08", - "summary": "新增收货单与入库单匹配入库接口", - "methods": [ - "storage.inventory.matchPutaway" - ], - "notes": [ - "接收多个收货单和入库单,按商品(stock_warehouse_id)进行数量匹配入库,完 成后根据入库单来源(QM/API)自动触发回传。入参为 receiving_ids(数组)和 entry_order_ids(数组),返回匹配汇总、各收货单入库状态、各入库单状态及回传结果。isNeedAuth=true, isNeedLogin=true, isNeedRight=false。" - ], - "type": "added" - }, - { - "version": "2026.04.08-system-02", - "date": "2026-04-08", - "summary": "saveApiConfig 新增 callback_url 可选参数", - "methods": [ - "storeWarehouse.store.saveApiConfig" - ], - "notes": [ - "新增 callback_url 参数(VARCHAR(500),可选),用于 OPEN_API 类型入库单的 回调地址配置。" - ], - "type": "changed" - }, - { - "version": "2026.04.08-system-03", - "date": "2026-04-08", - "summary": "serializeQimenConfig 新增返回 callback_url 字段,影响 list 和 listApiConfig 两个接口", - "methods": [ - "storeWarehouse.store.list", - "storeWarehouse.store.listApiConfig" - ], - "notes": [ - "serializeQimenConfig() 序列化方法新增 callback_url(string)字段。storeWarehouse.store.list 返回的每条记录 api_config 对象中包含 callback_url;storeWarehouse.store.listApiConfig 返回的 list 数组中每条配置包含 callback_url。" - ], - "type": "changed" - }, - { - "version": "2026.04.08-system-04", - "date": "2026-04-08", - "summary": "新增库存移库(库位转移)接口", - "methods": [ - "storage.inventory.transferLocation" - ], - "notes": [ - "新增 storage.inventory.transferLocation 接口,支持批量多商品多库位移库, 包含部分数量移库与全量移库。入参为 warehouse_id(仓库ID)和 transfers 数组(storage_id、target_space_id、quantity),触发 storage_transfer_completed 通知事件, 每条移库记录独立操作日志。isNeedAuth=true, isNeedLogin=true。" - ], - "type": "added" - }, - { - "version": "2026.04.08-system-05", - "date": "2026-04-08", - "summary": "简化移库接口入参,从批量 transfers 数组改为单条移库", - "methods": [ - "storage.inventory.transferLocation" - ], - "notes": [ - "移除 warehouse_id 和 transfers 数组入参,改为扁平的 storage_id + target_space_id + quantity 三个顶层参数。warehouse_id 从库存记录自动获取,接口从批量移库简化为单商品单库位移库。响应结构同步简化为单条结果对象。" - ], - "type": "modified" - }, - { - "version": "2026.04.08-system-06", - "date": "2026-04-08", - "summary": "新增商品库存明细查询接口", - "methods": [ - "stock.warehouse.getStockDetail" - ], - "notes": [ - "新增 stock.warehouse.getStockDetail 接口,按库位/批次维度查询商品库存分布。入参为 stock_id(必填,商品库存ID)和 pagination(可选,含 page/pageSize)。返回 stockItem(商品概要)、storageList(wms_storage 明细数组,含批次号、库位、数 量、锁定数量、生产日期、过期日期等,关联 location_space 库位信息)、pagination 分页信息。isNeedAuth=false, isNeedLogin=true。底层调用 stockStore.getStockDetail,自动校验商品归属当前仓库。" - ], - "type": "added" - }, - { - "version": "2026.04.08-system-07", - "date": "2026-04-08", - "summary": "新增入参 group_by_batch,支持按批次维度切换库存明细聚合方式", - "methods": [ - "stock.warehouse.getStockDetail" - ], - "notes": [ - "新增可选布尔参数 group_by_batch(默认 false)。false 时按库位合并数量,批次相关字段(batch_no, production_date, expiry_date, inbound_time, inbound_order_no, supplier_batch_no)置 null;true 时保持原逻辑返回每条明细。出参结构不变,但 storageList 中批次字段在合并模式下为 null。" - ], - "type": "modified" - }, - { - "version": "2026.04.08-system-08", - "date": "2026-04-08", - "summary": "新增按商品维度移库接口", - "methods": [ - "storage.inventory.transferByProduct" - ], - "notes": [ - "新增 storage.inventory.transferByProduct 接口,按库位+商品查找所有库存记 录合并移动。入参为 space_id(原库位ID)、stock_id(商品SKU ID,即 wms_stock_warehouse.id)、target_space_id(目标库位ID)、quantity(移库数量)。开启批次管理(is_batch_mgmt=Y)的商品会被拒绝,需使用 transferLocation 按库存记录精确移库。复用 storage_transfer_completed 通知事件,操作日志编码 STORAGE_TRANSFER_BY_PRODUCT。isNeedAuth=true, isNeedLogin=true。" - ], - "type": "added" - }, - { - "version": "2026.04.08-system-09", - "date": "2026-04-08", - "summary": "补充 storeWarehouse.store.list 完整 response 输出字段说明,移除 api_config / apiConfig", - "methods": [ - "storeWarehouse.store.list" - ], - "notes": [ - "从返回结果中移除 api_config 和 apiConfig 字段(代码中 delete serialized.api_config / delete serialized.apiConfig),文档 response 补充完整输出字段列表:id, store_id, store_name, warehouse_id, warehouse_name, counterparty_id, counterparty_name, current_subject_role, auth_status, auth_status_label, apply_reason, review_comment, apply_time, review_time, auth_start, auth_end, actual_end, print_quantity, applied_by, reviewed_by, ended_by, remask, use_status, policy_config, is_auth_valid, remaining_days 以及分页和 current_subject 信息。" - ], - "type": "updated" - }, - { - "version": "2026.04.08-system-10", - "date": "2026-04-08", - "summary": "货主列表返回新增 has_qimen_config 布尔字段", - "methods": [ - "storeWarehouse.store.list" - ], - "notes": [ - "storeWarehouse.store.list 返回的 data.list[] 中新增 has_qimen_config(boolean),表示该货主是否已配置奇门。" - ], - "type": "changed" - }, - { - "version": "2026.04.08-system-11", - "date": "2026-04-08", - "summary": "补全 stock.warehouse.search 接口文档,新增 params / response / errors 完整说明", - "methods": [ - "stock.warehouse.search" - ], - "notes": [ - "入参补充 keyword(string,模糊匹配 item_code / item_name / goods_code / barcode)和 store_id(number,按货主筛选)。响应补充 data 数组各字段(id, item_code, goods_code, item_name, sku_property, stock_unit, quantity, locked_quantity, brand_name, item_type, barcodes, store_stock)以及 total。errors 补充 code=0 搜 索失败场景。" - ], - "type": "updated" - }, - { - "version": "2026.04.08-system-12", - "date": "2026-04-08", - "summary": "新增 with_stock / is_batch 参数,支持返回关联库存明细(按库位分 组或按批次逐条)", - "methods": [ - "stock.warehouse.search" - ], - "notes": [ - "入参新增 with_stock(boolean,默认 false,是否返回关联库存数据)和 is_batch(boolean,默认 false,仅 with_stock=true 时生效,按批次明细返回)。响应 data[] 新增 storage[] 字段:is_batch=false 时按库位分组汇总(含 space_id、space、inventory_type、quantity、locked_quantity、available_quantity);is_batch=true 时逐 条返回批次明细(含 id、stock_id、space_id、batch_no、inventory_type、quantity、locked_quantity、available_quantity、production_date、expiry_date、inbound_time、inbound_order_no、supplier_batch_no、created_at、space)。" - ], - "type": "updated" - }, - { - "version": "2026.04.08-system-13", - "date": "2026-04-08", - "summary": "新增 wms_stock_transaction 表和模型", - "methods": [ - "wms_stock_transaction" - ], - "notes": [ - "新增出入库流水记录表 wms_stock_transaction,含 transaction_type(INBOUND/OUTBOUND)、warehouse_id、store_id、stock_id、storage_id、space_id、quantity、batch_no、inventory_type、order_type、order_no、order_id、receiving_id、entry_order_id、operator_id、operator_name、remark 等字段,关联 StockWarehouse 和 Storage 模型。" - ], - "type": "added" - }, - { - "version": "2026.04.08-system-14", - "date": "2026-04-08", - "summary": "quickPutaway 和 matchPutaway 入库时自动写入出入库记录", - "methods": [ - "storage.inventory.quickPutaway", - "storage.inventory.matchPutaway" - ], - "notes": [ - "入库操作完成后自动写入 wms_stock_transaction 记录。quickPutaway 写入 order_type='SCRK'(收货入库),matchPutaway 写入 order_type='MATCH'(匹配入库),均 自动填充 warehouse_id、store_id、stock_id、storage_id、space_id、quantity、batch_no、inventory_type 等字段。" - ], - "type": "updated" - }, - { - "version": "2026.04.08-system-15", - "date": "2026-04-08", - "summary": "新增 storage.inventory.list 出入库记录列表查询接口", - "methods": [ - "storage.inventory.list" - ], - "notes": [ - "出入库记录列表查询,支持 where 条件(transaction_type、stock_id、space_id、store_id、order_type、order_no、inventory_type、operator_name、created_at)、 分页(pagination)、排序(sort)和 group_by_batch 参数。默认合并模式按库位+商品 聚合返回合计数量与记录条数,group_by_batch=true 时返回每条明细含 batch_no、order_no、operator_name 等完整信息。响应均关联 stockItem(item_code、item_name、sku_property、stock_unit)。" - ], - "type": "added" - }, - { - "version": "2026.04.08-system-16", - "date": "2026-04-08", - "summary": "出入库流水记录查询接口从 storage.inventory.list 改名为 storage.transaction.list", - "methods": [ - "storage.transaction.list" - ], - "notes": [ - "将出入库流水记录查询从 storage.inventory.list 迁移到 storage.transaction.list,避免与库存列表概念混淆。功能和参数不变。isNeedAuth=false, isNeedLogin=true, isNeedRight=false。" - ], - "type": "rename", - "module": "storage" - }, - { - "version": "2026.04.08-system-17", - "date": "2026-04-08", - "summary": "新增 storage.inventory.list 库存列表查询接口", - "methods": [ - "storage.inventory.list" - ], - "notes": [ - "新增库存列表查询接口,查询 wms_storage 表。支持 where 条件(stock_id/space_id/store_id/inventory_type/batch_no/inbound_order_no/available_quantity/inbound_time/created_at)、分页、排序。支持 group_by_batch 参数:默认 false 按库位+商 品合并(SUM quantity/locked_quantity/available_quantity),true 返回每条明细含 batch_no/production_date/expiry_date 等。关联 stockItem(商品信息)和 space(库位信息)。isNeedAuth=false, isNeedLogin=true, isNeedRight=false。" - ], - "type": "add", - "module": "storage" - }, - { - "version": "2026.04.08-system-18", - "date": "2026-04-08", - "summary": "移除 storage.entry.create 创建入库单接口", - "methods": [ - "storage.entry.create" - ], - "notes": [ - "不再允许通过 API 创建入库单。入库单仅由快捷入库(quickPutaway)和匹配入库(matchPutaway)等内部流程自动创建。底层 service 实现保留但不再通过 systemMethods 对外暴露。" - ], - "type": "remove", - "module": "storage" - }, - { - "version": "2026.04.08-system-19", - "date": "2026-04-08", - "summary": "移除 storage.entry.addDetail / deleteDetail / detailChange 对外 接口", - "methods": [ - "storage.entry.addDetail", - "storage.entry.deleteDetail", - "storage.entry.detailChange" - ], - "notes": [ - "入库单明细编辑能力不再通过 systemMethods 对外暴露,入库单模块仅保留 list/get/cancel/completeEntry。" - ], - "type": "remove", - "module": "storage" - }, - { - "version": "2026.04.08-system-20", - "date": "2026-04-08", - "summary": "新增 storage.stockout 出库单模块(非订单出库单能力)", - "methods": [ - "storage.stockout.list", - "storage.stockout.toOrder", - "storage.stockout.listItems" - ], - "notes": [ - "新增 storage.stockout.list / toOrder / listItems 接口,作为非订单出库单的主出口(对应奇门 stockout.create)。storage.delivery.* 仅作为兼容转发保留;底层 部分能力仍复用 order 模块。" - ], - "type": "add", - "module": "storage" - }, - { - "version": "2026.04.08-system-21", - "date": "2026-04-08", - "summary": "将 storage.stockout.toOrder 标记为占位接口", - "methods": [ - "storage.stockout.toOrder" - ], - "notes": [ - "storage.stockout.toOrder 当前仅保留方法名用于后续扩展,暂不开放实际逻辑。调用时返回 code=405、message=占位接口,暂未开放。" - ], - "type": "change" - }, - { - "version": "2026.04.09-system-01", - "date": "2026-04-09", - "summary": "storage.entry.cancel 支持批量作废,新增 ids 入参并兼容单条 id", - "methods": [ - "storage.entry.cancel" - ], - "notes": [ - "新增入参 `ids`(number[])以支持批量作废,兼容旧入参 `id`;当同时传入 `ids` 与 `id` 时以 `ids` 为准。", - "参数校验:`ids` 必须为非空数组;非法 ID 或空数组返回 400。", - "业务约束:已完成/已作废/处于不可作废状态的单据不允许作废;批量场景下任一 单据不存在或状态不允许时整体返回 404/400,未执行部分更新。", - "响应说明:单条作废返回字段 `id`(number);批量作废返回字段 `ids`(number[])。", - "已同步更新 methods/system.json(storage.entry.cancel)为 SSOT。" - ] - }, - { - "version": "2026.04.09-system-02", - "date": "2026-04-09", - "summary": "新增基础模块车牌识别接口 index.recognizeLicensePlate", - "methods": [ - "index.recognizeLicensePlate" - ], - "notes": [ - "入参:base64(string,必填)或 imageBase64/image_base64(兼容)", - "响应:返回归一化后的识别对象,包含 licensePlate、plateNumber、color、confidence、requestId、imageSize、rawData", - "错误:400(参数或图片格式/尺寸问题),500(第三方 OCR 调用失败或云密钥未 配置)", - "文档中不包含任何敏感配置;实际腾讯云密钥保留在配置文件中,勿在文档中暴露 。" - ], - "type": "added" - }, - { - "version": "2026.04.09-system-03", - "date": "2026-04-09", - "summary": "收紧基础模块车牌识别接口响应,仅返回 licensePlate 字段", - "methods": [ - "index.recognizeLicensePlate" - ], - "notes": [ - "出参由 {licensePlate, plateNumber, color, confidence, requestId, imageSize, rawData} 调整为 {licensePlate}", - "调用方请仅依赖 licensePlate 字段以适配新版本;历史字段已裁剪且不再保证存 在。", - "文档中未包含任何云密钥或敏感配置信息。" - ], - "type": "changed" - }, - { - "version": "2026.04.10-system-01", - "date": "2026-04-10", - "summary": "订单审核字段由 audit_status 替换为整数字段 step,并添加数据库迁移", - "methods": [ - "order.getreviewOrderlist", - "order.reviewOrder.getreviewOrderlist", - "order.reviewOrder.reviewOrder", - "order.deliveryOrder.getdeliveryOrderlist", - "order.list", - "order.stats" - ], - "notes": [ - "字段变更:order 相关审核字段从字符串/枚举 audit_status 替换为整数 step。", - "step 映射:0=未审核,1=已审核,2=处理中,3=驳回/异常,4=配送中,5=已完成,9=已关闭。", - "reviewOrder 接口在更新 inspection_status 的同时会写入 step 字段。", - "必须执行迁移脚本:20260410150000-replace-audit-status-with-step-on-order-delivery-tables.js" - ], - "type": "changed" - }, - { - "version": "2026.04.13-system-02", - "date": "2026-04-13", - "summary": "stock.warehouse.search 返回新增效期管理字段并保留 is_shelf_life_mgmt", - "methods": [ - "stock.warehouse.search" - ], - "notes": [ - "响应 data[] 中新增字段:inbound_min_days、outbound_min_days、shelf_life_days、remaining_threshold_days(均为 number,单位:天)。", - "保留并说明 is_shelf_life_mgmt 布尔字段(boolean),表示是否启用效期管理(true=启用)。", - "仅更新文档(methods/system.json 与变更记录),代码行为不变。" - ], - "type": "updated" - }, - { - "version": "2026.04.13-system-02", - "date": "2026-04-13", - "summary": "新增 storage.expiry.list 库存有效期列表查询接口", - "methods": [ - "storage.expiry.list" - ], - "notes": [ - "该接口查询 wms_storage,关联 stockWarehouse 和 locationSpace,并按当前仓库与 remaining_threshold_days / expiry_date 过滤。" - ], - "type": "added" - }, - { - "version": "2026.04.13-system-03", - "date": "2026-04-13", - "summary": "新增 storage.inventory.list 库存列表返回效期字段与预警标记", - "methods": [ - "storage.inventory.list" - ], - "notes": [ - "库存列表响应增加生产日期、过期日期、效期预警是否触发字段", - "预警标记仅在商品启用保质期管理且到期日满足阈值条件时为 true" - ], - "type": "updated" - }, - { - "version": "2026.04.14-system-01", - "date": "2026-04-14", - "summary": "更新 index.searchSpace 文档", - "methods": [ - "index.searchSpace" - ], - "notes": [ - "补充 index.searchSpace 的 params/response,按 ctx.user.store_id 作为仓库上下文;keyword 为可选字符串,对 space_code 与 custom_barcode 做 %keyword% 模糊匹配;返回字段 id、space_code、custom_barcode、custom_name,最多 50 条;仅文档同步,无代码变更。" - ], - "type": "updated" - }, - { - "version": "2026.04.16-system-01", - "date": "2026-04-16", - "summary": "基础模块新增快递产品类型查询接口", - "methods": [ - "index.getExpressProductTypeList" - ], - "notes": [ - "新增 index.getExpressProductTypeList,归属基础模块(module=index),用于查询指定快递公司的产品类型列表。", - "对应服务实现:app/service/systems/express.js 中的 getExpressProductTypeList,支持传入 express_code 作为可选筛选参数(source=body)。", - "接口设置为免鉴权(isNeedAuth=false)但需登录(isNeedLogin=true),与 index.getExpressList / index.getPlatformList 一致,优先从缓存读取。" - ], - "type": "added" - }, - { - "version": "2026.04.17-system-01", - "date": "2026-04-17", - "summary": "新增快递管理模块(setting.express)及 5 个接口文档", - "methods": [ - "setting.express.list", - "setting.express.listBase", - "setting.express.create", - "setting.express.checkCodeUnique", - "setting.express.update" - ], - "notes": [ - "新增独立模块组:快递管理模块(module=setting.express),将快递映射管理相关接口独立为一组以便维护。", - "接口实现参考:app/service/systems/setting/express.js(返回结构)与 app/service/systemMethods/setting/express.js(对外方法包装)。", - "接口鉴权与上下文:isNeedAuth=false, isNeedLogin=true;需在请求中传入 Authorization 以携带登录上下文(用于获取当前仓库/货主上下文)。", - "已同步更新 methods/system.json,补充 params/response/errors,保持文档与实现一致。" - ], - "type": "added" - }, - { - "version": "2026.04.17-system-02", - "date": "2026-04-17", - "summary": "setting.express.list 分页入参统一为 pagination", - "methods": [ - "setting.express.list" - ], - "notes": [ - "将 setting.express.list 的分页入参文档从顶层 page/page_size/pageSize 迁移为 pagination 对象,主形态为 pagination;兼容 snake_case 的 page_size 与 camelCase 的 pageSize。", - "文档与当前实现一致:顶层 page/page_size/pageSize 会被归一化到 data.pagination 并转发到系统服务。" - ], - "type": "updated" - }, - { - "version": "2026.04.17-system-03", - "date": "2026-04-17", - "summary": "新增快递接口管理模块(setting.expressInterface)及 4 个接口文档", - "methods": [ - "setting.expressInterface.list", - "setting.expressInterface.create", - "setting.expressInterface.update", - "setting.expressInterface.delete" - ], - "notes": [ - "新增独立模块组:快递接口管理模块(module=setting.expressInterface),对应实现:app/service/systems/setting/expressInterface.js 与对外包装 app/service/systemMethods/setting/expressInterface.js。", - "接口为当前仓库范围(基于 ctx.user.store_id),仓库边界由系统服务强制校验;禁止通过接口指定 warehouse_id/warehouseId。操作需登录(isNeedLogin=true),无需额外鉴权(isNeedAuth=false)。", - "已在 methods/system.json 新增对应接口的 params/response/errors 文档,保持与实现一致。" - ], - "type": "added" - }, - { - "version": "2026.04.18-system-01", - "date": "2026-04-18", - "summary": "补充订单储位分配接口文档:order.storageAllocation.allocateStorage", - "methods": [ - "order.storageAllocation.allocateStorage" - ], - "notes": [ - "新增 order.storageAllocation.allocateStorage:按订单批量分配储位,支持多种入参别名(order_ids/ids/orderId 等)与仓库上下文优先级。", - "响应包含 requested_order_ids, pending_order_ids, allocated_order_ids, shortage_order_ids, skipped_orders, picking_count, stock_lock_summary, storage_lock_summary 等字段,用于前端展示分配结果与不足提示。" - ], - "type": "added" - }, - { - "version": "2026.04.18-system-02", - "date": "2026-04-18", - "summary": "新增 order.pendingOrder.allocateExpressCode:待处理订单模块的批量分配快递号入口,复用 express.createWaybillCodePipeline。", - "methods": [ - "order.pendingOrder.allocateExpressCode" - ], - "notes": [ - "该接口直接接收订单对象数组入参;订单对象应为来自待处理订单列表或详情的原始订单对象。每个订单对象必须包含 order_id 与 business_key;sys_platform_code、logistics_code 为订单对象自带字段,前端无需额外拼装或单独构造,直接原样回传订单对象即可。", - "实际的运单创建、归一化与跳过逻辑由 express.createWaybillCodePipeline 处理。", - "接口返回值与现有分配链路一致,已用统一 success 包装返回。" - ], - "type": "added" - }, - { - "version": "2026.04.18-system-03", - "date": "2026-04-18", - "summary": "将 order.storageAllocation.allocateStorage 迁移到 order.pendingOrder.allocateStorage,并移除原有公开分组。", - "methods": [ - "order.pendingOrder.allocateStorage" - ], - "notes": [ - "将对外入口从 order.storageAllocation.allocateStorage 迁移到 order.pendingOrder.allocateStorage,旧的 order.storageAllocation 分组已从 methods/system.json 中移除。", - "新的对外接口不接受 warehouse_id / warehouseId,仓库上下文由当前登录用户(ctx.user.store_id)提供。", - "本次变更仅同步文档位置与对外方法名,底层实现保留且通过新的 system 方法暴露。" - ], - "type": "changed" - }, - { - "version": "2026.04.19-system-02", - "date": "2026-04-19", - "summary": "新增待处理模块取消分配储位接口 order.pendingOrder.cancelAllocateStorage", - "methods": [ - "order.pendingOrder.cancelAllocateStorage" - ], - "notes": [ - "新增待处理模块取消分配储位接口 `order.pendingOrder.cancelAllocateStorage`,直接对接 `service.systems.orderStorageAllocation.cancelAllocateStorage` 实现。", - "接口现在仅接受订单ID(order_ids),不再接受 allow_storage_location;禁止传入 `warehouse_id/warehouseId`,仓库上下文由当前登录用户的 `store_id` 提供。", - "响应返回标准 { flag, code, message, data } 结构,data 包含取消分配的汇总结果(warehouse_id, requested_order_ids, cancellable_order_ids, skipped_orders, orders, picking_count, storage_unlock_summary, stock_unlock_summary)。" - ], - "type": "added" - }, - { - "version": "2026.04.21-system-01", - "date": "2026-04-21", - "summary": "新增 order.pendingOrder.updateOrderPlatform 方法:批量修改待处理订单平台信息", - "methods": [ - "order.pendingOrder.updateOrderPlatform" - ], - "notes": [ - "通过 code 查找 wms_platform,平台不存在时返回 404 错误。", - "仅操作当前仓库的当前订单表。", - "noNeedRight=true,noNeedAuth=true(isNeedAuth: true 在 spec 中对应权限配置 noNeedAuth=true)。" - ], - "type": "added" - }, - { - "version": "2026.04.21-system-02", - "date": "2026-04-21", - "summary": "新增方法 order.pendingOrder.updateOrderExpress:批量修改待处理订单的快递信息", - "methods": [ - "order.pendingOrder.updateOrderExpress" - ], - "notes": [ - "新增 order.pendingOrder.updateOrderExpress:批量修改待处理订单的快递信息,按 express_code 从仓库快递列表(带缓存)匹配快递项。", - "自定义映射(is_system_setting=true)时,sys_logistics_code/name 写入系统快递编码和名称,logistics_code/name 写入自定义编码和名称;系统快递(is_system_setting=false)时四个字段均写系统快递的 code/name。", - "只操作当前仓库的当前订单表,不处理其他订单表;操作后写入操作日志(ORDER_UPDATE_EXPRESS)。" - ], - "type": "added" - }, - { - "version": "2026.04.21-system-03", - "date": "2026-04-21", - "summary": "新增 order.expectionOrder.resolveException:将待处理异常订单转回正常待处理状态", - "methods": [ - "order.expectionOrder.resolveException" - ], - "notes": [ - "新增 order.expectionOrder.resolveException:批量将 step=3 的异常订单恢复为 step=2 正常待处理状态。", - "入参 ids 为订单ID 正整数数组,不能为空;仅操作当前仓库当前订单表。", - "返回 updated_count(实际更新行数)与 ids(本次操作ID列表)。", - "权限配置:noNeedLogin=false、noNeedRight=true、noNeedLog=false、noNeedAuth=true" - ], - "type": "added" - }, - { - "version": "2026.04.21-system-04", - "date": "2026-04-21", - "summary": "新增 order.pendingOrder.cloneOrder 方法:克隆待处理订单", - "methods": [ - "order.pendingOrder.cloneOrder" - ], - "notes": [ - "支持对 step 0/1/2/3 的待处理订单进行克隆操作。", - "若原订单已分配储位(storage_status=fin),克隆前自动清除已分配库存。", - "原订单取消后(step→9, status→cancel),以原订单业务数据创建新订单,流程状态字段全部重置为初始落库状态。", - "克隆订单明细含 stock_id,新订单 ID 重新绑定。", - "noNeedAuth=true,noNeedRight=true,noNeedLogin=false。" - ], - "type": "added" - }, - { - "version": "2026.04.21-system-06", - "date": "2026-04-21", - "summary": "新增 order.pendingOrder.createOrder:手动创建待处理/待审核订单", - "methods": [ - "order.pendingOrder.createOrder" - ], - "notes": [ - "新增 order.pendingOrder.createOrder:手动创建订单,step 由货主策略 need_order_approval 决定(1→待审核 step=0,0→待处理 step=1)。", - "必填字段:store_id、name、mobile/tel 至少一项、detail_address、items[](含 item_code 和 plan_qty)。", - "delivery_order_code 不传则自动生成(SYS+时间戳+随机4位);logistics_code/sys_platform_code 不传则读货主合约策略 default_express_code/default_platform_code。", - "不做库存锁定,储位分配为独立步骤。操作日志写入 ORDER_CREATE。", - "noNeedRight=true,noNeedAuth=true,noNeedLogin=false。" - ], - "type": "added" - }, - { - "version": "2026.04.21-system-07", - "date": "2026-04-21", - "summary": "新增 Excel 模板下载与批量导入创建订单接口:order.pendingOrder.downloadCreateTemplate 和 order.pendingOrder.importOrdersFromExcel", - "methods": [ - "order.pendingOrder.downloadCreateTemplate", - "order.pendingOrder.importOrdersFromExcel" - ], - "notes": [ - "新增 order.pendingOrder.downloadCreateTemplate:生成 Excel 导入模板,返回 base64 编码的 xlsx 文件,表头中带 * 的列为必填项(橙色背景),可选列为灰色背景,含示例数据行和填写说明工作表。", - "新增 order.pendingOrder.importOrdersFromExcel:接受 base64 编码的 xlsx 文件,按订单号分组,每组调用 createOrder 逻辑创建订单;不中断执行,逐条记录成功/失败结果返回。", - "多行相同订单号的行组成一个完整订单,每行代表一条商品明细;订单头信息(收件人、地址等)取每组第一行。", - "step 由货主策略 need_order_approval 决定(与 createOrder 一致);通过事务保证每个订单的主记录与明细原子写入。" - ], - "type": "added" - }, - { - "version": "2026.05.01-system-01", - "date": "2026-05-01", - "summary": "新增基础模块 IM 登录码接口文档:index.loginToIm", - "methods": [ - "index.loginToIm" - ], - "notes": [ - "新增 index.loginToIm 文档,入参为空对象({}),依赖当前登录用户上下文生成一次性 code。", - "响应增加 data.code 字段,长度固定 64 位(hex),默认有效期 5 分钟。", - "错误码补充:401(用户未登录)、400(用户信息不完整,缺 employees_id 或 employees_name)。", - "该接口仅做登录码签发,实际换取员工信息由 IM 侧 ssoCodeToId 完成并在成功后使 code 失效。" - ], - "type": "added" - }, - { - "version": "2026.05.01-system-03", - "date": "2026-05-01", - "summary": "扩展 index.loginToIm 返回字段:增加主体/主体类型/头像信息", - "methods": [ - "index.loginToIm" - ], - "notes": [ - "登录码签发接口响应新增 employees_id、employees_name、subject、store_type、avatar 字段。", - "subject 包含 id/name;store_type 严格取自 wms_store.project 字段,不再返回 subject_type 兼容字段。", - "同一批字段会写入 code 缓存,供 IM 侧 ssoCodeToId 换取并在成功后失效。" - ], - "type": "updated" - }, - { - "version": "2026.05.01-system-04", - "date": "2026-05-01", - "summary": "index.loginToIm 与 ssoCodeToId 改为严格字段模式,不再做兼容回退", - "methods": [ - "index.loginToIm" - ], - "notes": [ - "loginToIm 仅读取 ctx.user 标准字段:employees_id、employees_name、store_id、store_name、store_type、avatar。", - "不再兼容 id/real_name/username/company_name/avatar_url 等历史字段。", - "ssoCodeToId 返回值不再使用默认兜底,缺少关键字段时按 code 无效处理。" - ], - "type": "updated" - }, - { - "version": "2026.05.03-system-01", - "date": "2026-05-03", - "summary": "将 order.wave.fetch 调整为异步任务提交接口,删除同步返回抓取结果字段", - "methods": [ - "order.wave.fetch" - ], - "notes": [ - "接口从同步返回抓取结果改为提交任务并异步处理。", - "移除原方法中 result_list / total_request_quantity / total_fetched_quantity 等同步返回字段。" - ], - "type": "updated" - }, - { - "version": "2026.05.03-system-06", - "date": "2026-05-03", - "summary": "order.wave.batchList:新增 where 支持并限制传入字段", - "methods": [ - "order.wave.batchList" - ], - "notes": [ - "batchList 新增 where 支持及白名单过滤;禁止传入 warehouse_id/warehouseId。" - ], - "type": "updated" - }, - { - "version": "2026.05.03-system-08", - "date": "2026-05-03", - "summary": "order.pendingOrder.allocateStorage 改为异步提交", - "methods": [ - "order.pendingOrder.allocateStorage" - ], - "notes": [ - "接口变更为异步提交:调用后立即返回 request_id,后端异步执行储位分配;接口不再在响应中同步返回分配明细(如 requested_order_ids、allocated_order_ids 等)。客户端可后续通过任务 ID / 查询链路或事件获取最终分配结果。" - ], - "type": "updated" - }, - { - "version": "2026.05.03-system-10", - "date": "2026-05-03", - "summary": "新增订单批量移出波次接口", - "methods": [ - "order.wave.batchRemoveOrders" - ], - "notes": [ - "按订单ID批量移出波次;仅处理待处理订单表中非待审核订单(step in [1,2,3])。", - "操作在单事务内完成:清空订单的 wave_id/wave_no,并回写 wms_wave_batch 统计(重算 total_orders;当波次被清空时将 wave_status 置为 -1)。", - "仓库上下文来自当前登录用户(ctx.user.store_id)。" - ], - "type": "updated" - }, - { - "version": "2026.05.08-system-05", - "date": "2026-05-08", - "summary": "order.wave.batchList:新增 source 字段并支持 where.source 过滤,返回 list item 中新增 source 字段", - "methods": [ - "order.wave.batchList" - ], - "notes": [ - "新增 where.source(可选,number)用于按来源过滤:0=普通波次(正常后台操作),1=管理后台策略任务,2=PDA策略任务;不传则不过滤。", - "响应 list 每条记录新增字段 source(number),用于区分波次来源。", - "仅更新文档,业务代码不在此变更范围。" - ], - "type": "updated" - }, - { - "version": "2026.05.09-system-01", - "date": "2026-05-09", - "summary": "新增 order.wave.wavePickTaskCancelSelf;order.wave.waveStrategyList 新增预演计数字段/参数", - "methods": [ - "order.wave.wavePickTaskCancelSelf", - "order.wave.waveStrategyList" - ], - "notes": [ - "新增接口 `order.wave.wavePickTaskCancelSelf`:仅支持单个 `task_id`(number,必填),明确不支持 `task_ids` 批量参数。", - "业务约束:仅允许取消当前登录用户本人创建的拣货任务;若尝试取消非本人创建任务,接口应返回 400 错误(仅允许取消本人创建任务)。", - "返回建议:与现有取消接口风格一致,包含 `cancelled_count`(0/1)、`task_id`、`task_no`(若后端返回)或相应的取消结果汇总。", - "错误码建议:400 参数不合法(task_id 缺失或传了 task_ids);400 仅允许取消本人创建任务;500 取消失败。", - "新增参数:calculate_next_fetch_order_count(number,可选),含别名 calculateNextFetchOrderCount;取值 0=不计算(默认),1=计算并返回每条策略的 next_fetch_order_count,用于前端在策略列表中预览抓取量。", - "新增响应字段:list[*].next_fetch_order_count(number),含义:按当前策略口径预演一次自动抓取时,预计会选中的订单数量;当未开启计算时返回 0。" - ], - "type": "added" - }, - { - "version": "2026.05.11-system-01", - "date": "2026-05-11", - "summary": "新增字段 wave_prefix(策略层波次前缀),并补充 PDA 抓取波次号生成行为说明", - "methods": [ - "order.wave.waveStrategyList", - "order.wave.waveStrategyCreate", - "order.wave.waveStrategyUpdate", - "order.wave.waveStrategyFetchPda" - ], - "notes": [ - "在 wave strategy 对象中新增可选字段 wave_prefix:策略波次前缀,优先于仓库前缀。", - "校验规则:长度 1-5,仅允许 A-Z0-9;保存时会转为大写;为空时回退仓库前缀:团购使用 group_wave_prefix,散单使用 delete_order_wave_prefix。", - "在 order.wave.waveStrategyList 的返回 list[*] 中新增字段 wave_prefix(string)。", - "在 order.wave.waveStrategyCreate / waveStrategyUpdate 的入参中新增可选字段 wave_prefix(string),创建/更新成功后保存为大写且触发策略版本推进。", - "在 order.wave.waveStrategyFetchPda 的行为说明中补充:生成波次号(wave_no)时优先使用策略层 wave_prefix,否则按策略类型回退到仓库前缀;前缀校验同上。" - ], - "type": "updated" - } + { + "version": "2026.05.12-system-01", + "date": "2026-05-12", + "summary": "调整订单打印中间态返回结构为 waveGroups(波次 -> 平台 -> 订单)", + "methods": [ + "order.print.getWavePlatformPrintData" + ], + "notes": [ + "主要变更:将方法的主返回结构改为 waveGroups,按波次分组,波次内按平台分组,平台内为订单列表(波次 -> 平台 -> 订单)。", + "兼容性:保留旧字段 platform_groups 与 order_list 作为向后兼容字段,但文档主结构与推荐使用为 waveGroups。", + "返回结构说明:summary(total_waves/total_orders/total_platforms)、wave_ids(通过过滤的波次ID数组)、waveGroups(数组,项含 wave_id、wave_no、order_count、platforms[...],platforms项含 platform、platform_name、order_count、orders[...])、ext(missing_wave_ids、filtered_wave_ids)。", + "errors:保留 400 / 500 不变。" + ], + "type": "modified" + }, + { + "version": "2026.05.11-system-05", + "date": "2026-05-11", + "summary": "order.wave.batchList:支持 express/print 分配状态筛选,入参改为英文枚举(express/print)", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "修复 where.express_assignment_status 可按快递分配状态筛选。", + "新增 where.print_assignment_status 筛选(按打印分配聚合判断)。", + "express_assignment_status / print_assignment_status 要求使用英文枚举值:express=unassigned/partially_assigned/assigned,print=unprinted/partially_printed/printed;storage_assignment_status 继续兼容中文枚举(未分配/部分分配/已分配)。", + "若传入非法枚举值,接口返回 400(参数校验失败),message 中会说明允许取值。" + ], + "type": "updated" + }, + { + "version": "2026.05.11-system-04", + "date": "2026-05-11", + "summary": "调整 order.wave.waveStrategyFetchAdmin:由创建任务改为直接创建波次(不创建拣货任务)", + "methods": [ + "order.wave.waveStrategyFetchAdmin" + ], + "notes": [ + "接口行为变更:按策略直接抓取命中订单并创建波次,不再创建拣货任务(不返回 task_id/task_no 等任务字段)。", + "响应调整为建波结果:fetch_state(1=成功/2=失败)、wave_ids、wave_nos、created_wave_count、created_order_count、order_ids、(可选)wave_prefix、wave_prefix_source、tip/message。", + "错误调整:策略校验失败返回 400(并可能返回 validation_errors),缺少仓库上下文返回 400,建波失败返回 500 并在 message 中说明。" + ], + "type": "updated" + }, + { + "version": "2026.05.11-system-03", + "date": "2026-05-11", + "summary": "更新 pick.query:由查询拣货明细调整为按 keyword 获取/创建拣货任务", + "methods": [ + "pick.query" + ], + "notes": [ + "入参由 waybill_code/full_display 调整为 keyword(支持运单号或波次号)。", + "接口语义调整为任务化返回:命中活动任务则返回 existing 任务ID;无活动任务则创建并返回 created 任务ID。", + "新增任务归属冲突错误:当活动任务创建人非当前用户时返回冲突提示,并附带创建人及任务ID信息。" + ], + "type": "updated" + }, + { + "version": "2026.05.11-system-02", + "date": "2026-05-11", + "summary": "新增 pick.wavePickTaskCurrent:PDA 无参查询当前进行中拣货任务", + "methods": [ + "pick.wavePickTaskCurrent" + ], + "notes": [ + "新增 PDA 专用无参接口 pick.wavePickTaskCurrent。", + "按当前登录用户上下文(pick_user_id + warehouse_id)查询状态在 0/1/2 的最新任务。", + "命中返回 task_id,未命中返回 task_id=null。" + ], + "type": "added" + }, + { + "version": "2026.05.10-system-04", + "date": "2026-05-10", + "summary": "pick.wavePickTaskDetail 新增按任务类型区分的 picking_view 形态输出", + "methods": [ + "pick.wavePickTaskDetail" + ], + "notes": [ + "新增响应字段:picking_view(object),按 task.pick_mode 区分 5 种形态输出。", + "picking_view 字段说明:mode_code, mode_name, require_box_allocations, group_by, sort_by, items[](每项含 space_id、space_name、location_space、item_code、item_name、stock_id、total_qty、box_allocations[])。", + "当 pick_mode=1/3/4 时 require_box_allocations=true;当 pick_mode=2/5 时 require_box_allocations=false。" + ], + "type": "updated" + }, + { + "version": "2026.05.10-system-02", + "date": "2026-05-10", + "summary": "order.wave.waveStrategyFetchPda/Admin 返回新增 fetch_state 三态与简短 tip", + "methods": [ + "order.wave.waveStrategyFetchPda", + "order.wave.waveStrategyFetchAdmin" + ], + "notes": [ + "新增返回字段:fetch_state(number)、tip(string)、can_enter_pick_flow(boolean)", + "fetch_state 含义:1=创建成功(返回 task_id/task_no),2=普通失败(task_id=null),3=存在未完成任务(返回 existing task_id/task_no,前端可直接进入拣货流程)", + "当 fetch_state=3 时,字段 can_enter_pick_flow=true,表示前端可直接进入拣货流程;tip 为简短提示文本" + ], + "type": "updated" + }, + { + "version": "2026.05.10-system-03", + "date": "2026-05-10", + "summary": "裁剪 pick.wavePickTaskDetail 返回:移除 waves/orders,精简 task 并补充 boxes 拣货统计字段", + "methods": [ + "pick.wavePickTaskDetail" + ], + "notes": [ + "移除响应中的 waves 与 orders 子表,接口仅返回精简的 task、boxes、picking_details 与 picking_summary。", + "task 子字段裁剪为:task_id, task_no, status, pick_mode, start_at, finish_at, batch_no。", + "boxes 补充并明确返回:ref_label(箱参考标签)、required_qty(箱内需拣总数)、picked_qty(已拣数量)。", + "本次变更为文档层面的返回裁剪,前端应以新字段集合为准,旧字段可能不再返回。" + ], + "type": "updated" + }, + { + "version": "2026.05.10-system-01", + "date": "2026-05-10", + "summary": "order.wave.waveStrategyList 新增 strategy_type 最小过滤(散单/团购)", + "methods": [ + "order.wave.waveStrategyList" + ], + "notes": [ + "新增 strategy_type 过滤,仅 1/2", + "支持顶层 strategy_type 和 where.strategy_type,顶层优先", + "当前不引入其他 where 字段" + ], + "type": "updated" + }, + { + "version": "2026.05.09-system-02", + "date": "2026-05-09", + "summary": "新增 pick.wavePickTaskDetail:按任务ID解析拣货任务详情", + "methods": [ + "pick.wavePickTaskDetail" + ], + "notes": [ + "新增 pick.wavePickTaskDetail:传入 task_id 获取拣货任务完整信息,包含主表字段(task/pick_mode/status/wave_count/order_count/box_count 等)及三张子表数据(waves/orders/boxes)。", + "安全限制:接口会校验当前登录用户(operator_id/employees_id)与任务的 pick_user_id 是否一致;不一致时直接返回 403,不返回任何拣货信息。", + "鉴权配置:noNeedRight=true,noNeedAuth=true,isNeedLogin=true。" + ], + "type": "added" + }, + { + "version": "2026.05.08-system-05", + "date": "2026-05-08", + "summary": "order.wave.batchList:新增 source 字段并支持 where.source 过滤,返回 list item 中新增 source 字段", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "新增 where.source(可选,number)用于按来源过滤:0=普通波次(正常后台操作),1=管理后台策略任务,2=PDA策略任务;不传则不过滤。", + "响应 list 每条记录新增字段 source(number),用于区分波次来源。", + "仅更新文档,业务代码不在此变更范围。" + ], + "type": "updated" + }, + { + "version": "2026.05.08-system-04", + "date": "2026-05-08", + "summary": "完善 order.wave.wavePickTaskList 文档:补充入参、分页与返回字段兼容说明", + "methods": [ + "order.wave.wavePickTaskList", + "order.wave.wavePickTaskCancel" + ], + "notes": [ + "入参补充:warehouse_id(必填)、status(支持单值或数组,建议传数组)、source、keyword、page_no、page_size;保留 pagination 对象以兼容旧客户端。", + "兼容说明:接口同时支持历史 where 结构与顶层参数;当存在同名顶层参数时以顶层参数优先;pagination 支持 page/current 与 pageSize/size 别名。", + "返回格式:响应包含 total 与 list;list 每项包含字段:task_id、task_no、status、source、pick_mode、wave_count、order_count、box_count、operator_id、operator_name、start_at、finish_at、created_at。为兼容旧客户端,响应同时保留旧字段:pick_user_id、pick_user_name、start_time、finish_time、create_time。", + "入参 strategy_id 当前主表未存,接口会忽略该过滤,不建议使用。", + "默认排序:create_time desc.", + "文档变更:移除 order.wave.wavePickTaskCancel 的入参 operator_id 与 warehouse_id;入参改为仅支持 task_ids(数组,必填),不再兼容单个 task_id;操作人与仓库由请求上下文(例如当前登录用户上下文)自动获取;若上下文缺失接口将返回错误。响应补充批量结果字段:cancelled_count、task_ids、task_nos(若后端返回)。仅更新文档,未修改业务实现。" + ], + "type": "updated" + }, + { + "version": "2026.05.08-system-03", + "date": "2026-05-08", + "summary": "升级按策略抓取接口为创建任务主流程:order.wave.waveStrategyFetchPda / order.wave.waveStrategyFetchAdmin", + "methods": [ + "order.wave.waveStrategyFetchPda", + "order.wave.waveStrategyFetchAdmin" + ], + "notes": [ + "将 PDA/Admin 场景的按策略抓取接口由受理壳方法升级为 '创建任务主流程':接口会执行参数校验并在同步响应中创建任务记录(state=created),返回 task_id、task_no、plan 与 plan_summary 供前端展示与后续查询。", + "入参新增/扩展与创建流程相关字段:至少包含 cart_id(关联拣货车/作业车ID)、source(操作来源语义)并保留并透传 strategy_id 与 strategy_params(策略参数),以支持在创建阶段对策略进行局部覆盖或透传。", + "成功返回示例字段:state=created、task_id、task_no、plan(对象)和 plan_summary(字符串);失败场景会返回 validation_errors(数组,每项含 field/message)或 message 描述创建失败原因。", + "边界说明:当前为最小主流程(创建与计划预览),后续扫描/任务执行阶段(如实际抓取订单、写入 wave 等)将在后续版本中追加与完善。" + ], + "type": "updated" + }, + { + "version": "2026.05.08-system-02", + "date": "2026-05-08", + "summary": "调整按策略抓取壳方法:order.wave.waveStrategyFetch 更名为 order.wave.waveStrategyFetchPda,并新增 order.wave.waveStrategyFetchAdmin", + "methods": [ + "order.wave.waveStrategyFetch", + "order.wave.waveStrategyFetchPda", + "order.wave.waveStrategyFetchAdmin" + ], + "notes": [ + "waveStrategyFetchPda 仅用于 PDA 场景", + "waveStrategyFetchAdmin 仅用于后台管理场景", + "两者当前均为壳子受理方法,不执行真实抓取" + ], + "type": "updated" + }, + { + "version": "2026.05.08-system-01", + "date": "2026-05-08", + "summary": "新增 order.wave.waveStrategyFetch:按策略提交抓取任务(壳子方法)", + "methods": [ + "order.wave.waveStrategyFetch" + ], + "notes": [ + "当前方法为壳子方法:仅受理并返回任务受理信息,不执行真实抓取逻辑,后续补齐执行链路。" + ], + "type": "added" + }, + { + "version": "2026.05.07-system-05", + "date": "2026-05-07", + "summary": "新增 order.wave.waveStrategyCreate 与 order.wave.waveStrategyUpdate:波次策略创建与更新接口(含参数校验与版本推进)", + "methods": [ + "order.wave.waveStrategyCreate", + "order.wave.waveStrategyUpdate" + ], + "notes": [ + "仓库 ID 与创建人(creator_name)由当前登录仓库/操作者上下文获取,接口不接受外部覆盖。", + "入参 allowed_owners 与 allowed_expresses 会校验是否在系统可用范围内(基于仓库签约货主或系统快递列表),若存在非法值接口会直接报错(400)。", + "max_same_structure 受仓库配置 min_group_order_fetch_quantity 限制:若传入值 >= min_group_order_fetch_quantity,则自动下调为 min_group_order_fetch_quantity - 1(最小值为 1)。", + "新建/更新成功后会触发仓库的 wave_strategy_version 自增(+1)并失效相关仓库配置缓存,调用方可通过策略版本推进或缓存变化感知策略已生效。" + ], + "type": "added" + }, + { + "version": "2026.05.07-system-06", + "date": "2026-05-07", + "summary": "收敛 order.wave.waveStrategyFallbackOrderList 返回字段,限定 where 白名单,补充 order.wave.singleFetchByIds 别名与返回语义", + "methods": [ + "order.wave.waveStrategyFallbackOrderList", + "order.wave.singleFetchByIds" + ], + "notes": [ + "收敛 order.wave.waveStrategyFallbackOrderList response.list 字段为 id, delivery_no, tracking_no, items_count, items_total, sys_logistics_name, store_name, province, sys_platform_name, item_snapshot;item_snapshot 格式示例:商品名称*数量|...。", + "限制 order.wave.waveStrategyFallbackOrderList.where 白名单,禁止传入 warehouse_id / warehouseId;传入未列出字段或别名冲突将返回 400。", + "补充 order.wave.singleFetchByIds:明确支持 ids / order_ids / orderIds 三个别名(优先顺序 ids -> order_ids -> orderIds)并说明返回字段 fetched_order_ids、excluded_existing_wave_order_ids、skipped_order_ids、not_found_order_ids 的语义与兼容性。" + ], + "type": "updated" + }, + { + "version": "2026.05.07-system-04", + "date": "2026-05-07", + "summary": "更新 order.wave.waveStrategyFallbackOrderList,新增商品快照字段 item_snapshot", + "methods": [ + "order.wave.waveStrategyFallbackOrderList" + ], + "notes": [ + "item_snapshot 返回格式为 商品名称1*数量|商品名称2*数量" + ], + "type": "updated" + }, + { + "version": "2026.05.07-system-03", + "date": "2026-05-07", + "summary": "新增 order.wave.waveStrategyQuickScan 与进度查询接口", + "methods": [ + "order.wave.waveStrategyQuickScan", + "order.wave.waveStrategyQuickScanTaskProgress" + ], + "notes": [ + "同仓只允许一个扫描任务并使用缓存锁;扫描范围为当前表非待审核、未分配波次且订单策略版本与仓库当前版本不一致的订单;命中策略标记 wave_scan_result=1,否则=2" + ], + "type": "added" + }, + { + "version": "2026.05.07-system-02", + "date": "2026-05-07", + "summary": "新增 order.wave.waveStrategyList:查询当前仓库波次策略列表", + "methods": [ + "order.wave.waveStrategyList" + ], + "notes": [ + "从 wms_wave_strategy 拉取当前仓库的波次策略列表,分页返回" + ], + "type": "added" + }, + { + "version": "2026.05.07-system-01", + "date": "2026-05-07", + "summary": "移除 order.wave.singleOrderFetchDetailList,新增 order.wave.waveStrategyFallbackOrderList(内置固定筛选条件)", + "methods": [ + "order.wave.singleOrderFetchDetailList", + "order.wave.waveStrategyFallbackOrderList" + ], + "notes": [ + "移除 order.wave.singleOrderFetchDetailList。", + "新增 order.wave.waveStrategyFallbackOrderList。", + "新接口基于订单通用查询口径,固定内置筛选条件:step != 0、wave_id = 0、wave_scan_result = 2。" + ], + "type": "updated" + }, + { + "version": "2026.05.06-system-06", + "date": "2026-05-06", + "summary": "新增 order.wave.singleOrderFetchDetailList:订单级散单候选明细视图", + "methods": [ + "order.wave.singleOrderFetchDetailList" + ], + "notes": [ + "新增 order.wave.singleOrderFetchDetailList:提供订单级的散单候选明细列表,返回按订单聚合的明细(非分组级)。", + "返回订单级而非分组级;响应每项包含订单 id、group_count、item_detail_machine、item_detail_machine_snapshot、item_detail、item_snapshot、logistics_name、store_id、distinguish_express、create_at 与 status_summary 等关键字段。", + "仍沿用 same_order_quantity 阈值来排除团购命中分组(仅保留 group_count < same_order_quantity 的候选项)。", + "singleOrderFetchList 暂保留以兼容现有前端,前端可在切换到订单级视图后迁移到本接口。" + ], + "type": "added" + }, + { + "version": "2026.05.06-system-05", + "date": "2026-05-06", + "summary": "storage.receiving.get 返回扩展:data.details[*] 新增 box_remainder、box_weight", + "methods": [ + "storage.receiving.get" + ], + "notes": [ + "storage.receiving.get 的响应在 data.details[*] 中新增可选字段:box_remainder(箱内剩余数量/零散数量,number,默认 0)与 box_weight(实测箱重,number,默认 0)。", + "兼容性:新增字段为可选,旧客户端无需修改;建议前端在需要展示箱内余量/箱重时使用这些字段。" + ], + "type": "updated" + }, + { + "version": "2026.05.06-system-04", + "date": "2026-05-06", + "summary": "storage.receiving.getReceivingDetail 返回扩展:明细增加 box_remainder、box_weight;storage.receiving.completeReceiving 通知包含这两个字段", + "methods": [ + "storage.receiving.getReceivingDetail", + "storage.receiving.completeReceiving" + ], + "notes": [ + "为支持箱规统计与通知回传,getReceivingDetail 的明细项(receiving.details 或 data.details)在响应中新增可选字段:box_remainder(箱内剩余数量/零散数量,number)与 box_weight(实测箱重,number,单位同系统重量)。", + "completeReceiving 在完成收货后会发送通知(或回调),通知 payload/metadata 中将包含每条明细的 box_remainder 与 box_weight 字段,供下游系统/前端展示或审计使用。", + "兼容性:新增字段为可选,旧客户端在未使用这些字段时无需变更。" + ], + "type": "updated" + }, + { + "version": "2026.05.06-system-03", + "date": "2026-05-06", + "summary": "storage.receiving.detailChange:新增入参/出参字段 box_remainder、box_weight", + "methods": [ + "storage.receiving.detailChange" + ], + "notes": [ + "为支持箱规细化与回写,detailChange 新增可选入参 box_remainder(箱内余量/零散数量)和 box_weight(实测箱重,单位同系统重量),写入后会回写至明细并在响应 data 中返回对应字段。", + "兼容性:新增字段为可选,不传入则不影响现有调用;建议前端在需要回写箱余与箱重时一并传入。" + ], + "type": "updated" + }, + { + "version": "2026.05.06-system-02", + "date": "2026-05-06", + "summary": "新增 order.wave.singleFetchByIds:按订单ID抓取到一个散单波次", + "methods": [ + "order.wave.singleFetchByIds" + ], + "notes": [ + "新增 order.wave.singleFetchByIds:按入参 ids(兼容 order_ids/orderIds)去重后筛选当前仓库内待处理且不在波次中的订单,若存在可抓取订单则创建单个散单波次并把这些订单写入该波次(不区分快递);成功后批量写入订单操作日志;若无可抓取订单返回 wave_id=0。", + "接口行为严格对齐实现:过滤条件包含 step in [1,2,3]、status != 'cancel'、outbound_status != 'padding';已在波次的订单会被排除并返回 excluded_existing_wave_order_ids;响应包含 ids、wave_id、wave_no、fetched_order_ids、fetched_order_count、excluded_existing_wave_order_ids、skipped_order_ids、not_found_order_ids。" + ], + "type": "added" + }, + { + "version": "2026.05.06-system-01", + "date": "2026-05-06", + "summary": "新增 order.wave.groupFetch 与 order.wave.singleFetch;order.wave.fetch 保留兼容别名;抓取进度补充上限字段", + "methods": [ + "order.wave.groupFetch", + "order.wave.singleFetch", + "order.wave.fetch", + "order.wave.fetchTaskProgress" + ], + "notes": [ + "新增 order.wave.groupFetch:抓取团购接口(异步任务提交),参数 structure_list 与原 fetch 一致。", + "新增 order.wave.singleFetch:抓取散单接口(异步任务提交),在 structure_list 每项新增必填字段 max_fetch_quantity(最大抓取上限,订单数,正整数)。", + "order.wave.fetch 保留为兼容别名(等同 groupFetch),避免误导客户端。", + "groupFetch/singleFetch/fetch 的响应新增可选字段 fetch_mode;singleFetch 响应额外返回 max_fetch_quantity。", + "order.wave.fetchTaskProgress 的响应增加单模式相关字段:fetch_mode、max_fetch_quantity、limit_reached、stop_reason,用于描述散单抓取的上限与停止原因。" + ], + "type": "updated" + }, + { + "version": "2026.05.05-system-02", + "date": "2026-05-05", + "summary": "order.wave.batchList:新增 where.storage_assignment_status 的过滤语义说明", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "新增 where 字段 `storage_assignment_status`:类型 string,可选值:`未分配`、`部分分配`、`已分配`;默认不传:不做分配状态限制。", + "过滤语义:`已分配`:聚合后全部 fin;`部分分配`:不含 error,且既不是全 none,也不是全 fin;`未分配`:全 none 或包含 error(异常并入未分配筛选集合)。", + "说明:返回字段 `storage_assignment_status` 的展示值保持不变;包含 error 时仍可能展示“分配异常”,但 where 的过滤语义把异常算到“未分配”集合,避免把过滤语义与展示值混淆。" + ], + "type": "updated" + }, + { + "version": "2026.05.05-system-01", + "date": "2026-05-05", + "summary": "新增 order.wave.singleOrderFetchList:散单候选分组查询(排除团购命中分组)", + "methods": [ + "order.wave.singleOrderFetchList" + ], + "notes": [ + "新增 order.wave.singleOrderFetchList:返回按机器结构分组的散单候选列表,接口会排除已达团购阈值(同组订单数量 >= same_order_quantity 或仓库配置 min_group_order_fetch_quantity)的分组,仅返回同组订单数量 < 阈值 的分组(散单候选)。", + "与 order.wave.groupOrderFetchList 的关键差异:groupOrderFetchList 返回满足团购阈值(>=)的分组;singleOrderFetchList 返回未达阈值(<)的散单候选分组。", + "影响范围:订单波次抓取相关前端/调度服务。兼容性:不影响或修改现有 order.wave.groupOrderFetchList,两个接口可并行使用。" + ], + "type": "added" + }, + { + "version": "2026.05.04-system-04", + "date": "2026-05-04", + "summary": "完善商品编码唯一性校验接口文档,补充 item_id(排除自身)和 owner_id(货主ID)入参说明,新增 unique/isUnique 返回字段描述", + "methods": [ + "stock.warehouse.checkItemCodeUnique" + ], + "notes": [ + "完善商品编码唯一性校验接口文档,补充 item_id(排除自身)和 owner_id(货主ID)入参说明,新增 unique/isUnique 返回字段描述" + ], + "type": "modified" + }, + { + "version": "2026.05.04-system-03", + "date": "2026-05-04", + "summary": "新增订单打印模块:按波次IDs获取打印数据并自动过滤未完全分配波次", + "methods": [ + "order.print.getWavePrintData" + ], + "notes": [ + "按波次IDs获取订单打印数据,内部去重并规范化 wave_ids,自动过滤快递未完全分配的波次;返回通过过滤的波次订单明细,按 wave_no 排序分组,并在 ext 中返回 missing_wave_ids 与 filtered_wave_ids。" + ], + "type": "added" + }, + { + "version": "2026.05.04-system-02", + "date": "2026-05-04", + "summary": "修改 pick.query 入参:order_id -> waybill_code", + "methods": [ + "pick.query" + ], + "notes": [ + "入参从 order_id 改为 waybill_code(快递号),通过快递号查找订单后再查波次拣货信息" + ], + "type": "breaking_change" + }, + { + "version": "2026.05.04-system-01", + "date": "2026-05-04", + "summary": "新增 system method pick.query:按订单查询波次拣货信息", + "methods": [ + "pick.query" + ], + "notes": [ + "按订单查询该订单所属波次的拣货信息,支持 full/full_display/is_full 控制是否完整显示;接口按当前登录用户仓库上下文过滤,防止跨仓越界。" + ], + "type": "added" + }, + { + "version": "2026.05.03-system-09", + "date": "2026-05-03", + "summary": "新增按 request_id 查询分配状态/结果接口", + "methods": [ + "order.pendingOrder.allocateStorageProgress" + ], + "notes": [ + "新增按 request_id 查询储位分配异步任务状态/结果接口,支持 status:submitted/running/success/failed/not_found;success 返回 result(底层分配结果),failed 返回 error(错误信息);兼容 requestId 参数名。" + ], + "type": "updated" + }, + { + "version": "2026.05.03-system-07", + "date": "2026-05-03", + "summary": "新增抓取进度查询接口", + "methods": [ + "order.wave.fetch", + "order.wave.fetchTaskProgress" + ], + "notes": [ + "新增按 task_id 查询抓取任务进度的接口 order.wave.fetchTaskProgress,支持返回 status(submitted/running/success/failed/not_found)及进度相关字段:progress_percent、finished_structure_count、total_fetched_quantity、duration_ms、error、update_time 等;同时明确 order.wave.fetch 为异步任务提交接口,客户端可通过 task_id 调用 order.wave.fetchTaskProgress 查询进度和最终结果。" + ], + "type": "updated" + }, + { + "version": "2026.05.03-system-05", + "date": "2026-05-03", + "summary": "补齐仓库设置模块 setting.warehouse 的 methods 文档", + "methods": [ + "setting.warehouse.getSettings", + "setting.warehouse.getFieldMeta", + "setting.warehouse.saveSettings" + ], + "notes": [ + "补齐仓库配置 methods API 文档" + ], + "type": "updated" + }, + { + "version": "2026.05.03-system-04", + "date": "2026-05-03", + "summary": "order.wave:自动加团新增跳过规则并新增批量结束自动加团接口", + "methods": [ + "order.wave.batchAutoGrouping", + "order.wave.batchFinishAutoGrouping" + ], + "notes": [ + "开启自动加团新增“已打印/超最大波次容量”跳过规则并在响应中返回跳过明细;新增批量结束自动加团接口(将 wave_status=0 的波次批量置为 1)" + ], + "type": "updated" + }, + { + "version": "2026.05.03-system-03", + "date": "2026-05-03", + "summary": "裁剪 order_list 以轻量化返回", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "移除响应中的 order_list 字段,接口仅返回波次基础信息与状态汇总(order_count / storage_assignment_status / express_assignment_status / print_assignment_status)" + ], + "type": "updated" + }, + { + "version": "2026.05.03-system-02", + "date": "2026-05-03", + "summary": "新增 order.wave.batchAutoGrouping:批量改为自动加团中", + "methods": [ + "order.wave.batchAutoGrouping" + ], + "notes": [ + "新增批量改为自动加团中接口及返回字段" + ], + "type": "updated" + }, + { + "version": "2026.04.22-system-02", + "date": "2026-04-22", + "summary": "新增 order.pendingOrder.syncOrderIds:待处理订单同步透传入口", + "methods": [ + "order.pendingOrder.syncOrderIds" + ], + "notes": [ + "新增 order.pendingOrder.syncOrderIds:仅接收 order_ids 并转发到服务层,当前不做业务处理。", + "接口保留登录态校验,入参仅接受订单 ID 相关字段,响应以服务层返回值为准。", + "该方法用于预留同步链路,后续补齐业务逻辑时再扩展服务层实现。" + ], + "type": "updated" + }, + { + "version": "2026.04.22-system-01", + "date": "2026-04-22", + "summary": "补全订单工作台各模块 detail 方法文档", + "methods": [ + "order.detail", + "order.pendingOrder.detail", + "order.reviewOrder.detail", + "order.expectionOrder.detail", + "order.outboundOrder.detail", + "order.deliveryOrder.detail", + "order.deliveryExpectionOrder.detail", + "order.entrustOrder.detail", + "order.archiveOrder.detail" + ], + "notes": [ + "补全文档:detail 为订单工作台通用详情方法,入参支持 ids/id/order_id/orderId;可选 tableType/tablePosition/type/moduleName,支持 current/history/dispatch/outsourced/order/revieworder/pendingorder 等。", + "返回包含 order/detail(订单头)、orderItems/items(商品明细)、expresses(运单信息)、waybill_codes(去重运单号数组)。" + ], + "type": "updated" + }, + { + "version": "2026.04.19-system-01", + "date": "2026-04-19", + "summary": "新增方法 setting.expressInterface.listByWarehousePlatformCode:按 warehouse_id + platform_code 查询全字段列表并支持缓存", + "methods": [ + "setting.expressInterface.listByWarehousePlatformCode" + ], + "notes": [ + "新增 setting.expressInterface.listByWarehousePlatformCode:按 warehouse_id + platform_code 返回快递接口的全字段数组(不分页),每条记录包含 express 关联对象(id/code/name/platform 等)。", + "支持缓存,缓存键由 warehouse_id + platform_code 组成;缓存命中将直接返回缓存结果以提升查询性能。", + "在创建/更新/删除操作(setting.expressInterface.create/update/delete)后,会主动清理对应 warehouse_id + platform_code 的缓存以确保数据一致性。" + ], + "type": "added" + }, + { + "version": "2026.04.17-system-08", + "date": "2026-04-17", + "summary": "新增快递编码管理模块批量软删除接口 setting.express.delete", + "methods": [ + "setting.express.delete" + ], + "notes": [ + "新增批量软删除接口 setting.express.delete:接受 ids(数组、逗号字符串或单值),对属于当前仓库且未被删除的记录执行软删除(设置 deleted_at),并清理 express 列表缓存。", + "当任一目标记录的 code 被 wms_express_interface.express_code 引用时,接口会拒绝删除并返回 409,错误信息中包含被引用的编码列表。", + "响应包含 ids、deleted_ids、already_deleted_ids 与 status,已删除与未删除的 id 会明确分类。仅记录已实现行为。" + ], + "type": "added" + }, + { + "version": "2026.04.17-system-05", + "date": "2026-04-17", + "summary": "新增文档分组:平台编码管理模块(收口 index.getPlatformList 与 setting.platform.*)", + "methods": [ + "index.getPlatformList", + "setting.platform.list", + "setting.platform.create", + "setting.platform.update", + "setting.platform.delete" + ], + "notes": [ + "新增独立文档分组 '平台编码管理模块',将平台基础列表(index.getPlatformList)与平台设置管理接口(setting.platform.*)归并为单一分组以便维护;仅文档变更,不修改实现。", + "文档中仅包含已实现的方法与字段,未新增或推断不存在的参数/返回字段。" + ], + "type": "added" + }, + { + "version": "2026.04.17-system-04", + "date": "2026-04-17", + "summary": "新增独立平台设置模块 setting.platform(wms_platfrom_setting)及其 CRUD 接口:list/create/update/delete。", + "methods": [ + "setting.platform.list", + "setting.platform.create", + "setting.platform.update", + "setting.platform.delete" + ], + "notes": [ + "新增独立模块 setting.platform,映射数据表 wms_platfrom_setting;list 支持 where(id/code/name/platform_code/quickWhere)与 pagination(兼容 page/pageSize/page_size);create/update 要求 platform_code 必须存在于系统平台表(wms_platform),且禁止越权写入 warehouse_id;delete 需传入 id 并校验当前仓库范围。" + ], + "type": "added" + }, + { + "version": "2026.04.15-system-07", + "date": "2026-04-15", + "summary": "将 docs/order-workbench-list-api.md 引用统一为 window 链接格式", + "methods": [ + "order.list", + "order.reviewOrder.list", + "order.pendingOrder.list", + "order.outboundOrder.list", + "order.expectionOrder.list", + "order.entrustOrder.list", + "order.deliveryOrder.list", + "order.deliveryExpectionOrder.list" + ], + "notes": [ + "将所有 methods/system.json 中指向 docs/order-workbench-list-api.md 的说明统一替换为 docs/order-workbench-list-api.md 格式,以便 HTML 渲染识别为 window 链接。", + "仅修改 methods/system.json 的文档字段,不涉及任何业务代码或接口契约变化。" + ], + "type": "updated" + }, + { + "version": "2026.04.15-system-06", + "date": "2026-04-15", + "summary": "订单工作台列表文档补全 raw 字段字典与中文语义说明", + "methods": [ + "order.list", + "order.reviewOrder.list", + "order.pendingOrder.list", + "order.outboundOrder.list", + "order.expectionOrder.list", + "order.entrustOrder.list", + "order.deliveryOrder.list", + "order.deliveryExpectionOrder.list", + "order.archiveOrder.list" + ], + "notes": [ + "在 docs/order-workbench-list-api.md 中补充所有订单列表通用 raw 字段字典,明确每个字段的中文语义与 enum 取值。", + "补充 express_numbers / waybill_codes 两个服务层派生字段说明,便于前端直接渲染多个快递号。", + "methods/system.json 中所有订单 list 的 response.list 描述已指向该字段字典章节。" + ], + "type": "updated" + }, + { + "version": "2026.04.15-system-05", + "date": "2026-04-15", + "summary": "基础模块新增快递/平台列表查询接口并设置为不鉴权,复用缓存 service", + "methods": [ + "index.getExpressList", + "index.getPlatformList" + ], + "notes": [ + "新增 index.getExpressList,归属基础模块(module=index),对应 app/service/systems/express.js 中的 getExpressList。", + "index.getExpressList 设置为不鉴权,不需要 Authorization 头。", + "新增 index.getPlatformList,归属基础模块(module=index),对应 app/service/systems/platform.js 中的 getPlatformList。", + "index.getPlatformList 设置为不鉴权,不需要 Authorization 头。", + "快递列表与平台列表都支持缓存优先,缓存未命中时回源数据库并写入缓存。", + "平台列表支持缓存优先,缓存未命中时回源 wms_platform 并写入缓存。" + ], + "type": "added" + }, + { + "version": "2026.04.15-system-02", + "date": "2026-04-15", + "summary": "签约策略字段元信息新增 default_express_code / default_platform_code list 选项", + "methods": [ + "storeWarehouse.store.getPolicyConfigFields" + ], + "notes": [ + "getPolicyConfigFields 现在返回 default_express_code 与 default_platform_code 两个 list 字段,并从 wms_express / wms_platform 读取选项列表。", + "默认值仍保留为 default_express_code=STO、default_platform_code=TB。" + ], + "type": "updated" + }, + { + "version": "2026.04.15-system-03", + "date": "2026-04-15", + "summary": "签约策略字段移除 sku_visibility,receive_mode options 改为 value/label 结构", + "methods": [ + "storeWarehouse.store.savePolicyConfig", + "storeWarehouse.store.getPolicyConfigFields" + ], + "notes": [ + "策略字段定义不再包含 sku_visibility,历史值读取时仍会被归一化忽略。", + "receive_mode 的 options 改为 [{ value, label }] 格式,便于前端直接渲染。" + ], + "type": "updated" + }, + { + "version": "2026.04.15-system-04", + "date": "2026-04-15", + "summary": "按文件模块拆分 order 目录系统文档分组,覆盖订单工作台入口及各子模块方法", + "methods": [ + "order.list", + "order.manualOutboundOrder", + "order.badgeCount", + "order.outboundOrder.manualOutboundOrder", + "order.reviewOrder.list", + "order.reviewOrder.reviewOrder", + "order.pendingOrder.list", + "order.pendingOrder.reverseReviewOrder", + "order.pendingOrder.markPendingOutboundOrder", + "order.pendingOrder.cancelOrder", + "order.outboundOrder.list", + "order.expectionOrder.list", + "order.entrustOrder.list", + "order.deliveryOrder.list", + "order.deliveryExpectionOrder.list", + "order.archiveOrder.list" + ], + "notes": [ + "按 app/service/systemMethods/order 下的实际对外方法补全 methods/system.json 文档,只覆盖 system,不处理 qimen。", + "order 文档已按 index / reviewOrder / pendingOrder / outboundOrder / expectionOrder / entrustOrder / deliveryOrder / deliveryExpectionOrder / archiveOrder 拆成多个模块分组。", + "同步根据当前代码意图补充 params / response / errors,且不再把 index.js 已移除的兼容接口写回文档。" + ], + "type": "updated" + }, + { + "version": "2026.04.15-system-01", + "date": "2026-04-15", + "summary": "货主主体配置默认补齐 default_express_code / default_platform_code", + "methods": [ + "store.createStore", + "store.createWarehouse" + ], + "notes": [ + "当 subject_config 未传或缺少字段时,自动补齐 default_express_code=STO、default_platform_code=TB,并保留现有的 max_notice_webhook_count 默认值。", + "同步更新 methods/system.json 中 store.createStore 与 store.createWarehouse 的参数说明。" + ], + "type": "updated" + }, + { + "version": "2026.04.14-system-01", + "date": "2026-04-14", + "summary": "库存列表新增货主名称字段 stock.store_name", + "methods": [ + "storage.inventory.list" + ], + "notes": [ + "在 methods/system.json 的 storage.inventory.list response 中补充 stock.store_name:来源于签约表 store_remask,若无签约关系则为 null。", + "只同步文档,不修改业务代码。" + ], + "type": "updated" + }, + { + "version": "2026.04.13-system-01", + "date": "2026-04-13", + "summary": "补全 storage.receiving.detailChange 的入参/出参契约与错误码说明", + "methods": [ + "storage.receiving.detailChange" + ], + "notes": [ + "在 methods/system.json 中补充 storage.receiving.detailChange 的 params/response/errors,明确 id 与 receiving_id 必填。", + "说明 expiry_date 小于当前日期时返回 400 且 message 为 \"到期日期已过期,不能录入收货\"。", + "说明当传入 system_product_id 时会回填条码、重量、箱规、商品名称与 product_snapshot;未传时 barcode/product_name 也可单独更新。", + "同步补充文档:docs/storage-receiving-api.md 中新增 detailChange 段落。" + ], + "type": "updated" + }, + { + "version": "2026.04.07-system-01", + "date": "2026-04-07", + "summary": "修正 warehouse.getAreaRacks 的鉴权/权限链路文档,明确该接口需要 登录并走权限校验。", + "methods": [ + "warehouse.getAreaRacks" + ], + "notes": [ + "对齐当前 system 文档中的 isNeedAuth=true、isNeedLogin=true。", + "用于补充该接口权限链路修正文档的历史上下文,不改变 methods/system.json 的 SSOT 角色。" + ] + }, + { + "version": "2026.04.07-system-02", + "date": "2026-04-07", + "summary": "补充签约配置相关接口文档,覆盖策略字段元信息查询与面单数量人工调整。", + "methods": [ + "storeWarehouse.store.getPolicyConfigFields", + "storeWarehouse.store.adjustPrintQuantity" + ], + "notes": [ + "getPolicyConfigFields 说明为获取签约策略可配置字段元信息列表。", + "adjustPrintQuantity 说明为人工调整签约关系下的面单余额并记录变更日志,并 明确 id、change_quantity、reason 等关键入参。" + ] + }, + { + "version": "2026.04.07-system-03", + "date": "2026-04-07", + "summary": "对外命名从 qimenConfig 收口为 apiConfig,并在接口配置文档中强调 interface_type_id 校验。", + "methods": [ + "storeWarehouse.store.listApiConfig", + "storeWarehouse.store.saveApiConfig", + "storeWarehouse.store.deleteQimenConfig" + ], + "notes": [ + "文档对外统一使用 apiConfig / api_config 命名,减少 qimenConfig 历史别名歧义。", + "saveApiConfig 要求 interface_type_id 为必填且必须指向已存在的 wms_interface_type 记录。", + "listApiConfig / deleteQimenConfig 同步补充 interface_type_id 字段说明。" + ] + }, + { + "version": "2026.04.07-system-04", + "date": "2026-04-07", + "summary": "补充 /api/docs 文档体验增强说明,新增查看变更记录与查看原文 JSON 的入口说明。", + "methods": [ + "/api/docs", + "/api/docs/:docName", + "/api/docs/:docName/raw", + "/api/docs/:docName/changes" + ], + "notes": [ + "sidecar 变更数组用于承载文档历史说明,不替代 methods/system.json 作为 SSOT。", + "原文 JSON 入口继续用于直接查看当前生效文档。" + ] + }, + { + "version": "2026.04.07-system-05", + "date": "2026-04-07", + "summary": "修正 storeWarehouse.store.adjustPrintQuantity 的面单余额调整语义:由增减/累加改为覆盖设置目标余额。", + "methods": [ + "storeWarehouse.store.adjustPrintQuantity" + ], + "notes": [ + "adjustPrintQuantity 当前兼容 print_quantity、target_quantity、change_quantity、adjust_quantity 作为目标面单余额输入,不再按增减量解释。", + "变更日志中的 change_quantity 由 before/after 自动计算差值,以兼容历史审计与展示。" + ] + }, + { + "version": "2026.04.07-system-06", + "date": "2026-04-07", + "summary": "按接口类型分类限制必填字段,OPEN_API 创建时自动生成 self_app_key/self_app_secret", + "methods": [ + "storeWarehouse.store.saveApiConfig" + ], + "notes": [ + "QM_WMS 类型须填写 qimen_app_key/qimen_customer_id/qimen_warehouse_code;OPEN_API 类型三个奇门字段非必填,创建时自动生成 self_app_key(WMS+32位HEX)和 self_app_secret(64位HEX),更新时保留已有密钥。" + ], + "type": "changed" + }, + { + "version": "2026.04.07-system-07", + "date": "2026-04-07", + "summary": "新增接口类型列表查询接口,归属基础模块,无需权限", + "methods": [ + "index.listInterfaceTypes" + ], + "notes": [ + "返回所有已启用的接口类型(wms_interface_type),包含 id、interface_code、interface_name、interface_category、description 字段。设置 isNeedAuth: false, isNeedLogin: true。" + ], + "type": "added" + }, + { + "version": "2026.04.07-system-08", + "date": "2026-04-07", + "summary": "app_name 改为必传参数", + "methods": [ + "storeWarehouse.store.saveApiConfig" + ], + "notes": [ + "app_name 不再有默认值自动生成逻辑,调用方必须传入非空的 app_name,否则返 回 400 错误。" + ], + "type": "changed" + }, + { + "version": "2026.04.07-system-09", + "date": "2026-04-07", + "summary": "新增收货单快捷入库上架接口", + "methods": [ + "storage.inventory.quickPutaway" + ], + "notes": [ + "新建 storage.inventory 库存操作模块。quickPutaway 从收货单直接生成入库单 (SCRK)并写入 wms_storage 库存表,同时更新 wms_stock_warehouse 库存数量(悲观行锁),回填收货明细入库状态。要求收货单已完成且所有明细已匹配系统商品。" + ], + "type": "added" + }, + { + "version": "2026.04.08-system-01", + "date": "2026-04-08", + "summary": "新增收货单与入库单匹配入库接口", + "methods": [ + "storage.inventory.matchPutaway" + ], + "notes": [ + "接收多个收货单和入库单,按商品(stock_warehouse_id)进行数量匹配入库,完 成后根据入库单来源(QM/API)自动触发回传。入参为 receiving_ids(数组)和 entry_order_ids(数组),返回匹配汇总、各收货单入库状态、各入库单状态及回传结果。isNeedAuth=true, isNeedLogin=true, isNeedRight=false。" + ], + "type": "added" + }, + { + "version": "2026.04.08-system-02", + "date": "2026-04-08", + "summary": "saveApiConfig 新增 callback_url 可选参数", + "methods": [ + "storeWarehouse.store.saveApiConfig" + ], + "notes": [ + "新增 callback_url 参数(VARCHAR(500),可选),用于 OPEN_API 类型入库单的 回调地址配置。" + ], + "type": "changed" + }, + { + "version": "2026.04.08-system-03", + "date": "2026-04-08", + "summary": "serializeQimenConfig 新增返回 callback_url 字段,影响 list 和 listApiConfig 两个接口", + "methods": [ + "storeWarehouse.store.list", + "storeWarehouse.store.listApiConfig" + ], + "notes": [ + "serializeQimenConfig() 序列化方法新增 callback_url(string)字段。storeWarehouse.store.list 返回的每条记录 api_config 对象中包含 callback_url;storeWarehouse.store.listApiConfig 返回的 list 数组中每条配置包含 callback_url。" + ], + "type": "changed" + }, + { + "version": "2026.04.08-system-04", + "date": "2026-04-08", + "summary": "新增库存移库(库位转移)接口", + "methods": [ + "storage.inventory.transferLocation" + ], + "notes": [ + "新增 storage.inventory.transferLocation 接口,支持批量多商品多库位移库, 包含部分数量移库与全量移库。入参为 warehouse_id(仓库ID)和 transfers 数组(storage_id、target_space_id、quantity),触发 storage_transfer_completed 通知事件, 每条移库记录独立操作日志。isNeedAuth=true, isNeedLogin=true。" + ], + "type": "added" + }, + { + "version": "2026.04.08-system-05", + "date": "2026-04-08", + "summary": "简化移库接口入参,从批量 transfers 数组改为单条移库", + "methods": [ + "storage.inventory.transferLocation" + ], + "notes": [ + "移除 warehouse_id 和 transfers 数组入参,改为扁平的 storage_id + target_space_id + quantity 三个顶层参数。warehouse_id 从库存记录自动获取,接口从批量移库简化为单商品单库位移库。响应结构同步简化为单条结果对象。" + ], + "type": "modified" + }, + { + "version": "2026.04.08-system-06", + "date": "2026-04-08", + "summary": "新增商品库存明细查询接口", + "methods": [ + "stock.warehouse.getStockDetail" + ], + "notes": [ + "新增 stock.warehouse.getStockDetail 接口,按库位/批次维度查询商品库存分布。入参为 stock_id(必填,商品库存ID)和 pagination(可选,含 page/pageSize)。返回 stockItem(商品概要)、storageList(wms_storage 明细数组,含批次号、库位、数 量、锁定数量、生产日期、过期日期等,关联 location_space 库位信息)、pagination 分页信息。isNeedAuth=false, isNeedLogin=true。底层调用 stockStore.getStockDetail,自动校验商品归属当前仓库。" + ], + "type": "added" + }, + { + "version": "2026.04.08-system-07", + "date": "2026-04-08", + "summary": "新增入参 group_by_batch,支持按批次维度切换库存明细聚合方式", + "methods": [ + "stock.warehouse.getStockDetail" + ], + "notes": [ + "新增可选布尔参数 group_by_batch(默认 false)。false 时按库位合并数量,批次相关字段(batch_no, production_date, expiry_date, inbound_time, inbound_order_no, supplier_batch_no)置 null;true 时保持原逻辑返回每条明细。出参结构不变,但 storageList 中批次字段在合并模式下为 null。" + ], + "type": "modified" + }, + { + "version": "2026.04.08-system-08", + "date": "2026-04-08", + "summary": "新增按商品维度移库接口", + "methods": [ + "storage.inventory.transferByProduct" + ], + "notes": [ + "新增 storage.inventory.transferByProduct 接口,按库位+商品查找所有库存记 录合并移动。入参为 space_id(原库位ID)、stock_id(商品SKU ID,即 wms_stock_warehouse.id)、target_space_id(目标库位ID)、quantity(移库数量)。开启批次管理(is_batch_mgmt=Y)的商品会被拒绝,需使用 transferLocation 按库存记录精确移库。复用 storage_transfer_completed 通知事件,操作日志编码 STORAGE_TRANSFER_BY_PRODUCT。isNeedAuth=true, isNeedLogin=true。" + ], + "type": "added" + }, + { + "version": "2026.04.08-system-09", + "date": "2026-04-08", + "summary": "补充 storeWarehouse.store.list 完整 response 输出字段说明,移除 api_config / apiConfig", + "methods": [ + "storeWarehouse.store.list" + ], + "notes": [ + "从返回结果中移除 api_config 和 apiConfig 字段(代码中 delete serialized.api_config / delete serialized.apiConfig),文档 response 补充完整输出字段列表:id, store_id, store_name, warehouse_id, warehouse_name, counterparty_id, counterparty_name, current_subject_role, auth_status, auth_status_label, apply_reason, review_comment, apply_time, review_time, auth_start, auth_end, actual_end, print_quantity, applied_by, reviewed_by, ended_by, remask, use_status, policy_config, is_auth_valid, remaining_days 以及分页和 current_subject 信息。" + ], + "type": "updated" + }, + { + "version": "2026.04.08-system-10", + "date": "2026-04-08", + "summary": "货主列表返回新增 has_qimen_config 布尔字段", + "methods": [ + "storeWarehouse.store.list" + ], + "notes": [ + "storeWarehouse.store.list 返回的 data.list[] 中新增 has_qimen_config(boolean),表示该货主是否已配置奇门。" + ], + "type": "changed" + }, + { + "version": "2026.04.08-system-11", + "date": "2026-04-08", + "summary": "补全 stock.warehouse.search 接口文档,新增 params / response / errors 完整说明", + "methods": [ + "stock.warehouse.search" + ], + "notes": [ + "入参补充 keyword(string,模糊匹配 item_code / item_name / goods_code / barcode)和 store_id(number,按货主筛选)。响应补充 data 数组各字段(id, item_code, goods_code, item_name, sku_property, stock_unit, quantity, locked_quantity, brand_name, item_type, barcodes, store_stock)以及 total。errors 补充 code=0 搜 索失败场景。" + ], + "type": "updated" + }, + { + "version": "2026.04.08-system-12", + "date": "2026-04-08", + "summary": "新增 with_stock / is_batch 参数,支持返回关联库存明细(按库位分 组或按批次逐条)", + "methods": [ + "stock.warehouse.search" + ], + "notes": [ + "入参新增 with_stock(boolean,默认 false,是否返回关联库存数据)和 is_batch(boolean,默认 false,仅 with_stock=true 时生效,按批次明细返回)。响应 data[] 新增 storage[] 字段:is_batch=false 时按库位分组汇总(含 space_id、space、inventory_type、quantity、locked_quantity、available_quantity);is_batch=true 时逐 条返回批次明细(含 id、stock_id、space_id、batch_no、inventory_type、quantity、locked_quantity、available_quantity、production_date、expiry_date、inbound_time、inbound_order_no、supplier_batch_no、created_at、space)。" + ], + "type": "updated" + }, + { + "version": "2026.04.08-system-13", + "date": "2026-04-08", + "summary": "新增 wms_stock_transaction 表和模型", + "methods": [ + "wms_stock_transaction" + ], + "notes": [ + "新增出入库流水记录表 wms_stock_transaction,含 transaction_type(INBOUND/OUTBOUND)、warehouse_id、store_id、stock_id、storage_id、space_id、quantity、batch_no、inventory_type、order_type、order_no、order_id、receiving_id、entry_order_id、operator_id、operator_name、remark 等字段,关联 StockWarehouse 和 Storage 模型。" + ], + "type": "added" + }, + { + "version": "2026.04.08-system-14", + "date": "2026-04-08", + "summary": "quickPutaway 和 matchPutaway 入库时自动写入出入库记录", + "methods": [ + "storage.inventory.quickPutaway", + "storage.inventory.matchPutaway" + ], + "notes": [ + "入库操作完成后自动写入 wms_stock_transaction 记录。quickPutaway 写入 order_type='SCRK'(收货入库),matchPutaway 写入 order_type='MATCH'(匹配入库),均 自动填充 warehouse_id、store_id、stock_id、storage_id、space_id、quantity、batch_no、inventory_type 等字段。" + ], + "type": "updated" + }, + { + "version": "2026.04.08-system-15", + "date": "2026-04-08", + "summary": "新增 storage.inventory.list 出入库记录列表查询接口", + "methods": [ + "storage.inventory.list" + ], + "notes": [ + "出入库记录列表查询,支持 where 条件(transaction_type、stock_id、space_id、store_id、order_type、order_no、inventory_type、operator_name、created_at)、 分页(pagination)、排序(sort)和 group_by_batch 参数。默认合并模式按库位+商品 聚合返回合计数量与记录条数,group_by_batch=true 时返回每条明细含 batch_no、order_no、operator_name 等完整信息。响应均关联 stockItem(item_code、item_name、sku_property、stock_unit)。" + ], + "type": "added" + }, + { + "version": "2026.04.08-system-16", + "date": "2026-04-08", + "summary": "出入库流水记录查询接口从 storage.inventory.list 改名为 storage.transaction.list", + "methods": [ + "storage.transaction.list" + ], + "notes": [ + "将出入库流水记录查询从 storage.inventory.list 迁移到 storage.transaction.list,避免与库存列表概念混淆。功能和参数不变。isNeedAuth=false, isNeedLogin=true, isNeedRight=false。" + ], + "type": "rename", + "module": "storage" + }, + { + "version": "2026.04.08-system-17", + "date": "2026-04-08", + "summary": "新增 storage.inventory.list 库存列表查询接口", + "methods": [ + "storage.inventory.list" + ], + "notes": [ + "新增库存列表查询接口,查询 wms_storage 表。支持 where 条件(stock_id/space_id/store_id/inventory_type/batch_no/inbound_order_no/available_quantity/inbound_time/created_at)、分页、排序。支持 group_by_batch 参数:默认 false 按库位+商 品合并(SUM quantity/locked_quantity/available_quantity),true 返回每条明细含 batch_no/production_date/expiry_date 等。关联 stockItem(商品信息)和 space(库位信息)。isNeedAuth=false, isNeedLogin=true, isNeedRight=false。" + ], + "type": "add", + "module": "storage" + }, + { + "version": "2026.04.08-system-18", + "date": "2026-04-08", + "summary": "移除 storage.entry.create 创建入库单接口", + "methods": [ + "storage.entry.create" + ], + "notes": [ + "不再允许通过 API 创建入库单。入库单仅由快捷入库(quickPutaway)和匹配入库(matchPutaway)等内部流程自动创建。底层 service 实现保留但不再通过 systemMethods 对外暴露。" + ], + "type": "remove", + "module": "storage" + }, + { + "version": "2026.04.08-system-19", + "date": "2026-04-08", + "summary": "移除 storage.entry.addDetail / deleteDetail / detailChange 对外 接口", + "methods": [ + "storage.entry.addDetail", + "storage.entry.deleteDetail", + "storage.entry.detailChange" + ], + "notes": [ + "入库单明细编辑能力不再通过 systemMethods 对外暴露,入库单模块仅保留 list/get/cancel/completeEntry。" + ], + "type": "remove", + "module": "storage" + }, + { + "version": "2026.04.08-system-20", + "date": "2026-04-08", + "summary": "新增 storage.stockout 出库单模块(非订单出库单能力)", + "methods": [ + "storage.stockout.list", + "storage.stockout.toOrder", + "storage.stockout.listItems" + ], + "notes": [ + "新增 storage.stockout.list / toOrder / listItems 接口,作为非订单出库单的主出口(对应奇门 stockout.create)。storage.delivery.* 仅作为兼容转发保留;底层 部分能力仍复用 order 模块。" + ], + "type": "add", + "module": "storage" + }, + { + "version": "2026.04.08-system-21", + "date": "2026-04-08", + "summary": "将 storage.stockout.toOrder 标记为占位接口", + "methods": [ + "storage.stockout.toOrder" + ], + "notes": [ + "storage.stockout.toOrder 当前仅保留方法名用于后续扩展,暂不开放实际逻辑。调用时返回 code=405、message=占位接口,暂未开放。" + ], + "type": "change" + }, + { + "version": "2026.04.09-system-01", + "date": "2026-04-09", + "summary": "storage.entry.cancel 支持批量作废,新增 ids 入参并兼容单条 id", + "methods": [ + "storage.entry.cancel" + ], + "notes": [ + "新增入参 `ids`(number[])以支持批量作废,兼容旧入参 `id`;当同时传入 `ids` 与 `id` 时以 `ids` 为准。", + "参数校验:`ids` 必须为非空数组;非法 ID 或空数组返回 400。", + "业务约束:已完成/已作废/处于不可作废状态的单据不允许作废;批量场景下任一 单据不存在或状态不允许时整体返回 404/400,未执行部分更新。", + "响应说明:单条作废返回字段 `id`(number);批量作废返回字段 `ids`(number[])。", + "已同步更新 methods/system.json(storage.entry.cancel)为 SSOT。" + ] + }, + { + "version": "2026.04.09-system-02", + "date": "2026-04-09", + "summary": "新增基础模块车牌识别接口 index.recognizeLicensePlate", + "methods": [ + "index.recognizeLicensePlate" + ], + "notes": [ + "入参:base64(string,必填)或 imageBase64/image_base64(兼容)", + "响应:返回归一化后的识别对象,包含 licensePlate、plateNumber、color、confidence、requestId、imageSize、rawData", + "错误:400(参数或图片格式/尺寸问题),500(第三方 OCR 调用失败或云密钥未 配置)", + "文档中不包含任何敏感配置;实际腾讯云密钥保留在配置文件中,勿在文档中暴露 。" + ], + "type": "added" + }, + { + "version": "2026.04.09-system-03", + "date": "2026-04-09", + "summary": "收紧基础模块车牌识别接口响应,仅返回 licensePlate 字段", + "methods": [ + "index.recognizeLicensePlate" + ], + "notes": [ + "出参由 {licensePlate, plateNumber, color, confidence, requestId, imageSize, rawData} 调整为 {licensePlate}", + "调用方请仅依赖 licensePlate 字段以适配新版本;历史字段已裁剪且不再保证存 在。", + "文档中未包含任何云密钥或敏感配置信息。" + ], + "type": "changed" + }, + { + "version": "2026.04.10-system-01", + "date": "2026-04-10", + "summary": "订单审核字段由 audit_status 替换为整数字段 step,并添加数据库迁移", + "methods": [ + "order.getreviewOrderlist", + "order.reviewOrder.getreviewOrderlist", + "order.reviewOrder.reviewOrder", + "order.deliveryOrder.getdeliveryOrderlist", + "order.list", + "order.stats" + ], + "notes": [ + "字段变更:order 相关审核字段从字符串/枚举 audit_status 替换为整数 step。", + "step 映射:0=未审核,1=已审核,2=处理中,3=驳回/异常,4=配送中,5=已完成,9=已关闭。", + "reviewOrder 接口在更新 inspection_status 的同时会写入 step 字段。", + "必须执行迁移脚本:20260410150000-replace-audit-status-with-step-on-order-delivery-tables.js" + ], + "type": "changed" + }, + { + "version": "2026.04.13-system-02", + "date": "2026-04-13", + "summary": "stock.warehouse.search 返回新增效期管理字段并保留 is_shelf_life_mgmt", + "methods": [ + "stock.warehouse.search" + ], + "notes": [ + "响应 data[] 中新增字段:inbound_min_days、outbound_min_days、shelf_life_days、remaining_threshold_days(均为 number,单位:天)。", + "保留并说明 is_shelf_life_mgmt 布尔字段(boolean),表示是否启用效期管理(true=启用)。", + "仅更新文档(methods/system.json 与变更记录),代码行为不变。" + ], + "type": "updated" + }, + { + "version": "2026.04.13-system-02", + "date": "2026-04-13", + "summary": "新增 storage.expiry.list 库存有效期列表查询接口", + "methods": [ + "storage.expiry.list" + ], + "notes": [ + "该接口查询 wms_storage,关联 stockWarehouse 和 locationSpace,并按当前仓库与 remaining_threshold_days / expiry_date 过滤。" + ], + "type": "added" + }, + { + "version": "2026.04.13-system-03", + "date": "2026-04-13", + "summary": "新增 storage.inventory.list 库存列表返回效期字段与预警标记", + "methods": [ + "storage.inventory.list" + ], + "notes": [ + "库存列表响应增加生产日期、过期日期、效期预警是否触发字段", + "预警标记仅在商品启用保质期管理且到期日满足阈值条件时为 true" + ], + "type": "updated" + }, + { + "version": "2026.04.14-system-01", + "date": "2026-04-14", + "summary": "更新 index.searchSpace 文档", + "methods": [ + "index.searchSpace" + ], + "notes": [ + "补充 index.searchSpace 的 params/response,按 ctx.user.store_id 作为仓库上下文;keyword 为可选字符串,对 space_code 与 custom_barcode 做 %keyword% 模糊匹配;返回字段 id、space_code、custom_barcode、custom_name,最多 50 条;仅文档同步,无代码变更。" + ], + "type": "updated" + }, + { + "version": "2026.04.16-system-01", + "date": "2026-04-16", + "summary": "基础模块新增快递产品类型查询接口", + "methods": [ + "index.getExpressProductTypeList" + ], + "notes": [ + "新增 index.getExpressProductTypeList,归属基础模块(module=index),用于查询指定快递公司的产品类型列表。", + "对应服务实现:app/service/systems/express.js 中的 getExpressProductTypeList,支持传入 express_code 作为可选筛选参数(source=body)。", + "接口设置为免鉴权(isNeedAuth=false)但需登录(isNeedLogin=true),与 index.getExpressList / index.getPlatformList 一致,优先从缓存读取。" + ], + "type": "added" + }, + { + "version": "2026.04.17-system-01", + "date": "2026-04-17", + "summary": "新增快递管理模块(setting.express)及 5 个接口文档", + "methods": [ + "setting.express.list", + "setting.express.listBase", + "setting.express.create", + "setting.express.checkCodeUnique", + "setting.express.update" + ], + "notes": [ + "新增独立模块组:快递管理模块(module=setting.express),将快递映射管理相关接口独立为一组以便维护。", + "接口实现参考:app/service/systems/setting/express.js(返回结构)与 app/service/systemMethods/setting/express.js(对外方法包装)。", + "接口鉴权与上下文:isNeedAuth=false, isNeedLogin=true;需在请求中传入 Authorization 以携带登录上下文(用于获取当前仓库/货主上下文)。", + "已同步更新 methods/system.json,补充 params/response/errors,保持文档与实现一致。" + ], + "type": "added" + }, + { + "version": "2026.04.17-system-02", + "date": "2026-04-17", + "summary": "setting.express.list 分页入参统一为 pagination", + "methods": [ + "setting.express.list" + ], + "notes": [ + "将 setting.express.list 的分页入参文档从顶层 page/page_size/pageSize 迁移为 pagination 对象,主形态为 pagination;兼容 snake_case 的 page_size 与 camelCase 的 pageSize。", + "文档与当前实现一致:顶层 page/page_size/pageSize 会被归一化到 data.pagination 并转发到系统服务。" + ], + "type": "updated" + }, + { + "version": "2026.04.17-system-03", + "date": "2026-04-17", + "summary": "新增快递接口管理模块(setting.expressInterface)及 4 个接口文档", + "methods": [ + "setting.expressInterface.list", + "setting.expressInterface.create", + "setting.expressInterface.update", + "setting.expressInterface.delete" + ], + "notes": [ + "新增独立模块组:快递接口管理模块(module=setting.expressInterface),对应实现:app/service/systems/setting/expressInterface.js 与对外包装 app/service/systemMethods/setting/expressInterface.js。", + "接口为当前仓库范围(基于 ctx.user.store_id),仓库边界由系统服务强制校验;禁止通过接口指定 warehouse_id/warehouseId。操作需登录(isNeedLogin=true),无需额外鉴权(isNeedAuth=false)。", + "已在 methods/system.json 新增对应接口的 params/response/errors 文档,保持与实现一致。" + ], + "type": "added" + }, + { + "version": "2026.04.18-system-01", + "date": "2026-04-18", + "summary": "补充订单储位分配接口文档:order.storageAllocation.allocateStorage", + "methods": [ + "order.storageAllocation.allocateStorage" + ], + "notes": [ + "新增 order.storageAllocation.allocateStorage:按订单批量分配储位,支持多种入参别名(order_ids/ids/orderId 等)与仓库上下文优先级。", + "响应包含 requested_order_ids, pending_order_ids, allocated_order_ids, shortage_order_ids, skipped_orders, picking_count, stock_lock_summary, storage_lock_summary 等字段,用于前端展示分配结果与不足提示。" + ], + "type": "added" + }, + { + "version": "2026.04.18-system-02", + "date": "2026-04-18", + "summary": "新增 order.pendingOrder.allocateExpressCode:待处理订单模块的批量分配快递号入口,复用 express.createWaybillCodePipeline。", + "methods": [ + "order.pendingOrder.allocateExpressCode" + ], + "notes": [ + "该接口直接接收订单对象数组入参;订单对象应为来自待处理订单列表或详情的原始订单对象。每个订单对象必须包含 order_id 与 business_key;sys_platform_code、logistics_code 为订单对象自带字段,前端无需额外拼装或单独构造,直接原样回传订单对象即可。", + "实际的运单创建、归一化与跳过逻辑由 express.createWaybillCodePipeline 处理。", + "接口返回值与现有分配链路一致,已用统一 success 包装返回。" + ], + "type": "added" + }, + { + "version": "2026.04.18-system-03", + "date": "2026-04-18", + "summary": "将 order.storageAllocation.allocateStorage 迁移到 order.pendingOrder.allocateStorage,并移除原有公开分组。", + "methods": [ + "order.pendingOrder.allocateStorage" + ], + "notes": [ + "将对外入口从 order.storageAllocation.allocateStorage 迁移到 order.pendingOrder.allocateStorage,旧的 order.storageAllocation 分组已从 methods/system.json 中移除。", + "新的对外接口不接受 warehouse_id / warehouseId,仓库上下文由当前登录用户(ctx.user.store_id)提供。", + "本次变更仅同步文档位置与对外方法名,底层实现保留且通过新的 system 方法暴露。" + ], + "type": "changed" + }, + { + "version": "2026.04.19-system-02", + "date": "2026-04-19", + "summary": "新增待处理模块取消分配储位接口 order.pendingOrder.cancelAllocateStorage", + "methods": [ + "order.pendingOrder.cancelAllocateStorage" + ], + "notes": [ + "新增待处理模块取消分配储位接口 `order.pendingOrder.cancelAllocateStorage`,直接对接 `service.systems.orderStorageAllocation.cancelAllocateStorage` 实现。", + "接口现在仅接受订单ID(order_ids),不再接受 allow_storage_location;禁止传入 `warehouse_id/warehouseId`,仓库上下文由当前登录用户的 `store_id` 提供。", + "响应返回标准 { flag, code, message, data } 结构,data 包含取消分配的汇总结果(warehouse_id, requested_order_ids, cancellable_order_ids, skipped_orders, orders, picking_count, storage_unlock_summary, stock_unlock_summary)。" + ], + "type": "added" + }, + { + "version": "2026.04.21-system-01", + "date": "2026-04-21", + "summary": "新增 order.pendingOrder.updateOrderPlatform 方法:批量修改待处理订单平台信息", + "methods": [ + "order.pendingOrder.updateOrderPlatform" + ], + "notes": [ + "通过 code 查找 wms_platform,平台不存在时返回 404 错误。", + "仅操作当前仓库的当前订单表。", + "noNeedRight=true,noNeedAuth=true(isNeedAuth: true 在 spec 中对应权限配置 noNeedAuth=true)。" + ], + "type": "added" + }, + { + "version": "2026.04.21-system-02", + "date": "2026-04-21", + "summary": "新增方法 order.pendingOrder.updateOrderExpress:批量修改待处理订单的快递信息", + "methods": [ + "order.pendingOrder.updateOrderExpress" + ], + "notes": [ + "新增 order.pendingOrder.updateOrderExpress:批量修改待处理订单的快递信息,按 express_code 从仓库快递列表(带缓存)匹配快递项。", + "自定义映射(is_system_setting=true)时,sys_logistics_code/name 写入系统快递编码和名称,logistics_code/name 写入自定义编码和名称;系统快递(is_system_setting=false)时四个字段均写系统快递的 code/name。", + "只操作当前仓库的当前订单表,不处理其他订单表;操作后写入操作日志(ORDER_UPDATE_EXPRESS)。" + ], + "type": "added" + }, + { + "version": "2026.04.21-system-03", + "date": "2026-04-21", + "summary": "新增 order.expectionOrder.resolveException:将待处理异常订单转回正常待处理状态", + "methods": [ + "order.expectionOrder.resolveException" + ], + "notes": [ + "新增 order.expectionOrder.resolveException:批量将 step=3 的异常订单恢复为 step=2 正常待处理状态。", + "入参 ids 为订单ID 正整数数组,不能为空;仅操作当前仓库当前订单表。", + "返回 updated_count(实际更新行数)与 ids(本次操作ID列表)。", + "权限配置:noNeedLogin=false、noNeedRight=true、noNeedLog=false、noNeedAuth=true" + ], + "type": "added" + }, + { + "version": "2026.04.21-system-04", + "date": "2026-04-21", + "summary": "新增 order.pendingOrder.cloneOrder 方法:克隆待处理订单", + "methods": [ + "order.pendingOrder.cloneOrder" + ], + "notes": [ + "支持对 step 0/1/2/3 的待处理订单进行克隆操作。", + "若原订单已分配储位(storage_status=fin),克隆前自动清除已分配库存。", + "原订单取消后(step→9, status→cancel),以原订单业务数据创建新订单,流程状态字段全部重置为初始落库状态。", + "克隆订单明细含 stock_id,新订单 ID 重新绑定。", + "noNeedAuth=true,noNeedRight=true,noNeedLogin=false。" + ], + "type": "added" + }, + { + "version": "2026.04.21-system-06", + "date": "2026-04-21", + "summary": "新增 order.pendingOrder.createOrder:手动创建待处理/待审核订单", + "methods": [ + "order.pendingOrder.createOrder" + ], + "notes": [ + "新增 order.pendingOrder.createOrder:手动创建订单,step 由货主策略 need_order_approval 决定(1→待审核 step=0,0→待处理 step=1)。", + "必填字段:store_id、name、mobile/tel 至少一项、detail_address、items[](含 item_code 和 plan_qty)。", + "delivery_order_code 不传则自动生成(SYS+时间戳+随机4位);logistics_code/sys_platform_code 不传则读货主合约策略 default_express_code/default_platform_code。", + "不做库存锁定,储位分配为独立步骤。操作日志写入 ORDER_CREATE。", + "noNeedRight=true,noNeedAuth=true,noNeedLogin=false。" + ], + "type": "added" + }, + { + "version": "2026.04.21-system-07", + "date": "2026-04-21", + "summary": "新增 Excel 模板下载与批量导入创建订单接口:order.pendingOrder.downloadCreateTemplate 和 order.pendingOrder.importOrdersFromExcel", + "methods": [ + "order.pendingOrder.downloadCreateTemplate", + "order.pendingOrder.importOrdersFromExcel" + ], + "notes": [ + "新增 order.pendingOrder.downloadCreateTemplate:生成 Excel 导入模板,返回 base64 编码的 xlsx 文件,表头中带 * 的列为必填项(橙色背景),可选列为灰色背景,含示例数据行和填写说明工作表。", + "新增 order.pendingOrder.importOrdersFromExcel:接受 base64 编码的 xlsx 文件,按订单号分组,每组调用 createOrder 逻辑创建订单;不中断执行,逐条记录成功/失败结果返回。", + "多行相同订单号的行组成一个完整订单,每行代表一条商品明细;订单头信息(收件人、地址等)取每组第一行。", + "step 由货主策略 need_order_approval 决定(与 createOrder 一致);通过事务保证每个订单的主记录与明细原子写入。" + ], + "type": "added" + }, + { + "version": "2026.05.01-system-01", + "date": "2026-05-01", + "summary": "新增基础模块 IM 登录码接口文档:index.loginToIm", + "methods": [ + "index.loginToIm" + ], + "notes": [ + "新增 index.loginToIm 文档,入参为空对象({}),依赖当前登录用户上下文生成一次性 code。", + "响应增加 data.code 字段,长度固定 64 位(hex),默认有效期 5 分钟。", + "错误码补充:401(用户未登录)、400(用户信息不完整,缺 employees_id 或 employees_name)。", + "该接口仅做登录码签发,实际换取员工信息由 IM 侧 ssoCodeToId 完成并在成功后使 code 失效。" + ], + "type": "added" + }, + { + "version": "2026.05.01-system-03", + "date": "2026-05-01", + "summary": "扩展 index.loginToIm 返回字段:增加主体/主体类型/头像信息", + "methods": [ + "index.loginToIm" + ], + "notes": [ + "登录码签发接口响应新增 employees_id、employees_name、subject、store_type、avatar 字段。", + "subject 包含 id/name;store_type 严格取自 wms_store.project 字段,不再返回 subject_type 兼容字段。", + "同一批字段会写入 code 缓存,供 IM 侧 ssoCodeToId 换取并在成功后失效。" + ], + "type": "updated" + }, + { + "version": "2026.05.01-system-04", + "date": "2026-05-01", + "summary": "index.loginToIm 与 ssoCodeToId 改为严格字段模式,不再做兼容回退", + "methods": [ + "index.loginToIm" + ], + "notes": [ + "loginToIm 仅读取 ctx.user 标准字段:employees_id、employees_name、store_id、store_name、store_type、avatar。", + "不再兼容 id/real_name/username/company_name/avatar_url 等历史字段。", + "ssoCodeToId 返回值不再使用默认兜底,缺少关键字段时按 code 无效处理。" + ], + "type": "updated" + }, + { + "version": "2026.05.03-system-01", + "date": "2026-05-03", + "summary": "将 order.wave.fetch 调整为异步任务提交接口,删除同步返回抓取结果字段", + "methods": [ + "order.wave.fetch" + ], + "notes": [ + "接口从同步返回抓取结果改为提交任务并异步处理。", + "移除原方法中 result_list / total_request_quantity / total_fetched_quantity 等同步返回字段。" + ], + "type": "updated" + }, + { + "version": "2026.05.03-system-06", + "date": "2026-05-03", + "summary": "order.wave.batchList:新增 where 支持并限制传入字段", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "batchList 新增 where 支持及白名单过滤;禁止传入 warehouse_id/warehouseId。" + ], + "type": "updated" + }, + { + "version": "2026.05.03-system-08", + "date": "2026-05-03", + "summary": "order.pendingOrder.allocateStorage 改为异步提交", + "methods": [ + "order.pendingOrder.allocateStorage" + ], + "notes": [ + "接口变更为异步提交:调用后立即返回 request_id,后端异步执行储位分配;接口不再在响应中同步返回分配明细(如 requested_order_ids、allocated_order_ids 等)。客户端可后续通过任务 ID / 查询链路或事件获取最终分配结果。" + ], + "type": "updated" + }, + { + "version": "2026.05.03-system-10", + "date": "2026-05-03", + "summary": "新增订单批量移出波次接口", + "methods": [ + "order.wave.batchRemoveOrders" + ], + "notes": [ + "按订单ID批量移出波次;仅处理待处理订单表中非待审核订单(step in [1,2,3])。", + "操作在单事务内完成:清空订单的 wave_id/wave_no,并回写 wms_wave_batch 统计(重算 total_orders;当波次被清空时将 wave_status 置为 -1)。", + "仓库上下文来自当前登录用户(ctx.user.store_id)。" + ], + "type": "updated" + }, + { + "version": "2026.05.08-system-05", + "date": "2026-05-08", + "summary": "order.wave.batchList:新增 source 字段并支持 where.source 过滤,返回 list item 中新增 source 字段", + "methods": [ + "order.wave.batchList" + ], + "notes": [ + "新增 where.source(可选,number)用于按来源过滤:0=普通波次(正常后台操作),1=管理后台策略任务,2=PDA策略任务;不传则不过滤。", + "响应 list 每条记录新增字段 source(number),用于区分波次来源。", + "仅更新文档,业务代码不在此变更范围。" + ], + "type": "updated" + }, + { + "version": "2026.05.09-system-01", + "date": "2026-05-09", + "summary": "新增 order.wave.wavePickTaskCancelSelf;order.wave.waveStrategyList 新增预演计数字段/参数", + "methods": [ + "order.wave.wavePickTaskCancelSelf", + "order.wave.waveStrategyList" + ], + "notes": [ + "新增接口 `order.wave.wavePickTaskCancelSelf`:仅支持单个 `task_id`(number,必填),明确不支持 `task_ids` 批量参数。", + "业务约束:仅允许取消当前登录用户本人创建的拣货任务;若尝试取消非本人创建任务,接口应返回 400 错误(仅允许取消本人创建任务)。", + "返回建议:与现有取消接口风格一致,包含 `cancelled_count`(0/1)、`task_id`、`task_no`(若后端返回)或相应的取消结果汇总。", + "错误码建议:400 参数不合法(task_id 缺失或传了 task_ids);400 仅允许取消本人创建任务;500 取消失败。", + "新增参数:calculate_next_fetch_order_count(number,可选),含别名 calculateNextFetchOrderCount;取值 0=不计算(默认),1=计算并返回每条策略的 next_fetch_order_count,用于前端在策略列表中预览抓取量。", + "新增响应字段:list[*].next_fetch_order_count(number),含义:按当前策略口径预演一次自动抓取时,预计会选中的订单数量;当未开启计算时返回 0。" + ], + "type": "added" + }, + { + "version": "2026.05.11-system-01", + "date": "2026-05-11", + "summary": "新增字段 wave_prefix(策略层波次前缀),并补充 PDA 抓取波次号生成行为说明", + "methods": [ + "order.wave.waveStrategyList", + "order.wave.waveStrategyCreate", + "order.wave.waveStrategyUpdate", + "order.wave.waveStrategyFetchPda" + ], + "notes": [ + "在 wave strategy 对象中新增可选字段 wave_prefix:策略波次前缀,优先于仓库前缀。", + "校验规则:长度 1-5,仅允许 A-Z0-9;保存时会转为大写;为空时回退仓库前缀:团购使用 group_wave_prefix,散单使用 delete_order_wave_prefix。", + "在 order.wave.waveStrategyList 的返回 list[*] 中新增字段 wave_prefix(string)。", + "在 order.wave.waveStrategyCreate / waveStrategyUpdate 的入参中新增可选字段 wave_prefix(string),创建/更新成功后保存为大写且触发策略版本推进。", + "在 order.wave.waveStrategyFetchPda 的行为说明中补充:生成波次号(wave_no)时优先使用策略层 wave_prefix,否则按策略类型回退到仓库前缀;前缀校验同上。" + ], + "type": "updated" + }, + { + "version": "2026.05.15-system-01", + "date": "2026-05-15", + "summary": "仅更新文档:将 setting.express.create 入参与实现对齐(新增 express_code,移除 platform)", + "methods": [ + "setting.express.create" + ], + "notes": [ + "仅同步文档,与实现对齐,未修改任何业务代码或行为" + ], + "type": "updated" + }, + { + "version": "2026.05.15-system-02", + "date": "2026-05-15", + "summary": "新增 storage.report.search:库存流水统计报表,支持按时间闭区间过滤与按库位/按商品聚合", + "methods": [ + "storage.report.search" + ], + "notes": [ + "方法新增:storage.report.search", + "时间过滤为闭区间:created_at >= start_time 且 created_at <= end_time", + "当 where.by_space 为 false(默认)时,按商品+货主聚合(多个库位汇总);当为 true 时按商品+库位返回", + "不返回无流水的商品/键(仅返回在查询区间内出现过流水的数据)" + ], + "type": "added" + }, + { + "version": "2026.05.15-system-03", + "date": "2026-05-15", + "summary": "库存报表模块主入口迁移到 stock.report.search,storage.report.search 保持兼容别名", + "methods": [ + "stock.report.search", + "storage.report.search" + ], + "notes": [ + "新增主入口方法 stock.report.search,沿用既有报表统计口径(时间闭区间、by_space/store_ids、返回字段保持一致)。", + "保留 storage.report.search 作为兼容别名,并在描述中明确建议迁移到 stock.report.search。", + "仅更新 methods 文档配置,不修改业务代码。" + ], + "type": "updated" + }, + { + "version": "2026.05.15-system-04", + "date": "2026-05-15", + "summary": "文档主入口统一为 stock.report.search,storage.report.search 调整为兼容别名简述", + "methods": [ + "stock.report.search", + "storage.report.search" + ], + "notes": [ + "保留 stock.report.search 作为库存报表唯一完整文档入口。", + "storage.report.search 不再维护完整重复字段,仅保留迁移与兼容说明。", + "仅更新 methods 文档配置,不修改业务代码。" + ], + "type": "updated" + }, + { + "version": "2026.05.15-system-05", + "date": "2026-05-15", + "summary": "拆分 storage.report 模块并移除错误 stock.report.search 文档入口", + "methods": [ + "storage.report.search", + "stock.report.search" + ], + "notes": [ + "将库存报表从 storage.inventory 中拆分为独立模块 storage.report,storage.report.search 文档改为主入口语义(不再作为兼容别名)。", + "从 storage.inventory 分组中移除错误的 stock.report.search 文档入口以及兼容别名条目 storage.report.search。", + "最终归属:storage.report.search 属于模块 storage.report;stock.report.search 的文档入口已移除以避免混淆(代码实现保留于 app/service/systemMethods/storage/report.js 的 storage.report.search)。", + "仅修改文档,不修改应用代码实现。" + ], + "type": "updated" + }, + { + "version": "2026.05.15-system-06", + "date": "2026-05-15", + "summary": "storage.report.search 新增排序能力文档说明", + "methods": [ + "storage.report.search" + ], + "notes": [ + "补充 sort 参数:支持 sortField/sort_field、sortOrder/sort_order。", + "补充排序白名单:begin_total、inbound_total、outbound_total、end_total。", + "补充非法排序字段/顺序回退默认排序说明。", + "响应说明补充:已按 sort 规则排序返回。" + ], + "type": "updated" + }, + { + "version": "2026.05.16-system-01", + "date": "2026-05-16", + "summary": "新增 storage.report.export:按与 storage.report.search 相同条件导出库存报表 Excel", + "methods": [ + "storage.report.export" + ], + "notes": [ + "新增方法:storage.report.export,复用 storage.report.search 的 where/sort 查询条件。", + "导出文件包含两个 sheet:汇总、变更记录。", + "用于在统计结果基础上回溯明细流水,提升库存变动追溯效率。" + ], + "type": "added" + }, + { + "version": "2026.05.16-system-02", + "date": "2026-05-16", + "summary": "storage.report.export 改为异步任务 + 新增 exportTaskProgress", + "methods": [ + "storage.report.export", + "storage.report.exportTaskProgress" + ], + "notes": [ + "调用方式调整为两步:先调用 storage.report.export 提交任务并获取 task_id,再调用 storage.report.exportTaskProgress 轮询任务进度。", + "下载链接获取方式:当 status=success 时,从 exportTaskProgress 响应的 download_url 字段获取导出文件地址。", + "任务状态值补充:submitted/running/success/failed/not_found。" + ], + "type": "updated" + } ] diff --git a/methods/system.json b/methods/system.json index 51a08b2..471d928 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,8 +1,8 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "2026.05.08-system-05", - "updatedAt": "2026-05-08", + "version": "2026.05.16-system-02", + "updatedAt": "2026-05-16", "headers": [ { "name": "platform", @@ -33,6 +33,10 @@ { "value": "other", "name": "其他" + }, + { + "value": "workerstation", + "name": "工作台" } ] }, @@ -6904,7 +6908,7 @@ { "name": "platforms", "type": "array", - "description": "波次下的平台分组", + "description": "按平台和系统快递分组后的订单列表", "children": [ { "name": "platform", @@ -6919,12 +6923,22 @@ { "name": "order_count", "type": "number", - "description": "该平台订单数" + "description": "该平台+系统快递分组的订单数" + }, + { + "name": "sys_logistics_code", + "type": "string", + "description": "系统快递编码" + }, + { + "name": "sys_logistics_name", + "type": "string", + "description": "系统快递名称" }, { "name": "orders", "type": "array", - "description": "订单列表(逐单中间态)", + "description": "该分组内的订单列表(逐单中间态,字段同平台层 orders 中元素)", "children": [ { "name": "wave_id", @@ -7103,7 +7117,7 @@ "list": [ { "method": "print.send", - "description": "发送打印任务到打印电脑,并记录打印单", + "description": "发送打印任务到打印电脑,并记录打印单。说明:当 type=express 时,接口按 data.waveGroups(来源于 order.print.getWavePlatformPrintData 返回的 data.waveGroups)进行处理,按 waveGroups -> platforms 串行处理,每个平台+快递 组分别发送;返回沿用现有简要风格,不返回明细。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -7118,37 +7132,37 @@ { "name": "computerId", "type": "string", - "required": true, + "required": false, "source": "body", - "description": "打印电脑 ID" + "description": "打印电脑 ID;历史/customize 分支可能使用。注意:type=express 场景下不适用(该字段不再作为 express 路径的必填或传输约束)。" }, { "name": "count", "type": "number", "required": false, "source": "body", - "description": "打印份数,可选" + "description": "打印份数;对 type=customize 有效。type=express 场景下不保留,相应字段会被忽略。" }, { "name": "data", "type": "object", "required": true, "source": "body", - "description": "打印业务数据对象,字段由模板和 type 决定" + "description": "打印业务数据对象。对于 type=express:必须提供 data.waveGroups(来源于 order.print.getWavePlatformPrintData 的返回值 data.waveGroups),接口按 waveGroups->platforms 串行处理,每个 平台+快递 组分别发送;对于 type=customize,data 的具体字段由模板决定。" }, { "name": "printer", "type": "string", - "required": true, + "required": false, "source": "body", - "description": "打印机名称" + "description": "打印机名称;type=customize 使用。type=express 下忽略(由快递平台/站点决定打印目标)。" }, { "name": "template", "type": "object", "required": false, "source": "body", - "description": "打印模板对象;仅 type=customize 时必填且应包含 page_width、page_height、template_content,type=express 可不传", + "description": "打印模板对象;仅 type=customize 时必填且应包含 page_width、page_height、template_content。type=express 场景下忽略 template 字段。", "children": [ { "name": "page_width", @@ -7175,14 +7189,28 @@ "type": "string", "required": false, "source": "body", - "description": "业务时间戳,可选" + "description": "业务时间戳;历史字段。type=express 场景下不适用。" }, { "name": "type", "type": "string", "required": true, "source": "body", - "description": "打印类型;当前实现支持 customize、express" + "description": "打印类型;支持 customize、express。对于 express 场景,必须遵守下列额外约束:提供 printStationId、requestCode,并在 data.waveGroups 中传入来自 order.print.getWavePlatformPrintData 的 waveGroups 数据。" + }, + { + "name": "printStationId", + "type": "string", + "required": true, + "source": "body", + "description": "打印站点/工作站标识(必填,type=express 时必须提供),用于指示目标打印站或分发单元。" + }, + { + "name": "requestCode", + "type": "string", + "required": true, + "source": "body", + "description": "请求去重/防重放 ID(必填,type=express 时必须提供)。接口约束:requestCode 在约定周期内不得变更(例如一次批次/会话期间),系统在同一次请求处理范围内保证对重复 requestCode 进行防重放处理;此保护仅保证同一次请求内的去重/防重放,不等同于跨请求的强幂等保证。" } ], "response": [ @@ -7204,7 +7232,7 @@ { "name": "printId", "type": "number", - "description": "打印记录 ID;任务入库成功后返回,失败时若已生成记录也会返回" + "description": "打印记录 ID;任务入库成功后返回,失败时若已生成记录也会返回。接口在 express 场景下不返回明细结果,只给出调用结果摘要。" } ], "errors": [ @@ -7420,23 +7448,67 @@ "required": true, "description": "打印台原始记录(PrintStation raw),字段示例", "children": [ - { "name": "id", "type": "number", "description": "打印台 ID" }, - { "name": "name", "type": "string", "description": "打印台名称" }, - { "name": "computer_id", "type": "number", "description": "关联打印电脑 ID" }, - { "name": "custom_barcode", "type": "string", "description": "自定义条码" }, - { "name": "default_printer_name", "type": "string", "description": "默认打印机名称" }, - { "name": "subject_config", "type": "object", "description": "打印台 subject_config 配置(见下文)" }, - { "name": "create_at", "type": "string", "description": "创建时间" }, - { "name": "update_at", "type": "string", "description": "更新时间" }, - { "name": "deleted", "type": "number", "description": "软删除标识,1=已删除" }, - { "name": "warehouse_id", "type": "number", "description": "所属仓库 ID" } + { + "name": "id", + "type": "number", + "description": "打印台 ID" + }, + { + "name": "name", + "type": "string", + "description": "打印台名称" + }, + { + "name": "computer_id", + "type": "number", + "description": "关联打印电脑 ID" + }, + { + "name": "custom_barcode", + "type": "string", + "description": "自定义条码" + }, + { + "name": "default_printer_name", + "type": "string", + "description": "默认打印机名称" + }, + { + "name": "subject_config", + "type": "object", + "description": "打印台 subject_config 配置(见下文)" + }, + { + "name": "create_at", + "type": "string", + "description": "创建时间" + }, + { + "name": "update_at", + "type": "string", + "description": "更新时间" + }, + { + "name": "deleted", + "type": "number", + "description": "软删除标识,1=已删除" + } ] } ], "errors": [ - { "code": "400", "description": "参数错误:缺少 id 或 id 格式不正确" }, - { "code": "404", "description": "打印台不存在" }, - { "code": "500", "description": "内部错误" } + { + "code": "400", + "description": "参数错误:缺少 id 或 id 格式不正确" + }, + { + "code": "404", + "description": "打印台不存在" + }, + { + "code": "500", + "description": "内部错误" + } ] }, { @@ -7453,10 +7525,34 @@ } ], "params": [ - { "name": "computer_id", "type": "number", "required": true, "source": "body", "description": "关联的打印电脑 ID(必填)" }, - { "name": "name", "type": "string", "required": true, "source": "body", "description": "打印台名称(必填)" }, - { "name": "custom_barcode", "type": "string", "required": false, "source": "body", "description": "自定义条码" }, - { "name": "default_printer_name", "type": "string", "required": false, "source": "body", "description": "默认打印机名称" }, + { + "name": "computer_id", + "type": "number", + "required": true, + "source": "body", + "description": "关联的打印电脑 ID(必填)" + }, + { + "name": "name", + "type": "string", + "required": true, + "source": "body", + "description": "打印台名称(必填)" + }, + { + "name": "custom_barcode", + "type": "string", + "required": false, + "source": "body", + "description": "自定义条码" + }, + { + "name": "default_printer_name", + "type": "string", + "required": false, + "source": "body", + "description": "默认打印机名称" + }, { "name": "subject_config", "type": "object", @@ -7469,19 +7565,40 @@ "type": "array", "description": "快递与打印机绑定数组,数组项仅包含 { express_code, printer_name }", "children": [ - { "name": "express_code", "type": "string", "required": true, "description": "快递编码,必填" }, - { "name": "printer_name", "type": "string", "required": true, "description": "打印机名称,必填" } + { + "name": "express_code", + "type": "string", + "required": true, + "description": "快递编码,必填" + }, + { + "name": "printer_name", + "type": "string", + "required": true, + "description": "打印机名称,必填" + } ] } ] } ], "response": [ - { "name": "data", "type": "object", "required": true, "description": "新建的打印台对象(raw)" } + { + "name": "data", + "type": "object", + "required": true, + "description": "新建的打印台对象(raw)" + } ], "errors": [ - { "code": "400", "description": "参数错误:缺少必填字段(computer_id/name)或 subject_config 格式不合法" }, - { "code": "500", "description": "创建失败或内部错误" } + { + "code": "400", + "description": "参数错误:缺少必填字段(computer_id/name)或 subject_config 格式不合法" + }, + { + "code": "500", + "description": "创建失败或内部错误" + } ] }, { @@ -7530,11 +7647,41 @@ } ], "params": [ - { "name": "id", "type": "number", "required": true, "source": "body", "description": "打印台 ID(必填)" }, - { "name": "computer_id", "type": "number", "required": false, "source": "body", "description": "要更新的打印电脑 ID" }, - { "name": "custom_barcode", "type": "string", "required": false, "source": "body", "description": "自定义条码" }, - { "name": "name", "type": "string", "required": false, "source": "body", "description": "打印台名称" }, - { "name": "default_printer_name", "type": "string", "required": false, "source": "body", "description": "默认打印机名称" }, + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "打印台 ID(必填)" + }, + { + "name": "computer_id", + "type": "number", + "required": false, + "source": "body", + "description": "要更新的打印电脑 ID" + }, + { + "name": "custom_barcode", + "type": "string", + "required": false, + "source": "body", + "description": "自定义条码" + }, + { + "name": "name", + "type": "string", + "required": false, + "source": "body", + "description": "打印台名称" + }, + { + "name": "default_printer_name", + "type": "string", + "required": false, + "source": "body", + "description": "默认打印机名称" + }, { "name": "subject_config", "type": "object", @@ -7547,20 +7694,44 @@ "type": "array", "description": "快递-打印机绑定数组,数组项仅包含 { express_code, printer_name }", "children": [ - { "name": "express_code", "type": "string", "required": true, "description": "快递编码,必填" }, - { "name": "printer_name", "type": "string", "required": true, "description": "打印机名称,必填" } + { + "name": "express_code", + "type": "string", + "required": true, + "description": "快递编码,必填" + }, + { + "name": "printer_name", + "type": "string", + "required": true, + "description": "打印机名称,必填" + } ] } ] } ], "response": [ - { "name": "data", "type": "object", "required": false, "description": "更新结果,通常返回 null" } + { + "name": "data", + "type": "object", + "required": false, + "description": "更新结果,通常返回 null" + } ], "errors": [ - { "code": "400", "description": "参数错误(缺少 id 或 subject_config 格式不合法)" }, - { "code": "404", "description": "打印台不存在" }, - { "code": "500", "description": "更新失败或内部错误" } + { + "code": "400", + "description": "参数错误(缺少 id 或 subject_config 格式不合法)" + }, + { + "code": "404", + "description": "打印台不存在" + }, + { + "code": "500", + "description": "更新失败或内部错误" + } ] }, { @@ -7586,11 +7757,22 @@ } ], "response": [ - { "name": "data", "type": "object", "required": false, "description": "返回空数据结构,表示操作成功" } + { + "name": "data", + "type": "object", + "required": false, + "description": "返回空数据结构,表示操作成功" + } ], "errors": [ - { "code": "400", "description": "参数错误:ids 必须为非空数组" }, - { "code": "500", "description": "删除失败或内部错误" } + { + "code": "400", + "description": "参数错误:ids 必须为非空数组" + }, + { + "code": "500", + "description": "删除失败或内部错误" + } ] }, { @@ -7614,16 +7796,38 @@ "required": true, "description": "打印电脑数组,每项为打印电脑的原始记录", "children": [ - { "name": "id", "type": "number", "description": "打印电脑 ID" }, - { "name": "name", "type": "string", "description": "打印电脑名称或标识" }, - { "name": "status", "type": "number", "description": "状态,1=启用" }, - { "name": "warehouse_id", "type": "number", "description": "所属仓库 ID" } + { + "name": "id", + "type": "number", + "description": "打印电脑 ID" + }, + { + "name": "name", + "type": "string", + "description": "打印电脑名称或标识" + }, + { + "name": "status", + "type": "number", + "description": "状态,1=启用" + }, + { + "name": "warehouse_id", + "type": "number", + "description": "所属仓库 ID" + } ] } ], "errors": [ - { "code": "400", "description": "未识别到当前仓库上下文" }, - { "code": "500", "description": "查询失败或内部错误" } + { + "code": "400", + "description": "未识别到当前仓库上下文" + }, + { + "code": "500", + "description": "查询失败或内部错误" + } ] }, { @@ -7649,11 +7853,22 @@ } ], "response": [ - { "name": "data", "type": "array", "required": true, "description": "打印机数组,通常为字符串名称数组或打印机对象数组(取决于 redis 存储格式)" } + { + "name": "data", + "type": "array", + "required": true, + "description": "打印机数组,通常为字符串名称数组或打印机对象数组(取决于 redis 存储格式)" + } ], "errors": [ - { "code": "400", "description": "参数错误:缺少 id" }, - { "code": "500", "description": "读取 Redis 或解析数据失败" } + { + "code": "400", + "description": "参数错误:缺少 id" + }, + { + "code": "500", + "description": "读取 Redis 或解析数据失败" + } ] }, { @@ -7670,7 +7885,13 @@ } ], "params": [ - { "name": "defaultPrinter", "type": "string", "required": true, "source": "body", "description": "默认打印机名称(必填),会写入打印台的 `default_printer_name` 字段" }, + { + "name": "defaultPrinter", + "type": "string", + "required": true, + "source": "body", + "description": "默认打印机名称(必填),会写入打印台的 `default_printer_name` 字段" + }, { "name": "express", "type": "array", @@ -7678,21 +7899,61 @@ "source": "body", "description": "快递与打印机绑定数组(必填)。每项应包含首选字段 `express_code`(string)和 `printer_name`(string)。为兼容历史字段,也接受 `express_id`(可映射为 `express_code`)和 `name`(可映射为 `printer_name`)。接口实现会将结果序列化后写入打印台的 `subject_config.express_bind_printer`。", "children": [ - { "name": "express_code", "type": "string", "required": false, "description": "首选:快递编码(string),实现中优先使用该字段" }, - { "name": "printer_name", "type": "string", "required": false, "description": "首选:打印机名称(string),实现中优先使用该字段" }, - { "name": "express_id", "type": "number|string", "required": false, "description": "兼容字段:历史的 express_id,可映射为 express_code 使用" }, - { "name": "name", "type": "string", "required": false, "description": "兼容字段:历史的 name,可映射为 printer_name 使用" } + { + "name": "express_code", + "type": "string", + "required": false, + "description": "首选:快递编码(string),实现中优先使用该字段" + }, + { + "name": "printer_name", + "type": "string", + "required": false, + "description": "首选:打印机名称(string),实现中优先使用该字段" + }, + { + "name": "express_id", + "type": "number|string", + "required": false, + "description": "兼容字段:历史的 express_id,可映射为 express_code 使用" + }, + { + "name": "name", + "type": "string", + "required": false, + "description": "兼容字段:历史的 name,可映射为 printer_name 使用" + } ] }, - { "name": "print_station_id", "type": "number", "required": true, "source": "body", "description": "目标打印台 ID(必填)。接口会根据此 ID 更新对应打印台记录的 default_printer_name 与 subject_config.express_bind_printer" } + { + "name": "print_station_id", + "type": "number", + "required": true, + "source": "body", + "description": "目标打印台 ID(必填)。接口会根据此 ID 更新对应打印台记录的 default_printer_name 与 subject_config.express_bind_printer" + } ], "response": [ - { "name": "data", "type": "object", "required": false, "description": "成功不返回业务数据,语义为成功(实现中返回 { data: null, code: 0 })" } + { + "name": "data", + "type": "object", + "required": false, + "description": "成功不返回业务数据,语义为成功(实现中返回 { data: null, code: 0 })" + } ], "errors": [ - { "code": "400", "description": "参数错误:defaultPrinter/express/print_station_id 格式或缺失" }, - { "code": "404", "description": "打印台不存在:未找到对应 print_station_id 的打印台记录" }, - { "code": "500", "description": "保存失败或内部错误" } + { + "code": "400", + "description": "参数错误:defaultPrinter/express/print_station_id 格式或缺失" + }, + { + "code": "404", + "description": "打印台不存在:未找到对应 print_station_id 的打印台记录" + }, + { + "code": "500", + "description": "保存失败或内部错误" + } ] } ] @@ -8229,7 +8490,7 @@ }, { "method": "setting.express.create", - "description": "创建快递映射,仅写入已实现字段(code、name、platform 等)", + "description": "创建快递映射,仅写入已实现字段(code、name、express_code 等)", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -8246,21 +8507,21 @@ "type": "string", "required": true, "source": "body", - "description": "快递编码" + "description": "快递映射编码;接口会转为大写" }, { "name": "name", "type": "string", "required": true, "source": "body", - "description": "快递名称" + "description": "快递名称(最大 50 字符)" }, { - "name": "platform", + "name": "express_code", "type": "string", - "required": false, + "required": true, "source": "body", - "description": "平台标识(可选)" + "description": "系统快递编码;同时支持驼峰写法 expressCode" } ], "response": [], @@ -8300,7 +8561,7 @@ }, { "method": "setting.express.update", - "description": "更新快递映射,仅更新已实现字段(例如 name、platform)", + "description": "更新快递映射。必须提供 `id`(必填),且至少提供 `code`、`name` 或 `express_code` 中的一个用于更新;同时支持 `expressCode` 驼峰写法。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -8317,25 +8578,100 @@ "type": "number", "required": true, "source": "body", - "description": "快递记录ID" + "description": "快递记录ID;也兼容别名 `setting_id` / `settingId`" + }, + { + "name": "code", + "type": "string", + "required": false, + "source": "body", + "description": "快递映射编码(最大 50 字符,接口会大写化并校验在当前仓库的唯一性)" }, { "name": "name", "type": "string", "required": false, "source": "body", - "description": "快递名称" + "description": "快递名称(最大 50 字符)" }, { - "name": "platform", + "name": "express_code", "type": "string", "required": false, "source": "body", - "description": "平台标识(可选)" + "description": "系统快递编码(必须为系统已存在的编码);支持 `expressCode` 驼峰写法" } ], - "response": [], - "errors": [] + "response": [ + { + "name": "data", + "type": "object", + "required": true, + "description": "更新后的快递映射对象(规范化字段)", + "children": [ + { + "name": "id", + "type": "number", + "description": "记录ID" + }, + { + "name": "warehouse_id", + "type": "number", + "description": "所属仓库ID" + }, + { + "name": "code", + "type": "string", + "description": "快递映射编码" + }, + { + "name": "name", + "type": "string", + "description": "快递名称" + }, + { + "name": "express_code", + "type": "string", + "description": "系统快递编码" + }, + { + "name": "express_name", + "type": "string", + "description": "系统快递名称(从系统快递表映射)" + } + ] + } + ], + "errors": [ + { + "code": "400", + "message": "id 参数不能为空" + }, + { + "code": "400", + "message": "至少需要提供一个可更新字段" + }, + { + "code": "400", + "message": "code 参数不能为空" + }, + { + "code": "400", + "message": "express_code 参数不能为空" + }, + { + "code": "400", + "message": "系统快递编码不存在" + }, + { + "code": "404", + "message": "快递映射不存在或无权限操作" + }, + { + "code": "409", + "message": "快递编码已被当前仓库使用" + } + ] }, { "method": "setting.express.delete", @@ -10814,13 +11150,41 @@ "type": "object", "description": "拣货任务主表(精简字段)", "children": [ - { "name": "task_id", "type": "number", "description": "任务ID" }, - { "name": "task_no", "type": "string", "description": "任务编号" }, - { "name": "status", "type": "number", "description": "任务状态" }, - { "name": "pick_mode", "type": "number", "description": "拣货模式" }, - { "name": "start_at", "type": "string", "description": "开始时间(ISO 字符串或 null)" }, - { "name": "finish_at", "type": "string", "description": "完成时间(ISO 字符串或 null)" }, - { "name": "batch_no", "type": "string", "description": "批次号" } + { + "name": "task_id", + "type": "number", + "description": "任务ID" + }, + { + "name": "task_no", + "type": "string", + "description": "任务编号" + }, + { + "name": "status", + "type": "number", + "description": "任务状态" + }, + { + "name": "pick_mode", + "type": "number", + "description": "拣货模式" + }, + { + "name": "start_at", + "type": "string", + "description": "开始时间(ISO 字符串或 null)" + }, + { + "name": "finish_at", + "type": "string", + "description": "完成时间(ISO 字符串或 null)" + }, + { + "name": "batch_no", + "type": "string", + "description": "批次号" + } ] }, { @@ -10828,14 +11192,46 @@ "type": "array", "description": "箱列表;包含用于前端展示与拣货进度的统计字段", "children": [ - { "name": "task_id", "type": "number", "description": "任务ID" }, - { "name": "box_id", "type": "number", "description": "箱ID" }, - { "name": "box_no", "type": "string", "description": "箱编码" }, - { "name": "box_type", "type": "number", "description": "箱类型" }, - { "name": "status", "type": "number", "description": "箱状态" }, - { "name": "ref_label", "type": "string", "description": "箱参考标签或关联业务标识(用于前端定位/关联)" }, - { "name": "required_qty", "type": "number", "description": "箱内需要拣货的总数量" }, - { "name": "picked_qty", "type": "number", "description": "当前已完成拣货的数量" } + { + "name": "task_id", + "type": "number", + "description": "任务ID" + }, + { + "name": "box_id", + "type": "number", + "description": "箱ID" + }, + { + "name": "box_no", + "type": "string", + "description": "箱编码" + }, + { + "name": "box_type", + "type": "number", + "description": "箱类型" + }, + { + "name": "status", + "type": "number", + "description": "箱状态" + }, + { + "name": "ref_label", + "type": "string", + "description": "箱参考标签或关联业务标识(用于前端定位/关联)" + }, + { + "name": "required_qty", + "type": "number", + "description": "箱内需要拣货的总数量" + }, + { + "name": "picked_qty", + "type": "number", + "description": "当前已完成拣货的数量" + } ] }, { @@ -10843,29 +11239,93 @@ "type": "array", "description": "拣货明细列表(按库位/商品/数量拆分),用于从明细视角展示拣货要求", "children": [ - { "name": "order_id", "type": "number", "description": "订单ID" }, - { "name": "order_item_id", "type": "number", "description": "订单行ID" }, - { "name": "quantity", "type": "number", "description": "本行需拣货数量" }, - { "name": "storage_id", "type": "number", "description": "仓库ID" }, - { "name": "space_id", "type": "number", "description": "库位ID" }, - { "name": "space_name", "type": "string", "description": "库位名称" }, + { + "name": "order_id", + "type": "number", + "description": "订单ID" + }, + { + "name": "order_item_id", + "type": "number", + "description": "订单行ID" + }, + { + "name": "quantity", + "type": "number", + "description": "本行需拣货数量" + }, + { + "name": "storage_id", + "type": "number", + "description": "仓库ID" + }, + { + "name": "space_id", + "type": "number", + "description": "库位ID" + }, + { + "name": "space_name", + "type": "string", + "description": "库位名称" + }, { "name": "location_space", "type": "object", "description": "库位扩展信息(当存在时返回)", "children": [ - { "name": "space_code", "type": "string", "description": "库位编码" }, - { "name": "custom_name", "type": "string", "description": "库位自定义名称" }, - { "name": "custom_barcode", "type": "string", "description": "库位自定义条码" }, - { "name": "pick_sequence", "type": "number", "description": "拣货序列,用于路线/优先级排序" }, - { "name": "pick_priority", "type": "number", "description": "拣货优先级(数值越小优先级越高)" } + { + "name": "space_code", + "type": "string", + "description": "库位编码" + }, + { + "name": "custom_name", + "type": "string", + "description": "库位自定义名称" + }, + { + "name": "custom_barcode", + "type": "string", + "description": "库位自定义条码" + }, + { + "name": "pick_sequence", + "type": "number", + "description": "拣货序列,用于路线/优先级排序" + }, + { + "name": "pick_priority", + "type": "number", + "description": "拣货优先级(数值越小优先级越高)" + } ] }, - { "name": "item_code", "type": "string", "description": "商品编码" }, - { "name": "item_name", "type": "string", "description": "商品名称" }, - { "name": "stock_id", "type": "number", "description": "库存记录ID(stock 主键)" }, - { "name": "plan_qty", "type": "number", "description": "计划拣货数量(用于与实际拣货对比)" }, - { "name": "item_snapshot", "type": "object", "description": "商品快照(下单时的商品信息,可能包含规格/属性等)" } + { + "name": "item_code", + "type": "string", + "description": "商品编码" + }, + { + "name": "item_name", + "type": "string", + "description": "商品名称" + }, + { + "name": "stock_id", + "type": "number", + "description": "库存记录ID(stock 主键)" + }, + { + "name": "plan_qty", + "type": "number", + "description": "计划拣货数量(用于与实际拣货对比)" + }, + { + "name": "item_snapshot", + "type": "object", + "description": "商品快照(下单时的商品信息,可能包含规格/属性等)" + } ] }, { @@ -10873,64 +11333,168 @@ "type": "object", "description": "对 picking_details 的汇总信息,用于统计与前端显示", "children": [ - { "name": "total_lines", "type": "number", "description": "明细行数(picking_details.length)" }, - { "name": "total_qty", "type": "number", "description": "明细总数量(quantity 汇总)" }, - { "name": "distinct_spaces", "type": "number", "description": "涉及的不同库位数量" }, - { "name": "distinct_items", "type": "number", "description": "涉及的不同商品数量" } + { + "name": "total_lines", + "type": "number", + "description": "明细行数(picking_details.length)" + }, + { + "name": "total_qty", + "type": "number", + "description": "明细总数量(quantity 汇总)" + }, + { + "name": "distinct_spaces", + "type": "number", + "description": "涉及的不同库位数量" + }, + { + "name": "distinct_items", + "type": "number", + "description": "涉及的不同商品数量" + } ] }, { "name": "picking_view", - "type": "object", - "description": "按 pick_mode 区分的 picking_view 形态输出(五种形态);用于前端按任务类型展示聚合视图。", + "type": "object", + "description": "按 pick_mode 区分的 picking_view 形态输出(五种形态);用于前端按任务类型展示聚合视图。", + "children": [ + { + "name": "mode_code", + "type": "number", + "description": "拣货视图模式编码,与 task.pick_mode 对应" + }, + { + "name": "mode_name", + "type": "string", + "description": "拣货视图模式名称" + }, + { + "name": "require_box_allocations", + "type": "boolean", + "description": "当前模式是否需要箱分配;pick_mode=1/3/4 时为 true,pick_mode=2/5 时为 false" + }, + { + "name": "group_by", + "type": "string", + "description": "分组字段,示例值:\"space+item\"" + }, + { + "name": "sort_by", + "type": "array", + "description": "排序字段数组,典型为 [\"pick_sequence\",\"pick_priority\",\"space_id\",\"item_code\"]" + }, + { + "name": "items", + "type": "array", + "description": "分组后的拣货项数组(按库位+商品聚合)", "children": [ - { "name": "mode_code", "type": "number", "description": "拣货视图模式编码,与 task.pick_mode 对应" }, - { "name": "mode_name", "type": "string", "description": "拣货视图模式名称" }, - { "name": "require_box_allocations", "type": "boolean", "description": "当前模式是否需要箱分配;pick_mode=1/3/4 时为 true,pick_mode=2/5 时为 false" }, - { "name": "group_by", "type": "string", "description": "分组字段,示例值:\"space+item\"" }, - { "name": "sort_by", "type": "array", "description": "排序字段数组,典型为 [\"pick_sequence\",\"pick_priority\",\"space_id\",\"item_code\"]" }, { - "name": "items", - "type": "array", - "description": "分组后的拣货项数组(按库位+商品聚合)", + "name": "space_id", + "type": "number", + "description": "库位 ID" + }, + { + "name": "space_name", + "type": "string", + "description": "库位名称" + }, + { + "name": "location_space", + "type": "object", + "description": "库位扩展信息(同 picking_details.location_space 结构)", "children": [ - { "name": "space_id", "type": "number", "description": "库位 ID" }, - { "name": "space_name", "type": "string", "description": "库位名称" }, { - "name": "location_space", - "type": "object", - "description": "库位扩展信息(同 picking_details.location_space 结构)", - "children": [ - { "name": "space_code", "type": "string", "description": "库位编码" }, - { "name": "custom_name", "type": "string", "description": "库位自定义名称" }, - { "name": "custom_barcode", "type": "string", "description": "库位自定义条码" }, - { "name": "pick_sequence", "type": "number", "description": "拣货序列,用于路线/优先级排序" }, - { "name": "pick_priority", "type": "number", "description": "拣货优先级(数值越小优先)" } - ] + "name": "space_code", + "type": "string", + "description": "库位编码" }, - { "name": "item_code", "type": "string", "description": "商品编码" }, - { "name": "item_name", "type": "string", "description": "商品名称" }, - { "name": "stock_id", "type": "number", "description": "库存记录ID(stock 主键)" }, - { "name": "total_qty", "type": "number", "description": "该库位该商品的总需拣货数量" }, { - "name": "box_allocations", - "type": "array", - "description": "与该库位/商品相关的箱分配列表(当 require_box_allocations=true 时返回)", - "children": [ - { "name": "box_id", "type": "number", "description": "箱ID" }, - { "name": "box_no", "type": "string", "description": "箱编码" }, - { "name": "box_type", "type": "number", "description": "箱类型" }, - { "name": "required_qty", "type": "number", "description": "该箱分配需要拣货的数量" }, - { "name": "picked_qty", "type": "number", "description": "该箱已完成拣货的数量" }, - { "name": "allocated_qty", "type": "number", "description": "该箱已分配的数量(由后端分配)" } - ] + "name": "custom_name", + "type": "string", + "description": "库位自定义名称" + }, + { + "name": "custom_barcode", + "type": "string", + "description": "库位自定义条码" + }, + { + "name": "pick_sequence", + "type": "number", + "description": "拣货序列,用于路线/优先级排序" + }, + { + "name": "pick_priority", + "type": "number", + "description": "拣货优先级(数值越小优先)" + } + ] + }, + { + "name": "item_code", + "type": "string", + "description": "商品编码" + }, + { + "name": "item_name", + "type": "string", + "description": "商品名称" + }, + { + "name": "stock_id", + "type": "number", + "description": "库存记录ID(stock 主键)" + }, + { + "name": "total_qty", + "type": "number", + "description": "该库位该商品的总需拣货数量" + }, + { + "name": "box_allocations", + "type": "array", + "description": "与该库位/商品相关的箱分配列表(当 require_box_allocations=true 时返回)", + "children": [ + { + "name": "box_id", + "type": "number", + "description": "箱ID" + }, + { + "name": "box_no", + "type": "string", + "description": "箱编码" + }, + { + "name": "box_type", + "type": "number", + "description": "箱类型" + }, + { + "name": "required_qty", + "type": "number", + "description": "该箱分配需要拣货的数量" + }, + { + "name": "picked_qty", + "type": "number", + "description": "该箱已完成拣货的数量" + }, + { + "name": "allocated_qty", + "type": "number", + "description": "该箱已分配的数量(由后端分配)" } ] } ] } - ], - "errors": [ + ] + } + ], + "errors": [ { "code": "400", "description": "task_id 缺失或不合法" @@ -13085,6 +13649,450 @@ } ] }, + { + "groupName": "库存报表模块", + "module": "storage.report", + "list": [ + { + "method": "storage.report.search", + "description": "库存报表查询(主入口):按时间闭区间统计商品出入库并支持按库位或按商品聚合", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "查询条件对象。支持字段:start_time(闭区间下限)、end_time(闭区间上限)、by_space(是否按库位返回,默认 false)、store_ids(货主ID数组)。仅返回在时间区间内存在流水的数据(无流水键不返回)。" + }, + { + "name": "where.start_time", + "type": "string", + "required": false, + "source": "body", + "description": "开始时间,支持字符串/Date;用于闭区间过滤:created_at >= start_time" + }, + { + "name": "where.end_time", + "type": "string", + "required": false, + "source": "body", + "description": "结束时间,支持字符串/Date;用于闭区间过滤:created_at <= end_time" + }, + { + "name": "where.by_space", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否按库位返回,默认 false。false=按商品+货主聚合(多库位汇总),true=按商品+库位+货主返回;当 where.by_space=true 时,额外返回 space_id、space_name(custom_name 优先,否则使用 space_code)。" + }, + { + "name": "where.store_ids", + "type": "array", + "required": false, + "source": "body", + "description": "货主ID数组,用于过滤特定货主(空或未传表示不过滤)", + "list": [] + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数对象(请求体 data.sort)。支持 data.sort.sortField / data.sort.sort_field 与 data.sort.sortOrder / data.sort.sort_order;sortField 白名单:begin_total、inbound_total、outbound_total、end_total;sortOrder 支持 ASC / DESC(大小写不敏感);非法字段或顺序将回退默认排序。" + }, + { + "name": "sort.sortField", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序字段(兼容 data.sort.sortField)。白名单:begin_total、inbound_total、outbound_total、end_total;非法值回退默认排序。" + }, + { + "name": "sort.sort_field", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序字段下划线别名(兼容 data.sort.sort_field),规则同 sort.sortField。" + }, + { + "name": "sort.sortOrder", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序方向(兼容 data.sort.sortOrder),支持 ASC / DESC(大小写不敏感);非法值回退默认排序。" + }, + { + "name": "sort.sort_order", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序方向下划线别名(兼容 data.sort.sort_order),规则同 sort.sortOrder。" + } + ], + "response": [ + { + "name": "data.list", + "type": "array", + "required": true, + "description": "匹配到的报表行列表\n已按 sort 规则排序返回。" + }, + { + "name": "data.list[]", + "type": "object", + "required": true, + "description": "单条报表记录字段", + "children": [ + { + "name": "start_time", + "type": "string", + "description": "请求时传入的 start_time(或 null)" + }, + { + "name": "end_time", + "type": "string", + "description": "请求时传入的 end_time(或 null)" + }, + { + "name": "store_name", + "type": "string", + "description": "货主名称" + }, + { + "name": "item_name", + "type": "string", + "description": "商品名称" + }, + { + "name": "barcode", + "type": "string", + "description": "商品条码(逗号分隔)" + }, + { + "name": "item_code", + "type": "string", + "description": "商品编码" + }, + { + "name": "begin_total", + "type": "number", + "description": "期初库存量:取 start_time 前最后一条记录的 after_quantity(若 start_time 未传,默认为 0)" + }, + { + "name": "end_total", + "type": "number", + "description": "期末库存量:取 end_time 时点(<= end_time)最后一条记录的 after_quantity(若 end_time 未传则取最近一条)" + }, + { + "name": "inbound_total", + "type": "number", + "description": "在查询区间内累计入库数(INBOUND)" + }, + { + "name": "outbound_total", + "type": "number", + "description": "在查询区间内累计出库数(OUTBOUND)" + }, + { + "name": "stock_id", + "type": "number", + "description": "商品库存记录ID(stock_warehouse.id)" + }, + { + "name": "store_id", + "type": "number", + "description": "货主ID" + }, + { + "name": "begin_total", + "type": "number", + "description": "期初库存(数值)" + }, + { + "name": "end_total", + "type": "number", + "description": "期末库存(数值)" + }, + { + "name": "inbound_total", + "type": "number", + "description": "入库合计" + }, + { + "name": "outbound_total", + "type": "number", + "description": "出库合计" + }, + { + "name": "by_space_mode", + "type": "string", + "description": "说明当前返回模式:'by_space' 或 'by_product'" + }, + { + "name": "space_id", + "type": "number", + "description": "库位ID(仅当 where.by_space=true 返回)" + }, + { + "name": "space_name", + "type": "string", + "description": "库位名称(custom_name 优先,否则使用 space_code,where.by_space=true 时返回)" + } + ] + } + ], + "errors": [ + { + "code": 400, + "message": "start_time 不合法" + }, + { + "code": 400, + "message": "end_time 不合法" + }, + { + "code": 400, + "message": "start_time 不能大于 end_time" + } + ] + }, + { + "method": "storage.report.export", + "description": "提交库存报表导出异步任务(与 storage.report.search 使用相同查询条件),立即返回任务受理信息,不直接返回文件。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "查询条件对象。支持字段:start_time(闭区间下限)、end_time(闭区间上限)、by_space(是否按库位返回,默认 false)、store_ids(货主ID数组)。仅返回在时间区间内存在流水的数据(无流水键不返回)。" + }, + { + "name": "where.start_time", + "type": "string", + "required": false, + "source": "body", + "description": "开始时间,支持字符串/Date;用于闭区间过滤:created_at >= start_time" + }, + { + "name": "where.end_time", + "type": "string", + "required": false, + "source": "body", + "description": "结束时间,支持字符串/Date;用于闭区间过滤:created_at <= end_time" + }, + { + "name": "where.by_space", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否按库位返回,默认 false。false=按商品+货主聚合(多库位汇总),true=按商品+库位+货主返回;当 where.by_space=true 时,导出汇总 sheet 会额外包含 space_id、space_name。" + }, + { + "name": "where.store_ids", + "type": "array", + "required": false, + "source": "body", + "description": "货主ID数组,用于过滤特定货主(空或未传表示不过滤)", + "list": [] + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数对象(请求体 data.sort)。支持 data.sort.sortField / data.sort.sort_field 与 data.sort.sortOrder / data.sort.sort_order;sortField 白名单:begin_total、inbound_total、outbound_total、end_total;sortOrder 支持 ASC / DESC(大小写不敏感);非法字段或顺序将回退默认排序。" + }, + { + "name": "sort.sortField", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序字段(兼容 data.sort.sortField)。白名单:begin_total、inbound_total、outbound_total、end_total;非法值回退默认排序。" + }, + { + "name": "sort.sort_field", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序字段下划线别名(兼容 data.sort.sort_field),规则同 sort.sortField。" + }, + { + "name": "sort.sortOrder", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序方向(兼容 data.sort.sortOrder),支持 ASC / DESC(大小写不敏感);非法值回退默认排序。" + }, + { + "name": "sort.sort_order", + "type": "string", + "required": false, + "source": "body.sort", + "description": "排序方向下划线别名(兼容 data.sort.sort_order),规则同 sort.sortOrder。" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "导出任务ID,用于后续查询进度。" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态,提交受理后初始为 submitted。" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "任务进度百分比(0-100)。" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务受理提示信息。" + }, + { + "name": "error", + "type": "string", + "required": true, + "description": "错误信息;受理成功时通常为空字符串。" + }, + { + "name": "result", + "type": "object|null", + "required": true, + "description": "任务结果对象;受理阶段为 null。" + }, + { + "name": "update_time", + "type": "number", + "required": true, + "description": "任务状态更新时间(时间戳)。" + } + ], + "errors": [ + { + "code": 400, + "message": "start_time 不合法" + }, + { + "code": 400, + "message": "end_time 不合法" + }, + { + "code": 400, + "message": "start_time 不能大于 end_time" + } + ] + }, + { + "method": "storage.report.exportTaskProgress", + "description": "根据 task_id 查询库存报表导出任务进度与结果;status 可能值:submitted/running/success/failed/not_found。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "task_id", + "type": "string", + "required": false, + "source": "body", + "description": "导出任务ID(下划线写法)。" + }, + { + "name": "taskId", + "type": "string", + "required": false, + "source": "body", + "description": "导出任务ID(驼峰写法,兼容别名)。" + } + ], + "response": [ + { + "name": "task_id", + "type": "string", + "required": true, + "description": "导出任务ID。" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "任务状态:submitted/running/success/failed/not_found。" + }, + { + "name": "progress", + "type": "number", + "required": true, + "description": "任务进度百分比(0-100)。" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "任务状态说明。" + }, + { + "name": "error", + "type": "string", + "required": true, + "description": "失败时的错误信息;成功时通常为空字符串。" + }, + { + "name": "download_url", + "type": "string", + "required": true, + "description": "任务成功后返回的下载链接;未完成或失败时为空字符串。" + }, + { + "name": "update_time", + "type": "number", + "required": true, + "description": "任务状态更新时间(时间戳)。" + }, + { + "name": "result", + "type": "object|null", + "required": true, + "description": "任务结果对象(包含导出文件信息);未完成或失败时可能为 null。" + } + ], + "errors": [] + } + ] + }, { "groupName": "主体模块", "module": "store", diff --git a/printer_data_template/kuaishou.json b/printer_data_template/kuaishou.json index 2e3519a..7089539 100644 --- a/printer_data_template/kuaishou.json +++ b/printer_data_template/kuaishou.json @@ -7,8 +7,9 @@ "taskID": "001778509772549", "printer": "打印机", - "preview": {}, - + "preview": false, + "firstDocumentNumber": 1, + "totalDocumentCount": 1, "documents": [ diff --git a/test/app/controller/system.storage.inventory.list.test.js b/test/app/controller/system.storage.inventory.list.test.js deleted file mode 100644 index 6180b78..0000000 --- a/test/app/controller/system.storage.inventory.list.test.js +++ /dev/null @@ -1,141 +0,0 @@ -'use strict'; - -const assert = require('node:assert/strict'); -const { - getAuthToken, - invokeSystemMethod, -} = require('../../support/system_method_client'); - -const EXTRA_HEADERS = { - platform: 'web', - project: 'all', -}; - -const FALLBACK_ROLE_IDS = [ 4, 6, 30 ]; - -async function switchToWarehouseRole(token) { - let currentToken = token; - const infoRes = await invokeSystemMethod('user.info', {}, currentToken, EXTRA_HEADERS); - - assert.equal(infoRes.status, 200); - assert.equal(infoRes.body.flag, 'success'); - assert.equal(infoRes.body.code, 200); - - const employees = Array.isArray(infoRes.body?.data?.employees) ? infoRes.body.data.employees : []; - const warehouseRoles = employees.filter(item => item && item.role_type === 'warehouse' && Number(item.id)); - const candidateRoleIds = [ ...new Set([ - ...warehouseRoles.map(item => Number(item.id)), - ...FALLBACK_ROLE_IDS, - ].filter(Boolean)) ]; - - assert.ok(candidateRoleIds.length > 0, '当前账号没有可尝试的仓库角色'); - - for (const roleId of candidateRoleIds) { - const changeRes = await invokeSystemMethod('user.changeRole', { - roleId, - }, currentToken, EXTRA_HEADERS); - - if (changeRes.status !== 200 || changeRes.body?.flag !== 'success' || changeRes.body?.code !== 200) { - continue; - } - - currentToken = changeRes.body?.data?.token || currentToken; - - const listRes = await invokeSystemMethod('storage.inventory.list', { - pagination: { page: 1, pageSize: 1 }, - where: {}, - }, currentToken, EXTRA_HEADERS); - - if (listRes.status === 200 && listRes.body?.flag === 'success' && listRes.body?.code === 200) { - return { - token: currentToken, - roleId, - }; - } - } - - throw new Error('未找到可访问库存列表的仓库角色'); -} - -describe('test/app/controller/system.storage.inventory.list.test.js', () => { - let warehouseToken; - - before(async function() { - const { token } = await getAuthToken(); - - try { - const switched = await switchToWarehouseRole(token); - warehouseToken = switched.token; - } catch (error) { - this.skip(); - } - }); - - it('should return merged inventory list by default', async () => { - const res = await invokeSystemMethod('storage.inventory.list', { - pagination: { page: 1, pageSize: 200 }, - where: {}, - }, warehouseToken, EXTRA_HEADERS); - - assert.equal(res.status, 200); - assert.equal(res.body.flag, 'success'); - assert.equal(res.body.code, 200); - - const data = res.body.data; - assert.ok(data, '响应缺少 data'); - assert.ok(Array.isArray(data.list), 'list 应为数组'); - assert.ok(data.pagination, '缺少 pagination'); - - const hasMergedRow = data.list.some(row => row && row.batch_count !== undefined); - assert.ok(hasMergedRow, '默认模式应返回聚合后的库存记录'); - - const firstRow = data.list[0]; - assert.ok(firstRow?.stock, '默认模式应包含 stock 子对象'); - assert.ok(Array.isArray(firstRow.stock.barcodes), 'stock.barcodes 应为数组'); - assert.ok(Array.isArray(firstRow.stock.images), 'stock.images 应为数组'); - }); - - it('should return batch-level inventory records when group_by_batch=true', async () => { - const mergedRes = await invokeSystemMethod('storage.inventory.list', { - pagination: { page: 1, pageSize: 200 }, - where: {}, - }, warehouseToken, EXTRA_HEADERS); - - assert.equal(mergedRes.status, 200); - assert.equal(mergedRes.body.flag, 'success'); - assert.equal(mergedRes.body.code, 200); - - const mergedList = mergedRes.body.data.list; - - const detailRes = await invokeSystemMethod('storage.inventory.list', { - pagination: { page: 1, pageSize: 200 }, - group_by_batch: true, - where: {}, - }, warehouseToken, EXTRA_HEADERS); - - assert.equal(detailRes.status, 200); - assert.equal(detailRes.body.flag, 'success'); - assert.equal(detailRes.body.code, 200); - - const detailList = detailRes.body.data.list; - assert.ok(Array.isArray(detailList), 'group_by_batch=true 时 list 应为数组'); - assert.ok(detailList.length >= mergedList.length, 'group_by_batch=true 时记录数不应少于合并模式'); - - for (const row of detailList) { - assert.ok('id' in row, '明细模式应包含 id'); - assert.ok('batch_no' in row, '明细模式应包含 batch_no'); - assert.ok('production_date' in row, '明细模式应包含 production_date'); - assert.ok('expiry_date' in row, '明细模式应包含 expiry_date'); - assert.ok('expiry_remaining_days' in row, '明细模式应包含 expiry_remaining_days'); - assert.ok('inventory_warning_level' in row, '明细模式应包含 inventory_warning_level'); - assert.ok('inventory_warning_color' in row, '明细模式应包含 inventory_warning_color'); - assert.ok('inventory_warning_range' in row, '明细模式应包含 inventory_warning_range'); - assert.ok('inventory_warning_tip_text' in row, '明细模式应包含 inventory_warning_tip_text'); - assert.ok('inbound_time' in row, '明细模式应包含 inbound_time'); - assert.ok('inbound_order_no' in row, '明细模式应包含 inbound_order_no'); - assert.ok('supplier_batch_no' in row, '明细模式应包含 supplier_batch_no'); - assert.ok(Array.isArray(row.stock?.barcodes), 'stock.barcodes 应为数组'); - assert.ok(Array.isArray(row.stock?.images), 'stock.images 应为数组'); - } - }); -}); diff --git a/test/app/model/print_stations.test.js b/test/app/model/print_stations.test.js index 2e7215d..b238a78 100644 --- a/test/app/model/print_stations.test.js +++ b/test/app/model/print_stations.test.js @@ -4,7 +4,7 @@ const assert = require('node:assert/strict'); /** * 构造 print_stations 模型测试所需的最小 Sequelize 类型集合。 - * @returns {Object} Sequelize 类型集合。 + * @return {Object} Sequelize 类型集合。 */ function createSequelizeTypes() { const makeType = sql => ({ @@ -30,7 +30,7 @@ function createSequelizeTypes() { /** * 构造加载 print_stations 模型所需的最小应用对象。 - * @returns {Object} 应用对象。 + * @return {Object} 应用对象。 */ function createApp() { return { diff --git a/test/app/service/systemMethods/order/wave.batchAutoGrouping.test.js b/test/app/service/systemMethods/order/wave.batchAutoGrouping.test.js new file mode 100644 index 0000000..1727859 --- /dev/null +++ b/test/app/service/systemMethods/order/wave.batchAutoGrouping.test.js @@ -0,0 +1,242 @@ +'use strict'; + +const assert = require('node:assert/strict'); + +const { Op } = require('sequelize'); +const WaveService = require('../../../../../app/service/systemMethods/order/wave'); + +/** + * 创建自动加团相关测试上下文。 + * + * @param {Object} options 初始化选项。 + * @param {Array} options.orders 订单初始数据。 + * @param {Array} options.waves 波次初始数据。 + * @param {number} [options.storeId=100000] 仓库ID。 + * @param {number} [options.maxWaveQuantity=500] 最大波次订单数。 + * @return {{ service: WaveService, txState: Object, waves: Array }} 测试上下文。 + */ +function createHarness({ orders = [], waves = [], storeId = 100000, maxWaveQuantity = 500 } = {}) { + const orderStore = orders.map(row => ({ ...row })); + const waveStore = waves.map(row => ({ ...row })); + const txState = { + committed: false, + rolledBack: false, + sqlCalls: [], + }; + + const transaction = { + async commit() { + txState.committed = true; + }, + async rollback() { + txState.rolledBack = true; + }, + }; + + const ctx = { + app: { + config: {}, + }, + user: { + store_id: storeId, + }, + model: { + QueryTypes: { + SELECT: 'SELECT', + }, + async transaction() { + return transaction; + }, + async query(sql, options = {}) { + txState.sqlCalls.push({ sql, options }); + + if (sql.includes('SELECT wave_id, wave_status, total_orders')) { + const targetIds = Array.isArray(options.replacements && options.replacements.ids) + ? options.replacements.ids + : []; + return waveStore + .filter(item => Number(item.warehouse_id) === Number(options.replacements.warehouseId)) + .filter(item => targetIds.includes(item.wave_id)) + .map(item => ({ + wave_id: item.wave_id, + wave_status: item.wave_status, + total_orders: item.total_orders, + })); + } + + if (sql.includes('SELECT wave_id, wave_status') && !sql.includes('total_orders')) { + const targetIds = Array.isArray(options.replacements && options.replacements.ids) + ? options.replacements.ids + : []; + return waveStore + .filter(item => Number(item.warehouse_id) === Number(options.replacements.warehouseId)) + .filter(item => targetIds.includes(item.wave_id)) + .map(item => ({ + wave_id: item.wave_id, + wave_status: item.wave_status, + })); + } + + if (sql.includes('SET wave_status = 0')) { + const targetWaveIds = Array.isArray(options.replacements && options.replacements.waveIds) + ? options.replacements.waveIds + : []; + let affectedRows = 0; + for (const wave of waveStore) { + if (targetWaveIds.includes(wave.wave_id) && Number(wave.warehouse_id) === Number(options.replacements.warehouseId)) { + wave.wave_status = 0; + affectedRows += 1; + } + } + return [[], { affectedRows }]; + } + + if (sql.includes('SET wave_status = 1')) { + const targetWaveIds = Array.isArray(options.replacements && options.replacements.waveIds) + ? options.replacements.waveIds + : []; + let affectedRows = 0; + for (const wave of waveStore) { + if ( + targetWaveIds.includes(wave.wave_id) + && Number(wave.warehouse_id) === Number(options.replacements.warehouseId) + && Number(wave.wave_status) === 0 + ) { + wave.wave_status = 1; + affectedRows += 1; + } + } + return [[], { affectedRows }]; + } + + if (sql.includes('DELETE FROM wms_order_wave_index')) { + const targetWaveIds = Array.isArray(options.replacements && options.replacements.waveIds) + ? options.replacements.waveIds + : []; + return [[], { affectedRows: targetWaveIds.length }]; + } + + if (sql.includes('INSERT INTO wms_order_wave_index')) { + const replacements = options.replacements || {}; + let affectedRows = 0; + for (const key of Object.keys(replacements)) { + if (key.startsWith('orderId_')) { + affectedRows += 1; + } + } + return [[], { affectedRows }]; + } + + return [[], { affectedRows: 0 }]; + }, + }, + }; + + const service = new WaveService(ctx); + service.getDefaultWaveQuantity = async () => maxWaveQuantity; + service.getOrderModel = async () => ({ + async findAll(options = {}) { + const where = options.where || {}; + const waveIn = (where.wave_id && where.wave_id[Op.in]) || []; + const waveGt = Number((where.wave_id && where.wave_id[Op.gt]) || 0); + + const rows = orderStore + .filter(item => waveIn.includes(item.wave_id)) + .filter(item => Number(item.wave_id) > waveGt) + .sort((a, b) => { + if (Number(a.wave_id) !== Number(b.wave_id)) { + return Number(a.wave_id) - Number(b.wave_id); + } + return Number(a.id) - Number(b.id); + }); + + return rows.map(item => ({ + id: item.id, + wave_id: item.wave_id, + sys_platform_code: item.sys_platform_code, + })); + }, + }); + + return { + service, + txState, + waves: waveStore, + }; +} + +describe('test/app/service/systemMethods/order/wave.batchAutoGrouping.test.js', () => { + it('batchAutoGrouping should rebuild wave indexes for updatable waves', async () => { + const { service, txState, waves } = createHarness({ + maxWaveQuantity: 3, + orders: [ + { id: 1001, wave_id: 501, sys_platform_code: 'pdd' }, + { id: 1002, wave_id: 501, sys_platform_code: 'cainiao' }, + { id: 1003, wave_id: 502, sys_platform_code: 'pdd' }, + ], + waves: [ + { warehouse_id: 100000, wave_id: 501, wave_status: 1, total_orders: 2 }, + { warehouse_id: 100000, wave_id: 502, wave_status: 2, total_orders: 1 }, + { warehouse_id: 100000, wave_id: 503, wave_status: 1, total_orders: 3 }, + ], + }); + + const result = await service.batchAutoGrouping({ ids: [ 501, 502, 503 ] }); + + assert.equal(txState.committed, true); + assert.equal(txState.rolledBack, false); + assert.equal(result.flag, 'success'); + assert.deepEqual(result.affected_wave_ids, [ 501, 502, 503 ]); + assert.equal(result.updated_wave_count, 1); + + const targetWave = waves.find(item => item.wave_id === 501); + assert.equal(targetWave.wave_status, 0); + + const deleteIndexCall = txState.sqlCalls.find(call => call.sql.includes('DELETE FROM wms_order_wave_index')); + assert.ok(deleteIndexCall, '应按可更新波次整批删除索引'); + assert.deepEqual(deleteIndexCall.options.replacements.waveIds, [ 501 ]); + + const insertIndexCall = txState.sqlCalls.find(call => call.sql.includes('INSERT INTO wms_order_wave_index')); + assert.ok(insertIndexCall, '应按可更新波次整批重建索引'); + assert.equal(insertIndexCall.options.replacements.waveId_0, 501); + assert.equal(insertIndexCall.options.replacements.orderId_0, 1001); + assert.equal(insertIndexCall.options.replacements.orderId_1, 1002); + assert.equal(insertIndexCall.options.replacements.platformsIndex_0, 2); + assert.equal(insertIndexCall.options.replacements.platformsIndex_1, 1); + }); + + it('batchFinishAutoGrouping should rebuild wave indexes for updated waves', async () => { + const { service, txState, waves } = createHarness({ + orders: [ + { id: 2001, wave_id: 601 }, + { id: 2002, wave_id: 601 }, + { id: 2003, wave_id: 602 }, + ], + waves: [ + { warehouse_id: 100000, wave_id: 601, wave_status: 0, total_orders: 2 }, + { warehouse_id: 100000, wave_id: 602, wave_status: 1, total_orders: 1 }, + ], + }); + + const result = await service.batchFinishAutoGrouping({ ids: [ 601, 602 ] }); + + assert.equal(txState.committed, true); + assert.equal(txState.rolledBack, false); + assert.equal(result.flag, 'success'); + assert.deepEqual(result.updated_wave_ids, [ 601 ]); + assert.equal(result.updated_wave_count, 1); + + const updatedWave = waves.find(item => item.wave_id === 601); + assert.equal(updatedWave.wave_status, 1); + + const deleteIndexCall = txState.sqlCalls.find(call => call.sql.includes('DELETE FROM wms_order_wave_index')); + assert.ok(deleteIndexCall, '应按完成加团波次整批删除索引'); + assert.deepEqual(deleteIndexCall.options.replacements.waveIds, [ 601 ]); + + const insertIndexCall = txState.sqlCalls.find(call => call.sql.includes('INSERT INTO wms_order_wave_index')); + assert.ok(insertIndexCall, '应按完成加团波次整批重建索引'); + assert.equal(insertIndexCall.options.replacements.waveId_0, 601); + assert.equal(insertIndexCall.options.replacements.orderId_0, 2001); + assert.equal(insertIndexCall.options.replacements.orderId_1, 2002); + }); +}); diff --git a/test/app/service/systemMethods/order/wave.batchCancel.test.js b/test/app/service/systemMethods/order/wave.batchCancel.test.js new file mode 100644 index 0000000..98bd356 --- /dev/null +++ b/test/app/service/systemMethods/order/wave.batchCancel.test.js @@ -0,0 +1,126 @@ +'use strict'; + +const assert = require('node:assert/strict'); + +const WaveService = require('../../../../../app/service/systemMethods/order/wave'); + +/** + * 创建 batchCancel 轻量测试上下文。 + * + * @return {{ service: WaveService, state: Object }} 服务实例与状态记录。 + */ +function createHarness() { + const cacheStore = new Map(); + const state = { + sqlCalls: [], + orders: [ + { id: 101, wave_id: 11, wave_no: 'W11' }, + { id: 102, wave_id: 11, wave_no: 'W11' }, + ], + }; + + const transaction = { + async commit() {}, + async rollback() {}, + }; + + const ctx = { + app: { + config: {}, + async setCacheAsync(key, value) { + cacheStore.set(key, value); + }, + async getCacheAsync(key) { + return cacheStore.get(key) || null; + }, + }, + user: { + store_id: 100000, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + model: { + QueryTypes: { + SELECT: 'SELECT', + }, + async transaction() { + return transaction; + }, + async query(sql, options = {}) { + state.sqlCalls.push({ sql, options }); + + if (sql.includes('SELECT wave_id, wave_no') && options.type === 'SELECT') { + return [ + { wave_id: 11, wave_no: 'W11' }, + ]; + } + + if (sql.includes('DELETE FROM wms_order_wave_index')) { + return [[], { affectedRows: 2 }]; + } + + if (sql.includes('UPDATE wms_wave_batch') && sql.includes('SET wave_status = -1')) { + return [[], { affectedRows: 1 }]; + } + + return [[], { affectedRows: 0 }]; + }, + }, + }; + + const service = new WaveService(ctx); + service.batchCreateOrderOperationLogs = async () => 0; + service.getOrderModel = async () => ({ + async findAll() { + return state.orders.map(item => ({ ...item })); + }, + async update(values = {}, options = {}) { + const waveId = Number(options.where && options.where.wave_id || 0); + let affected = 0; + for (const row of state.orders) { + if (Number(row.wave_id || 0) !== waveId) { + continue; + } + + row.wave_id = Number(values.wave_id || 0); + row.wave_no = String(values.wave_no || ''); + affected += 1; + } + return [ affected ]; + }, + }); + + return { + service, + state, + }; +} + +describe('test/app/service/systemMethods/order/wave.batchCancel.test.js', () => { + it('runBatchCancelTask 应在取消波次时清理 wms_order_wave_index', async () => { + const { service, state } = createHarness(); + + await service.setBatchCancelTaskProgress('task_cancel_1', 'submitted', { + warehouse_id: 100000, + wave_ids: '11', + wave_id_list: [ 11 ], + }); + + await service.runBatchCancelTask({ + taskId: 'task_cancel_1', + warehouseId: 100000, + waveIds: [ 11 ], + }); + + const deleteCall = state.sqlCalls.find(call => call.sql.includes('DELETE FROM wms_order_wave_index')); + assert.ok(deleteCall, '应删除波次索引'); + assert.deepEqual(deleteCall.options.replacements.orderIds.sort((a, b) => a - b), [ 101, 102 ]); + + const progress = await service.getBatchCancelTaskProgress('task_cancel_1'); + assert.equal(progress.state, 'success'); + assert.equal(progress.result.canceled_wave_count, 1); + }); +}); diff --git a/test/app/service/systemMethods/order/wave.batchRemoveOrders.test.js b/test/app/service/systemMethods/order/wave.batchRemoveOrders.test.js index 502e918..ede751c 100644 --- a/test/app/service/systemMethods/order/wave.batchRemoveOrders.test.js +++ b/test/app/service/systemMethods/order/wave.batchRemoveOrders.test.js @@ -20,6 +20,7 @@ function createHarness({ orders = [], waves = [], storeId = 100000 } = {}) { const txState = { committed: false, rolledBack: false, + sqlCalls: [], }; const transaction = { @@ -52,6 +53,26 @@ function createHarness({ orders = [], waves = [], storeId = 100000 } = {}) { return transaction; }, async query(sql, options = {}) { + txState.sqlCalls.push({ sql, options }); + + if (sql.includes('DELETE FROM wms_order_wave_index')) { + const targetWaveIds = Array.isArray(options.replacements && options.replacements.waveIds) + ? options.replacements.waveIds + : []; + return [[], { affectedRows: targetWaveIds.length }]; + } + + if (sql.includes('INSERT INTO wms_order_wave_index')) { + let affectedRows = 0; + const replacements = options.replacements || {}; + for (const key of Object.keys(replacements)) { + if (key.startsWith('orderId_')) { + affectedRows += 1; + } + } + return [[], { affectedRows }]; + } + if (sql.includes('SET total_orders = :remainingCount')) { const waveId = Number(options.replacements && options.replacements.waveId || 0); const remainingCount = Number(options.replacements && options.replacements.remainingCount || 0); @@ -87,32 +108,38 @@ function createHarness({ orders = [], waves = [], storeId = 100000 } = {}) { async findAll(options = {}) { const where = options.where || {}; const idIn = (where.id && where.id[Op.in]) || []; - const stepIn = (where.step && where.step[Op.in]) || []; + const hasStepFilter = !!(where.step && where.step[Op.in]); + const stepIn = hasStepFilter ? where.step[Op.in] : []; const waveIn = (where.wave_id && where.wave_id[Op.in]) || []; const waveGt = Number((where.wave_id && where.wave_id[Op.gt]) || 0); - if (Array.isArray(options.group) && options.group.includes('wave_id')) { - const result = []; - for (const waveId of waveIn) { - const count = orderStore.filter(item => Number(item.wave_id) === Number(waveId) && Number(item.wave_id) > waveGt).length; - if (count > 0) { - result.push({ - wave_id: Number(waveId), - remaining_count: count, - }); - } - } - return result; + let rows = orderStore.slice(); + if (idIn.length > 0) { + rows = rows.filter(item => idIn.includes(item.id)); + } + if (hasStepFilter) { + rows = rows.filter(item => stepIn.includes(item.step)); + } + if (waveIn.length > 0) { + rows = rows.filter(item => waveIn.includes(item.wave_id)); + } + if (waveGt > 0) { + rows = rows.filter(item => Number(item.wave_id) > waveGt); } - return orderStore - .filter(item => idIn.includes(item.id)) - .filter(item => stepIn.includes(item.step)) - .filter(item => Number(item.wave_id) > waveGt) - .map(item => ({ - id: item.id, - wave_id: item.wave_id, - })); + rows.sort((a, b) => { + if (Number(a.wave_id) !== Number(b.wave_id)) { + return Number(a.wave_id) - Number(b.wave_id); + } + return Number(a.id) - Number(b.id); + }); + + return rows.map(item => ({ + id: item.id, + wave_id: item.wave_id, + sys_platform_code: item.sys_platform_code, + source_platform_code: item.source_platform_code, + })); }, async update(values = {}, options = {}) { @@ -202,6 +229,63 @@ describe('test/app/service/systemMethods/order/wave.batchRemoveOrders.test.js', assert.equal(emptiedWave.total_orders, 0); assert.equal(emptiedWave.processed_orders, 0); assert.equal(emptiedWave.wave_status, -1); + + const deleteIndexCall = txState.sqlCalls.find(call => call.sql.includes('DELETE FROM wms_order_wave_index')); + assert.ok(deleteIndexCall, '应按波次整批删除波次索引'); + assert.deepEqual(deleteIndexCall.options.replacements.waveIds.sort((a, b) => a - b), [ 21, 22 ]); + + const insertIndexCall = txState.sqlCalls.find(call => call.sql.includes('INSERT INTO wms_order_wave_index')); + assert.ok(insertIndexCall, '应按当前波次订单重建波次索引'); + assert.equal(insertIndexCall.options.replacements.orderId_0, 12); + assert.equal(insertIndexCall.options.replacements.waveId_0, 21); + assert.equal(insertIndexCall.options.replacements.waveIndex_0, 1); + assert.equal(insertIndexCall.options.replacements.platformsIndex_0, 1); + }); + + it('should rebuild platforms_index by normalized sys/source platform key after batch remove', async () => { + const { service, txState } = createHarness({ + orders: [ + { id: 50, step: 1, wave_id: 61, wave_no: 'W61', sys_platform_code: 'PDD', source_platform_code: '' }, + { id: 51, step: 2, wave_id: 61, wave_no: 'W61', sys_platform_code: ' JD ', source_platform_code: '' }, + { id: 52, step: 0, wave_id: 61, wave_no: 'W61', sys_platform_code: '', source_platform_code: 'tmall' }, + { id: 53, step: 0, wave_id: 61, wave_no: 'W61', sys_platform_code: ' pdd ', source_platform_code: '' }, + { id: 54, step: 0, wave_id: 61, wave_no: 'W61', sys_platform_code: '', source_platform_code: ' JD' }, + { id: 55, step: 0, wave_id: 61, wave_no: 'W61', sys_platform_code: 'jd', source_platform_code: '' }, + { id: 56, step: 0, wave_id: 61, wave_no: 'W61', sys_platform_code: '', source_platform_code: ' pdd ' }, + ], + waves: [ + { wave_id: 61, total_orders: 7, processed_orders: 0, wave_status: 1 }, + ], + }); + + const result = await service.batchRemoveOrders({ ids: [ 50, 51 ] }); + + assert.equal(result.flag, 'success'); + assert.deepEqual(result.updated_wave_ids, [ 61 ]); + + const insertIndexCall = txState.sqlCalls.find(call => call.sql.includes('INSERT INTO wms_order_wave_index')); + assert.ok(insertIndexCall, '应在移除后重建剩余订单索引'); + + const { replacements } = insertIndexCall.options; + assert.equal(replacements.orderId_0, 52); + assert.equal(replacements.waveIndex_0, 1); + assert.equal(replacements.platformsIndex_0, 1); + + assert.equal(replacements.orderId_1, 53); + assert.equal(replacements.waveIndex_1, 2); + assert.equal(replacements.platformsIndex_1, 1); + + assert.equal(replacements.orderId_2, 54); + assert.equal(replacements.waveIndex_2, 3); + assert.equal(replacements.platformsIndex_2, 1); + + assert.equal(replacements.orderId_3, 55); + assert.equal(replacements.waveIndex_3, 4); + assert.equal(replacements.platformsIndex_3, 2); + + assert.equal(replacements.orderId_4, 56); + assert.equal(replacements.waveIndex_4, 5); + assert.equal(replacements.platformsIndex_4, 2); }); it('should accept order_ids alias and normalize ids in response', async () => { diff --git a/test/app/service/systemMethods/order/wave.fetch.test.js b/test/app/service/systemMethods/order/wave.fetch.test.js index 393ab9f..cff1146 100644 --- a/test/app/service/systemMethods/order/wave.fetch.test.js +++ b/test/app/service/systemMethods/order/wave.fetch.test.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict'; const assert = require('node:assert/strict'); const { Op } = require('sequelize'); @@ -224,7 +224,7 @@ describe('test/app/service/systemMethods/order/wave.fetch.test.js', () => { return transaction; }, async query(sql, options = {}) { - sqlCalls.push({ sql, options }); + sqlCalls.push({ sql, options }); console.log('SQL:', sql); console.log('Replacements:', JSON.stringify(options.replacements)); if (sql.includes('INSERT INTO wms_wave_batch')) { return [{ insertId: 900001 }, { insertId: 900001 }]; } @@ -350,7 +350,7 @@ describe('test/app/service/systemMethods/order/wave.fetch.test.js', () => { return transaction; }, async query(sql, options = {}) { - sqlCalls.push({ sql, options }); + sqlCalls.push({ sql, options }); console.log('SQL:', sql); console.log('Replacements:', JSON.stringify(options.replacements)); if (sql.includes('INSERT INTO wms_wave_batch')) { return [{}, {}]; } @@ -480,7 +480,7 @@ describe('test/app/service/systemMethods/order/wave.fetch.test.js', () => { return transaction; }, async query(sql, options = {}) { - sqlCalls.push({ sql, options }); + sqlCalls.push({ sql, options }); console.log('SQL:', sql); console.log('Replacements:', JSON.stringify(options.replacements)); if (sql.includes('INSERT INTO wms_wave_batch')) { return [{ insertId: 900003 }, { insertId: 900003 }]; } @@ -522,10 +522,14 @@ describe('test/app/service/systemMethods/order/wave.fetch.test.js', () => { .filter(item => item.wave_id === 0) .map(item => ({ id: item.id })); } - if (where.wave_id === 900003) { + const waveIdInList = where.wave_id && where.wave_id[Op.in]; + const normalizedWaveIdInList = Array.isArray(waveIdInList) + ? waveIdInList.map(item => Number(item)).filter(item => Number.isInteger(item) && item > 0) + : []; + if (where.wave_id === 900003 || normalizedWaveIdInList.includes(900003)) { return orders .filter(item => item.wave_id === 900003) - .map(item => ({ id: item.id })); + .map(item => ({ id: item.id, wave_id: item.wave_id })); } return []; }, @@ -564,5 +568,10 @@ describe('test/app/service/systemMethods/order/wave.fetch.test.js', () => { const insertCall = sqlCalls.find(call => call.sql.includes('INSERT INTO wms_order_wave_index')); assert.ok(insertCall, '应触发 INSERT INTO wms_order_wave_index'); + + const deleteIndex = sqlCalls.findIndex(call => call.sql.includes('DELETE FROM wms_order_wave_index')); + const insertIndex = sqlCalls.findIndex(call => call.sql.includes('INSERT INTO wms_order_wave_index')); + assert.ok(deleteIndex >= 0 && insertIndex >= 0 && deleteIndex < insertIndex, '应先删除旧索引再写入新索引'); }); }); + diff --git a/test/app/service/systemMethods/print.savePrinters.test.js b/test/app/service/systemMethods/print.savePrinters.test.js index df9c9b2..ec4bb77 100644 --- a/test/app/service/systemMethods/print.savePrinters.test.js +++ b/test/app/service/systemMethods/print.savePrinters.test.js @@ -7,7 +7,7 @@ const PrintService = require('../../../../app/service/systemMethods/print'); * 构造 savePrinters 测试上下文。 * @param {Object} [options] 测试选项。 * @param {Object|null} [options.stationItem] 打印台模型实例。 - * @returns {{ctx: Object, calls: Object, stationItem: Object|null}} 测试上下文与调用记录。 + * @return {{ctx: Object, calls: Object, stationItem: Object|null}} 测试上下文与调用记录。 */ function createContext(options = {}) { const calls = { diff --git a/test/app/service/systemMethods/print.send.test.js b/test/app/service/systemMethods/print.send.test.js index fb943ce..2e6a424 100644 --- a/test/app/service/systemMethods/print.send.test.js +++ b/test/app/service/systemMethods/print.send.test.js @@ -5,21 +5,96 @@ const PrintService = require('../../../../app/service/systemMethods/print'); /** * 构建 print.send 测试上下文。 - * @returns {{ctx: Object, calls: Object}} + * @param {Object} [options] 可选项。 + * @param {Object} [options.printStation] 打印台数据。 + * @param {Function} [options.sendToComputer] 发送函数桩。 + * @return {{ctx: Object, calls: Object}} 包含模拟上下文与调用记录。 */ -function createContext() { +function createContext(options = {}) { + const requestOptions = options && typeof options === 'object' ? options : {}; const calls = { printRecordCreatePayloads: [], printRecordUpdatePayloads: [], sendToComputerPayloads: [], + sendOrderMarks: [], + redisGetKeys: [], + platformFindAllWheres: [], + }; + + const platformComponents = requestOptions.platformComponents || { + cainiao: '菜鸟', + pdd: '拼多多', + douyin: '抖音', + }; + + const printStation = requestOptions.printStation || { + id: 101, + warehouse_id: 100000, + deleted: 0, + computer_id: 'PC-STATION-001', + default_printer_name: 'PRN-DEFAULT', + subject_config: { + express_bind_printer: [ + { + express_code: 'STO', + printer_name: 'PRN-STO', + }, + ], + }, + }; + + const sendToComputer = requestOptions.sendToComputer || (async payload => { + calls.sendToComputerPayloads.push(payload); + const marker = payload + && payload.data + && payload.data.data + && payload.data.data.task + && Array.isArray(payload.data.data.task.documents) + && payload.data.data.task.documents[0] + && Array.isArray(payload.data.data.task.documents[0].contents) + && payload.data.data.task.documents[0].contents[0] + ? payload.data.data.task.documents[0].contents[0].marker + : ''; + calls.sendOrderMarks.push(marker); + return { + status: 'success', + }; + }); + + const defaultComponentStatusMap = { + 'printer:PC-STATION-001:name:菜鸟:status': 'connected', + 'printer:PC-STATION-001:name:拼多多:status': 'connected', + 'printer:PC-STATION-001:name:抖音:status': 'connected', + }; + const componentStatusMap = { + ...defaultComponentStatusMap, + ...(requestOptions.componentStatuses || {}), }; const ctx = { app: { + baseDir: process.cwd(), config: { jwt: {}, }, Sequelize: {}, + redis: { + get() { + return { + async get(key) { + calls.redisGetKeys.push(key); + return Object.prototype.hasOwnProperty.call(componentStatusMap, key) + ? componentStatusMap[key] + : null; + }, + }; + }, + }, + }, + logger: { + info() {}, + warn() {}, + error() {}, }, user: { store_id: 100000, @@ -36,17 +111,31 @@ function createContext() { }; }, }, + PrintStations: { + async findOne() { + return printStation; + }, + }, + Platform: { + async findAll(query) { + calls.platformFindAllWheres.push(query && query.where ? query.where : {}); + const codeList = query && query.where && Array.isArray(query.where.code) + ? query.where.code + : []; + return codeList.map(code => ({ + code, + component: Object.prototype.hasOwnProperty.call(platformComponents, code) + ? platformComponents[code] + : '', + })); + }, + }, }, service: { systems: { print: { index: { - async sendToComputer(payload) { - calls.sendToComputerPayloads.push(payload); - return { - status: 'success', - }; - }, + sendToComputer, }, }, }, @@ -56,48 +145,409 @@ function createContext() { return { ctx, calls }; } +/** + * 构建 express 场景的 waveGroups。 + * @return {Array} waveGroups。 + */ +function createExpressWaveGroups() { + return [ + { + wave_id: 1, + wave_no: 'WAVE-1', + platforms: [ + { + platform: 'cainiao', + sys_logistics_code: 'STO', + orders: [ + { + print_data: { + documentID: 'DOC-OLD-1', + contents: [ + { + marker: 'W1-P1', + }, + ], + }, + }, + { + print_data: { + documentID: 'DOC-OLD-2', + contents: [ + { + marker: 'W1-P1-2', + }, + ], + }, + }, + ], + }, + { + platform: 'pdd', + sys_logistics_code: 'YTO', + orders: [ + { + print_data: { + documentID: 'DOC-OLD-3', + contents: [ + { + marker: 'W1-P2', + }, + ], + }, + }, + ], + }, + ], + }, + { + wave_id: 2, + wave_no: 'WAVE-2', + platforms: [ + { + platform: 'douyin', + sys_logistics_code: 'STO', + orders: [ + { + print_data: { + documentID: 'DOC-OLD-4', + contents: [ + { + marker: 'W2-P1', + }, + ], + }, + }, + ], + }, + ], + }, + ]; +} + +/** + * 构建快手平台的 express 场景波次数据。 + * @param {number} orderCount 订单数量。 + * @return {Array} waveGroups。 + */ +function createKuaishouWaveGroups(orderCount) { + const normalizedOrderCount = Number(orderCount) || 0; + const orders = []; + for (let index = 0; index < normalizedOrderCount; index++) { + const current = index + 1; + orders.push({ + print_data: { + documentID: `DOC-KS-${current}`, + contents: [ + { + marker: `KS-${current}`, + }, + ], + }, + }); + } + return [ + { + wave_id: 1, + wave_no: 'WAVE-KS-1', + platforms: [ + { + platform: 'kuaishou', + sys_logistics_code: 'STO', + orders, + }, + ], + }, + ]; +} + describe('test/app/service/systemMethods/print.send.test.js', () => { - it('type=express 不传 printer 时应发送成功并调用 sendToComputer', async () => { + it('type=express 缺失 printStationId 时应返回失败', async () => { const { ctx, calls } = createContext(); const service = new PrintService(ctx); const result = await service.send({ - computerId: 'PC-00', type: 'express', + requestCode: 'REQ-MISSING-STATION', data: { - order_no: 'SO10000', + waveGroups: createExpressWaveGroups(), + }, + }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.code, 400); + assert.match(result.message, /printStationId/); + assert.equal(calls.sendToComputerPayloads.length, 0); + }); + + it('type=express 使用 waveGroups 串行发送并保持 success 返回风格', async () => { + const { ctx, calls } = createContext(); + const service = new PrintService(ctx); + + const result = await service.send({ + type: 'express', + printStationId: 101, + requestCode: 'REQ-SEQ-001', + data: { + waveGroups: createExpressWaveGroups(), }, - timestamp: '1709999999', - count: 1, }); assert.equal(result.flag, 'success'); assert.equal(result.code, 200); - assert.equal(calls.sendToComputerPayloads.length, 1); + assert.equal(calls.printRecordCreatePayloads.length, 1); + assert.equal(calls.printRecordCreatePayloads[0].computer_id, 'PC-STATION-001'); + assert.equal(calls.printRecordCreatePayloads[0].printer, 'PRN-DEFAULT'); + assert.equal(calls.sendToComputerPayloads.length, 3); + assert.deepEqual(calls.sendOrderMarks, [ 'W1-P1', 'W1-P2', 'W2-P1' ]); assert.equal(calls.printRecordUpdatePayloads.length, 1); assert.equal(calls.printRecordUpdatePayloads[0].status, 'sent'); }); - it('type=express 不传 template 时应发送成功并调用 sendToComputer', async () => { + it('type=express 默认打印机为空时创建记录应写入稳定占位值', async () => { + const { ctx, calls } = createContext({ + printStation: { + id: 101, + warehouse_id: 100000, + deleted: 0, + computer_id: 'PC-STATION-001', + default_printer_name: '', + subject_config: { + express_bind_printer: [ + { + express_code: 'STO', + printer_name: 'PRN-STO', + }, + { + express_code: 'YTO', + printer_name: 'PRN-YTO', + }, + ], + }, + }, + }); + const service = new PrintService(ctx); + + const result = await service.send({ + type: 'express', + printStationId: 101, + requestCode: 'REQ-RECORD-PLACEHOLDER-001', + data: { + waveGroups: createExpressWaveGroups(), + }, + }); + + assert.equal(result.flag, 'success'); + assert.equal(calls.printRecordCreatePayloads.length, 1); + assert.equal(calls.printRecordCreatePayloads[0].computer_id, 'PC-STATION-001'); + assert.equal(calls.printRecordCreatePayloads[0].printer, 'EXPRESS_DYNAMIC_PRINTER'); + }); + + it('type=express 应按快递匹配打印机并在未命中时回退默认打印机', async () => { const { ctx, calls } = createContext(); const service = new PrintService(ctx); const result = await service.send({ - computerId: 'PC-01', - printer: 'Printer-A', type: 'express', + printStationId: 101, + requestCode: 'REQ-PRINTER-001', data: { - order_no: 'SO10001', + waveGroups: createExpressWaveGroups(), + }, + }); + + assert.equal(result.flag, 'success'); + assert.equal(calls.sendToComputerPayloads.length, 3); + const printerNames = calls.sendToComputerPayloads.map(item => item.data.printer); + assert.deepEqual(printerNames, [ 'PRN-STO', 'PRN-DEFAULT', 'PRN-STO' ]); + }); + + it('type=express 发送成功时 payload 应带 component 字段', async () => { + const { ctx, calls } = createContext(); + const service = new PrintService(ctx); + + const result = await service.send({ + type: 'express', + printStationId: 101, + requestCode: 'REQ-COMPONENT-OK-001', + data: { + waveGroups: createExpressWaveGroups(), + }, + }); + + assert.equal(result.flag, 'success'); + const components = calls.sendToComputerPayloads.map(item => item.data.component); + assert.deepEqual(components, [ '菜鸟', '拼多多', '抖音' ]); + }); + + it('type=express 任意组件离线时应整批失败且不发送任务', async () => { + const { ctx, calls } = createContext({ + componentStatuses: { + 'printer:PC-STATION-001:name:拼多多:status': 'disconnected', + }, + }); + const service = new PrintService(ctx); + + const result = await service.send({ + type: 'express', + printStationId: 101, + requestCode: 'REQ-COMPONENT-OFFLINE-001', + data: { + waveGroups: createExpressWaveGroups(), + }, + }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.code, 400); + assert.match(result.message, /未在线/); + assert.equal(calls.printRecordCreatePayloads.length, 0); + assert.equal(calls.sendToComputerPayloads.length, 0); + }); + + it('type=express 某平台 orders 为空且组件离线时不应影响整批发送', async () => { + const { ctx, calls } = createContext({ + componentStatuses: { + 'printer:PC-STATION-001:name:拼多多:status': 'disconnected', + }, + }); + const service = new PrintService(ctx); + const waveGroups = [ + { + wave_id: 1, + wave_no: 'WAVE-EMPTY-PLATFORM-1', + platforms: [ + { + platform: 'cainiao', + sys_logistics_code: 'STO', + orders: [ + { + print_data: { + documentID: 'DOC-ONLY-1', + contents: [ + { + marker: 'ONLY-CAINIAO', + }, + ], + }, + }, + ], + }, + { + platform: 'pdd', + sys_logistics_code: 'YTO', + orders: [], + }, + ], + }, + ]; + + const result = await service.send({ + type: 'express', + printStationId: 101, + requestCode: 'REQ-EMPTY-PLATFORM-OFFLINE-001', + data: { + waveGroups, }, - timestamp: '1710000000', - count: 1, }); assert.equal(result.flag, 'success'); - assert.equal(result.code, 200); assert.equal(calls.sendToComputerPayloads.length, 1); - assert.equal(calls.printRecordUpdatePayloads.length, 1); - assert.equal(calls.printRecordUpdatePayloads[0].status, 'sent'); + assert.deepEqual(calls.sendOrderMarks, [ 'ONLY-CAINIAO' ]); + assert.equal(calls.platformFindAllWheres.length, 1); + assert.deepEqual(calls.platformFindAllWheres[0].code, [ 'cainiao' ]); + assert.deepEqual(calls.redisGetKeys, [ 'printer:PC-STATION-001:name:菜鸟:status' ]); + }); + + it('type=express 平台 component 为空时应失败且不发送任务', async () => { + const { ctx, calls } = createContext({ + platformComponents: { + cainiao: '菜鸟', + pdd: '', + douyin: '抖音', + }, + }); + const service = new PrintService(ctx); + + const result = await service.send({ + type: 'express', + printStationId: 101, + requestCode: 'REQ-COMPONENT-EMPTY-001', + data: { + waveGroups: createExpressWaveGroups(), + }, + }); + + assert.equal(result.flag, 'failure'); + assert.equal(result.code, 400); + assert.match(result.message, /未配置打印组件/); + assert.equal(calls.printRecordCreatePayloads.length, 0); + assert.equal(calls.sendToComputerPayloads.length, 0); + }); + + it('type=express 快手平台应按10单分批发送并注入文档位置信息', async () => { + const { ctx, calls } = createContext({ + platformComponents: { + kuaishou: '快手', + }, + componentStatuses: { + 'printer:PC-STATION-001:name:快手:status': 'connected', + }, + }); + const service = new PrintService(ctx); + + const result = await service.send({ + type: 'express', + printStationId: 101, + requestCode: 'REQ-KS-BATCH-001', + data: { + waveGroups: createKuaishouWaveGroups(21), + }, + }); + + assert.equal(result.flag, 'success'); + assert.equal(calls.sendToComputerPayloads.length, 3); + + const requestPayloads = calls.sendToComputerPayloads.map(item => item.data.data); + const firstDocumentNumbers = requestPayloads.map(item => item.task.firstDocumentNumber); + const totalDocumentCounts = requestPayloads.map(item => item.task.totalDocumentCount); + const documentCounts = requestPayloads.map(item => item.task.documents.length); + + assert.deepEqual(firstDocumentNumbers, [ 1, 11, 21 ]); + assert.deepEqual(totalDocumentCounts, [ 21, 21, 21 ]); + assert.deepEqual(documentCounts, [ 10, 10, 1 ]); + }); + + it('type=express 同一次请求内 requestId/taskID/documentID 应唯一', async () => { + const { ctx, calls } = createContext(); + const service = new PrintService(ctx); + + const result = await service.send({ + type: 'express', + printStationId: 101, + requestCode: 'REQ-UNIQ-001', + data: { + waveGroups: createExpressWaveGroups(), + }, + }); + + assert.equal(result.flag, 'success'); + const requestIdSet = new Set(); + const taskIdSet = new Set(); + const documentIdSet = new Set(); + + for (const callPayload of calls.sendToComputerPayloads) { + const requestPayload = callPayload.data.data; + const requestId = requestPayload.requestID || requestPayload.requetID; + requestIdSet.add(requestId); + taskIdSet.add(requestPayload.task.taskID); + const documents = Array.isArray(requestPayload.task.documents) ? requestPayload.task.documents : []; + for (const document of documents) { + documentIdSet.add(document.documentID); + } + } + + assert.equal(requestIdSet.size, calls.sendToComputerPayloads.length); + assert.equal(taskIdSet.size, calls.sendToComputerPayloads.length); + assert.equal(documentIdSet.size, 4); }); it('type=customize 不传 printer 时应返回失败且提示 printer', async () => { diff --git a/test/app/service/systems/order_async.syncOrderIds.test.js b/test/app/service/systems/order_async.syncOrderIds.test.js index 9237e8c..bb43bfd 100644 --- a/test/app/service/systems/order_async.syncOrderIds.test.js +++ b/test/app/service/systems/order_async.syncOrderIds.test.js @@ -30,6 +30,7 @@ function createHarness(options = {}) { ? options.orderItems.map(item => ({ ...item })) : [ { + id: 101, order_id: 1, order_line_no: '1', source_order_code: 'SRC-1', @@ -107,6 +108,12 @@ function createHarness(options = {}) { const normalizedIds = targetIds.map(item => Number(item)); return orderRows.filter(row => normalizedIds.includes(Number(row.id))); }, + async findOne(query = {}) { + const where = query.where || {}; + const targetId = Number(where.id); + const targetWarehouseId = Number(where.warehouse_id); + return orderRows.find(row => Number(row.id) === targetId && Number(row.warehouse_id) === targetWarehouseId) || null; + }, async update(values, options) { updates.push({ values, options }); return [ 1 ]; @@ -180,10 +187,10 @@ function createHarness(options = {}) { }, }), stockStore: { - async outbound(itemId, quantity, transaction) { - outboundCalls.push({ itemId, quantity, transaction }); + async outbound(itemId, quantity, transaction, meta) { + outboundCalls.push({ itemId, quantity, transaction, meta }); if (typeof options.onOutbound === 'function') { - return await options.onOutbound({ itemId, quantity, transaction }); + return await options.onOutbound({ itemId, quantity, transaction, meta }); } return { success: true, @@ -251,6 +258,11 @@ describe('test/app/service/systems/order_async.syncOrderIds.test.js', () => { assert.equal(outboundCalls[0].itemId, 1001); assert.equal(outboundCalls[0].quantity, 2); assert.equal(outboundCalls[0].transaction, transactionCalls[0].transaction); + assert.deepEqual(outboundCalls[0].meta, { + orderId: 1, + orderNo: 'DO-1001', + orderItemId: 101, + }); assert.equal(updates.length, 1); assert.equal(updates[0].values.sync_status, 'fin'); assert.equal(updates[0].values.inspection_status, 'padding'); @@ -368,6 +380,11 @@ describe('test/app/service/systems/order_async.syncOrderIds.test.js', () => { assert.equal(noticeCalls[0].event, 'order_sync_completed'); assert.equal(noticeCalls[0].businessName, 'order'); assert.equal(outboundCalls.length, 1); + assert.deepEqual(outboundCalls[0].meta, { + orderId: 1, + orderNo: 'DO-1001', + orderItemId: 101, + }); }); it('should include waybill code in manual notice payload', async () => { @@ -616,6 +633,11 @@ describe('test/app/service/systems/order_async.syncOrderIds.test.js', () => { assert.equal(result.sync_results.length, 1); assert.equal(result.sync_results[0].status, 'success'); assert.equal(outboundCalls.length, 1); + assert.deepEqual(outboundCalls[0].meta, { + orderId: 1, + orderNo: 'DO-1001', + orderItemId: 101, + }); }); it('should process QM orders concurrently per order', async () => { diff --git a/test/app/service/systems/order_print.getWavePlatformPrintData.test.js b/test/app/service/systems/order_print.getWavePlatformPrintData.test.js index 867b231..8833642 100644 --- a/test/app/service/systems/order_print.getWavePlatformPrintData.test.js +++ b/test/app/service/systems/order_print.getWavePlatformPrintData.test.js @@ -700,6 +700,45 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js' assert.equal(capturedWhere.business_key, 1); }); + it('should keep original platform value in resolvePrintPlatformCode without alias mapping', () => { + const service = createOrderPrintServiceHarness(); + + const platformCode = service.resolvePrintPlatformCode( + { + sys_platform_code: ' Taobao ', + source_platform_code: ' tb ', + }, + { + platform_code: ' cainiao ', + } + ); + + assert.equal(platformCode, 'Taobao'); + }); + + it('should keep original platform field in buildOrderPlatformPrintItem result', () => { + const service = createOrderPrintServiceHarness(); + + const result = service.buildOrderPlatformPrintItem({ + orderRow: { + id: 301, + wave_id: 31, + wave_no: 'W031', + delivery_order_code: 'DO301', + store_id: 1, + warehouse_id: 100000, + }, + orderExpress: { + waybill_code: 'WB301', + }, + policyConfig: {}, + platformCode: ' Taobao ', + templateSample: {}, + }); + + assert.equal(result.platform, 'Taobao'); + }); + it('should throw when business_key=1 waybill data is missing', async () => { const service = createOrderPrintServiceHarness(); @@ -758,7 +797,7 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js' ); }); - it('should return waveGroups grouped by wave then platform and keep summary counters correct', async () => { + it('should return waveGroups grouped by wave then platform+sys_logistics and keep summary counters correct', async () => { const service = createOrderPrintServiceHarness(); service.queryWavesByIds = async () => ([ @@ -863,6 +902,8 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js' { platform: 'cainiao', platform_name: '菜鸟', + sys_logistics_code: 'unknown', + sys_logistics_name: 'unknown', order_count: 1, orders: [ { @@ -874,6 +915,8 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js' { platform: 'jd', platform_name: '京东', + sys_logistics_code: 'unknown', + sys_logistics_name: 'unknown', order_count: 1, orders: [ { @@ -893,6 +936,8 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js' { platform: 'jd', platform_name: '京东', + sys_logistics_code: 'unknown', + sys_logistics_name: 'unknown', order_count: 1, orders: [ { @@ -910,6 +955,95 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js' }); }); + it('should group platform orders by platform+sys_logistics as flattened platform items', () => { + const service = createOrderPrintServiceHarness(); + + const waveGroups = service.groupOrderPrintItemsByWaveAndPlatform({ + waveRows: [ + { wave_id: 1, wave_no: 'W001' }, + ], + hitWaveIds: [ 1 ], + orderPrintList: [ + { + wave_id: 1, + platform: 'jd', + platform_name: '京东', + sys_logistics_code: 'ZTO', + sys_logistics_name: '中通快递', + print_data: { order_id: 11 }, + }, + { + wave_id: 1, + platform: 'jd', + platform_name: '京东', + sys_logistics_code: 'YTO', + sys_logistics_name: '圆通速递', + print_data: { order_id: 12 }, + }, + { + wave_id: 1, + platform: 'jd', + platform_name: '京东', + sys_logistics_code: 'ZTO', + sys_logistics_name: '中通快递', + print_data: { order_id: 13 }, + }, + { + wave_id: 1, + platform: 'jd', + platform_name: '京东', + sys_logistics_code: '', + sys_logistics_name: '', + print_data: { order_id: 14 }, + }, + ], + }); + + assert.equal(waveGroups.length, 1); + assert.equal(waveGroups[0].platforms.length, 3); + assert.equal(waveGroups[0].order_count, 4); + + const ztoGroup = waveGroups[0].platforms.find(item => item && item.sys_logistics_code === 'ZTO'); + assert.ok(ztoGroup); + assert.deepEqual(ztoGroup, { + platform: 'jd', + platform_name: '京东', + sys_logistics_code: 'ZTO', + sys_logistics_name: '中通快递', + order_count: 2, + orders: [ + { order_id: 11 }, + { order_id: 13 }, + ], + }); + + const ytoGroup = waveGroups[0].platforms.find(item => item && item.sys_logistics_code === 'YTO'); + assert.ok(ytoGroup); + assert.deepEqual(ytoGroup, { + platform: 'jd', + platform_name: '京东', + sys_logistics_code: 'YTO', + sys_logistics_name: '圆通速递', + order_count: 1, + orders: [ + { order_id: 12 }, + ], + }); + + const unknownGroup = waveGroups[0].platforms.find(item => item && item.sys_logistics_code === 'unknown'); + assert.ok(unknownGroup); + assert.deepEqual(unknownGroup, { + platform: 'jd', + platform_name: '京东', + sys_logistics_code: 'unknown', + sys_logistics_name: 'unknown', + order_count: 1, + orders: [ + { order_id: 14 }, + ], + }); + }); + it('should batch load picking locations from wms_picking for print items', async () => { const service = createOrderPrintServiceHarness(); const currentOrderItemsModel = { @@ -988,7 +1122,7 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js' wave_id: 30, wave_index: 12, platforms_index: 3, - } ], + }], ]); service.queryWaveTotalOrderCountMap = async () => new Map([ [ 30, 66 ], @@ -996,7 +1130,7 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js' service.getPolicyConfigMapByStore = async () => new Map([ [ 1, { waybill_custom_display_type: '4', - } ], + }], ]); service.loadTemplateSampleByPlatform = () => ({ cmd: 'print', @@ -1054,6 +1188,82 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js' assert.ok(printText.includes('E2区08-05-02 55443 【1】')); }); + it('should use real order wave_id for wave total count when wave index has dirty wave_id', async () => { + const service = createOrderPrintServiceHarness(); + let capturedWaveIdsForIndexQuery = []; + let capturedWaveIdsForCountQuery = []; + + service.queryWavesByIds = async () => ([ + { wave_id: 40, wave_no: 'W040' }, + ]); + service.queryOrdersByWaveIds = async () => ([ + { + id: 401, + wave_id: 40, + wave_no: 'W040', + warehouse_id: 100000, + store_id: 1, + delivery_order_code: 'O401', + post_status: 'fin', + sys_platform_code: 'pdd', + }, + ]); + service.filterFullyAssignedExpressWaves = () => ({ + validWaveIds: [ 40 ], + filteredWaveIds: [], + }); + service.queryOrderExpressByOrderIds = async () => ([ + { + order_id: 401, + business_key: 1, + waybill_code: 'WB401', + }, + ]); + service.getPolicyConfigMapByStore = async () => new Map([ + [ 1, {}], + ]); + service.queryWaveOrderIndexMapByOrderIds = async (orderIds, warehouseId, waveIds) => { + capturedWaveIdsForIndexQuery = Array.isArray(waveIds) ? waveIds : []; + assert.deepEqual(orderIds, [ 401 ]); + assert.equal(warehouseId, 100000); + + return new Map([ + [ 401, { + wave_id: 999, + wave_index: 7, + platforms_index: 2, + }], + ]); + }; + service.queryWaveTotalOrderCountMap = async waveIds => { + capturedWaveIdsForCountQuery = Array.isArray(waveIds) ? waveIds : []; + return new Map([ + [ 40, 66 ], + [ 999, 1 ], + ]); + }; + service.loadTemplateSampleByPlatform = () => ({}); + service.buildOrderPlatformPrintItem = ({ orderRow, platformCode }) => ({ + wave_id: Number(orderRow.wave_id || 0), + platform: String(platformCode || ''), + platform_name: '拼多多', + print_data: { + order_id: Number(orderRow.id || 0), + wave_total_orders: Number(orderRow.wave_total_orders || 0), + }, + }); + + const result = await service.getWavePlatformPrintData({ + waveIds: [ 40 ], + warehouseId: 100000, + }); + + assert.deepEqual(capturedWaveIdsForIndexQuery, [ 40 ]); + assert.deepEqual(capturedWaveIdsForCountQuery, [ 40 ]); + assert.ok(!capturedWaveIdsForCountQuery.includes(999)); + assert.equal(result.waveGroups[0].platforms[0].orders[0].wave_total_orders, 66); + }); + it('should prefer snapshot item_name for display type 2 in getWavePlatformPrintData', async () => { const service = createOrderPrintServiceHarness(); const currentOrderItemsModel = { @@ -1132,7 +1342,7 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js' wave_id: 31, wave_index: 1, platforms_index: 1, - } ], + }], ]); service.queryWaveTotalOrderCountMap = async () => new Map([ [ 31, 10 ], @@ -1140,7 +1350,7 @@ describe('test/app/service/systems/order_print.getWavePlatformPrintData.test.js' service.getPolicyConfigMapByStore = async () => new Map([ [ 1, { waybill_custom_display_type: '2', - } ], + }], ]); service.loadTemplateSampleByPlatform = () => ({ cmd: 'print', diff --git a/test/app/service/systems/stock_store.outbound.picking.test.js b/test/app/service/systems/stock_store.outbound.picking.test.js new file mode 100644 index 0000000..cecec44 --- /dev/null +++ b/test/app/service/systems/stock_store.outbound.picking.test.js @@ -0,0 +1,145 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const StockStoreService = require('../../../../app/service/systems/stock_store'); + +function createHarness() { + const stockTransactionCalls = []; + const ctx = { + user: { + store_id: 100000, + employees_id: 9001, + employees_name: '测试用户', + }, + model: { + Picking: { + async findAll() { + return [ + { + storage_id: 501, + space_id: 601, + quantity: 2, + }, + { + storage_id: 502, + space_id: 602, + quantity: 1, + }, + ]; + }, + }, + StockWarehouse: { + async update() { + return [ 1 ]; + }, + async findByPk() { + return { + id: 77, + warehouse_id: 100000, + quantity: 5, + locked_quantity: 1, + update_at: new Date('2026-05-15T08:00:00.000Z'), + }; + }, + }, + }, + service: { + systems: { + stockTransaction: { + async create(payload) { + stockTransactionCalls.push(payload); + return { + id: stockTransactionCalls.length, + }; + }, + }, + }, + }, + }; + + const app = { + Sequelize: { + Op: { + gte: Symbol('gte'), + }, + literal(sql) { + return sql; + }, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + }; + + ctx.app = app; + ctx.logger = app.logger; + + const service = new StockStoreService(ctx); + service.getItemStorages = async () => { + return { + success: true, + data: { + storage: { + exists: true, + id: 77, + storeId: 200001, + quantity: 10, + lockedQuantity: 6, + }, + }, + }; + }; + service.getStoreWarehousePolicyConfigByStockId = async () => { + return { + allowOversell: false, + }; + }; + service.clearItemStorageCache = async () => {}; + + return { + service, + stockTransactionCalls, + }; +} + +describe('test/app/service/systems/stock_store.outbound.picking.test.js', () => { + it('should write outbound transactions by picking rows with order and location fields', async () => { + const { service, stockTransactionCalls } = createHarness(); + + const result = await service.outbound(1001, 5, { + id: 'tx-1', + }, { + orderId: 2001, + orderNo: 'DO-2001', + orderItemId: 3001, + }); + + assert.equal(result.success, true); + assert.equal(stockTransactionCalls.length, 3); + + assert.equal(stockTransactionCalls[0].storage_id, 501); + assert.equal(stockTransactionCalls[0].space_id, 601); + assert.equal(stockTransactionCalls[0].quantity, 2); + assert.equal(stockTransactionCalls[0].order_id, 2001); + assert.equal(stockTransactionCalls[0].order_no, 'DO-2001'); + + assert.equal(stockTransactionCalls[1].storage_id, 502); + assert.equal(stockTransactionCalls[1].space_id, 602); + assert.equal(stockTransactionCalls[1].quantity, 1); + assert.equal(stockTransactionCalls[1].order_id, 2001); + assert.equal(stockTransactionCalls[1].order_no, 'DO-2001'); + + assert.equal(stockTransactionCalls[2].storage_id, null); + assert.equal(stockTransactionCalls[2].space_id, null); + assert.equal(stockTransactionCalls[2].quantity, 2); + assert.equal(stockTransactionCalls[2].order_id, 2001); + assert.equal(stockTransactionCalls[2].order_no, 'DO-2001'); + + stockTransactionCalls.forEach(payload => { + assert.equal(payload.store_id, 200001); + assert.equal(payload.remark, '订单出库'); + }); + }); +}); diff --git a/test/app/service/systems/stock_transaction.create.test.js b/test/app/service/systems/stock_transaction.create.test.js index 9bf7a1f..25e53f7 100644 --- a/test/app/service/systems/stock_transaction.create.test.js +++ b/test/app/service/systems/stock_transaction.create.test.js @@ -6,6 +6,15 @@ const StockTransactionService = require('../../../../app/service/systems/stock_t function createServiceHarness() { const calls = { createArgs: null, + orderFindOneArgs: null, + }; + + const state = { + orderRow: { + id: 500001, + source_order_codes: 'SRC-ORDER-001,SRC-ORDER-002', + wave_no: 'WAVE-001', + }, }; const model = { @@ -21,6 +30,12 @@ function createServiceHarness() { }; }, }, + OrderDelivery: { + async findOne(query) { + calls.orderFindOneArgs = query; + return state.orderRow; + }, + }, }; const ctx = { @@ -35,10 +50,25 @@ function createServiceHarness() { return { service, calls, + state, }; } describe('test/app/service/systems/stock_transaction.create.test.js', () => { + it('should throw error when transaction is missing', async () => { + const { service } = createServiceHarness(); + + await assert.rejects(async () => { + await service.create({ + transaction_type: 'INBOUND', + warehouse_id: 100000, + store_id: 1000000, + stock_id: 200001, + quantity: 12, + }); + }, /stockTransaction\.create.*transaction/); + }); + it('should create stock transaction with snapshot fields', async () => { const { service, calls } = createServiceHarness(); const transaction = { @@ -82,4 +112,195 @@ describe('test/app/service/systems/stock_transaction.create.test.js', () => { assert.equal(calls.createArgs.payload.quantity, 12); assert.equal(calls.createArgs.payload.transaction_type, 'INBOUND'); }); + + it('should force inbound order_id to null when upstream passes order_id', async () => { + const { service, calls } = createServiceHarness(); + const transaction = { + id: 'tx-inbound-null-order-id', + }; + + await service.create({ + transaction_type: 'INBOUND', + warehouse_id: 100000, + store_id: 1000000, + stock_id: 200001, + quantity: 5, + order_type: 'SCRK', + order_no: 'EO-999999', + order_id: 999999, + remark: '入库测试', + }, { + transaction, + }); + + assert.equal(calls.createArgs.payload.order_id, null); + assert.equal(calls.createArgs.payload.order_no, 'EO-999999'); + assert.equal(calls.createArgs.payload.order_type, 'SCRK'); + }); + + it('should normalize outbound order fields by order id and source_order_codes', async () => { + const { service, calls } = createServiceHarness(); + const transaction = { + id: 'tx-2', + }; + + await service.create({ + transaction_type: 'OUTBOUND', + warehouse_id: 100000, + store_id: 1000000, + stock_id: 200001, + quantity: 3, + order_type: 'STOCK_STORE_OUTBOUND', + order_id: 500001, + order_no: 'DO-500001', + remark: '订单出库', + }, { + transaction, + }); + + assert.ok(calls.orderFindOneArgs, '应查询订单来源单号用于出库流水兜底'); + assert.equal(calls.orderFindOneArgs.where.id, 500001); + assert.equal(calls.orderFindOneArgs.transaction, transaction); + assert.equal(calls.createArgs.payload.order_id, 500001); + assert.equal(calls.createArgs.payload.order_no, 'SRC-ORDER-001,SRC-ORDER-002'); + assert.equal(calls.createArgs.payload.order_type, 'ORDER'); + assert.equal(calls.createArgs.payload.batch_no, 'WAVE-001'); + }); + + it('should keep non-inbound order_id unchanged for outbound transaction', async () => { + const { service, calls } = createServiceHarness(); + const transaction = { + id: 'tx-outbound-keep-order-id', + }; + + await service.create({ + transaction_type: 'OUTBOUND', + warehouse_id: 100000, + store_id: 1000000, + stock_id: 200001, + quantity: 3, + order_type: 'STOCK_STORE_OUTBOUND', + order_id: 500001, + source_order_codes: 'SRC-ORDER-001,SRC-ORDER-002', + remark: '订单出库', + }, { + transaction, + }); + + assert.equal(calls.createArgs.payload.order_id, 500001); + assert.equal(calls.createArgs.payload.order_type, 'ORDER'); + }); + + it('should overwrite outbound batch_no with wave_no when order has wave_no', async () => { + const { service, calls, state } = createServiceHarness(); + const transaction = { + id: 'tx-2-1', + }; + + state.orderRow = { + id: 500001, + source_order_codes: 'SRC-ORDER-009', + wave_no: 'WAVE-009', + }; + + await service.create({ + transaction_type: 'OUTBOUND', + warehouse_id: 100000, + store_id: 1000000, + stock_id: 200001, + quantity: 3, + order_type: 'ANY_UPSTREAM_TYPE', + order_id: 500001, + source_order_codes: 'SRC-ORDER-009', + batch_no: 'UPSTREAM-BATCH-009', + remark: '订单出库', + }, { + transaction, + }); + + assert.equal(calls.createArgs.payload.order_type, 'ORDER'); + assert.equal(calls.createArgs.payload.order_id, 500001); + assert.equal(calls.createArgs.payload.order_no, 'SRC-ORDER-009'); + assert.equal(calls.createArgs.payload.batch_no, 'WAVE-009'); + }); + + it('should set outbound batch_no to null when order wave_no is empty', async () => { + const { service, calls, state } = createServiceHarness(); + const transaction = { + id: 'tx-2-1-null', + }; + + state.orderRow = { + id: 500001, + source_order_codes: 'SRC-ORDER-010', + wave_no: '', + }; + + await service.create({ + transaction_type: 'OUTBOUND', + warehouse_id: 100000, + store_id: 1000000, + stock_id: 200001, + quantity: 3, + order_type: 'ORDER', + order_id: 500001, + source_order_codes: 'SRC-ORDER-010', + batch_no: 'UPSTREAM-BATCH-010', + remark: '订单出库', + }, { + transaction, + }); + + assert.equal(calls.createArgs.payload.order_type, 'ORDER'); + assert.equal(calls.createArgs.payload.batch_no, null); + }); + + it('should keep non-order outbound order_type unchanged', async () => { + const { service, calls } = createServiceHarness(); + const transaction = { + id: 'tx-2-2', + }; + + await service.create({ + transaction_type: 'OUTBOUND', + warehouse_id: 100000, + store_id: 1000000, + stock_id: 200001, + quantity: 2, + order_type: 'STOCK_MOVE', + batch_no: 'MOVE-BATCH-001', + order_id: null, + order_no: 'MOVE-001', + remark: '移库出库', + }, { + transaction, + }); + + assert.equal(calls.createArgs.payload.order_type, 'STOCK_MOVE'); + assert.equal(calls.createArgs.payload.order_no, 'MOVE-001'); + assert.equal(calls.createArgs.payload.batch_no, 'MOVE-BATCH-001'); + assert.equal(calls.orderFindOneArgs, null); + }); + + it('should reject outbound transaction when order_id is invalid', async () => { + const { service } = createServiceHarness(); + const transaction = { + id: 'tx-3', + }; + + await assert.rejects(async () => { + await service.create({ + transaction_type: 'OUTBOUND', + warehouse_id: 100000, + store_id: 1000000, + stock_id: 200001, + quantity: 1, + order_type: 'STOCK_STORE_OUTBOUND', + order_id: null, + remark: '订单出库', + }, { + transaction, + }); + }, /order_id 必须为订单主键 id/); + }); }); diff --git a/test/app/service/systems/storage.inventory.transfer.test.js b/test/app/service/systems/storage.inventory.transfer.test.js new file mode 100644 index 0000000..0520554 --- /dev/null +++ b/test/app/service/systems/storage.inventory.transfer.test.js @@ -0,0 +1,374 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const StorageInventoryService = require('../../../../app/service/systems/storage/inventory'); + +/** + * 创建移库测试支架。 + * @return {{service: StorageInventoryService, calls: Object}} 测试支架 + */ +function createTransferHarness() { + const calls = { + stockTransactions: [], + storageUpdates: [], + locationSpaceUpdates: [], + commitCount: 0, + rollbackCount: 0, + }; + + const transaction = { + LOCK: { + UPDATE: 'UPDATE', + }, + async commit() { + calls.commitCount += 1; + }, + async rollback() { + calls.rollbackCount += 1; + }, + }; + + const srcRecord = { + id: 11, + warehouse_id: 100000, + store_id: 100001, + space_id: 21, + stock_id: 301, + batch_no: 'BATCH-TRANSFER-001', + inventory_type: 'ZP', + quantity: 10, + locked_quantity: 0, + available_quantity: 10, + is_enabled: 1, + delete_at: null, + }; + + const model = { + async transaction() { + return transaction; + }, + StockWarehouse: { + async findOne() { + return { + id: 301, + quantity: 100, + locked_quantity: 12, + }; + }, + }, + Storage: { + async findOne(args) { + if (typeof args.where.id === 'number') { + return srcRecord; + } + return null; + }, + async update(values, options) { + calls.storageUpdates.push({ values, options }); + }, + async count() { + return 0; + }, + }, + LocationSpace: { + async findOne() { + return { + id: 22, + warehouse_id: 100000, + is_enabled: true, + space_status: 'AVAILABLE', + space_code: 'A-22', + }; + }, + async update(values, options) { + calls.locationSpaceUpdates.push({ values, options }); + }, + }, + }; + + const ctx = { + model, + app: { + Sequelize: { + Op: { + ne: '$ne', + }, + literal(value) { + return { literal: value }; + }, + }, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + user: { + employees_id: 'EMP-001', + employees_name: '测试操作员', + }, + service: { + systems: { + stockTransaction: { + async create(payload, options) { + calls.stockTransactions.push({ payload, options }); + return { id: calls.stockTransactions.length, ...payload }; + }, + }, + operationLog: { + async createOperationLog() {}, + }, + notice: { + async send() {}, + }, + }, + }, + }; + + return { + service: new StorageInventoryService(ctx), + calls, + }; +} + +/** + * 创建按商品移库测试支架。 + * @return {{service: StorageInventoryService, calls: Object}} 测试支架 + */ +function createTransferByProductHarness() { + const calls = { + stockTransactions: [], + storageUpdates: [], + storageCreates: [], + locationSpaceUpdates: [], + commitCount: 0, + rollbackCount: 0, + }; + + const transaction = { + LOCK: { + UPDATE: 'UPDATE', + }, + async commit() { + calls.commitCount += 1; + }, + async rollback() { + calls.rollbackCount += 1; + }, + }; + + const srcRecords = [ + { + id: 101, + warehouse_id: 100000, + store_id: 100001, + space_id: 21, + stock_id: 301, + batch_no: null, + inventory_type: 'ZP', + quantity: 2, + locked_quantity: 0, + available_quantity: 2, + is_enabled: 1, + delete_at: null, + }, + { + id: 102, + warehouse_id: 100000, + store_id: 100001, + space_id: 21, + stock_id: 301, + batch_no: null, + inventory_type: 'ZP', + quantity: 4, + locked_quantity: 0, + available_quantity: 4, + is_enabled: 1, + delete_at: null, + }, + ]; + + const model = { + async transaction() { + return transaction; + }, + StockWarehouse: { + async findOne() { + return { + id: 301, + is_batch_mgmt: 'N', + quantity: 50, + locked_quantity: 7, + }; + }, + }, + Storage: { + async findAll() { + return srcRecords; + }, + async findOne() { + return null; + }, + async update(values, options) { + calls.storageUpdates.push({ values, options }); + }, + async create(payload) { + const created = { + id: 900 + calls.storageCreates.length + 1, + ...payload, + }; + calls.storageCreates.push(created); + return created; + }, + async count(options) { + if (options.where.space_id === 22) { + return 0; + } + return 1; + }, + }, + LocationSpace: { + async findOne() { + return { + id: 22, + warehouse_id: 100000, + is_enabled: true, + space_status: 'AVAILABLE', + space_code: 'A-22', + }; + }, + async update(values, options) { + calls.locationSpaceUpdates.push({ values, options }); + }, + }, + }; + + const ctx = { + model, + app: { + Sequelize: { + Op: { + ne: '$ne', + }, + literal(value) { + return { literal: value }; + }, + }, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + user: { + employees_id: 'EMP-001', + employees_name: '测试操作员', + }, + service: { + systems: { + stockTransaction: { + async create(payload, options) { + calls.stockTransactions.push({ payload, options }); + return { id: calls.stockTransactions.length, ...payload }; + }, + }, + operationLog: { + async createOperationLog() {}, + }, + notice: { + async send() {}, + }, + }, + }, + }; + + return { + service: new StorageInventoryService(ctx), + calls, + }; +} + +describe('test/app/service/systems/storage.inventory.transfer.test.js', () => { + it('should create TRANSFER_OUT and TRANSFER_IN transactions in transferLocation', async () => { + const { service, calls } = createTransferHarness(); + + const result = await service.transferLocation({ + storage_id: 11, + target_space_id: 22, + quantity: 10, + }); + + assert.equal(result.code, 200); + assert.equal(calls.commitCount, 1); + assert.equal(calls.rollbackCount, 0); + assert.equal(calls.stockTransactions.length, 2); + + const transferOut = calls.stockTransactions[0]; + const transferIn = calls.stockTransactions[1]; + + assert.equal(transferOut.payload.transaction_type, 'TRANSFER_OUT'); + assert.equal(transferOut.payload.storage_id, 11); + assert.equal(transferOut.payload.space_id, 21); + assert.equal(transferOut.payload.quantity, 10); + assert.equal(transferOut.payload.before_quantity, 100); + assert.equal(transferOut.payload.after_quantity, 100); + assert.equal(transferOut.payload.before_locked_quantity, 12); + assert.equal(transferOut.payload.after_locked_quantity, 12); + assert.equal(transferOut.payload.order_id, null); + assert.equal(transferOut.payload.order_no, null); + assert.equal(transferOut.payload.order_type, null); + assert.equal(transferOut.payload.remark, '移库出'); + + assert.equal(transferIn.payload.transaction_type, 'TRANSFER_IN'); + assert.equal(transferIn.payload.storage_id, 11); + assert.equal(transferIn.payload.space_id, 22); + assert.equal(transferIn.payload.quantity, 10); + assert.equal(transferIn.payload.before_quantity, 100); + assert.equal(transferIn.payload.after_quantity, 100); + assert.equal(transferIn.payload.before_locked_quantity, 12); + assert.equal(transferIn.payload.after_locked_quantity, 12); + assert.equal(transferIn.payload.order_id, null); + assert.equal(transferIn.payload.order_no, null); + assert.equal(transferIn.payload.order_type, null); + assert.equal(transferIn.payload.remark, '移库入'); + }); + + it('should create TRANSFER_OUT and TRANSFER_IN transactions in transferByProduct for each toTransfer', async () => { + const { service, calls } = createTransferByProductHarness(); + + const result = await service.transferByProduct({ + space_id: 21, + stock_id: 301, + target_space_id: 22, + quantity: 5, + }); + + assert.equal(result.code, 200); + assert.equal(calls.commitCount, 1); + assert.equal(calls.rollbackCount, 0); + assert.equal(calls.stockTransactions.length, 4); + + const transferOutTransactions = calls.stockTransactions.filter((item) => item.payload.transaction_type === 'TRANSFER_OUT'); + const transferInTransactions = calls.stockTransactions.filter((item) => item.payload.transaction_type === 'TRANSFER_IN'); + + assert.equal(transferOutTransactions.length, 2); + assert.equal(transferInTransactions.length, 2); + + const outTotalQuantity = transferOutTransactions.reduce((sum, item) => sum + Number(item.payload.quantity || 0), 0); + const inTotalQuantity = transferInTransactions.reduce((sum, item) => sum + Number(item.payload.quantity || 0), 0); + assert.equal(outTotalQuantity, 5); + assert.equal(inTotalQuantity, 5); + + for (const tx of calls.stockTransactions) { + assert.equal(tx.payload.before_quantity, tx.payload.after_quantity); + assert.equal(tx.payload.before_locked_quantity, tx.payload.after_locked_quantity); + assert.equal(tx.payload.before_quantity, 50); + assert.equal(tx.payload.after_quantity, 50); + assert.equal(tx.payload.before_locked_quantity, 7); + assert.equal(tx.payload.after_locked_quantity, 7); + assert.equal(tx.payload.order_id, null); + assert.equal(tx.payload.order_no, null); + assert.equal(tx.payload.order_type, null); + } + }); +}); diff --git a/test/app/service/systems/storage.report.test.js b/test/app/service/systems/storage.report.test.js new file mode 100644 index 0000000..4b65f57 --- /dev/null +++ b/test/app/service/systems/storage.report.test.js @@ -0,0 +1,764 @@ +'use strict'; + +const assert = require('node:assert/strict'); +const StorageReportService = require('../../../../app/service/systems/storage/report'); +const StorageReportMethodService = require('../../../../app/service/systemMethods/storage/report'); + +/** + * 构建 storage.report service 测试桩。 + * @param {Object} options 自定义参数 + * @return {{service: StorageReportService, calls: Object}} service 与调用记录 + */ +function createReportServiceHarness(options = {}) { + const calls = { + queries: [], + exports: [], + }; + let queryIndex = 0; + const queryResults = Array.isArray(options.queryResults) ? options.queryResults : []; + + const model = { + async query(sql, queryOptions = {}) { + calls.queries.push({ + sql, + options: queryOptions, + }); + const result = queryResults[queryIndex] || []; + queryIndex += 1; + return result; + }, + StockWarehouse: { + async findAll() { + return options.stockRows || []; + }, + }, + StockBarcode: { + async findAll() { + return options.barcodeRows || []; + }, + }, + Store: { + async findAll() { + return options.storeRows || []; + }, + }, + LocationSpace: { + async findAll() { + return options.spaceRows || []; + }, + }, + }; + + const ctx = { + user: { + store_id: options.warehouseId || 100000, + }, + model, + app: { + Sequelize: { + QueryTypes: { + SELECT: 'SELECT', + }, + }, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + service: { + systems: { + excel: { + async generateAndUpload(exportOptions) { + calls.exports.push(exportOptions); + return { + filename: exportOptions.filename, + fileKey: `exports/mock/${exportOptions.filename}`, + url: `https://cdn.example.com/${exportOptions.filename}`, + }; + }, + }, + }, + }, + }; + + return { + service: new StorageReportService(ctx), + calls, + }; +} + +/** + * 构建 storage.report method 测试桩。 + * @param {Object} options 自定义参数 + * @return {{methodService: StorageReportMethodService, captured: Object, cacheStore: Map}} method 与调用记录 + */ +function createReportMethodHarness(options = {}) { + const captured = { + exportCalls: [], + }; + const cacheStore = new Map(); + + const ctx = { + app: { + Sequelize: { + Op: {}, + }, + async setCacheAsync(cacheKey, value) { + cacheStore.set(cacheKey, value); + }, + async getCacheAsync(cacheKey) { + return cacheStore.get(cacheKey); + }, + }, + service: { + systems: { + storage: { + report: { + async export(startTime, endTime, bySpace, storeIds, sort) { + captured.exportCalls.push({ + startTime, + endTime, + bySpace, + storeIds, + sort, + }); + return options.exportResult || { + filename: '库存报表_20260501_20260502.xlsx', + fileKey: 'exports/mock/库存报表_20260501_20260502.xlsx', + url: 'https://cdn.example.com/库存报表_20260501_20260502.xlsx', + }; + }, + }, + }, + }, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + user: { + store_id: options.warehouseId || 100000, + }, + }; + + const methodService = new StorageReportMethodService(ctx); + methodService.prepareWhereContext = function prepareWhereContext() { + return { + whereValue: { + start_time: '2026-05-01 00:00:00', + end_time: '2026-05-02 23:59:59', + by_space: false, + store_ids: [ 33, 44 ], + sort_field: 'inbound_total', + sort_order: 'ASC', + }, + }; + }; + + return { + methodService, + captured, + cacheStore, + }; +} + +describe('test/app/service/systems/storage.report.test.js', () => { + it('should use last pre-start after and last in-range after by stock+store when by_space is false', async () => { + const { service, calls } = createReportServiceHarness({ + queryResults: [ + [ + { stock_id: 101, store_id: 201, quantity: 99 }, + { stock_id: 102, store_id: 202, quantity: 88 }, + ], + [ + { stock_id: 101, space_id: 11, store_id: 201, inbound_total: 5, outbound_total: 2 }, + { stock_id: 101, space_id: 12, store_id: 201, inbound_total: 3, outbound_total: 1 }, + { stock_id: 102, space_id: 13, store_id: 202, inbound_total: 4, outbound_total: 0 }, + ], + [ + { id: 1, stock_id: 101, space_id: 11, storage_id: 9001, store_id: 201, before_quantity: 50, after_quantity: 55, created_at: '2026-05-01 09:00:00' }, + { id: 2, stock_id: 101, space_id: 12, storage_id: 9009, store_id: 201, before_quantity: 55, after_quantity: 60, created_at: '2026-05-01 10:00:00' }, + { id: 3, stock_id: 101, space_id: 11, storage_id: 9010, store_id: 201, before_quantity: 60, after_quantity: 66, created_at: '2026-05-02 12:00:00' }, + { id: 4, stock_id: 102, space_id: 13, storage_id: 9003, store_id: 202, before_quantity: 3, after_quantity: 4, created_at: '2026-05-02 14:00:00' }, + ], + [ + { id: 10, stock_id: 101, space_id: 11, store_id: 201, after_quantity: 47, created_at: '2026-04-30 09:00:00' }, + { id: 11, stock_id: 101, space_id: 12, store_id: 201, after_quantity: 48, created_at: '2026-04-30 23:00:00' }, + { id: 12, stock_id: 102, space_id: 13, store_id: 202, after_quantity: 2, created_at: '2026-04-30 20:00:00' }, + ], + ], + stockRows: [ + { id: 101, item_name: '商品A', item_code: 'SKU-A' }, + { id: 102, item_name: '商品B', item_code: 'SKU-B' }, + ], + barcodeRows: [ + { stock_id: 101, barcode: 'BC-A-1' }, + { stock_id: 101, barcode: 'BC-A-2' }, + { stock_id: 102, barcode: 'BC-B-1' }, + ], + storeRows: [ + { id: 201, company_name: '货主甲' }, + { id: 202, company_name: '货主乙' }, + ], + }); + + const result = await service.search('2026-05-01 00:00:00', '2026-05-02 23:59:59', false, [ 201, 202 ]); + + assert.equal(result.code, 200); + assert.equal(result.data.list.length, 2); + + const stockA = result.data.list.find(item => item.stock_id === 101 && item.store_id === 201); + assert.ok(stockA); + assert.equal(stockA.begin_total, 48); + assert.equal(stockA.end_total, 66); + assert.equal(stockA.inbound_total, 8); + assert.equal(stockA.outbound_total, 3); + assert.notEqual(stockA.begin_total, 50); + assert.equal(stockA.space_id, undefined); + assert.match(stockA.barcode, /BC-A-1/); + assert.match(stockA.barcode, /BC-A-2/); + + const stockB = result.data.list.find(item => item.stock_id === 102 && item.store_id === 202); + assert.ok(stockB); + assert.equal(stockB.begin_total, 2); + assert.equal(stockB.end_total, 4); + assert.equal(stockB.inbound_total, 4); + assert.equal(stockB.outbound_total, 0); + assert.match(calls.queries[2].sql, /before_quantity/); + assert.doesNotMatch(calls.queries[2].sql, /storage_id/); + assert.match(calls.queries[3].sql, /created_at < :startTime/); + assert.match(calls.queries[3].sql, /after_quantity/); + }); + + it('should keep space dimension with pre-start-last-after for begin and in-range-last-after for end', async () => { + const { service } = createReportServiceHarness({ + queryResults: [ + [ + { stock_id: 301, space_id: 501, store_id: 401, quantity: 7 }, + { stock_id: 301, space_id: 502, store_id: 401, quantity: 11 }, + ], + [ + { stock_id: 301, space_id: 501, store_id: 401, inbound_total: 2, outbound_total: 1 }, + { stock_id: 301, space_id: 502, store_id: 401, inbound_total: 3, outbound_total: 0 }, + ], + [ + { id: 1, stock_id: 301, space_id: 501, storage_id: 8801, store_id: 401, before_quantity: 7, after_quantity: 8, created_at: '2026-05-01 09:00:00' }, + { id: 2, stock_id: 301, space_id: 501, storage_id: 8802, store_id: 401, before_quantity: 8, after_quantity: 10, created_at: '2026-05-01 12:00:00' }, + { id: 3, stock_id: 301, space_id: 502, storage_id: 8803, store_id: 401, before_quantity: 11, after_quantity: 12, created_at: '2026-05-01 10:00:00' }, + ], + [ + { id: 10, stock_id: 301, space_id: 501, store_id: 401, after_quantity: 6, created_at: '2026-04-30 23:00:00' }, + { id: 11, stock_id: 301, space_id: 502, store_id: 401, after_quantity: 10, created_at: '2026-04-30 22:00:00' }, + ], + ], + stockRows: [ + { id: 301, item_name: '商品C', item_code: 'SKU-C' }, + ], + barcodeRows: [ + { stock_id: 301, barcode: 'BC-C-1' }, + ], + storeRows: [ + { id: 401, company_name: '货主丙' }, + ], + spaceRows: [ + { id: 501, custom_name: '高位货架', space_code: 'A-01' }, + { id: 502, custom_name: '', space_code: 'B-02' }, + ], + }); + + const result = await service.search('2026-05-01 00:00:00', '2026-05-01 23:59:59', true, [ 401 ]); + + assert.equal(result.code, 200); + assert.equal(result.data.list.length, 2); + + const spaceA = result.data.list.find(item => item.space_id === 501); + const spaceB = result.data.list.find(item => item.space_id === 502); + assert.ok(spaceA); + assert.ok(spaceB); + assert.equal(spaceA.space_name, '高位货架'); + assert.equal(spaceB.space_name, 'B-02'); + assert.equal(spaceA.begin_total, 6); + assert.equal(spaceA.end_total, 10); + assert.equal(spaceB.begin_total, 10); + assert.equal(spaceB.end_total, 12); + }); + + it('should return base space keys with zero fallback when by_space is true and interval has no transactions', async () => { + const { service } = createReportServiceHarness({ + queryResults: [ + [ + { stock_id: 901, space_id: 301, store_id: 701, quantity: 15 }, + { stock_id: 902, space_id: 302, store_id: 701, quantity: 9 }, + ], + [], + [], + [], + ], + stockRows: [ + { id: 901, item_name: '商品M', item_code: 'SKU-M' }, + { id: 902, item_name: '商品N', item_code: 'SKU-N' }, + ], + storeRows: [ + { id: 701, company_name: '货主M' }, + ], + spaceRows: [ + { id: 301, custom_name: '一号位', space_code: 'A-01' }, + { id: 302, custom_name: '', space_code: 'A-02' }, + ], + }); + + const result = await service.search( + '2026-05-10 00:00:00', + '2026-05-10 23:59:59', + true, + [], + { + sortField: 'begin_total', + sortOrder: 'DESC', + } + ); + + assert.equal(result.code, 200); + assert.equal(result.data.list.length, 2); + + assert.deepEqual(result.data.list[0], { + start_time: '2026-05-10 00:00:00', + end_time: '2026-05-10 23:59:59', + stock_id: 901, + store_id: 701, + space_id: 301, + begin_total: 0, + end_total: 0, + inbound_total: 0, + outbound_total: 0, + store_name: '货主M', + item_name: '商品M', + barcode: '', + item_code: 'SKU-M', + space_name: '一号位', + }); + + assert.deepEqual(result.data.list[1], { + start_time: '2026-05-10 00:00:00', + end_time: '2026-05-10 23:59:59', + stock_id: 902, + store_id: 701, + space_id: 302, + begin_total: 0, + end_total: 0, + inbound_total: 0, + outbound_total: 0, + store_name: '货主M', + item_name: '商品N', + barcode: '', + item_code: 'SKU-N', + space_name: 'A-02', + }); + }); + + it('should return base stocks with zero fallback when by_space is false and interval has no transactions', async () => { + const { service, calls } = createReportServiceHarness({ + queryResults: [ + [ + { stock_id: 701, store_id: 901, quantity: 37 }, + ], + [], + [], + [], + ], + stockRows: [ + { id: 701, item_name: '商品X', item_code: 'SKU-X' }, + ], + storeRows: [ + { id: 901, company_name: '货主X' }, + ], + }); + + const result = await service.search('2026-05-10 00:00:00', '2026-05-10 23:59:59', false, [ 901 ]); + + assert.equal(result.code, 200); + assert.equal(result.data.list.length, 1); + assert.deepEqual(result.data.list[0], { + start_time: '2026-05-10 00:00:00', + end_time: '2026-05-10 23:59:59', + stock_id: 701, + store_id: 901, + begin_total: 0, + end_total: 0, + inbound_total: 0, + outbound_total: 0, + store_name: '货主X', + item_name: '商品X', + barcode: '', + item_code: 'SKU-X', + }); + assert.equal(calls.queries.length, 4); + assert.match(calls.queries[1].sql, /created_at >= :startTime/); + assert.match(calls.queries[1].sql, /created_at <= :endTime/); + assert.deepEqual(calls.queries[1].options.replacements.storeIds, [ 901 ]); + assert.match(calls.queries[3].sql, /created_at < :startTime/); + }); + + it('should sort by end_total in DESC order when sort params are valid', async () => { + const { service } = createReportServiceHarness({ + queryResults: [ + [ + { stock_id: 801, store_id: 901, quantity: 10 }, + { stock_id: 802, store_id: 901, quantity: 20 }, + ], + [ + { stock_id: 801, space_id: 0, store_id: 901, inbound_total: 1, outbound_total: 0 }, + { stock_id: 802, space_id: 0, store_id: 901, inbound_total: 2, outbound_total: 0 }, + ], + [ + { id: 1, stock_id: 801, space_id: 0, storage_id: 9101, store_id: 901, before_quantity: 10, after_quantity: 11, created_at: '2026-05-01 12:00:00' }, + { id: 2, stock_id: 802, space_id: 0, storage_id: 9102, store_id: 901, before_quantity: 20, after_quantity: 22, created_at: '2026-05-01 12:00:00' }, + ], + [], + ], + stockRows: [ + { id: 801, item_name: '商品Y', item_code: 'SKU-Y' }, + { id: 802, item_name: '商品Z', item_code: 'SKU-Z' }, + ], + storeRows: [ + { id: 901, company_name: '货主Y' }, + ], + }); + + const result = await service.search( + '2026-05-01 00:00:00', + '2026-05-01 23:59:59', + false, + [ 901 ], + { + sortField: 'end_total', + sortOrder: 'DESC', + } + ); + + assert.equal(result.code, 200); + assert.equal(result.data.list.length, 2); + assert.equal(result.data.list[0].stock_id, 802); + assert.equal(result.data.list[0].end_total, 22); + assert.equal(result.data.list[1].stock_id, 801); + assert.equal(result.data.list[1].end_total, 11); + }); + + it('should pass destructured where params from method layer to systems layer', async () => { + const captured = { + startTime: null, + endTime: null, + bySpace: null, + storeIds: null, + sort: null, + }; + + const ctx = { + app: { + Sequelize: { + Op: {}, + }, + }, + service: { + systems: { + storage: { + report: { + async search(startTime, endTime, bySpace, storeIds, sort) { + captured.startTime = startTime; + captured.endTime = endTime; + captured.bySpace = bySpace; + captured.storeIds = storeIds; + captured.sort = sort; + return { + code: 200, + message: '查询成功', + data: { list: [] }, + }; + }, + }, + }, + }, + }, + logger: { + info() {}, + warn() {}, + error() {}, + }, + user: { + store_id: 100000, + }, + }; + + const methodService = new StorageReportMethodService(ctx); + methodService.prepareWhereContext = function prepareWhereContext() { + return { + whereValue: { + start_time: '2026-05-01 00:00:00', + end_time: '2026-05-02 23:59:59', + by_space: true, + store_ids: [ 11, 22 ], + sort_field: 'begin_total', + sort_order: 'asc', + }, + }; + }; + + const result = await methodService.search({ + sort: { + sort_field: 'end_total', + sort_order: 'desc', + }, + where: { + start_time: 'ignored', + }, + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.code, 200); + assert.equal(captured.startTime, '2026-05-01 00:00:00'); + assert.equal(captured.endTime, '2026-05-02 23:59:59'); + assert.equal(captured.bySpace, true); + assert.deepEqual(captured.storeIds, [ 11, 22 ]); + assert.deepEqual(captured.sort, { + sortField: 'end_total', + sortOrder: 'desc', + }); + }); + + it('should submit export task and return task_id with submitted status', async () => { + const { methodService } = createReportMethodHarness(); + + const result = await methodService.export({ + sort: { + sort_field: 'end_total', + sort_order: 'desc', + }, + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.code, 1); + assert.ok(result.task_id); + assert.equal(result.status, 'submitted'); + assert.equal(result.progress, 0); + }); + + it('should return success progress and download_url after setImmediate task execution', async () => { + const { methodService, captured } = createReportMethodHarness(); + + const submitResult = await methodService.export({ + sort: { + sort_field: 'end_total', + sort_order: 'desc', + }, + }); + const taskId = submitResult.task_id; + assert.ok(taskId); + + await new Promise(resolve => setImmediate(resolve)); + await new Promise(resolve => setImmediate(resolve)); + + const progressResult = await methodService.exportTaskProgress({ + task_id: taskId, + }); + + assert.equal(progressResult.flag, 'success'); + assert.equal(progressResult.code, 1); + assert.equal(progressResult.task_id, taskId); + assert.equal(progressResult.status, 'success'); + assert.equal(progressResult.progress, 100); + assert.equal(progressResult.download_url, 'https://cdn.example.com/库存报表_20260501_20260502.xlsx'); + assert.equal(captured.exportCalls.length, 1); + assert.equal(captured.exportCalls[0].startTime, '2026-05-01 00:00:00'); + assert.equal(captured.exportCalls[0].endTime, '2026-05-02 23:59:59'); + assert.equal(captured.exportCalls[0].bySpace, false); + assert.deepEqual(captured.exportCalls[0].storeIds, [ 33, 44 ]); + assert.deepEqual(captured.exportCalls[0].sort, { + sortField: 'end_total', + sortOrder: 'desc', + }); + }); + + it('should return not_found when task_id does not exist', async () => { + const { methodService } = createReportMethodHarness(); + + const result = await methodService.exportTaskProgress({ + task_id: 'not_exists_task_id', + }); + + assert.equal(result.flag, 'success'); + assert.equal(result.code, 1); + assert.equal(result.task_id, 'not_exists_task_id'); + assert.equal(result.status, 'not_found'); + assert.equal(result.progress, 0); + assert.equal(result.download_url, ''); + }); + + it('should export summary and transaction sheets with readable detail fields', async () => { + const { service, calls } = createReportServiceHarness({ + queryResults: [ + [ + { stock_id: 701, store_id: 901, quantity: 37 }, + ], + [ + { stock_id: 701, space_id: 0, store_id: 901, inbound_total: 2, outbound_total: 1 }, + ], + [ + { id: 1, stock_id: 701, space_id: 0, storage_id: 5001, store_id: 901, before_quantity: 10, after_quantity: 11, created_at: '2026-05-01 12:00:00' }, + ], + [ + { id: 10, stock_id: 701, space_id: 0, store_id: 901, after_quantity: 9, created_at: '2026-04-30 23:00:00' }, + ], + [ + { + id: 1001, + created_at: '2026-05-01 12:00:00', + transaction_type: ' inbound ', + store_id: 901, + stock_id: 701, + space_id: 301, + quantity: 2, + before_quantity: 10, + after_quantity: 12, + before_locked_quantity: 1, + after_locked_quantity: 1, + batch_no: 'BATCH-001', + inventory_type: 'ZP', + order_type: 'SCRK', + order_no: 'RK20260501001', + order_id: 6001, + receiving_id: 7001, + entry_order_id: 8001, + operator_name: '张三', + remark: '测试备注', + }, + { + id: 1002, + created_at: '2026-05-01 12:30:00', + transaction_type: ' transfer_out ', + store_id: 901, + stock_id: 701, + space_id: 301, + quantity: 1, + before_quantity: 12, + after_quantity: 12, + before_locked_quantity: 0, + after_locked_quantity: 0, + batch_no: 'BATCH-001', + inventory_type: 'ZP', + order_type: null, + order_no: null, + order_id: null, + receiving_id: null, + entry_order_id: null, + operator_name: '张三', + remark: '移库出', + }, + { + id: 1003, + created_at: '2026-05-01 12:31:00', + transaction_type: 'transfer_in', + store_id: 901, + stock_id: 701, + space_id: 301, + quantity: 1, + before_quantity: 15, + after_quantity: 15, + before_locked_quantity: 0, + after_locked_quantity: 0, + batch_no: 'BATCH-001', + inventory_type: 'ZP', + order_type: null, + order_no: null, + order_id: null, + receiving_id: null, + entry_order_id: null, + operator_name: '张三', + remark: '移库入', + }, + { + id: 1004, + created_at: '2026-05-01 12:32:00', + transaction_type: ' custom_type ', + store_id: 901, + stock_id: 701, + space_id: 301, + quantity: 1, + before_quantity: 15, + after_quantity: 16, + before_locked_quantity: 0, + after_locked_quantity: 0, + batch_no: 'BATCH-001', + inventory_type: 'ZP', + order_type: null, + order_no: null, + order_id: null, + receiving_id: null, + entry_order_id: null, + operator_name: '张三', + remark: '未知类型', + }, + ], + ], + stockRows: [ + { id: 701, item_name: '商品X', item_code: 'SKU-X' }, + ], + barcodeRows: [ + { stock_id: 701, barcode: 'BC-X-1' }, + ], + storeRows: [ + { id: 901, company_name: '货主X' }, + ], + spaceRows: [ + { id: 301, custom_name: 'A01位', space_code: 'A-01' }, + ], + }); + + const result = await service.export( + '2026-05-01 00:00:00', + '2026-05-01 23:59:59', + false, + [ 901 ], + { + sortField: 'end_total', + sortOrder: 'DESC', + } + ); + + assert.ok(result.filename.endsWith('.xlsx')); + assert.ok(result.fileKey); + assert.ok(result.url); + assert.equal(calls.exports.length, 1); + + const exportPayload = calls.exports[0]; + assert.equal(exportPayload.sheets.length, 2); + assert.equal(exportPayload.sheets[0].name, '汇总'); + assert.equal(exportPayload.sheets[1].name, '变更记录'); + + assert.equal(exportPayload.sheets[0].rows.length, 1); + assert.equal(exportPayload.sheets[0].rows[0].stock_id, 701); + assert.equal(exportPayload.sheets[0].rows[0].store_name, '货主X'); + + assert.equal(exportPayload.sheets[1].rows.length, 4); + const detailRow = exportPayload.sheets[1].rows[0]; + assert.equal(detailRow.transaction_type, '入库'); + assert.equal(detailRow.store_name, '货主X'); + assert.equal(detailRow.item_code, 'SKU-X'); + assert.equal(detailRow.item_name, '商品X'); + assert.equal(detailRow.barcode, 'BC-X-1'); + assert.equal(detailRow.space_name, 'A01位'); + assert.equal(detailRow.quantity, 2); + assert.equal(detailRow.before_locked_quantity, 1); + assert.equal(detailRow.after_locked_quantity, 1); + assert.equal(detailRow.order_no, 'RK20260501001'); + assert.equal(detailRow.operator_name, '张三'); + + const transferOutRow = exportPayload.sheets[1].rows[1]; + const transferInRow = exportPayload.sheets[1].rows[2]; + const unknownTypeRow = exportPayload.sheets[1].rows[3]; + assert.equal(transferOutRow.transaction_type, '移库出'); + assert.equal(transferInRow.transaction_type, '移库入'); + assert.equal(unknownTypeRow.transaction_type, 'custom_type'); + }); +});