diff --git a/.github/agents/开发.agent.md b/.github/agents/开发.agent.md index 37edf55..2b11c3c 100644 --- a/.github/agents/开发.agent.md +++ b/.github/agents/开发.agent.md @@ -167,6 +167,7 @@ model: GPT-5.3-Codex (copilot) 10. **禁止method入口直接调用model层**,必须先调用service层,保持分层职责的清晰和一致 11. **所有编码风格必须要通过ESLint检查**,禁止任何 ESLint 错误或警告存在于提交的代码中 12. **禁止修改底层公共代码来“顺手解决问题”**,如需要改 `app.js`、`app/extend/application.js`、`app/service/main.js` 等公共能力入口,必须先评估改动影响范围,并优先考虑在业务层做适配或扩展,避免对全局能力造成不确定风险,如确实需要改公共代码,必须先驳回到调度 agent 升级给专家 agent 进行兜底处理,禁止直接改公共代码后再评估风险的流程 +13. system块的methods禁止入参warehouse_id,必须由服务端从当前上下文自动注入,前端无需传递。 ## 关键定位地图 diff --git a/.github/agents/数据库.agent.md b/.github/agents/数据库.agent.md index 8b451ef..a050a04 100644 --- a/.github/agents/数据库.agent.md +++ b/.github/agents/数据库.agent.md @@ -1,4 +1,4 @@ ---- +--- name: wms-db-agent description: "Use when the user asks about 数据库、查数据、SQL、MySQL、库表定位、字段含义、索引建议、接口数据排查、script/db-query.ps1、wms/ye4s client。专用于 WMS 数据库查询与排障。" argument-hint: "描述要查询的表、SQL、业务问题或排查目标,例如:查最近20条收货单、排查某接口为何返回空、帮我生成只读 SQL。" @@ -46,6 +46,36 @@ model : DeepSeek V4 Pro (deepseek) - 所有回复必须以 `[DB]` 开头 - 优先给结论、关键字段和下一步建议 + +## 环境路由规则(⚠️ 必读) + +**每次查询必须明确标注是开发环境还是生产环境,禁止混淆!** + +### 查询方式速查 + +| 环境 | 迁移状态查询 | 数据查询 | +|------|------------|---------| +| **开发环境** | `npx sequelize-cli db:migrate:status` | `powershell -ExecutionPolicy Bypass -File .\script\db-query.ps1 -Query "..." -AsTable` | +| **生产环境** | `$env:NODE_ENV='production'; npx sequelize-cli db:migrate:status --env production` | SSH+mysql 或 `$env:NODE_ENV='production'; npx sequelize-cli ... --env production` | + +- 开发环境:`config/config.local.js` → `mysql.clients.wms` +- 生产环境:`config/config.default.js` → `config.sequelize` + +### 🔴 红线 + +1. **绝对禁止**:用不加 `--env production` 的命令查询,然后声称是生产环境。`script/db-query.ps1` 永远是开发环境! +2. 每次返回结果第一行必须标注环境:`[DB] 开发环境 (config.local.js)` 或 `[DB] 生产环境 (config.default.js)` +3. 查询迁移状态时必须**两边都查**做对比 +4. 若用户提到"生产"二字,必须使用生产环境命令 + +### 当前环境差异(2026-06-25) + +| 项目 | 开发环境 | 生产环境 | +|------|---------|---------| +| SequelizeMeta 记录数 | 127+ | 123 | +| 最新迁移 | `20260623140000` | `20260622110000` | +| 缺失迁移 | 无 | 4条 | + ## 常用命令模板 ### 1) 当前连接库自检 diff --git a/.github/agents/调度.agent.md b/.github/agents/调度.agent.md index 71f750c..02ad16b 100644 --- a/.github/agents/调度.agent.md +++ b/.github/agents/调度.agent.md @@ -17,7 +17,7 @@ model: DeepSeek V4 Pro (deepseek) - 将子任务委派给最合适的专属 agent - 等待各子任务返回结果,汇总后给出最终结论 - **不深入专属 agent 的内部技术细节**,只关注其输入、输出和完成状态 - +- 本项目无需重启, 也不需要你直接修改代码、数据库或 Redis;所有操作都必须通过专属 agent 执行 ## 适用范围 以下场景优先使用本 Agent: diff --git a/3 b/3 deleted file mode 100644 index e69de29..0000000 diff --git a/app/lib/express_print_payload_builder.js b/app/lib/express_print_payload_builder.js index e630ac8..9a5e2ac 100644 --- a/app/lib/express_print_payload_builder.js +++ b/app/lib/express_print_payload_builder.js @@ -132,7 +132,7 @@ class ExpressPrintPayloadBuilder { } if (normalizedPlatform === 'sph') { - this.applySphTaskDynamicFields(payload, orders); + payload.taskList = this.buildTaskListFromOrders(orders, idGenerator); } else { if (!isPlainObject(payload.task)) { payload.task = {}; @@ -170,6 +170,28 @@ class ExpressPrintPayloadBuilder { }); } + /** + * 将 orders 映射为 SPH taskList 项。 + * SPH 的 task item 结构(taskID / printInfo / customInfo / extendData 等)与通用 document 结构不兼容, + * 因此需要独立的构建方法,但处理模式与 buildDocumentsFromOrders 一致: + * 遍历 orders → deepClone → 分配唯一 ID → 放入数组。 + * + * @param {Array} orders 订单数组,每个元素直接是 SPH task item 对象。 + * @param {RequestScopedPrintIdGenerator} idGenerator 请求内 ID 生成器。 + * @return {Array} taskList 数组。 + */ + buildTaskListFromOrders(orders, idGenerator) { + const taskList = []; + for (const order of orders) { + if (order && typeof order === 'object' && !Array.isArray(order)) { + const taskItem = deepClone(order); + taskItem.taskID = idGenerator.nextTaskId(); + taskList.push(taskItem); + } + } + return taskList; + } + /** * 将 orders 映射为 documents。 * @param {Array} orders 订单数组。 @@ -188,91 +210,6 @@ class ExpressPrintPayloadBuilder { }); } - /** - * 将 SPH 订单中的动态业务字段回填到模板 taskList[0]。 - * - * 仅覆盖动态字段,避免改写模板固定结构。 - * - * @param {Object} payload 打印请求 payload。 - * @param {Array} orders 外部传入的订单打印数据数组。 - */ - applySphTaskDynamicFields(payload, orders) { - if (!Array.isArray(payload.taskList) || !isPlainObject(payload.taskList[0])) { - return; - } - - const sourceTask = this.resolveSphTaskFromOrders(orders); - if (!isPlainObject(sourceTask)) { - return; - } - - const targetTask = payload.taskList[0]; - const dynamicFields = [ - 'printInfo', - 'printNum', - 'splitControl', - 'showDeliveryLogo', - 'customInfo', - 'extendData', - 'taskID', - ]; - - dynamicFields.forEach(field => { - if (Object.prototype.hasOwnProperty.call(sourceTask, field)) { - targetTask[field] = deepClone(sourceTask[field]); - } - }); - } - - /** - * 从首个订单提取 SPH 动态任务数据。 - * - * 优先读取标准 taskList[0];若上游直接传 task 结构(printInfo/printNum 等)也兼容。 - * - * @param {Array} orders 外部传入的订单打印数据数组。 - * @return {Object|null} SPH 动态任务对象。 - */ - resolveSphTaskFromOrders(orders) { - if (!Array.isArray(orders) || orders.length === 0) { - return null; - } - - const firstOrder = isPlainObject(orders[0]) ? orders[0] : {}; - const candidates = []; - if (isPlainObject(firstOrder.print_data)) { - candidates.push(firstOrder.print_data); - } - if (isPlainObject(firstOrder)) { - candidates.push(firstOrder); - } - - const sphDynamicFields = [ - 'printInfo', - 'printNum', - 'splitControl', - 'showDeliveryLogo', - 'customInfo', - 'extendData', - 'taskID', - ]; - - for (const candidate of candidates) { - if (Array.isArray(candidate.taskList) && isPlainObject(candidate.taskList[0])) { - return candidate.taskList[0]; - } - - if (isPlainObject(candidate.taskList)) { - return candidate.taskList; - } - - if (sphDynamicFields.some(field => Object.prototype.hasOwnProperty.call(candidate, field))) { - return candidate; - } - } - - return null; - } - /** * 解析单个订单对应的 document。 * @param {Object} order 订单对象。 diff --git a/app/model/entry_order_receiving.js b/app/model/entry_order_receiving.js index fd823ad..2100143 100644 --- a/app/model/entry_order_receiving.js +++ b/app/model/entry_order_receiving.js @@ -41,16 +41,16 @@ module.exports = app => { indexes: [ { name: 'idx_entry_order_id', - fields: ['entry_order_id'], + fields: [ 'entry_order_id' ], }, { name: 'idx_receiving_id', - fields: ['receiving_id'], + fields: [ 'receiving_id' ], }, { name: 'uk_entry_order_receiving', unique: true, - fields: ['entry_order_id', 'receiving_id'], + fields: [ 'entry_order_id', 'receiving_id' ], }, ], }); diff --git a/app/model/order_stockout.js b/app/model/order_stockout.js new file mode 100644 index 0000000..601f832 --- /dev/null +++ b/app/model/order_stockout.js @@ -0,0 +1,261 @@ +'use strict'; + +/** + * 出库单主表 Model。 + * + * 对应数据库表 `wms_order_stockout`,存储奇门 stockout.create 接口下发的出库单信息。 + * + * 业务类型枚举值: + * - JYCK:一般交易出库 + * - HHCK:换货出库 + * - BFCK:补发出库 + * - QTCK:其他出库 + * @param {import('egg').Application} app - Egg 应用实例 + */ +module.exports = app => { + const { STRING, INTEGER, BIGINT, ENUM, TEXT, TINYINT, DATE, JSON: JSON_TYPE } = app.Sequelize; + + const OrderStockout = app.model.define('wms_order_stockout', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + stockout_order_code: { + type: STRING(50), + allowNull: false, + comment: '出库单号(对应奇门 deliveryOrderCode)', + validate: { + notEmpty: true, + }, + }, + order_type: { + type: STRING(50), + allowNull: false, + comment: '业务类型(JYCK一般交易出库/HHCK换货出库/BFCK补发出库/QTCK其他出库等)', + validate: { + notEmpty: true, + }, + }, + total_order_lines: { + type: INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '单据总行数', + }, + order_create_time: { + type: DATE, + allowNull: true, + comment: '订单创建时间(对应奇门 createTime)', + }, + source_type: { + type: ENUM('WMS', 'API', 'QM'), + allowNull: false, + defaultValue: 'QM', + comment: '来源类型', + }, + order_status: { + type: ENUM('CREATING', 'CREATED', 'PENDING', 'COMPLETED', 'CANCELLED'), + allowNull: false, + defaultValue: 'CREATED', + comment: '订单状态:CREATING=创建中, CREATED=已创建待审核, PENDING=已审核, COMPLETED=已完成, CANCELLED=已作废', + }, + sync_status: { + type: ENUM('PENDING', 'SUCCESS', 'FAILED'), + allowNull: false, + defaultValue: 'PENDING', + comment: '同步状态', + }, + sync_message: { + type: TEXT, + allowNull: true, + comment: '同步返回信息', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + store_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '货主ID', + }, + store_name: { + type: STRING(200), + allowNull: true, + comment: '货主名称快照', + }, + warehouse_name: { + type: STRING(200), + allowNull: true, + comment: '仓库名称快照', + }, + qimen_owner_code: { + type: STRING(100), + allowNull: true, + comment: '奇门货主code(对应 ownerCode)', + }, + qimen_warehouse_code: { + type: STRING(100), + allowNull: true, + comment: '奇门仓库code(对应 warehouseCode)', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + extend_props: { + type: JSON_TYPE, + allowNull: true, + comment: '扩展属性', + }, + is_enabled: { + type: TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '是否启用', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + deleted_at: { + type: DATE, + allowNull: true, + comment: '软删除时间', + }, + }, { + tableName: 'wms_order_stockout', + comment: '出库单主表', + timestamps: false, + indexes: [ + { + name: 'uk_stockout_order_code', + unique: true, + fields: [ 'stockout_order_code', 'warehouse_id', 'store_id' ], + }, + { + name: 'idx_order_type', + fields: [ 'order_type' ], + }, + { + name: 'idx_order_status', + fields: [ 'order_status' ], + }, + { + name: 'idx_sync_status', + fields: [ 'sync_status' ], + }, + { + name: 'idx_source_type', + fields: [ 'source_type' ], + }, + { + name: 'idx_warehouse_store', + fields: [ 'warehouse_id', 'store_id' ], + }, + { + name: 'idx_order_create_time', + fields: [ 'order_create_time' ], + }, + { + name: 'idx_is_enabled', + fields: [ 'is_enabled' ], + }, + { + name: 'idx_deleted_at', + fields: [ 'deleted_at' ], + }, + ], + }); + + /** + * 关联关系定义。 + * - 关联货主 / 仓库(均通过 Store 表) + * - 关联出库明细表 + */ + OrderStockout.associate = function() { + const { OrderStockout, Store, OrderStockoutItems } = app.model; + + // 关联仓库 + OrderStockout.belongsTo(Store, { + foreignKey: 'warehouse_id', + as: 'warehouse', + }); + + // 关联货主 + OrderStockout.belongsTo(Store, { + foreignKey: 'store_id', + as: 'store', + }); + + // 关联出库明细 + OrderStockout.hasMany(OrderStockoutItems, { + foreignKey: 'order_id', + as: 'items', + }); + }; + + // ---------- 状态机辅助方法 ---------- + + /** 判断订单是否处于"已创建"状态 */ + OrderStockout.prototype.isCreated = function() { + return this.order_status === 'CREATED'; + }; + + /** 判断订单是否处于"已审核"状态 */ + OrderStockout.prototype.isPending = function() { + return this.order_status === 'PENDING'; + }; + + /** 判断订单是否已完成 */ + OrderStockout.prototype.isCompleted = function() { + return this.order_status === 'COMPLETED'; + }; + + /** 判断订单是否已作废 */ + OrderStockout.prototype.isCancelled = function() { + return this.order_status === 'CANCELLED'; + }; + + /** 当前订单是否允许审核 */ + OrderStockout.prototype.canConfirm = function() { + return [ 'CREATED', 'PENDING' ].includes(this.order_status); + }; + + /** 当前订单是否允许取消 */ + OrderStockout.prototype.canCancel = function() { + return [ 'CREATED', 'PENDING' ].includes(this.order_status); + }; + + /** 当前订单是否允许完成 */ + OrderStockout.prototype.canComplete = function() { + return [ 'PENDING' ].includes(this.order_status); + }; + + /** 同步是否成功 */ + OrderStockout.prototype.isSyncSuccess = function() { + return this.sync_status === 'SUCCESS'; + }; + + /** 同步是否失败 */ + OrderStockout.prototype.isSyncFailed = function() { + return this.sync_status === 'FAILED'; + }; + + /** 是否启用(未软删除) */ + OrderStockout.prototype.isEnabled = function() { + return this.is_enabled === 1 && !this.deleted_at; + }; + + return OrderStockout; +}; diff --git a/app/model/order_stockout_items.js b/app/model/order_stockout_items.js new file mode 100644 index 0000000..c8780bb --- /dev/null +++ b/app/model/order_stockout_items.js @@ -0,0 +1,145 @@ +'use strict'; + +/** + * 出库单明细表 Model。 + * + * 对应数据库表 `wms_order_stockout_items`,存储奇门 stockout.create 接口中 + * 每个 节点的明细数据。 + * + * 与主表 `wms_order_stockout` 通过 `order_id` 外键关联(CASCADE 删除)。 + * 与库存表 `wms_stock_warehouse` 通过 `stock_id` 外键关联(RESTRICT 删除)。 + * @param {import('egg').Application} app - Egg 应用实例 + */ +module.exports = app => { + const { STRING, INTEGER, BIGINT, DATE, JSON: JSON_TYPE } = app.Sequelize; + + const OrderStockoutItems = app.model.define('wms_order_stockout_items', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + order_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '出库单ID,外键关联 wms_order_stockout.id', + }, + out_biz_code: { + type: STRING(255), + allowNull: true, + comment: '外部业务编码(幂等键)', + }, + order_line_no: { + type: STRING(50), + allowNull: false, + comment: '订单行号(对应奇门 orderLineNo)', + }, + owner_code: { + type: STRING(50), + allowNull: true, + comment: '货主编码(对应奇门 ownerCode)', + }, + item_code: { + type: STRING(50), + allowNull: true, + comment: '商品编码(对应奇门 itemCode)', + }, + item_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: 'WMS商品ID(对应奇门 itemId)', + }, + item_name: { + type: STRING(200), + allowNull: true, + comment: '商品名称', + }, + plan_qty: { + type: INTEGER(12), + allowNull: true, + comment: '计划数量(对应奇门 planQty)', + }, + actual_qty: { + type: INTEGER(12), + allowNull: false, + defaultValue: 0, + comment: '实发数量', + }, + inventory_type: { + type: STRING(50), + allowNull: true, + comment: '库存类型(ZP正品/CC残次等)', + }, + stock_id: { + type: BIGINT(20), + allowNull: true, + comment: '库存ID,外键关联 wms_stock_warehouse.id', + }, + extend_props: { + type: JSON_TYPE, + allowNull: true, + comment: '扩展属性', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + }, { + tableName: 'wms_order_stockout_items', + comment: '出库明细表', + timestamps: false, + indexes: [ + { + name: 'uk_order_line_no', + unique: true, + fields: [ 'order_id', 'order_line_no' ], + }, + { + name: 'idx_order_id', + fields: [ 'order_id' ], + }, + { + name: 'idx_stock_id', + fields: [ 'stock_id' ], + }, + { + name: 'idx_item_code', + fields: [ 'item_code' ], + }, + { + name: 'idx_out_biz_code', + fields: [ 'out_biz_code' ], + }, + ], + }); + + /** + * 关联关系定义。 + * - 关联出库单主表 + * - 关联商品 SKU(wms_stock_warehouse) + */ + OrderStockoutItems.associate = function() { + const { OrderStockoutItems, OrderStockout, StockWarehouse } = app.model; + + // 关联出库单 + OrderStockoutItems.belongsTo(OrderStockout, { + foreignKey: 'order_id', + as: 'order', + }); + + // 关联商品 SKU + OrderStockoutItems.belongsTo(StockWarehouse, { + foreignKey: 'stock_id', + as: 'stock', + }); + }; + + return OrderStockoutItems; +}; diff --git a/app/model/platform.js b/app/model/platform.js index ab70628..ee16114 100644 --- a/app/model/platform.js +++ b/app/model/platform.js @@ -6,7 +6,7 @@ * @return {import('sequelize').ModelCtor} 平台模型 */ module.exports = app => { - const { STRING, INTEGER, BIGINT } = app.Sequelize; + const { STRING, BIGINT } = app.Sequelize; const Platform = app.model.define('platform', { code: { diff --git a/app/model/receiving.js b/app/model/receiving.js index b8c52ae..71ae988 100644 --- a/app/model/receiving.js +++ b/app/model/receiving.js @@ -38,10 +38,10 @@ module.exports = app => { comment: '明细匹配状态:all_matched-全部匹配, partial_matched-部分匹配, unmatched-未匹配', }, storage_status: { - type: ENUM('none', 'partial', 'all'), + type: ENUM('none', 'waiting', 'partial', 'all'), defaultValue: 'none', allowNull: false, - comment: '入库状态:none-未入库, partial-部分入库, all-全部入库', + comment: '入库状态:none-未入库, waiting-等待入库, partial-部分入库, all-全部入库', }, delivery_method: { type: ENUM('truck', 'express', 'air_freight', 'sea_freight', 'other'), diff --git a/app/model/receiving_detail.js b/app/model/receiving_detail.js index da18c8f..5ff72ee 100644 --- a/app/model/receiving_detail.js +++ b/app/model/receiving_detail.js @@ -61,9 +61,9 @@ module.exports = app => { comment: '收货状态', }, storage_status: { - type: ENUM('none', 'partial', 'all'), + type: ENUM('none', 'waiting', 'partial', 'all'), defaultValue: 'none', - comment: '入库状态:none-未入库, partial-部分入库, all-全部入库', + comment: '入库状态:none-未入库, waiting-等待入库, partial-部分入库, all-全部入库', }, stored_quantity: { type: INTEGER, diff --git a/app/service/apiMethods/test.js b/app/service/apiMethods/test.js index 45bc1e5..b9ab6b0 100644 --- a/app/service/apiMethods/test.js +++ b/app/service/apiMethods/test.js @@ -18,10 +18,6 @@ class testServer extends Service { } } - async entryorderConfirm(data) { - const { ctx } = this; - return await ctx.service.systems.entryOrder.entryorderConfirm(data.id, data.isCompleted); - } async playbackRequest(data) { const { app } = this; try { diff --git a/app/service/im.js b/app/service/im.js index dcdedc1..b8429dc 100644 --- a/app/service/im.js +++ b/app/service/im.js @@ -75,7 +75,7 @@ class ImService extends Service { } /** * 获取主体员工信息 - * @param data {Object<>} 请求数据,包含 store_id + * @param {Object} data 请求数据,包含 store_id * @return {Promise<{code: number, message: string, data: Array}>} 响应数据,包含员工列表 */ async getStoreEmployees(data) { diff --git a/app/service/main.js b/app/service/main.js index 5b0f62c..b2a13bc 100644 --- a/app/service/main.js +++ b/app/service/main.js @@ -338,7 +338,9 @@ class MainService extends Service { const decoded = app.jwt.verify(token, app.config.jwt.secret); const now = Math.floor(Date.now() / 1000); const expiresIn = decoded.exp - now; - if (expiresIn < 14399 && expiresIn > 0) { + const renewThreshold = app.config.jwt.renewThreshold + ?? (app.config.jwt.expiresIn ? app.config.jwt.expiresIn - 1 : 14399); + if (expiresIn < renewThreshold && expiresIn > 0) { // 移除过期时间(exp)和签发时间(iat),保留其他payload const payload = { ...decoded }; delete payload.exp; diff --git a/app/service/openapi/callback.js b/app/service/openapi/callback.js index e9b2995..016a908 100644 --- a/app/service/openapi/callback.js +++ b/app/service/openapi/callback.js @@ -7,7 +7,7 @@ const { signRequest } = require('../../lib/api_sign'); const MAX_RETRY = 3; /** @type {number[]} 递增重试延迟(毫秒) */ -const RETRY_DELAY_MS = [2000, 5000, 15000]; +const RETRY_DELAY_MS = [ 2000, 5000, 15000 ]; /** * OpenAPI 统一回调通知服务。 @@ -166,7 +166,7 @@ class OpenapiCallbackService extends Service { } const appConfig = await ctx.model.ApiApp.findOne({ - attributes: ['self_app_key', 'self_app_secret', 'callback_url'], + attributes: [ 'self_app_key', 'self_app_secret', 'callback_url' ], where: { self_app_key: normalizedAppKey, is_enabled: 1, @@ -204,11 +204,10 @@ class OpenapiCallbackService extends Service { * @param {string} options.callbackUrl 回调目标 URL。 * @param {boolean} options.success 是否成功。 * @param {number} options.retryCount 重试次数。 - * @param {*} options.response 响应数据。 * @param {string} [options.error] 错误信息。 * @return {void} 无返回值。 */ - async logCallback({ appKey, event, callbackUrl, success, retryCount, response, error }) { + async logCallback({ appKey, event, callbackUrl, success, retryCount, error }) { const { ctx } = this; const logMessage = `[OpenapiCallback] event=${event} appKey=${appKey} url=${callbackUrl} retry=${retryCount} success=${success}`; diff --git a/app/service/openapiMethods/callback.js b/app/service/openapiMethods/callback.js index 1daa9a7..0ee4cd7 100644 --- a/app/service/openapiMethods/callback.js +++ b/app/service/openapiMethods/callback.js @@ -23,7 +23,7 @@ class OpenapiCallbackMethodService extends MainService { } const appConfig = await ctx.model.ApiApp.findOne({ - attributes: ['self_app_key'], + attributes: [ 'self_app_key' ], where: { self_app_key: normalizedAppKey, is_enabled: 1, diff --git a/app/service/openapiMethods/deliveryorder.js b/app/service/openapiMethods/deliveryorder.js index 6d47240..8cbda55 100644 --- a/app/service/openapiMethods/deliveryorder.js +++ b/app/service/openapiMethods/deliveryorder.js @@ -20,7 +20,7 @@ class OpenapiDeliveryorderService extends MainService { attributes: [ 'id', 'warehouse_id', - [app.Sequelize.col('contract.store_id'), 'store_id'], + [ app.Sequelize.col('contract.store_id'), 'store_id' ], ], where: { self_app_key: normalizedAppKey, diff --git a/app/service/openapiMethods/order.js b/app/service/openapiMethods/order.js index 81aef19..27be4b4 100644 --- a/app/service/openapiMethods/order.js +++ b/app/service/openapiMethods/order.js @@ -129,6 +129,26 @@ class OpenapiOrderService extends MainService { await transaction.commit(); + // 写入取消操作日志(不影响主流程) + try { + if (this.ctx.model && this.ctx.model.OperationLog) { + const appKey = String(query.app_key || '').trim(); + await this.ctx.model.OperationLog.create({ + business_type: 'order', + business_id: String(existingOrder.id), + operation_code: 'ORDER_CANCEL', + operator_id: null, + operator_name: appKey ? `openapi:${appKey}` : 'openapi', + external_log_type: 'NONE', + warehouse_id: info.warehouseId || null, + platform_code: appKey || 'SYSTEM', + message: 'OpenAPI 取消订单', + }); + } + } catch (logErr) { + this.ctx.logger.warn('[OpenapiOrderCancel] 写入取消操作日志失败,不影响主流程', logErr); + } + // 取消成功后触发 OpenAPI 回调通知(fire-and-forget,不阻塞主流程) try { const callbackService = this.ctx.service.openapi && this.ctx.service.openapi.callback; diff --git a/app/service/qimenMethods/order.js b/app/service/qimenMethods/order.js index adac7d9..2b2370f 100644 --- a/app/service/qimenMethods/order.js +++ b/app/service/qimenMethods/order.js @@ -203,6 +203,25 @@ class orderServer extends MainService { return this.fail('取消失败,已通知拦截执行'); } + // 已同步订单不允许取消,转为拦截处理 + const syncStatus = String(existingOrder.sync_status || '').trim(); + if (syncStatus === 'fin') { + await existingOrder.update({ + intercept_status: 'requested', + updated_at: new Date(), + }, { + transaction, + }); + + await transaction.commit(); + await this.sendCancelInterceptNotice({ + orderCode, + existingOrder, + info, + }); + return this.fail('订单已同步,不可取消,已转为拦截处理'); + } + await existingOrder.update({ status: 'cancel', outbound_status: 'fin', @@ -220,6 +239,27 @@ class orderServer extends MainService { }); await transaction.commit(); + + // 写入取消操作日志(不影响主流程) + try { + if (ctx.model && ctx.model.OperationLog) { + const customerId = String(info.customerId || '').trim(); + await ctx.model.OperationLog.create({ + business_type: 'order', + business_id: String(existingOrder.id), + operation_code: 'ORDER_CANCEL', + operator_id: null, + operator_name: customerId ? `qimen:${customerId}` : 'qimen', + external_log_type: 'NONE', + warehouse_id: info.warehouseId || null, + platform_code: customerId || 'SYSTEM', + message: '奇门取消订单', + }); + } + } catch (logErr) { + ctx.logger.warn('[QimenOrderCancel] 写入取消操作日志失败,不影响主流程', logErr); + } + return this.success('取消订单成功'); } catch (error) { try { diff --git a/app/service/qimenMethods/stockout.js b/app/service/qimenMethods/stockout.js index a5fdb49..5f280e9 100644 --- a/app/service/qimenMethods/stockout.js +++ b/app/service/qimenMethods/stockout.js @@ -2,69 +2,217 @@ const MainService = require('../main'); +/** + * 奇门出库单服务。 + * + * 处理 stockout.create / stockout.query 接口, + * 使用专用表 `wms_order_stockout` + `wms_order_stockout_items`。 + */ class stockoutServer extends MainService { + /** + * 创建出库单。 + * + * 将奇门 stockout.create 请求的 deliveryOrder / orderLines 写入 + * `wms_order_stockout` 主表和 `wms_order_stockout_items` 明细表, + * 整个过程在一个数据库事务内完成,失败自动回滚。 + * + * @param {object} data - 奇门 stockout.create 请求体 + * @param {object} data.request - 请求数据 + * @param {object} data.request.deliveryOrder - 出库单头信息 + * @param {object} data.request.orderLines - 出库单明细 + * @param {object|object[]} data.request.orderLines.orderLine - 明细行(单条为对象,多条为数组) + * @return {Promise} 返回 success / fail 结果 + */ async create(data) { - const { app, ctx, appKey, storeId, warehouseId, customerId, warehouseCode } = this; - const fail = this.fail.bind(this); - const success = this.success.bind(this); + const { app, ctx, appKey, storeId, warehouseId, warehouseCode } = this; + const { deliveryOrder, orderLines } = data.request; - let totalOrderLines = data.request.deliveryOrder.totalOrderLines || 0; - - let orderLine = data.request.orderLines.orderLine; - if (orderLine.orderLineNo) { + // 单条 orderLine 转为数组 + let orderLine = orderLines && orderLines.orderLine; + if (orderLine && orderLine.orderLineNo) { orderLine = [ orderLine ]; } - totalOrderLines = totalOrderLines || orderLine.length; + + if (!orderLine || !Array.isArray(orderLine) || orderLine.length === 0) { + return this.fail('创建出库单失败,失败原因:\n没有有效的订单明细数据'); + } + + const totalOrderLines = deliveryOrder.totalOrderLines || orderLine.length; + + // 第一步:校验所有商品是否在 StockStore 中存在,并收集有效明细 const errors = []; const items = []; for (let i = 0; i < orderLine.length; i++) { - const wms_stock = await app.model.StockStore.findByPk(orderLine[i].itemId); - if (!wms_stock) { - errors.push(`SKU${orderLine[i].itemId}商品《${orderLine[i].itemName}》编码《${orderLine[i].itemCode}》\n未同步推送到仓库`); + const line = orderLine[i]; + const wmsStock = await app.model.StockStore.findByPk(line.itemId); + if (!wmsStock) { + errors.push( + `SKU${line.itemId}商品《${line.itemName}》编码《${line.itemCode}》\n未同步推送到仓库` + ); continue; } - if (!wms_stock.stock_id) { - errors.push(`SKU${orderLine[i].itemId}商品《${orderLine[i].itemName}》编码《${orderLine[i].itemCode}》wms无对应关系\n请联系仓库关联创建商品`); + if (!wmsStock.stock_id) { + errors.push( + `SKU${line.itemId}商品《${line.itemName}》编码《${line.itemCode}》wms无对应关系\n请联系仓库关联创建商品` + ); continue; } - wms_stock.inventory_type = orderLine[i].inventoryType; - wms_stock.order_line_no = orderLine[i].orderLineNo; - wms_stock.count = orderLine[i].planQty; - wms_stock.item_id = orderLine[i].itemId; - items.push(wms_stock); - } - if (errors.length > 0) { - return this.fail('创建入库单失败,失败原因:\n' + errors.join('\n')); - } - const order = await ctx.service.systems.deliveryOrder.tryCreatedeliveryOrder(data.request.deliveryOrder, appKey, storeId, warehouseId, totalOrderLines, 'QM', customerId, warehouseCode); - if (!order.success) { - return fail('创建入库单失败,失败原因:\n' + order.error); - } - const orderId = order.deliveryOrderId; - for (let i = 0; i < items.length; i++) { - const item = items[i]; - const res = await ctx.service.systems.deliveryOrder.addItems(item, orderId); - if (!res.success) { - errors.push(`SKU${item.itemId}商品《${item.itemName}》编码《${item.itemCode}》入库失败,错误信息:${res.error}`); + const planQty = parseInt(line.planQty) || 0; + if (planQty <= 0) { + errors.push( + `SKU${line.itemId}商品《${line.itemName}》编码《${line.itemCode}》\n计划数量必须大于0` + ); + continue; } + items.push({ + orderLineNo: line.orderLineNo, + ownerCode: line.ownerCode, + itemCode: line.itemCode, + itemId: line.itemId, + itemName: line.itemName, + planQty, + inventoryType: line.inventoryType, + stockId: wmsStock.stock_id, + }); } + if (errors.length > 0) { - // 失败删除; - await ctx.model.deliveryOrder.delete(orderId); - return fail('创建入库单失败,失败原因:\n' + errors.join('\n')); + return this.fail(`创建出库单失败,失败原因:\n${errors.join('\n')}`); } - const lineCount = await ctx.service.systems.deliveryOrder.getLineCount(orderId); // 获取接收行数 - // 所有行数接收完成 - if (lineCount === totalOrderLines) { - await ctx.service.systems.deliveryOrder.received(orderId, warehouseId, storeId); // 接收完成 - return success('入库单接收完毕', { deliveryOrderId: orderId }); + + // 预取超卖配置,避免每次 lockItemStorages 在锁内回退查 DB + const oversellConfig = await ctx.service.systems.stockStore + .getStoreWarehousePolicyByStoreAndWarehouse(storeId, warehouseId); + + // 第二步:在事务中写入主表 + 库存锁定 + 明细表 + const transaction = await ctx.model.transaction(); + try { + const order = await ctx.model.OrderStockout.create( + { + stockout_order_code: deliveryOrder.deliveryOrderCode, + order_type: deliveryOrder.orderType, + total_order_lines: totalOrderLines, + order_create_time: deliveryOrder.createTime + ? new Date(deliveryOrder.createTime) + : null, + remark: deliveryOrder.remark || null, + warehouse_id: warehouseId, + store_id: storeId, + qimen_owner_code: appKey, + qimen_warehouse_code: warehouseCode, + source_type: 'QM', + created_at: new Date(), + updated_at: new Date(), + }, + { transaction } + ); + + const orderId = order.id; + + // 库存锁定:按 stockId 升序排序后逐个加锁,避免死锁 + const sortedItems = [ ...items ].sort((a, b) => a.stockId - b.stockId); + for (const item of sortedItems) { + const lockResult = await ctx.service.systems.stockStore.lockItemStorages( + item.stockId, + item.planQty, + transaction, + oversellConfig + ); + if (!lockResult.success) { + throw new Error( + `SKU${item.itemId}商品《${item.itemName}》编码《${item.itemCode}》\n库存锁定失败: ${lockResult.error}` + ); + } + } + + // 批量创建明细 + const now = new Date(); + const itemRecords = items.map(item => ({ + order_id: orderId, + order_line_no: item.orderLineNo, + owner_code: item.ownerCode, + item_code: item.itemCode, + item_id: item.itemId, + item_name: item.itemName, + plan_qty: item.planQty, + inventory_type: item.inventoryType, + stock_id: item.stockId, + created_at: now, + updated_at: now, + })); + + await ctx.model.OrderStockoutItems.bulkCreate(itemRecords, { + transaction, + validate: true, + }); + + await transaction.commit(); + + return this.success('出库单创建成功', { + stockoutOrderId: order.id, + stockoutOrderCode: order.stockout_order_code, + }); + } catch (err) { + await transaction.rollback(); + ctx.logger.error('[stockout.create] 事务写入失败:', err); + return this.fail(`创建出库单失败,失败原因:\n${err.message}`); } - return success('入库单接收中'); } - async query() { - const { fail } = this; - return fail('接口未完善'); + + /** + * 查询出库单。 + * + * 根据 deliveryOrderCode 查 `wms_order_stockout` 主表, + * 然后关联查 `wms_order_stockout_items` 明细,按奇门标准响应格式返回。 + * + * @param {object} data - 奇门 stockout.query 请求体 + * @param {object} data.request - 请求数据 + * @param {object} data.request.deliveryOrder - 出库单查询条件 + * @param {string} data.request.deliveryOrder.deliveryOrderCode - 出库单号 + * @return {Promise} 返回 success / fail 结果 + */ + async query(data) { + const { app, ctx } = this; + const { deliveryOrderCode } = data.request.deliveryOrder; + + // 查主表 + const order = await ctx.model.OrderStockout.findOne({ + where: { stockout_order_code: deliveryOrderCode }, + }); + if (!order) { + return this.fail('未找到出库单'); + } + + // 查明细 + const items = await ctx.model.OrderStockoutItems.findAll({ + where: { order_id: order.id }, + order: [[ 'order_line_no', 'ASC' ]], + }); + + return this.success('成功', { + totalLines: items.length, + deliveryOrder: { + deliveryOrderCode: order.stockout_order_code, + deliveryOrderId: order.id, + warehouseCode: order.qimen_warehouse_code, + orderType: order.order_type, + status: order.order_status, + createTime: order.order_create_time ? app.formatDate(order.order_create_time) : null, + remark: order.remark || '', + }, + orderLines: { + orderLine: items.map(item => ({ + orderLineNo: item.order_line_no, + ownerCode: item.owner_code, + itemCode: item.item_code, + itemId: item.item_id, + itemName: item.item_name, + planQty: item.plan_qty, + inventoryType: item.inventory_type, + })), + }, + }); } } diff --git a/app/service/systemMethods/dashboard.js b/app/service/systemMethods/dashboard.js index 8868138..1b16148 100644 --- a/app/service/systemMethods/dashboard.js +++ b/app/service/systemMethods/dashboard.js @@ -302,7 +302,7 @@ class dashboardService extends MainService { } /** * 订单趋势统计:按小时统计当日订单数与发货数 - * @returns {Object} 包含 categories(时段)、orders(订单数)、shipments(发货数)和 summary(汇总)的响应数据 + * @return {Object} 包含 categories(时段)、orders(订单数)、shipments(发货数)和 summary(汇总)的响应数据 */ async order_trend() { const { ctx } = this; diff --git a/app/service/systemMethods/index.js b/app/service/systemMethods/index.js index 92e46bc..2ad7b8f 100644 --- a/app/service/systemMethods/index.js +++ b/app/service/systemMethods/index.js @@ -377,7 +377,7 @@ function appendExpressMappingKey(targetMap, rawKey, mappingItem) { * 构建抖音电子面单快递映射表。 * * @param {Array} expressList 系统快递列表 - * @param platformCode + * @param {string} [platformCode='DY'] 平台编码,默认为 'DY' * @return {Object} 支持 DY 平台编码与系统快递编码双键的映射表 */ function buildExpressNameMap(expressList, platformCode = 'DY') { @@ -2050,7 +2050,7 @@ class indexService extends MainService { * * @param {string} appSecret 菠萝派访问令牌 * @param {string|number} platid 菠萝派平台标识 - * @param isJD + * @param {boolean} [isJD=false] 是否为京东平台 * @return {Promise>} 归一化后的模板数组 * @throws {Error} 当配置缺失或接口返回失败时抛出异常 */ @@ -2061,10 +2061,10 @@ class indexService extends MainService { throw new Error('菠萝派接口配置缺失'); } const query_data = { templatestype: 'ALL' }; - if (platid == 673) { + if (platid === 673) { query_data.BizVersion = '2'; } - if (platid == 544) { + if (platid === 544) { platid = 611; } let interface_url = 'https://api.polyapi.com/OpenAPI/do'; @@ -2670,9 +2670,9 @@ class indexService extends MainService { * 当前已实现 CAINIAO 平台,其它平台返回空对象,便于后续扩展。 * * @param {string} platformCode 平台编码 - * @param s - * @param platid - * @param expressCode + * @param {string|null} [s=null] 平台密钥或令牌 + * @param {string|number|null} [platid=null] 平台标识ID + * @param {string} [expressCode=''] 快递编码 * @return {Promise} 平台模板响应 */ async requestPrintPlatformTemplateList(platformCode, s = null, platid = null, expressCode = '') { diff --git a/app/service/systemMethods/order/base.js b/app/service/systemMethods/order/base.js index ad6010c..ec97b04 100644 --- a/app/service/systemMethods/order/base.js +++ b/app/service/systemMethods/order/base.js @@ -45,6 +45,8 @@ const ORDER_LIST_BASE_ATTRIBUTES = [ 'post_status', 'storage_status', 'pick_status', 'pack_status', 'inspection_status', 'print_status', 'claim_status', 'outbound_status', 'lock_status', 'intercept_status', 'basket_number', 'recheck_status', + 'create_channel', + 'store_id', ]; const ORDER_WEIGHT_TYPE_LABELS = Object.freeze({ @@ -53,6 +55,11 @@ const ORDER_WEIGHT_TYPE_LABELS = Object.freeze({ 2: '重货', 3: '冷链', }); +const CREATE_CHANNEL_LABELS = Object.freeze({ + MANUAL: '手工单', + API: '接口', + QM: '奇门', +}); const ORDER_TABLE_TYPE_ALIASES = Object.freeze({ current: 'current', history: 'history', @@ -483,6 +490,24 @@ class OrderBaseService extends MainService { return ORDER_WEIGHT_TYPE_LABELS[0]; } + /** + * 将创建来源渠道编码转换为中文展示值。 + * @param {string} channel 创建来源渠道编码。 + * @return {string} 中文渠道名称。 + */ + formatCreateChannelLabel(channel) { + if (!channel || typeof channel !== 'string') { + return ''; + } + + const trimmedChannel = channel.trim(); + if (Object.prototype.hasOwnProperty.call(CREATE_CHANNEL_LABELS, trimmedChannel)) { + return CREATE_CHANNEL_LABELS[trimmedChannel]; + } + + return trimmedChannel; + } + /** * 规范波次扫描结果,空值时默认返回 0(未扫描)。 * @param {*} scanResult 扫描结果原始值。 @@ -528,6 +553,7 @@ class OrderBaseService extends MainService { weight_type: this.formatWeightTypeLabel(order.weight_type), wave_strategy_version: this.normalizeWaveStrategyVersion(order.wave_strategy_version), wave_scan_result: this.normalizeWaveScanResult(order.wave_scan_result), + create_channel: this.formatCreateChannelLabel(order.create_channel), }; } @@ -1125,9 +1151,44 @@ class OrderBaseService extends MainService { }), ]); - const normalizedList = await this.attachOrderExpressNumbers( - list.map(order => this.normalizeOrderListItem(order)) - ); + const normalized = list.map(order => this.normalizeOrderListItem(order)); + + // 批量查询货主备注(wms_store_warehouse.store_remask) + const storeRemarkMap = new Map(); + if (normalized.length > 0 && this.ctx.model && this.ctx.model.StoreWarehouse) { + const storeIds = [ + ...new Set( + normalized + .map(row => Number(row.store_id || 0)) + .filter(id => id > 0) + ), + ]; + if (storeIds.length > 0) { + const swRows = await this.ctx.model.StoreWarehouse.findAll({ + where: { + store_id: { [this.app.Sequelize.Op.in]: storeIds }, + warehouse_id: contextWarehouseId, + }, + attributes: [ 'store_id', 'store_remask' ], + raw: true, + }); + for (const sw of (Array.isArray(swRows) ? swRows : [])) { + const sid = Number(sw.store_id || 0); + if (sid > 0 && !storeRemarkMap.has(sid)) { + storeRemarkMap.set(sid, String(sw.store_remask || '').trim()); + } + } + } + } + + const listWithRemark = normalized.map(row => ({ + ...row, + store_remark: storeRemarkMap.has(Number(row.store_id || 0)) + ? storeRemarkMap.get(Number(row.store_id || 0)) + : '', + })); + + const normalizedList = await this.attachOrderExpressNumbers(listWithRemark); const totalPages = pageSize > 0 ? Math.ceil(total / pageSize) : 0; diff --git a/app/service/systemMethods/order/pendingOrder.js b/app/service/systemMethods/order/pendingOrder.js index 09e804e..8fa822e 100644 --- a/app/service/systemMethods/order/pendingOrder.js +++ b/app/service/systemMethods/order/pendingOrder.js @@ -1749,6 +1749,38 @@ class PendingOrderService extends OrderBaseService { throw new Error('订单当前状态不允许取消'); } + // 已同步订单不允许取消,转为拦截处理 + const syncedOrders = existingOrders.filter( + order => String(order.sync_status || '').trim() === 'fin' + ); + if (syncedOrders.length > 0) { + const syncedOrderIds = syncedOrders.map(order => Number(order.id)).filter( + id => Number.isInteger(id) && id > 0 + ); + if (syncedOrderIds.length > 0) { + const syncNow = new Date(); + await model.update( + { + intercept_status: 'requested', + updated_at: syncNow, + }, + { + where: { + id: syncedOrderIds, + }, + } + ); + this.ctx.logger.info( + `[PendingOrderService.cancelOrder] 订单已同步,不可取消,已转为拦截处理,订单ID: ${syncedOrderIds.join(',')}` + ); + } + const syncedCodes = syncedOrders + .map(order => String(order.delivery_order_code || order.pre_delivery_order_code || order.id || '').trim()) + .filter(Boolean) + .join(', '); + throw new Error(`订单已同步,不可取消,已转为拦截处理:${syncedCodes}`); + } + const now = new Date(); const updateValues = { status: PENDING_CANCEL_STATUS, @@ -1916,6 +1948,37 @@ class PendingOrderService extends OrderBaseService { const firstOrder = normalizedOrders[0]; + // 写入取消操作日志(不影响主流程) + try { + const operator = this.getOrderLogOperator(); + const logWarehouseId = this.getOrderLogWarehouseId(warehouseId); + if (normalizedOrders.length > 0 && this.ctx.model && this.ctx.model.OperationLog) { + const operatorInfo = operator || {}; + const operatorId = operatorInfo.id != null ? String(operatorInfo.id) : null; + const operatorName = operatorInfo.name ? String(operatorInfo.name) : 'system'; + const now = new Date(); + + const logRows = normalizedOrders.map(order => ({ + business_type: 'order', + business_id: String(order.id), + operation_code: 'ORDER_CANCEL', + operator_id: operatorId, + operator_name: operatorName, + external_log_type: 'NONE', + warehouse_id: logWarehouseId || null, + platform_code: 'SYSTEM', + message: '订单取消', + created_at: now, + })).filter(row => Number(row.business_id) > 0); + + if (logRows.length > 0) { + await this.ctx.model.OperationLog.bulkCreate(logRows); + } + } + } catch (logErr) { + this.ctx.logger.warn('[PendingOrderService.cancelOrder] 写入取消操作日志失败,不影响业务', logErr); + } + return { id: firstOrder.id, status: firstOrder.status, diff --git a/app/service/systemMethods/order/recheckOrder.js b/app/service/systemMethods/order/recheckOrder.js index c83bd6b..158f5ca 100644 --- a/app/service/systemMethods/order/recheckOrder.js +++ b/app/service/systemMethods/order/recheckOrder.js @@ -1287,10 +1287,12 @@ class RecheckOrderService extends OrderBaseService { if (Array.isArray(detail.barcodes) && detail.barcodes.length > 0) { barcodeMap.set(sid, detail.barcodes.map(bc => String(bc.barcode || '').trim()).filter(Boolean)); } - // 从 getStockDetails 提取图片 URL - const detailImageUrl = String(detail.image_url || '').trim(); - if (detailImageUrl) { - imagesByStockId.set(sid, [ detailImageUrl ]); + // 从 getStockDetails 提取图片 URL(兼容数组/字符串格式) + const imageUrls = Array.isArray(detail.image_url) + ? detail.image_url.map(u => String(u || '').trim()).filter(Boolean) + : (detail.image_url ? [ String(detail.image_url).trim() ] : []); + if (imageUrls.length > 0) { + imagesByStockId.set(sid, imageUrls); } } } @@ -3684,12 +3686,14 @@ class RecheckOrderService extends OrderBaseService { } ); - // 步骤3:检查是否存在 wms_picking 记录 + // 步骤3:检查是否存在 wms_picking 记录(仅统计 pending 且未删除的记录) const pickingRows = await ctx.model.query( `SELECT id, storage_id, quantity, space_id FROM wms_picking WHERE order_id = :orderId - AND warehouse_id = :warehouseId`, + AND warehouse_id = :warehouseId + AND status = 'pending' + AND deleted_at IS NULL`, { replacements: { orderId, warehouseId }, type: ctx.model.QueryTypes.SELECT, @@ -3700,12 +3704,14 @@ class RecheckOrderService extends OrderBaseService { const normalizedPickingRows = Array.isArray(pickingRows) ? pickingRows : []; if (normalizedPickingRows.length > 0) { - // 更新 wms_picking.status = 'fin' + // 更新 wms_picking.status = 'fin'(仅更新 pending 且未删除的记录) await ctx.model.query( `UPDATE wms_picking SET status = 'fin', updated_at = NOW() WHERE order_id = :orderId - AND warehouse_id = :warehouseId`, + AND warehouse_id = :warehouseId + AND status = 'pending' + AND deleted_at IS NULL`, { replacements: { orderId, warehouseId }, type: ctx.model.QueryTypes.UPDATE, diff --git a/app/service/systemMethods/order/wave.js b/app/service/systemMethods/order/wave.js index 8f58a71..abf04ac 100644 --- a/app/service/systemMethods/order/wave.js +++ b/app/service/systemMethods/order/wave.js @@ -5570,9 +5570,9 @@ class WaveService extends OrderBaseService { const deletedCount = await matchModel.destroy({ where }); // 清理后重建 - if (Number.isInteger(normalizedWarehouseId) && normalizedWarehouseId > 0) { + if (Number.isInteger(warehouseId) && warehouseId > 0) { setImmediate(() => { - this.submitWaveStrategyQuickScanForWarehouse(normalizedWarehouseId).catch(err => { + this.submitWaveStrategyQuickScanForWarehouse(warehouseId).catch(err => { this.ctx.logger.warn('[wave.cleanupWaveStrategyQuickScanMatchedStrategies] 清理后自动扫描失败: %s', err.message); }); }); diff --git a/app/service/systemMethods/pick.js b/app/service/systemMethods/pick.js index 80cdd9b..c0c81f4 100644 --- a/app/service/systemMethods/pick.js +++ b/app/service/systemMethods/pick.js @@ -77,7 +77,8 @@ class PickService extends MainService { const pad2 = value => String(value).padStart(2, '0'); const datePart = `${now.getFullYear()}${pad2(now.getMonth() + 1)}${pad2(now.getDate())}`; const timePart = `${pad2(now.getHours())}${pad2(now.getMinutes())}${pad2(now.getSeconds())}`; - const randomPart = Math.random().toString(36).slice(2, 6).toUpperCase(); + const randomPart = Math.random().toString(36).slice(2, 6) + .toUpperCase(); return `PK${datePart}${timePart}${randomPart}`; } @@ -190,16 +191,16 @@ class PickService extends MainService { } ); - const taskInsertHead = Array.isArray(taskInsertResult) ? taskInsertResult[0] : null; - const taskInsertMeta = Array.isArray(taskInsertResult) ? taskInsertResult[1] : null; - let taskId = Number( - (taskInsertMeta && (taskInsertMeta.insertId || taskInsertMeta.lastID || taskInsertMeta.id)) + const taskInsertHead = Array.isArray(taskInsertResult) ? taskInsertResult[0] : null; + const taskInsertMeta = Array.isArray(taskInsertResult) ? taskInsertResult[1] : null; + let taskId = Number( + (taskInsertMeta && (taskInsertMeta.insertId || taskInsertMeta.lastID || taskInsertMeta.id)) || (taskInsertHead && (taskInsertHead.insertId || taskInsertHead.lastID || taskInsertHead.id)) || 0 - ); - if (!Number.isInteger(taskId) || taskId <= 0) { - const taskIdRows = await ctx.model.query( - ` + ); + if (!Number.isInteger(taskId) || taskId <= 0) { + const taskIdRows = await ctx.model.query( + ` SELECT id FROM wms_wave_pick_task WHERE warehouse_id = :warehouseId @@ -207,18 +208,18 @@ class PickService extends MainService { ORDER BY id DESC LIMIT 1 `, - { - replacements: { - warehouseId, - taskNo, - }, - type: ctx.model.QueryTypes.SELECT, - transaction, - } - ); - const taskRow = Array.isArray(taskIdRows) && taskIdRows.length > 0 ? taskIdRows[0] : null; - taskId = Number(taskRow && taskRow.id || 0); - } + { + replacements: { + warehouseId, + taskNo, + }, + type: ctx.model.QueryTypes.SELECT, + transaction, + } + ); + const taskRow = Array.isArray(taskIdRows) && taskIdRows.length > 0 ? taskIdRows[0] : null; + taskId = Number(taskRow && taskRow.id || 0); + } if (!Number.isInteger(taskId) || taskId <= 0) { throw Object.assign(new Error('任务创建失败(未返回任务ID)'), { code: 500 }); } diff --git a/app/service/systemMethods/print.js b/app/service/systemMethods/print.js index efa64a2..3b63d15 100644 --- a/app/service/systemMethods/print.js +++ b/app/service/systemMethods/print.js @@ -327,147 +327,6 @@ class PrintService extends MainService { return lowerPlatformCode; } - /** - * 按订单ID批量加载波次序号上下文,用于 SPH 发送阶段覆写 printNum。 - * 数据来源:wms_order_wave_index。 - * 查询失败时优雅降级为空映射,不阻断发送流程。 - * @param {Object} payload 入参。 - * @param {number|string} payload.warehouseId 仓库ID。 - * @param {Array} payload.orderIds 订单ID列表。 - * @return {Promise<{orderWaveIndexMap:Map,waveTotalOrdersMap:Map}>} 波次索引上下文。 - */ - async queryWavePrintNumContextForOrderIds(payload = {}) { - const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; - const warehouseId = Number(normalizedPayload.warehouseId || 0); - const orderIds = this.normalizeOrderIds(normalizedPayload.orderIds); - const emptyResult = { - orderWaveIndexMap: new Map(), - waveTotalOrdersMap: new Map(), - }; - if (!Number.isInteger(warehouseId) || warehouseId <= 0 || orderIds.length === 0) { - return emptyResult; - } - - const orderPrintService = this.service && this.service.systems && this.service.systems.orderPrint; - if (!orderPrintService - || typeof orderPrintService.queryWaveOrderIndexMapByOrderIds !== 'function' - || typeof orderPrintService.queryWaveTotalOrderCountMap !== 'function') { - this.ctx.logger.warn('[print.send] SPH printNum 覆写依赖服务不可用,跳过波次索引查询', { - warehouseId, - orderIdsCount: orderIds.length, - }); - return emptyResult; - } - - try { - const orderWaveIndexMapResult = await orderPrintService.queryWaveOrderIndexMapByOrderIds(orderIds, warehouseId); - const orderWaveIndexMap = orderWaveIndexMapResult instanceof Map - ? orderWaveIndexMapResult - : new Map(); - const waveIds = Array.from(new Set(Array.from(orderWaveIndexMap.values()) - .map(item => Number(item && item.wave_id || 0)) - .filter(waveId => Number.isInteger(waveId) && waveId > 0))); - const waveTotalOrdersMapResult = await orderPrintService.queryWaveTotalOrderCountMap(waveIds, warehouseId); - const waveTotalOrdersMap = waveTotalOrdersMapResult instanceof Map - ? waveTotalOrdersMapResult - : new Map(); - return { - orderWaveIndexMap, - waveTotalOrdersMap, - }; - } catch (error) { - this.ctx.logger.warn('[print.send] SPH printNum 覆写波次索引查询失败,回退模板默认值', { - warehouseId, - orderIdsCount: orderIds.length, - reason: error && error.message ? error.message : `${error}`, - }); - return emptyResult; - } - } - - /** - * 将 SPH 发送任务中的 printNum 覆写为波次内序号与波次总单数。 - * @param {Object} payload 入参。 - * @param {Object} payload.requestPayload 待发送 payload。 - * @param {number|string} payload.orderId 当前订单ID。 - * @param {Map} payload.orderWaveIndexMap 订单波次索引映射。 - * @param {Map} payload.waveTotalOrdersMap 波次总单数映射。 - * @return {{applied:boolean,orderId:number,waveId:number,curNum:number,sumNum:number,reason:string}} 覆写结果。 - */ - applySphPrintNumByWaveIndex(payload = {}) { - const normalizedPayload = payload && typeof payload === 'object' ? payload : {}; - const requestPayload = normalizedPayload.requestPayload && typeof normalizedPayload.requestPayload === 'object' - ? normalizedPayload.requestPayload - : null; - const orderId = Number(normalizedPayload.orderId || 0); - const fallbackResult = { - applied: false, - orderId, - waveId: 0, - curNum: 0, - sumNum: 0, - reason: '', - }; - if (!requestPayload) { - return { - ...fallbackResult, - reason: 'requestPayload 非对象', - }; - } - - const taskList = Array.isArray(requestPayload.taskList) ? requestPayload.taskList : []; - const firstTask = taskList[0] && typeof taskList[0] === 'object' ? taskList[0] : null; - if (!firstTask) { - return { - ...fallbackResult, - reason: 'taskList[0] 不存在', - }; - } - if (!Number.isInteger(orderId) || orderId <= 0) { - return { - ...fallbackResult, - reason: 'orderId 非法', - }; - } - - const orderWaveIndexMap = normalizedPayload.orderWaveIndexMap instanceof Map - ? normalizedPayload.orderWaveIndexMap - : new Map(); - const waveTotalOrdersMap = normalizedPayload.waveTotalOrdersMap instanceof Map - ? normalizedPayload.waveTotalOrdersMap - : new Map(); - const waveOrderIndexInfo = orderWaveIndexMap.get(orderId); - const waveId = Number(waveOrderIndexInfo && waveOrderIndexInfo.wave_id || 0); - const curNum = Number(waveOrderIndexInfo && waveOrderIndexInfo.wave_index || 0); - const sumNum = Number(waveTotalOrdersMap.get(waveId) || 0); - if (!Number.isInteger(waveId) || waveId <= 0 || !Number.isInteger(curNum) || curNum <= 0 || !Number.isInteger(sumNum) || sumNum <= 0) { - return { - ...fallbackResult, - waveId, - curNum, - sumNum, - reason: '波次索引信息缺失', - }; - } - - const currentPrintNum = firstTask.printNum && typeof firstTask.printNum === 'object' && !Array.isArray(firstTask.printNum) - ? firstTask.printNum - : {}; - firstTask.printNum = { - ...currentPrintNum, - curNum, - sumNum, - }; - return { - applied: true, - orderId, - waveId, - curNum, - sumNum, - reason: '', - }; - } - /** * 从打印记录 data 中提取订单ID列表。 * 兼容 data 为对象或 JSON 字符串,无法识别时返回空数组。 @@ -2257,13 +2116,8 @@ class PrintService extends MainService { payloadBuilder: normalizedPayload.payloadBuilder, }); const isKuaishouPlatform = normalizedPlatformCode === 'kuaishou'; - const isSphPlatform = normalizedPlatformCode === 'sph'; const orderBatches = []; - if (isSphPlatform) { - for (const order of orders) { - orderBatches.push([ order ]); - } - } else if (isKuaishouPlatform) { + if (isKuaishouPlatform) { for (let index = 0; index < orders.length; index += 10) { orderBatches.push(orders.slice(index, index + 10)); } @@ -2271,23 +2125,6 @@ class PrintService extends MainService { orderBatches.push(orders); } const totalDocumentCount = orders.length; - let sphOrderWaveIndexMap = new Map(); - let sphWaveTotalOrdersMap = new Map(); - if (isSphPlatform) { - const platformOrderIds = this.collectOrderIdsFromPlatformGroup(platformGroup, orders); - const wavePrintNumContext = await this.queryWavePrintNumContextForOrderIds({ - warehouseId: normalizedPayload.warehouseId, - orderIds: platformOrderIds, - }); - sphOrderWaveIndexMap = wavePrintNumContext.orderWaveIndexMap; - sphWaveTotalOrdersMap = wavePrintNumContext.waveTotalOrdersMap; - this.ctx.logger.info('[print.send] SPH 波次索引上下文加载完成', { - ...groupSummary, - orderIdsCount: platformOrderIds.length, - orderWaveIndexCount: sphOrderWaveIndexMap.size, - waveCount: sphWaveTotalOrdersMap.size, - }); - } for (let batchIndex = 0; batchIndex < orderBatches.length; batchIndex++) { const batchOrders = orderBatches[batchIndex]; @@ -2313,44 +2150,13 @@ class PrintService extends MainService { requestPayload.task.totalDocumentCount = totalDocumentCount; } currentTaskCode = await this.reserveUniquePrintTaskCode(); - if (isSphPlatform - && Array.isArray(requestPayload.taskList) - && requestPayload.taskList[0] - && typeof requestPayload.taskList[0] === 'object' - && !Array.isArray(requestPayload.taskList[0])) { - requestPayload.taskList[0].taskID = currentTaskCode; - } else if (requestPayload.task && typeof requestPayload.task === 'object' && !Array.isArray(requestPayload.task)) { + if (requestPayload.task && typeof requestPayload.task === 'object' && !Array.isArray(requestPayload.task)) { requestPayload.task.taskID = currentTaskCode; } if (currentTaskCode && !generatedTaskCodes.includes(currentTaskCode)) { generatedTaskCodes.push(currentTaskCode); } - if (isSphPlatform) { - const currentOrderId = Number(batchOrderIds[0] || 0); - const sphOverrideResult = this.applySphPrintNumByWaveIndex({ - requestPayload, - orderId: currentOrderId, - orderWaveIndexMap: sphOrderWaveIndexMap, - waveTotalOrdersMap: sphWaveTotalOrdersMap, - }); - if (sphOverrideResult.applied) { - this.ctx.logger.info('[print.send] SPH printNum 覆写成功', { - ...batchSummary, - orderId: sphOverrideResult.orderId, - waveId: sphOverrideResult.waveId, - curNum: sphOverrideResult.curNum, - sumNum: sphOverrideResult.sumNum, - }); - } else { - this.ctx.logger.info('[print.send] SPH printNum 覆写跳过,保持模板默认值', { - ...batchSummary, - orderId: sphOverrideResult.orderId, - reason: sphOverrideResult.reason, - }); - } - } - const payloadSummary = this.summarizeExpressPayload(requestPayload); this.ctx.logger.info('[print.send] 组装 payload 成功', { ...batchSummary, diff --git a/app/service/systemMethods/storage/direct_inbound.js b/app/service/systemMethods/storage/direct_inbound.js index 37d0c3d..651de7d 100644 --- a/app/service/systemMethods/storage/direct_inbound.js +++ b/app/service/systemMethods/storage/direct_inbound.js @@ -30,7 +30,7 @@ class DirectInboundService extends MainService { /** * 按商品增量添加导入/PDA 入库记录。 * @param {Object} data 请求体 - * @param {string} data.entry_order_code 入库单号 + * @param {number} data.entry_order_id 入库单 ID * @param {number} data.stock_id 商品SKU ID * @param {number} data.quantity 入库数量 * @param {string} data.inbound_type 入库方式:import 或 pda @@ -46,13 +46,13 @@ class DirectInboundService extends MainService { /** * 提交确认完成导入/PDA 入库,写入库存并触发奇门/API 回传。 * @param {Object} data 请求体 - * @param {string} data.entry_order_code 入库单号 + * @param {number} data.entry_order_id 入库单 ID * @return {Promise} 统一成功包装响应 */ async commit(data = {}) { const { service } = this; - const { entry_order_code } = data || {}; - const result = await service.systems.inboundDirectLog.commit(entry_order_code); + const { entry_order_id } = data || {}; + const result = await service.systems.inboundDirectLog.commit(entry_order_id); return this.success('ok', result); } diff --git a/app/service/systemMethods/storage/entry.js b/app/service/systemMethods/storage/entry.js index abae4df..cf25099 100644 --- a/app/service/systemMethods/storage/entry.js +++ b/app/service/systemMethods/storage/entry.js @@ -9,9 +9,9 @@ class entryService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,get,cancel,completeEntry,getPrintData,getDirectInboundItems,addDirectInboundItem,commitDirectInbound,removeDirectInboundItem,quickInbound,receivingCompare'; - const _noNeedLog = 'list,get,getPrintData'; - const _noNeedAuth = 'list,get,cancel,completeEntry,getPrintData,getDirectInboundItems,addDirectInboundItem,commitDirectInbound,removeDirectInboundItem,bindReceivingDetails,quickInbound,receivingCompare'; + const _noNeedRight = 'list,get,cancel,getPrintData,getDirectInboundItems,addDirectInboundItem,commitDirectInbound,removeDirectInboundItem,quickInbound,receivingCompare,queryEntryLogs,getReceivingDetailsForBind,reviewEntry,containerList'; + const _noNeedLog = 'list,get,getPrintData,reviewEntry,containerList'; + const _noNeedAuth = 'list,get,cancel,getPrintData,getDirectInboundItems,addDirectInboundItem,commitDirectInbound,removeDirectInboundItem,bindReceiving,quickInbound,receivingCompare,unbindReceiving,queryEntryLogs,getReceivingDetailsForBind,reviewEntry,containerList'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -64,20 +64,6 @@ class entryService extends MainService { return this.success('ok', result); } - /** - * 完成入库单(纯状态变更,不写库存)。 - * 仅校验状态=PENDING、有明细,然后将 order_status 更新为 COMPLETED。 - * @param {Object} data 请求体 - * @param {number} data.id 入库单ID - * @return {Promise} 统一 success 包装 - */ - async completeEntry(data = {}) { - const { service } = this; - const { id } = data; - const result = await service.systems.storage.entry.completeEntry({ id }); - return this.success('ok', result); - } - /** * 获取入库单的导入/PDA 直接入库信息(从 storage.entry 模块暴露)。 * @param {Object} data 请求体 @@ -110,13 +96,13 @@ class entryService extends MainService { /** * 提交确认完成导入/PDA 直接入库(从 storage.entry 模块暴露)。 * @param {Object} data 请求体 - * @param {string} data.entry_order_code 入库单号 + * @param {number} data.entry_order_id 入库单 ID * @return {Promise} 统一 success 包装 */ async commitDirectInbound(data = {}) { const { service } = this; - const { entry_order_code } = data || {}; - const result = await service.systems.inboundDirectLog.commit(entry_order_code); + const { entry_order_id } = data || {}; + const result = await service.systems.inboundDirectLog.commit(entry_order_id); return this.success('ok', result); } @@ -133,19 +119,43 @@ class entryService extends MainService { } /** - * 批量绑定入库单明细与收货单明细(system method 包装层)。 + * 绑定入库单与收货单的主表关系(仅主表绑定,不做明细分配)。 * @param {Object} data 请求体 - * @param {number} data.entry_order_id 入库单ID - * @param {Array} data.bindings 绑定列表 [{ entry_item_id, receiving_detail_id, allocated_quantity }] + * @param {number} data.entry_order_id 入库单 ID + * @param {number[]} data.receiving_ids 收货单 ID 列表 * @return {Promise} 统一 success 包装 */ - async bindReceivingDetails(data = {}) { - const { service } = this; - const { entry_order_id, bindings } = data || {}; - const result = await service.systems.receiving_entry_match.bindReceivingDetails({ entry_order_id, bindings }); + async bindReceiving(data = {}) { + const { ctx } = this; + console.log('[DEBUG] systems keys:', Object.keys(ctx.service.systems)); + console.log('[DEBUG] receiving_entry_match:', typeof ctx.service.systems.receivingEntryMatch); + const { entry_order_id, receiving_ids } = data || {}; + const creator_id = ctx.user ? ctx.user.id || ctx.user.user_id : undefined; + const result = await ctx.service.systems.receivingEntryMatch.bindEntryOrderReceiving({ + entry_order_id, + receiving_ids, + creator_id, + }); return this.success('绑定完成', result); } + /** + * 解除入库单与收货单的绑定关系。 + * @param {Object} data 请求体 + * @param {number} data.entry_order_id 入库单 ID + * @param {number[]} data.receiving_ids 要解除绑定的收货单 ID 列表 + * @return {Promise} 统一 success 包装 + */ + async unbindReceiving(data = {}) { + const { ctx } = this; + const { entry_order_id, receiving_ids } = data || {}; + const result = await ctx.service.systems.receivingEntryMatch.unbindEntryOrderReceiving({ + entry_order_id, + receiving_ids, + }); + return this.success('解绑完成', result); + } + /** * 快捷直入/虚拟入库(system method 包装层)。 * @param {Object} data 请求体 @@ -156,7 +166,10 @@ class entryService extends MainService { const { service } = this; const { id } = data; const result = await service.systems.storage.entry.quickInbound({ id }); - return this.success('ok', result); + if (result && result.code === 200) { + return this.success(result.message || 'ok', result); + } + return this.fail(result?.message || '快捷入库失败', result); } /** @@ -246,17 +259,88 @@ class entryService extends MainService { } /** * 入库单商品与收货单商品逐行对照视图(system method 包装层)。 + * 支持传入多个收货单ID进行批量对照预览。 * @param {Object} data 请求体 * @param {number} data.entry_order_id 入库单ID - * @param {number} data.receiving_id 收货单ID + * @param {number[]} [data.receiving_ids] 收货单ID列表(优先使用) + * @param {number} [data.receiving_id] 单个收货单ID(向后兼容) * @return {Promise} 统一 success 包装 */ async receivingCompare(data = {}) { const { service } = this; - const { entry_order_id, receiving_id } = data || {}; - const result = await service.systems.storage.entry.receivingCompare({ entry_order_id, receiving_id }); + const { entry_order_id, receiving_id, receiving_ids } = data || {}; + const result = await service.systems.storage.entry.receivingCompare({ entry_order_id, receiving_id, receiving_ids }); return this.success('ok', result); } + /** + * 查询入库单操作日志。warehouseId 由服务端从当前上下文自动注入,前端无需传递。 + * @param {Object} data 请求体 + * @param {number} data.id 入库单ID + * @param {number} [data.page=1] 页码 + * @param {number} [data.pageSize=20] 每页数量 + * @return {Promise} 统一 success 包装 + */ + async queryEntryLogs(data = {}) { + const { ctx, service } = this; + const warehouseId = ctx.user?.store_id; + const result = await service.systems.operationLog.queryEntryOrderLogs({ + id: data.id, + warehouseId, + page: data.page, + pageSize: data.pageSize, + }); + return this.success('ok', result); + } + + /** + * 查询入库单已绑定收货单中匹配指定商品的可绑定收货明细列表。 + * @param {Object} data 请求体 + * @param {number} data.entry_order_id 入库单ID + * @param {number} data.stock_id 商品stock_id + * @return {Promise} 统一 success 包装 + */ + async getReceivingDetailsForBind(data = {}) { + const { service } = this; + const result = await service.systems.storage.entry.getReceivingDetailsForBind(data); + if (result && result.code === 200) { + return this.success('ok', result.data); + } + return this.fail(result?.message || '查询失败', result); + } + + /** + * 拉取入库单绑定的收货单中,指定商品的可用容器列表(收货明细)。 + * 用于 PDA 上架时选择容器。 + * @param {Object} data 请求体 + * @param {number} data.entry_order_id 入库单ID + * @param {number} data.stock_id 商品stock_id + * @return {Promise} 统一 success 包装,data 包含 { list, total } + */ + async containerList(data = {}) { + const { service } = this; + const { entry_order_id, stock_id } = data || {}; + const result = await service.systems.storage.entry.containerList({ entry_order_id, stock_id }); + if (result && result.code === 200) { + return this.success('ok', result.data); + } + return this.fail(result?.message || '查询失败', result); + } + + /** + * 审核入库单(CREATED → PENDING)。 + * @param {Object} data 请求体 + * @param {number} data.id 入库单ID + * @return {Promise} 统一 success/fail 包装 + */ + async reviewEntry(data = {}) { + const { service } = this; + const result = await service.systems.entryOrder.reviewEntry(data); + if (result && result.success) { + return this.success(result.message, result.data, 200); + } + return this.fail(result?.message || '审核失败', result, 400); + } + } module.exports = entryService; diff --git a/app/service/systemMethods/storage/inventory.js b/app/service/systemMethods/storage/inventory.js index 33f63cf..f860d40 100644 --- a/app/service/systemMethods/storage/inventory.js +++ b/app/service/systemMethods/storage/inventory.js @@ -12,7 +12,7 @@ class InventoryMethodService extends MainService { const _noNeedLogin = ''; const _noNeedRight = 'list'; const _noNeedLog = 'list'; - const _noNeedAuth = 'list'; + const _noNeedAuth = 'list,quickPutaway'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -61,6 +61,20 @@ class InventoryMethodService extends MainService { const result = await service.systems.storage.inventory.getInventoryList(pagination, sort, group_by_batch); return this.success('ok', result); } + + /** + * 收货单快捷入库:将收货单的明细直接转为入库单,相同商品自动合并数量。 + * 要求货主配置中允许收货单快捷入库,否则直接返回失败。 + * @param {Object} data 请求体 + * @param {number} data.receiving_id 收货单ID(必填) + * @return {Promise} 统一 success 包装,返回创建的入库单信息 + */ + async quickPutaway(data = {}) { + const { service } = this; + const { receiving_id } = data; + const result = await service.systems.storage.inventory.quickPutaway({ receiving_id }); + return this.success('ok', result); + } } module.exports = InventoryMethodService; diff --git a/app/service/systemMethods/storage/receiving.js b/app/service/systemMethods/storage/receiving.js index 8c6ddd2..1cf6234 100644 --- a/app/service/systemMethods/storage/receiving.js +++ b/app/service/systemMethods/storage/receiving.js @@ -10,9 +10,9 @@ class configService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs'; - const _noNeedLog = 'getReceivingList,get,addDetail,deleteDetail,detailChange,bindStore,bindDetailProduct,queryReceivingLogs'; - const _noNeedAuth = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs'; + const _noNeedRight = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs,scanDetail'; + const _noNeedLog = 'getReceivingList,get,addDetail,deleteDetail,detailChange,bindStore,bindDetailProduct,queryReceivingLogs,scanDetail'; + const _noNeedAuth = 'getReceivingList,get,addDetail,deleteDetail,detailChange,cancel,completeReceiving,bindStore,bindDetailProduct,rejectReceiving,reviewReceiving,queryReceivingLogs,scanDetail'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -21,11 +21,13 @@ class configService extends MainService { * @param {Object} data 请求体 * @param {Object} [data.pagination] 分页参数 * @param {Object} [data.where] 筛选条件 + * @param {boolean} [data.filterDepleted=false] 是否过滤掉无可再用量的收货单(所有明细已被其他入库单 committed 绑定占满) + * @param {number} [data.entry_order_id] 可选,按入库单商品交集过滤:只返回"至少有一条明细的 system_product_id 在入库单明细中"的收货单 * @return {Promise} 统一成功包装响应 */ async getReceivingList(data) { const { service } = this; - const { pagination, sort } = data; + const { pagination, sort, filterDepleted = false, entry_order_id: entryOrderId } = data; const { where } = this.prepareWhereContext(data, { specialFieldMap: { quickWhere: { @@ -33,7 +35,7 @@ class configService extends MainService { }, }, }); - const result = await service.systems.storage.receiving.getReceivingList(where, pagination, sort); + const result = await service.systems.storage.receiving.getReceivingList(where, pagination, sort, { filterDepleted, entry_order_id: entryOrderId }); return this.success('ok', result); } @@ -260,5 +262,23 @@ class configService extends MainService { }); } + /** + * PDA 扫码定位收货明细(system method 包装层),返回匹配的明细列表。 + * 同一条码可能匹配到多条收货明细,以列表形式返回所有匹配结果。 + * @param {Object} data 请求体 + * @param {number} data.entry_order_id 入库单ID + * @param {string} data.barcode 扫描条码(商品条码/箱唛/托盘唛/明细ID) + * @return {Promise} 统一成功包装响应,含匹配的收货明细列表 { list, total } + */ + async scanDetail(data) { + const { service } = this; + const { entry_order_id, barcode } = data; + const result = await service.systems.storage.receiving.scanDetail(entry_order_id, barcode); + if (result.code !== 200) { + return this.fail(result.message); + } + return this.success('查询成功', result.data); + } + } module.exports = configService; diff --git a/app/service/systems/delivery_order.js b/app/service/systems/delivery_order.js index fb9f2c1..0fa7e8c 100644 --- a/app/service/systems/delivery_order.js +++ b/app/service/systems/delivery_order.js @@ -778,10 +778,12 @@ class DeliveryOrderService extends Service { /** * 根据货主仓库策略解析订单步骤。 + * 若货主与仓库之间不存在已启用已签约的记录(auth_status=2, use_status=1),则抛出错误拒绝创建。 * - * @param {Object} info 当前仓库与货主上下文。 + * @param {Object} info 当前仓库与货主上下文,需包含 storeId 和 warehouseId。 * @param {Object|null} transaction 数据库事务。 * @return {Promise} 订单步骤,需审批返回 0,免审批返回 1。 + * @throws {Error} 货主未与当前仓库签约时抛出。 */ async resolveOrderStep(info, transaction = null) { const { ctx } = this; @@ -805,7 +807,7 @@ class DeliveryOrderService extends Service { }); if (!relation) { - return DELIVERY_ORDER_STEP.PENDING_REVIEW; + throw new Error('货主未与当前仓库签约,无法创建订单'); } const storeWarehouseService = ctx.service && ctx.service.systems && ctx.service.systems.storeWarehouse; diff --git a/app/service/systems/entry_order.js b/app/service/systems/entry_order.js index 33de8b1..8056b22 100644 --- a/app/service/systems/entry_order.js +++ b/app/service/systems/entry_order.js @@ -131,6 +131,26 @@ class entryOrderService extends Service { ); } + // 写入操作日志 + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'entry_order', + businessId: orderId, + operationCode: 'ENTRY_ORDER_CREATE', + operator: { + id: ctx.user?.employees_id || ctx.user?.id || '', + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + storeId, + entryOrderCode: orderCode, + sourceType: fromCode, + totalOrderLines, + finalStatus, + }, + transaction, + }); + // 提交事务 await transaction.commit(); @@ -172,9 +192,9 @@ class entryOrderService extends Service { } catch (error) { // 发生异常,回滚事务 - await transaction.rollback().catch(e => console.error('回滚事务失败:', e)); + await transaction.rollback().catch(e => ctx.logger.error(`回滚事务失败: ${e.message}`, e)); - console.error('addOrder 事务异常:', error); + ctx.logger.error(`addOrder 事务异常: ${error.message}`, error); return { success: false, message: `系统异常: ${error.message}`, @@ -825,248 +845,74 @@ class entryOrderService extends Service { } } - async qimenEntryorderConfirm(entryOrder, orderLines, isFin, outBizCode) { - if (orderLines.length < 1) { - throw new Error('行不能为空'); - } - const queryData = { - request: { - entryOrder: { - entryOrderCode: entryOrder.entry_order_code, - ownerCode: entryOrder.qimen_owner_code, - warehouseCode: entryOrder.qimen_warehouse_code, - entryOrderId: entryOrder.id, - entryOrderType: entryOrder.order_type, - outBizCode, - confirmType: isFin ? 0 : 1, - status: isFin ? 'FULFILLED' : 'PARTFULFILLED', - freight: 0, - operateTime: this.app.formatDate(new Date()), - remark: entryOrder.remark, - }, - orderLines, - }, - }; - const Result = await this.app.qimenClient.send('taobao.qimen.entryorder.confirm', entryOrder.qimen_owner_code, queryData, { - ctx: this.ctx, - }); - return Result; - } - async entryorderConfirm(orderId, isCompleted) { + /** + * 审核入库单(CREATED → PENDING)。 + * 只允许已绑定收货单的入库单推进状态,未绑定则拒绝。 + * + * @param {Object} data 请求体 + * @param {number} data.id 入库单 ID + * @return {Promise} { success, message, data } + */ + async reviewEntry(data = {}) { const { app, ctx } = this; - const transaction = await app.model.transaction(); + const orderId = Number(data.id || 0); - try { - // 锁定数据 - const entryOrder = await app.model.EntryOrder.findOne({ - where: { - id: orderId, - is_enabled: 1, - deleted_at: null, - }, - include: [ - { - model: app.model.EntryItems, - as: 'items', - lock: transaction.LOCK.UPDATE, - }, - ], - lock: transaction.LOCK.UPDATE, - transaction, - }); + if (!orderId) { + return { success: false, message: 'id 必填' }; + } - if (!entryOrder) { - await transaction.rollback(); - return { success: false, message: '入库单不存在' }; - } + const entryOrder = await app.model.EntryOrder.findOne({ + where: { id: orderId, is_enabled: 1, deleted_at: null }, + }); - // 状态检查 - const allowedStatuses = [ 'CREATED', 'PENDING' ]; - if (!allowedStatuses.includes(entryOrder.order_status)) { - await transaction.rollback(); - return { - success: false, - code: 'INVALID_STATUS', - message: `入库单状态[${entryOrder.order_status}]不允许确认`, - }; - } - - const orderLines = []; - let totalPlanQty = 0; - let totalReceivedQty = 0; - let totalConfirmIncrement = 0; - let hasItemsToConfirm = false; - - // 第一阶段:计算和验证,不执行更新 - const pendingUpdates = []; - - for (let i = 0; i < entryOrder.items.length; i++) { - const item = entryOrder.items[i]; - const planQty = item.count || 0; - const receivedQty = item.received_quantity || 0; - const confirmedQty = item.confirm_quantity || 0; - - // 计算本次确认的增量 - const confirmIncrement = Math.max(0, receivedQty - confirmedQty); - - if (confirmIncrement > 0) { - hasItemsToConfirm = true; - - // 奇门需要的是本次确认的数量(actualQty) - const orderLine = { - orderLineNo: i + 1, - ownerCode: item.owner_code, - itemCode: item.item_code, - itemId: item.item_id, - inventoryType: item.inventory_type, - planQty, - actualQty: confirmIncrement, // 传本次增量 - }; - orderLines.push(orderLine); - - totalConfirmIncrement += confirmIncrement; - - // 记录待更新数据(不执行) - pendingUpdates.push({ - id: item.id, - item_id: item.item_id, - new_confirm_quantity: confirmedQty + confirmIncrement, - old_confirm_quantity: confirmedQty, - received_quantity: receivedQty, - confirm_increment: confirmIncrement, - }); - } - - totalPlanQty += planQty; - totalReceivedQty += receivedQty; - } - - // 没有需要确认的数量 - if (!hasItemsToConfirm) { - await transaction.rollback(); - return { success: false, message: '没有需要确认的收货数量' }; - } - - // 判断是否最终完成 - const isFin = isCompleted ? true : (totalReceivedQty >= totalPlanQty); - let qimenResult = {}; - // 奇门入库单,数据同步到奇门 - if (String(entryOrder.source_type) === 'QM') { - // 第二阶段:调用奇门接口 - const Result = await this.qimenEntryorderConfirm( - entryOrder, - orderLines, - isFin, - Math.round(new Date() / 1000) - ); - qimenResult = Result.xmlArray.response; - // 奇门调用失败,回滚事务 - if (!qimenResult || String(qimenResult.flag) !== 'success') { - await transaction.rollback(); - console.error('奇门接口调用失败:', qimenResult); - return { - success: false, - code: 'QIMEN_FAILED', - message: '奇门接口调用失败', - detail: qimenResult?.message || '未知错误', - }; - } - } - // 第三阶段:奇门成功,执行数据库更新 - - // 1. 更新确认数量 - for (const update of pendingUpdates) { - const result = await app.model.EntryItems.update({ - confirm_quantity: update.new_confirm_quantity, - updated_at: new Date(), - }, { - where: { - id: update.id, - confirm_quantity: update.old_confirm_quantity, // 乐观锁,防止并发 - }, - transaction, - }); - await ctx.service.systems.stockStore.inbound(update.item_id, update.confirm_increment, transaction); - if (result[0] === 0) { - // 更新失败,可能被并发修改了 - console.warn(`更新入库明细失败,可能已被修改: id=${update.id}`); - // 可以选择重试或抛出异常 - } - } - - // 2. 更新入库单状态 - let newOrderStatus = entryOrder.order_status; - if (isFin) { - newOrderStatus = 'COMPLETED'; - } else if (totalConfirmIncrement > 0) { - // CREATED 确认后变为 PENDING,PENDING 确认后保持 PENDING(多次收货确认) - newOrderStatus = 'PENDING'; - } - - const updateResult = await app.model.EntryOrder.update({ - order_status: newOrderStatus, - sync_status: 'SUCCESS', - sync_message: JSON.stringify({ - confirmTime: new Date(), - totalPlan: totalPlanQty, - totalReceived: totalReceivedQty, - totalConfirmIncrement, - isFin, - pendingUpdatesCount: pendingUpdates.length, - qimenResult: qimenResult?.data || {}, - }), - updated_at: new Date(), - }, { - where: { - id: entryOrder.id, - order_status: entryOrder.order_status, // 乐观锁 - }, - transaction, - }); - - if (updateResult[0] === 0) { - // 入库单状态已被修改,回滚 - await transaction.rollback(); - return { - success: false, - code: 'CONCURRENT_MODIFICATION', - message: '入库单已被修改,请刷新后重试', - }; - } - // 4. 提交事务 - await transaction.commit(); - - return { - success: true, - message: isFin ? '入库单完成确认' : '入库单增量确认成功', - data: { - entryOrderId: entryOrder.id, - entryOrderCode: entryOrder.entry_order_code, - orderStatus: newOrderStatus, - totalPlan: totalPlanQty, - totalReceived: totalReceivedQty, - totalConfirmIncrement, - isFin, - updatedItemsCount: pendingUpdates.length, - orderLinesCount: orderLines.length, - }, - }; - - } catch (error) { - // 发生异常,回滚事务 - await transaction.rollback().catch(e => { - console.error('回滚事务失败:', e); - }); - - console.error('确认入库单失败:', error); + if (!entryOrder) { + return { success: false, message: '入库单不存在' }; + } + if (entryOrder.order_status !== 'CREATED') { return { success: false, - code: 'SYSTEM_ERROR', - message: `系统异常: ${error.message}`, - stack: process.env.NODE_ENV === 'development' ? error.stack : undefined, + message: `当前状态[${entryOrder.order_status}]不允许审核,仅 CREATED 可审核`, }; } + + // 校验:必须有绑定的收货单 + const hasReceiving = await ctx.model.EntryOrderReceiving.findOne({ + where: { entry_order_id: orderId, deleted_at: null }, + }); + if (!hasReceiving) { + return { + success: false, + message: '入库单未绑定收货单,请先绑定收货单后再审核', + }; + } + + // 推进状态 + await entryOrder.update({ + order_status: 'PENDING', + updated_at: new Date(), + }); + + // 写操作日志 + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'entry_order', + businessId: entryOrder.id, + operationCode: 'ENTRY_ORDER_REVIEW', + operator: { + id: ctx.user?.employees_id || ctx.user?.id || '', + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: entryOrder.warehouse_id, + message: '入库单审核通过(CREATED → PENDING)', + }, + }); + + return { + success: true, + message: '审核成功', + data: { id: entryOrder.id, order_status: 'PENDING' }, + }; } } diff --git a/app/service/systems/express.js b/app/service/systems/express.js index 928eb74..e7d38a1 100644 --- a/app/service/systems/express.js +++ b/app/service/systems/express.js @@ -2427,21 +2427,8 @@ class ExpressService extends Service { }); // 发件人相关字段统一走接口配置,货主配置仅用于打印链路。 - // 三级兜底:express_interface → 仓库 subject_config → 空字符串 - const storeRow = await this.ctx.model.Store.findByPk(warehouseId, { - attributes: [ 'subject_config' ], - raw: true, - }); - const subjectConfig = (storeRow && storeRow.subject_config) ? storeRow.subject_config : {}; const expressInterfaceConfig = expressInterface ? { ...expressInterface, - sender_name: expressInterface.sender_name || subjectConfig.sender_name || '', - sender_tel: expressInterface.sender_tel || subjectConfig.sender_tel || '', - province_name: expressInterface.province_name || subjectConfig.province_name || '', - city_name: expressInterface.city_name || subjectConfig.city_name || '', - district_name: expressInterface.district_name || subjectConfig.district_name || '', - town_name: expressInterface.town_name || subjectConfig.town_name || '', - address: expressInterface.address || subjectConfig.address || '', } : null; for (const batch of batches) { diff --git a/app/service/systems/express_platform.js b/app/service/systems/express_platform.js index be62f09..400376c 100644 --- a/app/service/systems/express_platform.js +++ b/app/service/systems/express_platform.js @@ -729,27 +729,17 @@ class ExpressPlatformService extends MainService { inputsite: listByWarehousePlatformCode.site_code || '', sitecode: listByWarehousePlatformCode.site_code || '', shipperno: listByWarehousePlatformCode.shipperno || '', - sender: (() => { - const senderName = listByWarehousePlatformCode.sender_name || ''; - const senderTel = listByWarehousePlatformCode.sender_tel || ''; - const senderProvince = listByWarehousePlatformCode.province_name || ''; - const senderCity = listByWarehousePlatformCode.city_name || ''; - const senderDistrict = listByWarehousePlatformCode.district_name || ''; - const senderTown = listByWarehousePlatformCode.town_name || ''; - const senderAddress = listByWarehousePlatformCode.address || ''; - const fallback = '仓库未配置发件人'; - return { - company: listByWarehousePlatformCode.shop_name || '', - name: senderName || fallback, - phone: senderTel || (senderName ? '' : fallback), - country: 'CN', - city: senderCity || fallback, - province: senderProvince || fallback, - area: senderDistrict || fallback, - town: senderTown || fallback, - address: senderAddress || fallback, - }; - })(), + sender: { + company: listByWarehousePlatformCode.shop_name || '', + name: listByWarehousePlatformCode.sender_name || '', + phone: listByWarehousePlatformCode.sender_tel || '', + country: 'CN', + city: listByWarehousePlatformCode.city_name || '', + province: listByWarehousePlatformCode.province_name || '', + area: listByWarehousePlatformCode.district_name || '', + town: listByWarehousePlatformCode.town_name || '', + address: listByWarehousePlatformCode.address || '', + }, // 需要实现 receiver: { name: order.name || '', company: order.company || '', @@ -789,7 +779,6 @@ class ExpressPlatformService extends MainService { providercode, numpackage, businessplat, - paymode, ordertype, businessType, codpaymoney, @@ -817,12 +806,11 @@ class ExpressPlatformService extends MainService { const { name, phone, - mobile, province: receiverProvince, city: receiverCity, address: receiverAddress, } = receiver; - const senderName = senderNameRaw || listByWarehousePlatformCode.sender_name || listByWarehousePlatformCode.shop_name || '仓库未配置发件人'; + const senderName = senderNameRaw || listByWarehousePlatformCode.sender_name || listByWarehousePlatformCode.shop_name || ''; const senderCompany = senderCompanyRaw || listByWarehousePlatformCode.shop_name || ''; const customername = senderNameRaw || senderCompanyRaw || listByWarehousePlatformCode.shop_name || '测试'; @@ -874,18 +862,18 @@ class ExpressPlatformService extends MainService { playload.codpaymoney = ''; } } - if(matchedPlatform.platid ===672){ - if(!order.source_order_codes){ + if (matchedPlatform.platid === 672) { + if (!order.source_order_codes) { throw new Error('订单数据错误,缺失平台订单号'); } - playload.object_Id = order.source_order_codes.split(",")[0]; - if(!order.extend_props.ewaybill_order_code){ + playload.object_Id = order.source_order_codes.split(',')[0]; + if (!order.extend_props.ewaybill_order_code) { throw new Error('订单数据错误,参数不全缺失extend_props.ewaybill_order_code,请复制次信息给ERP方反馈'); } playload.oaid = order.extend_props.ewaybill_order_code; - playload.transtype = "0"; + playload.transtype = '0'; playload.Mallmaskid = order.buyer_nick; - playload.mainsubpaymode = "1"; + playload.mainsubpaymode = '1'; delete playload.plattradeno; } playload.ProviderID = listByWarehousePlatformCode.providerid; @@ -1233,39 +1221,39 @@ class ExpressPlatformService extends MainService { }; }); break; - case 'QT': - case 'OTHER': - successUpdates = (result.results || []).map(item => { - const [ warehouse_id, order_id, business_key ] = String(item.orderno || '').split('_'); - const waybillCode = String(item.logisticno || item.waybill_code || '').trim(); - return { - warehouse_id, - order_id, - business_key, + case 'QT': + case 'OTHER': + successUpdates = (result.results || []).map(item => { + const [ warehouse_id, order_id, business_key ] = String(item.orderno || '').split('_'); + const waybillCode = String(item.logisticno || item.waybill_code || '').trim(); + return { + warehouse_id, + order_id, + business_key, + waybill_code: waybillCode, + orderExpressValues: { waybill_code: waybillCode, - orderExpressValues: { - waybill_code: waybillCode, - printinfo: item.printinfo, - signature: item.signature, - encryptprintinfo: item.encryptprintinfo, - encryptedtoken: item.encryptedtoken, - ...this.buildOrderExpressVerPatch([ item.ver ]), - create_at: new Date(), - logistics_code: listByWarehousePlatformCode.logistics_code || '', - logistics_interface_id: listByWarehousePlatformCode.id || null, - logistics_name: listByWarehousePlatformCode.logistics_name || '', - logistics_interface_name: listByWarehousePlatformCode.name || '', - platform_code: listByWarehousePlatformCode.platform_code || '', - status: 1, - retry_count: 0, - }, - orderDeliveryValues: { - post_status: 'fin', - order_flag: '', - }, - }; - }); - break; + printinfo: item.printinfo, + signature: item.signature, + encryptprintinfo: item.encryptprintinfo, + encryptedtoken: item.encryptedtoken, + ...this.buildOrderExpressVerPatch([ item.ver ]), + create_at: new Date(), + logistics_code: listByWarehousePlatformCode.logistics_code || '', + logistics_interface_id: listByWarehousePlatformCode.id || null, + logistics_name: listByWarehousePlatformCode.logistics_name || '', + logistics_interface_name: listByWarehousePlatformCode.name || '', + platform_code: listByWarehousePlatformCode.platform_code || '', + status: 1, + retry_count: 0, + }, + orderDeliveryValues: { + post_status: 'fin', + order_flag: '', + }, + }; + }); + break; default: { const unmatchedPlatformCode = String(listByWarehousePlatformCode && listByWarehousePlatformCode.platform_code || '').trim(); this.ctx.logger.error('[expressPlatform.polyapi] switch 无匹配 platform_code', { @@ -1546,10 +1534,10 @@ class ExpressPlatformService extends MainService { // 自动同步回传:快递号分配成功后异步触发订单同步 try { const settlementEntries = Array.from(settlementRelationMap.entries()); - for (const [key, relation] of settlementEntries) { + for (const [ key, relation ] of settlementEntries) { const successCount = Number(relation && relation.success_count) || 0; if (successCount <= 0) continue; - const [storeId, warehouseId] = key.split(':').map(Number); + const [ storeId, warehouseId ] = key.split(':').map(Number); if (!storeId || !warehouseId) continue; const contractConfig = await this.service.systems.storeWarehouse.getContractConfig( @@ -1700,28 +1688,18 @@ class ExpressPlatformService extends MainService { ? (listByWarehousePlatformCode.express.CAINIAO || listByWarehousePlatformCode.express.cainiao_code || '') : '', product_code: String(listByWarehousePlatformCode.product_type || '').trim(), - sender: (() => { - const senderName = listByWarehousePlatformCode.sender_name || ''; - const senderTel = listByWarehousePlatformCode.sender_tel || ''; - const senderProvince = listByWarehousePlatformCode.province_name || ''; - const senderCity = listByWarehousePlatformCode.city_name || ''; - const senderDistrict = listByWarehousePlatformCode.district_name || ''; - const senderTown = listByWarehousePlatformCode.town_name || ''; - const senderAddress = listByWarehousePlatformCode.address || ''; - const fallback = '仓库未配置发件人'; - return { - address: { - city: senderCity || fallback, - detail: senderAddress || fallback, - district: senderDistrict || fallback, - province: senderProvince || fallback, - town: senderTown || null, - }, - mobile: senderTel || (senderName ? '' : fallback), - name: senderName || fallback, - phone: senderTel || (senderName ? '' : fallback), - }; - })(), + sender: { + address: { + city: listByWarehousePlatformCode.city_name, + detail: listByWarehousePlatformCode.address, + district: listByWarehousePlatformCode.district_name, + province: listByWarehousePlatformCode.province_name, + town: listByWarehousePlatformCode.town_name || null, + }, + mobile: listByWarehousePlatformCode.sender_tel, + name: listByWarehousePlatformCode.sender_name, + phone: listByWarehousePlatformCode.sender_tel, + }, trade_order_info_dtos: tradeOrderList, brand_code: String(listByWarehousePlatformCode.site_code || 'default').trim(), need_encrypt: true, @@ -1886,10 +1864,10 @@ class ExpressPlatformService extends MainService { orderMetaMap ); const settlementEntries = Array.from(settlementRelationMap.entries()); - for (const [key, relation] of settlementEntries) { + for (const [ key, relation ] of settlementEntries) { const successCount = Number(relation && relation.success_count) || 0; if (successCount <= 0) continue; - const [storeId, warehouseId] = key.split(':').map(Number); + const [ storeId, warehouseId ] = key.split(':').map(Number); if (!storeId || !warehouseId) continue; const contractConfig = await this.service.systems.storeWarehouse.getContractConfig( @@ -2218,7 +2196,6 @@ class ExpressPlatformService extends MainService { */ async pdd(data = {}) { const { - matchedPlatform = {}, listByWarehousePlatformCode = {}, orders = [], } = data && typeof data === 'object' ? data : {}; @@ -2267,29 +2244,19 @@ class ExpressPlatformService extends MainService { accessToken: listByWarehousePlatformCode.token, param_waybill_cloud_print_apply_new_request: { need_encrypt: true, - sender: (() => { - const senderName = listByWarehousePlatformCode.sender_name || ''; - const senderTel = listByWarehousePlatformCode.sender_tel || ''; - const senderProvince = listByWarehousePlatformCode.province_name || ''; - const senderCity = listByWarehousePlatformCode.city_name || ''; - const senderDistrict = listByWarehousePlatformCode.district_name || ''; - const senderTown = listByWarehousePlatformCode.town_name || ''; - const senderAddress = listByWarehousePlatformCode.address || ''; - const fallback = '仓库未配置发件人'; - return { - address: { - country: '中国', - city: senderCity || fallback, - province: senderProvince || fallback, - district: senderDistrict || fallback, - town: senderTown || null, - detail: senderAddress || fallback, - }, - moblie: senderTel || (senderName ? '' : fallback), - name: senderName || fallback, - phone: senderTel || (senderName ? '' : fallback), - }; - })(), + sender: { + address: { + country: '中国', + city: listByWarehousePlatformCode.city_name, + province: listByWarehousePlatformCode.province_name, + district: listByWarehousePlatformCode.district_name, + town: listByWarehousePlatformCode.town_name || null, + detail: listByWarehousePlatformCode.address, + }, + moblie: listByWarehousePlatformCode.sender_tel, + name: listByWarehousePlatformCode.sender_name, + phone: listByWarehousePlatformCode.sender_tel, + }, trade_order_info_dtos: tradeOrderList, wp_code: listByWarehousePlatformCode && listByWarehousePlatformCode.express ? (listByWarehousePlatformCode.express.PDD || '') @@ -2581,10 +2548,10 @@ class ExpressPlatformService extends MainService { // 自动同步回传:快递号分配成功后异步触发订单同步 try { const settlementEntries = Array.from(settlementRelationMap.entries()); - for (const [key, relation] of settlementEntries) { + for (const [ key, relation ] of settlementEntries) { const successCount = Number(relation && relation.success_count) || 0; if (successCount <= 0) continue; - const [storeId, warehouseId] = key.split(':').map(Number); + const [ storeId, warehouseId ] = key.split(':').map(Number); if (!storeId || !warehouseId) continue; const contractConfig = await this.service.systems.storeWarehouse.getContractConfig( diff --git a/app/service/systems/inbound_direct_log.js b/app/service/systems/inbound_direct_log.js index 6ea3993..31d9991 100644 --- a/app/service/systems/inbound_direct_log.js +++ b/app/service/systems/inbound_direct_log.js @@ -13,13 +13,16 @@ const Service = require('egg').Service; class InboundDirectLogService extends Service { /** - * 获取入库单的受控入库信息。 - * 返回入库单基本信息、明细列表,以及每项明细已有的导入/PDA 入库记录。 + * 获取入库单的受控入库信息(精简版)。 + * 返回入库单基本信息、明细列表(含计划数量与已完成数量)、收货单绑定关系。 * @param {string} entryOrderCode 入库单号 * @return {Promise} code/data/message 结构 + * - data.entryOrder: { id, entry_order_code, order_status, store_remask } + * - data.items: [{ id, stock_id, planned, completed, stock, bindings }] + * - data.receivingBindings: 收货单绑定关系列表 */ async getItems(entryOrderCode) { - const { ctx } = this; + const { ctx, app } = this; const code = String(entryOrderCode || '').trim(); if (!code) { @@ -67,22 +70,19 @@ class InboundDirectLogService extends Service { return { code: 404, message: '入库单不存在或无权访问', data: null }; } + // 查询货主商家备注 + const storeWarehouse = await ctx.model.StoreWarehouse.findOne({ + where: { store_id: entryOrder.store_id, warehouse_id: entryOrder.warehouse_id }, + attributes: [ 'store_remask' ], + raw: true, + }); + // 查询该入库单下已有的导入/PDA 入库记录 const directLogs = await ctx.model.InboundDirectLog.findAll({ where: { entry_order_id: entryOrder.id }, order: [[ 'created_at', 'ASC' ]], }); - // 按 stock_id 汇总已入库数量 - const logSummary = {}; - for (const log of directLogs) { - const key = String(log.stock_id); - if (!logSummary[key]) { - logSummary[key] = 0; - } - logSummary[key] += Number(log.quantity); - } - // 将直接入库记录按 entry_item_id 关联到明细 const itemDirectLogs = {}; for (const log of directLogs) { @@ -96,6 +96,7 @@ class InboundDirectLogService extends Service { stock_id: log.stock_id, quantity: log.quantity, inbound_type: log.inbound_type, + space_id: log.space_id, remark: log.remark, operator_id: log.operator_id, operator_name: log.operator_name, @@ -112,30 +113,134 @@ class InboundDirectLogService extends Service { })) : []; - // 组装明细 + // 收集所有 stock_id,通过 getStockDetails 批量获取带缓存的商品详情 + const stockIds = [ ...new Set( + (entryOrder.items || []) + .map(item => Number(item.stock_id)) + .filter(id => id && id > 0) + ) ]; + + /** @type {Map} */ + const stockMap = new Map(); + if (stockIds.length > 0) { + const warehouseId = ctx.user.store_id; + const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { warehouseId }); + for (const detail of stockDetails) { + stockMap.set(detail.id, detail); + } + } + + // 组装明细(精简字段,突出已入/总数) const items = (entryOrder.items || []).map(item => { const planQty = Number(item.count) || 0; const logKey = String(item.id); const logs = itemDirectLogs[logKey] || []; const directInQty = logs.reduce((sum, l) => sum + Number(l.quantity), 0); - // 入库进度使用已收货数量 + 导入/PDA 已入库数量 - const totalInboundQty = directInQty + Number(item.received_quantity || 0); return { id: item.id, stock_id: item.stock_id, - count: planQty, - received_quantity: Number(item.received_quantity) || 0, - item_code: item.item_code, - warehouse_item_code: (item.stock && item.stock.item_code) || '', - warehouse_item_name: (item.stock && item.stock.item_name) || '', - warehouse_item_spec: (item.stock && item.stock.sku_property) || '', - direct_inbound_quantity: directInQty, - remaining_quantity: Math.max(0, planQty - totalInboundQty), - direct_logs: logs, + planned: planQty, + completed: directInQty, + stock: stockMap.get(Number(item.stock_id)) || null, }; }); + // 收集所有 InboundDirectLog 中的 space_id,批量查询库位名称 + /** @type {Map} space_id -> space_name */ + const spaceNameMap = new Map(); + const allSpaceIds = [ ...new Set( + Object.values(itemDirectLogs) + .flat() + .map(log => log.space_id) + .filter(id => id != null) + ) ]; + if (allSpaceIds.length > 0) { + const spaces = await ctx.model.LocationSpace.findAll({ + where: { id: { [app.Sequelize.Op.in]: allSpaceIds } }, + attributes: [ 'id', 'custom_name', 'space_code' ], + raw: true, + }); + for (const sp of spaces) { + spaceNameMap.set(sp.id, sp.custom_name || sp.space_code || ''); + } + } + + // 批量查询已绑定的收货明细列表 + const entryItemIds = items.map(i => i.id).filter(Boolean); + /** @type {Map>} 按 entry_item_id 分组 */ + const bindingsMap = new Map(); + if (entryItemIds.length > 0) { + // 1. 查绑定关系表 + const bindingRows = await ctx.model.EntryReceivingBinding.findAll({ + where: { + entry_item_id: { [app.Sequelize.Op.in]: entryItemIds }, + deleted_at: null, + }, + attributes: [ 'id', 'entry_item_id', 'receiving_detail_id', 'allocated_quantity', 'status' ], + raw: true, + }); + + if (bindingRows.length > 0) { + // 2. 验证收货明细存在性(仅校验,不取冗余字段) + const detailIds = [ ...new Set(bindingRows.map(b => b.receiving_detail_id).filter(Boolean)) ]; + const validDetailIds = new Set(); + if (detailIds.length > 0) { + const details = await ctx.model.ReceivingDetail.findAll({ + where: { id: { [app.Sequelize.Op.in]: detailIds } }, + attributes: [ 'id' ], + raw: true, + }); + for (const d of details) { + validDetailIds.add(d.id); + } + } + + // 3. 按 entry_item_id 分组,只保留核心字段 + for (const b of bindingRows) { + const key = b.entry_item_id; + if (!bindingsMap.has(key)) { + bindingsMap.set(key, []); + } + bindingsMap.get(key).push({ + detail_id: b.receiving_detail_id, + binding_id: b.id, + allocated_quantity: b.allocated_quantity || 0, + }); + } + } + } + + // 将 bindings 挂到对应 item,并补充库位信息(space_id/space_name 来自 InboundDirectLog) + for (const item of items) { + const bindings = bindingsMap.get(item.id) || []; + const logKey = String(item.id); + const directLogs = itemDirectLogs[logKey] || []; + + // 从 InboundDirectLog 中提取 space_id,并解析库位名称 + // 如果 bindings 为空但有 directLog 带 space_id,则构造一条 binding 展示库位信息 + if (bindings.length === 0 && directLogs.length > 0) { + const firstWithSpace = directLogs.find(l => l.space_id); + if (firstWithSpace) { + item.bindings = [{ + space_id: firstWithSpace.space_id, + space_name: spaceNameMap.get(Number(firstWithSpace.space_id)) || '', + }]; + } else { + item.bindings = []; + } + } else { + // 如果有 bindings,取第一条带 space_id 的 directLog 补充 + const firstWithSpace = directLogs.find(l => l.space_id); + const sid = firstWithSpace ? firstWithSpace.space_id : null; + item.bindings = bindings.map(b => ({ + ...b, + space_id: sid, + space_name: sid != null ? (spaceNameMap.get(Number(sid)) || '') : '', + })); + } + } + return { code: 200, message: '查询成功', @@ -143,33 +248,22 @@ class InboundDirectLogService extends Service { entryOrder: { id: entryOrder.id, entry_order_code: entryOrder.entry_order_code, - order_type: entryOrder.order_type, order_status: entryOrder.order_status, - source_type: entryOrder.source_type, - warehouse_id: entryOrder.warehouse_id, - store_id: entryOrder.store_id, - remark: entryOrder.remark, + store_remask: (storeWarehouse && storeWarehouse.store_remask) || '', }, items, - direct_logs: directLogs, receivingBindings, - summary: { - total_items: items.length, - total_planned: items.reduce((s, i) => s + i.count, 0), - total_direct_inbound: items.reduce((s, i) => s + i.direct_inbound_quantity, 0), - total_import: directLogs.filter(l => l.inbound_type === 'import').reduce((s, l) => s + Number(l.quantity), 0), - total_pda: directLogs.filter(l => l.inbound_type === 'pda').reduce((s, l) => s + Number(l.quantity), 0), - }, }, }; } /** * 单条校验并写入一条导入/PDA 入库记录。 - * @param {Object} ctx + * @param {Object} ctx Egg.js 上下文对象 * @param {Object} entryOrder 入库单实例 - * @param {Object} item { stock_id, quantity, inbound_type, remark } - * @return {Promise<{ok: boolean, log?: Object, error?: Object}>} + * @param {Object} item 入库项,包含 stock_id、quantity、inbound_type、remark、space_id + * @param {Object} [transaction] Sequelize 事务对象,可选 + * @return {Promise<{ok: boolean, log?: Object, error?: Object}>} 返回操作结果,ok 为 true 时 log 包含入库记录详情,ok 为 false 时 error 包含错误信息 */ async _addSingleItem(ctx, entryOrder, item, transaction) { const stockId = Number(item.stock_id || 0); @@ -177,17 +271,70 @@ class InboundDirectLogService extends Service { const inboundType = String(item.inbound_type || '').trim().toLowerCase(); const remark = item.remark ? String(item.remark).trim() : ''; const spaceId = item.space_id ? Number(item.space_id) : null; + const receivingDetailId = Number(item.receiving_detail_id || 0); + const isBindingMode = receivingDetailId > 0; if (!stockId) { return { ok: false, error: { code: 400, message: 'items[].stock_id 必填' } }; } - if (!quantity || quantity <= 0 || !Number.isFinite(quantity)) { - return { ok: false, error: { code: 400, message: 'items[].quantity 必须为正整数' } }; + + // 绑定模式下必须传 space_id + if (isBindingMode && !spaceId) { + return { ok: false, error: { code: 400, message: '绑定收货明细时必须指定 space_id' } }; } + + // 非绑定模式下校验 quantity 必填且为正整数 + if (!isBindingMode) { + if (!quantity || quantity <= 0 || !Number.isFinite(quantity)) { + return { ok: false, error: { code: 400, message: 'items[].quantity 必须为正整数' } }; + } + } + if (![ 'import', 'pda' ].includes(inboundType)) { return { ok: false, error: { code: 400, message: 'items[].inbound_type 必须为 import 或 pda' } }; } + // 确定有效数量:绑定模式下自动计算收货明细的可用数量(actual_quantity - 已绑定数量) + let effectiveQuantity = quantity; + if (isBindingMode) { + // 查询收货明细 + const receivingDetail = await ctx.model.ReceivingDetail.findOne({ + where: { id: receivingDetailId }, + ...(transaction ? { transaction } : {}), + }); + if (!receivingDetail) { + return { ok: false, error: { code: 400, message: `收货明细不存在(id=${receivingDetailId})` } }; + } + // 绑定模式下 stock_id 必须匹配收货明细的 system_product_id + if (receivingDetail.system_product_id !== stockId) { + return { ok: false, error: { code: 400, message: `收货明细的商品(system_product_id=${receivingDetail.system_product_id})与传入的 stock_id(${stockId})不匹配` } }; + } + + // 查询该收货明细已被占用的数量(pending + committed) + const allocatedSum = await ctx.model.query( + `SELECT COALESCE(SUM(allocated_quantity), 0) AS total + FROM wms_entry_receiving_binding + WHERE receiving_detail_id = :rdId AND status IN ('pending', 'committed') AND deleted_at IS NULL`, + { + replacements: { rdId: receivingDetailId }, + type: ctx.model.QueryTypes.SELECT, + ...(transaction ? { transaction } : {}), + } + ); + const usedQty = Number(allocatedSum?.[0]?.total || 0); + const actualQty = Number(receivingDetail.actual_quantity) || 0; + effectiveQuantity = actualQty - usedQty; + if (effectiveQuantity <= 0) { + return { + ok: false, + error: { + code: 400, + message: `收货明细可用数量不足:实际数量 ${actualQty},已占用 ${usedQty},可用 ${effectiveQuantity}`, + }, + }; + } + } + // 查找入库单中该 stock_id 对应的所有明细,累加计划数量 const entryItems = await ctx.model.EntryItems.findAll({ where: { order_id: entryOrder.id, stock_id: stockId }, @@ -198,7 +345,7 @@ class InboundDirectLogService extends Service { return { ok: false, error: { code: 400, message: `入库单中不存在 stock_id=${stockId} 的商品` } }; } - const totalPlanQty = entryItems.reduce((sum, item) => sum + (Number(item.count) || 0), 0); + const totalPlanQty = entryItems.reduce((sum, ei) => sum + (Number(ei.count) || 0), 0); // 计算该 stock_id 在该入库单下已有的导入/PDA 入库总量 const logWhere = { entry_order_id: entryOrder.id, stock_id: stockId }; @@ -210,32 +357,37 @@ class InboundDirectLogService extends Service { }); const existingTotal = existingLogs.reduce((sum, log) => sum + Number(log.quantity), 0); - const newTotal = existingTotal + quantity; - - if (newTotal > totalPlanQty) { - return { - ok: false, - error: { - code: 400, - message: `入库数量超过计划:商品计划 ${totalPlanQty},已入库 ${existingTotal},本次 ${quantity},合计 ${newTotal}`, - data: { - stock_id: stockId, - plan_quantity: totalPlanQty, - existing_quantity: existingTotal, - requested_quantity: quantity, - exceeded_by: newTotal - totalPlanQty, + // 绑定模式下跳过入库单计划数量校验(允许超过计划数量) + // 只有 PENDING 非绑定模式限制超量;CREATED 人工导入允许超过 + const isManualImport = entryOrder.order_status === 'CREATED' && !isBindingMode; + if (!isBindingMode && !isManualImport) { + const newTotal = existingTotal + effectiveQuantity; + if (newTotal > totalPlanQty) { + return { + ok: false, + error: { + code: 400, + message: `入库数量超过计划:商品计划 ${totalPlanQty},已入库 ${existingTotal},本次 ${effectiveQuantity},合计 ${newTotal}`, + data: { + stock_id: stockId, + plan_quantity: totalPlanQty, + existing_quantity: existingTotal, + requested_quantity: effectiveQuantity, + exceeded_by: newTotal - totalPlanQty, + }, }, - }, - }; + }; + } } + const newTotal = existingTotal + effectiveQuantity; + // 写入记录 - const createOpts = transaction ? { transaction } : {}; const log = await ctx.model.InboundDirectLog.create({ warehouse_id: entryOrder.warehouse_id, store_id: entryOrder.store_id, stock_id: stockId, - quantity, + quantity: effectiveQuantity, inbound_type: inboundType, entry_order_id: entryOrder.id, entry_order_code: entryOrder.entry_order_code, @@ -244,72 +396,171 @@ class InboundDirectLogService extends Service { operator_id: ctx.user?.employees_id || ctx.user?.id || null, operator_name: ctx.user?.employees_name || '', created_at: new Date(), - }); + }, transaction ? { transaction } : {}); + + // 收货单明细绑定(可选) + let receivingBindResult = null; + if (isBindingMode) { + // 绑定模式:全量绑定,allocated_quantity = effectiveQuantity + item.allocated_quantity = effectiveQuantity; + receivingBindResult = await this._bindReceivingDetail( + ctx, entryOrder, item, stockId, receivingDetailId, effectiveQuantity, transaction + ); + } else if (receivingDetailId) { + receivingBindResult = await this._bindReceivingDetail( + ctx, entryOrder, item, stockId, receivingDetailId, effectiveQuantity, transaction + ); + } return { ok: true, log: { id: log.id, stock_id: stockId, - quantity, + quantity: effectiveQuantity, inbound_type: inboundType, space_id: spaceId, plan_quantity: totalPlanQty, existing_before: existingTotal, existing_after: newTotal, remaining: Math.max(0, totalPlanQty - newTotal), + ...(receivingBindResult ? { receivingBindResult } : {}), }, }; } + /** + * 将入库直接记录绑定到收货单明细(预占模式,status='pending')。 + * 校验收货明细存在、未取消、可用数量足够后,写入 wms_entry_receiving_binding 并确保主表绑定存在。 + * @param {Object} ctx Egg.js 上下文对象 + * @param {Object} entryOrder 入库单实例 + * @param {Object} item 入库项参数,包含 allocated_quantity、item_code 等可选字段 + * @param {number} stockId 商品SKU ID + * @param {number} receivingDetailId 收货单明细ID + * @param {number} quantity 本次入库数量 + * @param {Object} [transaction] Sequelize 事务对象,可选 + * @return {Promise} 返回绑定结果 { binding_id, receiving_detail_id, allocated_quantity, status } + */ + async _bindReceivingDetail(ctx, entryOrder, item, stockId, receivingDetailId, quantity, transaction) { + // 确定预分配数量:优先用 allocated_quantity,否则回退到 quantity + let allocatedQty = Number(item.allocated_quantity || 0); + if (!allocatedQty || allocatedQty <= 0) { + allocatedQty = quantity; + } + if (!Number.isFinite(allocatedQty) || allocatedQty <= 0) { + return { error: 'allocated_quantity 必须为正整数' }; + } + if (allocatedQty > quantity) { + return { error: `allocated_quantity(${allocatedQty}) 不能大于入库数量(${quantity})` }; + } + + // 1. 查询收货明细行(锁定) + const receivingDetail = await ctx.model.ReceivingDetail.findOne({ + where: { id: receivingDetailId }, + ...(transaction ? { lock: transaction.LOCK?.UPDATE, transaction } : {}), + }); + if (!receivingDetail) { + return { error: `收货明细不存在(id=${receivingDetailId})` }; + } + + // 2. 查询已占用(pending + committed)的分配量 + const allocatedSum = await ctx.model.query( + `SELECT COALESCE(SUM(allocated_quantity), 0) AS total + FROM wms_entry_receiving_binding + WHERE receiving_detail_id = :rdId AND status IN ('pending', 'committed') AND deleted_at IS NULL`, + { + replacements: { rdId: receivingDetailId }, + type: ctx.model.QueryTypes.SELECT, + ...(transaction ? { transaction } : {}), + } + ); + const usedQty = Number(allocatedSum?.[0]?.total || 0); + const availableQty = (Number(receivingDetail.actual_quantity) || 0) - usedQty; + if (allocatedQty > availableQty) { + return { + error: `收货明细可用数量不足: 可用${availableQty}, 请求${allocatedQty}`, + available_quantity: availableQty, + requested_quantity: allocatedQty, + }; + } + + // 3. 查找入库明细行(entry_item_id) + const entryItem = await ctx.model.EntryItems.findOne({ + where: { + order_id: entryOrder.id, + stock_id: stockId, + }, + ...(transaction ? { transaction } : {}), + }); + + // 4. 写入绑定(status='pending',预占不提交) + const binding = await ctx.model.EntryReceivingBinding.create({ + entry_item_id: entryItem?.id || 0, + receiving_detail_id: receivingDetailId, + allocated_quantity: allocatedQty, + status: 'pending', + creator_id: ctx.user?.id || 0, + }, transaction ? { transaction } : {}); + + return { + binding_id: binding.id, + receiving_detail_id: receivingDetailId, + allocated_quantity: allocatedQty, + status: 'pending', + }; + } + /** * 按商品增量添加导入/PDA 入库记录(支持单条和批量)。 * * 单条模式(兼容旧调用): - * { entry_order_code, stock_id, quantity, inbound_type, remark } + * { entry_order_id, stock_id, quantity, inbound_type, remark } * * 批量模式(推荐): - * { entry_order_code, items: [{ stock_id, quantity, inbound_type, remark }] } + * { entry_order_id, items: [{ stock_id, quantity, inbound_type, remark }] } * * 批量模式下所有商品共享同一个入库单状态校验,任一商品校验失败整批拒绝。 * 若该商品在当前入库单中的累计入库量超过计划数量则拒绝。 - * @param {Object} params - * @param {string} params.entry_order_code 入库单号 + * + * 可选收货单明细绑定(批量模式下 items 元素支持): + * { ..., receiving_detail_id, allocated_quantity } + * 传入 receiving_detail_id 后,将校验收货明细可用数量并写入 wms_entry_receiving_binding(status='pending' 预占)。 + * @param {Object} params 请求参数对象 + * @param {number} params.entry_order_id 入库单ID * @param {number} [params.stock_id] 商品SKU ID(单条模式) * @param {number} [params.quantity] 本次入库数量(单条模式) * @param {string} [params.inbound_type] 入库方式(单条模式) * @param {Array} [params.items] 商品列表(批量模式) * @param {string} [params.remark] 备注(单条模式) - * @return {Promise} code/data/message 结构 + * @param {number} [params.receiving_detail_id] 收货单明细ID(单条模式,可选,传入后触发预占绑定) + * @param {number} [params.allocated_quantity] 预分配数量(单条模式,可选,默认等于 quantity) + * @return {Promise} 返回 { code, message, data },code=200 表示成功 */ async addItem(params) { const { ctx } = this; - const entryOrderCode = String(params.entry_order_code || '').trim(); + const warehouseId = ctx.user.store_id; + const entryOrderId = Number(params.entry_order_id) || 0; - if (!entryOrderCode) { - return { code: 400, message: 'entry_order_code 必填', data: null }; + if (!entryOrderId || entryOrderId <= 0) { + return { code: 400, message: 'entry_order_id 必填', data: null }; } // 判断批量/单条模式 const isBatch = Array.isArray(params.items) && params.items.length > 0; const items = isBatch ? params.items : [{ stock_id: params.stock_id, + space_id: params.space_id, quantity: params.quantity, inbound_type: params.inbound_type, remark: params.remark, + receiving_detail_id: params.receiving_detail_id, + allocated_quantity: params.allocated_quantity, }]; - // 查找入库单 - const entryOrder = await ctx.model.EntryOrder.findOne({ - where: { - entry_order_code: entryOrderCode, - warehouse_id: ctx.user.store_id, - is_enabled: 1, - deleted_at: null, - }, - }); + // 通过主键查找入库单 + const entryOrder = await ctx.model.EntryOrder.findByPk(entryOrderId); - if (!entryOrder) { + if (!entryOrder || entryOrder.warehouse_id !== warehouseId) { return { code: 404, message: '入库单不存在或无权访问', data: null }; } @@ -321,6 +572,28 @@ class InboundDirectLogService extends Service { return { code: 400, message: '已完成的入库单不允许操作', data: null }; } + // 检查接入库单是否已绑定收货单 + const hasReceivingBindings = await ctx.model.EntryOrderReceiving.findOne({ + where: { entry_order_id: entryOrder.id, deleted_at: null }, + }); + + // CREATED + 已绑定 → 拒绝(需先走 reviewEntry 审核) + if (entryOrder.order_status === 'CREATED' && hasReceivingBindings) { + return { code: 400, message: '入库单已绑定收货单且状态为 CREATED,请先审核后再进行上架操作', data: null }; + } + + // PENDING 状态校验 + if (entryOrder.order_status === 'PENDING') { + if (!hasReceivingBindings) { + return { code: 400, message: '入库单未绑定收货单,无法上架', data: null }; + } + for (const item of items) { + if (!item.receiving_detail_id) { + return { code: 400, message: '随机入库需要选定收货单明细提交,缺少 receiving_detail_id', data: null }; + } + } + } + // 批量模式下用事务包裹,任一失败整批回退 const useTransaction = isBatch; const txn = useTransaction ? await ctx.model.transaction() : null; @@ -389,9 +662,9 @@ class InboundDirectLogService extends Service { /** * 移除一条导入/PDA 入库记录(仅限未提交的入库单)。 - * @param {Object} params + * @param {Object} params 请求参数对象 * @param {number} params.id 入库记录ID(wms_inbound_direct_log.id) - * @return {Promise} code/data/message 结构 + * @return {Promise} 返回 { code, message, data },code=200 表示移除成功 */ async removeItem(params) { const { ctx } = this; @@ -462,28 +735,25 @@ class InboundDirectLogService extends Service { } /** - * 提交确认完成入库,将导入/PDA 入库记录写入库存,并触发奇门/API 回传。 - * @param {string} entryOrderCode 入库单号 + * 提交确认完成入库(先同步后写库模式)。 + * 先调用 qimenEntrySync 进行奇门/API 回传,成功后在 onSuccess 回调内开启事务写入库存。 + * 同步失败则只写 FAILED 状态 + 操作日志,不写库存。 + * @param {number} entryOrderId 入库单 ID * @return {Promise} code/data/message 结构 */ - async commit(entryOrderCode) { + async commit(entryOrderId) { const { ctx, app } = this; - const code = String(entryOrderCode || '').trim(); + const warehouseId = ctx.user.store_id; + const entryOrderIdNum = Number(entryOrderId) || 0; - if (!code) { - return { code: 400, message: 'entry_order_code 必填', data: null }; + if (!entryOrderIdNum || entryOrderIdNum <= 0) { + return { code: 400, message: 'entry_order_id 必填', data: null }; } - const entryOrder = await ctx.model.EntryOrder.findOne({ - where: { - entry_order_code: code, - warehouse_id: ctx.user.store_id, - is_enabled: 1, - deleted_at: null, - }, - }); + // 通过主键查找入库单 + const entryOrder = await ctx.model.EntryOrder.findByPk(entryOrderIdNum); - if (!entryOrder) { + if (!entryOrder || entryOrder.warehouse_id !== warehouseId) { return { code: 404, message: '入库单不存在或无权访问', data: null }; } @@ -520,179 +790,287 @@ class InboundDirectLogService extends Service { return { code: 400, message: '入库单无明细', data: null }; } - const warehouseId = entryOrder.warehouse_id; const storeId = entryOrder.store_id; - const transaction = await ctx.model.transaction(); - try { - // 记录已处理过的 stock_id,避免同 stock_id 多明细重复写库存 - const processedStockIds = new Set(); + // ===== 阶段一:先同步奇门/API(事务外) ===== + const items = entryItems.map((item, idx) => ({ + orderLineNo: idx + 1, + ownerCode: item.owner_code || '', + itemCode: item.item_code || '', + itemId: item.item_id || '', + inventoryType: item.inventory_type || 'ZP', + planQty: Number(item.count) || 0, + actualQty: Number(item.count) || 0, + })); - // 逐商品写入库存 - for (const item of entryItems) { - const stockId = item.stock_id; - if (!stockId) continue; + const syncResult = await this.qimenEntrySync({ + entryOrder, + orderLines: items, + outBizCode: `DIRECT_INBOUND_${Date.now()}`, + remark: '导入/PDA直接入库提交', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + // ===== 阶段二:同步成功后在 onSuccess 内开启事务写入库存 ===== + onSuccess: async eo => { + const transaction = await ctx.model.transaction(); - const inboundQty = stockSummary[String(stockId)] || 0; - if (inboundQty <= 0) continue; + try { + const processedStockIds = new Set(); - // 更新入库明细的 received_quantity(按该明细的计划占比分配) - const planQty = Number(item.count) || 0; - const itemReceivedQty = planQty > 0 ? Math.min(planQty, inboundQty) : inboundQty; - await ctx.model.EntryItems.update({ - received_quantity: itemReceivedQty, - }, { - where: { id: item.id }, - transaction, - }); + // 查询 pending 绑定:entry_item_id → 收货明细ID + const entryItemIds = entryItems.map(ei => ei.id); + const pendingBindings = await ctx.model.EntryReceivingBinding.findAll({ + where: { entry_item_id: entryItemIds, status: 'pending', deleted_at: null }, + attributes: [ 'id', 'entry_item_id', 'receiving_detail_id' ], + raw: true, + }); - // 同一 stock_id 只写一次库存 - if (processedStockIds.has(String(stockId))) continue; - processedStockIds.add(String(stockId)); + // 查收货明细详情,构建 entry_item_id → 明细信息 的映射 + const detailIds = [ ...new Set(pendingBindings.map(b => b.receiving_detail_id)) ]; + const bindingDetailMap = new Map(); + if (detailIds.length > 0) { + const details = await ctx.model.ReceivingDetail.findAll({ + where: { id: detailIds }, + attributes: [ 'id', 'receiving_id', 'batch_number', 'production_date', 'expiry_date' ], + raw: true, + }); + const detailById = new Map(details.map(d => [ d.id, d ])); + for (const b of pendingBindings) { + const d = detailById.get(b.receiving_detail_id); + if (d) bindingDetailMap.set(b.entry_item_id, d); + } + } - // 使用入库单号作为批次号 - const batchNo = entryOrder.entry_order_code; - const inventoryType = item.inventory_type || 'ZP'; + // 逐商品写入库存 + for (const item of entryItems) { + const stockId = item.stock_id; + if (!stockId) continue; - // 从该 stock_id 的入库记录中取第一个非空 space_id,兜底 1 - const logForSpace = directLogs.find(l => String(l.stock_id) === String(stockId) && l.space_id); - const spaceId = logForSpace ? Number(logForSpace.space_id) : 1; + const inboundQty = stockSummary[String(stockId)] || 0; + if (inboundQty <= 0) continue; - // 锁定并更新 StockWarehouse 总库存 - const stockRecord = await ctx.model.StockWarehouse.findOne({ - where: { id: stockId, is_valid: 'Y', deleted_at: null }, - lock: transaction.LOCK.UPDATE, - transaction, - }); + // 更新入库明细的 received_quantity(按该明细的计划占比分配) + const planQty = Number(item.count) || 0; + const itemReceivedQty = planQty > 0 ? Math.min(planQty, inboundQty) : inboundQty; + await ctx.model.EntryItems.update({ + received_quantity: itemReceivedQty, + }, { + where: { id: item.id }, + transaction, + }); - if (stockRecord) { - const beforeQuantity = Number(stockRecord.quantity) || 0; - const beforeLockedQuantity = Number(stockRecord.locked_quantity) || 0; + // 同一 stock_id 只写一次库存 + if (processedStockIds.has(String(stockId))) continue; + processedStockIds.add(String(stockId)); - await stockRecord.increment('quantity', { by: inboundQty, transaction, silent: true }); - await stockRecord.reload({ transaction }); + // 使用入库单号作为批次号;若有收货绑定则使用收货明细信息 + const bindInfo = bindingDetailMap.get(item.id); + const rdReceivingId = bindInfo ? bindInfo.receiving_id : null; + const effectiveBatchNo = bindInfo?.batch_number || eo.entry_order_code; + const rdProductionDate = bindInfo?.production_date || null; + const rdExpiryDate = bindInfo?.expiry_date || null; + const batchNo = eo.entry_order_code; + const inventoryType = item.inventory_type || 'ZP'; - const afterQuantity = Number(stockRecord.quantity) || 0; - const afterLockedQuantity = Number(stockRecord.locked_quantity) || 0; + // 从该 stock_id 的入库记录中取第一个非空 space_id,兜底 1 + const logForSpace = directLogs.find(l => String(l.stock_id) === String(stockId) && l.space_id); + const spaceId = logForSpace ? Number(logForSpace.space_id) : 1; - // 写入库存流水 - await ctx.service.systems.stockTransaction.create({ - transaction_type: 'INBOUND', - warehouse_id: warehouseId, - store_id: storeId, - stock_id: stockId, - quantity: inboundQty, - batch_no: batchNo, - inventory_type: inventoryType, - order_type: entryOrder.order_type, - order_no: entryOrder.entry_order_code, - entry_order_id: entryOrder.id, - operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), - operator_name: ctx.user?.employees_name || '', - remark: '导入/PDA直接入库提交', - before_quantity: beforeQuantity, - after_quantity: afterQuantity, - before_locked_quantity: beforeLockedQuantity, - after_locked_quantity: afterLockedQuantity, - created_at: new Date(), - }, { transaction }); - } + // 锁定并更新 StockWarehouse 总库存 + const stockRecord = await ctx.model.StockWarehouse.findOne({ + where: { id: stockId, is_valid: 'Y', deleted_at: null }, + lock: transaction.LOCK.UPDATE, + transaction, + }); - // 创建/更新 Storage 库位库存 - const storageRecord = await ctx.model.Storage.findOne({ - where: { - space_id: spaceId, - stock_id: stockId, - batch_no: batchNo, - inventory_type: inventoryType, - is_enabled: 1, - delete_at: null, - }, - lock: transaction.LOCK.UPDATE, - transaction, - }); + if (stockRecord) { + const beforeQuantity = Number(stockRecord.quantity) || 0; + const beforeLockedQuantity = Number(stockRecord.locked_quantity) || 0; - if (storageRecord) { - await ctx.model.Storage.update({ - quantity: app.Sequelize.literal(`quantity + ${inboundQty}`), - available_quantity: app.Sequelize.literal(`available_quantity + ${inboundQty}`), - entry_order_id: entryOrder.id, - inbound_time: new Date(), - inbound_order_no: entryOrder.entry_order_code, + await stockRecord.increment('quantity', { by: inboundQty, transaction, silent: true }); + await stockRecord.reload({ transaction }); + + const afterQuantity = Number(stockRecord.quantity) || 0; + const afterLockedQuantity = Number(stockRecord.locked_quantity) || 0; + + // 写入库存流水 + await ctx.service.systems.stockTransaction.create({ + transaction_type: 'INBOUND', + warehouse_id: warehouseId, + store_id: storeId, + stock_id: stockId, + quantity: inboundQty, + batch_no: batchNo, + inventory_type: inventoryType, + order_type: eo.order_type, + order_no: eo.entry_order_code, + entry_order_id: eo.id, + operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), + operator_name: ctx.user?.employees_name || '', + remark: '导入/PDA直接入库提交', + before_quantity: beforeQuantity, + after_quantity: afterQuantity, + before_locked_quantity: beforeLockedQuantity, + after_locked_quantity: afterLockedQuantity, + created_at: new Date(), + }, { transaction }); + } + + // 创建/更新 Storage 库位库存 + const storageRecord = await ctx.model.Storage.findOne({ + where: { + space_id: spaceId, + stock_id: stockId, + batch_no: batchNo, + inventory_type: inventoryType, + is_enabled: 1, + delete_at: null, + }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + let storageId = null; + let storageBeforeQty = 0; + let storageAfterQty = 0; + + if (storageRecord) { + storageBeforeQty = Number(storageRecord.quantity) || 0; + storageAfterQty = storageBeforeQty + inboundQty; + + await ctx.model.Storage.update({ + quantity: app.Sequelize.literal(`quantity + ${inboundQty}`), + available_quantity: app.Sequelize.literal(`available_quantity + ${inboundQty}`), + entry_order_id: eo.id, + inbound_time: new Date(), + inbound_order_no: eo.entry_order_code, + production_date: rdProductionDate, + expiry_date: rdExpiryDate, + receiving_id: rdReceivingId, + updated_at: new Date(), + }, { + where: { id: storageRecord.id }, + transaction, + }); + storageId = storageRecord.id; + } else { + storageBeforeQty = 0; + storageAfterQty = inboundQty; + + const createdStorage = await ctx.model.Storage.create({ + warehouse_id: warehouseId, + store_id: storeId, + space_id: spaceId, + stock_id: stockId, + batch_no: effectiveBatchNo, + inventory_type: inventoryType, + quantity: inboundQty, + locked_quantity: 0, + available_quantity: inboundQty, + inbound_time: new Date(), + inbound_order_no: eo.entry_order_code, + receiving_id: rdReceivingId, + entry_order_id: eo.id, + supplier_id: null, + supplier_batch_no: null, + production_date: rdProductionDate, + expiry_date: rdExpiryDate, + is_enabled: 1, + created_at: new Date(), + updated_at: new Date(), + }, { transaction }); + storageId = createdStorage.id; + } + + // 写入库位维度库存流水 + await ctx.model.StorageTransaction.create({ + transaction_type: 'INBOUND', + warehouse_id: warehouseId, + store_id: storeId, + stock_id: stockId, + storage_id: storageId, + space_id: spaceId, + quantity: inboundQty, + before_quantity: storageBeforeQty, + after_quantity: storageAfterQty, + batch_no: effectiveBatchNo, + inventory_type: inventoryType, + order_type: 'entry_order', + order_no: eo.entry_order_code, + order_id: eo.id, + operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), + operator_name: ctx.user?.employees_name || '', + remark: '导入/PDA直接入库提交', + created_at: new Date(), + }, { transaction }); + } + + // 将 pending 绑定升级为 committed + if (pendingBindings.length > 0) { + await ctx.model.EntryReceivingBinding.update( + { status: 'committed', updated_at: new Date() }, + { where: { id: pendingBindings.map(b => b.id) }, transaction } + ); + } + + // 回写收货单和收货明细的入库状态 + await this._syncReceivingStorageStatus({ entryItemIds, transaction }); + + // 更新入库单状态为 COMPLETED + await eo.update({ + order_status: 'COMPLETED', + sync_status: 'SUCCESS', + sync_message: JSON.stringify({ + completedAt: new Date(), + totalQuantity: Object.values(stockSummary).reduce((s, q) => s + q, 0), + itemCount: processedStockIds.size, + source: 'direct_inbound', + }), updated_at: new Date(), - }, { - where: { id: storageRecord.id }, + }, { transaction }); + + // 记录操作日志(事务内) + const totalQty = Object.values(stockSummary).reduce((s, q) => s + q, 0); + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'entry_order', + businessId: eo.id, + operationCode: 'DIRECT_INBOUND_COMMIT', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: eo.warehouse_id, + message: `导入/PDA入库提交完成,共 ${processedStockIds.size} 种商品,总数量 ${totalQty}`, + }, transaction, }); - } else { - await ctx.model.Storage.create({ - warehouse_id: warehouseId, - store_id: storeId, - space_id: spaceId, - stock_id: stockId, - batch_no: batchNo, - inventory_type: inventoryType, - quantity: inboundQty, - locked_quantity: 0, - available_quantity: inboundQty, - inbound_time: new Date(), - inbound_order_no: entryOrder.entry_order_code, - receiving_id: null, - entry_order_id: entryOrder.id, - supplier_id: null, - supplier_batch_no: null, - is_enabled: 1, - created_at: new Date(), - updated_at: new Date(), - }, { transaction }); + + await transaction.commit(); + } catch (error) { + if (transaction && typeof transaction.rollback === 'function') { + await transaction.rollback(); + } + throw error; } - } - - // 更新入库单状态为 COMPLETED - await entryOrder.update({ - order_status: 'COMPLETED', - sync_status: 'SUCCESS', - sync_message: JSON.stringify({ - completedAt: new Date(), - totalQuantity: Object.values(stockSummary).reduce((s, q) => s + q, 0), - itemCount: processedStockIds.size, - source: 'direct_inbound', - }), - updated_at: new Date(), - }, { transaction }); - - // 记录操作日志(事务内) - const totalQty = Object.values(stockSummary).reduce((s, q) => s + q, 0); - await ctx.service.systems.operationLog.createOperationLog({ - businessType: 'entry_order', - businessId: entryOrder.id, - operationCode: 'DIRECT_INBOUND_COMMIT', - operator: { - id: ctx.user?.employees_id || ctx.user?.id, - name: ctx.user?.employees_name || '', - }, - extras: { - warehouseId: entryOrder.warehouse_id, - message: `导入/PDA入库提交完成,共 ${processedStockIds.size} 种商品,总数量 ${totalQty}`, - }, - transaction, - }); - - await transaction.commit(); - } catch (error) { - if (transaction && typeof transaction.rollback === 'function') { - await transaction.rollback(); - } - throw error; - } - - // 事务外:异步触发奇门/API 回传 - setImmediate(() => { - this._sendCallback(entryOrder).catch(err => { - ctx.logger.error(`[InboundDirectLog] 回传异常 entryOrderId=${entryOrder.id}: ${err.message}`, err.stack); - }); + }, }); + if (!syncResult.success) { + ctx.logger.warn(`[InboundDirectLog] commit 同步失败 entryOrderId=${entryOrder.id}: ${syncResult.message}`); + return { + code: 500, + message: syncResult.message, + data: { + id: entryOrder.id, + entry_order_code: entryOrder.entry_order_code, + sync_status: 'FAILED', + }, + }; + } + return { code: 200, message: '入库完成', @@ -707,110 +1085,16 @@ class InboundDirectLogService extends Service { }; } - /** - * 根据入库单来源异步回传(奇门 / OpenAPI)。 - * @param {Object} entryOrder 入库单实例 - * @return {Promise} - */ - async _sendCallback(entryOrder) { - const { ctx } = this; - const sourceType = String(entryOrder.source_type || '').toUpperCase(); - - ctx.logger.info( - `[InboundDirectLog] 准备回传 entryOrderId=${entryOrder.id} sourceType=${sourceType}` - ); - - try { - const items = await ctx.model.EntryItems.findAll({ - where: { order_id: entryOrder.id }, - attributes: [ 'item_code', 'item_id', 'count', 'inventory_type', 'owner_code', 'received_quantity' ], - raw: true, - }); - - if (!items || items.length === 0) { - ctx.logger.warn(`[InboundDirectLog] 回传:入库单无明细 entryOrderId=${entryOrder.id}`); - return; - } - - const orderLines = items.map((item, index) => ({ - orderLineNo: index + 1, - ownerCode: item.owner_code || '', - itemCode: item.item_code || '', - itemId: item.item_id || '', - inventoryType: item.inventory_type || 'ZP', - planQty: item.count || 0, - actualQty: item.received_quantity || 0, - })); - - if (sourceType === 'QM') { - await this._sendQimenCallback(entryOrder, orderLines); - } else if (sourceType === 'API') { - await this._sendOpenApiCallback(entryOrder); - } else { - ctx.logger.info(`[InboundDirectLog] 来源类型 ${sourceType} 不支持回传`); - } - } catch (error) { - ctx.logger.error(`[InboundDirectLog] _sendCallback 异常: ${error.message}`, error.stack); - } - } - - /** - * 奇门回传:调用 taobao.qimen.entryorder.confirm。 - * @param {Object} entryOrder 入库单 - * @param {Array} orderLines 明细行 - * @return {Promise} - */ - async _sendQimenCallback(entryOrder, orderLines) { - const { ctx, app } = this; - - try { - const queryData = { - request: { - entryOrder: { - entryOrderCode: entryOrder.entry_order_code, - ownerCode: entryOrder.qimen_owner_code || '', - warehouseCode: entryOrder.qimen_warehouse_code || '', - entryOrderId: entryOrder.id, - entryOrderType: entryOrder.order_type, - outBizCode: `DIRECT_INBOUND_${Date.now()}`, - confirmType: 0, - status: 'FULFILLED', - freight: 0, - operateTime: app.formatDate(new Date()), - remark: '导入/PDA直接入库提交', - }, - orderLines, - }, - }; - - const result = await app.qimenClient.send( - 'taobao.qimen.entryorder.confirm', - entryOrder.qimen_owner_code, - queryData, - { ctx } - ); - - const qimenResult = result && result.xmlArray && result.xmlArray.response; - if (qimenResult && String(qimenResult.flag) === 'success') { - ctx.logger.info(`[InboundDirectLog] 奇门回传成功 entryOrderId=${entryOrder.id}`); - } else { - ctx.logger.warn( - `[InboundDirectLog] 奇门回传失败 entryOrderId=${entryOrder.id} ` + - `message=${qimenResult?.message || '未知错误'}` - ); - } - } catch (error) { - ctx.logger.error(`[InboundDirectLog] 奇门回传异常: ${error.message}`, error.stack); - } - } - /** * OpenAPI 回传:查询 ApiApp 回调地址并 POST 回传。 * @param {Object} entryOrder 入库单 - * @return {Promise} + * @param {Object} [options] 可选配置 + * @param {boolean} [options.throwOnError=false] 失败时是否向外抛出异常 + * @return {Promise} 返回回传结果 { success, error?, statusCode?, body? },异常时返回 null */ - async _sendOpenApiCallback(entryOrder) { + async _sendOpenApiCallback(entryOrder, options = {}) { const { ctx, app } = this; + const { throwOnError = false } = options; try { const storeWarehouse = await ctx.model.StoreWarehouse.findOne({ @@ -824,11 +1108,13 @@ class InboundDirectLogService extends Service { }); if (!storeWarehouse) { - ctx.logger.warn( - '[InboundDirectLog] OpenAPI回传:未找到授权关系 ' + - `entryOrderId=${entryOrder.id}` - ); - return; + const warnMsg = `[InboundDirectLog] OpenAPI回传:未找到授权关系 entryOrderId=${entryOrder.id}`; + ctx.logger.warn(warnMsg); + console.log('[quickInbound] _sendOpenApiCallback 最终返回:', { success: false, error: '未找到授权关系' }); + if (throwOnError) { + throw new Error(warnMsg); + } + return null; } const apiApp = await ctx.model.ApiApp.findOne({ @@ -847,11 +1133,13 @@ class InboundDirectLogService extends Service { }); if (!apiApp || !apiApp.callback_url) { - ctx.logger.warn( - '[InboundDirectLog] OpenAPI回传:未找到有效ApiApp配置 ' + - `entryOrderId=${entryOrder.id}` - ); - return; + const warnMsg = `[InboundDirectLog] OpenAPI回传:未找到有效ApiApp配置 entryOrderId=${entryOrder.id}`; + ctx.logger.warn(warnMsg); + console.log('[quickInbound] _sendOpenApiCallback 最终返回:', { success: false, error: '未找到ApiApp配置' }); + if (throwOnError) { + throw new Error(warnMsg); + } + return null; } const callbackData = { @@ -861,6 +1149,13 @@ class InboundDirectLogService extends Service { inboundType: 'direct', }; + console.log('[quickInbound] _sendOpenApiCallback 发送前:', { + entryOrderId: entryOrder.id, + callbackUrl: apiApp.callback_url, + appKey: apiApp.self_app_key, + callbackData, + }); + const result = await ctx.service.openapi.callback.sendWithRetry({ callbackUrl: apiApp.callback_url, appKey: apiApp.self_app_key, @@ -873,19 +1168,376 @@ class InboundDirectLogService extends Service { }, }); + console.log('[quickInbound] _sendOpenApiCallback 响应:', { + entryOrderId: entryOrder.id, + success: result?.success, + statusCode: result?.statusCode, + error: result?.error, + body: typeof result?.body === 'string' ? result.body.substring(0, 500) : JSON.stringify(result?.body || {}).substring(0, 500), + }); + if (result.success) { ctx.logger.info( `[InboundDirectLog] OpenAPI回传成功 entryOrderId=${entryOrder.id} ` + `callbackUrl=${apiApp.callback_url}` ); } else { - ctx.logger.warn( - `[InboundDirectLog] OpenAPI回传失败 entryOrderId=${entryOrder.id} ` + - `error=${result.error}` - ); + const failMsg = `[InboundDirectLog] OpenAPI回传失败 entryOrderId=${entryOrder.id} error=${result.error}`; + ctx.logger.warn(failMsg); + if (throwOnError) { + throw new Error(failMsg); + } } + + console.log('[quickInbound] _sendOpenApiCallback 最终返回:', result); + return result; } catch (error) { ctx.logger.error(`[InboundDirectLog] OpenAPI回传异常: ${error.message}`, error.stack); + console.log('[quickInbound] _sendOpenApiCallback 最终返回 (异常):', { success: false, error: error.message }); + if (throwOnError) { + throw error; + } + return null; + } + } + + /** + * 奇门入库同步(统一入口)。 + * 先发奇门 entryorder.confirm 请求,成功才执行本地回调,失败则写操作日志并返回失败。 + * + * @param {Object} params 参数对象 + * @param {Object} params.entryOrder - 入库单完整对象(EntryOrder model instance) + * @param {Array} params.orderLines - 明细行数组 [{ orderLineNo, ownerCode, itemCode, itemId, inventoryType, planQty, actualQty }] + * @param {string} params.outBizCode - 外部业务编码(如 DIRECT_INBOUND_xxx) + * @param {string} params.remark - 备注(如 "导入/PDA直接入库提交") + * @param {boolean} [params.isFin=true] - 是否最终确认(confirmType: 0=最终, 1=部分) + * @param {Function} params.onSuccess - 同步成功后执行的回调(接收 entryOrder),在独立事务中执行,应包含业务写库 + operationLog(QUICK_INBOUND) + * @param {Object} params.operator - 操作人 { id, name },用于 operationLog + * @return {Promise} { success: boolean, message: string, data?: any } + */ + async qimenEntrySync(params) { + const { ctx, app } = this; + const { + entryOrder, + orderLines, + outBizCode, + remark, + isFin = true, + onSuccess, + operator, + } = params; + + console.log('[qimenEntrySync] 进入:', { + entryOrderId: entryOrder?.id, + entryOrderCode: entryOrder?.entry_order_code, + sourceType: entryOrder?.source_type, + orderLinesCount: orderLines?.length, + isFin, + }); + + // 1. 校验 + if (!orderLines || orderLines.length === 0) { + console.log('[qimenEntrySync] 最终判定: failure (行不能为空)'); + return { success: false, message: '行不能为空' }; + } + + // 2. 按来源类型分别处理 + const sourceType = String(entryOrder.source_type || '').toUpperCase(); + + if (sourceType !== 'QM' && sourceType !== 'API') { + const skipMsg = `来源类型 ${sourceType} 不支持回传`; + console.log(`[qimenEntrySync] 最终判定: 跳过 (${skipMsg})`); + ctx.logger.info(`[qimenEntrySync] ${skipMsg} entryOrderId=${entryOrder.id}`); + + // 不需要回传的来源类型,直接执行回调 + if (onSuccess) { + await onSuccess(entryOrder); + } + return { success: true, message: `无需同步,来源类型: ${sourceType}` }; + } + + // 3. 构造 queryData 并发请求(事务外) + if (sourceType === 'QM') { + const queryData = { + request: { + entryOrder: { + entryOrderCode: entryOrder.entry_order_code, + ownerCode: entryOrder.qimen_owner_code || '', + warehouseCode: entryOrder.qimen_warehouse_code || '', + entryOrderId: entryOrder.id, + entryOrderType: entryOrder.order_type, + outBizCode: outBizCode || `DIRECT_INBOUND_${Date.now()}`, + confirmType: isFin ? 0 : 1, + status: isFin ? 'FULFILLED' : 'PARTFULFILLED', + freight: 0, + operateTime: app.formatDate(new Date()), + remark: remark || '', + }, + orderLines, + }, + }; + + console.log('[qimenEntrySync] 奇门请求发送前:', { + entryOrderId: entryOrder.id, + api: 'taobao.qimen.entryorder.confirm', + ownerCode: entryOrder.qimen_owner_code, + queryData, + }); + + let qimenResult; + try { + const result = await app.qimenClient.send( + 'taobao.qimen.entryorder.confirm', + entryOrder.qimen_owner_code, + queryData, + { ctx } + ); + qimenResult = result?.xmlArray?.response; + } catch (err) { + qimenResult = { flag: 'error', code: '-1', message: err.message }; + } + + console.log('[qimenEntrySync] 奇门响应:', { + entryOrderId: entryOrder.id, + flag: qimenResult?.flag, + code: qimenResult?.code, + message: qimenResult?.message, + }); + + const isQimenSuccess = qimenResult && String(qimenResult.flag) === 'success'; + + if (!isQimenSuccess) { + const failMsg = qimenResult?.message || '奇门同步失败'; + console.log(`[qimenEntrySync] 最终判定: failure (${failMsg})`); + + const txn = await ctx.model.transaction(); + try { + await entryOrder.update({ + sync_status: 'FAILED', + sync_message: JSON.stringify({ + error: failMsg, + errorCode: 'QIMEN_FAILED', + errorTime: new Date().toISOString(), + source: 'qimenEntrySync', + }), + updated_at: new Date(), + }, { transaction: txn }); + + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'entry_order', + businessId: entryOrder.id, + operationCode: 'QUICK_INBOUND_FAILED', + operator: operator || {}, + extras: { warehouseId: entryOrder.warehouse_id, message: failMsg }, + transaction: txn, + }); + + await txn.commit(); + } catch (e) { + await txn.rollback(); + ctx.logger.error(`[qimenEntrySync] 失败日志写入异常: ${e.message}`); + } + + return { success: false, message: failMsg }; + } + + // 4. 成功:执行回调 + ctx.logger.info(`[qimenEntrySync] 奇门回传成功 entryOrderId=${entryOrder.id}`); + console.log('[qimenEntrySync] 最终判定: success'); + + if (onSuccess) { + await onSuccess(entryOrder); + } + + return { success: true, message: '同步成功' }; + } + + // API 来源:调用 OpenAPI 回传 + if (sourceType === 'API') { + console.log('[qimenEntrySync] OpenAPI 回传开始:', { + entryOrderId: entryOrder.id, + }); + + let apiResult; + try { + apiResult = await this._sendOpenApiCallback(entryOrder, { throwOnError: true }); + } catch (err) { + apiResult = { success: false, error: err.message }; + } + + console.log('[qimenEntrySync] OpenAPI 回传结果:', apiResult); + + const isApiSuccess = apiResult && apiResult.success === true; + + if (!isApiSuccess) { + const failMsg = apiResult?.error || 'API回传失败'; + console.log(`[qimenEntrySync] 最终判定: failure (${failMsg})`); + + const txn = await ctx.model.transaction(); + try { + await entryOrder.update({ + sync_status: 'FAILED', + sync_message: JSON.stringify({ + error: failMsg, + errorCode: 'API_FAILED', + errorTime: new Date().toISOString(), + source: 'qimenEntrySync', + }), + updated_at: new Date(), + }, { transaction: txn }); + + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'entry_order', + businessId: entryOrder.id, + operationCode: 'QUICK_INBOUND_FAILED', + operator: operator || {}, + extras: { warehouseId: entryOrder.warehouse_id, message: failMsg }, + transaction: txn, + }); + + await txn.commit(); + } catch (e) { + await txn.rollback(); + ctx.logger.error(`[qimenEntrySync] API失败日志写入异常: ${e.message}`); + } + + return { success: false, message: failMsg }; + } + + ctx.logger.info(`[qimenEntrySync] OpenAPI回传成功 entryOrderId=${entryOrder.id}`); + console.log('[qimenEntrySync] 最终判定: success (API)'); + + if (onSuccess) { + await onSuccess(entryOrder); + } + + return { success: true, message: '同步成功' }; + } + } + + /** + * 根据已提交(committed)的入库明细-收货明细绑定,回写收货单及收货明细的入库状态。 + * 在事务内执行,读取 committed 绑定并按 receiving_detail_id 汇总。 + * + * @param {Object} params 参数 + * @param {number[]} params.entryItemIds 当前入库单的所有明细 ID 列表 + * @param {Object} params.transaction Sequelize 事务对象 + * @return {Promise} + */ + async _syncReceivingStorageStatus({ entryItemIds, transaction }) { + const { ctx } = this; + + // 查询所有 committed 状态的绑定记录 + const committedBindings = await ctx.model.EntryReceivingBinding.findAll({ + where: { + entry_item_id: entryItemIds, + status: 'committed', + deleted_at: null, + }, + attributes: [ 'receiving_detail_id', 'allocated_quantity' ], + raw: true, + transaction, + }); + + if (!committedBindings || committedBindings.length === 0) { + return; + } + + // 按 receiving_detail_id 汇总 allocated_quantity + const detailQuantityMap = new Map(); + for (const b of committedBindings) { + const detailId = b.receiving_detail_id; + const qty = Number(b.allocated_quantity) || 0; + detailQuantityMap.set(detailId, (detailQuantityMap.get(detailId) || 0) + qty); + } + + const detailIds = [ ...detailQuantityMap.keys() ]; + + // 查询收货明细(含 actual_quantity 和 receiving_id) + const details = await ctx.model.ReceivingDetail.findAll({ + where: { id: detailIds }, + attributes: [ 'id', 'receiving_id', 'actual_quantity', 'stored_quantity', 'storage_status' ], + raw: true, + transaction, + }); + + if (!details.length) { + return; + } + + // 逐条计算并更新收货明细 + const receivingIdSet = new Set(); + for (const detail of details) { + const storedQuantity = detailQuantityMap.get(detail.id) || 0; + const actualQuantity = Number(detail.actual_quantity) || 0; + const storageStatus = storedQuantity >= actualQuantity + ? 'all' + : (storedQuantity > 0 ? 'partial' : 'none'); + + receivingIdSet.add(detail.receiving_id); + + await ctx.model.ReceivingDetail.update( + { + stored_quantity: storedQuantity, + storage_status: storageStatus, + updated_at: new Date(), + }, + { + where: { id: detail.id }, + transaction, + } + ); + } + + // 按收货单汇总,更新 wms_receiving.storage_status + const receivingIds = [ ...receivingIdSet ]; + if (receivingIds.length === 0) { + return; + } + + // 重新查询该收货单下所有明细的 storage_status,汇总主表状态 + const allDetails = await ctx.model.ReceivingDetail.findAll({ + where: { receiving_id: receivingIds }, + attributes: [ 'receiving_id', 'storage_status' ], + raw: true, + transaction, + group: [ 'receiving_id', 'storage_status' ], + }); + + // 按 receiving_id 分组 + const receivingDetailStatusMap = new Map(); + for (const d of allDetails) { + const rid = d.receiving_id; + if (!receivingDetailStatusMap.has(rid)) { + receivingDetailStatusMap.set(rid, new Set()); + } + receivingDetailStatusMap.get(rid).add(d.storage_status); + } + + for (const [ rid, statusSet ] of receivingDetailStatusMap) { + let receivingStorageStatus = 'none'; + if (statusSet.has('all') && statusSet.has('partial')) { + receivingStorageStatus = 'partial'; + } else if (statusSet.has('all')) { + if (statusSet.has('none') || statusSet.has('waiting')) { + receivingStorageStatus = 'partial'; + } else { + receivingStorageStatus = 'all'; + } + } else if (statusSet.has('partial')) { + receivingStorageStatus = 'partial'; + } + + await ctx.model.Receiving.update( + { + storage_status: receivingStorageStatus, + updated_at: new Date(), + }, + { + where: { id: rid }, + transaction, + } + ); } } } diff --git a/app/service/systems/operation_log.js b/app/service/systems/operation_log.js index 0dbdabe..923d2d0 100644 --- a/app/service/systems/operation_log.js +++ b/app/service/systems/operation_log.js @@ -306,6 +306,19 @@ class operationLogService extends Service { return await this.queryLogsByBusinessType(query, 'receiving'); } + /** + * 查询入库单操作日志。 + * @param {Object} query 查询参数。 + * @param {string|number} query.id 入库单ID。 + * @param {string|number} query.warehouseId 仓库ID。 + * @param {number} [query.page=1] 页码。 + * @param {number} [query.pageSize=20] 每页数量。 + * @return {Promise<{list: Object[], pagination: Object}>} 分页结果。 + */ + async queryEntryOrderLogs(query = {}) { + return await this.queryLogsByBusinessType(query, 'entry_order'); + } + async getMessageDetail(data) { const { id, type } = data; const { ctx } = this; diff --git a/app/service/systems/order_async.js b/app/service/systems/order_async.js index ac6c97e..1175b4e 100644 --- a/app/service/systems/order_async.js +++ b/app/service/systems/order_async.js @@ -479,12 +479,19 @@ async function finalizeSuccessfulQimenSyncInternal(service, orderModel, orderIte id: orderId, warehouse_id: warehouseId, }, - attributes: [ 'id', 'delivery_order_code', 'order_type', 'source_order_codes' ], + attributes: [ 'id', 'delivery_order_code', 'order_type', 'source_order_codes', 'sync_status' ], + lock: transaction.LOCK.UPDATE, raw: true, transaction, }); } + // 防重:如果订单已完成同步,跳过本次出库扣减 + if (resolvedOrderRow && String(resolvedOrderRow.sync_status || '').trim() === 'fin') { + service.ctx.logger.info(`[order_async] 订单已完成同步,跳过重复出库 orderId=${orderId}`); + return; + } + const outboundMetaOrderId = Number(resolvedOrderRow && resolvedOrderRow.id) || Number(orderId) || null; const outboundMetaOrderNo = String(resolvedOrderRow && resolvedOrderRow.delivery_order_code || '').trim() || null; const freshOrderItems = await orderItemsModel.findAll({ @@ -543,6 +550,23 @@ async function processLocalChannelOrderInternal(service, createChannel, orderMod try { await runTransactionWithLockRetryInternal(service, 'processLocalChannelOrder', async transaction => { + // 防重:SELECT FOR UPDATE 锁定订单行并检查 sync_status,防止重复出库 + const lockedOrderRow = await orderModel.findOne({ + where: { + id: orderId, + warehouse_id: warehouseId, + }, + attributes: [ 'id', 'sync_status' ], + lock: transaction.LOCK.UPDATE, + raw: true, + transaction, + }); + + if (lockedOrderRow && String(lockedOrderRow.sync_status || '').trim() === 'fin') { + service.ctx.logger.info(`[order_async] 订单已完成同步,跳过重复出库 orderId=${orderId}`); + return; + } + const freshOrderItems = await orderItemsModel.findAll({ where: { order_id: orderId, diff --git a/app/service/systems/order_auto_outbound.js b/app/service/systems/order_auto_outbound.js index 3c829d9..0b1dd68 100644 --- a/app/service/systems/order_auto_outbound.js +++ b/app/service/systems/order_auto_outbound.js @@ -7,6 +7,7 @@ const OUTBOUND_STATUS = 'fin'; const OUTBOUND_STEP = 4; const ORDER_STATUS_FINISHED = 'finished'; const MAX_BATCH_SIZE = 500; +const STORAGE_STATUS_FIN = 'fin'; /** * 订单自动化出库服务。 @@ -119,6 +120,7 @@ class OrderAutoOutboundService extends MainService { status: { [Op.notIn]: [ 'cancel', 'error', 'finished' ], }, + storage_status: STORAGE_STATUS_FIN, }; if (rules.require_recheck) { diff --git a/app/service/systems/order_print.js b/app/service/systems/order_print.js index e894bb1..f9f52b4 100644 --- a/app/service/systems/order_print.js +++ b/app/service/systems/order_print.js @@ -424,7 +424,7 @@ class OrderPrintSystemService extends OrderBaseService { } // 合并 barcodes 数组(Set 去重) if (item.barcodes && item.barcodes.length > 0) { - const merged = new Set([...(existing.barcodes || []), ...item.barcodes]); + const merged = new Set([ ...(existing.barcodes || []), ...item.barcodes ]); existing.barcodes = Array.from(merged); } } else { @@ -1516,7 +1516,7 @@ class OrderPrintSystemService extends OrderBaseService { if (Array.isArray(dispatchRows) && dispatchRows.length > 0) { // 合并 current 表与 dispatch 表结果,按 wave_id、id 升序排列 - const mergedRows = [...currentRows, ...dispatchRows].sort((a, b) => { + const mergedRows = [ ...currentRows, ...dispatchRows ].sort((a, b) => { const waveDiff = (a.wave_id || 0) - (b.wave_id || 0); if (waveDiff !== 0) return waveDiff; return (a.id || 0) - (b.id || 0); @@ -1546,7 +1546,7 @@ class OrderPrintSystemService extends OrderBaseService { * 返回 business_key=1 的主运单,按 order_id、business_key、id 升序排列。 * * @param {number[]} orderIds 订单 ID 列表。 - * @returns {Promise>} 匹配的运单记录数组,字段包含 id、order_id、business_key、waybill_code、 + * @return {Promise>} 匹配的运单记录数组,字段包含 id、order_id、business_key、waybill_code、 * logistics_code、logistics_name、logistics_interface_id、logistics_interface_name、platform_code、 * warehouse_id、printinfo、signature、encryptprintinfo、ver。 */ @@ -2682,8 +2682,8 @@ ${waveFilterSql} is_active: 1, delete_at: null, }, - order: [['bind_count', 'DESC']], - attributes: ['package_material_name'], + order: [[ 'bind_count', 'DESC' ]], + attributes: [ 'package_material_name' ], raw: true, }); if (topMatch && topMatch.package_material_name) { @@ -2707,7 +2707,7 @@ ${waveFilterSql} let subjectConfig = {}; if (warehouseId > 0) { const storeRow = await this.ctx.model.Store.findByPk(warehouseId, { - attributes: ['subject_config'], + attributes: [ 'subject_config' ], raw: true, }); if (storeRow && storeRow.subject_config) { diff --git a/app/service/systems/order_storage_allocation.js b/app/service/systems/order_storage_allocation.js index 5197b13..e03e5a3 100644 --- a/app/service/systems/order_storage_allocation.js +++ b/app/service/systems/order_storage_allocation.js @@ -837,6 +837,10 @@ class OrderStorageAllocationService extends MainService { const totalCount = pendingOrderIds.length; let processedCount = 0; + // 按订单维度跟踪已锁定的库存记录,用于缺货订单的原子回滚。 + // Map> + const orderLockRecords = new Map(); + // 对于 storage_status='error' 的重分配订单,先清理旧的 picking 记录并释放已锁定的库存 if (errorRetryOrderIds.length > 0) { writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 检测到 error 重试订单,开始清理旧数据', { @@ -1108,6 +1112,19 @@ class OrderStorageAllocationService extends MainService { storageRow.id, allocationQuantity, { transaction } ); + // 回退内存计数器:storageRow 的 available_quantity 和 locked_quantity + storageRow.available_quantity = currentAvailable; + storageRow.locked_quantity = toNumber(storageRow.locked_quantity, 0) - allocationQuantity; + + // 回退 remainingQuantity:未分配成功的数量加回去 + remainingQuantity += allocationQuantity; + + // 回退 allocatedQuantityForItem + allocatedQuantityForItem -= allocationQuantity; + + // 回退 allocatedQuantityForOrder + allocatedQuantityForOrder -= allocationQuantity; + // 回退 storageAllocationMap 中的累加值 const prevStorageQty = storageAllocationMap.get(storageRow.id) || 0; const newStorageQty = prevStorageQty - allocationQuantity; @@ -1117,17 +1134,29 @@ class OrderStorageAllocationService extends MainService { storageAllocationMap.set(storageRow.id, newStorageQty); } - writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 库位无效,回退库存主表锁定累加', { + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 库位无效,回退库存主表锁定累加及内存计数器', { orderId, storageId: storageRow.id, allocationQuantity, prevStorageQty, newStorageQty, + rollback: { + remainingQuantity, + allocatedQuantityForItem, + allocatedQuantityForOrder, + storageAvailableQuantity: storageRow.available_quantity, + storageLockedQuantity: storageRow.locked_quantity, + }, }); continue; } + // 记录本次成功锁定(lockQuantity + spaceId 有效),用于订单级别缺货回滚 + const orderLockList = orderLockRecords.get(orderId) || []; + orderLockList.push({ storageId: storageRow.id, quantity: allocationQuantity }); + orderLockRecords.set(orderId, orderLockList); + pickingRows.push({ order_id: orderId, order_item_id: toNumber(orderItem.id, 0), @@ -1143,6 +1172,12 @@ class OrderStorageAllocationService extends MainService { } if (remainingQuantity > 0) { + // 确保每个明细的缺货原因独立计算,避免候选库位为空时的诊断原因 + // 被错误地复用到候选库位非空但仍不足的明细上 + const finalShortageReason = candidateStorageRows.length === 0 + ? shortageReason + : (shortageReason || '库存不足'); + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 准备写入缺货条目', { orderId, orderItemId: toNumber(orderItem.id, 0), @@ -1151,12 +1186,14 @@ class OrderStorageAllocationService extends MainService { allocatedQuantity: allocatedQuantityForItem, remainingQuantity, candidateCount: candidateStorageRows.length, + shortageReason, + finalShortageReason, }); shortageItems.push({ stock_id: stockId, required_quantity: requiredQuantity, allocated_quantity: allocatedQuantityForItem, - reason: shortageReason, + reason: finalShortageReason, }); writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单明细存在缺货', { orderId, @@ -1166,6 +1203,7 @@ class OrderStorageAllocationService extends MainService { allocatedQuantityForItem, remainingQuantity, shortageReason, + finalShortageReason, }); } } @@ -1185,6 +1223,62 @@ class OrderStorageAllocationService extends MainService { finalShortageMessage, }); + // 单订单原子性分配:如果本订单有缺货,回滚该订单所有已成功锁定的库存, + // 并从 pickingRows 中移除该订单的所有记录,确保同一事务内该订单不留任何 locked_quantity。 + if (finalShortageMessage) { + const orderLocks = orderLockRecords.get(orderId); + if (Array.isArray(orderLocks) && orderLocks.length > 0) { + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 开始回滚订单已锁定库存', { + orderId, + orderLockCount: orderLocks.length, + orderLocks, + }); + + for (const lockRecord of orderLocks) { + await ctx.service.systems.storage.index.unlockQuantity( + lockRecord.storageId, lockRecord.quantity, { transaction } + ); + + // 回退 storageAllocationMap 中的累加值 + const prevStorageQty = storageAllocationMap.get(lockRecord.storageId) || 0; + const newStorageQty = prevStorageQty - lockRecord.quantity; + if (newStorageQty <= 0) { + storageAllocationMap.delete(lockRecord.storageId); + } else { + storageAllocationMap.set(lockRecord.storageId, newStorageQty); + } + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 已回滚单条库存锁定', { + orderId, + storageId: lockRecord.storageId, + quantity: lockRecord.quantity, + prevStorageQty, + newStorageQty, + }); + } + + // 回退订单级别的已分配数量计数器 + allocatedQuantityForOrder = 0; + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 订单锁定库存回滚完成,已重置 allocatedQuantityForOrder', { + orderId, + }); + } + + // 从 pickingRows 中移除该订单的所有记录。 + // 使用反向遍历 + splice 避免索引漂移,保持 pickingRows 顺序。 + for (let pickIdx = pickingRows.length - 1; pickIdx >= 0; pickIdx -= 1) { + if (pickingRows[pickIdx].order_id === orderId) { + pickingRows.splice(pickIdx, 1); + } + } + + writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 已从 pickingRows 移除缺货订单记录', { + orderId, + remainingPickingCount: pickingRows.length, + }); + } + const orderUpdateValues = finalShortageMessage ? { storage_status: STORAGE_STATUS_ERROR, @@ -1752,14 +1846,12 @@ class OrderStorageAllocationService extends MainService { let msg; if (isPending) msg = `同步到${channelNames}渠道`; else if (failed) { - const reasonMap = { 'express_unallocated': '快递未分配', 'sn_batch_forbidden': 'SN订单不支持批量' }; + const reasonMap = { express_unallocated: '快递未分配', sn_batch_forbidden: 'SN订单不支持批量' }; msg = `同步跳过:${reasonMap[failed.failed_reason] || failed.failed_reason || failed.message || '条件不满足'}`; - } - else if (skipped) { - const skipReasonMap = { 'already_synced': '已同步', 'not_found': '订单不存在' }; + } else if (skipped) { + const skipReasonMap = { already_synced: '已同步', not_found: '订单不存在' }; msg = `同步跳过:${skipReasonMap[skipped.skipped_reason] || skipped.skipped_reason || '已同步'}`; - } - else msg = `同步跳过`; + } else msg = '同步跳过'; return { businessType: 'order', businessId: `${orderId}`, diff --git a/app/service/systems/pick.js b/app/service/systems/pick.js index b71a08b..77301b5 100644 --- a/app/service/systems/pick.js +++ b/app/service/systems/pick.js @@ -57,6 +57,7 @@ class PickSystemService extends Service { * * @param {string} message 错误文案。 * @param {number} [code=400] 错误码。 + * @param {*} [data=null] 附加数据。 * @return {Error} 错误对象。 */ createBusinessError(message, code = 400, data = null) { diff --git a/app/service/systems/print/printData.js b/app/service/systems/print/printData.js index abb6e15..44d50bb 100644 --- a/app/service/systems/print/printData.js +++ b/app/service/systems/print/printData.js @@ -2,11 +2,6 @@ const Service = require('egg').Service; -const result = { - platform: null, - count: 0, - datas: [], -}; class PrintDataService extends Service { async getPrintData({ printType, orderId }) { diff --git a/app/service/systems/receiving_entry_match.js b/app/service/systems/receiving_entry_match.js index 6d41b74..37b1538 100644 --- a/app/service/systems/receiving_entry_match.js +++ b/app/service/systems/receiving_entry_match.js @@ -184,6 +184,172 @@ class ReceivingEntryMatchService extends Service { } } + /** + * 写入入库单与收货单的主表级绑定关系(仅主表绑定,不做明细分配)。 + * + * 流程: + * 1. 校验入库单状态 = CREATED + * 2. 校验每个收货单:存在、同仓库、同货主、已审核、未取消 + * 3. 逐条写入 EntryOrderReceiving.findOrCreate(主表绑定) + * + * @param {Object} data 请求参数 + * @param {number} data.entry_order_id 入库单 ID + * @param {number[]} data.receiving_ids 收货单 ID 列表 + * @param {number} [data.creator_id] 操作人 ID(可选) + * @return {Promise} 绑定结果,含 bound、skipped、summary + */ + async bindEntryOrderReceiving(data = {}) { + const { ctx } = this; + const { entry_order_id: entryOrderId, receiving_ids: receivingIds, creator_id: creatorId } = data || {}; + + // 参数校验 + if (!entryOrderId) { + throw new Error('entry_order_id 不能为空'); + } + if (!Array.isArray(receivingIds) || receivingIds.length === 0) { + throw new Error('receiving_ids 不能为空且必须为数组'); + } + + // ========== 第1步:查询入库单,校验状态 ========== + const entryOrder = await ctx.model.EntryOrder.findByPk(entryOrderId); + if (!entryOrder) { + throw new Error('入库单不存在'); + } + // 只允许 CREATED 状态 + if (entryOrder.order_status !== 'CREATED') { + throw new Error(`入库单状态不允许绑定,当前状态: ${entryOrder.order_status},仅 CREATED 状态可操作`); + } + + const warehouseId = entryOrder.warehouse_id; + + // ========== 第2步:校验每个收货单的有效性 ========== + const validatedReceivings = []; + const failedValidations = []; + + for (const receivingId of receivingIds) { + const receiving = await ctx.model.Receiving.findOne({ + where: { id: receivingId, is_deleted: false }, + attributes: [ 'id', 'receiving_number', 'warehouse_id', 'store_id', 'status', 'is_review' ], + }); + + if (!receiving) { + failedValidations.push({ + receiving_id: receivingId, + error_code: 'RECEIVING_NOT_FOUND', + message: '收货单不存在或已删除', + }); + continue; + } + + if (receiving.warehouse_id !== warehouseId) { + failedValidations.push({ + receiving_id: receivingId, + receiving_number: receiving.receiving_number, + error_code: 'WAREHOUSE_MISMATCH', + message: `收货单 ${receiving.receiving_number} 与入库单不属于同一仓库`, + }); + continue; + } + + if (receiving.store_id !== entryOrder.store_id) { + failedValidations.push({ + receiving_id: receivingId, + receiving_number: receiving.receiving_number, + error_code: 'OWNER_MISMATCH', + message: `收货单 ${receiving.receiving_number} 与入库单货主不一致`, + }); + continue; + } + + if (receiving.status === 'cancelled') { + failedValidations.push({ + receiving_id: receivingId, + receiving_number: receiving.receiving_number, + error_code: 'RECEIVING_CANCELLED', + message: `收货单 ${receiving.receiving_number} 已取消`, + }); + continue; + } + + if (!receiving.is_review) { + failedValidations.push({ + receiving_id: receivingId, + receiving_number: receiving.receiving_number, + error_code: 'RECEIVING_NOT_REVIEWED', + message: `收货单 ${receiving.receiving_number} 未审核`, + }); + continue; + } + + validatedReceivings.push(receiving); + } + + // 有校验失败的收货单 → 直接返回失败 + if (failedValidations.length > 0) { + ctx.logger.info( + `[ReceivingEntryMatch] bindEntryOrderReceiving 收货单校验失败 entryOrderId=${entryOrderId} failed=${failedValidations.length}` + ); + return { + bound: [], + skipped: [], + summary: { bound_count: 0, skipped_count: failedValidations.length }, + }; + } + + // ========== 第3步:逐条写入主表绑定关系 ========== + const boundResults = []; + const skippedResults = []; + + for (const receiving of validatedReceivings) { + try { + const [ , created ] = await ctx.model.EntryOrderReceiving.findOrCreate({ + where: { entry_order_id: entryOrderId, receiving_id: receiving.id }, + defaults: { entry_order_id: entryOrderId, receiving_id: receiving.id }, + }); + + if (created) { + ctx.logger.info( + `[ReceivingEntryMatch] 主表绑定成功 entryOrderId=${entryOrderId} receivingId=${receiving.id}` + ); + } else { + ctx.logger.info( + `[ReceivingEntryMatch] 主表绑定已存在,跳过 entryOrderId=${entryOrderId} receivingId=${receiving.id}` + ); + } + + boundResults.push({ + receiving_id: receiving.id, + receiving_number: receiving.receiving_number, + created, + }); + } catch (error) { + ctx.logger.error( + `[ReceivingEntryMatch] 主表绑定写入失败 entryOrderId=${entryOrderId} receivingId=${receiving.id}: ${error.message}`, + error.stack + ); + skippedResults.push({ + receiving_id: receiving.id, + receiving_number: receiving.receiving_number, + error_code: 'BINDING_WRITE_FAILED', + message: `写入绑定失败: ${error.message}`, + }); + } + } + + ctx.logger.info( + `[ReceivingEntryMatch] bindEntryOrderReceiving 主表绑定完成 entryOrderId=${entryOrderId} bound=${boundResults.length} skipped=${skippedResults.length} creatorId=${creatorId || 'N/A'}` + ); + + return { + bound: boundResults, + skipped: skippedResults, + summary: { + bound_count: boundResults.length, + skipped_count: skippedResults.length, + }, + }; + } + /** * 获取仓库近 3 天的收货单列表(优先从 Redis 缓存读取)。 * @@ -212,6 +378,7 @@ class ReceivingEntryMatchService extends Service { where: { warehouse_id: warehouseId, is_deleted: false, + is_review: 1, status: [ 'receiving', 'completed' ], created_at: { [app.Sequelize.Op.gte]: threeDaysAgo }, }, @@ -288,7 +455,7 @@ class ReceivingEntryMatchService extends Service { // 如果缓存的收货单没有 details(可能为空),重新加载 if (!matched.details || matched.details.length === 0) { const fullOrder = await ctx.model.Receiving.findOne({ - where: { id: matched.id, warehouse_id: warehouseId }, + where: { id: matched.id, warehouse_id: warehouseId, is_deleted: false, is_review: 1 }, attributes: [ 'id', 'receiving_number', 'status', 'storage_status' ], include: [{ model: ctx.model.ReceivingDetail, @@ -746,177 +913,247 @@ class ReceivingEntryMatchService extends Service { } /** - * 批量绑定入库单明细与收货单明细。 - * 依次校验入库单状态、商品匹配关系、可用数量,事务写入绑定并确保主级绑定存在。 - * @param {Object} data 请求参数 - * @param {number} data.entry_order_id 入库单ID - * @param {Array} data.bindings 绑定列表 - * @param {number} data.bindings[].entry_item_id 入库单明细ID - * @param {number} data.bindings[].receiving_detail_id 收货单明细ID - * @param {number} data.bindings[].allocated_quantity 分配数量 - * @return {Promise} { success: [...], failed: [...], success_count, failed_count } + * 内部公共方法:在事务中提交单条入库明细-收货明细绑定。 + * 包含 FOR UPDATE 行锁、可用量二次校验、绑定写入、主表绑定确保。 + * 被 PDA 上架 addItem 流程调用,用于逐条写入明细绑定。 + * + * @param {Object} params 绑定参数 + * @param {number} params.entryItemId 入库单明细 ID + * @param {number} params.receivingDetailId 收货单明细 ID + * @param {number} params.qty 分配数量 + * @param {number} params.expectedSpId 期望的 system_product_id(用于匹配校验,可选) + * @param {number} params.entryOrderId 入库单 ID(用于确保主表绑定存在) + * @param {Object} params.transaction Sequelize 事务对象 + * @throws {Object} 结构化错误对象,包含 error_code、message、detail + * @return {Promise} */ + async _commitBinding({ entryItemId, receivingDetailId, qty, expectedSpId, entryOrderId, transaction } = {}) { + const { ctx } = this; + + // 1. FOR UPDATE 锁收货明细行 + const lockedDetail = await ctx.model.query( + `SELECT id, actual_quantity, receiving_id, system_product_id + FROM wms_receiving_detail + WHERE id = :rdId FOR UPDATE`, + { + replacements: { rdId: receivingDetailId }, + type: ctx.model.QueryTypes.SELECT, + transaction, + } + ); + if (!lockedDetail || lockedDetail.length === 0) { + throw { + error_code: 'RECEIVING_DETAIL_NOT_FOUND', + message: '收货明细不存在', + detail: { receiving_detail_id: receivingDetailId }, + }; + } + + // 2. 校验收货明细与入库商品是否匹配(system_product_id) + if (expectedSpId !== undefined && lockedDetail[0].system_product_id !== expectedSpId) { + throw { + error_code: 'RECEIVING_DETAIL_MISMATCH', + message: '收货明细与入库商品不匹配', + detail: { + entry_item_id: entryItemId, + receiving_detail_id: receivingDetailId, + expected_sp_id: expectedSpId, + actual_sp_id: lockedDetail[0].system_product_id, + }, + }; + } + + // 3. 查已 committed 的分配量 + const allocatedSum = await ctx.model.query( + `SELECT COALESCE(SUM(allocated_quantity), 0) AS total + FROM wms_entry_receiving_binding + WHERE receiving_detail_id = :rdId AND status = 'committed' AND deleted_at IS NULL`, + { + replacements: { rdId: receivingDetailId }, + type: ctx.model.QueryTypes.SELECT, + transaction, + } + ); + const availableQty = lockedDetail[0].actual_quantity - Number(allocatedSum[0]?.total || 0); + if (qty > availableQty) { + throw { + error_code: 'INSUFFICIENT_AVAILABLE_QUANTITY', + message: '分配数量超出可用量', + detail: { available_quantity: availableQty, requested_quantity: qty }, + }; + } + + // 4. 写入明细绑定 + await ctx.model.EntryReceivingBinding.create({ + entry_item_id: entryItemId, + receiving_detail_id: receivingDetailId, + allocated_quantity: qty, + status: 'committed', + creator_id: ctx.currentUser?.id || 0, + }, { transaction }); + + // 5. 确保主级绑定存在 + await ctx.model.EntryOrderReceiving.findOrCreate({ + where: { entry_order_id: entryOrderId, receiving_id: lockedDetail[0].receiving_id }, + defaults: { entry_order_id: entryOrderId, receiving_id: lockedDetail[0].receiving_id }, + transaction, + }); + } + /** - * 批量绑定入库单明细与收货单明细。 - * 在事务中对每条绑定使用 FOR UPDATE 行锁防并发超卖,失败项返回结构化错误码。 + * 解除入库单与收货单的绑定关系。 + * + * 逻辑: + * 1. 校验入库单存在,状态必须是 PENDING 或 CREATED(COMPLETED / CANCELLED 不允许解绑) + * 2. 逐个收货单: + * a. 查 wms_entry_order_receiving 主表绑定是否存在(只查 deleted_at IS NULL) + * b. 查 wms_entry_receiving_binding 明细绑定是否存在(status='committed' 且 deleted_at IS NULL) + * c. 无明细绑定 → 只软删除主表绑定 + * d. 有明细绑定 → 事务中软删除明细绑定 + 软删除主表绑定 + * 3. 不回退入库单状态(PENDING 解绑后仍是 PENDING) * * @param {Object} data 请求参数 * @param {number} data.entry_order_id 入库单 ID - * @param {Array<{entry_item_id: number, receiving_detail_id: number, allocated_quantity: number}>} data.bindings 绑定列表 - * @return {Promise<{success: Array, failed: Array, success_count: number, failed_count: number}>} 绑定结果 + * @param {number[]} data.receiving_ids 要解除绑定的收货单 ID 列表 + * @return {Promise} { success: Array, failed: Array, success_count: number, failed_count: number } */ - async bindReceivingDetails(data = {}) { + async unbindEntryOrderReceiving(data = {}) { const { ctx } = this; - const { entry_order_id: entryOrderId, bindings = [] } = data || {}; + const { entry_order_id: entryOrderId, receiving_ids: receivingIds } = data || {}; - if (!entryOrderId || !Array.isArray(bindings) || bindings.length === 0) { - throw new Error('参数不完整'); + // 参数校验 + if (!entryOrderId) { + throw new Error('entry_order_id 不能为空'); + } + if (!Array.isArray(receivingIds) || receivingIds.length === 0) { + throw new Error('receiving_ids 不能为空且必须为数组'); } - // 1. 查询入库单,校验状态(必须是 PENDING 或 CREATED) + // ---------- 第1步:校验入库单存在且状态允许解绑 ---------- const entryOrder = await ctx.model.EntryOrder.findByPk(entryOrderId); - if (!entryOrder || ![ 'CREATED', 'PENDING' ].includes(entryOrder.order_status)) { - // 入库单状态不对 → 全部 bindings 标记为 ENTRY_ORDER_STATUS_INVALID - const allFailed = bindings.map(b => ({ - entry_item_id: b.entry_item_id, - receiving_detail_id: b.receiving_detail_id, - allocated_quantity: b.allocated_quantity, - error_code: 'ENTRY_ORDER_STATUS_INVALID', - message: '入库单状态不允许绑定', - detail: { order_status: entryOrder ? entryOrder.order_status : null }, - })); - return { success: [], failed: allFailed, success_count: 0, failed_count: allFailed.length }; + if (!entryOrder) { + return { + success: [], + failed: receivingIds.map(rid => ({ + receiving_id: rid, + error_code: 'ENTRY_ORDER_NOT_FOUND', + message: '入库单不存在', + })), + success_count: 0, + failed_count: receivingIds.length, + }; } + // 只允许 PENDING 或 CREATED 状态解绑(COMPLETED / CANCELLED 不允许) + if (![ 'CREATED', 'PENDING' ].includes(entryOrder.order_status)) { + return { + success: [], + failed: receivingIds.map(rid => ({ + receiving_id: rid, + error_code: 'ENTRY_ORDER_STATUS_INVALID', + message: `入库单状态不允许解绑,当前状态: ${entryOrder.order_status}`, + })), + success_count: 0, + failed_count: receivingIds.length, + }; + } + + // ---------- 第2步:逐个收货单处理解绑 ---------- const success = []; const failed = []; - for (const binding of bindings) { - const { entry_item_id: entryItemId, receiving_detail_id: receivingDetailId, allocated_quantity: qty } = binding; + for (const receivingId of receivingIds) { try { - // 2. 查询 entry_item 和对应的 stock_id - const entryItem = await ctx.model.EntryItems.findByPk(entryItemId); - if (!entryItem) { - throw { - error_code: 'ENTRY_ITEM_NOT_FOUND', - message: '入库明细不存在', - detail: { entry_item_id: entryItemId }, - }; - } - - // 3. 通过 stock_id → system_product_id 校验收货单明细匹配 - const sw = await ctx.model.StockWarehouse.findOne({ - where: { id: entryItem.stock_id, warehouse_id: entryOrder.warehouse_id }, - attributes: [ 'system_product_id' ], - raw: true, - }); - if (!sw || !sw.system_product_id) { - throw { - error_code: 'STOCK_NOT_FOUND', - message: '商品不存在', - detail: { stock_id: entryItem.stock_id }, - }; - } - - // 4. 事务:FOR UPDATE 锁行 → 查已分配量 → 写入绑定 - await ctx.model.transaction(async t => { - // 4a. 先锁收货明细行 - const lockedDetail = await ctx.model.query( - `SELECT id, actual_quantity, receiving_id, system_product_id - FROM wms_receiving_detail - WHERE id = :rdId FOR UPDATE`, - { - replacements: { rdId: receivingDetailId }, - type: ctx.model.QueryTypes.SELECT, - transaction: t, - } - ); - if (!lockedDetail || lockedDetail.length === 0) { - throw { - error_code: 'RECEIVING_DETAIL_NOT_FOUND', - message: '收货明细不存在', - detail: { receiving_detail_id: receivingDetailId }, - }; - } - - // 4b. 校验收货明细与入库商品是否匹配(system_product_id) - if (lockedDetail[0].system_product_id !== sw.system_product_id) { - throw { - error_code: 'RECEIVING_DETAIL_MISMATCH', - message: '收货明细与入库商品不匹配', - detail: { - entry_item_id: entryItemId, - receiving_detail_id: receivingDetailId, - expected_sp_id: sw.system_product_id, - actual_sp_id: lockedDetail[0].system_product_id, - }, - }; - } - - // 4c. 查已 committed 的分配量 - const allocatedSum = await ctx.model.query( - `SELECT COALESCE(SUM(allocated_quantity), 0) AS total - FROM wms_entry_receiving_binding - WHERE receiving_detail_id = :rdId AND status = 'committed' AND deleted_at IS NULL`, - { - replacements: { rdId: receivingDetailId }, - type: ctx.model.QueryTypes.SELECT, - transaction: t, - } - ); - const availableQty = lockedDetail[0].actual_quantity - Number(allocatedSum[0]?.total || 0); - if (qty > availableQty) { - throw { - error_code: 'INSUFFICIENT_AVAILABLE_QUANTITY', - message: '分配数量超出可用量', - detail: { available_quantity: availableQty, requested_quantity: qty }, - }; - } - - // 4d. 写入绑定 - await ctx.model.EntryReceivingBinding.create({ - entry_item_id: entryItemId, - receiving_detail_id: receivingDetailId, - allocated_quantity: qty, - status: 'committed', - creator_id: ctx.currentUser?.id || 0, - }, { transaction: t }); - - // 确保主级绑定存在 - await ctx.model.EntryOrderReceiving.findOrCreate({ - where: { entry_order_id: entryOrderId, receiving_id: lockedDetail[0].receiving_id }, - defaults: { entry_order_id: entryOrderId, receiving_id: lockedDetail[0].receiving_id }, - transaction: t, - }); + // 2a. 查主表绑定是否存在 + const mainBinding = await ctx.model.EntryOrderReceiving.findOne({ + where: { + entry_order_id: entryOrderId, + receiving_id: receivingId, + deleted_at: null, + }, }); - success.push({ entry_item_id: entryItemId, receiving_detail_id: receivingDetailId, allocated_quantity: qty }); - } catch (err) { - // 结构化错误对象或普通 Error 统一转为 failed 项 - if (err.error_code) { + if (!mainBinding) { failed.push({ - entry_item_id: entryItemId, - receiving_detail_id: receivingDetailId, - allocated_quantity: qty, - error_code: err.error_code, - message: err.message, - detail: err.detail || {}, + receiving_id: receivingId, + error_code: 'BINDING_NOT_FOUND', + message: '主表绑定不存在', + }); + continue; + } + + // 2b. 查明细绑定是否存在 + const detailBindings = await ctx.model.EntryReceivingBinding.findAll({ + where: { + status: 'committed', + deleted_at: null, + }, + include: [{ + model: ctx.model.ReceivingDetail, + as: 'receivingDetail', + required: true, + attributes: [], + where: { receiving_id: receivingId }, + }], + attributes: [ 'id', 'receiving_detail_id', 'allocated_quantity' ], + }); + + if (detailBindings.length === 0) { + // 2c. 无明细绑定 → 只软删除主表绑定 + await mainBinding.destroy(); + ctx.logger.info( + `[ReceivingEntryMatch] 解绑成功(仅主表) entryOrderId=${entryOrderId} receivingId=${receivingId}` + ); + success.push({ + receiving_id: receivingId, + released_detail_count: 0, + message: '已解除主表绑定(无明细绑定)', }); } else { - failed.push({ - entry_item_id: entryItemId, - receiving_detail_id: receivingDetailId, - allocated_quantity: qty, - error_code: 'INTERNAL_ERROR', - message: err.message || '未知错误', - detail: {}, + // 2d. 有明细绑定 → 事务:软删除明细绑定 + 软删除主表绑定 + const detailIds = detailBindings.map(d => d.receiving_detail_id); + + await ctx.model.transaction(async t => { + // 软删除所有明细绑定 + for (const binding of detailBindings) { + await binding.destroy({ transaction: t }); + } + + // 软删除主表绑定 + await mainBinding.destroy({ transaction: t }); + }); + + ctx.logger.info( + `[ReceivingEntryMatch] 解绑成功(含明细) entryOrderId=${entryOrderId} ` + + `receivingId=${receivingId} detailCount=${detailBindings.length} ` + + `detailIds=[${detailIds.join(',')}]` + ); + + success.push({ + receiving_id: receivingId, + released_detail_ids: detailIds, + released_detail_count: detailBindings.length, + message: '已解除主表及明细绑定', }); } + } catch (error) { + ctx.logger.error( + `[ReceivingEntryMatch] 解绑异常 entryOrderId=${entryOrderId} ` + + `receivingId=${receivingId}: ${error.message}`, + error.stack + ); + failed.push({ + receiving_id: receivingId, + error_code: 'UNBIND_ERROR', + message: `解绑过程异常: ${error.message}`, + }); } } return { success, failed, success_count: success.length, failed_count: failed.length }; } + + } module.exports = ReceivingEntryMatchService; diff --git a/app/service/systems/shops.js b/app/service/systems/shops.js index 9f59a94..110cdd8 100644 --- a/app/service/systems/shops.js +++ b/app/service/systems/shops.js @@ -675,10 +675,9 @@ class ShopsService extends Service { * @return {Promise} 会话信息 */ async getAuthorizeSessionKey(data = {}) { - const { ctx, service } = this; + const { ctx } = this; const authUrl = 'http://61.160.223.183:3012/api'; - const warehouseId = this.getCurrentWarehouseId(); const shopId = data.id !== undefined ? data.id : (data.shop_id !== undefined ? data.shop_id : data.shopId); const callbackUrl = this.normalizeText( data.callbackurl !== undefined ? data.callbackurl : data.callback_url, diff --git a/app/service/systems/stock_warehouse.js b/app/service/systems/stock_warehouse.js index b3378ba..dad60e4 100644 --- a/app/service/systems/stock_warehouse.js +++ b/app/service/systems/stock_warehouse.js @@ -31,7 +31,7 @@ class StockWarehouseService extends Service { * @param {Object} [options={}] 选项 * @param {number} [options.warehouseId] 仓库ID(优先使用 options.warehouseId,否则兜底 ctx.user.store_id) * @param {number} [options.cacheTTL=300] 缓存过期时间(秒) - * @return {Promise}>>} 商品详情列表 + * @return {Promise}>>} 商品详情列表 */ async getStockDetails(stockIds, options = {}) { const { ctx, app } = this; @@ -99,6 +99,7 @@ class StockWarehouseService extends Service { attributes: [ 'file_url' ], required: false, }], + order: [[ 'display_order', 'ASC' ]], raw: true, }), ]); @@ -121,8 +122,11 @@ class StockWarehouseService extends Service { for (const row of imageRows) { const sid = Number(row.business_id); if (!imageUrlMap.has(sid)) { - const url = (row['file.file_url'] && String(row['file.file_url']).trim()) || ''; - imageUrlMap.set(sid, url); + imageUrlMap.set(sid, []); + } + const url = (row['file.file_url'] && String(row['file.file_url']).trim()) || ''; + if (url) { + imageUrlMap.get(sid).push(url); } } @@ -141,7 +145,7 @@ class StockWarehouseService extends Service { store_id: row.store_id != null ? Number(row.store_id) : 0, packing_requirements: row.packing_requirements || '', stock_unit: row.stock_unit || '', - image_url: imageUrlMap.get(row.id) || '', + image_url: imageUrlMap.get(row.id) || [], barcodes: barcodeMap.get(row.id) || [], }; dbResults.set(row.id, detail); @@ -176,6 +180,13 @@ class StockWarehouseService extends Service { const cached = cacheHits.get(stockId); // 空标记(防穿透缓存)跳过 if (cached !== null && cached !== undefined) { + // 兼容旧缓存格式:image_url 可能是字符串,统一转为数组 + if (cached && typeof cached.image_url === 'string') { + cached.image_url = cached.image_url ? [ cached.image_url ] : []; + } + if (cached && !Array.isArray(cached.image_url)) { + cached.image_url = []; + } result.push(cached); } } else if (dbResults.has(stockId)) { diff --git a/app/service/systems/storage/entry.js b/app/service/systems/storage/entry.js index 0f6a91b..2c74639 100644 --- a/app/service/systems/storage/entry.js +++ b/app/service/systems/storage/entry.js @@ -93,7 +93,8 @@ class EntryService extends Service { * @return {Object|null} Sequelize.where 条件,无法构建时返回 null */ buildEntryStockTransactionExistsCondition(fieldName, condition = {}) { - const { app } = this; + const { app, ctx } = this; + const db = ctx.model.sequelize; const values = this.normalizeFilterValues(condition) .map(item => (typeof item === 'string' ? item.trim() : item)) .filter(item => item !== '' && item !== undefined && item !== null); @@ -104,13 +105,13 @@ class EntryService extends Service { const operator = String(condition.operator || 'eq').trim().toLowerCase(); const escapedColumn = `st.${fieldName}`; - const escapedValues = values.map(item => app.Sequelize.escape(item)); + const escapedValues = values.map(item => db.escape(item)); let valueClause = ''; if (operator === 'in') { valueClause = `${escapedColumn} IN (${escapedValues.join(',')})`; } else if (operator === 'like' || operator === 'contains') { - const likeClauses = values.map(item => `${escapedColumn} LIKE ${app.Sequelize.escape(`%${String(item)}%`)}`); + const likeClauses = values.map(item => `${escapedColumn} LIKE ${db.escape(`%${String(item)}%`)}`); valueClause = likeClauses.length === 1 ? likeClauses[0] : `(${likeClauses.join(' OR ')})`; } else { valueClause = `${escapedColumn} = ${escapedValues[0]}`; @@ -131,7 +132,42 @@ class EntryService extends Service { * @param {Object} normalizedWhere 标准化后的 where 条件 * @return {{where: Object, extraConditions: Array, errorMessage: string}} 预处理结果 */ - preprocessEntryListWhere(normalizedWhere = {}) { + /** + * 根据 hasReceiving 虚拟字段构建入库单 ID 筛选条件。 + * @param {boolean} hasReceiving true=已绑定,false=未绑定 + * @return {Promise} Sequelize where 条件,无需额外筛选时返回 null + */ + async buildHasReceivingCondition(hasReceiving) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + + const bindings = await ctx.model.EntryOrderReceiving.findAll({ + attributes: [[ app.Sequelize.fn('DISTINCT', app.Sequelize.col('entry_order_id')), 'entry_order_id' ]], + where: { deleted_at: null }, + raw: true, + }); + + const boundIds = bindings.map(item => item.entry_order_id); + + if (hasReceiving === true) { + if (boundIds.length === 0) { + return { id: { [Op.eq]: null } }; + } + return { id: { [Op.in]: boundIds } }; + } + + if (boundIds.length === 0) { + return null; + } + return { id: { [Op.notIn]: boundIds } }; + } + + /** + * 预处理入库单列表筛选条件,兼容历史别名并构建扩展筛选。 + * @param {Object} normalizedWhere 标准化后的 where 条件 + * @return {Promise<{where: Object, extraConditions: Array, errorMessage: string}>} 预处理结果 + */ + async preprocessEntryListWhere(normalizedWhere = {}) { const { ctx } = this; const whereForParse = normalizedWhere && typeof normalizedWhere === 'object' ? { ...normalizedWhere } @@ -161,6 +197,19 @@ class EntryService extends Service { } delete whereForParse.operator_id; + // 处理虚拟字段 hasReceiving:从 where 中剥离,构建绑定/未绑定筛选条件 + if (Object.prototype.hasOwnProperty.call(whereForParse, 'hasReceiving')) { + const rawHasReceiving = whereForParse.hasReceiving; + delete whereForParse.hasReceiving; + + if (rawHasReceiving === true || rawHasReceiving === false) { + const receivingCondition = await this.buildHasReceivingCondition(rawHasReceiving); + if (receivingCondition) { + extraConditions.push(receivingCondition); + } + } + } + if (Object.prototype.hasOwnProperty.call(whereForParse, 'expense_record')) { const hasExpenseRecordField = Boolean( ctx.model @@ -202,7 +251,6 @@ class EntryService extends Service { const { ctx, app } = this; const { Sequelize } = app; const { Op } = Sequelize; - const page = Math.max(Number(pageParams.page) || 1, 1); const pageSize = Math.max(Number(pageParams.pageSize) || 20, 1); @@ -234,7 +282,7 @@ class EntryService extends Service { where: parsedSourceWhere, extraConditions, errorMessage, - } = this.preprocessEntryListWhere(normalizedWhere); + } = await this.preprocessEntryListWhere(normalizedWhere); if (errorMessage) { return { @@ -309,15 +357,27 @@ class EntryService extends Service { const andConditions = [ baseWhere ]; if (quickWhereValue !== undefined && quickWhereValue !== null && String(quickWhereValue).trim() !== '') { const kw = String(quickWhereValue).trim(); - andConditions.push({ - [Op.or]: [ - { entry_order_code: { [Op.like]: `%${kw}%` } }, - { purchase_order_code: { [Op.like]: `%${kw}%` } }, - { supplier_name: { [Op.like]: `%${kw}%` } }, - { store_name: { [Op.like]: `%${kw}%` } }, - { warehouse_name: { [Op.like]: `%${kw}%` } }, - ], - }); + const receivingDetailId = Number(kw); + const orConditions = [ + { entry_order_code: { [Op.like]: `%${kw}%` } }, + { purchase_order_code: { [Op.like]: `%${kw}%` } }, + { supplier_name: { [Op.like]: `%${kw}%` } }, + { store_name: { [Op.like]: `%${kw}%` } }, + { warehouse_name: { [Op.like]: `%${kw}%` } }, + // 搜索收货单明细 ID(箱唛/托盘唛唯一编码,精确数字匹配);仅当 kw 是有效正数时追加 EXISTS + ...(Number.isFinite(receivingDetailId) && receivingDetailId > 0 ? [ + Sequelize.where(Sequelize.literal( + `EXISTS ( + SELECT 1 FROM wms_entry_order_receiving eor + JOIN wms_receiving_detail rd ON rd.receiving_id = eor.receiving_id + WHERE eor.entry_order_id = wms_entry_order.id + AND eor.deleted_at IS NULL + AND rd.id = ${receivingDetailId} + )` + ), 1), + ] : []), + ]; + andConditions.push({ [Op.or]: orConditions }); } const dynamicConditions = parsedResult.dynamicConditions || []; @@ -354,6 +414,44 @@ class EntryService extends Service { distinct: true, }); + // 批量查询收货单绑定信息 + const entryOrderIds = rows.map(row => row.id); + /** @type {Map>} */ + const receivingBindingsMap = new Map(); + if (entryOrderIds.length > 0) { + const allBindings = await ctx.model.EntryOrderReceiving.findAll({ + where: { entry_order_id: { [Op.in]: entryOrderIds }, deleted_at: null }, + include: [ + { + model: ctx.model.Receiving, + as: 'receiving', + attributes: [ 'id', 'receiving_number', 'status', 'storage_status', 'created_at' ], + required: false, + }, + ], + order: [[ 'id', 'ASC' ]], + }); + + for (const binding of allBindings) { + const eid = binding.entry_order_id; + if (!receivingBindingsMap.has(eid)) { + receivingBindingsMap.set(eid, []); + } + receivingBindingsMap.get(eid).push(binding); + } + } + + // 为每行附加收货单绑定信息 + const enrichedRows = rows.map(row => { + const rowJSON = row.toJSON ? row.toJSON() : row; + const bindings = receivingBindingsMap.get(row.id) || []; + return { + ...rowJSON, + receivingBindings: bindings, + hasReceiving: bindings.length > 0, + }; + }); + const statusRows = await ctx.model.EntryOrder.findAll({ attributes: [ 'order_status', @@ -383,7 +481,7 @@ class EntryService extends Service { code: 200, message: '查询成功', data: { - list: rows, + list: enrichedRows, pagination: { page, pageSize, @@ -610,7 +708,7 @@ class EntryService extends Service { COALESCE(SUM(erb.allocated_quantity), 0) AS allocated_quantity, rd.actual_quantity - COALESCE(SUM(erb.allocated_quantity), 0) AS available_quantity FROM wms_receiving_detail rd - INNER JOIN wms_receiving r ON r.id = rd.receiving_id AND r.deleted_at IS NULL + INNER JOIN wms_receiving r ON r.id = rd.receiving_id AND r.is_deleted = false LEFT JOIN wms_entry_receiving_binding erb ON erb.receiving_detail_id = rd.id AND erb.status = 'committed' @@ -740,7 +838,6 @@ class EntryService extends Service { } const orderIds = normalizedResult.ids || []; - const entryOrders = []; for (const orderId of orderIds) { const entryOrder = await this.getOwnedEntryOrderById(orderId); @@ -752,6 +849,15 @@ class EntryService extends Service { }; } + // 6b: sync_status=SUCCESS 不可取消 + if (entryOrder.sync_status === 'SUCCESS') { + return { + code: 400, + message: '入库单已完成回传,不可取消', + data: null, + }; + } + if (entryOrder.order_status === 'COMPLETED') { return { code: 400, @@ -760,107 +866,125 @@ class EntryService extends Service { }; } - entryOrders.push(entryOrder); - } - - const transaction = ctx.model && typeof ctx.model.transaction === 'function' - ? await ctx.model.transaction() - : null; - - try { - const updatedAt = new Date(); - - for (const entryOrder of entryOrders) { - await entryOrder.update({ - order_status: 'CANCELLED', - updated_at: updatedAt, - }, transaction ? { - transaction, - } : undefined); + if (entryOrder.order_status === 'CANCELLED') { + return { + code: 400, + message: '入库单已作废', + data: null, + }; } - if (transaction && typeof transaction.commit === 'function') { - await transaction.commit(); + // 6a: QM 来源需发送取消同步 + if (String(entryOrder.source_type) === 'QM') { + const entryItems = await ctx.model.EntryItems.findAll({ + where: { order_id: entryOrder.id }, + attributes: [ 'item_code', 'item_id', 'count', 'inventory_type', 'owner_code' ], + raw: true, + }); + + const orderLines = (entryItems || []).map((item, idx) => ({ + orderLineNo: idx + 1, + ownerCode: item.owner_code || '', + itemCode: item.item_code || '', + itemId: item.item_id || '', + inventoryType: item.inventory_type || 'ZP', + planQty: item.count || 0, + actualQty: 0, // 全部为 0,通知 ERP 关闭 + })); + + const syncResult = await ctx.service.systems.inboundDirectLog.qimenEntrySync({ + entryOrder, + orderLines, + outBizCode: `CANCEL_${Date.now()}`, + remark: '入库单取消', + operator: { + id: ctx.user?.employees_id || ctx.user?.id || '', + name: ctx.user?.employees_name || '', + }, + }); + + if (!syncResult.success) { + return { + code: 500, + message: `取消失败: ${syncResult.message}`, + data: null, + }; + } } - } catch (error) { - if (transaction && typeof transaction.rollback === 'function') { - await transaction.rollback(); - } - throw error; + + // 更新状态 + await entryOrder.update({ + order_status: 'CANCELLED', + updated_at: new Date(), + }); + + // 回退关联收货单的入库状态,避免死锁 + await this._rollbackReceivingStorageStatus(entryOrder.id); + + // 写操作日志 + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'entry_order', + businessId: entryOrder.id, + operationCode: 'ENTRY_ORDER_CANCEL', + operator: { + id: ctx.user?.employees_id || ctx.user?.id || '', + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: entryOrder.warehouse_id, + message: '入库单已取消', + }, + }); } return { code: 200, message: '作废成功', - data: { - [orderIds.length === 1 ? 'id' : 'ids']: orderIds.length === 1 ? entryOrders[0].id : orderIds, - }, + data: { ids: orderIds }, }; } /** - * 完成入库单。 - * @param {Object} data 请求体 - * @return {Promise} code/data/message 结构 + * 回退入库单关联收货单的入库状态(入库单作废时调用)。 + * 失败不阻塞主流程,仅打印日志。 + * @param {number} entryOrderId 入库单ID + * @return {Promise} */ - async completeEntry(data = {}) { + async _rollbackReceivingStorageStatus(entryOrderId) { const { ctx } = this; - const orderId = Number(data.id || 0); + try { + // 1. 查询关联的收货单ID列表 + const bindings = await ctx.model.EntryOrderReceiving.findAll({ + where: { entry_order_id: entryOrderId, deleted_at: null }, + attributes: [ 'receiving_id' ], + raw: true, + }); - if (!orderId) { - return { - code: 400, - message: 'id 必填', - data: null, - }; + const receivingIds = (bindings || [ ]).map(b => b.receiving_id).filter(Boolean); + if (receivingIds.length === 0) { + return; + } + + // 2. 回退收货单主表 storage_status → 'none' + await ctx.model.Receiving.update( + { storage_status: 'none', updated_at: new Date() }, + { where: { id: { [ctx.app.Sequelize.Op.in]: receivingIds } } } + ); + + // 3. 回退收货单明细 storage_status → 'none', stored_quantity → 0 + await ctx.model.ReceivingDetail.update( + { storage_status: 'none', stored_quantity: 0, updated_at: new Date() }, + { where: { receiving_id: { [ctx.app.Sequelize.Op.in]: receivingIds } } } + ); + + ctx.logger.info( + `[storage.entry.cancel] 入库单 ${entryOrderId} 作废,已回退收货单入库状态,receivingIds=[${receivingIds.join(',')}]` + ); + } catch (err) { + ctx.logger.error( + `[storage.entry.cancel] 回退收货单入库状态失败,entryOrderId=${entryOrderId},err=${err.message}` + ); } - - const entryOrder = await this.getOwnedEntryOrderById(orderId); - if (!entryOrder) { - return { - code: 404, - message: '入库单不存在或无权访问', - data: null, - }; - } - - if (entryOrder.order_status === 'CANCELLED') { - return { - code: 400, - message: '已作废入库单不允许完成', - data: null, - }; - } - - if (![ 'PENDING' ].includes(entryOrder.order_status)) { - return { - code: 400, - message: `当前入库单状态为 ${entryOrder.order_status},仅 PENDING 状态可完成入库`, - data: null, - }; - } - - const detailCount = await ctx.model.EntryItems.count({ where: { order_id: orderId } }); - if (detailCount <= 0) { - return { - code: 400, - message: '请先添加入库明细', - data: null, - }; - } - - await entryOrder.update({ - order_status: 'COMPLETED', - updated_at: new Date(), - }); - - return { - code: 200, - message: '完成成功', - data: { - id: entryOrder.id, - }, - }; } /** @@ -909,8 +1033,208 @@ class EntryService extends Service { return await ctx.service.systems.inboundDirectLog.removeItem(data); } + /** + * 查询入库单已绑定收货单中匹配指定 stock_id 的收货明细列表。 + * 用于 PDA 导入时选择要绑定的收货明细。 + * @param {Object} data 请求体 + * @param {number} data.entry_order_id 入库单 ID + * @param {number} data.stock_id 商品 stock_id + * @return {Promise} { code, message, data: { list: [{ receiving_detail_id, receiving_id, receiving_number, actual_quantity, used_quantity, available_quantity, system_product_id }] } } + */ + async getReceivingDetailsForBind(data = {}) { + const { ctx, app } = this; + const entryOrderId = Number(data.entry_order_id); + const stockId = Number(data.stock_id); + + if (!entryOrderId || !stockId) { + return { code: 400, message: 'entry_order_id 和 stock_id 必填', data: null }; + } + + // 1. 查入库单绑定的收货单 ID 列表 + const orderReceivings = await ctx.model.EntryOrderReceiving.findAll({ + where: { entry_order_id: entryOrderId, deleted_at: null }, + attributes: [ 'receiving_id' ], + raw: true, + }); + if (!orderReceivings.length) { + return { code: 200, message: 'ok', data: { list: [] } }; + } + const receivingIds = orderReceivings.map(r => r.receiving_id); + + // 2. 查收货明细(system_product_id = stockId,且收货单未取消/未删除) + const details = await ctx.model.ReceivingDetail.findAll({ + where: { + system_product_id: stockId, + receiving_id: receivingIds, + deleted_at: null, + }, + attributes: [ 'id', 'receiving_id', 'actual_quantity', 'system_product_id' ], + include: [{ + model: ctx.model.Receiving, + as: 'receiving', + attributes: [ 'id', 'receiving_number', 'status' ], + where: { status: { [ app.Sequelize.Op.ne ]: 'cancelled' }, deleted_at: null }, + required: true, + }], + raw: false, + }); + + // 3. 查每个明细的已占用数量(pending + committed) + const detailIds = details.map(d => d.id); + const usedMap = new Map(); + if (detailIds.length > 0) { + const usedRows = await ctx.model.query( + `SELECT receiving_detail_id, COALESCE(SUM(allocated_quantity), 0) AS used_qty + FROM wms_entry_receiving_binding + WHERE receiving_detail_id IN (:ids) + AND status IN ('pending', 'committed') + AND deleted_at IS NULL + GROUP BY receiving_detail_id`, + { + replacements: { ids: detailIds }, + type: ctx.model.QueryTypes.SELECT, + } + ); + for (const row of usedRows) { + usedMap.set(row.receiving_detail_id, Number(row.used_qty)); + } + } + + // 4. 组装返回 + const list = details.map(d => { + const rid = d.id; + const used = usedMap.get(rid) || 0; + return { + receiving_detail_id: rid, + receiving_id: d.receiving_id, + receiving_number: d.receiving?.receiving_number || '', + actual_quantity: d.actual_quantity || 0, + used_quantity: used, + available_quantity: Math.max(0, (d.actual_quantity || 0) - used), + system_product_id: d.system_product_id, + }; + }); + + return { code: 200, message: 'ok', data: { list } }; + } + + /** + * 拉取入库单绑定的收货单中,指定商品的可用容器列表(收货明细)。 + * 用于 PDA 上架时选择容器。 + * @param {Object} data 请求参数 + * @param {number} data.entry_order_id 入库单ID + * @param {number} data.stock_id 商品stock_id + * @return {Promise} { code, message, data: { list, total } } + */ + async containerList(data = {}) { + const { ctx, app } = this; + const warehouseId = ctx.user?.store_id; + const entryOrderId = Number(data.entry_order_id); + const stockId = Number(data.stock_id); + + // 参数校验 + if (!warehouseId) { + return { code: 0, message: '用户未绑定仓库', data: null }; + } + if (!entryOrderId || entryOrderId <= 0) { + return { code: 0, message: 'entry_order_id 不能为空', data: null }; + } + if (!stockId || stockId <= 0) { + return { code: 0, message: 'stock_id 不能为空', data: null }; + } + + try { + // 1. 验证入库单存在且属于当前仓库 + const entryOrder = await ctx.model.EntryOrder.findOne({ + where: { + id: entryOrderId, + warehouse_id: warehouseId, + }, + attributes: [ 'id' ], + raw: true, + }); + + if (!entryOrder) { + return { code: 0, message: '入库单不存在或无权访问', data: null }; + } + + // 2. 通过 wms_entry_order_receiving 查出关联的 receiving_id 列表 + const entryReceivingRows = await ctx.model.EntryOrderReceiving.findAll({ + where: { entry_order_id: entryOrderId, deleted_at: null }, + attributes: [ 'receiving_id' ], + raw: true, + }); + + const receivingIds = entryReceivingRows.map(r => r.receiving_id).filter(Boolean); + if (receivingIds.length === 0) { + return { code: 200, message: 'ok', data: { list: [], total: 0 } }; + } + + // 3. 排除已绑定的收货明细(wms_entry_receiving_binding 中有记录且未软删除) + const notBoundCondition = app.Sequelize.literal( + 'NOT EXISTS (SELECT 1 FROM wms_entry_receiving_binding erb WHERE erb.receiving_detail_id = wms_receiving_detail.id AND erb.deleted_at IS NULL)' + ); + + // 4. 查询指定商品的未绑定收货明细 + const details = await ctx.model.ReceivingDetail.findAll({ + where: { + [app.Sequelize.Op.and]: [ + { system_product_id: stockId }, + { receiving_id: { [app.Sequelize.Op.in]: receivingIds } }, + notBoundCondition, + ], + }, + raw: true, + }); + + // 5. 收集所有明细的 system_product_id,批量获取 stock 详情 + const stockIdSet = new Set(); + for (const d of details) { + if (d.system_product_id != null) { + stockIdSet.add(Number(d.system_product_id)); + } + } + const stockIds = [ ...stockIdSet ]; + + /** @type {Map} */ + const stockDetailMap = new Map(); + if (stockIds.length > 0) { + const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { warehouseId }); + for (const sd of stockDetails) { + if (sd && sd.id != null) { + stockDetailMap.set(sd.id, sd); + } + } + } + + // 6. 组装返回结果 + const list = details.map(detail => ({ + detail_id: detail.id, + receiving_id: detail.receiving_id, + barcode: detail.barcode || '', + product_name: detail.product_name || '', + actual_quantity: detail.actual_quantity || 0, + receiving_status: detail.receiving_status || '', + stock: stockDetailMap.get(Number(detail.system_product_id)) || null, + })); + + return { + code: 200, + message: 'ok', + data: { + list, + total: list.length, + }, + }; + } catch (error) { + ctx.logger.error('[storage.entry.containerList] 查询容器列表失败', error); + return { code: 500, message: `服务器错误: ${error.message}`, data: null }; + } + } + /** * 快捷直入/虚拟入库:将入库单的所有商品按明细数量全部直入到虚拟库位(space_id=2),跳过收货、质检等正常流程。 + * 采用"先同步后写库"两段式:① 先发奇门/OpenAPI 回传,② 回传成功后再开启事务写库存。 * @param {Object} data 请求体 * @param {number} data.id 入库单ID * @return {Promise} code/data/message 结构 @@ -972,172 +1296,224 @@ class EntryService extends Service { }; } - const warehouseId = entryOrder.warehouse_id; - const storeId = entryOrder.store_id; - const batchNo = entryOrder.entry_order_code; - const hardcodedSpaceId = 2; - const transaction = await ctx.model.transaction(); + // ===== 阶段一 + 阶段二合并为统一调用 ===== + const syncResult = await ctx.service.systems.inboundDirectLog.qimenEntrySync({ + entryOrder, + orderLines: entryItems.map((item, idx) => ({ + orderLineNo: idx + 1, + ownerCode: item.owner_code || '', + itemCode: item.item_code || '', + itemId: item.item_id || '', + inventoryType: item.inventory_type || 'ZP', + planQty: Number(item.count) || 0, + actualQty: Number(item.count) || 0, + })), + outBizCode: `DIRECT_INBOUND_${Date.now()}`, + remark: '导入/PDA直接入库提交', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + onSuccess: async eo => { + const warehouseId = eo.warehouse_id; + const storeId = eo.store_id; + const batchNo = eo.entry_order_code; + const hardcodedSpaceId = 2; + const transaction = await ctx.model.transaction(); - const processedStockIds = new Set(); - let totalInboundQty = 0; + const processedStockIds = new Set(); + let totalInboundQty = 0; - try { - // 3. 逐商品写入库存 - for (const item of entryItems) { - const stockId = item.stock_id; - if (!stockId) continue; + try { + for (const item of entryItems) { + const stockId = item.stock_id; + if (!stockId) continue; - const planQty = Number(item.count) || 0; - if (planQty <= 0) continue; + const planQty = Number(item.count) || 0; + if (planQty <= 0) continue; - const inventoryType = item.inventory_type || 'ZP'; + const inventoryType = item.inventory_type || 'ZP'; - // 更新入库明细的 received_quantity 为计划数量(全部入库) - await ctx.model.EntryItems.update({ - received_quantity: planQty, - }, { - where: { id: item.id }, - transaction, - }); + await ctx.model.EntryItems.update({ + received_quantity: planQty, + }, { + where: { id: item.id }, + transaction, + }); - // 同一 stock_id 只写一次库存 - if (processedStockIds.has(String(stockId))) continue; - processedStockIds.add(String(stockId)); - totalInboundQty += planQty; + if (processedStockIds.has(String(stockId))) continue; + processedStockIds.add(String(stockId)); + totalInboundQty += planQty; - // 锁定并更新 StockWarehouse 总库存 - const stockRecord = await ctx.model.StockWarehouse.findOne({ - where: { id: stockId, is_valid: 'Y', deleted_at: null }, - lock: transaction.LOCK.UPDATE, - transaction, - }); + const stockRecord = await ctx.model.StockWarehouse.findOne({ + where: { id: stockId, is_valid: 'Y', deleted_at: null }, + lock: transaction.LOCK.UPDATE, + transaction, + }); - if (stockRecord) { - const beforeQuantity = Number(stockRecord.quantity) || 0; - const beforeLockedQuantity = Number(stockRecord.locked_quantity) || 0; + if (stockRecord) { + const beforeQuantity = Number(stockRecord.quantity) || 0; + const beforeLockedQuantity = Number(stockRecord.locked_quantity) || 0; - await stockRecord.increment('quantity', { by: planQty, transaction, silent: true }); - await stockRecord.reload({ transaction }); + await stockRecord.increment('quantity', { by: planQty, transaction, silent: true }); + await stockRecord.reload({ transaction }); - const afterQuantity = Number(stockRecord.quantity) || 0; - const afterLockedQuantity = Number(stockRecord.locked_quantity) || 0; + const afterQuantity = Number(stockRecord.quantity) || 0; + const afterLockedQuantity = Number(stockRecord.locked_quantity) || 0; - // 写入库存流水 - await ctx.service.systems.stockTransaction.create({ - transaction_type: 'INBOUND', - warehouse_id: warehouseId, - store_id: storeId, - stock_id: stockId, - quantity: planQty, - batch_no: batchNo, - order_type: entryOrder.order_type, - order_no: entryOrder.entry_order_code, - entry_order_id: entryOrder.id, - operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), - operator_name: ctx.user?.employees_name || '', - remark: '快捷直入/虚拟入库', - before_quantity: beforeQuantity, - after_quantity: afterQuantity, - before_locked_quantity: beforeLockedQuantity, - after_locked_quantity: afterLockedQuantity, - created_at: new Date(), - }, { transaction }); - } + await ctx.service.systems.stockTransaction.create({ + transaction_type: 'INBOUND', + warehouse_id: warehouseId, + store_id: storeId, + stock_id: stockId, + quantity: planQty, + batch_no: batchNo, + order_type: eo.order_type, + order_no: eo.entry_order_code, + entry_order_id: eo.id, + operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), + operator_name: ctx.user?.employees_name || '', + remark: '快捷直入/虚拟入库', + before_quantity: beforeQuantity, + after_quantity: afterQuantity, + before_locked_quantity: beforeLockedQuantity, + after_locked_quantity: afterLockedQuantity, + created_at: new Date(), + }, { transaction }); + } - // 创建/更新 Storage 库位库存(space_id 硬编码为 2) - const storageRecord = await ctx.model.Storage.findOne({ - where: { - space_id: hardcodedSpaceId, - stock_id: stockId, - batch_no: batchNo, - inventory_type: inventoryType, - is_enabled: 1, - delete_at: null, - }, - lock: transaction.LOCK.UPDATE, - transaction, - }); + const storageRecord = await ctx.model.Storage.findOne({ + where: { + space_id: hardcodedSpaceId, + stock_id: stockId, + batch_no: batchNo, + inventory_type: inventoryType, + is_enabled: 1, + delete_at: null, + }, + lock: transaction.LOCK.UPDATE, + transaction, + }); - if (storageRecord) { - await ctx.model.Storage.update({ - quantity: app.Sequelize.literal(`quantity + ${planQty}`), - available_quantity: app.Sequelize.literal(`available_quantity + ${planQty}`), - entry_order_id: entryOrder.id, - inbound_time: new Date(), - inbound_order_no: entryOrder.entry_order_code, + let storageId = null; + let storageBeforeQty = 0; + let storageAfterQty = 0; + + if (storageRecord) { + storageBeforeQty = Number(storageRecord.quantity) || 0; + storageAfterQty = storageBeforeQty + planQty; + + await ctx.model.Storage.update({ + quantity: app.Sequelize.literal(`quantity + ${planQty}`), + available_quantity: app.Sequelize.literal(`available_quantity + ${planQty}`), + entry_order_id: eo.id, + inbound_time: new Date(), + inbound_order_no: eo.entry_order_code, + updated_at: new Date(), + }, { + where: { id: storageRecord.id }, + transaction, + }); + storageId = storageRecord.id; + } else { + storageBeforeQty = 0; + storageAfterQty = planQty; + + const createdStorage = await ctx.model.Storage.create({ + warehouse_id: warehouseId, + store_id: storeId, + space_id: hardcodedSpaceId, + stock_id: stockId, + batch_no: batchNo, + inventory_type: inventoryType, + quantity: planQty, + locked_quantity: 0, + available_quantity: planQty, + inbound_time: new Date(), + inbound_order_no: eo.entry_order_code, + receiving_id: null, + entry_order_id: eo.id, + supplier_id: null, + supplier_batch_no: null, + is_enabled: 1, + created_at: new Date(), + updated_at: new Date(), + }, { transaction }); + storageId = createdStorage.id; + } + + // 写入库位维度库存流水 + await ctx.model.StorageTransaction.create({ + transaction_type: 'INBOUND', + warehouse_id: warehouseId, + store_id: storeId, + stock_id: stockId, + storage_id: storageId, + space_id: hardcodedSpaceId, + quantity: planQty, + before_quantity: storageBeforeQty, + after_quantity: storageAfterQty, + batch_no: batchNo, + inventory_type: inventoryType, + order_type: 'entry_order', + order_no: eo.entry_order_code, + order_id: eo.id, + operator_id: String(ctx.user?.employees_id || ctx.user?.id || ''), + operator_name: ctx.user?.employees_name || '', + remark: '快捷直入/虚拟入库', + created_at: new Date(), + }, { transaction }); + } + + await eo.update({ + order_status: 'COMPLETED', + sync_status: 'SUCCESS', + sync_message: JSON.stringify({ + completedAt: new Date(), + totalQuantity: totalInboundQty, + itemCount: processedStockIds.size, + source: 'quick_inbound', + }), updated_at: new Date(), - }, { - where: { id: storageRecord.id }, + }, { transaction }); + + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'entry_order', + businessId: eo.id, + operationCode: 'QUICK_INBOUND', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: eo.warehouse_id, + message: `快捷直入完成,共 ${processedStockIds.size} 种商品,总数量 ${totalInboundQty}`, + }, transaction, }); - } else { - await ctx.model.Storage.create({ - warehouse_id: warehouseId, - store_id: storeId, - space_id: hardcodedSpaceId, - stock_id: stockId, - batch_no: batchNo, - inventory_type: inventoryType, - quantity: planQty, - locked_quantity: 0, - available_quantity: planQty, - inbound_time: new Date(), - inbound_order_no: entryOrder.entry_order_code, - receiving_id: null, - entry_order_id: entryOrder.id, - supplier_id: null, - supplier_batch_no: null, - is_enabled: 1, - created_at: new Date(), - updated_at: new Date(), - }, { transaction }); + + await transaction.commit(); + } catch (error) { + if (transaction && typeof transaction.rollback === 'function') { + await transaction.rollback(); + } + throw error; } - } - - // 4. 更新入库单状态为 COMPLETED - await entryOrder.update({ - order_status: 'COMPLETED', - sync_status: 'SUCCESS', - sync_message: JSON.stringify({ - completedAt: new Date(), - totalQuantity: totalInboundQty, - itemCount: processedStockIds.size, - source: 'quick_inbound', - }), - updated_at: new Date(), - }, { transaction }); - - // 记录操作日志(事务内) - await ctx.service.systems.operationLog.createOperationLog({ - businessType: 'entry_order', - businessId: entryOrder.id, - operationCode: 'QUICK_INBOUND', - operator: { - id: ctx.user?.employees_id || ctx.user?.id, - name: ctx.user?.employees_name || '', - }, - extras: { - warehouseId: entryOrder.warehouse_id, - message: `快捷直入完成,共 ${processedStockIds.size} 种商品,总数量 ${totalInboundQty}`, - }, - transaction, - }); - - await transaction.commit(); - } catch (error) { - if (transaction && typeof transaction.rollback === 'function') { - await transaction.rollback(); - } - throw error; - } - - // 事务外:异步触发奇门/API 回传(复用 inboundDirectLog 的回传逻辑) - setImmediate(() => { - ctx.service.systems.inboundDirectLog._sendCallback(entryOrder).catch(err => { - ctx.logger.error(`[quickInbound] 回传异常 entryOrderId=${entryOrder.id}: ${err.message}`, err.stack); - }); + }, }); + if (!syncResult.success) { + return { + code: 500, + message: syncResult.message, + data: { + id: entryOrder.id, + entry_order_code: entryOrder.entry_order_code, + sync_status: 'FAILED', + }, + }; + } + return { code: 200, message: '快捷入库完成', @@ -1147,35 +1523,116 @@ class EntryService extends Service { order_status: 'COMPLETED', sync_status: 'SUCCESS', items_count: entryItems.length, - total_quantity: totalInboundQty, + total_quantity: entryItems.reduce((s, item) => s + (Number(item.count) || 0), 0), }, }; } /** - * 入库单商品与收货单商品逐行对照视图。 + * 入库单商品与收货单商品逐行对照视图(支持多个收货单)。 * 以入库单明细为主,按 stock_id ↔ system_product_id 匹配收货单明细, - * 返回匹配/未匹配/收货单多余的对照结果。 + * 返回每个收货单的匹配/未匹配/收货单多余对照结果及汇总。 * * @param {Object} data 请求参数 * @param {number} data.entry_order_id 入库单ID - * @param {number} data.receiving_id 收货单ID + * @param {number[]} [data.receiving_ids] 收货单ID列表(优先使用) + * @param {number} [data.receiving_id] 单个收货单ID(向后兼容,receiving_ids 优先) * @return {Promise} code/data/message 结构 */ async receivingCompare(data = {}) { - const { ctx, app } = this; + const { ctx } = this; const entryOrderId = Number(data.entry_order_id || 0); - const receivingId = Number(data.receiving_id || 0); const warehouseId = ctx.user.store_id; + // 入参处理:receiving_ids 优先,receiving_id 向后兼容 + let receivingIds = data.receiving_ids; + if (!Array.isArray(receivingIds) || receivingIds.length === 0) { + const singleId = Number(data.receiving_id || 0); + if (singleId) { + receivingIds = [ singleId ]; + } else { + return { code: 400, message: 'receiving_ids 或 receiving_id 必填', data: null }; + } + } + receivingIds = [ ...new Set(receivingIds.map(id => Number(id)).filter(Boolean)) ]; + if (!entryOrderId) { return { code: 400, message: 'entry_order_id 必填', data: null }; } - if (!receivingId) { - return { code: 400, message: 'receiving_id 必填', data: null }; + + // 1. 校验入库单存在性 + const entryOrder = await this.getOwnedEntryOrderById(entryOrderId); + if (!entryOrder) { + return { code: 404, message: '入库单不存在或无权访问', data: null }; } - // 1. 校验收货单存在性 + // 2. 查询入库单明细(所有收货单共用) + const entryItems = await ctx.model.EntryItems.findAll({ + where: { order_id: entryOrderId }, + attributes: [ 'id', 'stock_id', 'count', 'received_quantity' ], + raw: true, + }); + + // 3. 收集入库单所有 stock_id + const entryStockIds = [ ...new Set(entryItems.map(item => Number(item.stock_id)).filter(Boolean)) ]; + + // 4. 对每个收货单执行对比 + const comparisons = []; + const errors = []; + + for (const receivingId of receivingIds) { + const singleResult = await this._compareSingleReceiving({ + receivingId, + warehouseId, + entryOrderId, + entryOrder, + entryItems, + entryStockIds, + }); + if (singleResult._error) { + errors.push(singleResult._error); + } else { + comparisons.push(singleResult); + } + } + + const totalReceivings = receivingIds.length; + const matchedCount = comparisons.length; + const errorCount = errors.length; + + return { + code: 200, + message: '查询成功', + data: { + entry_order_id: entryOrderId, + entry_order_code: entryOrder.entry_order_code, + comparisons, + errors, + total_summary: { + total_receivings: totalReceivings, + matched_count: matchedCount, + error_count: errorCount, + }, + }, + }; + } + + /** + * 对单个收货单执行商品对照逻辑。 + * @param {Object} params 参数 + * @param {number} params.receivingId 收货单ID + * @param {number} params.warehouseId 仓库ID + * @param {number} params.entryOrderId 入库单ID + * @param {Object} params.entryOrder 入库单记录 + * @param {Object[]} params.entryItems 入库单明细列表 + * @param {number[]} params.entryStockIds 入库单 stock_id 集合 + * @return {Promise} 单个收货单的对照结果,或 { _error: ... } + */ + async _compareSingleReceiving(params = {}) { + const { ctx, app } = this; + const { receivingId, warehouseId, entryItems, entryStockIds } = params; + + // 校验收货单存在性与仓库匹配 const receivingOrder = await ctx.model.Receiving.findOne({ where: { id: receivingId, @@ -1186,34 +1643,25 @@ class EntryService extends Service { raw: true, }); if (!receivingOrder) { - return { code: 404, message: '收货单不存在或无权访问', data: null }; + return { + _error: { + receiving_id: receivingId, + status: 'error', + error_code: 'RECEIVING_NOT_FOUND', + error_message: '收货单不存在或无权访问', + }, + }; } - // 2. 校验收货单存在性(复用 getOwnedEntryOrderById) - const entryOrder = await this.getOwnedEntryOrderById(entryOrderId); - if (!entryOrder) { - return { code: 404, message: '入库单不存在或无权访问', data: null }; - } - - // 3. 查询入库单明细 - const entryItems = await ctx.model.EntryItems.findAll({ - where: { order_id: entryOrderId }, - attributes: [ 'id', 'stock_id', 'count', 'received_quantity' ], - raw: true, - }); - - // 4. 查询收货单明细 + // 查询收货单明细 const receivingDetails = await ctx.model.ReceivingDetail.findAll({ where: { receiving_id: receivingId }, attributes: [ 'id', 'system_product_id', 'actual_quantity', 'product_name' ], raw: true, }); - // 5. 收集所有 stock_id,批量查询商品信息 - const entryStockIds = [ ...new Set(entryItems.map(item => Number(item.stock_id)).filter(Boolean)) ]; + // 收集所有 stock_id,批量查询商品信息 const receivingSystemProductIds = [ ...new Set(receivingDetails.map(d => Number(d.system_product_id)).filter(Boolean)) ]; - - // 6. 批量查询 wms_stock_warehouse — 入库单商品(按 stock_id)和收货单商品(按 system_product_id = id) const allStockIds = [ ...new Set([ ...entryStockIds, ...receivingSystemProductIds ]) ]; const stockDetailMap = new Map(); if (allStockIds.length > 0) { @@ -1223,8 +1671,7 @@ class EntryService extends Service { } } - // stock_id 即 wms_stock_warehouse.id,与 wms_receiving_detail.system_product_id 直接对应 - // 只需确认 stock_warehouse 记录存在即可构建映射 + // stock_id ↔ system_product_id 映射 const stockIdToSystemProductId = new Map(); const systemProductIdToEntryStockIds = new Map(); if (entryStockIds.length > 0) { @@ -1243,18 +1690,20 @@ class EntryService extends Service { } } - // 7. 查询已分配量(从 wms_entry_receiving_binding) + // 查询已分配量(限定本入库单的 entry_items,避免全局绑定干扰) const receivingDetailIds = receivingDetails.map(d => d.id); + const entryItemIds = entryItems.map(ei => ei.id); const allocatedMap = new Map(); - if (receivingDetailIds.length > 0) { + if (receivingDetailIds.length > 0 && entryItemIds.length > 0) { const bindingRows = await ctx.model.EntryReceivingBinding.findAll({ attributes: [ 'receiving_detail_id', [ app.Sequelize.fn('SUM', app.Sequelize.col('allocated_quantity')), 'total_allocated' ], ], where: { + entry_item_id: { [app.Sequelize.Op.in]: entryItemIds }, receiving_detail_id: { [app.Sequelize.Op.in]: receivingDetailIds }, - status: 'committed', + status: { [app.Sequelize.Op.in]: [ 'pending', 'committed' ] }, deleted_at: null, }, group: [ 'receiving_detail_id' ], @@ -1265,7 +1714,7 @@ class EntryService extends Service { } } - // 8. 构建对照视图:以入库单明细为主 + // 构建对照视图:以入库单明细为主 const comparison = []; const matchedReceivingDetailIds = new Set(); @@ -1274,13 +1723,11 @@ class EntryService extends Service { const systemProductId = stockIdToSystemProductId.get(stockId) || 0; const stockDetail = stockDetailMap.get(stockId) || null; - // 找到同 system_product_id 的收货单明细 const matchedReceiving = systemProductId > 0 ? receivingDetails.filter(rd => Number(rd.system_product_id) === systemProductId) : []; if (matchedReceiving.length > 0) { - // 有匹配的收货明细 for (const rd of matchedReceiving) { matchedReceivingDetailIds.add(rd.id); const rdStockDetail = (rd.system_product_id != null && stockDetailMap.get(Number(rd.system_product_id))) || null; @@ -1304,7 +1751,6 @@ class EntryService extends Service { }); } } else { - // 入库商品在收货单中不存在 comparison.push({ entry_item_id: Number(entryItem.id), stock_id: stockId, @@ -1324,44 +1770,63 @@ class EntryService extends Service { } } - // 9. 收货单中多余的商品(未被任何入库单明细匹配的) + // 收货单中多余的商品 const receivingOnly = []; + const receivingStockMap = new Map(); for (const rd of receivingDetails) { if (!matchedReceivingDetailIds.has(Number(rd.id))) { const rdStockDetail = (rd.system_product_id != null && stockDetailMap.get(Number(rd.system_product_id))) || null; + const stockId = rd.system_product_id != null ? Number(rd.system_product_id) : null; + const qty = Number(rd.actual_quantity) || 0; + const name = rd.product_name || (rdStockDetail && rdStockDetail.item_name) || ''; const allocated = allocatedMap.get(Number(rd.id)) || 0; - const available = Math.max(0, (Number(rd.actual_quantity) || 0) - allocated); - receivingOnly.push({ - receiving_detail_id: Number(rd.id), - receiving_product_code: (rdStockDetail && rdStockDetail.item_code) || '', - receiving_product_name: rd.product_name || (rdStockDetail && rdStockDetail.item_name) || '', - receiving_actual_quantity: Number(rd.actual_quantity) || 0, - receiving_allocated: allocated, - receiving_available: available, - }); + const available = Math.max(0, qty - allocated); + + if (stockId === null) { + receivingOnly.push({ + receiving_product_name: name, + receiving_actual_quantity: qty, + receiving_allocated: allocated, + receiving_available: available, + }); + } else if (receivingStockMap.has(stockId)) { + const existing = receivingStockMap.get(stockId); + existing.receiving_actual_quantity += qty; + existing.receiving_allocated += allocated; + existing.receiving_available += available; + if (!existing.receiving_product_name && name) { + existing.receiving_product_name = name; + } + } else { + receivingStockMap.set(stockId, { + receiving_product_name: name, + receiving_actual_quantity: qty, + receiving_allocated: allocated, + receiving_available: available, + }); + } } } + for (const item of receivingStockMap.values()) { + item.receiving_available = Math.max(0, item.receiving_available); + receivingOnly.push(item); + } - // 10. 汇总 + // 汇总 const matchedItems = comparison.filter(c => c.match_status === 'matched').length; const entryOnlyItems = comparison.filter(c => c.match_status === 'entry_only').length; return { - code: 200, - message: '查询成功', - data: { - entry_order_id: entryOrderId, - entry_order_code: entryOrder.entry_order_code, - receiving_id: receivingId, - receiving_number: receivingOrder.receiving_number, - comparison, - receiving_only: receivingOnly, - summary: { - total_entry_items: entryItems.length, - matched_items: matchedItems, - entry_only_items: entryOnlyItems, - receiving_only_items: receivingOnly.length, - }, + receiving_id: receivingId, + receiving_number: receivingOrder.receiving_number, + status: 'matched', + comparison, + receiving_only: receivingOnly, + summary: { + total_entry_items: entryItems.length, + matched_items: matchedItems, + entry_only_items: entryOnlyItems, + receiving_only_items: receivingOnly.length, }, }; } diff --git a/app/service/systems/storage/inventory.js b/app/service/systems/storage/inventory.js index c3b0762..e1c7eac 100644 --- a/app/service/systems/storage/inventory.js +++ b/app/service/systems/storage/inventory.js @@ -171,9 +171,12 @@ async function loadStockAttachments(ctx, stockIds = []) { } } - // 提取图片 - if (detail.image_url) { - imagesByStockId.set(stockId, [ String(detail.image_url).trim() ]); + // 提取图片(兼容数组/字符串格式) + const imageUrls = Array.isArray(detail.image_url) + ? detail.image_url.map(u => String(u || '').trim()).filter(Boolean) + : (detail.image_url ? [ String(detail.image_url).trim() ] : []); + if (imageUrls.length > 0) { + imagesByStockId.set(stockId, imageUrls); } } } catch (error) { @@ -1394,6 +1397,334 @@ class InventoryService extends Service { }, }; } + /** + * 收货单快捷入库:判断货主配置是否允许收货单快捷入库,不允许直接返回失败; + * 允许的话使用收货单的明细创建入库单,相同 stock_id 的合并为一条,汇集总数。 + * 在 wms_entry_order_receiving 表建立绑定关系,入库单自动审批到 PENDING 状态。 + * + * @param {Object} data 请求体 + * @param {number} data.receiving_id 收货单ID(必填) + * @return {Promise} code/data/message 结构,data 中包含创建的入库单信息 + */ + async quickPutaway(data = {}) { + const { ctx, app } = this; + const receivingId = Number(data.receiving_id || 0); + + // ────────── 1. 参数校验 ────────── + if (!receivingId) { + return { code: 400, message: 'receiving_id 必填', data: null }; + } + + const warehouseId = ctx.user.store_id; + if (!warehouseId) { + return { code: 400, message: '无法获取当前仓库信息', data: null }; + } + + // ────────── 2. 加载收货单主表及明细 ────────── + const receiving = await ctx.model.Receiving.findOne({ + where: { id: receivingId, warehouse_id: warehouseId, is_deleted: false }, + }); + + if (!receiving) { + return { code: 404, message: `收货单不存在或无权访问: receiving_id=${receivingId}`, data: null }; + } + + if (receiving.status === 'cancelled') { + return { code: 400, message: '收货单已作废,不允许快捷入库', data: null }; + } + + if (receiving.status !== 'completed') { + return { code: 400, message: `收货单状态不允许快捷入库,当前状态: ${receiving.status},仅 completed 状态可操作`, data: null }; + } + + if (!receiving.is_review) { + return { code: 400, message: '收货单未审核,不允许快捷入库', data: null }; + } + + const storeId = receiving.store_id; + + // ────────── 3. 检查货主配置:是否允许收货单快捷入库 ────────── + const storeWarehouse = await ctx.model.StoreWarehouse.findOne({ + where: { store_id: storeId, warehouse_id: warehouseId, use_status: 1 }, + attributes: [ 'id', 'policy_config' ], + }); + + if (!storeWarehouse) { + return { code: 400, message: '货主仓库签约关系不存在', data: null }; + } + + const policyConfig = storeWarehouse.policy_config || {}; + const allowQuickPutaway = Number(policyConfig.allow_receiving_quick_putaway) === 1; + + if (!allowQuickPutaway) { + return { code: 400, message: '货主未开启收货单快捷入库功能,请联系管理员开启', data: null }; + } + + // ────────── 4. 加载收货单明细 ────────── + const receivingDetails = await ctx.model.ReceivingDetail.findAll({ + where: { receiving_id: receivingId }, + attributes: [ + 'id', 'system_product_id', 'actual_quantity', 'product_name', + 'batch_number', 'production_date', 'expiry_date', + 'storage_status', 'stored_quantity', + ], + }); + + if (!receivingDetails || receivingDetails.length === 0) { + return { code: 400, message: '收货单无明细,无法创建入库单', data: null }; + } + + // ────────── 5. 按 stock_id(system_product_id)分组,合并数量 ────────── + /** @type {Map} */ + const groupedMap = new Map(); + + for (const detail of receivingDetails) { + const stockId = Number(detail.system_product_id); + if (!stockId) { + // 跳过未匹配系统商品的明细 + continue; + } + + const qty = Number(detail.actual_quantity) || 0; + if (qty <= 0) { + continue; + } + + const existing = groupedMap.get(stockId); + if (existing) { + existing.total_quantity += qty; + existing.detail_ids.push(detail.id); + } else { + groupedMap.set(stockId, { + system_product_id: stockId, + total_quantity: qty, + product_name: detail.product_name || '', + batch_number: detail.batch_number || '', + production_date: detail.production_date || null, + expiry_date: detail.expiry_date || null, + detail_ids: [ detail.id ], + }); + } + } + + if (groupedMap.size === 0) { + return { code: 400, message: '收货单中所有明细均未关联系统商品,无法创建入库单', data: null }; + } + + const groupedItems = Array.from(groupedMap.values()); + + // ────────── 6. 批量查询 stock_warehouse 获取 stock_id 对应的商品信息 ────────── + const stockIds = groupedItems.map(item => item.system_product_id); + const stockRows = await ctx.model.StockWarehouse.findAll({ + where: { id: { [app.Sequelize.Op.in]: stockIds }, warehouse_id: warehouseId }, + attributes: [ 'id', 'item_code', 'item_name', 'stock_unit', 'is_valid' ], + raw: true, + }); + const stockMap = new Map(); + for (const row of stockRows) { + stockMap.set(Number(row.id), row); + } + + // 校验所有 stock_id 是否存在且有效 + const missingStockIds = stockIds.filter(sid => !stockMap.has(sid)); + if (missingStockIds.length > 0) { + return { + code: 400, + message: `以下商品在当前仓库中不存在或已失效: stock_id=${missingStockIds.join(',')}`, + data: null, + }; + } + + // ────────── 7. 开事务,创建入库单及明细 ────────── + const transaction = await ctx.model.transaction(); + + try { + // 获取货主和仓库名称快照 + const storeData = await ctx.service.systems.store.getStoreName(storeId); + const storeName = (storeData.code === 200 && storeData.data) ? storeData.data.company_name : ''; + const warehouseData = await ctx.service.systems.store.getStoreName(warehouseId); + const warehouseName = (warehouseData.code === 200 && warehouseData.data) ? warehouseData.data.company_name : ''; + + // 生成入库单号 + const entryOrderCode = await this._generateEntryOrderCode(warehouseId, storeId, transaction); + + // 创建入库单主表(状态直接设为 PENDING) + const entryOrder = await ctx.model.EntryOrder.create({ + entry_order_code: entryOrderCode, + order_type: 'SCRK', + total_order_lines: groupedItems.length, + order_create_time: new Date(), + source_type: 'WMS', + order_status: 'PENDING', + sync_status: 'PENDING', + is_enabled: 1, + warehouse_id: warehouseId, + store_id: storeId, + store_name: storeName, + warehouse_name: warehouseName, + remark: `收货单${receiving.receiving_number}快捷入库`, + expense_record: 0, + }, { transaction }); + + const entryOrderId = entryOrder.id; + + // 创建入库单明细(按合并后的分组) + for (let i = 0; i < groupedItems.length; i++) { + const group = groupedItems[i]; + const stockInfo = stockMap.get(group.system_product_id); + + await ctx.model.EntryItems.create({ + order_id: entryOrderId, + out_biz_code: '', + order_line_no: i + 1, + owner_code: '', + item_code: stockInfo ? stockInfo.item_code : '', + item_id: 0, + count: group.total_quantity, + inventory_type: 'ZP', + stock_id: group.system_product_id, + received_quantity: 0, + confirm_quantity: 0, + }, { transaction }); + } + + // ────────── 8. 写入 wms_entry_order_receiving 绑定关系 ────────── + await ctx.model.EntryOrderReceiving.create({ + entry_order_id: entryOrderId, + receiving_id: receivingId, + }, { transaction }); + + // ────────── 9. 更新收货单主表 storage_status ────────── + // 快捷入库后收货单进入"等待入库"状态(后续可通过 matchPutaway 补全) + const [ affectedRows ] = await ctx.model.Receiving.update({ + storage_status: 'waiting', + updated_at: new Date(), + }, { + where: { id: receivingId, storage_status: 'none' }, + transaction, + }); + + if (affectedRows === 0) { + await transaction.rollback(); + return { code: 400, message: '收货单入库状态已变更,可能已被其他操作处理,禁止重复快捷入库', data: null }; + } + + // ────────── 10. 更新收货单明细的 storage_status 为 waiting,stored_quantity 为对应用量 ────────── + for (const group of groupedItems) { + for (const detailId of group.detail_ids) { + const detailRow = receivingDetails.find(d => d.id === detailId); + if (!detailRow) continue; + + // 该明细的总量和已入库量 + const detailTotalQty = Number(detailRow.actual_quantity) || 0; + // 该明细在本次合并中的贡献量按比例计入(简化:按该明细数量在合并总量中的占比) + const detailRatio = group.total_quantity > 0 ? detailTotalQty / group.total_quantity : 0; + const thisStoredQty = Math.round(detailRatio * group.total_quantity); + + const newStoredQty = Math.min(detailTotalQty, (Number(detailRow.stored_quantity) || 0) + thisStoredQty); + // 明细实际数量表示的是该明细的收货量,合并后该 SKU 的明细可能有多条 + // 简化:如果该明细被完全用完则设为 all,否则 waiting(等待手工上架) + const newStorageStatus = newStoredQty >= detailTotalQty ? 'all' : 'waiting'; + + await ctx.model.ReceivingDetail.update({ + storage_status: newStorageStatus, + stored_quantity: newStoredQty, + updated_at: new Date(), + }, { + where: { id: detailId }, + transaction, + }); + } + } + + // ────────── 11. 操作日志 ────────── + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'entry_order', + businessId: entryOrderId, + operationCode: 'ENTRY_ORDER_QUICK_PUTAWAY', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + storeId, + receivingId, + entryOrderCode, + receivingNumber: receiving.receiving_number, + totalLines: groupedItems.length, + }, + transaction, + }); + } catch (logErr) { + ctx.logger.warn('[inventory.quickPutaway] 写入操作日志失败,不影响业务', logErr); + } + + // ────────── 12. 提交事务 ────────── + await transaction.commit(); + + ctx.logger.info(`[inventory.quickPutaway] 快捷入库完成 entryOrderId=${entryOrderId} receivingId=${receivingId} lines=${groupedItems.length}`); + + return { + code: 200, + message: '快捷入库成功', + data: { + entry_order_id: entryOrderId, + entry_order_code: entryOrderCode, + order_status: 'PENDING', + receiving_id: receivingId, + total_lines: groupedItems.length, + total_quantity: groupedItems.reduce((sum, g) => sum + g.total_quantity, 0), + }, + }; + } catch (error) { + await transaction.rollback(); + ctx.logger.error(`[inventory.quickPutaway] 快捷入库异常 receivingId=${receivingId}: ${error.message}`, error.stack); + return { code: 500, message: `系统异常: ${error.message}`, data: null }; + } + } + + /** + * 生成入库单号。 + * 格式:SCRK + 年月日 + 4位流水号 + * + * @param {number} warehouseId 仓库ID + * @param {number} storeId 货主ID + * @param {Object} transaction 数据库事务 + * @return {Promise} 生成的入库单号 + */ + async _generateEntryOrderCode(warehouseId, storeId, transaction) { + const { ctx, app } = this; + const now = new Date(); + const dateStr = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}`; + const prefix = `SCRK${dateStr}`; + + // 查询当天该仓库+货主下已有的最大入库单号 + const lastOrder = await ctx.model.EntryOrder.findOne({ + where: { + entry_order_code: { [app.Sequelize.Op.like]: `${prefix}%` }, + warehouse_id: warehouseId, + store_id: storeId, + }, + order: [[ 'entry_order_code', 'DESC' ]], + attributes: [ 'entry_order_code' ], + transaction, + raw: true, + paranoid: false, + }); + + let seq = 1; + if (lastOrder && lastOrder.entry_order_code) { + const seqPart = lastOrder.entry_order_code.slice(prefix.length); + const seqNum = parseInt(seqPart, 10); + if (!Number.isNaN(seqNum)) { + seq = seqNum + 1; + } + } + + return `${prefix}${String(seq).padStart(4, '0')}`; + } } module.exports = InventoryService; diff --git a/app/service/systems/storage/receiving.js b/app/service/systems/storage/receiving.js index a4d4d81..cc93682 100644 --- a/app/service/systems/storage/receiving.js +++ b/app/service/systems/storage/receiving.js @@ -35,9 +35,12 @@ class ReceivingService extends Service { * @param {number} [pageParams.page=1] 页码 * @param {number} [pageParams.pageSize=20] 每页条数 * @param {Object} [sortParams] 排序参数 + * @param {Object} [options] 额外选项 + * @param {boolean} [options.filterDepleted=false] 是否过滤掉无可再用量的收货单 + * @param {number} [options.entry_order_id] 可选,按入库单商品交集过滤:只返回"至少有一条明细的 system_product_id 在入库单明细中"的收货单 * @return {Promise} 列表、分页与汇总信息 */ - async getReceivingList(where, pageParams = {}, sortParams = {}) { + async getReceivingList(where, pageParams = {}, sortParams = {}, options = {}) { const { ctx, app, @@ -58,6 +61,7 @@ class ReceivingService extends Service { sortField = 'id', sortOrder = 'DESC', } = sortParams; + const { filterDepleted = false, entry_order_id: entryOrderId } = options; const queryOptions = { where: { @@ -175,14 +179,147 @@ class ReceivingService extends Service { }, ]; + // 可选过滤:排除无可再用量的收货单 + let filteredReceivingIds = null; + if (filterDepleted) { + const candidateRows = await ctx.model.Receiving.findAll({ + attributes: [ 'id' ], + where: queryOptions.where, + include, + distinct: true, + raw: true, + }); + const candidateIds = candidateRows.map(r => r.id); + + if (candidateIds.length > 0) { + // 1. 候选收货单明细的 actual_quantity 总和(按 receiving_id 分组) + const detailSums = await ctx.model.ReceivingDetail.findAll({ + attributes: [ + 'receiving_id', + [ Sequelize.fn('SUM', Sequelize.col('actual_quantity')), 'total_actual' ], + ], + where: { receiving_id: { [Op.in]: candidateIds } }, + group: [ 'receiving_id' ], + raw: true, + }); + const totalActualMap = {}; + for (const row of detailSums) { + totalActualMap[row.receiving_id] = Number(row.total_actual) || 0; + } + + // 2. 这些明细对应的 committed 绑定量(按 receiving_detail_id 分组) + const detailIds = detailSums.length > 0 + ? (await ctx.model.ReceivingDetail.findAll({ + attributes: [ 'id' ], + where: { receiving_id: { [Op.in]: candidateIds } }, + raw: true, + })).map(r => r.id) + : []; + + const committedByDetailId = {}; + if (detailIds.length > 0) { + const bindingRows = await ctx.model.EntryReceivingBinding.findAll({ + attributes: [ + 'receiving_detail_id', + [ Sequelize.fn('SUM', Sequelize.col('allocated_quantity')), 'committed_sum' ], + ], + where: { + receiving_detail_id: { [Op.in]: detailIds }, + status: 'committed', + }, + group: [ 'receiving_detail_id' ], + raw: true, + }); + for (const row of bindingRows) { + committedByDetailId[row.receiving_detail_id] = Number(row.committed_sum) || 0; + } + } + + // 3. 计算每个收货单的剩余可用量 = SUM(actual_quantity) - SUM(committed) + const idToDetailIdsMap = {}; + if (detailIds.length > 0) { + const detailIdRows = await ctx.model.ReceivingDetail.findAll({ + attributes: [ 'id', 'receiving_id' ], + where: { id: { [Op.in]: detailIds } }, + raw: true, + }); + for (const d of detailIdRows) { + if (!idToDetailIdsMap[d.receiving_id]) idToDetailIdsMap[d.receiving_id] = []; + idToDetailIdsMap[d.receiving_id].push(d.id); + } + } + + const remainingByReceivingId = {}; + for (const receivingId of candidateIds) { + const totalActual = totalActualMap[receivingId] || 0; + const detailIdList = idToDetailIdsMap[receivingId] || []; + const totalCommitted = detailIdList.reduce((sum, did) => sum + (committedByDetailId[did] || 0), 0); + remainingByReceivingId[receivingId] = totalActual - totalCommitted; + } + + // 过滤:只保留剩余可用量 > 0 的收货单 + filteredReceivingIds = candidateIds.filter(id => remainingByReceivingId[id] > 0); + } else { + filteredReceivingIds = []; + } + } + + // 可选过滤:按入库单商品交集过滤(只返回 system_product_id 有交集的收货单) + let intersectionFilteredIds = null; + if (entryOrderId) { + // 1. 查该入库单的所有 entry_items → stock_id 集合 + const entryItemRows = await ctx.model.EntryItems.findAll({ + where: { order_id: entryOrderId }, + attributes: [ 'stock_id' ], + raw: true, + }); + const entrySpIdSet = new Set(entryItemRows.map(r => r.stock_id).filter(Boolean)); + + if (entrySpIdSet.size === 0) { + // 入库单无明细 → 不返回任何收货单 + intersectionFilteredIds = []; + } else { + // 2. 查所有收货单明细,找出 system_product_id 在 entrySpIdSet 中的收货单 ID + const matchingDetailRows = await ctx.model.ReceivingDetail.findAll({ + attributes: [ 'receiving_id' ], + where: { + system_product_id: { [Op.in]: [ ...entrySpIdSet ] }, + }, + group: [ 'receiving_id' ], + raw: true, + }); + intersectionFilteredIds = matchingDetailRows.map(r => r.receiving_id); + } + } + + // 合并 filterDepleted 和 entry_order_id 的过滤结果 + let combinedFilteredIds = null; + if (filteredReceivingIds !== null || intersectionFilteredIds !== null) { + if (filteredReceivingIds !== null && intersectionFilteredIds !== null) { + // 两个过滤都启用 → 取交集 + const intersectionSet = new Set(intersectionFilteredIds); + combinedFilteredIds = filteredReceivingIds.filter(id => intersectionSet.has(id)); + } else if (filteredReceivingIds !== null) { + combinedFilteredIds = filteredReceivingIds; + } else { + combinedFilteredIds = intersectionFilteredIds; + } + } + + // 如果启用了过滤,用过滤后的 ID 做最终查询 + const finalWhere = combinedFilteredIds !== null + ? { id: { [Op.in]: combinedFilteredIds } } + : queryOptions.where; + const [ total, data ] = await Promise.all([ ctx.model.Receiving.count({ - where: queryOptions.where, + where: finalWhere, include, distinct: true, }), ctx.model.Receiving.findAll({ ...queryOptions, + where: finalWhere, include, limit: parseInt(pageSize), offset: parseInt(offset), @@ -217,8 +354,9 @@ class ReceivingService extends Service { } const processedData = data.map(item => { - const availableQuantity = Math.max(0, item.quantity - item.locked_quantity); - const lockRate = item.quantity > 0 ? (item.locked_quantity / item.quantity * 100).toFixed(2) : 0; + // 注意:wms_receiving 表中没有 locked_quantity 字段,total_quantity 为商品总数量 + const availableQuantity = Math.max(0, item.total_quantity || 0); + const lockRate = 0; const itemImages = images .filter(row => parseInt(row.business_id) === item.id) .map(row => row.file.file_url); @@ -234,9 +372,9 @@ class ReceivingService extends Service { }); const summary = { - total_quantity: data.reduce((sum, item) => sum + item.quantity, 0), - total_locked: data.reduce((sum, item) => sum + item.locked_quantity, 0), - total_available: data.reduce((sum, item) => sum + Math.max(0, item.quantity - item.locked_quantity), 0), + total_quantity: data.reduce((sum, item) => sum + (item.total_quantity || 0), 0), + total_locked: 0, + total_available: data.reduce((sum, item) => sum + (item.total_quantity || 0), 0), total_items: data.length, }; @@ -4218,6 +4356,157 @@ class ReceivingService extends Service { } } + /** + * PDA 扫码定位收货明细:通过入库单ID + 扫描条码快速定位收货明细。 + * 搜索策略: + * 1. 通过 entry_order_id → wms_entry_order_receiving 查出关联的 receiving_id 列表; + * 2. 查出所有未绑定的收货明细(仅按 receiving_id IN + 排除已绑定过滤); + * 3. 收集明细的 system_product_id,批量调用 getStockDetails 获取条码信息; + * 4. 在内存中遍历明细进行精确匹配: + * - 若 barcode 为纯数字,优先按明细 ID 精确匹配; + * - 再按 getStockDetails 返回的 barcodes[].barcode 精确匹配商品条码; + * 5. 返回所有匹配的明细列表(同一条码可能匹配到多条收货明细)。 + * @param {number} entryOrderId 入库单ID + * @param {string} barcode 扫描条码(商品条码/箱唛/托盘唛/明细ID) + * @return {Promise} 包含 code、message 与匹配明细列表 data.list 的结果对象 + */ + async scanDetail(entryOrderId, barcode) { + const { ctx, app } = this; + const { Op } = app.Sequelize; + const warehouseId = ctx.user?.store_id; + + // 参数校验 + if (!warehouseId) { + return { code: 0, message: '用户未绑定仓库', data: null }; + } + if (!entryOrderId || Number(entryOrderId) <= 0) { + return { code: 0, message: '入库单ID不能为空', data: null }; + } + if (!barcode || String(barcode).trim() === '') { + return { code: 0, message: '扫描条码不能为空', data: null }; + } + + const normalizedBarcode = String(barcode).trim(); + const normalizedEntryOrderId = Number(entryOrderId); + + try { + // 1. 验证入库单存在且属于当前仓库 + const entryOrder = await ctx.model.EntryOrder.findOne({ + where: { + id: normalizedEntryOrderId, + warehouse_id: warehouseId, + }, + attributes: [ 'id' ], + raw: true, + }); + + if (!entryOrder) { + return { code: 0, message: '入库单不存在或无权访问', data: null }; + } + + // 2. 通过 wms_entry_order_receiving 查出关联的 receiving_id 列表 + const entryReceivingRows = await ctx.model.EntryOrderReceiving.findAll({ + where: { entry_order_id: normalizedEntryOrderId }, + attributes: [ 'receiving_id' ], + raw: true, + }); + + const receivingIds = entryReceivingRows.map(r => r.receiving_id).filter(Boolean); + if (receivingIds.length === 0) { + return { code: 0, message: '该入库单尚未关联收货单', data: null }; + } + + // 排除已绑定的收货明细(wms_entry_receiving_binding 中有记录且未软删除) + const notBoundCondition = app.Sequelize.literal( + 'NOT EXISTS (SELECT 1 FROM wms_entry_receiving_binding erb WHERE erb.receiving_detail_id = wms_receiving_detail.id AND erb.deleted_at IS NULL)' + ); + + // 3. 查出所有未绑定的收货明细(不再在 SQL 层做 barcode 模糊匹配) + const details = await ctx.model.ReceivingDetail.findAll({ + where: { + [Op.and]: [ + { receiving_id: { [Op.in]: receivingIds } }, + notBoundCondition, + ], + }, + raw: true, + }); + + if (details.length === 0) { + return { code: 0, message: '未找到可用的收货明细', data: null }; + } + + // 4. 收集所有明细的 system_product_id,批量调用 getStockDetails 获取条码 + const stockIdSet = new Set(); + for (const d of details) { + if (d.system_product_id != null) { + stockIdSet.add(Number(d.system_product_id)); + } + } + const stockIds = [ ...stockIdSet ]; + + /** @type {Map} */ + const stockDetailMap = new Map(); + if (stockIds.length > 0) { + const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { warehouseId }); + for (const sd of stockDetails) { + if (sd && sd.id != null) { + stockDetailMap.set(sd.id, sd); + } + } + } + + // 5. 在内存中遍历明细,精确匹配,收集所有命中 + const isNumericBarcode = /^\d+$/.test(normalizedBarcode); + const matchedDetails = []; + + for (const detail of details) { + // 优先按明细 ID 精确匹配(托盘唛头场景) + if (isNumericBarcode && detail.id === Number(normalizedBarcode)) { + matchedDetails.push(detail); + continue; + } + + // 按商品条码精确匹配 + const stockDetail = stockDetailMap.get(detail.system_product_id); + if (stockDetail && Array.isArray(stockDetail.barcodes)) { + const barcodeMatch = stockDetail.barcodes.some( + bc => bc.barcode === normalizedBarcode + ); + if (barcodeMatch) { + matchedDetails.push(detail); + } + } + } + + if (matchedDetails.length === 0) { + return { code: 0, message: '未找到匹配的收货明细', data: null }; + } + + const list = matchedDetails.map(matchedDetail => ({ + detail_id: matchedDetail.id, + receiving_id: matchedDetail.receiving_id, + barcode: matchedDetail.barcode || '', + product_name: matchedDetail.product_name || '', + actual_quantity: matchedDetail.actual_quantity || 0, + receiving_status: matchedDetail.receiving_status || '', + stock: stockDetailMap.get(Number(matchedDetail.system_product_id)) || null, + })); + + return { + code: 200, + message: '查询成功', + data: { + list, + total: list.length, + }, + }; + } catch (error) { + ctx.logger.error('[receiving.scanDetail] 扫码定位收货明细失败', error); + return { code: 500, message: `服务器错误: ${error.message}`, data: null }; + } + } + } module.exports = ReceivingService; diff --git a/config/config.default.js b/config/config.default.js index 2627a9e..c012498 100644 --- a/config/config.default.js +++ b/config/config.default.js @@ -130,7 +130,7 @@ module.exports = appInfo => { 'audio/x-m4a': 'audio', }; config.cors = { - origin: '*', // 允许所有源,生产环境应指定具体域名 + origin: (ctx) => ctx.get('Origin'), // 动态返回请求源,配合 credentials: true 使用 allowMethods: 'GET,HEAD,PUT,POST,DELETE,PATCH,OPTIONS', exposeHeaders: 'Authorization', credentials: true, // 允许携带 cookie @@ -180,6 +180,7 @@ module.exports = appInfo => { config.jwt = { expiresIn: 14400, + renewThreshold: 7200, secret: 'E5#ex.g@,GfL_8?', }; diff --git a/database/migrations/20260629-add-waiting-storage-status.js b/database/migrations/20260629-add-waiting-storage-status.js new file mode 100644 index 0000000..32f8792 --- /dev/null +++ b/database/migrations/20260629-add-waiting-storage-status.js @@ -0,0 +1,76 @@ +'use strict'; + +/** + * 打印迁移阶段对应的数据库连接上下文信息。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {'up'|'down'} phase 迁移阶段。 + * @param {string} table 迁移目标表名。 + * @return {Promise} 无返回值。 + */ +const logMigrationDbContext = async (queryInterface, phase, table) => { + try { + const [rows] = await queryInterface.sequelize.query( + 'SELECT DATABASE() AS db_name, @@hostname AS db_host, @@port AS db_port, CURRENT_USER() AS db_user' + ); + const dbContext = Array.isArray(rows) && rows.length > 0 ? rows[0] : {}; + console.log( + `[Migration DB Context] phase=${phase}; table=${table}; db_name=${dbContext.db_name || 'unknown'}; db_host=${dbContext.db_host || 'unknown'}; db_port=${dbContext.db_port || 'unknown'}; db_user=${dbContext.db_user || 'unknown'}` + ); + } catch (error) { + console.warn( + `[Migration DB Context] 获取连接信息失败: phase=${phase}; table=${table}; reason=${error.message}` + ); + } +}; + +/** + * Migration: 为 wms_receiving 和 wms_receiving_detail 表的 storage_status 列新增 waiting 枚举值 + * + * 正向 SQL: + * ALTER TABLE wms_receiving MODIFY COLUMN storage_status ENUM('none','waiting','partial','all') NOT NULL DEFAULT 'none' COMMENT '入库状态:none-未入库, waiting-等待入库, partial-部分入库, all-全部入库'; + * ALTER TABLE wms_receiving_detail MODIFY COLUMN storage_status ENUM('none','waiting','partial','all') NOT NULL DEFAULT 'none' COMMENT '入库状态:none-未入库, waiting-等待入库, partial-部分入库, all-全部入库'; + * + * 回滚 SQL: + * ALTER TABLE wms_receiving MODIFY COLUMN storage_status ENUM('none','partial','all') NOT NULL DEFAULT 'none' COMMENT '入库状态:none-未入库, partial-部分入库, all-全部入库'; + * ALTER TABLE wms_receiving_detail MODIFY COLUMN storage_status ENUM('none','partial','all') NOT NULL DEFAULT 'none' COMMENT '入库状态:none-未入库, partial-部分入库, all-全部入库'; + */ + +const UP_SQL_RECEIVING = `ALTER TABLE wms_receiving MODIFY COLUMN storage_status ENUM('none','waiting','partial','all') NOT NULL DEFAULT 'none' COMMENT '入库状态:none-未入库, waiting-等待入库, partial-部分入库, all-全部入库'`; +const DOWN_SQL_RECEIVING = `ALTER TABLE wms_receiving MODIFY COLUMN storage_status ENUM('none','partial','all') NOT NULL DEFAULT 'none' COMMENT '入库状态:none-未入库, partial-部分入库, all-全部入库'`; + +const UP_SQL_DETAIL = `ALTER TABLE wms_receiving_detail MODIFY COLUMN storage_status ENUM('none','waiting','partial','all') NOT NULL DEFAULT 'none' COMMENT '入库状态:none-未入库, waiting-等待入库, partial-部分入库, all-全部入库'`; +const DOWN_SQL_DETAIL = `ALTER TABLE wms_receiving_detail MODIFY COLUMN storage_status ENUM('none','partial','all') NOT NULL DEFAULT 'none' COMMENT '入库状态:none-未入库, partial-部分入库, all-全部入库'`; + +module.exports = { + /** + * 执行正向迁移,为 storage_status 列新增 waiting 枚举值。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + up: async (queryInterface, Sequelize) => { + await logMigrationDbContext(queryInterface, 'up', 'wms_receiving'); + await queryInterface.sequelize.query(UP_SQL_RECEIVING); + console.log('[Migration] wms_receiving.storage_status 已新增 waiting 枚举值'); + + await logMigrationDbContext(queryInterface, 'up', 'wms_receiving_detail'); + await queryInterface.sequelize.query(UP_SQL_DETAIL); + console.log('[Migration] wms_receiving_detail.storage_status 已新增 waiting 枚举值'); + }, + + /** + * 执行回滚迁移,移除 waiting 枚举值,恢复为原有枚举。 + * @param {import('sequelize').QueryInterface} queryInterface 查询接口。 + * @param {import('sequelize')} Sequelize Sequelize 实例。 + * @return {Promise} 无返回值。 + */ + down: async (queryInterface, Sequelize) => { + await logMigrationDbContext(queryInterface, 'down', 'wms_receiving'); + await queryInterface.sequelize.query(DOWN_SQL_RECEIVING); + console.log('[Migration] wms_receiving.storage_status 已移除 waiting 枚举值'); + + await logMigrationDbContext(queryInterface, 'down', 'wms_receiving_detail'); + await queryInterface.sequelize.query(DOWN_SQL_DETAIL); + console.log('[Migration] wms_receiving_detail.storage_status 已移除 waiting 枚举值'); + }, +}; diff --git a/database/migrations/20260630160000-create-wms-order-stockout.js b/database/migrations/20260630160000-create-wms-order-stockout.js new file mode 100644 index 0000000..609fc87 --- /dev/null +++ b/database/migrations/20260630160000-create-wms-order-stockout.js @@ -0,0 +1,309 @@ +'use strict'; + +const MAIN_TABLE = 'wms_order_stockout'; +const ITEMS_TABLE = 'wms_order_stockout_items'; + +/** + * 创建奇门出库单主表与明细表。 + * + * - wms_order_stockout:出库单主表(对应奇门 stockout.create 的 节点) + * - wms_order_stockout_items:出库明细表(对应 节点) + * + * 幂等:如果表已存在则跳过创建。 + */ +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + + const exists = name => + tables.some(t => (typeof t === 'string' ? t : t.tableName) === name); + + // ----------------------- 主表 ----------------------- + if (!exists(MAIN_TABLE)) { + await queryInterface.createTable(MAIN_TABLE, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + stockout_order_code: { + type: Sequelize.STRING(50), + allowNull: false, + comment: '出库单号(对应奇门 deliveryOrderCode)', + }, + order_type: { + type: Sequelize.STRING(50), + allowNull: false, + comment: '业务类型(JYCK/HHCK/BFCK/QTCK 等)', + }, + total_order_lines: { + type: Sequelize.INTEGER(11), + allowNull: false, + defaultValue: 0, + comment: '单据总行数', + }, + order_create_time: { + type: Sequelize.DATE, + allowNull: true, + comment: '订单创建时间(对应奇门 createTime)', + }, + source_type: { + type: Sequelize.ENUM('WMS', 'API', 'QM'), + allowNull: false, + defaultValue: 'QM', + comment: '来源类型', + }, + order_status: { + type: Sequelize.ENUM('CREATING', 'CREATED', 'PENDING', 'COMPLETED', 'CANCELLED'), + allowNull: false, + defaultValue: 'CREATED', + comment: '订单状态', + }, + sync_status: { + type: Sequelize.ENUM('PENDING', 'SUCCESS', 'FAILED'), + allowNull: false, + defaultValue: 'PENDING', + comment: '同步状态', + }, + sync_message: { + type: Sequelize.TEXT, + allowNull: true, + comment: '同步返回信息', + }, + warehouse_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID', + }, + store_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '货主ID', + }, + store_name: { + type: Sequelize.STRING(200), + allowNull: true, + comment: '货主名称快照', + }, + warehouse_name: { + type: Sequelize.STRING(200), + allowNull: true, + comment: '仓库名称快照', + }, + qimen_owner_code: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '奇门货主code(对应 ownerCode)', + }, + qimen_warehouse_code: { + type: Sequelize.STRING(100), + allowNull: true, + comment: '奇门仓库code(对应 warehouseCode)', + }, + remark: { + type: Sequelize.STRING(500), + allowNull: true, + comment: '备注', + }, + extend_props: { + type: Sequelize.JSON, + allowNull: true, + comment: '扩展属性', + }, + is_enabled: { + type: Sequelize.TINYINT(1), + allowNull: false, + defaultValue: 1, + comment: '是否启用', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + deleted_at: { + type: Sequelize.DATE, + allowNull: true, + comment: '软删除时间', + }, + }); + + // 唯一索引:(stockout_order_code, warehouse_id, store_id) + await queryInterface.addIndex(MAIN_TABLE, [ 'stockout_order_code', 'warehouse_id', 'store_id' ], { + unique: true, + name: 'uk_stockout_order_code', + }); + + // 辅助查询索引 + await queryInterface.addIndex(MAIN_TABLE, [ 'order_type' ], { + name: 'idx_order_type', + }); + await queryInterface.addIndex(MAIN_TABLE, [ 'order_status' ], { + name: 'idx_order_status', + }); + await queryInterface.addIndex(MAIN_TABLE, [ 'sync_status' ], { + name: 'idx_sync_status', + }); + await queryInterface.addIndex(MAIN_TABLE, [ 'source_type' ], { + name: 'idx_source_type', + }); + await queryInterface.addIndex(MAIN_TABLE, [ 'warehouse_id', 'store_id' ], { + name: 'idx_warehouse_store', + }); + await queryInterface.addIndex(MAIN_TABLE, [ 'order_create_time' ], { + name: 'idx_order_create_time', + }); + await queryInterface.addIndex(MAIN_TABLE, [ 'is_enabled' ], { + name: 'idx_is_enabled', + }); + await queryInterface.addIndex(MAIN_TABLE, [ 'deleted_at' ], { + name: 'idx_deleted_at', + }); + } + + // ----------------------- 明细表 ----------------------- + if (!exists(ITEMS_TABLE)) { + await queryInterface.createTable(ITEMS_TABLE, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + order_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '出库单ID,外键关联 wms_order_stockout.id', + }, + out_biz_code: { + type: Sequelize.STRING(255), + allowNull: true, + comment: '外部业务编码(幂等键)', + }, + order_line_no: { + type: Sequelize.STRING(50), + allowNull: false, + comment: '订单行号(对应奇门 orderLineNo)', + }, + owner_code: { + type: Sequelize.STRING(50), + allowNull: true, + comment: '货主编码(对应奇门 ownerCode)', + }, + item_code: { + type: Sequelize.STRING(50), + allowNull: true, + comment: '商品编码(对应奇门 itemCode)', + }, + item_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: true, + comment: 'WMS商品ID(对应奇门 itemId)', + }, + item_name: { + type: Sequelize.STRING(200), + allowNull: true, + comment: '商品名称', + }, + plan_qty: { + type: Sequelize.INTEGER(12), + allowNull: true, + comment: '计划数量(对应奇门 planQty)', + }, + actual_qty: { + type: Sequelize.INTEGER(12), + allowNull: false, + defaultValue: 0, + comment: '实发数量', + }, + inventory_type: { + type: Sequelize.STRING(50), + allowNull: true, + comment: '库存类型(ZP正品/CC残次等)', + }, + stock_id: { + type: Sequelize.BIGINT(20), + allowNull: true, + comment: '库存ID,外键关联 wms_stock_warehouse.id', + }, + extend_props: { + type: Sequelize.JSON, + allowNull: true, + comment: '扩展属性', + }, + created_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP'), + comment: '创建时间', + }, + updated_at: { + type: Sequelize.DATE, + allowNull: false, + defaultValue: Sequelize.literal('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'), + comment: '更新时间', + }, + }); + + // 唯一索引:(order_id, order_line_no) + await queryInterface.addIndex(ITEMS_TABLE, [ 'order_id', 'order_line_no' ], { + unique: true, + name: 'uk_order_line_no', + }); + + // 辅助索引 + await queryInterface.addIndex(ITEMS_TABLE, [ 'order_id' ], { + name: 'idx_order_id', + }); + await queryInterface.addIndex(ITEMS_TABLE, [ 'stock_id' ], { + name: 'idx_stock_id', + }); + await queryInterface.addIndex(ITEMS_TABLE, [ 'item_code' ], { + name: 'idx_item_code', + }); + await queryInterface.addIndex(ITEMS_TABLE, [ 'out_biz_code' ], { + name: 'idx_out_biz_code', + }); + + // 外键约束 + await queryInterface.addConstraint(ITEMS_TABLE, { + fields: [ 'order_id' ], + type: 'foreign key', + name: 'fk_items_order_id', + references: { + table: MAIN_TABLE, + field: 'id', + }, + onDelete: 'CASCADE', + onUpdate: 'CASCADE', + }); + + await queryInterface.addConstraint(ITEMS_TABLE, { + fields: [ 'stock_id' ], + type: 'foreign key', + name: 'fk_items_stock_id', + references: { + table: 'wms_stock_warehouse', + field: 'id', + }, + onDelete: 'RESTRICT', + onUpdate: 'CASCADE', + }); + } + }, + + down: async queryInterface => { + await queryInterface.dropTable(ITEMS_TABLE); + await queryInterface.dropTable(MAIN_TABLE); + }, +}; diff --git a/docs/order-workbench-list-api.md b/docs/order-workbench-list-api.md index c6dbf67..7b99c0a 100644 --- a/docs/order-workbench-list-api.md +++ b/docs/order-workbench-list-api.md @@ -118,6 +118,7 @@ | oaid | string | OAID | 设备/终端标识 | | sync_status | enum | 同步状态 | padding=待同步,fin=完成,error=失败 | | store_id | number | 货主ID | 货主主键 | +| store_remark | string | 货主备注 | 来自 wms_store_warehouse.store_remask,服务层按 store_id+warehouse_id 聚合填充 | | warehouse_id | number | 仓库ID | 仓库主键 | | from_key | number | 来源键 | 来源系统键值 | | items | string | 商品JSON字符串 | 原始商品明细 JSON | diff --git a/order_todo.md b/docs/order_todo.md similarity index 100% rename from order_todo.md rename to docs/order_todo.md diff --git a/docs/storage-receiving-api.md b/docs/storage-receiving-api.md index 185f289..fdee9fe 100644 --- a/docs/storage-receiving-api.md +++ b/docs/storage-receiving-api.md @@ -467,7 +467,7 @@ curl -X POST "http://127.0.0.1:6060/system?method=storage.receiving.bindDetailPr |---|---|---| | `storage.entry.bindReceivingDetails` | 入库单明细与收货明细逐行绑定(基于 `wms_entry_receiving_binding` 表),关系已改为 `wms_entry_order_receiving` 主表级关联 | 不再需要,入库单与收货单直接通过主表关联 | | `storage.entry.unbindReceivingDetails` | 同上,逐行解绑已无必要 | 不再需要 | -| `storage.inventory.quickPutaway` | 单一收货单快捷入库,功能受限 | `storage.inventory.matchPutaway`(支持多收货单+多入库单批量匹配入库) | +| `storage.inventory.quickPutaway` | 单一收货单快捷转入库单(已重新实现):按 stock_id 合并收货明细创建入库单(SCRK,自动审批到 PENDING),写入主表级绑定 | `storage.entry.commitDirectInbound`(导入/PDA 入库完成确认) | ### 14.4 核心方法职责 diff --git a/methods/changes/2026-06-24-add-bind-receiving-details.json b/methods/changes/2026-06-24-add-bind-receiving-details.json deleted file mode 100644 index 37a9170..0000000 --- a/methods/changes/2026-06-24-add-bind-receiving-details.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "date": "2026-06-24", - "type": "addition", - "method": "storage.entry.bindReceivingDetails", - "summary": "新增批量绑定入库单明细与收货单明细接口,支持明细级数量分配与部分成功", - "related": ["storage.entry.get 追加 available_receiving_details 字段"] -} diff --git a/methods/changes/2026-06-24-deprecate-manual-match-entry-order.json b/methods/changes/2026-06-24-deprecate-manual-match-entry-order.json deleted file mode 100644 index 64c2dc7..0000000 --- a/methods/changes/2026-06-24-deprecate-manual-match-entry-order.json +++ /dev/null @@ -1,7 +0,0 @@ -{ - "date": "2026-06-24", - "type": "deprecation", - "method": "storage.receiving.manualMatchEntryOrder", - "summary": "废弃手动匹配入库单收货单接口,由 storage.entry.bindReceivingDetails 替代", - "migration": "使用 storage.entry.get(含 available_receiving_details 元数据)加载可匹配的收货单明细,然后调用 storage.entry.bindReceivingDetails 批量提交绑定" -} diff --git a/methods/changes/2026.05.08-system-06.json b/methods/changes/2026.05.08-system-06.json deleted file mode 100644 index 66a7b16..0000000 --- a/methods/changes/2026.05.08-system-06.json +++ /dev/null @@ -1,16 +0,0 @@ -[ - { - "version": "2026.05.08-system-06", - "date": "2026-05-08", - "summary": "新增取消拣货任务接口:order.wave.wavePickTaskCancel", - "methods": [ - "order.wave.wavePickTaskCancel" - ], - "notes": [ - "接口功能:取消拣货任务,同时释放关联波次(物理删除波次记录,订单回池)、解绑拣货车、写操作日志。", - "限制:仅允许在任务状态为 0(待开始)、1(拣货中)、2(待复核)时取消;状态为 3(已完成)或 9(已取消)时禁止取消,返回 400。", - "事务内操作:将任务状态更新为 9(已取消)、删除关联波次、清空订单 wave_id(回池)、解绑拣货车、写入 action_log 与 order_pick_trace;若有任一步骤失败则回滚并返回 500。" - ], - "type": "added" - } -] diff --git a/methods/changes/2026.05.13-system-01.json b/methods/changes/2026.05.13-system-01.json deleted file mode 100644 index e46b3d6..0000000 --- a/methods/changes/2026.05.13-system-01.json +++ /dev/null @@ -1,17 +0,0 @@ -[ - { - "version": "2026.05.13-system-01", - "date": "2026-05-13", - "summary": "完善 print.send 的 API 文档与返回说明", - "methods": [ - "print.send" - ], - "notes": [ - "补充请求参数说明:computerId、printer、template、data、type 标为必填,count、timestamp 保持可选。", - "补充 template 的子字段说明:page_width、page_height、template_content。", - "补充响应结构:flag、code、message、printId;其中成功时 code=200。", - "补充错误码说明:1001 对应不支持的打印类型,504 对应打印任务发送失败(包含打印机不存在、脱机、通讯失败等场景)。" - ], - "type": "updated" - } -] diff --git a/methods/changes/2026.05.20-system-01.json b/methods/changes/2026.05.20-system-01.json deleted file mode 100644 index 8424c5d..0000000 --- a/methods/changes/2026.05.20-system-01.json +++ /dev/null @@ -1,19 +0,0 @@ -[ - { - "version": "2026.05.20-system-01", - "date": "2026-05-20", - "summary": "新增订单复核模块方法:order.recheckOrder.scanOrder、order.recheckOrder.confirmRecheck", - "methods": [ - "order.recheckOrder.scanOrder", - "order.recheckOrder.confirmRecheck" - ], - "notes": [ - "用途:扫码查询订单明细(scanOrder);确认复核并落库 wms_recheck_task(confirmRecheck)。", - "scanOrder 返回运单号或车号匹配的订单头、商品明细、运单信息与相关日志;confirmRecheck 将复核结果写入 wms_recheck_task 并返回复核摘要信息(order_id、recheck_status、recheck_time、review_no)。", - "变更概要:confirmRecheck 改为按 order_id 进行复核(兼容 id/orderId);scanOrder 返回准确的 order_id 供前端直接使用;新增支持:查找范围包含 wms_wave_pick_task 的车号快照(current_cart_code_snapshot / wms_wave_pick_task_order.cart_code_snapshot)。", - "规则调整:移除打印状态约束,改为未拣货约束。", - "scanOrder 在车号命中场景按波次类型返回不同结构(1/5 groups, 2 orders, 3 pick_groups, 4 box_groups)。" - ], - "type": "added" - } -] \ No newline at end of file diff --git a/methods/changes/2026.05.20-system-03.json b/methods/changes/2026.05.20-system-03.json deleted file mode 100644 index b8ed107..0000000 --- a/methods/changes/2026.05.20-system-03.json +++ /dev/null @@ -1,18 +0,0 @@ -[ - { - "version": "2026.05.20-system-03", - "date": "2026-05-20", - "summary": "新增 storeWarehouse.store.queryPrintQuantityLogs:按 store_id 分页查询面单余额变更日志", - "methods": [ - "storeWarehouse.store.queryPrintQuantityLogs" - ], - "notes": [ - "新增方法:storeWarehouse.store.queryPrintQuantityLogs,用于按货主(store_id)分页查询面单余额变更日志。", - "入参:store_id(必填)、page(可选)、page_size / pageSize(可选,兼容别名)。", - "仅同步 methods/system.json 与本变更记录,不修改业务代码或测试。", - "返回:使用默认分页格式,响应在 `data` 下包含 `list`(变更日志数组)和 `pagination` 对象,`pagination` 字段:`page`、`pageSize`、`total`、`totalPages`、`hasPrevious`、`hasNext`。" - ], - "type": "added", - "module": "storeWarehouse" - } -] diff --git a/methods/changes/2026.05.28-system-01.json b/methods/changes/2026.05.28-system-01.json deleted file mode 100644 index 9505497..0000000 --- a/methods/changes/2026.05.28-system-01.json +++ /dev/null @@ -1,19 +0,0 @@ -[ - { - "version": "2026.05.28-system-01", - "date": "2026-05-28", - "summary": "新增包材相关表与在订单快递表新增包材关联字段(wms_package_material / wms_package_supplier / wms_order_express)", - "methods": [], - "notes": [ - "新增表 wms_package_material:主要字段 id, warehouse_id, material_code, material_name, material_type, spec, length, width, height, weight, cost_price, status, version, created_at, updated_at;索引:idx_wms_package_material_warehouse_id(warehouse_id),uk_wms_package_material_warehouse_material_code(warehouse_id + material_code 唯一)。", - "新增表 wms_package_supplier:主要字段 id, warehouse_id, supplier_code, supplier_name, contact_name, contact_phone, status, version, created_at, updated_at;索引:idx_wms_package_supplier_warehouse_id(warehouse_id),uk_wms_package_supplier_warehouse_supplier_code(warehouse_id + supplier_code 唯一)。", - "修改表 wms_order_express:新增可空字段 package_material_id (BIGINT unsigned) 与 package_material_name_snapshot (VARCHAR(128));新增索引 idx_wms_order_express_package_material_id(package_material_id)。", - "回滚要点:迁移脚本的 down 实现会移除上述索引与列,并删除新增的两张表(详见 database/migrations/20260528090000-create-wms-package-material-and-supplier.js 与 database/migrations/20260528091000-add-package-material-fields-to-wms-order-express.js)。生产回滚前请先迁移或备份依赖数据并通知下游系统。", - "兼容性说明:新增列均为可空(nullable),属于向后兼容的增量变更,不会影响现有查询或写入;若服务端或前端存在把 wms_order_express 全量序列化到外部响应的场景,响应中可能会包含这两个可选字段;目前已检查的对外 system 方法文档未声明返回 package_material_id 或 package_material_name_snapshot,因此本次不修改 methods/system.json(无接口契约变化)。", - "相关模型文件:新增 app/model/package_material.js、app/model/package_supplier.js;更新 app/model/order_express.js(新增字段与索引定义)。", - "验证建议:1) 在预发布环境执行 migrations up/down 并确认幂等性;2) 执行下单→分配快递→打印等关键路径以验证无回归;3) 若需要对外暴露包材字段,请在 methods/system.json 中补充对应接口的 response 字段并在变更记录中说明。" - ], - "type": "updated", - "module": "database" - } -] diff --git a/methods/changes/2026.06.16-system-01.json b/methods/changes/2026.06.16-system-01.json deleted file mode 100644 index c6d1df0..0000000 --- a/methods/changes/2026.06.16-system-01.json +++ /dev/null @@ -1,17 +0,0 @@ -[ - { - "version": "2026.06.16-system-01", - "date": "2026-06-16", - "summary": "新增 order.recheckOrder.queryRecheckOrderSingleList:散单复核列表接口,响应新增 items_weight(总重量kg)和 weight_type(重量类型)字段", - "methods": [ - "order.recheckOrder.queryRecheckOrderSingleList" - ], - "notes": [ - "新增方法 order.recheckOrder.queryRecheckOrderSingleList,为 recheckOrderList 散单模式的独立入口。", - "响应 list 每项新增字段 items_weight (number|null):订单总重量(kg),来自 wms_order.items_weight,为 null 时返回 null。", - "响应 list 每项新增字段 weight_type (string):重量类型中文标签,来自 wms_order.weight_type 经 formatWeightTypeLabel 转换;取值:常规/轻货/重货/冷链(对应 DB 值 0/1/2/3)。" - ], - "type": "added", - "module": "order.recheckOrder" - } -] diff --git a/methods/changes/2026.06.16-system-02.json b/methods/changes/2026.06.16-system-02.json deleted file mode 100644 index 545df34..0000000 --- a/methods/changes/2026.06.16-system-02.json +++ /dev/null @@ -1,16 +0,0 @@ -[ - { - "version": "2026.06.16-system-02", - "date": "2026-06-16", - "summary": "order.wave.groupOrderFetchList 响应新增 items_weight(总重量kg)字段", - "methods": [ - "order.wave.groupOrderFetchList" - ], - "notes": [ - "响应 list 每项新增字段 items_weight (number|null):订单总重量(kg),取组内首单 items_weight;组内订单 items_hash 相同重量一致。", - "为 null 时返回 null。" - ], - "type": "updated", - "module": "order.wave" - } -] diff --git a/methods/changes/2026.06.16-system-03.json b/methods/changes/2026.06.16-system-03.json deleted file mode 100644 index 15005a5..0000000 --- a/methods/changes/2026.06.16-system-03.json +++ /dev/null @@ -1,16 +0,0 @@ -[ - { - "version": "2026.06.16-system-03", - "date": "2026-06-16", - "summary": "order.wave.waveStrategyFallbackOrderList 响应新增 items_weight(总重量kg)和 weight_type(重量类型)字段", - "methods": [ - "order.wave.waveStrategyFallbackOrderList" - ], - "notes": [ - "响应 list 每项新增字段 items_weight (number|null):订单总重量(kg),来自 wms_order.items_weight,为 null 时返回 null。", - "响应 list 每项新增字段 weight_type (string):重量类型中文标签,来自 wms_order.weight_type 经 formatWeightTypeLabel 转换;取值:常规/轻货/重货/冷链(对应 DB 值 0/1/2/3)。" - ], - "type": "updated", - "module": "order.wave" - } -] diff --git a/methods/changes/2026.06.16-system-04.json b/methods/changes/2026.06.16-system-04.json deleted file mode 100644 index 4872712..0000000 --- a/methods/changes/2026.06.16-system-04.json +++ /dev/null @@ -1,16 +0,0 @@ -[ - { - "version": "2026.06.16-system-04", - "date": "2026-06-16", - "summary": "order.wave.singleOrderFetchList 响应新增 items_weight(总重量kg)字段", - "methods": [ - "order.wave.singleOrderFetchList" - ], - "notes": [ - "响应 list 每项新增字段 items_weight (number|null):订单总重量(kg),取组内首单 items_weight;组内订单 items_hash 相同重量一致。", - "为 null 时返回 null。" - ], - "type": "updated", - "module": "order.wave" - } -] diff --git a/methods/changes/openapi-2026-06-17-entryorder.json b/methods/changes/openapi-2026-06-17-entryorder.json deleted file mode 100644 index 232ddac..0000000 --- a/methods/changes/openapi-2026-06-17-entryorder.json +++ /dev/null @@ -1,20 +0,0 @@ -[ - { - "version": "2026.06.17-openapi-16", - "date": "2026-06-17", - "summary": "新增入库单模块(entryorder),支持 create(创建入库单)和 query(查询入库单)两个方法", - "methods": [ - "entryorder.create", - "entryorder.query" - ], - "notes": [ - "新增 entryorder.create:创建入库单接口,支持入库单主信息(entryOrder)和商品明细(orderLines.orderLine)的完整入参;创建渠道固定为 API;itemCode 与 itemId 二选一,优先使用 itemId", - "新增 entryorder.query:查询入库单接口,根据 entryOrderCode 查询入库单详情,返回基本信息及商品明细(itemId/itemCode/itemName/planQty/actualQty/inventoryType/orderLineNo)", - "查询范围为当前 app_key 绑定的仓库,跨仓库入库单无法查询", - "所有方法均支持 timestamp 时间戳时效校验:与服务器时间差不得超过 ±10 分钟(600 秒),否则返回 400", - "openapi 通道新增入库单创建和查询能力" - ], - "type": "added", - "module": "entryorder" - } -] diff --git a/methods/changes/qimen.json b/methods/changes/qimen.json index c127246..c744a7b 100644 --- a/methods/changes/qimen.json +++ b/methods/changes/qimen.json @@ -1,14 +1,57 @@ [ - { - "version": "2026.04.07-qimen-01", - "date": "2026-04-07", - "summary": "初始化 qimen 文档变更记录 sidecar,后续接口文档变更将持续追加到本数组。", - "methods": [ - "*" - ], - "notes": [ - "methods/qimen.json 仍为单一事实来源(SSOT)。", - "本文件仅记录变更历史与补充说明。" - ] - } + { + "version": "2026.07.01-qimen-01", + "date": "2026-07-01", + "summary": "补充 entryorder.create 的 request body 子结构和 response 结构", + "methods": [ + "entryorder.create" + ], + "notes": [ + "补充 request.entryOrder 子结构(entryOrderCode/warehouseCode/ownerCode/orderType)", + "补充 request.orderLines.orderLine 子结构(itemCode/itemId/itemName/planQty/orderLineNo/inventoryType)", + "补充 response 结构(entryOrderId/entryOrderCode/createTime/status)", + "参考代码:systems/entry_order.js addOrder 和 qimenMethods/entryorder.js create 返回值" + ], + "type": "updated", + "module": "entryorder" + }, + { + "version": "2026.04.07-qimen-01", + "date": "2026-04-07", + "summary": "初始化 qimen 文档变更记录 sidecar,后续接口文档变更将持续追加到本数组。", + "methods": [ + "*" + ], + "notes": [ + "methods/qimen.json 仍为单一事实来源(SSOT)。", + "本文件仅记录变更历史与补充说明。" + ] + }, + { + "version": "2026.06.30-stockout-create-01", + "date": "2026-06-30", + "summary": "stockout.create 重构:从不可用的 deliveryOrder 旧链路迁移到 wms_order_stockout 专用表;返回字段 deliveryOrderId→stockoutOrderId/stockoutOrderCode", + "methods": [ + "stockout.create" + ], + "notes": [ + "params 补全 deliveryOrder 和 orderLines 内部全部子字段", + "response 从空补充为 stockoutOrderId/stockoutOrderCode", + "文档与代码实现(qimenMethods/stockout.js create 方法)对齐" + ] + }, + { + "version": "2026.06.30-stockout-query-01", + "date": "2026-06-30", + "summary": "stockout.query 从占位(接口未完善)实现为完整查询:按 deliveryOrderCode 查 wms_order_stockout 主表+明细表", + "methods": [ + "stockout.query" + ], + "notes": [ + "params 补全 request.deliveryOrder.deliveryOrderCode(body)", + "response 从空补充为 deliveryOrder 主单 + orderLines.orderLine 明细 + totalLines", + "文档与代码实现(qimenMethods/stockout.js query 方法)对齐" + ], + "type": "updated" + } ] diff --git a/methods/changes/system.json b/methods/changes/system.json index 1ac129a..63bec51 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,125 @@ [ + { + "date": "2026-06-24", + "type": "addition", + "summary": "新增批量绑定入库单明细与收货单明细接口,支持明细级数量分配与部分成功", + "version": "2026-06-24-add-bind-receiving-details", + "methods": [ + "storage.entry.bindReceivingDetails" + ], + "notes": [] + }, + { + "date": "2026-06-24", + "type": "deprecation", + "summary": "废弃手动匹配入库单收货单接口,由 storage.entry.bindReceivingDetails 替代", + "version": "2026-06-24-deprecate-manual-match-entry-order", + "methods": [ + "storage.receiving.manualMatchEntryOrder" + ], + "notes": [] + }, + { + "version": "2026.06.16-system-03", + "date": "2026-06-16", + "summary": "order.wave.waveStrategyFallbackOrderList 响应新增 items_weight(总重量kg)和 weight_type(重量类型)字段", + "methods": [ + "order.wave.waveStrategyFallbackOrderList" + ], + "notes": [ + "响应 list 每项新增字段 items_weight (number|null):订单总重量(kg),来自 wms_order.items_weight,为 null 时返回 null。", + "响应 list 每项新增字段 weight_type (string):重量类型中文标签,来自 wms_order.weight_type 经 formatWeightTypeLabel 转换;取值:常规/轻货/重货/冷链(对应 DB 值 0/1/2/3)。" + ], + "type": "updated", + "module": "order.wave" + }, + { + "version": "2026.06.16-system-04", + "date": "2026-06-16", + "summary": "order.wave.singleOrderFetchList 响应新增 items_weight(总重量kg)字段", + "methods": [ + "order.wave.singleOrderFetchList" + ], + "notes": [ + "响应 list 每项新增字段 items_weight (number|null):订单总重量(kg),取组内首单 items_weight;组内订单 items_hash 相同重量一致。", + "为 null 时返回 null。" + ], + "type": "updated", + "module": "order.wave" + }, + { + "version": "2026.05.20-system-03", + "date": "2026-05-20", + "summary": "新增 storeWarehouse.store.queryPrintQuantityLogs:按 store_id 分页查询面单余额变更日志", + "methods": [ + "storeWarehouse.store.queryPrintQuantityLogs" + ], + "notes": [ + "新增方法:storeWarehouse.store.queryPrintQuantityLogs,用于按货主(store_id)分页查询面单余额变更日志。", + "入参:store_id(必填)、page(可选)、page_size / pageSize(可选,兼容别名)。", + "仅同步 methods/system.json 与本变更记录,不修改业务代码或测试。", + "返回:使用默认分页格式,响应在 `data` 下包含 `list`(变更日志数组)和 `pagination` 对象,`pagination` 字段:`page`、`pageSize`、`total`、`totalPages`、`hasPrevious`、`hasNext`。" + ], + "type": "added", + "module": "storeWarehouse" + }, + { + "version": "2026.05.13-system-01", + "date": "2026-05-13", + "summary": "完善 print.send 的 API 文档与返回说明", + "methods": [ + "print.send" + ], + "notes": [ + "补充请求参数说明:computerId、printer、template、data、type 标为必填,count、timestamp 保持可选。", + "补充 template 的子字段说明:page_width、page_height、template_content。", + "补充响应结构:flag、code、message、printId;其中成功时 code=200。", + "补充错误码说明:1001 对应不支持的打印类型,504 对应打印任务发送失败(包含打印机不存在、脱机、通讯失败等场景)。" + ], + "type": "updated" + }, + { + "version": "2026.05.08-system-06", + "date": "2026-05-08", + "summary": "新增取消拣货任务接口:order.wave.wavePickTaskCancel", + "methods": [ + "order.wave.wavePickTaskCancel" + ], + "notes": [ + "接口功能:取消拣货任务,同时释放关联波次(物理删除波次记录,订单回池)、解绑拣货车、写操作日志。", + "限制:仅允许在任务状态为 0(待开始)、1(拣货中)、2(待复核)时取消;状态为 3(已完成)或 9(已取消)时禁止取消,返回 400。", + "事务内操作:将任务状态更新为 9(已取消)、删除关联波次、清空订单 wave_id(回池)、解绑拣货车、写入 action_log 与 order_pick_trace;若有任一步骤失败则回滚并返回 500。" + ], + "type": "added" + }, + { + "version": "2026.07.01-system-01", + "date": "2026-07-01", + "summary": "storage.directInbound.addItem 参数名修正:entry_order_code → entry_order_id,类型 string → number", + "methods": [ + "storage.directInbound.addItem" + ], + "notes": [ + "文档 params 中 entry_order_code(string)改为 entry_order_id(number),与代码 app/service/systems/inbound_direct_log.js 第 544 行实际校验保持一致", + "同步修正 app/service/systemMethods/storage/direct_inbound.js JSDoc:@param {string} data.entry_order_code → @param {number} data.entry_order_id" + ], + "type": "fixed", + "module": "storage.directInbound" + }, + { + "version": "2026.07.01-system-02", + "date": "2026-07-01", + "summary": "新增 storage.entry.queryEntryLogs 接口文档定义", + "methods": [ + "storage.entry.queryEntryLogs" + ], + "notes": [ + "代码 method 层(systemMethods/storage/entry.js L284)和 systems 层(systems/operation_log.js L318)均已实现,补充文档定义", + "参数:id(number, required)、page(number, optional, 默认1)、pageSize(number, optional, 默认20)" + ], + "type": "added", + "module": "storage.entry" + }, { "version": "2026.06.18-system-01", "date": "2026-06-18", @@ -4199,5 +4320,332 @@ ], "type": "updated", "module": "setting.warehouse" + }, + { + "version": "2026.06.25-system-01", + "date": "2026-06-25", + "summary": "新增 storage.entry.bindReceiving 接口:将收货单绑定到入库单(主表级关联,不做明细数量分配)", + "methods": [ + "storage.entry.bindReceiving" + ], + "notes": [ + "新增入库单与收货单的主表绑定接口,与已有的 storage.entry.bindReceivingDetails(明细级绑定)区分:bindReceiving 仅建立 wms_entry_order_receiving 主表关联,不做明细数量分配。", + "入库单需为 CREATED 或 PENDING 状态;收货单需存在、同仓库且未取消。", + "支持部分成功模式:逐条校验收货单,校验通过的建立绑定,不通过的返回 error_code 和 message。", + "响应包含 success(成功列表)、failed(失败列表)、success_count、failed_count。" + ], + "type": "addition" + }, + { + "version": "2026.06.25-system-02", + "date": "2026-06-25", + "summary": "storage.entry.bindReceiving:新增 OWNER_MISMATCH 错误码,用于收货单与入库单货主不一致校验", + "methods": [ + "storage.entry.bindReceiving" + ], + "notes": [ + "在 storage.entry.bindReceiving 的 errors 数组中新增 OWNER_MISMATCH(收货单与入库单货主不一致)错误码。", + "同步更新 response.failed.error_code 的枚举描述,补充 OWNER_MISMATCH。" + ], + "type": "updated", + "module": "storage.entry" + }, + { + "version": "2026.06.25-system-03", + "date": "2026-06-25", + "summary": "storage.entry.bindReceiving:新增收货单未审核错误码 RECEIVING_NOT_REVIEWED", + "methods": [ + "storage.entry.bindReceiving" + ], + "notes": [ + "在 errors 数组中新增错误码 RECEIVING_NOT_REVIEWED(收货单未审核),用于标识绑定前收货单尚未完成审核的场景。", + "同步更新 response.failed.items.properties.error_code.description,在可能值列表中补充 RECEIVING_NOT_REVIEWED。" + ], + "type": "updated" + }, + { + "version": "2026.06.25-system-04", + "date": "2026-06-25", + "summary": "storage.entry.list 响应新增 receivingBindings 和 hasReceiving 字段,where 新增 hasReceiving 虚拟筛选条件", + "methods": [ + "storage.entry.list" + ], + "notes": [ + "响应 list 数组每项新增 receivingBindings(收货单绑定列表,主表级关联)和 hasReceiving(是否存在收货单绑定,boolean)字段。", + "入参 where 新增 hasReceiving 虚拟筛选字段,传 true/false 筛选已绑定/未绑定收货单的入库单,内部通过 wms_entry_order_receiving 表查询实现。", + "同步更新 description 以说明 hasReceiving 虚拟筛选的使用方式。" + ], + "type": "updated" + }, + { + "version": "2026.06.26-system-01", + "date": "2026-06-26", + "summary": "storage.entry.receivingCompare 支持多收货单对照预览", + "methods": [ + "storage.entry.receivingCompare" + ], + "notes": [ + "支持多个收货单ID对照预览(新增 receiving_ids 数组入参,优先于 receiving_id 使用)", + "入参 receiving_id 从 required 改为 optional,与 receiving_ids 二选一", + "出参结构调整为 comparisons[] 数组(多收货单),新增 errors[] 和 total_summary", + "向后兼容原 receiving_id 单值传参(底层自动转为单元素数组)", + "新增 400 错误码:receiving_ids 或 receiving_id 必填", + "移除 404 错误码:收货单不存在(已改为在 comparisons[]/errors[] 中以 status=error 形式返回)" + ], + "type": "enhancement" + }, + { + "version": "2026.06.26-system-02", + "date": "2026-06-26", + "summary": "storage.receiving.getReceivingList 新增 filterDepleted 可选参数;storage.entry.receivingCompare 返回值 receiving_only 字段新增 receiving_allocated 和 receiving_available 说明", + "methods": [ + "storage.receiving.getReceivingList", + "storage.entry.receivingCompare" + ], + "notes": [ + "storage.receiving.getReceivingList:params 新增 filterDepleted(boolean, 默认 false),用于过滤掉无可再用量的收货单(所有明细已被其他入库单 committed 绑定占满)。", + "storage.entry.receivingCompare:response 中 receiving_only 字段的 description 补充 receiving_allocated(已分配数量)和 receiving_available(可再用量)两个子字段说明。" + ], + "type": "updated" + }, + { + "version": "2026.06.26-system-03", + "date": "2026-06-26", + "summary": "storage.receiving.getReceivingList:新增可选参数 entry_order_id,按入库单商品交集过滤收货单列表", + "methods": [ + "storage.receiving.getReceivingList" + ], + "notes": [ + "新增可选参数 entry_order_id(number),传入入库单 ID 后只返回至少有一条明细的 system_product_id 在入库单明细中存在的收货单。", + "与现有 filterDepleted 参数可组合使用,二者取交集。", + "不传则不过滤,保持原有行为不变。" + ], + "type": "updated" + }, + { + "version": "2026.06.27-system-01", + "date": "2026-06-27", + "summary": "新增 storage.entry.reviewEntry 接口:审核入库单(CREATED→PENDING),需绑定收货单", + "methods": [ + "storage.entry.reviewEntry" + ], + "notes": [ + "新增入库单审核接口,支持 CREATED→PENDING 状态流转。", + "审核前置条件:入库单必须已绑定收货单(EntryOrderReceiving 存在关联记录)。", + "审核通过后写入操作日志(ENTRY_ORDER_REVIEW)。" + ], + "type": "added" + }, + { + "version": "2026.06.29-system-01", + "date": "2026-06-29", + "summary": "storage.inventory.quickPutaway 重新实现:收货单快捷转入库单", + "methods": [ + "storage.inventory.quickPutaway" + ], + "notes": [ + "此前已从代码中删除(2026.06.23-system-08),现由 wms-dev-agent 重新实现。", + "核心流程:参数校验 → 加载收货单及明细 → 检查货主配置 policy_config.allow_receiving_quick_putaway → 按 stock_id(system_product_id)分组合并数量 → 创建入库单 SCRK(自动审批到 PENDING)→ 写入 wms_entry_order_receiving 主表级绑定 → 更新收货单 storage_status 为 partial → 更新收货单明细 storage_status/stored_quantity → 提交事务。", + "前置条件:收货单状态为 completed 且 is_review=true(已审核),货主仓库签约配置 allow_receiving_quick_putaway=1。", + "与旧实现的区别:不涉及 wms_entry_receiving_binding 明细级绑定,使用 wms_entry_order_receiving 主表级关联;直接创建入库单并写入绑定,不再走 matchPutaway 匹配链路。", + "返回:entry_order_id、entry_order_code(SCRK 格式)、order_status(PENDING)、receiving_id、total_lines、total_quantity。" + ], + "type": "addition" + }, + { + "version": "2026.06.29-system-02", + "date": "2026-06-29", + "summary": "storage.entry.list:quickWhere 搜索范围扩展,新增收货单 ID(receiving_id)支持 PDA 扫描托盘唛头搜索绑定的入库单", + "methods": [ + "storage.entry.list" + ], + "notes": [ + "quickWhere 搜索字段新增 receiving_id(收货单 ID / 托盘唛头),通过 wms_entry_order_receiving 绑定表关联搜索。", + "同步更新 description 和 where 参数的 description,明确 quickWhere 完整搜索字段列表:entry_order_code、purchase_order_code、supplier_name、store_name、warehouse_name、receiving_id。" + ], + "type": "updated", + "module": "storage" + }, + { + "version": "2026.06.29-system-03", + "date": "2026-06-29", + "summary": "新增 storage.receiving.scanDetail 接口:PDA 上架扫码定位收货明细", + "methods": [ + "storage.receiving.scanDetail" + ], + "notes": [ + "新增 storage.receiving.scanDetail(PDA专用):通过 entry_order_id + barcode 扫码快速定位收货明细。", + "搜索逻辑:纯数字 barcode 优先按明细 ID 精确匹配(托盘唛头),未命中则模糊匹配商品条码;非纯数字仅模糊匹配商品条码。", + "入参:entry_order_id(必填 number)、barcode(必填 string)。", + "出参:detail_id、receiving_id、barcode、product_name、actual_quantity、receiving_status。", + "错误码:入库单不存在或无权访问、该入库单尚未关联收货单、未找到匹配的收货明细。" + ], + "type": "added" + }, + { + "version": "2026.06.29-system-04", + "date": "2026-06-29", + "summary": "storage.receiving.scanDetail 响应结构从单条改为列表:返回 { list, total } 支持同一条码匹配多条明细", + "methods": [ + "storage.receiving.scanDetail" + ], + "notes": [ + "响应结构变更:原返回 data.detail_id/data.receiving_id 等单条字段,现改为顶层 list 数组 + total 计数。", + "同一条码可能匹配到多条收货明细(不同收货单的同一商品),以列表形式返回所有匹配结果。", + "list 中每条明细包含 detail_id/receiving_id/barcode/product_name/actual_quantity/receiving_status。", + "补充错误码:用户未绑定仓库、入库单ID/条码为空、未找到可用的收货明细、500服务器错误。", + "PDA专用接口,description 更新说明匹配逻辑。" + ], + "type": "updated", + "module": "storage.receiving" + }, + { + "version": "2026.06.30-system-01", + "date": "2026-06-30", + "summary": "新增 storage.entry.containerList:PDA 上架时拉取入库单绑定收货单中指定商品的可用容器列表", + "methods": [ + "storage.entry.containerList" + ], + "notes": [ + "新增接口 storage.entry.containerList,用于 PDA 上架场景拉取入库单已绑定收货单中指定 stock_id 的可用收货明细(容器)列表。", + "入参:entry_order_id(入库单ID,必填)、stock_id(商品 stock_id,必填)。", + "出参:data.list 返回可用明细列表,每项含 detail_id、receiving_id、barcode、product_name、actual_quantity、receiving_status;data.total 为总数。", + "已绑定占用的收货明细(wms_entry_receiving_binding 中已有记录且未软删除)会被排除。", + "PDA 专用接口,无需额外鉴权(isNeedAuth=false)。" + ], + "type": "added" + }, + { + "version": "2026.06.30-system-02", + "date": "2026-06-30", + "summary": "storage.entry.addDirectInboundItem 入参变更:entry_order_code → entry_order_id(number);quantity 改为可选(传入 receiving_detail_id 时自动计算);新增 receiving_detail_id/allocated_quantity 参数支持 PDA 上架收货明细绑定模式;space_id 绑定模式下必填", + "methods": [ + "storage.entry.addDirectInboundItem" + ], + "notes": [ + "入参 entry_order_code(string) → entry_order_id(number),与底层 inboundDirectLog.addItem 实现对齐", + "quantity 改为可选:传入 receiving_detail_id 时自动从收货明细计算可用数量(actual_quantity - 已绑定数量)", + "新增 receiving_detail_id 参数:PDA 上架绑定收货明细时传入,触发预占绑定(wms_entry_receiving_binding status=pending)", + "新增 allocated_quantity 参数:预分配数量,默认等于 quantity", + "space_id 在绑定模式下必填;非绑定模式可选(commit 时兜底为 1)", + "PENDING 状态入库单必须传 receiving_detail_id 且已绑定收货单方可操作", + "CREATED + 已绑定收货单的入库单需先审核(reviewEntry)后才能上架", + "批量模式 items 数组同步支持 receiving_detail_id/allocated_quantity 字段", + "补充完整错误码列表:超量、可用数量不足、状态校验等" + ], + "type": "updated" + }, + { + "version": "2026.06.30-system-03", + "date": "2026-06-30", + "summary": "storage.entry.commitDirectInbound 入参变更:entry_order_code → entry_order_id(number),与底层 inboundDirectLog.commit 实现对齐", + "methods": [ + "storage.entry.commitDirectInbound" + ], + "notes": [ + "入参 entry_order_code(string) → entry_order_id(number),与底层 inboundDirectLog.commit(entryOrderId) 实现对齐", + "补充 description 说明先同步后写库两段式流程:① 奇门/API 回传 → ② onSuccess 内事务写库存", + "补充 commit 后 EntryReceivingBinding 状态从 pending 更新为 committed 的说明" + ], + "type": "updated" + }, + { + "version": "2026.06.30-system-04", + "date": "2026-06-30", + "summary": "storage.directInbound.commit 入参变更:entry_order_code → entry_order_id(number),与底层 inboundDirectLog.commit 实现对齐", + "methods": [ + "storage.directInbound.commit" + ], + "notes": [ + "入参 entry_order_code(string) → entry_order_id(number),与底层 inboundDirectLog.commit(entryOrderId) 实现对齐", + "该方法已标记 deprecated,推荐使用 storage.entry.commitDirectInbound" + ], + "type": "updated" + }, + { + "version": "2026.06.30-system-05", + "date": "2026-06-30", + "summary": "storage.entry.getDirectInboundItems 响应结构重构:entryOrder 精简字段,items[].count→planned、direct_inbound_quantity→completed,items[].bindings 新增,移除 direct_logs/summary 等冗余字段", + "methods": [ + "storage.entry.getDirectInboundItems" + ], + "notes": [ + "entryOrder 精简为 id / entry_order_code / order_status / store_remask 四个字段", + "items[].count → planned(计划数量),items[].direct_inbound_quantity → completed(已完成数量)", + "items[].bindings 新增,结构为 { detail_id, binding_id, allocated_quantity, space_id, space_name }", + "items[].stock 新增,返回 getStockDetails 缓存的商品详情(item_code、item_name、barcodes 等)", + "移除 direct_logs(现有响应中已不存在该顶层字段)", + "移除 summary(现有响应中已不存在该字段)", + "移除 items[].received_quantity、items[].remaining_quantity、items[].pending_binding_total 等旧字段", + "新增 receivingBindings 字段说明:入库单层级收货单绑定关系" + ], + "type": "updated" + }, + { + "version": "2026.06.30-system-06", + "date": "2026-06-30", + "summary": "storage.directInbound.getItems 响应结构重构:entryOrder 精简字段,items[].count→planned、direct_inbound_quantity→completed,items[].bindings 新增,移除 direct_logs/summary 等冗余字段", + "methods": [ + "storage.directInbound.getItems" + ], + "notes": [ + "响应结构与 storage.entry.getDirectInboundItems 对齐(两者共用同一个底层实现 inboundDirectLog.getItems)", + "entryOrder 精简为 id / entry_order_code / order_status / store_remask", + "items[].count → planned,items[].direct_inbound_quantity → completed", + "items[].bindings 新增 { detail_id, binding_id, allocated_quantity, space_id, space_name }", + "items[].stock 新增", + "移除 direct_logs、summary、items[].received_quantity、items[].remaining_quantity 等旧字段", + "新增 receivingBindings 字段" + ], + "type": "updated" + }, + { + "version": "2026.06.30-system-07", + "date": "2026-06-30", + "summary": "storage.entry.containerList 响应结构补充 stock 字段:返回商品详情(item_code、item_name、barcodes 等)", + "methods": [ + "storage.entry.containerList" + ], + "notes": [ + "响应 list[].stock 字段补充为必返回:通过 getStockDetails 批量获取商品详情缓存", + "stock 对象包含 item_code、item_name、sku_property、barcodes 等字段" + ], + "type": "updated" + }, + { + "version": "2026.06.30-system-08", + "date": "2026-06-30", + "summary": "storage.receiving.scanDetail 响应结构补充 stock 字段:返回商品详情(item_code、item_name、barcodes 等)", + "methods": [ + "storage.receiving.scanDetail" + ], + "notes": [ + "响应 list[].stock 字段补充为必返回:通过 getStockDetails 批量获取商品详情缓存", + "stock 对象包含 item_code、item_name、sku_property、barcodes 等字段", + "完善 error 列表:补充 未找到可用的收货明细、未找到匹配的收货明细、入库单ID不能为空、扫描条码不能为空 等错误" + ], + "type": "updated" + }, + { + "version": "2026.06.30-system-09", + "date": "2026-06-30", + "summary": "订单列表 list 响应新增 store_remark(货主备注)字段", + "methods": [ + "order.list", + "order.reviewOrder.list", + "order.pendingOrder.list", + "order.expectionOrder.list", + "order.entrustOrder.list", + "order.deliveryOrder.list", + "order.deliveryExpectionOrder.list", + "order.archiveOrder.list" + ], + "notes": [ + "数据库字段 store_remask,返回给前端的字段名为 store_remark。", + "服务层从 wms_store_warehouse.store_remask 按 store_id+warehouse_id 聚合批量填充。", + "货主备注值可能为空字符串(当货主未设置备注时)。", + "该字段对订单列表的所有 method 均适用(current/dispatch/outsourced/history 模型均返回)。" + ], + "type": "updated" } ] diff --git a/methods/qimen.json b/methods/qimen.json index 0f560ac..27468be 100644 --- a/methods/qimen.json +++ b/methods/qimen.json @@ -1,8 +1,8 @@ { "module": "qimen", "description": "奇门接口标准入口,method 对应 qimenMethods 异步方法,全部使用 POST 请求,参数包含 query 与 XML body(request 节点)", - "version": "0.3.0", - "updatedAt": "2026-03-22", + "version": "0.3.6", + "updatedAt": "2026-06-30", "headers": [], "methods": { "groups": [ @@ -240,7 +240,7 @@ "list": [ { "method": "entryorder.create", - "description": "entryorder.create 接口", + "description": "创建入库单。奇门 XML 推送创建入库单及明细,返回入库单 ID、单号、创建时间和状态", "isNeedAuth": false, "isNeedLogin": false, "headers": [], @@ -299,11 +299,129 @@ "type": "object", "required": true, "source": "body", - "description": "request XML 节点" + "description": "request XML 节点,包含 entryOrder 和 orderLines 子节点" + }, + { + "name": "request.entryOrder", + "type": "object", + "required": true, + "source": "body", + "description": "入库单头信息" + }, + { + "name": "request.entryOrder.entryOrderCode", + "type": "string", + "required": true, + "source": "body", + "description": "入库单号(外部系统单号)" + }, + { + "name": "request.entryOrder.warehouseCode", + "type": "string", + "required": true, + "source": "body", + "description": "仓库编码" + }, + { + "name": "request.entryOrder.ownerCode", + "type": "string", + "required": true, + "source": "body", + "description": "货主编码" + }, + { + "name": "request.entryOrder.orderType", + "type": "string", + "required": true, + "source": "body", + "description": "入库单类型:CGRK(采购入库)、JITRK(JIT入库)、THRK(退货入库)、QTRK(其他入库)等" + }, + { + "name": "request.orderLines.orderLine", + "type": "object|array", + "required": true, + "source": "body", + "description": "入库单明细行,单条为 object,多条为 array" + }, + { + "name": "request.orderLines.orderLine.itemCode", + "type": "string", + "required": true, + "source": "body", + "description": "商品编码" + }, + { + "name": "request.orderLines.orderLine.itemId", + "type": "string", + "required": false, + "source": "body", + "description": "商品 ID(StockStore 主键),建议必传以避免编码匹配问题" + }, + { + "name": "request.orderLines.orderLine.itemName", + "type": "string", + "required": true, + "source": "body", + "description": "商品名称" + }, + { + "name": "request.orderLines.orderLine.planQty", + "type": "number", + "required": true, + "source": "body", + "description": "计划入库数量" + }, + { + "name": "request.orderLines.orderLine.orderLineNo", + "type": "string", + "required": false, + "source": "body", + "description": "行号" + }, + { + "name": "request.orderLines.orderLine.inventoryType", + "type": "string", + "required": false, + "source": "body", + "description": "库存类型,如 ZP(正品),默认 ZP" } ], - "response": [], - "errors": [] + "response": [ + { + "name": "entryOrderId", + "type": "number", + "required": true, + "description": "WMS 入库单 ID" + }, + { + "name": "entryOrderCode", + "type": "string", + "required": true, + "description": "入库单号" + }, + { + "name": "createTime", + "type": "string", + "required": true, + "description": "创建时间" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "入库单状态:CREATED(已创建)或 PENDING(已审核)" + } + ], + "errors": [ + { + "code": 400, + "message": "创建入库单失败:商品未同步推送到仓库 / wms无对应关系" + }, + { + "code": 500, + "message": "服务器异常" + } + ] }, { "method": "entryorder.query", @@ -985,25 +1103,136 @@ }, { "name": "request.deliveryOrder", + "type": "object", + "required": true, + "source": "body", + "description": "出库单头信息" + }, + { + "name": "request.deliveryOrder.deliveryOrderCode", + "type": "string", + "required": true, + "source": "body", + "description": "出库单号" + }, + { + "name": "request.deliveryOrder.orderType", + "type": "string", + "required": true, + "source": "body", + "description": "业务类型(JYCK一般交易出库/HHCK换货出库/BFCK补发出库/QTCK其他出库)" + }, + { + "name": "request.deliveryOrder.warehouseCode", + "type": "string", + "required": true, + "source": "body", + "description": "仓库编码" + }, + { + "name": "request.deliveryOrder.createTime", "type": "string", "required": false, "source": "body", - "description": "request.deliveryOrder 参数" + "description": "订单创建时间" + }, + { + "name": "request.deliveryOrder.totalOrderLines", + "type": "integer", + "required": false, + "source": "body", + "description": "单据总行数" + }, + { + "name": "request.deliveryOrder.remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注" }, { "name": "request.orderLines", + "type": "object", + "required": true, + "source": "body", + "description": "出库单明细" + }, + { + "name": "request.orderLines.orderLine", + "type": "object/array", + "required": true, + "source": "body", + "description": "明细行(单条为对象,多条为数组)" + }, + { + "name": "request.orderLines.orderLine.orderLineNo", + "type": "string", + "required": true, + "source": "body", + "description": "订单行号" + }, + { + "name": "request.orderLines.orderLine.ownerCode", + "type": "string", + "required": true, + "source": "body", + "description": "货主编码" + }, + { + "name": "request.orderLines.orderLine.itemCode", + "type": "string", + "required": true, + "source": "body", + "description": "商品编码" + }, + { + "name": "request.orderLines.orderLine.itemId", + "type": "string", + "required": true, + "source": "body", + "description": "WMS商品ID" + }, + { + "name": "request.orderLines.orderLine.itemName", "type": "string", "required": false, "source": "body", - "description": "request.orderLines 参数" + "description": "商品名称" + }, + { + "name": "request.orderLines.orderLine.planQty", + "type": "integer", + "required": true, + "source": "body", + "description": "计划数量" + }, + { + "name": "request.orderLines.orderLine.inventoryType", + "type": "string", + "required": false, + "source": "body", + "description": "库存类型(ZP正品/CC残次等)" + } + ], + "response": [ + { + "name": "stockoutOrderId", + "type": "integer", + "required": true, + "description": "出库单ID" + }, + { + "name": "stockoutOrderCode", + "type": "string", + "required": true, + "description": "出库单号" } ], - "response": [], "errors": [] }, { "method": "stockout.query", - "description": "stockout.query 接口", + "description": "stockout.query 接口(查询非订单出库单;按 deliveryOrderCode 查 wms_order_stockout 主表+明细表)", "isNeedAuth": false, "isNeedLogin": false, "headers": [], @@ -1062,25 +1291,139 @@ "type": "object", "required": true, "source": "body", - "description": "request XML 节点" + "description": "请求数据" }, { "name": "request.deliveryOrder", - "type": "string", - "required": false, + "type": "object", + "required": true, "source": "body", - "description": "request.deliveryOrder 参数" + "description": "出库单查询条件" }, { - "name": "request.orderLines", + "name": "request.deliveryOrder.deliveryOrderCode", "type": "string", - "required": false, + "required": true, "source": "body", - "description": "request.orderLines 参数" + "description": "出库单号" } ], - "response": [], - "errors": [] + "response": [ + { + "name": "totalLines", + "type": "integer", + "required": true, + "description": "明细总行数" + }, + { + "name": "deliveryOrder", + "type": "object", + "required": true, + "description": "出库单主单信息" + }, + { + "name": "deliveryOrder.deliveryOrderCode", + "type": "string", + "required": true, + "description": "出库单号" + }, + { + "name": "deliveryOrder.deliveryOrderId", + "type": "integer", + "required": true, + "description": "出库单ID" + }, + { + "name": "deliveryOrder.warehouseCode", + "type": "string", + "required": true, + "description": "仓库编码" + }, + { + "name": "deliveryOrder.orderType", + "type": "string", + "required": true, + "description": "业务类型" + }, + { + "name": "deliveryOrder.status", + "type": "string", + "required": true, + "description": "订单状态" + }, + { + "name": "deliveryOrder.createTime", + "type": "string", + "required": true, + "description": "创建时间" + }, + { + "name": "deliveryOrder.remark", + "type": "string", + "required": true, + "description": "备注" + }, + { + "name": "orderLines", + "type": "object", + "required": true, + "description": "明细集合" + }, + { + "name": "orderLines.orderLine", + "type": "array", + "required": true, + "description": "明细行数组" + }, + { + "name": "orderLines.orderLine[].orderLineNo", + "type": "string", + "required": true, + "description": "订单行号" + }, + { + "name": "orderLines.orderLine[].ownerCode", + "type": "string", + "required": true, + "description": "货主编码" + }, + { + "name": "orderLines.orderLine[].itemCode", + "type": "string", + "required": true, + "description": "商品编码" + }, + { + "name": "orderLines.orderLine[].itemId", + "type": "string", + "required": true, + "description": "WMS商品ID" + }, + { + "name": "orderLines.orderLine[].itemName", + "type": "string", + "required": true, + "description": "商品名称" + }, + { + "name": "orderLines.orderLine[].planQty", + "type": "integer", + "required": true, + "description": "计划数量" + }, + { + "name": "orderLines.orderLine[].inventoryType", + "type": "string", + "required": true, + "description": "库存类型" + } + ], + "errors": [ + { + "code": 400, + "message": "未找到出库单(deliveryOrderCode 对应记录不存在)" + } + ] } ] }, diff --git a/methods/system.json b/methods/system.json index 7581b77..4d22ec6 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,8 +1,8 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.7", - "updatedAt": "2026-06-24", + "version": "0.3.5", + "updatedAt": "2026-06-30", "headers": [ { "name": "platform", @@ -1655,7 +1655,7 @@ "name": "list", "type": "array", "required": true, - "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节)" + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段。" }, { "name": "pagination", @@ -2541,7 +2541,7 @@ "name": "list", "type": "array", "required": true, - "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节)" + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段。" }, { "name": "pagination", @@ -2756,7 +2756,7 @@ "name": "list", "type": "array", "required": true, - "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节)" + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段。" }, { "name": "pagination", @@ -9640,19 +9640,13 @@ "name": "list", "type": "array", "required": true, - "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节)" + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段。" }, { "name": "pagination", "type": "object", "required": true, "description": "分页信息" - }, - { - "name": "recheck_status", - "type": "string", - "required": false, - "description": "复核状态:none=未复核,fin=已复核" } ], "errors": [ @@ -9831,19 +9825,13 @@ "name": "list", "type": "array", "required": true, - "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节)" + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段。" }, { "name": "pagination", "type": "object", "required": true, "description": "分页信息" - }, - { - "name": "recheck_status", - "type": "string", - "required": false, - "description": "复核状态:none=未复核,fin=已复核" } ], "errors": [ @@ -9975,7 +9963,7 @@ "name": "list", "type": "array", "required": true, - "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节)" + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段。" }, { "name": "pagination", @@ -10124,7 +10112,7 @@ "name": "list", "type": "array", "required": true, - "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节)" + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段。" }, { "name": "pagination", @@ -10268,7 +10256,7 @@ "name": "list", "type": "array", "required": true, - "description": "订单列表(raw 行数据)" + "description": "订单列表(raw 行数据,字段字典见 docs/order-workbench-list-api.md 中的“订单列表 raw 字段字典”章节),本次新增 store_remark(货主备注)字段。" }, { "name": "pagination", @@ -17586,7 +17574,7 @@ "list": [ { "method": "storage.receiving.getReceivingList", - "description": "storage.receiving.getReceivingList 接口", + "description": "查询收货单列表,支持分页和多条件筛选。支持 filterDepleted 参数过滤掉无可再用量的收货单(所有明细已被其他入库单 committed 绑定占满)。支持 entry_order_id 参数按入库单商品交集过滤。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -17611,6 +17599,20 @@ "required": false, "source": "body", "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;支持 quickWhere、status、store_id、日期区间等字段。示例:where.status={operator:eq,value:finished}; where.store_id={operator:eq,value:1001}; where.create_time_start={value:2026-03-01}。" + }, + { + "name": "filterDepleted", + "type": "boolean", + "required": false, + "source": "body", + "description": "是否过滤掉无可再用量的收货单(所有明细已被其他入库单 committed 绑定占满,即 available=0)。默认 false。" + }, + { + "name": "entry_order_id", + "type": "number", + "required": false, + "source": "body", + "description": "按入库单商品交集过滤。传入入库单 ID 后,只返回至少有一条收货明细的 system_product_id 在入库单明细中存在的收货单。与 filterDepleted 可组合使用。不传则不过滤。" } ], "response": [ @@ -17636,7 +17638,7 @@ "errors": [ { "code": "500", - "description": "查询失败" + "message": "查询失败" } ] }, @@ -18890,78 +18892,9 @@ ] }, { - "groupName": "入库模块", + "groupName": "入库管理", "module": "storage.entry", "list": [ - { - "method": "storage.entry.list", - "description": "入库单列表查询。where.order_status 支持 CREATING/CREATED/PENDING/COMPLETED/CANCELLED。CREATED=已创建待审核(需审核后才能绑定和完成入库),PENDING=已审核(可绑定和完成入库)。", - "isNeedAuth": false, - "isNeedLogin": true, - "headers": [ - { - "name": "Authorization", - "type": "string", - "required": true, - "description": "Bearer token" - } - ], - "params": [ - { - "name": "pagination", - "type": "object", - "required": false, - "source": "body", - "description": "分页参数,支持 page/pageSize" - }, - { - "name": "where", - "type": "object", - "required": false, - "source": "body", - "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;支持 quickWhere、order_status(CREATING/CREATED/PENDING/COMPLETED/CANCELLED)、store_id、order_type、日期区间等字段。新增 expense_record(费用是否记录)筛选,支持 eq/in;值会归一化为 0/1,兼容 true/false、1/0、y/n、yes/no(大小写不敏感,含布尔/字符串/数字写法)。示例:where.expense_record={operator:eq,value:true} 等价 where.expense_record={operator:eq,value:1};where.expense_record={operator:in,value:[true,\"0\",\"yes\",\"n\"]} 会归一化为 [1,0]。若部署环境尚未完成 expense_record 字段迁移,传入该筛选可能返回 400,错误提示为\"当前环境未提供 expense_record 字段,暂不支持该筛选条件,请先完成表结构升级\"。" - }, - { - "name": "sort", - "type": "object", - "required": false, - "source": "body", - "description": "排序参数,支持 sortField/sortOrder" - } - ], - "response": [ - { - "name": "list", - "type": "array", - "required": true, - "description": "入库单列表" - }, - { - "name": "pagination", - "type": "object", - "required": true, - "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)" - }, - { - "name": "summary", - "type": "object", - "required": true, - "description": "状态汇总(total、pending、creating、created、completed、cancelled)" - } - ], - "errors": [ - { - "code": "400", - "message": "筛选条件格式错误", - "description": "筛选条件格式错误" - }, - { - "code": "500", - "message": "查询失败", - "description": "查询失败" - } - ] - }, { "method": "storage.entry.get", "description": "查询入库单详情。返回的 entryOrder 包含顶层 receivingBindings(主表级关联,含关联的收货单信息),不再返回 items[].bindings(明细级绑定)。entryOrder.order_status 可能为 CREATING/CREATED/PENDING/COMPLETED/CANCELLED。CREATED=已创建待审核(需审核后才能绑定和完成入库),PENDING=已审核(可绑定和完成入库)。", @@ -19225,7 +19158,7 @@ }, { "method": "storage.entry.getDirectInboundItems", - "description": "获取入库单的导入/PDA 入库信息,返回入库单基本信息、明细列表,以及每项明细已有的导入/PDA 入库记录(含汇总和剩余可入库数量)。", + "description": "获取入库单的导入/PDA 入库信息(精简版)。返回入库单基本信息、明细列表(含计划数量 planned 与已完成数量 completed)、每项明细的收货绑定列表 bindings(含 detail_id、binding_id、allocated_quantity、space_id、space_name),以及收货单绑定关系 receivingBindings。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -19250,25 +19183,135 @@ "name": "entryOrder", "type": "object", "required": true, - "description": "入库单基本信息(id、entry_order_code、order_type、order_status、source_type、warehouse_id、store_id、remark)" + "description": "入库单基本信息", + "children": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "入库单ID" + }, + { + "name": "entry_order_code", + "type": "string", + "required": true, + "description": "入库单号" + }, + { + "name": "order_status", + "type": "string", + "required": true, + "description": "入库单状态(CREATED/PENDING/COMPLETED/CANCELLED)" + }, + { + "name": "store_remask", + "type": "string", + "required": true, + "description": "货主商家备注" + } + ] }, { "name": "items", "type": "array", "required": true, - "description": "入库明细列表,每项含 id、stock_id、count(计划数量)、received_quantity、direct_inbound_quantity(已导入/PDA入库数量)、remaining_quantity(剩余可入库数量)、pending_binding_total(pending 绑定总量)、bindings(pending 绑定列表,同 storage.entry.get 结构)、direct_logs(已有入库记录)" + "description": "入库明细列表", + "children": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "入库明细ID(wms_entry_items.id)" + }, + { + "name": "stock_id", + "type": "number", + "required": true, + "description": "商品SKU ID" + }, + { + "name": "planned", + "type": "number", + "required": true, + "description": "计划入库数量(对应原 count 字段)" + }, + { + "name": "completed", + "type": "number", + "required": true, + "description": "已完成导入/PDA 入库数量(对应原 direct_inbound_quantity 字段)" + }, + { + "name": "stock", + "type": "object", + "required": true, + "description": "商品详情(含 item_code、item_name、sku_property、barcodes 等缓存字段)" + }, + { + "name": "bindings", + "type": "array", + "required": true, + "description": "该明细的收货单绑定列表(来自 wms_entry_receiving_binding + InboundDirectLog)", + "children": [ + { + "name": "detail_id", + "type": "number", + "required": false, + "description": "收货明细ID(wms_receiving_detail.id),无绑定时可能不存在" + }, + { + "name": "binding_id", + "type": "number", + "required": false, + "description": "绑定记录ID(wms_entry_receiving_binding.id),无绑定时可能不存在" + }, + { + "name": "allocated_quantity", + "type": "number", + "required": false, + "description": "预分配数量" + }, + { + "name": "space_id", + "type": "number", + "required": false, + "description": "存放库位ID(取自 InboundDirectLog)" + }, + { + "name": "space_name", + "type": "string", + "required": false, + "description": "库位名称(取自 wms_location_space.custom_name 或 space_code)" + } + ] + } + ] }, { - "name": "direct_logs", + "name": "receivingBindings", "type": "array", "required": true, - "description": "该入库单下所有导入/PDA 入库记录(含 space_id)" - }, - { - "name": "summary", - "type": "object", - "required": true, - "description": "汇总信息(total_items、total_planned、total_direct_inbound)" + "description": "入库单层级的收货单绑定关系列表(wms_entry_order_receiving)", + "children": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "绑定记录ID" + }, + { + "name": "receiving_id", + "type": "number", + "required": true, + "description": "收货单ID" + }, + { + "name": "receiving", + "type": "object", + "required": true, + "description": "收货单信息(id、receiving_number、status、storage_status、created_at)" + } + ] } ], "errors": [ @@ -19284,7 +19327,7 @@ }, { "method": "storage.entry.addDirectInboundItem", - "description": "按商品增量添加导入/PDA 入库记录(支持单条和批量)。单条模式传 stock_id/quantity/inbound_type/remark,批量模式传 items 数组。批量模式所有商品共享同一个入库单状态校验,任一商品校验失败整批拒绝。若某商品累计入库量超过计划数量则拒绝。", + "description": "按商品增量添加导入/PDA 入库记录(支持单条和批量)。单条模式传 stock_id/quantity/inbound_type/remark,批量模式传 items 数组。批量模式所有商品共享同一个入库单状态校验,任一商品校验失败整批拒绝。若某商品累计入库量超过计划数量则拒绝(PENDING 非绑定模式)。PENDING 状态需传 receiving_detail_id 绑定收货明细;CREATED 人工导入允许超过计划数量;传入 receiving_detail_id 时 quantity 可选(自动计算可用数量),space_id 必填。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -19297,11 +19340,11 @@ ], "params": [ { - "name": "entry_order_code", - "type": "string", + "name": "entry_order_id", + "type": "number", "required": true, "source": "body", - "description": "入库单号" + "description": "入库单 ID" }, { "name": "stock_id", @@ -19313,9 +19356,9 @@ { "name": "quantity", "type": "number", - "required": true, + "required": false, "source": "body", - "description": "本次入库数量(正整数)" + "description": "本次入库数量(正整数)。传入 receiving_detail_id 时可选,自动计算收货明细可用数量;非绑定模式必填" }, { "name": "inbound_type", @@ -19336,14 +19379,28 @@ "type": "number", "required": false, "source": "body", - "description": "存放库位ID(单条模式),关联 wms_location_space.id;为空时 commit 默认使用库位 1" + "description": "存放库位ID(单条模式),关联 wms_location_space.id。绑定收货明细时必填;为空时 commit 默认使用库位 1" + }, + { + "name": "receiving_detail_id", + "type": "number", + "required": false, + "source": "body", + "description": "收货单明细ID(PDA 上架绑定模式),传入后触发收货明细预占绑定,quantity 自动计算" + }, + { + "name": "allocated_quantity", + "type": "number", + "required": false, + "source": "body", + "description": "预分配数量(单条模式,可选,默认等于 quantity)" }, { "name": "items", "type": "array", "required": false, "source": "body", - "description": "批量模式:商品列表,每项包含 stock_id(商品SKU ID, number, 必填)、quantity(入库数量, number, 必填)、inbound_type(import/pda, string, 必填)、space_id(库位ID, number, 可选)、remark(备注, string, 可选)。传入 items 时忽略顶层的 stock_id/quantity/inbound_type/remark/space_id。" + "description": "批量模式:商品列表,每项包含 stock_id(商品SKU ID, number, 必填)、quantity(入库数量, number, 绑定模式可选)、inbound_type(import/pda, string, 必填)、space_id(库位ID, number, 绑定模式必填)、remark(备注, string, 可选)、receiving_detail_id(收货明细ID, number, 可选)、allocated_quantity(预分配数量, number, 可选)。传入 items 时忽略顶层的 stock_id/quantity/inbound_type/remark/space_id。" } ], "response": [ @@ -19357,67 +19414,115 @@ "name": "stock_id", "type": "number", "required": false, - "description": "单条模式返回:商品SKU ID" + "description": "商品SKU ID" }, { "name": "quantity", "type": "number", "required": false, - "description": "单条模式返回:本次入库数量" + "description": "本次入库数量" }, { "name": "inbound_type", "type": "string", "required": false, - "description": "单条模式返回:入库方式" + "description": "入库方式" + }, + { + "name": "space_id", + "type": "number", + "required": false, + "description": "存放库位ID" }, { "name": "plan_quantity", "type": "number", "required": false, - "description": "单条模式返回:该商品计划入库总数" + "description": "入库单中该商品计划数量" }, { "name": "existing_before", "type": "number", "required": false, - "description": "单条模式返回:本次入库前已入库数量" + "description": "添加前已有入库总量" }, { "name": "existing_after", "type": "number", "required": false, - "description": "单条模式返回:本次入库后总入库数量" + "description": "添加后入库总量" }, { "name": "remaining", "type": "number", "required": false, - "description": "单条模式返回:剩余可入库数量" + "description": "剩余可入库数量" + }, + { + "name": "receivingBindResult", + "type": "object", + "required": false, + "description": "收货单绑定结果(仅绑定模式返回),含 binding_id、receiving_detail_id、allocated_quantity、status" }, { "name": "count", "type": "number", "required": false, - "description": "批量模式返回:成功添加的条目数" + "description": "批量模式:写入项数" }, { "name": "total_quantity", "type": "number", "required": false, - "description": "批量模式返回:入库总数量" + "description": "批量模式:入库总数量" }, { "name": "items", "type": "array", "required": false, - "description": "批量模式返回:入库结果列表,每项包含 id/stock_id/quantity/inbound_type/space_id/plan_quantity/existing_before/existing_after/remaining" + "description": "批量模式:每项入库记录详情(结构同单条模式)" } ], "errors": [ { "code": 400, - "message": "参数校验失败:entry_order_code 必填 / stock_id 必填 / quantity 必须为正整数 / inbound_type 必须为 import 或 pda / 已作废入库单不允许操作 / 已完成的入库单不允许操作 / 入库单中不存在该 stock_id 的商品 / 入库数量超过计划" + "message": "entry_order_id 必填" + }, + { + "code": 400, + "message": "items[].stock_id 必填 / items[].quantity 必须为正整数 / items[].inbound_type 必须为 import 或 pda" + }, + { + "code": 400, + "message": "已作废入库单不允许操作 / 已完成的入库单不允许操作" + }, + { + "code": 400, + "message": "入库单已绑定收货单且状态为 CREATED,请先审核后再进行上架操作" + }, + { + "code": 400, + "message": "入库单未绑定收货单,无法上架(PENDING)" + }, + { + "code": 400, + "message": "随机入库需要选定收货单明细提交,缺少 receiving_detail_id(PENDING)" + }, + { + "code": 400, + "message": "绑定收货明细时必须指定 space_id" + }, + { + "code": 400, + "message": "入库数量超过计划:商品计划 X,已入库 Y,本次 Z,合计 W" + }, + { + "code": 400, + "message": "收货明细可用数量不足:实际数量 X,已占用 Y,可用 Z" + }, + { + "code": 400, + "message": "入库单中不存在该商品" }, { "code": 404, @@ -19427,7 +19532,7 @@ }, { "method": "storage.entry.commitDirectInbound", - "description": "提交确认完成导入/PDA 入库。按实收数量写入库存(wms_storage、wms_stock_transaction),未入库商品跳过不做处理,更新入库单状态为 COMPLETED,并异步触发奇门/API 入库完成回传(按实收数量回传)。", + "description": "提交确认完成导入/PDA 入库。先同步奇门/API 回传,成功后在 onSuccess 回调内开启事务写入库存(wms_stock_warehouse.quantity 增量、wms_stock_transaction 流水),将 pending 状态的 EntryReceivingBinding 更新为 committed,更新入库单状态为 COMPLETED,同步 sync_status=SUCCESS。不足量提交时未入库商品跳过。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -19440,11 +19545,11 @@ ], "params": [ { - "name": "entry_order_code", - "type": "string", + "name": "entry_order_id", + "type": "number", "required": true, "source": "body", - "description": "入库单号" + "description": "入库单 ID" } ], "response": [ @@ -19488,11 +19593,19 @@ "errors": [ { "code": 400, - "message": "参数校验失败:entry_order_code 必填 / 已作废入库单不允许完成 / 入库单已完成请勿重复提交 / 暂无导入/PDA 入库记录 / 入库单无明细 / 库存写入异常" + "message": "entry_order_id 必填" + }, + { + "code": 400, + "message": "已作废入库单不允许完成 / 入库单已完成请勿重复提交 / 暂无导入/PDA 入库记录请先添加商品 / 入库单无明细" }, { "code": 404, "message": "入库单不存在或无权访问" + }, + { + "code": 500, + "message": "库存写入异常 / 同步回传失败" } ] }, @@ -19732,7 +19845,7 @@ }, { "method": "storage.entry.receivingCompare", - "description": "入库单与收货单商品对照预览:给定入库单ID和收货单ID,返回入库商品与收货商品的逐行对照视图,含匹配状态(matched/entry_only)和汇总统计。纯只读接口。", + "description": "入库单与收货单商品对照预览:给定入库单ID和收货单ID(支持多个),返回入库商品与收货商品的逐行对照视图,含匹配状态(matched/entry_only)和汇总统计。纯只读接口。", "isNeedAuth": false, "isNeedLogin": true, "headers": [], @@ -19747,9 +19860,16 @@ { "name": "receiving_id", "type": "number", - "required": true, + "required": false, "source": "body", - "description": "收货单ID" + "description": "收货单ID,单个时使用,与 receiving_ids 二选一" + }, + { + "name": "receiving_ids", + "type": "array", + "required": false, + "source": "body", + "description": "收货单ID数组,优先使用;与 receiving_id 二选一,传了此参数则忽略 receiving_id" } ], "response": [ @@ -19766,34 +19886,89 @@ "description": "入库单号" }, { - "name": "receiving_id", - "type": "number", - "required": true, - "description": "收货单ID" - }, - { - "name": "receiving_number", - "type": "string", - "required": true, - "description": "收货单号" - }, - { - "name": "comparison", + "name": "comparisons", "type": "array", "required": true, - "description": "逐行对照列表" + "description": "各收货单对照结果列表", + "children": [ + { + "name": "receiving_id", + "type": "number", + "required": true, + "description": "收货单ID" + }, + { + "name": "receiving_number", + "type": "string", + "required": true, + "description": "收货单号" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "对比状态:matched-匹配成功, error-校验失败" + }, + { + "name": "error_code", + "type": "string", + "required": false, + "description": "错误码(仅 status=error 时),如 RECEIVING_NOT_FOUND" + }, + { + "name": "error_message", + "type": "string", + "required": false, + "description": "错误信息(仅 status=error 时)" + }, + { + "name": "comparison", + "type": "array", + "required": false, + "description": "逐行对照列表(仅 status=matched 时),每项含 entry_item_id/stock_id/warehouse_item_code/warehouse_item_name/warehouse_item_spec/entry_count/entry_received/receiving_detail_id/receiving_product_code/receiving_product_name/receiving_actual_quantity/receiving_allocated/receiving_available/match_status" + }, + { + "name": "receiving_only", + "type": "array", + "required": false, + "description": "仅收货单有的商品列表(仅 status=matched 时),每项含 receiving_detail_id/receiving_product_code/receiving_product_name/receiving_actual_quantity/receiving_allocated/receiving_available" + }, + { + "name": "summary", + "type": "object", + "required": false, + "description": "该收货单的汇总统计(仅 status=matched 时),含 total_entry_items/matched_items/entry_only_items/receiving_only_items" + } + ] }, { - "name": "receiving_only", + "name": "errors", "type": "array", - "required": true, - "description": "仅收货单有的商品列表" + "required": false, + "description": "校验失败的收货单列表(status=error 的记录也会在此汇总)" }, { - "name": "summary", + "name": "total_summary", "type": "object", "required": true, - "description": "汇总统计" + "description": "总体汇总统计", + "children": [ + { + "name": "total_receivings", + "type": "number", + "description": "请求的收货单总数" + }, + { + "name": "matched_count", + "type": "number", + "description": "匹配成功的收货单数" + }, + { + "name": "error_count", + "type": "number", + "description": "校验失败的收货单数" + } + ] } ], "errors": [ @@ -19803,27 +19978,355 @@ }, { "code": 400, - "message": "receiving_id 必填" + "message": "receiving_ids 或 receiving_id 必填" }, { "code": 404, "message": "入库单不存在或无权访问" + } + ] + }, + { + "method": "storage.entry.bindReceiving", + "description": "将收货单绑定到入库单(仅建立主表级关联,不做明细数量分配)。校验入库单状态(需为 CREATED 或 PENDING)、收货单有效性(存在、同仓库、未取消)后,逐个建立 wms_entry_order_receiving 绑定记录。支持部分成功:校验通过的写入绑定,不通过的在 failed 列表中返回原因。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "entry_order_id", + "type": "number", + "required": true, + "source": "body", + "description": "入库单ID" + }, + { + "name": "receiving_ids", + "type": "array", + "required": true, + "source": "body", + "description": "要绑定的收货单ID列表,每项为 integer" + } + ], + "response": [ + { + "name": "success", + "type": "array", + "required": true, + "description": "绑定成功列表,每项包含 receiving_id、receiving_number" + }, + { + "name": "failed", + "type": "array", + "required": true, + "description": "绑定失败列表,每项包含 receiving_id、error_code、message", + "items": { + "type": "object", + "properties": { + "receiving_id": { + "type": "number", + "description": "收货单ID" + }, + "receiving_number": { + "type": "string", + "description": "收货单号(部分失败项可能不返回)" + }, + "error_code": { + "type": "string", + "description": "错误码,可能值:RECEIVING_NOT_FOUND(收货单不存在或已删除)、RECEIVING_NOT_REVIEWED(收货单未审核)、WAREHOUSE_MISMATCH(收货单与入库单仓库不一致)、RECEIVING_CANCELLED(收货单已取消)、OWNER_MISMATCH(收货单与入库单货主不一致)、BIND_ERROR(绑定过程异常)" + }, + "message": { + "type": "string", + "description": "中文错误描述" + } + } + } + }, + { + "name": "success_count", + "type": "number", + "required": true, + "description": "成功数量" + }, + { + "name": "failed_count", + "type": "number", + "required": true, + "description": "失败数量" + } + ], + "errors": [ + { + "code": 400, + "message": "参数校验失败:entry_order_id 必填 / receiving_ids 必填且为非空数组 / 入库单状态不允许绑定(当前状态非 CREATED/PENDING)" }, { "code": 404, - "message": "收货单不存在" + "message": "入库单不存在" + }, + { + "code": "OWNER_MISMATCH", + "message": "收货单与入库单货主不一致" + }, + { + "code": "RECEIVING_NOT_REVIEWED", + "message": "收货单未审核" + } + ] + }, + { + "method": "storage.entry.reviewEntry", + "description": "审核入库单(CREATED → PENDING),仅允许已绑定收货单的入库单推进状态", + "isNeedAuth": false, + "isNeedLogin": true, + "isNeedRight": false, + "isNeedLog": true, + "headers": [], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "入库单ID" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "success/failure" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "200 成功 / 400 失败" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息" + }, + { + "name": "data.id", + "type": "number", + "required": true, + "description": "入库单ID" + }, + { + "name": "data.order_status", + "type": "string", + "required": true, + "description": "审核后状态(PENDING)" + } + ], + "errors": [ + { + "code": 400, + "message": "id 必填" + }, + { + "code": 400, + "message": "入库单不存在" + }, + { + "code": 400, + "message": "当前状态[xxx]不允许审核,仅 CREATED 可审核" + }, + { + "code": 400, + "message": "入库单未绑定收货单,请先绑定收货单后再审核" + } + ] + }, + { + "method": "storage.entry.containerList", + "description": "PDA 上架时拉取入库单已绑定收货单中指定商品的可用容器列表(未绑定的收货明细)。返回匹配明细的 detail_id、receiving_id、barcode、product_name、actual_quantity、receiving_status,以及商品详情 stock。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "entry_order_id", + "type": "number", + "required": true, + "source": "body", + "description": "入库单 ID" + }, + { + "name": "stock_id", + "type": "number", + "required": true, + "source": "body", + "description": "商品 stock_id(即 wms_stock_warehouse.id)" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "可用容器(收货明细)列表" + }, + { + "name": "list[].detail_id", + "type": "number", + "required": true, + "description": "收货明细 ID" + }, + { + "name": "list[].receiving_id", + "type": "number", + "required": true, + "description": "收货单 ID" + }, + { + "name": "list[].barcode", + "type": "string", + "required": true, + "description": "商品条码" + }, + { + "name": "list[].product_name", + "type": "string", + "required": true, + "description": "商品名称" + }, + { + "name": "list[].actual_quantity", + "type": "number", + "required": true, + "description": "实收数量" + }, + { + "name": "list[].receiving_status", + "type": "string", + "required": true, + "description": "收货单状态" + }, + { + "name": "list[].stock", + "type": "object", + "required": true, + "description": "商品详情(通过 getStockDetails 获取,含 item_code、item_name、sku_property、barcodes 等缓存字段)" + }, + { + "name": "total", + "type": "number", + "required": true, + "description": "匹配总数" + } + ], + "errors": [ + { + "code": 0, + "message": "用户未绑定仓库" + }, + { + "code": 0, + "message": "entry_order_id 不能为空" + }, + { + "code": 0, + "message": "stock_id 不能为空" + }, + { + "code": 0, + "message": "入库单不存在或无权访问" + }, + { + "code": 500, + "message": "服务器查询失败" + } + ] + }, + { + "method": "storage.entry.queryEntryLogs", + "description": "查询入库单操作日志。根据入库单 ID 分页查询关联的操作日志记录(入库单创建、状态变更、审核等操作的审计轨迹)", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "入库单 ID(必填)" + }, + { + "name": "page", + "type": "number", + "required": false, + "source": "body", + "description": "页码,默认 1" + }, + { + "name": "pageSize", + "type": "number", + "required": false, + "source": "body", + "description": "每页数量,默认 20" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "操作日志列表" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)" + } + ], + "errors": [ + { + "code": 400, + "message": "id 不能为空" + }, + { + "code": 500, + "message": "查询失败" } ] } ] }, { - "groupName": "导入/PDA入库模块", + "groupName": "导入/PDA直接入库", "module": "storage.directInbound", "list": [ { "method": "storage.directInbound.getItems", - "description": "[@deprecated 已弃用,请使用 storage.entry.getDirectInboundItems 替代] 获取入库单的导入/PDA 入库信息,返回入库单基本信息、明细列表,以及每项明细已有的导入/PDA 入库记录(含汇总和剩余可入库数量)。", + "description": "[@deprecated 已弃用,请使用 storage.entry.getDirectInboundItems 替代] 获取入库单的导入/PDA 入库信息(精简版)。返回入库单基本信息、明细列表(含计划数量 planned 与已完成数量 completed)、每项明细的收货绑定列表 bindings(含 detail_id、binding_id、allocated_quantity、space_id、space_name),以及收货单绑定关系 receivingBindings。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -19848,25 +20351,135 @@ "name": "entryOrder", "type": "object", "required": true, - "description": "入库单基本信息(id、entry_order_code、order_type、order_status、source_type、warehouse_id、store_id、remark)" + "description": "入库单基本信息", + "children": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "入库单ID" + }, + { + "name": "entry_order_code", + "type": "string", + "required": true, + "description": "入库单号" + }, + { + "name": "order_status", + "type": "string", + "required": true, + "description": "入库单状态(CREATED/PENDING/COMPLETED/CANCELLED)" + }, + { + "name": "store_remask", + "type": "string", + "required": true, + "description": "货主商家备注" + } + ] }, { "name": "items", "type": "array", "required": true, - "description": "入库明细列表,每项含 id、stock_id、count(计划数量)、received_quantity、direct_inbound_quantity(已导入/PDA入库数量)、remaining_quantity(剩余可入库数量)、pending_binding_total(pending 绑定总量)、bindings(pending 绑定列表,同 storage.entry.get 结构)、direct_logs(已有入库记录)" + "description": "入库明细列表", + "children": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "入库明细ID(wms_entry_items.id)" + }, + { + "name": "stock_id", + "type": "number", + "required": true, + "description": "商品SKU ID" + }, + { + "name": "planned", + "type": "number", + "required": true, + "description": "计划入库数量(对应原 count 字段)" + }, + { + "name": "completed", + "type": "number", + "required": true, + "description": "已完成导入/PDA 入库数量(对应原 direct_inbound_quantity 字段)" + }, + { + "name": "stock", + "type": "object", + "required": true, + "description": "商品详情(含 item_code、item_name、sku_property、barcodes 等缓存字段)" + }, + { + "name": "bindings", + "type": "array", + "required": true, + "description": "该明细的收货单绑定列表", + "children": [ + { + "name": "detail_id", + "type": "number", + "required": false, + "description": "收货明细ID" + }, + { + "name": "binding_id", + "type": "number", + "required": false, + "description": "绑定记录ID" + }, + { + "name": "allocated_quantity", + "type": "number", + "required": false, + "description": "预分配数量" + }, + { + "name": "space_id", + "type": "number", + "required": false, + "description": "存放库位ID" + }, + { + "name": "space_name", + "type": "string", + "required": false, + "description": "库位名称" + } + ] + } + ] }, { - "name": "direct_logs", + "name": "receivingBindings", "type": "array", "required": true, - "description": "该入库单下所有导入/PDA 入库记录(含 space_id)" - }, - { - "name": "summary", - "type": "object", - "required": true, - "description": "汇总信息(total_items、total_planned、total_direct_inbound)" + "description": "入库单层级的收货单绑定关系列表", + "children": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "绑定记录ID" + }, + { + "name": "receiving_id", + "type": "number", + "required": true, + "description": "收货单ID" + }, + { + "name": "receiving", + "type": "object", + "required": true, + "description": "收货单信息(id、receiving_number、status、storage_status、created_at)" + } + ] } ], "errors": [ @@ -19895,11 +20508,11 @@ ], "params": [ { - "name": "entry_order_code", - "type": "string", + "name": "entry_order_id", + "type": "number", "required": true, "source": "body", - "description": "入库单号" + "description": "入库单 ID(必填,通过主键查找入库单)" }, { "name": "stock_id", @@ -20038,11 +20651,11 @@ ], "params": [ { - "name": "entry_order_code", - "type": "string", + "name": "entry_order_id", + "type": "number", "required": true, "source": "body", - "description": "入库单号" + "description": "入库单 ID" } ], "response": [ @@ -20086,7 +20699,11 @@ "errors": [ { "code": 400, - "message": "参数校验失败:entry_order_code 必填 / 已作废入库单不允许完成 / 入库单已完成请勿重复提交 / 暂无导入/PDA 入库记录 / 入库单无明细 / 库存写入异常" + "message": "entry_order_id 必填" + }, + { + "code": 400, + "message": "已作废入库单不允许完成 / 入库单已完成请勿重复提交 / 暂无导入/PDA 入库记录请先添加商品 / 入库单无明细" }, { "code": 404, @@ -20339,13 +20956,101 @@ "list": [ { "method": "storage.inventory.quickPutaway", - "description": "[已删除] 收货单快捷入库上架(此方法已从代码中移除)。原用于单一收货单的快速入库操作,现已弃用。请使用 storage.entry.commitDirectInbound 替代——commitDirectInbound 提供导入/PDA 入库完成确认功能,是目前唯一的库存写入入库链路。", + "description": "收货单快捷入库:将已审核的收货单(completed + is_review=true)明细按 stock_id(system_product_id)分组合并数量后,直接创建入库单(SCRK,自动审批到 PENDING),写入 wms_entry_order_receiving 主表级绑定,并更新收货单及其明细的入库状态(storage_status)。要求货主仓库签约配置 policy_config.allow_receiving_quick_putaway=1 开启快捷入库功能。", "isNeedAuth": true, "isNeedLogin": true, "headers": [], - "params": [], - "response": [], - "errors": [] + "params": [ + { + "name": "receiving_id", + "type": "number", + "required": true, + "source": "body", + "description": "收货单ID(必填)" + } + ], + "response": [ + { + "name": "entry_order_id", + "type": "number", + "description": "创建的入库单ID" + }, + { + "name": "entry_order_code", + "type": "string", + "description": "入库单号(SCRK + 年月日 + 4位流水号)" + }, + { + "name": "order_status", + "type": "string", + "description": "入库单状态(PENDING)" + }, + { + "name": "receiving_id", + "type": "number", + "description": "收货单ID" + }, + { + "name": "total_lines", + "type": "number", + "description": "入库单明细行数(按 stock_id 合并后的行数)" + }, + { + "name": "total_quantity", + "type": "number", + "description": "入库总数量" + } + ], + "errors": [ + { + "code": 400, + "message": "receiving_id 必填" + }, + { + "code": 400, + "message": "无法获取当前仓库信息" + }, + { + "code": 404, + "message": "收货单不存在或无权访问" + }, + { + "code": 400, + "message": "收货单已作废,不允许快捷入库" + }, + { + "code": 400, + "message": "收货单状态不允许快捷入库,仅 completed 状态可操作" + }, + { + "code": 400, + "message": "收货单未审核,不允许快捷入库" + }, + { + "code": 400, + "message": "货主仓库签约关系不存在" + }, + { + "code": 400, + "message": "货主未开启收货单快捷入库功能" + }, + { + "code": 400, + "message": "收货单无明细,无法创建入库单" + }, + { + "code": 400, + "message": "收货单中所有明细均未关联系统商品,无法创建入库单" + }, + { + "code": 400, + "message": "以下商品在当前仓库中不存在或已失效" + }, + { + "code": 500, + "message": "系统异常" + } + ] }, { "method": "storage.inventory.transferLocation", @@ -25508,7 +26213,7 @@ ] }, { - "groupName": "收货管理模块", + "groupName": "收货管理", "module": "storage.receiving", "list": [ { @@ -25520,6 +26225,213 @@ "params": [], "response": [], "errors": [] + }, + { + "method": "storage.receiving.scanDetail", + "description": "PDA 上架扫码定位收货明细:扫描商品条码/箱唛/托盘唛,快速定位收货明细。同一条码可能匹配多条收货明细,以列表 { list, total } 格式返回所有匹配结果。若 barcode 为纯数字优先按明细 ID 精确匹配,否则按商品条码精确匹配。PDA专用。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "entry_order_id", + "type": "number", + "required": true, + "source": "body", + "description": "入库单 ID" + }, + { + "name": "barcode", + "type": "string", + "required": true, + "source": "body", + "description": "扫描条码,支持:收货明细 ID(托盘唛头)、商品条码" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "匹配的收货明细列表" + }, + { + "name": "list[].detail_id", + "type": "number", + "required": true, + "description": "收货明细 ID" + }, + { + "name": "list[].receiving_id", + "type": "number", + "required": true, + "description": "收货单 ID" + }, + { + "name": "list[].barcode", + "type": "string", + "required": true, + "description": "商品条码" + }, + { + "name": "list[].product_name", + "type": "string", + "required": true, + "description": "商品名称" + }, + { + "name": "list[].actual_quantity", + "type": "number", + "required": true, + "description": "实收数量" + }, + { + "name": "list[].receiving_status", + "type": "string", + "required": true, + "description": "收货单状态" + }, + { + "name": "list[].stock", + "type": "object", + "required": true, + "description": "商品详情(通过 getStockDetails 获取,含 item_code、item_name、sku_property、barcodes 等缓存字段)" + }, + { + "name": "total", + "type": "number", + "required": true, + "description": "匹配总数" + } + ], + "errors": [ + { + "code": 0, + "message": "用户未绑定仓库" + }, + { + "code": 0, + "message": "入库单ID不能为空" + }, + { + "code": 0, + "message": "扫描条码不能为空" + }, + { + "code": 0, + "message": "入库单不存在或无权访问" + }, + { + "code": 0, + "message": "该入库单尚未关联收货单" + }, + { + "code": 0, + "message": "未找到可用的收货明细" + }, + { + "code": 0, + "message": "未找到匹配的收货明细" + }, + { + "code": 500, + "message": "服务器扫描查询失败" + } + ] + } + ] + }, + { + "groupName": "入库模块", + "module": "storage", + "list": [ + { + "method": "storage.entry.list", + "description": "入库单列表查询。where.order_status 支持 CREATING/CREATED/PENDING/COMPLETED/CANCELLED。CREATED=已创建待审核(需审核后才能绑定和完成入库),PENDING=已审核(可绑定和完成入库)。where 新增 hasReceiving 虚拟筛选字段,传 true/false 筛选已绑定/未绑定收货单的入库单(通过 wms_entry_order_receiving 表查询实现)。quickWhere 支持模糊搜索:entry_order_code(入库单号)、purchase_order_code(采购单号)、supplier_name(供应商名称)、store_name(货主名称)、warehouse_name(仓库名称)、receiving_id(收货单 ID / 托盘唛头,通过 wms_entry_order_receiving 绑定表关联搜索)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token" + } + ], + "params": [ + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数,支持 page/pageSize" + }, + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "统一 where 条件对象;推荐使用 { operator, value, type } 标准结构,历史简写会在 main 中自动标准化;支持 quickWhere、order_status(CREATING/CREATED/PENDING/COMPLETED/CANCELLED)、store_id、order_type、日期区间等字段。新增 expense_record(费用是否记录)筛选,支持 eq/in;值会归一化为 0/1,兼容 true/false、1/0、y/n、yes/no(大小写不敏感,含布尔/字符串/数字写法)。示例:where.expense_record={operator:eq,value:true} 等价 where.expense_record={operator:eq,value:1};where.expense_record={operator:in,value:[true,\"0\",\"yes\",\"n\"]} 会归一化为 [1,0]。若部署环境尚未完成 expense_record 字段迁移,传入该筛选可能返回 400,错误提示为\"当前环境未提供 expense_record 字段,暂不支持该筛选条件,请先完成表结构升级\"。新增 hasReceiving 虚拟筛选字段,传 true/false 筛选已绑定/未绑定收货单的入库单(虚拟字段,不直接对应数据库列,内部通过 wms_entry_order_receiving 表查询实现)。quickWhere 模糊搜索范围:entry_order_code(入库单号)、purchase_order_code(采购单号)、supplier_name(供应商名称)、store_name(货主名称)、warehouse_name(仓库名称)、receiving_id(收货单 ID / 托盘唛头,通过 wms_entry_order_receiving 绑定表关联搜索)。" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数,支持 sortField/sortOrder" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "入库单列表" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息(page、pageSize、total、totalPages、hasPrevious、hasNext)" + }, + { + "name": "summary", + "type": "object", + "required": true, + "description": "状态汇总(total、pending、creating、created、completed、cancelled)" + }, + { + "name": "list[].receivingBindings", + "type": "array", + "required": false, + "description": "收货单绑定列表(主表级关联),每项含 id、entry_order_id、receiving_id 及 receiving 对象(id、receiving_number、status、storage_status、created_at)" + }, + { + "name": "list[].hasReceiving", + "type": "boolean", + "required": false, + "description": "是否存在收货单绑定" + } + ], + "errors": [ + { + "code": "400", + "message": "筛选条件格式错误", + "description": "筛选条件格式错误" + }, + { + "code": "500", + "message": "查询失败", + "description": "查询失败" + } + ] } ] } diff --git a/skills/entry-order-test-guide.md b/skills/entry-order-test-guide.md new file mode 100644 index 0000000..163288c --- /dev/null +++ b/skills/entry-order-test-guide.md @@ -0,0 +1,449 @@ +# 入库单推送全流程测试指南 + +## 1. 全流程概述 + +``` +奇门推送 entryorder.create → 创建入库单(CREATED) + → bindReceiving(绑定收货单) + → reviewEntry(CREATED→PENDING) + → addItem(PDA上架,传 receiving_detail_id + space_id) + → commit(提交入库+奇门同步→COMPLETED) + +或 quickInbound(虚拟直入,跳过收货单,CREATED→COMPLETED) +``` + +### 流程说明 + +| 阶段 | method | 状态变化 | 说明 | +|------|--------|----------|------| +| 奇门创建 | `qimen.entryorder.create` | (无)→CREATED | 奇门 XML 推送,创建入库单及明细 | +| 绑定收货单 | `storage.entry.bindReceiving` | CREATED→CREATED | 将入库单与收货单关联 | +| 审核 | `storage.entry.reviewEntry` | CREATED→PENDING | 审核通过,允许上架,**必须已绑定收货单** | +| PDA上架 | `storage.directInbound.addItem` | PENDING→PENDING | PDA扫码上架,传 `receiving_detail_id` + `space_id` | +| 提交入库 | `storage.directInbound.commit` | PENDING→COMPLETED | 先奇门同步,再写库存 | +| 虚拟直入 | `storage.entry.quickInbound` | CREATED→COMPLETED | 跳过收货单,一键完成入库 | + +## 2. 关键接口列表 + +| 步骤 | method | 说明 | 入口 | +|------|--------|------|------| +| 创建 | `qimen.entryorder.create` | 奇门推送 XML 创建入库单 | /qimen | +| 绑定 | `storage.entry.bindReceiving` | 绑定收货单到入库单 | /system | +| 审核 | `storage.entry.reviewEntry` | CREATED→PENDING,需已绑定 | /system | +| 上架 | `storage.directInbound.addItem` | PDA添加,可选绑定收货明细 | /system | +| 提交 | `storage.directInbound.commit` | 同步奇门+写库存→COMPLETED | /system | +| 虚拟 | `storage.entry.quickInbound` | 一键虚拟入库 | /system | +| 对照 | `storage.entry.receivingCompare` | 入库单 vs 收货单明细对照 | /system | +| 查询 | `storage.directInbound.getItems` | 查询直入记录 | /system | +| 日志 | `storage.entry.queryEntryLogs` | 查询入库单操作日志 | /system | + +## 3. 踩坑点 + +### 3a. 端口 + +配置文件(`config/config.local.js`)中端口是 **6060**,不是 Egg.js 默认的 7001。 + +```powershell +# 确认端口 +Select-String -Path "config/config.local.js" -Pattern "port" +``` + +### 3b. app_key 双重角色 + +- **签名用**:`config.qimen.appKey`(如 `23535631`),用于奇门请求的 MD5 签名计算 +- **validateApi 查询匹配用**:请求参数中的 `app_key`(如 `23060081`),用于匹配 `wms_api_app` 表记录 +- **两个值不同**,签名的 `app_key` 不参与 `wms_api_app` 绑定查询 + +### 3c. 奇门签名 + +- **签名算法**:`secret + sortedParams + xmlBody + secret` → MD5 → 大写 +- **签名不验证入站请求**:qimen 入口无 `verifyTopRequest` 校验 +- **使用已有合约配置**:从 `wms_api_app` 表读取,不要无中生有创建新配置 + +### 3d. itemId 必传 + +- `itemId` 为空时,按 `item_code + app_key + warehouse_id + store_id` 查询 `StockStore` +- `app_key` 不匹配会导致找不到商品 +- **建议一律传 `itemId`** 以避免匹配问题 + +### 3e. 服务器重启 + +修改代码后需完全重启: + +```powershell +taskkill /F /IM node.exe +npm run dev +``` + +端口被占用排查: + +```powershell +netstat -ano | findstr :6060 +``` + +### 3f. /system 接口需要 headers + +```http +platform: web +project: wms +Authorization: Bearer +``` + +测试账号:`liufumingren` / `111111` + +获取 token: + +```powershell +curl -X POST http://localhost:6060/system?method=user.login ` + -H "platform: web" ` + -H "project: wms" ` + -H "Content-Type: application/json" ` + -d '{"username":"liufumingren","password":"111111"}' +``` + +### 3g. 先同步后写库 + +`quickInbound` 和 `commit` 的执行顺序已改为: + +1. 先调用 `qimenEntrySync` 同步到奇门/ERP +2. 同步成功后才写库存 +3. 同步失败不写库存,只标记为 `FAILED` + +### 3h. 绑定模式 + +`addItem` 传 `receiving_detail_id` 时进入绑定模式: + +- **忽略 `quantity` 字段**,实际数量从 `ReceivingDetail.actual_quantity` 取值 +- **必须传 `space_id`**(库位ID) +- **允许超过入库单 `planQty`**,不受计划数量限制 + +## 4. 快速测试脚本示例 + +### 4.1 准备工作:获取 Token + +```powershell +$loginBody = @{username="liufumingren";password="111111"} | ConvertTo-Json +$loginResp = curl -s -X POST "http://localhost:6060/system?method=user.login" ` + -H "platform: web" -H "project: wms" ` + -H "Content-Type: application/json" ` + -d $loginBody +$token = ($loginResp | ConvertFrom-Json).data.token +Write-Host "Token: $token" +``` + +### 4.2 创建入库单(奇门推送) + +```xml +POST /qimen?method=entryorder.create&app_key=23060081&customerId=4&v=1.0&format=xml&sign_method=md5×tamp=2026-06-27+10:00:00&sign=XXX + + + + TEST-ENTRY-001 + WH001 + JYCK + + + + SKU001 + 100 + + + +``` + +### 4.3 创建收货单 + +```powershell +$rcvBody = @{ + delivery_method="truck" + loading_method="without_pallet" + store_id=1000000 +} | ConvertTo-Json + +curl -s -X POST "http://localhost:6060/system?method=storage.receiving.create" ` + -H "platform: web" -H "project: wms" ` + -H "Authorization: Bearer $token" ` + -H "Content-Type: application/json" ` + -d $rcvBody +``` + +### 4.4 添加收货明细 + +```powershell +$detailBody = @{ + receiving_id="" + item=@{ + product_name="测试商品" + actual_quantity=86 + } +} | ConvertTo-Json + +curl -s -X POST "http://localhost:6060/system?method=storage.receiving.addDetail" ` + -H "platform: web" -H "project: wms" ` + -H "Authorization: Bearer $token" ` + -H "Content-Type: application/json" ` + -d $detailBody +``` + +### 4.5 完成收货 + 审核 + +```powershell +# 完成收货 +curl -s -X POST "http://localhost:6060/system?method=storage.receiving.completeReceiving" ` + -H "platform: web" -H "project: wms" ` + -H "Authorization: Bearer $token" ` + -H "Content-Type: application/json" ` + -d "{`"receiving_id`":`"`"}" + +# 审核收货单 +curl -s -X POST "http://localhost:6060/system?method=storage.receiving.reviewReceiving" ` + -H "platform: web" -H "project: wms" ` + -H "Authorization: Bearer $token" ` + -H "Content-Type: application/json" ` + -d "{`"receiving_id`":`"`"}" +``` + +### 4.6 绑定入库单 + 审核 + +```powershell +# 绑定收货单 +curl -s -X POST "http://localhost:6060/system?method=storage.entry.bindReceiving" ` + -H "platform: web" -H "project: wms" ` + -H "Authorization: Bearer $token" ` + -H "Content-Type: application/json" ` + -d "{`"entry_id`":`"`",`"receiving_id`":`"`"}" + +# 审核入库单 +curl -s -X POST "http://localhost:6060/system?method=storage.entry.reviewEntry" ` + -H "platform: web" -H "project: wms" ` + -H "Authorization: Bearer $token" ` + -H "Content-Type: application/json" ` + -d "{`"entry_id`":`"`"}" +``` + +### 4.7 PDA上架 + 提交 + +```powershell +# 添加直入记录(绑定模式) +$addItemBody = @{ + entry_id="" + receiving_detail_id="" + space_id="" + item_code="SKU001" +} | ConvertTo-Json + +curl -s -X POST "http://localhost:6060/system?method=storage.directInbound.addItem" ` + -H "platform: web" -H "project: wms" ` + -H "Authorization: Bearer $token" ` + -H "Content-Type: application/json" ` + -d $addItemBody + +# 提交入库 +curl -s -X POST "http://localhost:6060/system?method=storage.directInbound.commit" ` + -H "platform: web" -H "project: wms" ` + -H "Authorization: Bearer $token" ` + -H "Content-Type: application/json" ` + -d "{`"entry_id`":`"`"}" +``` + +### 4.8 虚拟直入(跳过收货单) + +```powershell +$quickBody = @{ + entry_id="" + items=@( + @{ + item_code="SKU001" + quantity=50 + space_id="" + } + ) +} | ConvertTo-Json + +curl -s -X POST "http://localhost:6060/system?method=storage.entry.quickInbound" ` + -H "platform: web" -H "project: wms" ` + -H "Authorization: Bearer $token" ` + -H "Content-Type: application/json" ` + -d $quickBody +``` + +## 5. 数据库关键表 + +| 表 | 用途 | 关键字段 | +|----|------|----------| +| `wms_entry_order` | 入库单主表 | id, entry_order_code, order_status, sync_status | +| `wms_entry_items` | 入库单明细 | id, entry_id, item_id, item_code, plan_quantity, actual_quantity | +| `wms_receiving` | 收货单主表 | id, receiving_code, status, store_id | +| `wms_receiving_detail` | 收货单明细 | id, receiving_id, product_name, actual_quantity | +| `wms_entry_order_receiving` | 入库单↔收货单主表绑定 | id, entry_id, receiving_id | +| `wms_entry_receiving_binding` | 入库明细↔收货明细绑定 | id, entry_item_id, receiving_detail_id, quantity | +| `wms_inbound_direct_log` | PDA直入记录 | id, entry_id, item_code, quantity, space_id, receiving_detail_id | +| `wms_api_app` | 奇门应用绑定配置 | id, app_key, app_secret, warehouse_id, store_id | +| `wms_operation_log` | 操作日志 | id, target_type, target_id, action, operator, created_at | + +## 6. 状态机速查 + +| 状态 | 含义 | 可执行操作 | +|------|------|------------| +| `CREATED` | 已创建,待绑定/审核 | bindReceiving, reviewEntry, quickInbound, cancel | +| `PENDING` | 已审核,待上架 | addItem, commit, cancel | +| `COMPLETED` | 已完成 | 不可操作 | +| `CANCELLED` | 已取消 | 不可操作 | +| `FAILED` | 同步失败 | 重试或取消 | + +## 7. 常见问题排查 + +### 7.1 找不到入库单 + +- 检查奇门 XML 中 `warehouseCode` 是否匹配 `wms_api_app` 中的 `warehouse_id` +- 检查 `app_key` 是否已在 `wms_api_app` 表中配置 + +### 7.2 reviewEntry 报错"未绑定收货单" + +- CREATED 状态且未调用 `bindReceiving` 时,审核会被拒绝 +- 先调用 `bindReceiving` 绑定收货单 + +### 7.3 addItem 报错"缺少 space_id" + +- 绑定模式下(传了 `receiving_detail_id`)必须同时传 `space_id` +- `space_id` 对应库位表主键 + +### 7.4 commit 后库存未变化 + +- 检查 `qimenEntrySync` 是否返回成功 +- 同步失败时标记为 `FAILED` 状态,库存不会写入 +- 查看 `wms_operation_log` 中的错误信息 + +### 7.5 端口被占用 + +```powershell +# 查找占用进程 +netstat -ano | findstr :6060 +# 强制结束 +taskkill /F /PID +``` + +## 8. 变更历史 + +| 日期 | 版本 | 变更内容 | +|------|------|----------| +| 2026-06-27 | v1.0 | 初始版本,覆盖入库单全流程测试指南 | +## 8. 问题清单与修复基准(来自 issues.txt) + +### 问题 1:缺失收货单直接转入库单的快捷入口 +- **现状**:收货单创建后,必须先手动创建入库单(走奇门或 OpenAPI),再通过 bindReceiving 绑定 +- **修复后应支持**:storage.receiving.createEntryOrder(receiving_id) → 自动创建入库单并绑定主表关系 + +### 问题 2:addItem 状态机校验不完整 +- **2a**:CREATED + 已绑定收货单 → 应拒绝(当前只强制要求传 receiving_detail_id) +- **2b**:PENDING + 已绑定 + 无明细ID → 应拒绝(当前未区分 CREATED/PENDING) +- **2c**:PENDING + 无绑定 → 应拒绝(PENDING 只能走 PDA 上架,必须已绑定收货单) +- **2d**:CREATED 人工导入 → 应允许超过 planQty(当前非绑定模式不允许超量) + +**修复后校验矩阵:** + +| 状态 | 有绑定 | 携带明细ID | 应允许 | 超 planQty | +|------|--------|-----------|--------|-----------| +| CREATED | 否 | 否 | ✅ 人工后台导入 | ✅ 允许 | +| CREATED | 是 | - | ❌ 拒绝 | - | +| PENDING | 否 | - | ❌ 拒绝 | - | +| PENDING | 是 | 否 | ❌ 拒绝 | - | +| PENDING | 是 | 是 | ✅ PDA上架 | ✅ 允许 | + +### 问题 3:状态机定义 +` +CREATING → CREATED → PENDING → COMPLETED + ↑ ↓ ↑ + └── 重试推送 ────────┘ │ + CANCELLED ←────────┘ +` +- CREATED:等待人工绑定和审核,可走人工后台导入(不限制 planQty),可走虚拟直入 +- PENDING:已审核,待上架/上架中,必须已绑定收货单,必须携带 receiving_detail_id +- COMPLETED:已完成,不可操作 + +### 问题 4:entryorderConfirm 增量回传应移除 +- 统一走 qimenEntrySync 全量同步,actualQty = item.count +- 移除 entry_order.js 的 entryorderConfirm 方法 + +### 问题 5:completeEntry 应作废 +- commit 已包含所有实质性工作(写库存、同步奇门、推进 COMPLETED) +- completeEntry 无独立存在意义 + +### 问题 6:入库单取消 +- 6a:取消时调用 qimenEntrySync,orderLines 全部 actualQty=0,通知 ERP 关闭 +- 6b:sync_status=SUCCESS 的入库单不允许取消(已通知 ERP 入库完成) +- 允许取消的状态:sync_status != 'SUCCESS' 且 order_status NOT IN ('COMPLETED','CANCELLED') + +## 9. 完整测试场景 + +### 场景 A:奇门创建 + 收货单 + PDA上架(完整链路) +` +1. qimen.entryorder.create → CREATED +2. storage.receiving.create → 收货单 +3. storage.receiving.addDetail → 收货明细 +4. storage.receiving.completeReceiving → 完成收货 +5. storage.receiving.reviewReceiving → 审核收货单 +6. storage.entry.bindReceiving → 绑定入库单↔收货单 +7. storage.entry.receivingCompare → 对照预览 +8. storage.entry.reviewEntry → CREATED→PENDING +9. storage.directInbound.addItem(receiving_detail_id) → PDA上架+明细绑定 +10. storage.directInbound.commit → 奇门同步+写库存→COMPLETED +` + +### 场景 B:人工后台导入(无收货单) +` +1. qimen.entryorder.create → CREATED +2. storage.directInbound.addItem(无 receiving_detail_id) → 人工导入 +3. storage.directInbound.commit → 奇门同步+写库存→COMPLETED +` + +### 场景 C:虚拟直入 +` +1. qimen.entryorder.create → CREATED +2. storage.entry.quickInbound → 奇门同步+写库存→COMPLETED(一步完成) +` + +### 场景 D:取消入库单 +` +1. 入库单 CREATED/PENDING 且 sync_status != SUCCESS +2. storage.entry.cancel → ①发送 qimenEntrySync(all actualQty=0) → ②更新 order_status=CANCELLED +` + +## 10. 数据库校验检查点 + +修复完成后,以下 SQL 可用于验证各场景正确性: + +\\\sql +-- 验证入库单状态 +SELECT id, entry_order_code, order_status, sync_status, sync_message FROM wms_entry_order WHERE id = ?; + +-- 验证入库明细收货量 +SELECT id, item_code, count, received_quantity, confirm_quantity FROM wms_entry_items WHERE order_id = ?; + +-- 验证主表绑定 +SELECT * FROM wms_entry_order_receiving WHERE entry_order_id = ?; + +-- 验证明细绑定 +SELECT id, entry_item_id, receiving_detail_id, allocated_quantity, status FROM wms_entry_receiving_binding WHERE entry_item_id IN (SELECT id FROM wms_entry_items WHERE order_id = ?); + +-- 验证直入记录 +SELECT id, stock_id, quantity, space_id FROM wms_inbound_direct_log WHERE entry_order_id = ?; + +-- 验证库存写入 +SELECT id, stock_id, batch_no, quantity, receiving_id, production_date, expiry_date FROM wms_storage WHERE entry_order_id = ?; + +-- 验证操作日志 +SELECT id, business_type, business_id, operation_code, message FROM wms_operation_log WHERE business_id = ? AND business_type = 'entry_order' ORDER BY created_at DESC; +\\\ + +## 11. 已知操作码清单 + +| operationCode | 触发接口 | 说明 | +|---------------|---------|------| +| ENTRY_ORDER_CREATE | qimen/OpenAPI entryorder.create | 入库单创建 | +| ENTRY_ORDER_REVIEW | storage.entry.reviewEntry | 审核通过 CREATED→PENDING | +| DIRECT_INBOUND_ADD | storage.directInbound.addItem | 直入记录添加 | +| DIRECT_INBOUND_COMMIT | storage.directInbound.commit | 提交入库 COMPLETED | +| DIRECT_INBOUND_REMOVE | storage.directInbound.removeItem | 移除直入记录 | +| QUICK_INBOUND | storage.entry.quickInbound | 虚拟直入完成 | +| QUICK_INBOUND_FAILED | quickInbound/commit 失败 | 同步失败 | diff --git a/temp_check_prod_migrations.js b/temp_check_prod_migrations.js deleted file mode 100644 index 42cdf9c..0000000 --- a/temp_check_prod_migrations.js +++ /dev/null @@ -1,71 +0,0 @@ -const mysql = require('mysql2/promise'); -const path = require('path'); -const fs = require('fs'); - -function walk(dir) { - const result = []; - const entries = fs.readdirSync(dir, { withFileTypes: true }); - for (const e of entries) { - const full = path.join(dir, e.name); - if (e.isDirectory()) result.push(...walk(full)); - else if (e.name.endsWith('.js')) result.push(e.name); - } - return result; -} - -(async () => { - const files = walk('database/migrations'); - console.log('迁移目录全部 .js 文件:', files.length, '个'); - - try { - const c = await mysql.createConnection({ - host: '112.124.21.102', - port: 3306, - user: 'wms', - password: 'P6j3YTHTpirepYWz', - database: 'wms', - charset: 'utf8mb4', - connectTimeout: 10000, - }); - - // 查迁移相关表 - const [tables] = await c.query( - "SELECT TABLE_NAME FROM information_schema.TABLES WHERE TABLE_SCHEMA='wms' AND (TABLE_NAME LIKE '%sequelize%' OR TABLE_NAME LIKE '%migration%') ORDER BY TABLE_NAME" - ); - console.log('\n=== 迁移相关表 ==='); - if (tables.length === 0) console.log(' 无'); - else tables.forEach(t => console.log(' ' + t.TABLE_NAME)); - - // 尝试查 sequelizemeta - try { - const [rows] = await c.query('SELECT name FROM sequelizemeta ORDER BY name'); - console.log('\nsequelizemeta 表记录数:', rows.length); - rows.forEach(r => console.log(' ' + r.name)); - } catch (e) { - console.log('\nsequelizemeta 表不存在或查询失败:', e.message); - } - - // 尝试查 SequelizeMeta (大写) - try { - const [rows] = await c.query('SELECT name FROM SequelizeMeta ORDER BY name'); - console.log('\nSequelizeMeta 表记录数:', rows.length); - rows.forEach(r => console.log(' ' + r.name)); - } catch (e) { - console.log('SequelizeMeta 表不存在或查询失败:', e.message); - } - - // 表总数 - const [cnt] = await c.query("SELECT COUNT(*) AS cnt FROM information_schema.TABLES WHERE TABLE_SCHEMA='wms'"); - console.log('\n生产数据库表总数:', cnt[0].cnt); - - await c.end(); - - // 对比 - if (tables.length > 0) { - console.log('\n=== 结论 ==='); - console.log('请检查上述迁移记录表,对比迁移目录中', files.length, '个文件即可知道未执行迁移。'); - } - } catch (e) { - console.log('连接错误:', e.code, e.message); - } -})(); diff --git a/temp_storage_entry_old.js b/temp_storage_entry_old.js deleted file mode 100644 index 2bb3f27..0000000 Binary files a/temp_storage_entry_old.js and /dev/null differ diff --git a/temp_systemMethods_storage_entry_old.js b/temp_systemMethods_storage_entry_old.js deleted file mode 100644 index e1225ba..0000000 Binary files a/temp_systemMethods_storage_entry_old.js and /dev/null differ diff --git a/test/app/service/systems/order_storage_allocation.test.js b/test/app/service/systems/order_storage_allocation.test.js index c865550..dfd1863 100644 --- a/test/app/service/systems/order_storage_allocation.test.js +++ b/test/app/service/systems/order_storage_allocation.test.js @@ -1478,4 +1478,225 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => { assert.ok(skipLog, '应有订单 53 的日志'); assert.ok(skipLog.extras.message.includes('跳过'), `跳过订单应含"跳过",实际: ${skipLog.extras.message}`); }); + + // ============================================================ + // 场景 5:space_id 无效时内存计数器回退验证 + // 当 storageRow.space_id 为 0 时,代码应: + // 1) 回退 allocatedQuantityForOrder(不应计入已分配量) + // 2) 回退 allocatedQuantityForItem + // 3) 回退 remainingQuantity(未分配成功的应加回) + // 4) 回退 storageAllocationMap + // 5) 调用 unlockQuantity 释放数据库锁 + // 核心 BUG:当前代码没有回退 allocatedQuantityForOrder/allocatedQuantityForItem/remainingQuantity + // ============================================================ + it('should rollback memory counters when storage space_id is invalid (zero)', async () => { + const { service, captures, storageRows, stockRows } = createHarness({ + orders: [ + { id: 601, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 }, + ], + orderItems: [ + { id: 6011, order_id: 601, stock_id: 901, plan_qty: 10, order_line_no: '1' }, + ], + stockRows: [ + { id: 901, item_code: 'SKU-901', item_name: '测试商品901', warehouse_id: 100000, deleted_at: null, is_valid: 'Y', locked_quantity: 0 }, + ], + storageRows: [ + // 库存A:有库存但 space_id = 0 → 无效,分配时应该回退 + { + id: 9001, + warehouse_id: 100000, + stock_id: 901, + is_enabled: 1, + delete_at: null, + available_quantity: 5, + quantity: 5, + locked_quantity: 0, + production_date: null, + inbound_time: '2026-06-20 08:00:00', + space_id: 0, // ← 无效 space_id,触发回退逻辑 + space: null, + }, + // 库存B:有效库存,space_id 有效 + { + id: 9002, + warehouse_id: 100000, + stock_id: 901, + is_enabled: 1, + delete_at: null, + available_quantity: 10, + quantity: 10, + locked_quantity: 0, + production_date: null, + inbound_time: '2026-06-20 09:00:00', + space_id: 50, + space: { + id: 50, + space_code: 'VALID-01', + custom_name: '有效库位', + is_preferred_pick: false, + locationType: { id: 1, allow_allocation: 1, is_active: 1 }, + }, + }, + ], + policies: { + 901: { policyConfig: { storage_separation: 1 } }, + }, + }); + + const result = await service.allocateStorage({ + allow_storage_location: true, + order_ids: [ 601 ], + }); + + // ============================================================= + // 核心断言:验证内存计数器回退 + // ============================================================= + // + // 订单需要 qty=10 + // 库存A: available=5, space_id=0 → lockQuantity 扣 5 → + // 空间无效 → unlockQuantity 释放 5,回退 remainingQuantity(+5) + // 库存B: available=10, space_id=50 → Math.min(remainingQuantity=10, 10)=10 + // → lockQuantity 扣 10 → remainingQuantity=0 + // + // 如果回退正确:库存B 10个全部满足 → storage_status = fin,allocated_quantity = 10 + // 如果回退不正确(BUG):库存B只锁5个 → storage_status = error,allocated_quantity = 5 + + const orderResult = result.data.orders.find(item => item.order_id === 601); + assert.ok(orderResult, '返回结果应包含订单601'); + + assert.equal( + orderResult.storage_status, + 'fin', + '空间无效库存被回退后,有效库存B应满足全部10个需求,storage_status 应为 fin,' + + `实际 storage_status=${orderResult.storage_status}` + ); + + assert.equal( + orderResult.allocated_quantity, + 10, + 'allocated_quantity 应为 10(库存B全部满足),' + + `实际 allocated_quantity=${orderResult.allocated_quantity}` + ); + + // 2) 验证 unlockQuantity 被调用(数据库锁释放) + const spaceIdInvalidUnlock = captures.storageUnlocks.find( + item => item.storageId === 9001 + ); + assert.ok(spaceIdInvalidUnlock, 'space_id=0 的库存应调用 unlockQuantity 释放锁'); + assert.equal(spaceIdInvalidUnlock.quantity, 5, '应释放 5 个锁定数量'); + + // 3) 验证有效库存被正确锁定(应为 10 个,因为库存B有10个满足全部需求) + const validLock = captures.storageLocks.find( + item => item.storageId === 9002 + ); + assert.ok(validLock, '有效库存B应被锁定'); + assert.equal(validLock.quantity, 10, '应从有效库存B锁定 10 个(满足全部需求)'); + + // 4) 验证 storageAllocationMap — 无效库存不应在映射中 + // 因为回退后 newStorageQty=0,会执行 delete + assert.equal( + storageRows.find(r => r.id === 9001).locked_quantity, + 0, + '无效库存的 locked_quantity 应回退到 0' + ); + + // 5) 验证 picking rows — 只有有效库存的记录 + assert.ok(Array.isArray(captures.pickingRows), '应有 picking 记录'); + assert.equal(captures.pickingRows.length, 1, '应只有 1 条 picking 记录(有效库存)'); + assert.equal(captures.pickingRows[0].storage_id, 9002, 'picking 应为有效库存B'); + assert.equal(captures.pickingRows[0].quantity, 10, 'picking 数量应为 10'); + + // 6) 验证 stock_warehouse locked_quantity + const matchedStock = stockRows.find(r => r.id === 901); + assert.ok(matchedStock, '应有对应 stock 记录'); + }); + + // ============================================================ + // 场景 6:space_id 无效时,如果有足够的其他有效库存满足需求,订单应为 fin + // ============================================================ + it('should correctly mark order as fin when other valid storages satisfy demand despite invalid space_id', async () => { + const { service, captures, storageRows } = createHarness({ + orders: [ + { id: 602, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2 }, + ], + orderItems: [ + { id: 6021, order_id: 602, stock_id: 902, plan_qty: 5, order_line_no: '1' }, + ], + stockRows: [ + { id: 902, item_code: 'SKU-902', item_name: '测试商品902', warehouse_id: 100000, deleted_at: null, is_valid: 'Y', locked_quantity: 0 }, + ], + storageRows: [ + // 库存A:space_id 无效 + { + id: 9101, + warehouse_id: 100000, + stock_id: 902, + is_enabled: 1, + delete_at: null, + available_quantity: 3, + quantity: 3, + locked_quantity: 0, + production_date: null, + inbound_time: '2026-06-20 08:00:00', + space_id: 0, + space: null, + }, + // 库存B:有效库存,足够满足全部需求 + { + id: 9102, + warehouse_id: 100000, + stock_id: 902, + is_enabled: 1, + delete_at: null, + available_quantity: 10, + quantity: 10, + locked_quantity: 0, + production_date: null, + inbound_time: '2026-06-20 09:00:00', + space_id: 60, + space: { + id: 60, + space_code: 'VALID-02', + custom_name: '有效库位2', + is_preferred_pick: false, + locationType: { id: 1, allow_allocation: 1, is_active: 1 }, + }, + }, + ], + policies: { + 902: { policyConfig: { storage_separation: 1 } }, + }, + }); + + const result = await service.allocateStorage({ + allow_storage_location: true, + order_ids: [ 602 ], + }); + + const orderResult = result.data.orders.find(item => item.order_id === 602); + assert.ok(orderResult, '返回结果应包含订单602'); + + // 订单需要5个,库存A无效(已回退),库存B可满足5个 + // 如果 remainingQuantity 正确回退:5-3=2 → 回退+3 → 5 → 再扣5 → 0 → fin + // 如果 remainingQuantity 未回退:5-3=2 → 再扣2 → 0 → fin(碰巧也能正确) + // 所以这个场景两个行为都可能导致 fin,关键验证 unlockedQuantity 被调用 + assert.equal(orderResult.storage_status, 'fin', '应标记为 fin'); + assert.equal(orderResult.status, 'success', '应为 success'); + + // 验证 unlockQuantity 确实被调用 + const spaceIdInvalidUnlock = captures.storageUnlocks.find( + item => item.storageId === 9101 + ); + assert.ok(spaceIdInvalidUnlock, 'space_id=0 的库存应调用 unlockQuantity'); + assert.equal(spaceIdInvalidUnlock.quantity, 3, '应释放 3 个锁定'); + + // 验证有效库存的 locked_quantity + assert.equal(storageRows.find(r => r.id === 9101).locked_quantity, 0, '无效库存 locked_quantity 应回退到 0'); + assert.equal(storageRows.find(r => r.id === 9102).locked_quantity, 5, '有效库存 locked_quantity 应为 5'); + + // 验证 picking rows + assert.equal(captures.pickingRows.length, 1, '应只有 1 条 picking'); + assert.equal(captures.pickingRows[0].storage_id, 9102, 'picking 应为有效库存'); + assert.equal(captures.pickingRows[0].quantity, 5, 'picking 数量应为 5'); + }); });