From 190d3cf9e5d55c613cbde88736e4d46ddc6a25b5 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Fri, 2 Oct 2026 15:43:49 +0800 Subject: [PATCH] =?UTF-8?q?feat(stock.check):=20=E7=9B=98=E7=82=B9?= =?UTF-8?q?=E6=A8=A1=E5=9D=97=E5=8A=9F=E8=83=BD=E6=89=A9=E5=B1=95=E5=B9=B6?= =?UTF-8?q?=E5=90=8C=E6=AD=A5=E6=8E=A5=E5=8F=A3=E6=96=87=E6=A1=A3=EF=BC=88?= =?UTF-8?q?0.3.227=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 盘点明细/记录支持未知商品(stock_id 可空)与库位范围,模式/状态口径修正 - 新增静态盘点任务、公告相关模型与迁移,stock_warehouse 增加预警数量 - methods/system.json 同步盘点接口文档;headers platform 微信端取值 wx 修正为 miniprogram --- app/model/stock_check.js | 10 +- app/model/stock_check_detail.js | 34 +- app/model/stock_check_record.js | 20 +- app/model/stock_static_check_task.js | 57 + app/model/stock_static_notice.js | 57 + app/model/stock_warehouse.js | 5 + app/model/store.js | 33 + app/service/systemMethods/stock/check.js | 267 +- app/service/systemMethods/stock/warehouse.js | 28 +- app/service/systems/pick.js | 4 + app/service/systems/setting/warehouse.js | 26 + app/service/systems/stock_check.js | 2800 +++++++++++++++-- app/service/systems/stock_check_patterns.js | 445 +++ app/service/systems/stock_store.js | 21 +- app/service/systems/stock_transaction.js | 84 +- app/service/systems/stock_warehouse.js | 219 ++ ...warning-quantity-to-wms-stock-warehouse.js | 17 + ...rt-location-scope-in-stock-check-detail.js | 131 + ...ype-stock-time-to-wms-stock-transaction.js | 16 + ...30130000-create-wms-stock-static-notice.js | 63 + ...0000-create-wms-stock-static-check-task.js | 63 + ...-remove-check-date-from-wms-stock-check.js | 56 + ...ort-unknown-goods-in-stock-check-record.js | 40 + methods/changes/system.json | 404 +++ methods/system.json | 729 ++++- 25 files changed, 5188 insertions(+), 441 deletions(-) create mode 100644 app/model/stock_static_check_task.js create mode 100644 app/model/stock_static_notice.js create mode 100644 app/service/systems/stock_check_patterns.js create mode 100644 database/migrations/20260930110000-add-warning-quantity-to-wms-stock-warehouse.js create mode 100644 database/migrations/20260930110000-support-location-scope-in-stock-check-detail.js create mode 100644 database/migrations/20260930120000-add-index-wh-type-stock-time-to-wms-stock-transaction.js create mode 100644 database/migrations/20260930130000-create-wms-stock-static-notice.js create mode 100644 database/migrations/20260930140000-create-wms-stock-static-check-task.js create mode 100644 database/migrations/20260930150000-remove-check-date-from-wms-stock-check.js create mode 100644 database/migrations/20261001100000-support-unknown-goods-in-stock-check-record.js diff --git a/app/model/stock_check.js b/app/model/stock_check.js index 3b4d6cc..a98b1a1 100644 --- a/app/model/stock_check.js +++ b/app/model/stock_check.js @@ -64,20 +64,15 @@ module.exports = app => { defaultValue: 'none_checked', comment: '明细盘点进度:none_checked=未盘,partial_checked=部分已盘,all_checked=全部已盘', }, - check_date: { - type: DATE, - allowNull: false, - comment: '盘点日期', - }, start_time: { type: DATE, allowNull: true, - comment: '实际开始时间', + comment: '盘点开始时间(第一个盘点明细写入的时间)', }, end_time: { type: DATE, allowNull: true, - comment: '实际结束时间', + comment: '盘点结束时间(完成盘点的时间)', }, creator_id: { type: BIGINT(20).UNSIGNED, @@ -121,7 +116,6 @@ module.exports = app => { paranoid: false, indexes: [ { name: 'uk_check_no', unique: true, fields: [ 'check_no' ] }, - { name: 'idx_warehouse_check_date', fields: [ 'warehouse_id', 'check_date' ] }, { name: 'idx_warehouse_status', fields: [ 'warehouse_id', 'status' ] }, { name: 'idx_store_id', fields: [ 'store_id' ] }, { name: 'idx_creator_id', fields: [ 'creator_id' ] }, diff --git a/app/model/stock_check_detail.js b/app/model/stock_check_detail.js index 5c90d03..d621bd9 100644 --- a/app/model/stock_check_detail.js +++ b/app/model/stock_check_detail.js @@ -1,7 +1,9 @@ 'use strict'; /** - * 库存盘点明细表模型(仅存盘点商品:stock_id + 商品快照)。 + * 库存盘点明细表模型(盘点范围行:商品或库位)。 + * 商品行(scope_type=goods):stock_id + 商品快照 + 账面数量快照; + * 库位行(scope_type=location):location_id/location_code + stock_id/item_code 为空。 * 库位/数量等盘点作业信息存放在 wms_stock_check_record。 * @param {import('egg').Application} app Egg 应用实例。 * @return {import('sequelize').ModelCtor} Sequelize 模型。 @@ -26,15 +28,31 @@ module.exports = app => { allowNull: false, comment: '仓库ID(冗余,隔离查询)', }, + scope_type: { + type: STRING(20), + allowNull: false, + defaultValue: 'goods', + comment: '盘点范围类型:goods=商品,location=库位', + }, stock_id: { type: BIGINT(20).UNSIGNED, - allowNull: false, - comment: '库存商品ID,关联 wms_stock_warehouse.id', + allowNull: true, + comment: '库存商品ID,关联 wms_stock_warehouse.id;库位盘点行为空', + }, + location_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '库位ID,关联 wms_location_space.id;库位盘点行为空', + }, + location_code: { + type: STRING(50), + allowNull: true, + comment: '库位编码(space_code);库位盘点行为空', }, item_code: { type: STRING(50), - allowNull: false, - comment: '商品编码快照', + allowNull: true, + comment: '商品编码快照;库位盘点行为空', }, item_name: { type: STRING(255), @@ -55,7 +73,7 @@ module.exports = app => { type: INTEGER(12), allowNull: false, defaultValue: 0, - comment: '账面数量快照(生成盘点明细时的系统库存,用于差异对比)', + comment: '账面数量快照(生成盘点明细时的系统库存,用于差异对比;库位行固定为 0,账面按 wms_storage 现算)', }, remark: { type: STRING(500), @@ -64,7 +82,7 @@ module.exports = app => { }, }, { tableName: 'wms_stock_check_detail', - comment: '库存盘点明细表(盘点商品清单)', + comment: '库存盘点明细表(盘点范围行:商品或库位)', timestamps: true, createdAt: 'created_at', updatedAt: 'updated_at', @@ -73,6 +91,8 @@ module.exports = app => { { name: 'idx_check_id', fields: [ 'check_id' ] }, { name: 'idx_warehouse_stock', fields: [ 'warehouse_id', 'stock_id' ] }, { name: 'idx_stock_id', fields: [ 'stock_id' ] }, + { name: 'uk_check_stock', unique: true, fields: [ 'check_id', 'stock_id' ] }, + { name: 'uk_check_location', unique: true, fields: [ 'check_id', 'location_code' ] }, ], }); diff --git a/app/model/stock_check_record.js b/app/model/stock_check_record.js index 8bc0451..42bcf7a 100644 --- a/app/model/stock_check_record.js +++ b/app/model/stock_check_record.js @@ -2,7 +2,10 @@ /** * 库存盘点作业记录表模型(存储盘点的库位、数量信息)。 - * 一个盘点明细(商品)可在多个库位多次上报,每次上报一条记录。 + * 一个盘点明细(商品行或库位行)可在多个库位/商品维度多次上报,每次上报一条记录; + * 覆盖式语义为「同明细 + 同商品 + 同库位」(uk_detail_stock_location 唯一索引); + * 支持未知商品(仿收货明细口径):stock_id 为空(NULL)+ barcode + item_name, + * 唯一索引中 NULL 不参与唯一约束,未知商品查重由应用层保证。 * @param {import('egg').Application} app Egg 应用实例。 * @return {import('sequelize').ModelCtor} Sequelize 模型。 */ @@ -33,8 +36,18 @@ module.exports = app => { }, stock_id: { type: BIGINT(20).UNSIGNED, - allowNull: false, - comment: '库存商品ID(冗余,商品维度查询),关联 wms_stock_warehouse.id', + allowNull: true, + comment: '库存商品ID(冗余,商品维度查询),关联 wms_stock_warehouse.id;NULL=未知商品', + }, + barcode: { + type: STRING(100), + allowNull: true, + comment: '扫描到的条码/编码(未知商品上报使用;已知商品可为空)', + }, + item_name: { + type: STRING(255), + allowNull: true, + comment: '未知商品名称快照(缺省为条码);已知商品为空', }, location_id: { type: BIGINT(20).UNSIGNED, @@ -85,6 +98,7 @@ module.exports = app => { { name: 'idx_detail_id', fields: [ 'detail_id' ] }, { name: 'idx_stock_id', fields: [ 'stock_id' ] }, { name: 'idx_warehouse_location', fields: [ 'warehouse_id', 'location_code' ] }, + { name: 'uk_detail_stock_location', unique: true, fields: [ 'detail_id', 'stock_id', 'location_code' ] }, ], }); diff --git a/app/model/stock_static_check_task.js b/app/model/stock_static_check_task.js new file mode 100644 index 0000000..440509b --- /dev/null +++ b/app/model/stock_static_check_task.js @@ -0,0 +1,57 @@ +'use strict'; + +module.exports = app => { + const { BIGINT, DATE } = app.Sequelize; + + const StockStaticCheckTask = app.model.define('stock_static_check_task', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + stock_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '商品ID,关联 wms_stock_warehouse.id', + }, + task_time: { + type: DATE, + allowNull: false, + comment: '创建盘点任务时间(有记录即表示已为该静态商品创建过盘点任务)', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + deleted_at: { + type: DATE, + defaultValue: null, + comment: '软删除时间', + }, + }, { + tableName: 'wms_stock_static_check_task', + freezeTableName: true, + timestamps: false, + paranoid: true, + comment: '静态商品盘点任务关联表(记录是否已为静态商品创建盘点任务,避免重复创建)', + indexes: [ + { + name: 'idx_stock_task_time', + fields: [ 'stock_id', 'task_time' ], + }, + { + name: 'idx_task_time', + fields: [ 'task_time' ], + }, + ], + }); + + return StockStaticCheckTask; +}; diff --git a/app/model/stock_static_notice.js b/app/model/stock_static_notice.js new file mode 100644 index 0000000..1480ce0 --- /dev/null +++ b/app/model/stock_static_notice.js @@ -0,0 +1,57 @@ +'use strict'; + +module.exports = app => { + const { BIGINT, DATE } = app.Sequelize; + + const StockStaticNotice = app.model.define('stock_static_notice', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键ID', + }, + stock_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '商品ID,关联 wms_stock_warehouse.id', + }, + notice_time: { + type: DATE, + allowNull: false, + comment: '通知时间', + }, + created_at: { + type: DATE, + allowNull: false, + comment: '创建时间', + }, + updated_at: { + type: DATE, + allowNull: false, + comment: '更新时间', + }, + deleted_at: { + type: DATE, + defaultValue: null, + comment: '软删除时间', + }, + }, { + tableName: 'wms_stock_static_notice', + freezeTableName: true, + timestamps: false, + paranoid: true, + comment: '静态商品通知关联表(记录静态商品已通知时间,避免重复通知)', + indexes: [ + { + name: 'idx_stock_notice_time', + fields: [ 'stock_id', 'notice_time' ], + }, + { + name: 'idx_notice_time', + fields: [ 'notice_time' ], + }, + ], + }); + + return StockStaticNotice; +}; diff --git a/app/model/stock_warehouse.js b/app/model/stock_warehouse.js index 92fd08a..f73edcd 100644 --- a/app/model/stock_warehouse.js +++ b/app/model/stock_warehouse.js @@ -175,6 +175,11 @@ module.exports = app => { defaultValue: 0, comment: '锁定数量', }, + warning_quantity: { + type: INTEGER(11), + defaultValue: 0, + comment: '库存预警数量', + }, prohibited_id: { type: INTEGER.UNSIGNED, comment: '违禁品类型id', diff --git a/app/model/store.js b/app/model/store.js index 3db1c62..4c20ee3 100644 --- a/app/model/store.js +++ b/app/model/store.js @@ -98,6 +98,9 @@ module.exports = app => { group_order_pack_max_minutes: 40, big_group_pack_coefficient: 3, single_weigh_require_pack: false, + stock_warning_enabled: false, + stock_warning_quantity: 0, + stock_static_hours: 168, return_unpack_max_record_minutes: 5, inventory_warning_rules: DEFAULT_INVENTORY_WARNING_RULES, auto_outbound_rules: DEFAULT_AUTO_OUTBOUND_RULES, @@ -540,6 +543,36 @@ module.exports = app => { ); } + // 是否开启库存预警:默认关闭 + if (Object.prototype.hasOwnProperty.call(parsed, 'stock_warning_enabled')) { + normalized.stock_warning_enabled = normalizeBooleanFlag( + parsed.stock_warning_enabled, + 'subject_config.stock_warning_enabled' + ); + } + + const rawStockWarningQuantity = parsed.stock_warning_quantity; + if (rawStockWarningQuantity === undefined || rawStockWarningQuantity === null || rawStockWarningQuantity === '') { + normalized.stock_warning_quantity = DEFAULT_SUBJECT_CONFIG.stock_warning_quantity; + } else { + const stockWarningQuantity = Number(rawStockWarningQuantity); + if (!Number.isInteger(stockWarningQuantity) || stockWarningQuantity < 0) { + throw new Error('subject_config.stock_warning_quantity 必须是非负整数'); + } + normalized.stock_warning_quantity = stockWarningQuantity; + } + + const rawStockStaticHours = parsed.stock_static_hours; + if (rawStockStaticHours === undefined || rawStockStaticHours === null || rawStockStaticHours === '') { + normalized.stock_static_hours = DEFAULT_SUBJECT_CONFIG.stock_static_hours; + } else { + const stockStaticHours = Number(rawStockStaticHours); + if (!Number.isFinite(stockStaticHours) || stockStaticHours <= 0) { + throw new Error('subject_config.stock_static_hours 必须是大于 0 的数字(小时)'); + } + normalized.stock_static_hours = stockStaticHours; + } + const rawReturnUnpackMaxRecordMinutes = parsed.return_unpack_max_record_minutes; if (rawReturnUnpackMaxRecordMinutes === undefined || rawReturnUnpackMaxRecordMinutes === null || rawReturnUnpackMaxRecordMinutes === '') { normalized.return_unpack_max_record_minutes = DEFAULT_SUBJECT_CONFIG.return_unpack_max_record_minutes; diff --git a/app/service/systemMethods/stock/check.js b/app/service/systemMethods/stock/check.js index 6bb1b90..408a419 100644 --- a/app/service/systemMethods/stock/check.js +++ b/app/service/systemMethods/stock/check.js @@ -8,8 +8,8 @@ const STOCK_CHECK_EXPORT_TASK_CACHE_TTL_SECONDS = 1800; /** 单次导出任务允许的最大盘点任务数量 */ const STOCK_CHECK_EXPORT_MAX_TASK_IDS = 50; -/** 全部 14 个 method 名(免权限/免鉴权清单共用) */ -const ALL_METHOD_NAMES = 'create,list,addDetail,detailDelete,detail,report,recordList,recordDelete,finish,submit,cancel,audit,export,exportTaskProgress'; +/** 全部 20 个 method 名(免权限/免鉴权清单共用) */ +const ALL_METHOD_NAMES = 'create,list,addDetail,addLocationDetail,detailDelete,detail,result,workData,report,recordList,recordDelete,finish,submit,cancel,audit,batchDelete,export,exportTaskProgress,patternList,patternCreate'; /** * 系统方法层:stock.check(库存盘点模块接口包装层)。 @@ -21,10 +21,10 @@ class StockCheckMethodService extends MainService { super(ctx); // 免登录方法列表:空(全部需要登录) const _noNeedLogin = ''; - // 免权限方法列表:全部 14 个方法免 API 权限校验(与 stock/transaction.js 口径一致) + // 免权限方法列表:全部 20 个方法免 API 权限校验(与 stock/transaction.js 口径一致) const _noNeedRight = ALL_METHOD_NAMES; - // 免日志方法列表:查询类与导出类不记录操作日志(recordDelete 为写操作,保留操作日志) - const _noNeedLog = 'list,detail,recordList,export,exportTaskProgress'; + // 免日志方法列表:查询类与导出类不记录操作日志(recordDelete/patternCreate 为写操作,保留操作日志) + const _noNeedLog = 'list,detail,result,workData,recordList,export,exportTaskProgress,patternList'; // 免鉴权(仓库有效期检查)方法列表:全部方法免鉴权(与 stock/transaction.js 口径一致) const _noNeedAuth = ALL_METHOD_NAMES; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); @@ -58,10 +58,11 @@ class StockCheckMethodService extends MainService { * @param {Object} data 请求体。 * @param {string} [data.title] 盘点名称/主题。 * @param {string} [data.type] 盘点范围类型:all/store/goods/location。 - * @param {string} [data.mode] 盘点方式:open=明盘/blind=盲盘。 + * @param {string} [data.mode] 盘点方式:open=明盘/blind=盲盘; + * 按库位盘点(all/location)一律盲盘,忽略前端传入;按商品盘点(store/goods)按传入值(默认明盘)。 * @param {number} [data.store_id] 货主ID(按货主盘点时必填)。 - * @param {string} [data.check_date] 盘点日期。 * @param {string} [data.remark] 备注。 + * 盘点日期固定为今天,前端不传。 * @return {Promise} 统一 success 包装,返回新建的盘点任务信息。 */ async create(data = {}) { @@ -69,7 +70,7 @@ class StockCheckMethodService extends MainService { const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; const creatorId = ctx.user ? (ctx.user.id || ctx.user.user_id || 0) : 0; const creatorName = ctx.user ? (ctx.user.employees_name || ctx.user.real_name || '') : ''; - const { title, type, mode, store_id: storeId, check_date: checkDate, remark } = data || {}; + const { title, type, mode, store_id: storeId, remark } = data || {}; return this._call( () => this.service.systems.stockCheck.create({ @@ -78,7 +79,6 @@ class StockCheckMethodService extends MainService { type, mode, storeId, - checkDate, remark, creatorId, creatorName, @@ -87,6 +87,60 @@ class StockCheckMethodService extends MainService { ); } + /** + * 拉取盘点定式清单(供前端选择定式快速创建盘点任务)。 + * + * @return {Promise} 统一 success 包装,返回 { patterns, total }; + * patterns 每条含 id/name/description/type。 + */ + async patternList() { + return this._call( + () => this.service.systems.stockCheck.patternList(), + '拉取盘点定式失败' + ); + } + + /** + * 按定式快速创建盘点任务。 + * warehouse_id 由服务端从当前上下文自动注入,前端无需传递。 + * 盘点方式由定式范围类型固定:库位类定式一律盲盘(blind)、商品类定式一律明盘(open); + * 盘点日期固定为今天,两者均无需前端传入。 + * + * @param {Object} data 请求体。 + * @param {string} data.pattern_id 定式ID(兼容 patternId 驼峰写法)。 + * @param {string} [data.title] 盘点名称/主题,缺省取定式 name。 + * @param {string} [data.remark] 备注。 + * @return {Promise} 统一 success 包装,返回 + * { check, total_items, pattern_id }。 + */ + async patternCreate(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const creatorId = ctx.user ? (ctx.user.id || ctx.user.user_id || 0) : 0; + const creatorName = ctx.user ? (ctx.user.employees_name || ctx.user.real_name || '') : ''; + const { + pattern_id: patternIdRaw, + patternId: patternIdAlias, + title, + remark, + } = data || {}; + const patternId = patternIdRaw !== undefined && patternIdRaw !== null && patternIdRaw !== '' + ? patternIdRaw + : patternIdAlias; + + return this._call( + () => this.service.systems.stockCheck.patternCreate({ + warehouseId, + patternId, + title, + remark, + creatorId, + creatorName, + }), + '按定式创建盘点任务失败' + ); + } + /** * 拉取盘点任务列表。 * 按当前用户仓库(ctx.user.store_id)限定数据范围。 @@ -95,8 +149,13 @@ class StockCheckMethodService extends MainService { * @param {Object} [data.pagination] 分页参数。 * @param {Object} [data.where] 查询条件。 * @param {string|Array} [data.where.status] 状态筛选(单值或数组)。 + * @param {string|Array} [data.where.type] 范围类型筛选(all/store/goods/location)。 + * @param {string|Array} [data.where.mode] 盘点方式筛选(open/blind)。 * @param {number} [data.where.store_id] 货主筛选。 * @param {string} [data.where.keyword] 关键字(单号/标题模糊)。 + * @param {string|Array} [data.where.created_at] 创建时间筛选(单值=当天起,[from,to]=区间)。 + * @param {string|Array} [data.where.start_time] 盘点开始时间筛选。 + * @param {string|Array} [data.where.end_time] 盘点结束时间筛选。 * @return {Promise} 统一 success 包装,返回 rows/total。 */ async list(data = {}) { @@ -107,74 +166,131 @@ class StockCheckMethodService extends MainService { return this._call(async () => { const { whereValue = {} } = this.prepareWhereContext(data); const status = whereValue.status !== undefined ? whereValue.status : data.status; + const type = whereValue.type !== undefined ? whereValue.type : data.type; + const mode = whereValue.mode !== undefined ? whereValue.mode : data.mode; const storeId = whereValue.store_id !== undefined ? whereValue.store_id : data.store_id; const keyword = whereValue.keyword !== undefined ? whereValue.keyword : data.keyword; + const createdAt = whereValue.created_at !== undefined ? whereValue.created_at : data.created_at; + const startTime = whereValue.start_time !== undefined ? whereValue.start_time : data.start_time; + const endTime = whereValue.end_time !== undefined ? whereValue.end_time : data.end_time; return this.service.systems.stockCheck.list({ warehouseId, status, + type, + mode, storeId, keyword, + createdAt, + startTime, + endTime, pagination, }); }, '查询盘点任务列表失败'); } /** - * 添加盘点明细。 + * 添加盘点明细(按任务盘点类型添加商品或库位)。 * * @param {Object} data 请求体。 * @param {number} data.id 盘点任务ID。 - * @param {Array} data.stock_ids 商品库存ID列表(wms_stock_warehouse.id)。 - * @return {Promise} 统一 success 包装,返回新增数与跳过数。 + * @param {Array} [data.stock_ids] 商品库存ID列表(wms_stock_warehouse.id,按商品盘点类型使用)。 + * @param {Array} [data.locations] 库位编码列表(按库位盘点类型使用;兼容 location_codes 写法)。 + * @param {Array} [data.location_ids] 库位ID列表(wms_location_space.id,按库位盘点类型使用; + * 兼容 locationIds 驼峰写法;与 locations 同时传入时 location_ids 优先、locations 忽略)。 + * @return {Promise} 统一 success 包装,返回新增数、跳过数与非法项列表。 */ async addDetail(data = {}) { const { ctx } = this; const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; - const { id, stock_ids: stockIds } = data || {}; + const { + id, + stock_ids: stockIds, + locations: locationsRaw, + location_codes: locationCodesRaw, + location_ids: locationIdsRaw, + locationIds: locationIdsAlias, + } = data || {}; + const locations = locationsRaw !== undefined ? locationsRaw : locationCodesRaw; + const locationIds = locationIdsRaw !== undefined ? locationIdsRaw : locationIdsAlias; return this._call( - () => this.service.systems.stockCheck.addDetail({ warehouseId, id, stockIds }), + () => this.service.systems.stockCheck.addDetail({ + warehouseId, + id, + stockIds, + locations, + locationIds, + }), '添加盘点明细失败' ); } /** - * 删除盘点明细(从任务中移除某个商品)。 - * 仅主表状态 created/rejected 允许删除;明细存在作业记录时一并防御性删除; - * 删除后重算主表 total_items。 + * 批量添加库位明细(兼容入口,转调 addDetail 的库位ID直查路径)。 + * 入参传库位ID列表,服务端直接按 ID 查库校验,不经过 space_code 二次解析; + * 幂等添加 scope_type='location' 明细行,已存在的同库位明细自动跳过。 * * @param {Object} data 请求体。 * @param {number} data.id 盘点任务ID。 - * @param {number} data.detail_id 盘点明细ID(兼容 detailId 驼峰写法)。 - * @param {number} [data.detailId] 盘点明细ID(驼峰别名)。 - * @return {Promise} 统一 success 包装,返回 { detail_id, deleted, total_items }。 + * @param {Array} data.location_ids 库位ID列表(wms_location_space.id,单次上限 200; + * 兼容 locationIds 驼峰写法)。 + * @return {Promise} 统一 success 包装,返回 + * { added, skipped, invalid_location_ids, total_items }。 + */ + async addLocationDetail(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const { id, location_ids: locationIdsRaw, locationIds: locationIdsAlias } = data || {}; + const locationIds = locationIdsRaw !== undefined ? locationIdsRaw : locationIdsAlias; + + return this._call( + () => this.service.systems.stockCheck.addLocationDetail({ warehouseId, id, locationIds }), + '批量添加库位明细失败' + ); + } + + /** + * 删除盘点明细(批量:从任务中移除一个或多个商品/库位范围行)。 + * 仅主表状态 created/rejected 允许删除;明细存在作业记录时一并防御性删除; + * 查不到的明细 ID 计入 skipped_ids 不报错;删除后重算主表 total_items。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 盘点任务ID。 + * @param {Array|number} data.detail_ids 盘点明细ID数组(单次上限 200; + * 兼容 detailIds 驼峰写法;兼容旧版单值 detail_id 写法,单值自动转数组)。 + * @return {Promise} 统一 success 包装,返回 + * { deleted_count, deleted_ids, skipped_ids, total_items }; + * 注意:本接口已由旧版单值删除升级为批量删除,响应结构由旧版 + * { detail_id, deleted, total_items } 变更为上述结构。 */ async detailDelete(data = {}) { const { ctx } = this; const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; - const { id, detail_id: detailIdRaw, detailId: detailIdAlias } = data || {}; - const detailId = detailIdRaw !== undefined && detailIdRaw !== null && detailIdRaw !== '' - ? detailIdRaw - : detailIdAlias; + const { id, detail_ids: detailIdsRaw, detailIds: detailIdsAlias, detail_id: detailIdSingle } = data || {}; + const detailIds = detailIdsRaw !== undefined + ? detailIdsRaw + : (detailIdsAlias !== undefined ? detailIdsAlias : detailIdSingle); return this._call( () => this.service.systems.stockCheck.detailDelete({ warehouseId, id, - detailId, + detailIds, }), '删除盘点明细失败' ); } /** - * 拉取盘点任务的全部明细行(商品清单)及每条明细的盘点作业记录(库位+数量)。 + * 拉取盘点任务明细(任务范围行:商品或库位)。 + * 只返回范围行,不包含盘点作业聚合与作业记录(作业聚合见 result; + * 作业记录的 barcode/item_name/images 口径见 result/recordList)。 * * @param {Object} data 请求体。 * @param {number} data.id 盘点任务ID。 - * @return {Promise} 统一 success 包装,返回 { check, rows, total };rows 每条含商品快照 + - * 已盘聚合(checked_quantity/diff_quantity/is_diff/location_codes/checkers/last_checked_at)、 - * records(作业记录列表)与 locations(按库位聚合 [{ location_id, location_code, quantity }])。 + * @return {Promise} 统一 success 包装,返回 { check, rows, total }; + * rows 每条为纯范围行字段:id/check_id/warehouse_id/scope_type/stock_id/location_id/ + * location_code/item_code/item_name/spec/batch_no/system_quantity/remark/created_at/updated_at。 */ async detail(data = {}) { const { ctx } = this; @@ -187,23 +303,80 @@ class StockCheckMethodService extends MainService { ); } + /** + * 拉取盘点明细结果(按范围行聚合作业记录)。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 盘点任务ID。 + * @return {Promise} 统一 success 包装,返回 { check, rows, total }; + * 商品行含已盘聚合(checked_quantity/diff_quantity/is_diff/status/location_codes/ + * checkers/last_checked_at)与 records(作业记录列表,每条含 barcode/item_name/images)、 + * locations(按库位聚合 [{ location_id, location_code, quantity }]); + * 库位行含 checked_quantity(行级合计)/diff_quantity(行内差异代数和)/is_diff/status + * 与 records、locations、stocks(按商品聚合,账面查 wms_storage SUM(quantity)); + * 未知商品(记录 stock_id 为空)行级输出 unknown_items [{ barcode, item_name, checked_quantity }] + * (无账面,差异 = 实盘 - 0 = 盘盈,已计入行级 checked_quantity/diff_quantity/is_diff)。 + */ + async result(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const { id } = data || {}; + + return this._call( + () => this.service.systems.stockCheck.result({ warehouseId, id }), + '查询盘点结果失败' + ); + } + + /** + * 拉取盘点作业数据(单接口三视图,view 入参驱动)。 + * warehouse_id 由服务端从当前上下文自动注入,前端无需传递。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 盘点任务ID。 + * @param {string} data.view 视图类型:location/goods/space。 + * @return {Promise} 统一 success 包装,返回 { check, rows, total };rows 结构按 view 不同: + * location=库位结构(任务库位范围行为列表,行内挂 goods/unknown 作业记录子列表); + * goods=商品结构(任务商品范围行为列表,行内挂按库位聚合的 locations 作业记录, + * 明盘返回数量与差异,盲盘不返回数量字段); + * space=商品结构(任务商品所在库位为列表,按拣货路径排序,行内挂该库位的任务商品, + * 明盘返回账面/实盘数量,盲盘不返回数量字段)。 + */ + async workData(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const { id, view } = data || {}; + + return this._call( + () => this.service.systems.stockCheck.workData({ warehouseId, id, view }), + '拉取盘点作业数据失败' + ); + } + /** * 盘点作业上报(覆盖式)。 - * 同明细 + 同库位编码重复上报时更新已有记录(未传库位归入"无库位"分组,location_code 为 null),不再新增。 + * 同明细 + 同商品 + 同库位编码重复上报时更新已有记录(未传库位归入"无库位"分组,location_code 为 null),不再新增; + * 未知商品(未传 stock_id 但传了 barcode):先按条码匹配系统商品,命中回填 stock_id 按已知商品处理, + * 未命中记录 stock_id=null + barcode + item_name(item_name 缺省为 barcode); + * stock_id 与 barcode 都未传沿用现有报错口径。 * * @param {Object} data 请求体。 * @param {number} data.id 盘点任务ID。 * @param {number} data.detail_id 明细ID。 - * @param {string} [data.location] 库位编码(可空)。 + * @param {string} [data.location] 库位编码(可空;库位明细行以明细库位为准)。 * @param {number} data.quantity 实盘数量(>=0)。 - * @return {Promise} 统一 success 包装,返回 { record, detail_id, mode: 'created'|'updated', ...summary }。 + * @param {number} [data.stock_id] 商品库存ID(wms_stock_warehouse.id;库位明细行必填,或改传 barcode)。 + * @param {string} [data.barcode] 扫描到的条码/编码(未传 stock_id 时按条码匹配系统商品,未命中记为未知商品)。 + * @param {string} [data.item_name] 未知商品名称(缺省为 barcode;已知商品忽略)。 + * @return {Promise} 统一 success 包装,返回 { record, detail_id, mode: 'created'|'updated', ...summary }; + * record 为作业记录全字段(含 barcode/item_name)。 */ async report(data = {}) { const { ctx } = this; const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; const checkerId = ctx.user ? (ctx.user.id || ctx.user.user_id || 0) : 0; const checkerName = ctx.user ? (ctx.user.employees_name || ctx.user.real_name || '') : ''; - const { id, detail_id: detailId, location, quantity } = data || {}; + const { id, detail_id: detailId, location, quantity, stock_id: stockId, barcode, item_name: itemName } = data || {}; return this._call( () => this.service.systems.stockCheck.report({ @@ -212,6 +385,9 @@ class StockCheckMethodService extends MainService { detailId, location, quantity, + stockId, + barcode, + itemName, checkerId, checkerName, }), @@ -228,7 +404,8 @@ class StockCheckMethodService extends MainService { * @param {number} [data.detail_id] 明细ID(可选,传了只查该明细)。 * @param {Object} [data.pagination] 分页参数。 * @return {Promise} 统一 success 包装,返回 { rows, total, page, pageSize }; - * rows 每条为记录表全字段 + 商品快照列(item_code/item_name)。 + * rows 每条为记录表全字段(含 barcode/item_name)+ 商品快照列(item_code/item_name, + * 未知商品显示扫描条码与名称快照)与 images: [{ id: file_id, url }](业务类型 stock_check_record)。 */ async recordList(data = {}) { const { ctx } = this; @@ -348,9 +525,29 @@ class StockCheckMethodService extends MainService { ); } + /** + * 批量删除盘点任务(仅删除已作废任务,非作废或查不到的任务跳过)。 + * warehouse_id 由服务端从当前上下文自动注入,前端无需传递。 + * + * @param {Object} data 请求体。 + * @param {Array} data.ids 盘点任务ID数组(单次上限 200)。 + * @return {Promise} 统一 success 包装,返回 + * { total, deleted_count, skipped_count, deleted_ids, skipped_ids }。 + */ + async batchDelete(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const { ids } = data || {}; + + return this._call( + () => this.service.systems.stockCheck.batchDelete({ warehouseId, ids }), + '批量删除盘点任务失败' + ); + } + /** * 提交盘点任务导出任务。 - * 异步执行:查询任务与明细 → ExcelJS 流式写入(Sheet1=盘点单行,Sheet2=明细行)→ COS 上传。 + * 异步执行:查询任务与作业记录 → ExcelJS 流式写入(Sheet1=盘点单行,Sheet2=盘点明细:一行一条实际盘点记录,含商品/库位/实盘数量/盘点人/时间,不导出未盘的任务范围行)→ COS 上传。 * 进度通过 Redis 缓存追踪,立即返回任务ID。 * * @param {Object} data 请求体。 diff --git a/app/service/systemMethods/stock/warehouse.js b/app/service/systemMethods/stock/warehouse.js index 65a305a..b677710 100644 --- a/app/service/systemMethods/stock/warehouse.js +++ b/app/service/systemMethods/stock/warehouse.js @@ -9,9 +9,9 @@ class WarehouseService extends MainService { constructor(ctx) { super(ctx); const _noNeedLogin = ''; - const _noNeedRight = 'list,externalList,externalExport,export,exportTaskProgress,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,getUnitList,createUnit,checkItemCodeUnique,deleteUnit,createProhibited,deleteProhibited,search,getStockDetail'; - const _noNeedLog = 'list,externalList,externalExport,export,exportTaskProgress,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search,getStockDetail'; - const _noNeedAuth = 'list,externalList,externalExport,export,exportTaskProgress,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search,getStockDetail'; + const _noNeedRight = 'list,externalList,externalExport,export,exportTaskProgress,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,getUnitList,createUnit,checkItemCodeUnique,deleteUnit,createProhibited,deleteProhibited,search,getStockDetail,staticList'; + const _noNeedLog = 'list,externalList,externalExport,export,exportTaskProgress,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search,getStockDetail,staticList'; + const _noNeedAuth = 'list,externalList,externalExport,export,exportTaskProgress,getProhibitedType,getInfo,getBarcodes,getStoreStocks,queryStockLogs,getStockUnits,checkItemCodeUnique,getUnitList,search,getStockDetail,staticList'; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); } @@ -561,6 +561,7 @@ class WarehouseService extends MainService { inbound_min_days, outbound_min_days, remaining_threshold_days, + warning_quantity, } = data || {}; try { const result = await service.systems.stockStore.saveWarehouseStock({ @@ -607,6 +608,7 @@ class WarehouseService extends MainService { inbound_min_days, outbound_min_days, remaining_threshold_days, + warning_quantity, }); return this.success('ok', { data: result, code: 200 }); } catch (error) { @@ -958,6 +960,26 @@ class WarehouseService extends MainService { } } + /** + * 查询静态商品列表(仓库级)。 + * 静态判定:商品最后一个收/发流水时间超过仓库配置的静态时间阈值即视为进入静态。 + * @param {Object} data 请求体 + * @param {Object} [data.pagination] 分页参数(page/pageSize) + * @param {number} [data.hours] 静态时间阈值(小时),缺省读仓库配置 stock_static_hours(默认 168) + * @return {Promise} data 为 { list, pagination } + */ + async staticList(data = {}) { + const { ctx, service } = this; + const pagination = this.isPlainObject(data.pagination) ? data.pagination : data; + const result = await service.systems.stockWarehouse.getStaticStockList({ + warehouseId: ctx.user && ctx.user.store_id, + hours: data.hours, + page: Number(pagination.page || 1), + pageSize: Number(pagination.pageSize || 20), + }); + return this.success('ok', result); + } + /** * 查询库存操作日志。 * @param {Object} data 请求体(会自动注入当前 warehouseId) diff --git a/app/service/systems/pick.js b/app/service/systems/pick.js index e3a612e..3965dea 100644 --- a/app/service/systems/pick.js +++ b/app/service/systems/pick.js @@ -500,6 +500,10 @@ class PickSystemService extends Service { item_name: String(groupItem && groupItem.item_name || '').trim(), stock_id: Number(groupItem && groupItem.stock_id || 0), total_qty: Number(groupItem && groupItem.total_qty || 0), + // 拣货要求:取自商品资料链路(getStockDetails),merge_requirements=Y 时已回退为打包要求 + pick_requirements: String( + (groupItem && groupItem.stock && groupItem.stock.pick_requirements) || '' + ).trim(), box_allocations: boxAllocations, store_id: groupItem.store_id != null ? Number(groupItem.store_id) : 0, owner_code: String(groupItem.owner_code || '').trim(), diff --git a/app/service/systems/setting/warehouse.js b/app/service/systems/setting/warehouse.js index baf587a..62f3e95 100644 --- a/app/service/systems/setting/warehouse.js +++ b/app/service/systems/setting/warehouse.js @@ -354,6 +354,32 @@ const WAREHOUSE_SETTING_FIELDS = Object.freeze([ required: false, description: '开启后散单称重(订单波次范围 wave_scope 非 1 大团购 / 3 小团购)前必须已打包完成(pack_status=fin),未打包时拒绝称重并返回错误,默认 false(关闭)', }), + Object.freeze({ + key: 'stock_warning_enabled', + name: '是否开启库存预警', + type: 'flag', + default: false, + required: false, + description: '开启后,库存数量低于预警数量时触发库存预警,默认 false(关闭)', + }), + Object.freeze({ + key: 'stock_warning_quantity', + name: '库存预警数量', + type: 'integer', + default: 0, + required: false, + description: '库存预警阈值:库存低于该数量时触发预警,默认 0,必须为非负整数', + min: 0, + }), + Object.freeze({ + key: 'stock_static_hours', + name: '商品进入静态时间(小时)', + type: 'number', + default: 168, + required: false, + description: '商品最后一个收/发流水时间超过该小时数即视为进入静态,默认 168 小时,必须大于 0', + min: 0.1, + }), Object.freeze({ key: 'return_unpack_max_record_minutes', name: '拆包最大录制时长(分钟)', diff --git a/app/service/systems/stock_check.js b/app/service/systems/stock_check.js index 9b00b47..0e085be 100644 --- a/app/service/systems/stock_check.js +++ b/app/service/systems/stock_check.js @@ -12,8 +12,12 @@ const Service = require('egg').Service; const STOCK_CHECK_TYPES = Object.freeze([ 'all', 'store', 'goods', 'location' ]); /** 盘点方式枚举(wms_stock_check.mode) */ const STOCK_CHECK_MODES = Object.freeze([ 'open', 'blind' ]); +/** 盘点作业数据视图枚举(stock.check.workData view 入参) */ +const STOCK_CHECK_WORK_VIEWS = Object.freeze([ 'location', 'goods', 'space' ]); /** 允许添加明细的主表状态 */ const ADD_DETAIL_ALLOWED_STATUSES = Object.freeze([ 'created', 'rejected' ]); +/** 单次批量添加库位明细允许的最大库位ID数量 */ +const STOCK_CHECK_ADD_LOCATION_DETAIL_MAX_IDS = 200; /** 允许盘点作业上报/完成的主表状态 */ const REPORT_ALLOWED_STATUSES = Object.freeze([ 'approved', 'checking' ]); /** 允许提交审核的主表状态 */ @@ -153,7 +157,6 @@ class StockCheckService extends Service { store_id: row.store_id || null, status: row.status || 'created', detail_status: row.detail_status || 'none_checked', - check_date: row.check_date || null, start_time: row.start_time || null, end_time: row.end_time || null, creator_id: row.creator_id || 0, @@ -178,6 +181,21 @@ class StockCheckService extends Service { return [ ...new Set(list.map(value => Number(value)).filter(value => Number.isInteger(value) && value > 0)) ]; } + /** + * 将库位编码入参(单值或数组)归一化为去重后的非空字符串列表(保持传入顺序)。 + * + * @param {string|Array} values 原始库位编码入参。 + * @return {Array} 去重后的非空库位编码列表。 + */ + _normalizeCodeList(values) { + const list = Array.isArray(values) ? values : [ values ]; + return [ ...new Set( + list + .map(value => (value === null || value === undefined ? '' : String(value)).trim()) + .filter(Boolean) + ) ]; + } + /** * 将日期值格式化为本地时间字符串(YYYY-MM-DD HH:mm:ss),供 Excel 导出使用。 * @@ -217,56 +235,161 @@ class StockCheckService extends Service { /** * 重算盘点主表的盘点进度汇总(checked_items / diff_items / detail_status)。 * 明细已盘口径:该明细存在盘点作业记录(wms_stock_check_record); - * 差异口径:明细实盘合计(记录 quantity 求和)与账面快照 system_quantity 不一致。 + * 差异口径:明细行内任一商品「实盘合计 ≠ 账面」即该行有差异,按明细去重计数; + * 商品行账面 = system_quantity 快照,库位行账面 = wms_storage 按 (space_id, stock_id) 汇总 + * (location_id 为空时账面按 0); + * 未知商品(stock_id 为空)无账面,按 barcode 维度归组,实盘 > 0 即盘盈、必然计入差异; * detail_status 按已盘明细占比自动重算:none_checked → partial_checked → all_checked。 * * @param {number} checkId 盘点任务ID。 - * @return {Promise} 重算后的汇总信息。 + * @return {Promise} 重算后的汇总信息(含 finish 复用的按明细/按商品/未知商品聚合数据)。 */ async _recalcCheckSummary(checkId) { const { ctx } = this; - const { fn, col } = ctx.app.Sequelize; + const { fn, col, Op } = ctx.app.Sequelize; - const detailWhere = { check_id: Number(checkId) }; + const checkIdNumber = Number(checkId); + const detailWhere = { check_id: checkIdNumber }; const totalItems = await ctx.model.StockCheckDetail.count({ where: detailWhere }); // 有作业记录的明细数(DISTINCT detail_id) const checkedCountRows = await ctx.model.StockCheckRecord.findAll({ - where: { check_id: Number(checkId) }, + where: { check_id: checkIdNumber }, attributes: [[ fn('COUNT', fn('DISTINCT', col('detail_id'))), 'checkedCount' ]], raw: true, }); const checkedItems = Number(checkedCountRows && checkedCountRows[0] && checkedCountRows[0].checkedCount) || 0; - // 差异明细数:实盘合计与账面不一致的明细数 - const diffCountRows = await ctx.model.StockCheckRecord.findAll({ - where: { check_id: Number(checkId) }, - attributes: [ - 'detail_id', - [ fn('SUM', col('quantity')), 'checkedQuantity' ], - ], - group: [ 'detail_id' ], + // 明细与作业记录 + const detailRows = await ctx.model.StockCheckDetail.findAll({ + where: detailWhere, + attributes: [ 'id', 'scope_type', 'stock_id', 'system_quantity', 'location_id' ], raw: true, }); + const recordRows = await ctx.model.StockCheckRecord.findAll({ + where: { check_id: checkIdNumber }, + attributes: [ 'detail_id', 'stock_id', 'barcode', 'item_name', 'quantity' ], + raw: true, + }); + + // 按明细聚合作业记录:明细总实盘 + 按商品分组实盘 + 未知商品按条码分组实盘 const checkedQuantityByDetail = new Map(); - for (const row of diffCountRows) { - checkedQuantityByDetail.set(Number(row.detail_id), Number(row.checkedQuantity) || 0); + const stockQuantityByDetail = new Map(); + const unknownQuantityByDetail = new Map(); + for (const record of recordRows) { + const detailId = Number(record.detail_id); + const stockId = Number(record.stock_id); + const quantity = Number(record.quantity) || 0; + checkedQuantityByDetail.set(detailId, (checkedQuantityByDetail.get(detailId) || 0) + quantity); + if (!Number.isInteger(stockId) || stockId <= 0) { + // 未知商品(stock_id 为空):按条码维度归组(无账面,差异 = 实盘 = 盘盈) + const barcodeKey = String(record.barcode || '').trim() || 'unknown'; + if (!unknownQuantityByDetail.has(detailId)) { + unknownQuantityByDetail.set(detailId, new Map()); + } + const byBarcode = unknownQuantityByDetail.get(detailId); + const unknownAgg = byBarcode.get(barcodeKey) || { + barcode: String(record.barcode || '').trim() || null, + item_name: record.item_name || null, + checked: 0, + }; + unknownAgg.checked += quantity; + byBarcode.set(barcodeKey, unknownAgg); + continue; + } + if (!stockQuantityByDetail.has(detailId)) { + stockQuantityByDetail.set(detailId, new Map()); + } + const byStock = stockQuantityByDetail.get(detailId); + const agg = byStock.get(stockId) || { checked: 0 }; + agg.checked += quantity; + byStock.set(stockId, agg); } - let diffItems = 0; - if (checkedQuantityByDetail.size > 0) { - const detailRows = await ctx.model.StockCheckDetail.findAll({ - where: detailWhere, - attributes: [ 'id', 'system_quantity' ], - raw: true, - }); - for (const detailRow of detailRows) { - const checkedQuantity = checkedQuantityByDetail.get(Number(detailRow.id)); - if (checkedQuantity === undefined) continue; - const diffQuantity = checkedQuantity - Number(detailRow.system_quantity || 0); - if (diffQuantity !== 0) { - diffItems++; + // 库位行账面:wms_storage 按 (space_id, stock_id) SUM(quantity),并附到按商品聚合 + const storageQuantityMap = new Map(); + const locationDetailRows = detailRows.filter(row => (row.scope_type || 'goods') === 'location'); + if (locationDetailRows.length > 0) { + const locationIds = [ ...new Set(locationDetailRows + .filter(row => row.location_id) + .map(row => Number(row.location_id))) ]; + const stockIds = new Set(); + for (const locationRow of locationDetailRows) { + const byStock = stockQuantityByDetail.get(Number(locationRow.id)); + if (!byStock) { + continue; } + for (const stockId of byStock.keys()) { + stockIds.add(stockId); + } + } + if (locationIds.length > 0 && stockIds.size > 0) { + const storageRows = await ctx.model.Storage.findAll({ + where: { + space_id: { [Op.in]: locationIds }, + stock_id: { [Op.in]: [ ...stockIds ] }, + }, + attributes: [ + 'space_id', + 'stock_id', + [ fn('SUM', col('quantity')), 'totalQuantity' ], + ], + group: [ 'space_id', 'stock_id' ], + raw: true, + }); + for (const storageRow of storageRows) { + storageQuantityMap.set( + `${Number(storageRow.space_id)}_${Number(storageRow.stock_id)}`, + Number(storageRow.totalQuantity) || 0 + ); + } + } + // 账面附到按商品聚合(location_id 为空时账面按 0) + for (const locationRow of locationDetailRows) { + const byStock = stockQuantityByDetail.get(Number(locationRow.id)); + if (!byStock) { + continue; + } + const locationId = locationRow.location_id ? Number(locationRow.location_id) : 0; + for (const [ stockId, agg ] of byStock) { + agg.system = locationId > 0 ? (storageQuantityMap.get(`${locationId}_${stockId}`) || 0) : 0; + } + } + } + + // 差异明细数:明细行内任一商品「实盘合计 ≠ 账面」即该行有差异,按明细去重计数; + // 未知商品(stock_id 为空)无账面,实盘 > 0 即盘盈、必然计入差异 + let diffItems = 0; + for (const detailRow of detailRows) { + const detailId = Number(detailRow.id); + const byStock = stockQuantityByDetail.get(detailId); + const byUnknown = unknownQuantityByDetail.get(detailId); + if ((!byStock || byStock.size === 0) && (!byUnknown || byUnknown.size === 0)) { + continue; + } + const scopeType = (detailRow.scope_type || 'goods') === 'location' ? 'location' : 'goods'; + let hasDiff = false; + if (scopeType === 'goods') { + const systemQuantity = Number(detailRow.system_quantity || 0); + hasDiff = (checkedQuantityByDetail.get(detailId) || 0) !== systemQuantity; + } else { + for (const agg of (byStock ? byStock.values() : [])) { + if (agg.checked !== (agg.system || 0)) { + hasDiff = true; + break; + } + } + if (!hasDiff && byUnknown) { + for (const agg of byUnknown.values()) { + if (agg.checked > 0) { + hasDiff = true; + break; + } + } + } + } + if (hasDiff) { + diffItems++; } } @@ -280,7 +403,7 @@ class StockCheckService extends Service { diff_items: diffItems, detail_status: detailStatus, }, - { where: { id: Number(checkId) } } + { where: { id: checkIdNumber } } ); return { @@ -289,6 +412,8 @@ class StockCheckService extends Service { diff_items: diffItems, detail_status: detailStatus, checked_quantity_by_detail: checkedQuantityByDetail, + stock_quantity_by_detail: stockQuantityByDetail, + unknown_quantity_by_detail: unknownQuantityByDetail, }; } @@ -300,10 +425,11 @@ class StockCheckService extends Service { * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 * @param {string} [params.title] 盘点名称/主题。 * @param {string} [params.type='all'] 盘点范围类型:all/store/goods/location。 - * @param {string} [params.mode='open'] 盘点方式:open=明盘/blind=盲盘。 + * @param {string} [params.mode='open'] 盘点方式:open=明盘/blind=盲盘; + * 按库位盘点(all/location)一律盲盘,忽略前端传入;按商品盘点(store/goods)按传入值(默认明盘)。 * @param {number} [params.storeId] 货主ID(按货主盘点时必填)。 - * @param {string} [params.checkDate] 盘点日期。 * @param {string} [params.remark] 备注。 + * 盘点日期固定为今天,前端不传。 * @param {number} params.creatorId 创建人账户ID(由方法层从上下文注入)。 * @param {string} [params.creatorName] 创建人名称快照(由方法层从上下文注入)。 * @return {Promise} 新建的盘点任务信息。 @@ -316,7 +442,6 @@ class StockCheckService extends Service { type, mode, storeId, - checkDate, remark, creatorId, creatorName, @@ -333,10 +458,15 @@ class StockCheckService extends Service { throw this.createBusinessError(`盘点范围类型不合法,仅支持 ${STOCK_CHECK_TYPES.join('/')}`); } - const normalizedMode = mode ? String(mode).trim() : 'open'; + let normalizedMode = mode ? String(mode).trim() : 'open'; if (!STOCK_CHECK_MODES.includes(normalizedMode)) { throw this.createBusinessError(`盘点方式不合法,仅支持 ${STOCK_CHECK_MODES.join('/')}`); } + // 按库位盘点(all/location)一律盲盘,不管前端传入什么; + // 按商品盘点(store/goods)按传入值(默认明盘) + if (normalizedType === 'all' || normalizedType === 'location') { + normalizedMode = 'blind'; + } const normalizedStoreId = storeId !== undefined && storeId !== null && storeId !== '' ? Number(storeId) @@ -345,11 +475,6 @@ class StockCheckService extends Service { throw this.createBusinessError('按货主盘点时必须指定货主'); } - const checkDateValue = checkDate ? new Date(checkDate) : null; - if (!checkDateValue || Number.isNaN(checkDateValue.getTime())) { - throw this.createBusinessError('盘点日期不能为空且格式必须合法'); - } - // 创建盘点任务(并发下撞 uk_check_no 唯一键时自动重取单号,参照收货单口径,最多重试 5 次) const maxCreateRetries = 5; let record = null; @@ -366,7 +491,6 @@ class StockCheckService extends Service { scope_snapshot: null, status: 'created', detail_status: 'none_checked', - check_date: checkDateValue, creator_id: creatorId ? Number(creatorId) : 0, creator_name: creatorName || null, remark: remark ? String(remark).trim() : null, @@ -383,23 +507,152 @@ class StockCheckService extends Service { } } - return this._formatCheckRow(record.get({ plain: true })); + const plainRecord = record.get({ plain: true }); + + // 写入操作日志(失败不影响主流程) + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'stock_check', + businessId: plainRecord.id, + operationCode: 'STOCK_CHECK_CREATE', + operationAction: 'CREATE', + changeSummary: `创建盘点任务:单号 ${plainRecord.check_no},范围类型 ${STOCK_CHECK_TYPE_LABELS[normalizedType]},盘点方式 ${STOCK_CHECK_MODE_LABELS[normalizedMode]}`, + operator: { + id: ctx.user?.employees_id || ctx.user?.id || '', + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: normalizedWarehouseId, + checkNo: plainRecord.check_no, + type: normalizedType, + mode: normalizedMode, + message: `创建盘点任务 ${plainRecord.check_no}(${STOCK_CHECK_TYPE_LABELS[normalizedType]}/${STOCK_CHECK_MODE_LABELS[normalizedMode]})`, + }, + }); + + return this._formatCheckRow(plainRecord); + } + + /** + * 批量解析货主名称映射。 + * 优先取合约表 wms_store_warehouse.store_remask(货主备注名称,按 store_id + warehouse_id), + * 无合约或备注为空时回退 wms_store.company_name(公司全称)。 + * + * @param {Array} storeIds 货主ID列表。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise>} store_id → 货主名称。 + */ + async _resolveStoreNameMap(storeIds, warehouseId) { + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + const normalizedIds = [ ...new Set((storeIds || []).map(v => Number(v)).filter(v => v > 0)) ]; + const resultMap = new Map(); + if (normalizedIds.length === 0) return resultMap; + + const contractRows = await ctx.model.StoreWarehouse.findAll({ + where: { + store_id: { [Op.in]: normalizedIds }, + warehouse_id: Number(warehouseId), + }, + attributes: [ 'store_id', 'store_remask' ], + raw: true, + }); + for (const row of contractRows) { + resultMap.set(Number(row.store_id), row.store_remask || ''); + } + + const storeRows = await ctx.model.Store.findAll({ + where: { id: { [Op.in]: normalizedIds } }, + attributes: [ 'id', 'company_name' ], + raw: true, + }); + for (const row of storeRows) { + if (!resultMap.get(Number(row.id))) { + resultMap.set(Number(row.id), row.company_name || ''); + } + } + + return resultMap; + } + + /** + * 构建时间范围查询条件。 + * 支持:[from, to] 数组(between)/ 单值(>=)/ 空值忽略。 + * + * @param {*} value 时间范围入参(数组或单值)。 + * @param {Object} Op Sequelize 操作符对象。 + * @return {Object|null} Sequelize where 条件片段,无有效值返回 null。 + */ + _buildTimeRangeCondition(value, Op) { + if (Array.isArray(value)) { + const [ from, to ] = value; + const fromDate = from ? new Date(from) : null; + const toDate = to ? new Date(to) : null; + if (fromDate && !Number.isNaN(fromDate.getTime()) && toDate && !Number.isNaN(toDate.getTime())) { + return { [Op.between]: [ fromDate, toDate ] }; + } + if (fromDate && !Number.isNaN(fromDate.getTime())) { + return { [Op.gte]: fromDate }; + } + if (toDate && !Number.isNaN(toDate.getTime())) { + return { [Op.lte]: toDate }; + } + return null; + } + if (value === undefined || value === null || value === '') { + return null; + } + const parsedDate = new Date(value); + if (Number.isNaN(parsedDate.getTime())) { + return null; + } + return { [Op.gte]: parsedDate }; + } + + /** + * 将单值/数组归一化为字符串列表(供 type/mode/status 等枚举筛选)。 + * + * @param {*} value 原始值。 + * @return {Array} 归一化后的字符串列表。 + */ + _normalizeEnumValues(value) { + const list = Array.isArray(value) ? value : [ value ]; + return [ ...new Set(list + .map(item => String(item === null || item === undefined ? '' : item).trim()) + .filter(Boolean)) ]; } /** * 拉取盘点任务列表。 - * 支持 status 筛选(单值或数组)、store_id 货主筛选、keyword(单号/标题模糊)、分页。 + * 支持筛选:status(状态,单值或数组)、type(范围类型)、mode(盘点方式)、 + * store_id(货主)、keyword(单号/标题模糊)、created_at(创建时间范围)、 + * start_time(盘点开始时间范围)、end_time(盘点结束时间范围)与分页。 * * @param {Object} params 查询参数。 * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 * @param {string|Array} [params.status] 状态筛选。 + * @param {string|Array} [params.type] 范围类型筛选。 + * @param {string|Array} [params.mode] 盘点方式筛选。 * @param {number|string} [params.storeId] 货主筛选。 * @param {string} [params.keyword] 关键字(盘点单号/标题模糊匹配)。 + * @param {*} [params.createdAt] 创建时间筛选(单值=当天起,[from,to]=区间)。 + * @param {*} [params.startTime] 盘点开始时间筛选。 + * @param {*} [params.endTime] 盘点结束时间筛选。 * @param {Object} [params.pagination] 分页参数。 * @return {Promise} { rows, total, page, pageSize }。 */ async list(params = {}) { - const { warehouseId, status, storeId, keyword, pagination = {} } = params; + const { + warehouseId, + status, + type, + mode, + storeId, + keyword, + createdAt, + startTime, + endTime, + pagination = {}, + } = params; const { ctx } = this; const { Op } = ctx.app.Sequelize; @@ -409,13 +662,29 @@ class StockCheckService extends Service { const where = { warehouse_id: Number(warehouseId) }; if (status !== undefined && status !== null && status !== '') { - if (Array.isArray(status)) { - const statusList = status.map(item => String(item).trim()).filter(Boolean); - if (statusList.length > 0) { - where.status = { [Op.in]: statusList }; - } - } else { - where.status = String(status).trim(); + const statusList = this._normalizeEnumValues(status); + if (statusList.length === 1) { + where.status = statusList[0]; + } else if (statusList.length > 1) { + where.status = { [Op.in]: statusList }; + } + } + + if (type !== undefined && type !== null && type !== '') { + const typeList = this._normalizeEnumValues(type); + if (typeList.length === 1) { + where.type = typeList[0]; + } else if (typeList.length > 1) { + where.type = { [Op.in]: typeList }; + } + } + + if (mode !== undefined && mode !== null && mode !== '') { + const modeList = this._normalizeEnumValues(mode); + if (modeList.length === 1) { + where.mode = modeList[0]; + } else if (modeList.length > 1) { + where.mode = { [Op.in]: modeList }; } } @@ -423,6 +692,19 @@ class StockCheckService extends Service { where.store_id = Number(storeId); } + const createdRange = this._buildTimeRangeCondition(createdAt, Op); + if (createdRange) { + where.created_at = createdRange; + } + const startRange = this._buildTimeRangeCondition(startTime, Op); + if (startRange) { + where.start_time = startRange; + } + const endRange = this._buildTimeRangeCondition(endTime, Op); + if (endRange) { + where.end_time = endRange; + } + const keywordValue = keyword ? String(keyword).trim() : ''; if (keywordValue) { where[Op.or] = [ @@ -439,25 +721,230 @@ class StockCheckService extends Service { raw: true, }); - return { rows, total: count, page, pageSize }; + // 补齐货主名称(合约货主备注优先、公司全称兜底) + const storeNameMap = await this._resolveStoreNameMap( + rows.map(row => row.store_id), + warehouseId + ); + const formattedRows = rows.map(row => ({ + ...row, + store_name: storeNameMap.get(Number(row.store_id)) || '', + })); + + return { rows: formattedRows, total: count, page, pageSize }; } /** - * 添加盘点明细。 - * 仅 created/rejected 状态允许;按 stock_ids 查询 wms_stock_warehouse 生成明细快照行, - * 已存在同 stock_id 的明细跳过(幂等),重算主表 total_items。 + * 拉取盘点定式清单。 + * 转调 stockCheckPatterns.listPatterns(),返回全部可用定式(id/name/description/type)。 + * + * @return {Promise} { patterns, total }。 + */ + async patternList() { + const { ctx } = this; + const patterns = ctx.service.systems.stockCheckPatterns.listPatterns(); + return { patterns, total: patterns.length }; + } + + /** + * 按定式快速创建盘点任务。 + * 按定式收集盘点对象(goods 型得到 stock_ids、location 型得到库位编码列表), + * 无符合条件对象时拒绝创建(错误码 400);创建后主表状态直接为 submitted(待审核)、 + * detail_status=none_checked、total_items 按明细重算;static 定式在任务创建成功后 + * 把命中的 stock_id 写入 wms_stock_static_check_task(写失败不影响主流程)。 + * + * @param {Object} params 创建参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {string} params.patternId 定式ID(pattern_id)。 + * @param {string} [params.title] 盘点名称/主题,缺省取定式 name。 + * @param {string} [params.remark] 备注。 + * @param {number} params.creatorId 创建人账户ID(由方法层从上下文注入)。 + * @param {string} [params.creatorName] 创建人名称快照(由方法层从上下文注入)。 + * 盘点方式由定式范围类型固定:库位类定式一律盲盘(blind)、商品类定式一律明盘(open); + * 盘点日期固定为今天,前端不传。 + * @return {Promise} { check, total_items, pattern_id }。 + * @throws {Error} 仓库上下文缺失/定式不存在/参数非法/无符合条件对象时抛出业务错误(错误码 400)。 + */ + async patternCreate(params = {}) { + const { + warehouseId, + patternId, + title, + remark, + creatorId, + creatorName, + } = params; + const { ctx } = this; + + const normalizedWarehouseId = Number(warehouseId); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + throw this.createBusinessError('无法获取当前仓库上下文'); + } + + const normalizedPatternId = String(patternId || '').trim(); + const pattern = normalizedPatternId + ? ctx.service.systems.stockCheckPatterns.getPatternById(normalizedPatternId) + : null; + if (!pattern) { + throw this.createBusinessError('盘点定式不存在'); + } + + // 盘点方式由定式范围类型固定:库位类一律盲盘、商品类一律明盘(前端不传) + const normalizedMode = pattern.type === 'location' ? 'blind' : 'open'; + + const normalizedTitle = title ? String(title).trim() : pattern.name; + + // 按定式收集盘点对象 + const collected = await ctx.service.systems.stockCheckPatterns.collectById(pattern.id, { + warehouseId: normalizedWarehouseId, + }); + const stockIds = Array.isArray(collected && collected.stock_ids) ? collected.stock_ids : []; + const locations = Array.isArray(collected && collected.locations) ? collected.locations : []; + if (pattern.type === 'location' && locations.length === 0) { + throw this.createBusinessError('当前仓库没有账面为空的库位'); + } + if (pattern.type === 'goods' && stockIds.length === 0) { + throw this.createBusinessError('没有符合条件的商品'); + } + + // 创建主表(并发下撞 uk_check_no 唯一键时自动重取单号,最多重试 5 次) + const maxCreateRetries = 5; + let record = null; + for (let attempt = 1; attempt <= maxCreateRetries; attempt++) { + const checkNo = await this.generateCheckNo(); + try { + record = await ctx.model.StockCheck.create({ + warehouse_id: normalizedWarehouseId, + check_no: checkNo, + title: normalizedTitle, + type: pattern.type, + mode: normalizedMode, + store_id: null, + scope_snapshot: null, + status: 'submitted', + detail_status: 'none_checked', + creator_id: creatorId ? Number(creatorId) : 0, + creator_name: creatorName || null, + remark: remark ? String(remark).trim() : null, + total_items: 0, + }); + break; + } catch (error) { + if (this.isCheckNoDuplicateError(error) && attempt < maxCreateRetries) { + ctx.logger.warn(`[StockCheckPatternCreateRetry] check_no 冲突,准备重试第 ${attempt + 1} 次`, { + warehouse_id: normalizedWarehouseId, + pattern_id: pattern.id, + }); + continue; + } + throw error; + } + } + + // 明细写入(goods 型按商品快照,location 型按库位) + const toCreate = []; + if (pattern.type === 'goods') { + await this._addGoodsDetailRows({ + checkId: record.id, + check: record, + warehouseId: normalizedWarehouseId, + numericStockIds: stockIds, + toCreate, + skippedItems: [], + invalidStockIds: [], + }); + } else { + const codes = [ ...new Set( + locations + .map(location => String(location && location.location_code || '').trim()) + .filter(Boolean) + ) ]; + await this._addLocationDetailRows({ + checkId: record.id, + warehouseId: normalizedWarehouseId, + codes, + toCreate, + skippedItems: [], + invalidLocations: [], + }); + } + if (toCreate.length > 0) { + await ctx.model.StockCheckDetail.bulkCreate(toCreate); + } + + // 重算并更新主表 total_items + const totalItems = await ctx.model.StockCheckDetail.count({ + where: { check_id: record.id }, + }); + await record.update({ total_items: totalItems }); + const plainRecord = record.get({ plain: true }); + + // static 定式:任务创建成功后写入静态盘点任务关联记录(失败不影响主流程) + if (pattern.id === 'static' && stockIds.length > 0) { + try { + await ctx.model.StockStaticCheckTask.bulkCreate( + stockIds.map(stockId => ({ + stock_id: Number(stockId), + task_time: new Date(), + })) + ); + } catch (error) { + ctx.logger.warn( + `[StockCheckPatternCreate] 写入静态盘点任务关联记录失败 pattern=${pattern.id}: ${error && error.message}` + ); + } + } + + // 写入操作日志(失败不影响主流程) + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'stock_check', + businessId: plainRecord.id, + operationCode: 'STOCK_CHECK_CREATE', + operationAction: 'CREATE', + changeSummary: `按定式创建盘点任务:单号 ${plainRecord.check_no},定式 ${pattern.name}(${pattern.id}),范围类型 ${STOCK_CHECK_TYPE_LABELS[pattern.type]},盘点方式 ${STOCK_CHECK_MODE_LABELS[normalizedMode]}`, + operator: { + id: ctx.user?.employees_id || ctx.user?.id || '', + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: normalizedWarehouseId, + patternId: pattern.id, + checkNo: plainRecord.check_no, + total_items: totalItems, + message: `按定式创建盘点任务 ${plainRecord.check_no}(${pattern.name}/${pattern.id})`, + }, + }); + + return { + check: this._formatCheckRow(plainRecord), + total_items: totalItems, + pattern_id: pattern.id, + }; + } + + /** + * 添加盘点明细(商品或库位,按任务盘点类型决定)。 + * 仅 created/rejected 状态允许;store/goods 类型按 stock_ids 添加商品行(商品必须属于 + * 任务货主);all/location 类型按 locations(库位编码,兼容旧调用)或 location_ids + * (库位ID,直接查库校验,不再解析编码)添加库位行,两者都传时 location_ids 优先、 + * locations 忽略;all 未传库位且未传库位ID时自动拉取全仓库启用库位; + * 兼容历史任务:type=all 且已存在商品明细行(改造前创建)时继续按商品模式接受 stock_ids; + * 已存在的同盘点项跳过(幂等),重算主表 total_items。 * * @param {Object} params 添加明细参数。 * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 * @param {number} params.id 盘点任务ID。 - * @param {number|Array} params.stockIds 商品库存ID列表(wms_stock_warehouse.id)。 - * @return {Promise} { added, skipped, invalid_stock_ids, total_items }。 + * @param {number|Array} [params.stockIds] 商品库存ID列表(wms_stock_warehouse.id,按商品盘点类型使用)。 + * @param {string|Array} [params.locations] 库位编码列表(按库位盘点类型使用,兼容旧调用; + * 与 locationIds 同时传入时被忽略)。 + * @param {number|Array} [params.locationIds] 库位ID列表(wms_location_space.id,按库位盘点类型使用; + * 与 locations 同时传入时优先使用)。 + * @return {Promise} { added, skipped, invalid_stock_ids, invalid_locations, invalid_location_ids, total_items }。 * @throws {Error} 状态不允许或参数非法时抛出业务错误(错误码 400)。 */ async addDetail(params = {}) { - const { warehouseId, id, stockIds } = params; + const { warehouseId, id, stockIds, locations, locationIds } = params; const { ctx } = this; - const { Op } = ctx.app.Sequelize; const checkId = Number(id); if (!Number.isInteger(checkId) || checkId <= 0) { @@ -472,11 +959,222 @@ class StockCheckService extends Service { throw this.createBusinessError(`当前状态(${check.status})不允许添加明细`); } + const checkType = String(check.type || 'all').trim(); + let isGoodsScope = checkType === 'store' || checkType === 'goods'; + let isLocationScope = checkType === 'all' || checkType === 'location'; const numericStockIds = this._normalizeIdList(stockIds); - if (numericStockIds.length === 0) { - throw this.createBusinessError('请至少选择一个商品'); + const locationCodes = this._normalizeCodeList(locations); + const numericLocationIds = this._normalizeIdList(locationIds); + + // 兼容历史任务:改造前 type=all 的任务按商品添加明细(明细行 scope_type='goods')。 + // 这类任务已存在商品明细行时,继续按商品模式接受 stock_ids,避免旧调用被 400 拒绝; + // 全新 type=all 任务(无任何商品明细行)维持新语义:按库位盘点,只能传 locations。 + if (checkType === 'all' && isLocationScope) { + const goodsScopeCount = await ctx.model.StockCheckDetail.count({ + where: { check_id: checkId, scope_type: 'goods' }, + }); + if (goodsScopeCount > 0) { + isGoodsScope = true; + isLocationScope = false; + } } + // 按盘点类型校验入参维度(商品与库位互斥) + if (isGoodsScope && locationCodes.length > 0) { + throw this.createBusinessError('当前盘点类型按商品盘点,请传 stock_ids'); + } + if (isGoodsScope && numericLocationIds.length > 0) { + throw this.createBusinessError('当前盘点类型按商品盘点,不能添加库位明细'); + } + if (isLocationScope && numericStockIds.length > 0) { + throw this.createBusinessError('当前盘点类型按库位盘点,请传 locations 或 location_ids(如需按商品盘点请创建 type=goods 任务)'); + } + + const toCreate = []; + const skippedItems = []; + const invalidStockIds = []; + const invalidLocations = []; + const invalidLocationIds = []; + + if (isGoodsScope) { + if (numericStockIds.length === 0) { + throw this.createBusinessError('请至少选择一个商品'); + } + await this._addGoodsDetailRows({ + checkId, + check, + warehouseId, + numericStockIds, + toCreate, + skippedItems, + invalidStockIds, + }); + } else if (isLocationScope) { + // location_ids 优先:两者都传时忽略 locations,直接按 ID 查库校验(不再解析编码) + if (numericLocationIds.length > 0) { + await this._addLocationRowsByIds({ + checkId, + warehouseId, + numericLocationIds, + toCreate, + skippedItems, + invalidLocationIds, + }); + } else { + let codes = locationCodes; + // 全盘:未显式传库位时自动拉取全仓库启用库位 + if (checkType === 'all' && codes.length === 0) { + const enabledSpaces = await ctx.model.LocationSpace.findAll({ + where: { warehouse_id: Number(warehouseId), is_enabled: true }, + attributes: [ 'space_code' ], + order: [[ 'id', 'ASC' ]], + raw: true, + }); + codes = [ ...new Set(enabledSpaces + .map(space => String(space.space_code || '').trim()) + .filter(Boolean)) ]; + if (codes.length === 0) { + throw this.createBusinessError('当前仓库没有启用库位,无法按全盘自动生成盘点范围'); + } + } + if (codes.length === 0) { + throw this.createBusinessError('请至少选择一个库位'); + } + await this._addLocationDetailRows({ + checkId, + warehouseId, + codes, + toCreate, + skippedItems, + invalidLocations, + }); + } + } + + if (toCreate.length > 0) { + await ctx.model.StockCheckDetail.bulkCreate(toCreate); + } + + // 重算主表 total_items + const totalItems = await ctx.model.StockCheckDetail.count({ + where: { check_id: checkId }, + }); + await check.update({ total_items: totalItems }); + + // 写入操作日志(失败不影响主流程) + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'stock_check', + businessId: checkId, + operationCode: 'STOCK_CHECK_ADD_DETAIL', + operationAction: 'UPDATE', + changeSummary: `添加盘点明细:新增 ${toCreate.length},跳过 ${skippedItems.length},无效商品 ${invalidStockIds.length},无效库位 ${invalidLocations.length},无效库位ID ${invalidLocationIds.length}`, + operator: { + id: ctx.user?.employees_id || ctx.user?.id || '', + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + checkNo: check.check_no, + added: toCreate.length, + skipped: skippedItems.length, + invalidStockIds, + invalidLocations, + invalidLocationIds, + message: `添加盘点明细 ${toCreate.length} 条,跳过 ${skippedItems.length} 条`, + }, + }); + + return { + added: toCreate.length, + skipped: skippedItems.length, + invalid_stock_ids: invalidStockIds, + invalid_locations: invalidLocations, + invalid_location_ids: invalidLocationIds, + total_items: totalItems, + }; + } + + /** + * 批量添加库位明细(兼容入口,薄封装转调 addDetail 的库位ID直查路径)。 + * 入参库位ID列表,服务端直接按 ID 查库校验,不经过 space_code 二次解析; + * 转发前保留旧口径的参数校验(任务ID不能为空、库位ID不能为空、单次上限 200), + * 任务存在性/状态/类型分派校验统一由 addDetail 处理; + * 返回结构从 addDetail 映射为 { added, skipped, invalid_location_ids, total_items } + * (过滤 invalid_locations/invalid_stock_ids),保持原返回口径不变。 + * + * @param {Object} params 批量添加库位明细参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {number} params.id 盘点任务ID。 + * @param {number|Array} params.locationIds 库位ID列表(wms_location_space.id,单次上限 200)。 + * @return {Promise} { added, skipped, invalid_location_ids, total_items }。 + * @throws {Error} 参数非法或状态不允许时抛出业务错误(错误码 400): + * - 盘点任务ID不能为空 + * - 请至少选择一个库位 + * - 单次最多添加 200 个库位 + * 其余校验(任务不存在/状态不允许/商品任务不可添加库位明细)由 addDetail 透传同款错误。 + */ + async addLocationDetail(params = {}) { + const { warehouseId, id, locationIds } = params; + + const checkId = Number(id); + if (!Number.isInteger(checkId) || checkId <= 0) { + throw this.createBusinessError('盘点任务ID不能为空'); + } + + // 库位ID归一化(去重正整数)与数量上限校验(保留旧口径,转发前拦截) + const numericLocationIds = this._normalizeIdList(locationIds); + if (numericLocationIds.length === 0) { + throw this.createBusinessError('请至少选择一个库位'); + } + if (numericLocationIds.length > STOCK_CHECK_ADD_LOCATION_DETAIL_MAX_IDS) { + throw this.createBusinessError(`单次最多添加 ${STOCK_CHECK_ADD_LOCATION_DETAIL_MAX_IDS} 个库位`); + } + + // 转调 addDetail(库位ID直查路径,空 stockIds/locations),过滤出兼容返回结构 + const result = await this.addDetail({ + warehouseId, + id, + stockIds: [], + locations: [], + locationIds: numericLocationIds, + }); + + return { + added: result.added, + skipped: result.skipped, + invalid_location_ids: result.invalid_location_ids, + total_items: result.total_items, + }; + } + + /** + * 生成按商品盘点明细的待创建行(store/goods 类型)。 + * 商品必须属于当前仓库;任务货主非空时商品货主必须与任务货主一致,否则记入 invalidStockIds; + * 已存在同 check_id+stock_id 的明细跳过(幂等)。 + * + * @param {Object} params 生成参数。 + * @param {number} params.checkId 盘点任务ID。 + * @param {Object} params.check 盘点主表模型实例(含 store_id)。 + * @param {number} params.warehouseId 仓库ID。 + * @param {Array} params.numericStockIds 归一化后的商品ID列表。 + * @param {Array} params.toCreate 待创建行收集数组(原地追加)。 + * @param {Array} params.skippedItems 跳过项收集数组(原地追加)。 + * @param {Array} params.invalidStockIds 非法商品ID收集数组(原地追加)。 + * @return {Promise} 无返回值。 + */ + async _addGoodsDetailRows(params = {}) { + const { + checkId, + check, + warehouseId, + numericStockIds, + toCreate, + skippedItems, + invalidStockIds, + } = params; + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + // 按 stock_ids 查询库存商品快照(限定当前仓库,自动过滤已删除) const stockRows = await ctx.model.StockWarehouse.findAll({ where: { @@ -498,74 +1196,224 @@ class StockCheckService extends Service { }); const existingStockIds = new Set(existingRows.map(item => Number(item.stock_id))); - const toCreate = []; - const skippedStockIds = []; - const invalidStockIds = []; + // 货主限制:任务货主非空时,商品货主必须与任务货主一致(限制非本货主商品加入盘点) + const checkStoreId = check.store_id !== null && check.store_id !== undefined + ? Number(check.store_id) + : 0; + for (const stockId of numericStockIds) { const stock = stockMap.get(stockId); if (!stock) { invalidStockIds.push(stockId); continue; } + if (checkStoreId > 0 && Number(stock.store_id) !== checkStoreId) { + invalidStockIds.push(stockId); + continue; + } if (existingStockIds.has(stockId)) { - skippedStockIds.push(stockId); + skippedItems.push(stockId); continue; } toCreate.push({ check_id: checkId, warehouse_id: Number(warehouseId), + scope_type: 'goods', stock_id: stockId, item_code: stock.item_code, item_name: stock.item_name || null, spec: stock.sku_property || null, batch_no: null, system_quantity: Number(stock.quantity) || 0, + location_id: null, + location_code: null, }); } - - if (toCreate.length > 0) { - await ctx.model.StockCheckDetail.bulkCreate(toCreate); - } - - // 重算主表 total_items - const totalItems = await ctx.model.StockCheckDetail.count({ - where: { check_id: checkId }, - }); - await check.update({ total_items: totalItems }); - - return { - added: toCreate.length, - skipped: skippedStockIds.length, - invalid_stock_ids: invalidStockIds, - total_items: totalItems, - }; } /** - * 删除盘点明细(从任务中移除某个商品)。 + * 生成按库位盘点明细的待创建行(all/location 类型)。 + * 按 space_code 匹配 wms_location_space(warehouse_id + space_code), + * 不存在的编码记入 invalidLocations;已存在同 check_id+location_code 的明细跳过(幂等)。 + * + * @param {Object} params 生成参数。 + * @param {number} params.checkId 盘点任务ID。 + * @param {number} params.warehouseId 仓库ID。 + * @param {Array} params.codes 归一化后的库位编码列表。 + * @param {Array} params.toCreate 待创建行收集数组(原地追加)。 + * @param {Array} params.skippedItems 跳过项收集数组(原地追加)。 + * @param {Array} params.invalidLocations 非法库位编码收集数组(原地追加)。 + * @return {Promise} 无返回值。 + */ + async _addLocationDetailRows(params = {}) { + const { checkId, warehouseId, codes, toCreate, skippedItems, invalidLocations } = params; + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + + const spaceRows = await ctx.model.LocationSpace.findAll({ + where: { + warehouse_id: Number(warehouseId), + space_code: { [Op.in]: codes }, + }, + attributes: [ 'id', 'space_code' ], + raw: true, + }); + const spaceByCode = new Map(spaceRows.map(item => [ String(item.space_code), item ])); + + // 幂等:已存在同 location_code 的明细跳过 + const existingRows = await ctx.model.StockCheckDetail.findAll({ + where: { + check_id: checkId, + location_code: { [Op.in]: codes }, + }, + attributes: [ 'location_code' ], + raw: true, + }); + const existingLocationCodes = new Set(existingRows + .map(item => String(item.location_code || '').trim()) + .filter(Boolean)); + + for (const code of codes) { + const space = spaceByCode.get(code); + if (!space) { + invalidLocations.push(code); + continue; + } + if (existingLocationCodes.has(code)) { + skippedItems.push(code); + continue; + } + toCreate.push({ + check_id: checkId, + warehouse_id: Number(warehouseId), + scope_type: 'location', + stock_id: null, + item_code: null, + item_name: null, + spec: null, + batch_no: null, + system_quantity: 0, + location_id: Number(space.id), + location_code: String(space.space_code), + }); + } + } + + /** + * 生成按库位盘点明细的待创建行(库位ID直查路径,all/location 类型)。 + * 直接按 wms_location_space.id 查库校验(warehouse_id 仓库隔离),不经过 space_code 二次解析; + * 查不到的 ID 记入 invalidLocationIds(不报错);库位编码为空(脏数据)或已存在 + * 同 check_id+location_code 的明细跳过(uk_check_location 唯一索引口径,幂等), + * 跳过项按库位ID记入 skippedItems;供 addDetail 与 addLocationDetail 共用。 + * + * @param {Object} params 生成参数。 + * @param {number} params.checkId 盘点任务ID。 + * @param {number} params.warehouseId 仓库ID。 + * @param {Array} params.numericLocationIds 归一化后的库位ID列表。 + * @param {Array} params.toCreate 待创建行收集数组(原地追加)。 + * @param {Array} params.skippedItems 跳过项收集数组(原地追加,记库位ID)。 + * @param {Array} params.invalidLocationIds 非法库位ID收集数组(原地追加)。 + * @return {Promise} 无返回值。 + */ + async _addLocationRowsByIds(params = {}) { + const { + checkId, + warehouseId, + numericLocationIds, + toCreate, + skippedItems, + invalidLocationIds, + } = params; + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + + // 直接按 ID 查库校验(仓库隔离),查不到的 ID 记入 invalidLocationIds(不报错) + const spaceRows = await ctx.model.LocationSpace.findAll({ + where: { + id: { [Op.in]: numericLocationIds }, + warehouse_id: Number(warehouseId), + }, + attributes: [ 'id', 'space_code' ], + raw: true, + }); + const spaceById = new Map(spaceRows.map(item => [ Number(item.id), item ])); + + // 幂等:已存在同 check_id+location_code 的明细跳过(uk_check_location 唯一索引口径) + const spaceCodes = [ ...new Set(spaceRows + .map(item => String(item.space_code || '').trim()) + .filter(Boolean)) ]; + const existingLocationCodes = new Set(); + if (spaceCodes.length > 0) { + const existingRows = await ctx.model.StockCheckDetail.findAll({ + where: { + check_id: checkId, + location_code: { [Op.in]: spaceCodes }, + }, + attributes: [ 'location_code' ], + raw: true, + }); + for (const row of existingRows) { + const code = String(row.location_code || '').trim(); + if (code) { + existingLocationCodes.add(code); + } + } + } + + for (const locationId of numericLocationIds) { + const space = spaceById.get(locationId); + if (!space) { + invalidLocationIds.push(locationId); + continue; + } + const spaceCode = String(space.space_code || '').trim(); + // 库位编码为空(脏数据)或已存在同库位明细行:跳过,避免撞 uk_check_location + if (!spaceCode || existingLocationCodes.has(spaceCode)) { + skippedItems.push(locationId); + continue; + } + existingLocationCodes.add(spaceCode); + toCreate.push({ + check_id: checkId, + warehouse_id: Number(warehouseId), + scope_type: 'location', + stock_id: null, + item_code: null, + item_name: null, + spec: null, + batch_no: null, + system_quantity: 0, + location_id: Number(space.id), + location_code: spaceCode, + }); + } + } + + /** + * 删除盘点明细(批量:从任务中移除一个或多个商品/库位范围行)。 * 仅主表状态 created/rejected(ADD_DETAIL_ALLOWED_STATUSES)允许删除; * 明细存在作业记录(wms_stock_check_record)时一并防御性删除(正常流程该状态不应有记录); - * 删除后重算主表 total_items。 + * 查不到的明细 ID 计入 skipped_ids 不报错;删除后重算主表 total_items。 + * 注意:响应结构由旧版 { detail_id, deleted, total_items } 变更为 + * { deleted_count, deleted_ids, skipped_ids, total_items }。 * * @param {Object} params 删除参数。 * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 * @param {number} params.id 盘点任务ID。 - * @param {number} params.detailId 盘点明细ID(方法层已兼容 detail_id/detailId 写法)。 - * @return {Promise} { detail_id, deleted, total_items }。 - * @throws {Error} 参数非法、任务/明细不存在或状态不允许时抛出业务错误(错误码 400)。 + * @param {Array|number} params.detailIds 盘点明细ID数组(单值自动转数组,单次上限 200)。 + * @return {Promise} { deleted_count, deleted_ids, skipped_ids, total_items }; + * deleted_ids/skipped_ids 均保持入参顺序。 + * @throws {Error} 参数非法、任务不存在、状态不允许或明细为空/超限时抛出业务错误(错误码 400)。 */ async detailDelete(params = {}) { - const { warehouseId, id, detailId } = params; + const { warehouseId, id, detailIds } = params; const { ctx } = this; + const { Op } = ctx.app.Sequelize; const checkId = Number(id); - const normalizedDetailId = Number(detailId); if (!Number.isInteger(checkId) || checkId <= 0) { throw this.createBusinessError('盘点任务ID不能为空'); } - if (!Number.isInteger(normalizedDetailId) || normalizedDetailId <= 0) { - throw this.createBusinessError('盘点明细ID不能为空'); - } const check = await this._findCheck(warehouseId, checkId); if (!check) { @@ -575,27 +1423,49 @@ class StockCheckService extends Service { throw this.createBusinessError(`当前状态(${check.status})不允许删除明细`); } - const detail = await ctx.model.StockCheckDetail.findOne({ - where: { - id: normalizedDetailId, - check_id: checkId, - warehouse_id: Number(warehouseId), - }, - }); - if (!detail) { - throw this.createBusinessError('盘点明细不存在'); + const numericDetailIds = this._normalizeIdList(detailIds); + if (numericDetailIds.length === 0) { + throw this.createBusinessError('请至少选择一个明细'); + } + if (numericDetailIds.length > 200) { + throw this.createBusinessError('单次最多删除 200 条明细'); } - await detail.destroy(); - - // 防御性处理:若该明细存在作业记录(正常流程 created/rejected 不应有记录),一并删除 - await ctx.model.StockCheckRecord.destroy({ + // 仓库隔离查询明细:id in ids + check_id + warehouse_id;查不到的 ID 计入 skipped_ids(不报错) + const detailRows = await ctx.model.StockCheckDetail.findAll({ where: { - detail_id: normalizedDetailId, + id: { [Op.in]: numericDetailIds }, check_id: checkId, warehouse_id: Number(warehouseId), }, + attributes: [ 'id' ], + raw: true, }); + const foundIdSet = new Set(detailRows.map(row => Number(row.id))); + const deletedIds = []; + const skippedIds = []; + for (const detailId of numericDetailIds) { + if (foundIdSet.has(detailId)) { + deletedIds.push(detailId); + } else { + skippedIds.push(detailId); + } + } + + if (deletedIds.length > 0) { + await ctx.model.StockCheckDetail.destroy({ + where: { id: { [Op.in]: deletedIds } }, + }); + + // 防御性处理:若这些明细存在作业记录(正常流程 created/rejected 不应有记录),一并删除 + await ctx.model.StockCheckRecord.destroy({ + where: { + detail_id: { [Op.in]: deletedIds }, + check_id: checkId, + warehouse_id: Number(warehouseId), + }, + }); + } // 删除明细后重算主表 total_items const totalItems = await ctx.model.StockCheckDetail.count({ @@ -603,23 +1473,50 @@ class StockCheckService extends Service { }); await check.update({ total_items: totalItems }); + // 写入操作日志(失败不影响主流程) + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'stock_check', + businessId: checkId, + operationCode: 'STOCK_CHECK_DELETE_DETAIL', + operationAction: 'UPDATE', + changeSummary: `删除盘点明细:单号 ${check.check_no},删除 ${deletedIds.length} 个,跳过 ${skippedIds.length} 个`, + operator: { + id: ctx.user?.employees_id || ctx.user?.id || '', + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: Number(warehouseId), + checkNo: check.check_no, + detailIds: deletedIds, + skippedIds, + deletedCount: deletedIds.length, + skippedCount: skippedIds.length, + message: `删除盘点明细:单号 ${check.check_no},删除 ${deletedIds.length} 个,跳过 ${skippedIds.length} 个`, + }, + }); + return { - detail_id: normalizedDetailId, - deleted: true, + deleted_count: deletedIds.length, + deleted_ids: deletedIds, + skipped_ids: skippedIds, total_items: totalItems, }; } /** - * 拉取盘点任务的全部明细行(商品清单)及其盘点作业记录(库位+数量)。 + * 拉取盘点任务明细(任务范围行:商品或库位)。 + * 只返回范围行原始字段,不包含盘点作业聚合结果(作业聚合请调用 result); + * 商品行(scope_type=goods)额外挂载 stock 对象(stock_warehouse 全局商品信息: + * item_code/item_name/sku_property/库存数量/管理标识/条码 barcodes/图片 image_url 等, + * 来自 stockWarehouse.getStockDetails,未命中为 null)。 * * @param {Object} params 查询参数。 * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 * @param {number} params.id 盘点任务ID。 - * @return {Promise} { check, rows, total };rows 每条含商品快照 + 已盘聚合 - * (checked_quantity=记录数量合计、diff_quantity=实盘-账面、is_diff、location_codes、 - * checkers、last_checked_at)、records(该明细全部作业记录)与 locations - * (按库位聚合 [{ location_id, location_code, quantity }],按首条记录 id 升序)。 + * @return {Promise} { check, rows, total }; + * rows 每条为纯范围行字段:id/check_id/warehouse_id/scope_type/stock_id/location_id/ + * location_code/item_code/item_name/spec/batch_no/system_quantity/remark/created_at/updated_at, + * 商品行另含 stock 挂载。 * @throws {Error} 任务不存在时抛出业务错误(错误码 400)。 */ async detail(params = {}) { @@ -642,75 +1539,83 @@ class StockCheckService extends Service { raw: true, }); + const rows = detailRows.map(row => this._formatDetailScopeRow(row)); + + // 商品行挂载 stock 全局商品信息(条码/图片/管理标识等,getStockDetails 带缓存) + const goodsStockIds = [ ...new Set(rows + .filter(row => row.scope_type === 'goods') + .map(row => Number(row.stock_id)) + .filter(stockId => Number.isInteger(stockId) && stockId > 0)) ]; + if (goodsStockIds.length > 0) { + const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(goodsStockIds, { + warehouseId: Number(warehouseId), + }); + const stockDetailMap = new Map(stockDetails.map(item => [ Number(item.id), item ])); + for (const row of rows) { + if (row.scope_type === 'goods') { + row.stock = stockDetailMap.get(Number(row.stock_id)) || null; + } + } + } + + return { + check: this._formatCheckRow(check.get({ plain: true })), + rows, + total: rows.length, + }; + } + + /** + * 拉取盘点明细结果(按范围行聚合作业记录)。 + * 商品行聚合其库位作业记录,库位行按商品聚合作业记录并从 wms_storage 补齐账面数量。 + * 未知商品(记录 stock_id 为空)按 barcode 维度归组,行级额外输出 unknown_items; + * 每条作业记录挂载 images(FileReference business_type=stock_check_record,仿收货 receivingItem 口径)。 + * + * @param {Object} params 查询参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {number} params.id 盘点任务ID。 + * @return {Promise} { check, rows, total };商品行含商品快照 + 已盘聚合 + * (checked_quantity=记录数量合计、diff_quantity=实盘-账面、is_diff、status、location_codes、 + * checkers、last_checked_at)、records(该明细全部作业记录,每条含 barcode/item_name/images)与 locations + * (按库位聚合 [{ location_id, location_code, quantity }],按首条记录 id 升序); + * 库位行输出 { ...row, scope_type: 'location', stocks },stocks 按商品聚合该明细下记录 + * [{ stock_id, item_code, item_name, system_quantity, checked_quantity, diff_quantity }], + * 账面数量查 wms_storage SUM(quantity),行级 checked_quantity 为行内合计、 + * diff_quantity 为行内各商品差异代数和; + * 未知商品单独输出行级 unknown_items [{ barcode, item_name, checked_quantity }] + * (无账面,差异 = 实盘 - 0 = 盘盈,已计入行级 checked_quantity/diff_quantity/is_diff)。 + * @throws {Error} 任务不存在时抛出业务错误(错误码 400)。 + */ + async result(params = {}) { + const { warehouseId, id } = params; + const { ctx } = this; + + const checkId = Number(id); + if (!Number.isInteger(checkId) || checkId <= 0) { + throw this.createBusinessError('盘点任务ID不能为空'); + } + + const check = await this._findCheck(warehouseId, checkId); + if (!check) { + throw this.createBusinessError('盘点任务不存在'); + } + + const detailRows = await ctx.model.StockCheckDetail.findAll({ + where: { check_id: checkId, warehouse_id: Number(warehouseId) }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + const records = await ctx.model.StockCheckRecord.findAll({ where: { check_id: checkId, warehouse_id: Number(warehouseId) }, order: [[ 'id', 'ASC' ]], raw: true, }); - // 按明细聚合作业记录 - const recordsByDetail = new Map(); - for (const record of records) { - const detailRowId = Number(record.detail_id); - if (!recordsByDetail.has(detailRowId)) { - recordsByDetail.set(detailRowId, []); - } - recordsByDetail.get(detailRowId).push(record); - } + // 挂载作业记录图片(FileReference business_type=stock_check_record,与收货 receivingItem 口径一致) + await this._attachRecordImages(records); - const rows = detailRows.map(detailRow => { - const detailRowId = Number(detailRow.id); - const detailRecords = recordsByDetail.get(detailRowId) || []; - const checkedQuantity = detailRecords.reduce((sum, record) => sum + (Number(record.quantity) || 0), 0); - const diffQuantity = checkedQuantity - Number(detailRow.system_quantity || 0); - const locationCodes = [ ...new Set(detailRecords - .map(record => String(record.location_code || '').trim()) - .filter(Boolean)) ]; - const checkers = [ ...new Set(detailRecords - .map(record => String(record.checker_name || '').trim()) - .filter(Boolean)) ]; - const lastCheckedAt = detailRecords.length > 0 - ? detailRecords[detailRecords.length - 1].checked_at - : null; - - // 按库位聚合作业记录(库位为空归入"无库位"分组,location_code 为 null),按首条记录 id 升序 - const locationGroups = new Map(); - for (const record of detailRecords) { - const recordLocationCode = record.location_code !== null && record.location_code !== undefined - ? String(record.location_code).trim() - : ''; - if (!locationGroups.has(recordLocationCode)) { - locationGroups.set(recordLocationCode, { - location_id: recordLocationCode ? (Number(record.location_id) || null) : null, - location_code: recordLocationCode || null, - quantity: 0, - first_record_id: Number(record.id) || 0, - }); - } - const locationGroup = locationGroups.get(recordLocationCode); - locationGroup.quantity += Number(record.quantity) || 0; - } - const locations = [ ...locationGroups.values() ] - .sort((left, right) => left.first_record_id - right.first_record_id) - .map(locationGroup => ({ - location_id: locationGroup.location_id, - location_code: locationGroup.location_code, - quantity: locationGroup.quantity, - })); - - return { - ...detailRow, - checked_quantity: detailRecords.length > 0 ? checkedQuantity : null, - diff_quantity: detailRecords.length > 0 ? diffQuantity : null, - is_diff: detailRecords.length > 0 && diffQuantity !== 0 ? 1 : 0, - status: detailRecords.length > 0 ? 'checked' : 'unchecked', - location_codes: locationCodes, - checkers, - last_checked_at: lastCheckedAt, - records: detailRecords, - locations, - }; - }); + const rows = await this._buildDetailAggregations({ detailRows, recordRows: records }); return { check: this._formatCheckRow(check.get({ plain: true })), @@ -719,24 +1624,408 @@ class StockCheckService extends Service { }; } + /** + * 将明细原始行格式化为纯范围行输出结构(不含盘点作业聚合字段)。 + * + * @param {Object} row 明细原始行。 + * @return {Object} 纯范围行字段:id/check_id/warehouse_id/scope_type/stock_id/location_id/ + * location_code/item_code/item_name/spec/batch_no/system_quantity/remark/created_at/updated_at。 + */ + _formatDetailScopeRow(row = {}) { + return { + id: row.id, + check_id: row.check_id, + warehouse_id: row.warehouse_id, + scope_type: (row.scope_type || 'goods') === 'location' ? 'location' : 'goods', + stock_id: row.stock_id !== undefined ? row.stock_id : null, + location_id: row.location_id !== undefined ? row.location_id : null, + location_code: row.location_code !== undefined ? row.location_code : null, + item_code: row.item_code !== undefined ? row.item_code : null, + item_name: row.item_name !== undefined ? row.item_name : null, + spec: row.spec !== undefined ? row.spec : null, + batch_no: row.batch_no !== undefined ? row.batch_no : null, + system_quantity: row.system_quantity !== undefined ? row.system_quantity : 0, + remark: row.remark !== undefined ? row.remark : null, + created_at: row.created_at || null, + updated_at: row.updated_at || null, + }; + } + + /** + * 为盘点作业记录挂载图片列表(图片独立维护,仿收货 receivingItem 口径)。 + * 查询 wms_file_reference(business_type=stock_check_record,business_id in 记录ID)并关联 + * wms_file 取 file_url,每条记录挂载 images: [{ id: file_id, url }],无图片返回空数组; + * 直接修改传入记录对象的 images 字段,无返回值。 + * + * @param {Array} records 作业记录原始行(每条需含 id 字段)。 + * @return {Promise} 无返回值。 + */ + async _attachRecordImages(records = []) { + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + const normalizedRecords = Array.isArray(records) ? records : []; + const recordIds = [ ...new Set(normalizedRecords + .map(record => Number(record && record.id)) + .filter(recordId => Number.isInteger(recordId) && recordId > 0)) ]; + if (recordIds.length === 0) { + return; + } + + const imageRefs = await ctx.model.FileReference.findAll({ + where: { + business_type: 'stock_check_record', + business_id: { [Op.in]: recordIds.map(String) }, + }, + include: [{ + model: ctx.model.File, + as: 'file', + attributes: [ 'file_url' ], + required: true, + }], + order: [[ 'display_order', 'ASC' ], [ 'id', 'ASC' ]], + }); + + const imageMap = new Map(); + for (const ref of imageRefs) { + const businessId = String(ref.business_id); + if (!imageMap.has(businessId)) { + imageMap.set(businessId, []); + } + imageMap.get(businessId).push({ + id: ref.file_id, + url: ref.file ? ref.file.file_url : null, + }); + } + + for (const record of normalizedRecords) { + record.images = imageMap.get(String(record.id)) || []; + } + } + + /** + * 构建盘点明细聚合行(商品行聚合其库位作业记录;库位行按商品聚合作业记录, + * 并从 wms_storage 补齐各商品账面数量;未知商品按 barcode 维度归组输出 unknown_items)。 + * + * @param {Object} params 聚合参数。 + * @param {Array} params.detailRows 明细原始行。 + * @param {Array} params.recordRows 作业记录原始行。 + * @return {Promise>} 格式化后的明细行列表。 + */ + async _buildDetailAggregations(params = {}) { + const { detailRows, recordRows } = params; + const { ctx } = this; + const { Op, fn, col } = ctx.app.Sequelize; + + // 按明细聚合作业记录 + const recordsByDetail = new Map(); + for (const record of recordRows) { + const detailRowId = Number(record.detail_id); + if (!recordsByDetail.has(detailRowId)) { + recordsByDetail.set(detailRowId, []); + } + recordsByDetail.get(detailRowId).push(record); + } + + // 收集商品 ID 集合:商品行取明细 stock_id,库位行取记录 stock_id + const stockIds = new Set(); + const locationRows = []; + for (const detailRow of detailRows) { + const scopeType = (detailRow.scope_type || 'goods') === 'location' ? 'location' : 'goods'; + if (scopeType === 'goods') { + if (detailRow.stock_id) { + stockIds.add(Number(detailRow.stock_id)); + } + } else { + locationRows.push(detailRow); + const detailRecords = recordsByDetail.get(Number(detailRow.id)) || []; + for (const record of detailRecords) { + if (record.stock_id) { + stockIds.add(Number(record.stock_id)); + } + } + } + } + + // 商品快照(item_code/item_name)从 wms_stock_warehouse 补齐 + let stockMap = new Map(); + if (stockIds.size > 0) { + const stockRows = await ctx.model.StockWarehouse.findAll({ + where: { id: { [Op.in]: [ ...stockIds ] } }, + attributes: [ 'id', 'item_code', 'item_name', 'sku_property' ], + raw: true, + }); + stockMap = new Map(stockRows.map(item => [ Number(item.id), item ])); + } + + // 库位行账面:wms_storage 按 (space_id, stock_id) SUM(quantity) + const storageQuantityMap = new Map(); + if (locationRows.length > 0 && stockIds.size > 0) { + const locationIds = [ ...new Set(locationRows + .filter(row => row.location_id) + .map(row => Number(row.location_id))) ]; + if (locationIds.length > 0) { + const storageRows = await ctx.model.Storage.findAll({ + where: { + space_id: { [Op.in]: locationIds }, + stock_id: { [Op.in]: [ ...stockIds ] }, + }, + attributes: [ + 'space_id', + 'stock_id', + [ fn('SUM', col('quantity')), 'totalQuantity' ], + ], + group: [ 'space_id', 'stock_id' ], + raw: true, + }); + for (const storageRow of storageRows) { + storageQuantityMap.set( + `${Number(storageRow.space_id)}_${Number(storageRow.stock_id)}`, + Number(storageRow.totalQuantity) || 0 + ); + } + } + } + + return detailRows.map(detailRow => this._formatDetailAggregationRow({ + detailRow, + recordsByDetail, + stockMap, + storageQuantityMap, + })); + } + + /** + * 将单条盘点明细格式化为聚合输出行。 + * 商品行:聚合作业记录输出已盘数量/差异/库位列表等; + * 库位行:按商品聚合作业记录输出 stocks 列表(含 wms_storage 账面与差异); + * 未知商品(记录 stock_id 为空)按 barcode 维度归组,行级输出 unknown_items: + * [{ barcode, item_name, checked_quantity }](无账面,差异 = 实盘 - 0 = 盘盈, + * 已计入行级 checked_quantity/diff_quantity/is_diff),stocks 保持只输出已知商品。 + * + * @param {Object} params 格式化参数。 + * @param {Object} params.detailRow 明细原始行。 + * @param {Map>} params.recordsByDetail 按明细ID分组的作业记录。 + * @param {Map} params.stockMap 商品快照映射。 + * @param {Map} params.storageQuantityMap 库位商品账面数量映射(键 `${space_id}_${stock_id}`)。 + * @return {Object} 格式化后的明细行。 + */ + _formatDetailAggregationRow(params = {}) { + const { detailRow, recordsByDetail, stockMap, storageQuantityMap } = params; + const detailRowId = Number(detailRow.id); + const scopeType = (detailRow.scope_type || 'goods') === 'location' ? 'location' : 'goods'; + const detailRecords = recordsByDetail.get(detailRowId) || []; + + const locationCodes = [ ...new Set(detailRecords + .map(record => String(record.location_code || '').trim()) + .filter(Boolean)) ]; + const checkers = [ ...new Set(detailRecords + .map(record => String(record.checker_name || '').trim()) + .filter(Boolean)) ]; + const lastCheckedAt = detailRecords.length > 0 + ? detailRecords[detailRecords.length - 1].checked_at + : null; + + // 按库位聚合作业记录(库位为空归入"无库位"分组,location_code 为 null),按首条记录 id 升序 + const locationGroups = new Map(); + for (const record of detailRecords) { + const recordLocationCode = record.location_code !== null && record.location_code !== undefined + ? String(record.location_code).trim() + : ''; + if (!locationGroups.has(recordLocationCode)) { + locationGroups.set(recordLocationCode, { + location_id: recordLocationCode ? (Number(record.location_id) || null) : null, + location_code: recordLocationCode || null, + quantity: 0, + first_record_id: Number(record.id) || 0, + }); + } + const locationGroup = locationGroups.get(recordLocationCode); + locationGroup.quantity += Number(record.quantity) || 0; + } + const locations = [ ...locationGroups.values() ] + .sort((left, right) => left.first_record_id - right.first_record_id) + .map(locationGroup => ({ + location_id: locationGroup.location_id, + location_code: locationGroup.location_code, + quantity: locationGroup.quantity, + })); + + // 未知商品(stock_id 为空)按 barcode 维度归组(无账面,差异 = 实盘 - 0 = 盘盈) + const unknownByBarcode = new Map(); + for (const record of detailRecords) { + const recordStockId = Number(record.stock_id); + if (Number.isInteger(recordStockId) && recordStockId > 0) { + continue; + } + const recordBarcode = String(record.barcode || '').trim() || null; + const barcodeKey = recordBarcode || 'unknown'; + const unknownAgg = unknownByBarcode.get(barcodeKey) || { + barcode: recordBarcode, + item_name: record.item_name || null, + checked: 0, + }; + unknownAgg.checked += Number(record.quantity) || 0; + unknownByBarcode.set(barcodeKey, unknownAgg); + } + const unknownItems = [ ...unknownByBarcode.values() ] + .sort((left, right) => String(left.barcode || '').localeCompare(String(right.barcode || ''))) + .map(agg => ({ + barcode: agg.barcode, + item_name: agg.item_name, + checked_quantity: agg.checked, + })); + + const base = { + ...detailRow, + scope_type: scopeType, + location_codes: locationCodes, + checkers, + last_checked_at: lastCheckedAt, + records: detailRecords, + locations, + }; + + if (scopeType === 'goods') { + const checkedQuantity = detailRecords.reduce((sum, record) => sum + (Number(record.quantity) || 0), 0); + const diffQuantity = checkedQuantity - Number(detailRow.system_quantity || 0); + return { + ...base, + checked_quantity: detailRecords.length > 0 ? checkedQuantity : null, + diff_quantity: detailRecords.length > 0 ? diffQuantity : null, + is_diff: detailRecords.length > 0 && diffQuantity !== 0 ? 1 : 0, + status: detailRecords.length > 0 ? 'checked' : 'unchecked', + unknown_items: unknownItems, + }; + } + + // 库位行:按商品聚合记录,账面从 wms_storage 取(location_id 为空时账面按 0) + const quantityByStock = new Map(); + for (const record of detailRecords) { + const stockId = Number(record.stock_id); + if (!Number.isInteger(stockId) || stockId <= 0) { + continue; + } + const agg = quantityByStock.get(stockId) || { checked: 0 }; + agg.checked += Number(record.quantity) || 0; + quantityByStock.set(stockId, agg); + } + const locationId = detailRow.location_id !== null && detailRow.location_id !== undefined + ? Number(detailRow.location_id) + : 0; + let checkedQuantity = 0; + let diffQuantitySum = 0; + let hasDiff = false; + const stocks = [ ...quantityByStock.keys() ] + .sort((left, right) => left - right) + .map(stockId => { + const agg = quantityByStock.get(stockId); + const stock = stockMap.get(stockId) || {}; + const systemQuantity = locationId > 0 + ? (storageQuantityMap.get(`${locationId}_${stockId}`) || 0) + : 0; + const diffQuantity = agg.checked - systemQuantity; + checkedQuantity += agg.checked; + diffQuantitySum += diffQuantity; + if (diffQuantity !== 0) { + hasDiff = true; + } + return { + stock_id: stockId, + item_code: stock.item_code || null, + item_name: stock.item_name || null, + system_quantity: systemQuantity, + checked_quantity: agg.checked, + diff_quantity: diffQuantity, + }; + }); + + // 未知商品无账面:实盘全部计入行级已盘数量与盘盈差异(必然差异) + for (const agg of unknownByBarcode.values()) { + checkedQuantity += agg.checked; + diffQuantitySum += agg.checked; + if (agg.checked > 0) { + hasDiff = true; + } + } + + return { + ...base, + stocks, + unknown_items: unknownItems, + checked_quantity: detailRecords.length > 0 ? checkedQuantity : null, + diff_quantity: detailRecords.length > 0 ? diffQuantitySum : null, + is_diff: hasDiff ? 1 : 0, + status: detailRecords.length > 0 ? 'checked' : 'unchecked', + }; + } + + /** + * 按条码解析系统商品ID(未知商品上报回填用)。 + * 查询 wms_stock_barcodes 按 barcode + warehouse_id 匹配条码,再校验 wms_stock_warehouse + * 中该商品确实属于本仓库(StockBarcode 关联 StockWarehouse),命中返回 stock_id,未命中返回 0。 + * + * @param {string} barcodeValue 扫描到的条码/编码。 + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 命中的库存商品ID(wms_stock_warehouse.id),未命中返回 0。 + */ + async _resolveStockIdByBarcode(barcodeValue, warehouseId) { + const { ctx } = this; + const normalizedBarcode = String(barcodeValue || '').trim(); + if (!normalizedBarcode) { + return 0; + } + const barcodeRow = await ctx.model.StockBarcode.findOne({ + where: { barcode: normalizedBarcode, warehouse_id: Number(warehouseId) }, + attributes: [ 'stock_id' ], + raw: true, + }); + const matchedStockId = barcodeRow ? Number(barcodeRow.stock_id) : 0; + if (!Number.isInteger(matchedStockId) || matchedStockId <= 0) { + return 0; + } + const stockRow = await ctx.model.StockWarehouse.findOne({ + where: { id: matchedStockId, warehouse_id: Number(warehouseId) }, + attributes: [ 'id' ], + raw: true, + }); + return stockRow ? matchedStockId : 0; + } + /** * 盘点作业上报(覆盖式)。 - * 仅 approved/checking 状态允许;同明细 + 同库位编码重复上报时更新已有记录的 + * 仅 approved/checking 状态允许;商品明细行固定上报明细商品(入参商品不一致报错), + * 库位明细行必须指定商品且商品必须属于本仓库,库位以明细库位为准(入参库位不一致报错); + * 同明细 + 同商品 + 同库位编码重复上报时更新已有记录的 * quantity/checker_id/checker_name/checked_at(保留原 location_id,若本次新匹配到 location_id 则回填), * 不再新增;未传库位归入"无库位"分组(location_code 存空串); * 库位编码匹配 wms_location_space.space_code 时回填 location_id; * 主表 approved 自动转 checking;重算 checked_items / diff_items / detail_status。 - * 数据库层由唯一索引 uk_detail_location(detail_id, location_code) 保证并发下不产生重复记录。 + * 数据库层由唯一索引 uk_detail_stock_location(detail_id, stock_id, location_code) 保证并发安全。 + * + * 未知商品上报口径(stock_id 与 barcode 至少传一项): + * - 传了 stock_id:按已知商品走现有逻辑(本仓库校验等); + * - 未传 stock_id 但传了 barcode:先按条码匹配系统商品(wms_stock_barcodes 按 + * barcode + 本仓库,关联 StockWarehouse 校验),命中则回填 stock_id 按已知商品处理; + * 未命中则记录 stock_id=NULL + barcode + item_name(item_name 缺省为 barcode); + * - 都未传:沿用现有报错口径(商品行缺商品信息报 400 / 库位行缺商品报 400)。 + * 覆盖式查重:已知商品 where { detail_id, stock_id, location_code } 不变; + * 未知商品 where { detail_id, stock_id: null, barcode, location_code }(应用层查重, + * 唯一索引不约束 NULL 行,并发兜底逻辑对未知商品同样降级更新)。 * * @param {Object} params 上报参数。 * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 * @param {number} params.id 盘点任务ID。 * @param {number} params.detailId 明细ID。 - * @param {string} [params.location] 库位编码(可空)。 + * @param {string} [params.location] 库位编码(可空;库位明细行以明细库位为准)。 * @param {number} params.quantity 实盘数量(>=0)。 + * @param {number} [params.stockId] 商品库存ID(wms_stock_warehouse.id;库位明细行必填,或改传 barcode)。 + * @param {string} [params.barcode] 扫描到的条码/编码(未传 stock_id 时按条码匹配系统商品, + * 未命中记为未知商品)。 + * @param {string} [params.itemName] 未知商品名称(缺省为 barcode;已知商品忽略)。 * @param {number} [params.checkerId] 盘点人账户ID(由方法层从上下文注入)。 * @param {string} [params.checkerName] 盘点人名称快照(由方法层从上下文注入)。 - * @return {Promise} { record, detail_id, mode, total_items, checked_items, diff_items, detail_status }。 + * @return {Promise} { record, detail_id, mode, total_items, checked_items, diff_items, detail_status }; + * record 为作业记录全字段(含 barcode/item_name)。 * @throws {Error} 状态不允许或参数非法时抛出业务错误(错误码 400)。 */ async report(params = {}) { @@ -746,6 +2035,9 @@ class StockCheckService extends Service { detailId, location, quantity, + stockId, + barcode, + itemName, checkerId, checkerName, } = params; @@ -780,31 +2072,136 @@ class StockCheckService extends Service { throw this.createBusinessError('盘点明细不存在'); } - // 库位编码匹配 wms_location_space.space_code 时回填 location_id; - // 未传库位归一为空串("无库位"分组,配合 uk_detail_location 唯一索引) - const locationCode = location !== undefined && location !== null && String(location).trim() !== '' - ? String(location).trim() + const scopeType = (detail.scope_type || 'goods') === 'location' ? 'location' : 'goods'; + const inputStockId = stockId !== undefined && stockId !== null && stockId !== '' + ? Number(stockId) + : 0; + const inputBarcode = barcode !== undefined && barcode !== null && String(barcode).trim() !== '' + ? String(barcode).trim() : ''; + // 未知商品名称:仅未知商品记录落库,缺省为条码 + const inputItemName = itemName !== undefined && itemName !== null && String(itemName).trim() !== '' + ? String(itemName).trim() + : ''; + + let normalizedStockId = 0; + let normalizedBarcode = null; + let normalizedItemName = null; + let isUnknownGoods = false; + let locationCode = ''; let locationId = null; - if (locationCode) { - const space = await ctx.model.LocationSpace.findOne({ - where: { - warehouse_id: Number(warehouseId), - space_code: locationCode, - }, - attributes: [ 'id' ], - raw: true, - }); - if (space) { - locationId = space.id; + + if (scopeType === 'goods') { + // 商品行:商品固定为明细商品,入参传了不同商品直接报错 + normalizedStockId = Number(detail.stock_id); + if (!Number.isInteger(normalizedStockId) || normalizedStockId <= 0) { + throw this.createBusinessError('盘点明细缺少商品信息'); } + if (inputStockId > 0 && inputStockId !== normalizedStockId) { + throw this.createBusinessError('上报商品与盘点明细商品不一致'); + } + if (inputStockId <= 0 && inputBarcode) { + // 仅传条码:先尝试回填系统商品;命中且与明细商品一致按已知商品处理,未命中记为未知商品 + const matchedStockId = await this._resolveStockIdByBarcode(inputBarcode, Number(warehouseId)); + if (matchedStockId > 0) { + if (matchedStockId !== normalizedStockId) { + throw this.createBusinessError('上报商品与盘点明细商品不一致'); + } + normalizedBarcode = inputBarcode; + } else { + isUnknownGoods = true; + normalizedStockId = 0; + normalizedBarcode = inputBarcode; + normalizedItemName = inputItemName || inputBarcode; + } + } else if (inputBarcode) { + normalizedBarcode = inputBarcode; + } + // 库位编码匹配 wms_location_space.space_code 时回填 location_id; + // 未传库位归一为空串("无库位"分组,配合 uk_detail_stock_location 唯一索引) + locationCode = location !== undefined && location !== null && String(location).trim() !== '' + ? String(location).trim() + : ''; + if (locationCode) { + const space = await ctx.model.LocationSpace.findOne({ + where: { + warehouse_id: Number(warehouseId), + space_code: locationCode, + }, + attributes: [ 'id' ], + raw: true, + }); + if (space) { + locationId = space.id; + } + } + } else { + // 库位行:必须指定商品(stock_id 或 barcode 至少一项);库位以明细库位为准 + if (inputStockId <= 0 && !inputBarcode) { + throw this.createBusinessError('按库位盘点时必须指定商品'); + } + if (inputStockId <= 0 && inputBarcode) { + // 仅传条码:先尝试回填系统商品;命中按已知商品处理,未命中记为未知商品 + const matchedStockId = await this._resolveStockIdByBarcode(inputBarcode, Number(warehouseId)); + if (matchedStockId > 0) { + normalizedStockId = matchedStockId; + normalizedBarcode = inputBarcode; + } else { + isUnknownGoods = true; + normalizedStockId = 0; + normalizedBarcode = inputBarcode; + normalizedItemName = inputItemName || inputBarcode; + } + } else { + // 传了 stock_id:现有校验口径(商品必须属于本仓库) + const stock = await ctx.model.StockWarehouse.findOne({ + where: { + id: inputStockId, + warehouse_id: Number(warehouseId), + }, + attributes: [ 'id' ], + raw: true, + }); + if (!stock) { + throw this.createBusinessError('上报商品不属于本仓库'); + } + normalizedStockId = inputStockId; + if (inputBarcode) { + normalizedBarcode = inputBarcode; + } + } + locationCode = String(detail.location_code || '').trim(); + if (!locationCode) { + throw this.createBusinessError('盘点明细缺少库位信息'); + } + const inputLocation = location !== undefined && location !== null && String(location).trim() !== '' + ? String(location).trim() + : ''; + if (inputLocation && inputLocation !== locationCode) { + throw this.createBusinessError('上报库位与盘点明细库位不一致'); + } + locationId = detail.location_id !== null && detail.location_id !== undefined + ? Number(detail.location_id) + : null; } const now = new Date(); - // 覆盖式上报:同明细 + 同库位编码(未传库位为空串"无库位"分组)更新已有记录; - // 依赖唯一索引 uk_detail_location(detail_id, location_code) 保证并发安全 - const existingRecordWhere = { detail_id: detailRowId, location_code: locationCode }; + // 覆盖式上报:已知商品按同明细 + 同商品 + 同库位编码(未传库位为空串"无库位"分组)更新已有记录, + // 依赖唯一索引 uk_detail_stock_location(detail_id, stock_id, location_code) 保证并发安全; + // 未知商品唯一索引不约束 NULL 行,按同明细 + 同条码 + 同库位编码在应用层查重 + const existingRecordWhere = isUnknownGoods + ? { + detail_id: detailRowId, + stock_id: null, + barcode: normalizedBarcode, + location_code: locationCode, + } + : { + detail_id: detailRowId, + stock_id: normalizedStockId, + location_code: locationCode, + }; const existingRecord = await ctx.model.StockCheckRecord.findOne({ where: existingRecordWhere, }); @@ -818,13 +2215,20 @@ class StockCheckService extends Service { const resolvedLocationId = locationId !== null && locationId !== undefined ? locationId : existingRecord.location_id; - await existingRecord.update({ + const updatePatch = { quantity: quantityValue, checker_id: normalizedCheckerId, checker_name: normalizedCheckerName, checked_at: now, location_id: resolvedLocationId, - }); + }; + if (normalizedBarcode !== null) { + updatePatch.barcode = normalizedBarcode; + } + if (normalizedItemName !== null) { + updatePatch.item_name = normalizedItemName; + } + await existingRecord.update(updatePatch); record = existingRecord.get({ plain: true }); mode = 'updated'; } else { @@ -833,7 +2237,9 @@ class StockCheckService extends Service { check_id: checkId, warehouse_id: Number(warehouseId), detail_id: detailRowId, - stock_id: Number(detail.stock_id), + stock_id: isUnknownGoods ? null : normalizedStockId, + barcode: normalizedBarcode, + item_name: normalizedItemName, location_id: locationId, location_code: locationCode, quantity: quantityValue, @@ -843,7 +2249,8 @@ class StockCheckService extends Service { }); record = createdRecord.get({ plain: true }); } catch (error) { - // 并发下撞唯一索引 uk_detail_location:降级为更新已有记录,避免调用方收到 500 + // 并发下撞唯一索引 uk_detail_stock_location(已知商品):降级为更新已有记录,避免调用方收到 500; + // 未知商品唯一索引不约束 NULL 行,同样按查重条件降级更新兜底 const isDuplicate = (error && error.name === 'SequelizeUniqueConstraintError') || (error && error.original && error.original.code === 'ER_DUP_ENTRY'); if (!isDuplicate) { @@ -858,48 +2265,90 @@ class StockCheckService extends Service { const resolvedLocationId = locationId !== null && locationId !== undefined ? locationId : latestRecord.location_id; - await latestRecord.update({ + const updatePatch = { quantity: quantityValue, checker_id: normalizedCheckerId, checker_name: normalizedCheckerName, checked_at: now, location_id: resolvedLocationId, - }); + }; + if (normalizedBarcode !== null) { + updatePatch.barcode = normalizedBarcode; + } + if (normalizedItemName !== null) { + updatePatch.item_name = normalizedItemName; + } + await latestRecord.update(updatePatch); record = latestRecord.get({ plain: true }); mode = 'updated'; } } - // 主表 approved → checking 自动转移(首次上报) + // 主表 approved → checking 自动转移;盘点开始时间=第一个盘点明细写入的时间 + // (start_time 为空则补写,保证任何状态下首个明细落盘时间都被记录) + const checkPatch = {}; if (check.status === 'approved') { - await check.update({ - status: 'checking', - start_time: check.start_time || now, - }); + checkPatch.status = 'checking'; + } + if (!check.start_time) { + checkPatch.start_time = now; + } + if (Object.keys(checkPatch).length > 0) { + await check.update(checkPatch); } // 重算 checked_items / diff_items / detail_status const summary = await this._recalcCheckSummary(checkId); + // 写入操作日志(失败不影响主流程) + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'stock_check', + businessId: checkId, + operationCode: 'STOCK_CHECK_REPORT', + operationAction: 'UPDATE', + changeSummary: `盘点作业上报:明细 ${detailRowId},库位 ${locationCode || '未指定'},实盘 ${quantityValue}${normalizedBarcode ? `,条码 ${normalizedBarcode}` : ''}(${mode === 'created' ? '新增' : '更新'})`, + operator: { + id: ctx.user?.employees_id || ctx.user?.id || '', + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + checkNo: check.check_no, + detailId: detailRowId, + locationCode, + quantity: quantityValue, + barcode: normalizedBarcode, + isUnknownGoods, + mode, + message: `盘点作业上报:明细 ${detailRowId} 实盘 ${quantityValue}`, + }, + }); + return { record, detail_id: detailRowId, mode, - ...summary, + total_items: summary.total_items, + checked_items: summary.checked_items, + diff_items: summary.diff_items, + detail_status: summary.detail_status, }; } /** * 拉取盘点作业记录列表。 * 至少传 id(盘点任务ID)或 detail_id(明细ID)之一;rows 每条为作业记录全字段 + - * 商品快照列(item_code/item_name,从明细表查得);按记录 id 倒序。 + * 商品快照列(item_code/item_name,从明细表查得)按记录 id 倒序; + * 未知商品(stock_id 为空)商品编码列显示扫描条码(barcode)、名称列显示上报名称快照(item_name); + * 每条记录挂载 images(FileReference business_type=stock_check_record,仿收货 receivingItem 口径)。 * * @param {Object} params 查询参数。 * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 * @param {number} [params.id] 盘点任务ID(可选)。 * @param {number} [params.detailId] 明细ID(可选)。 * @param {Object} [params.pagination] 分页参数。 - * @return {Promise} { rows, total, page, pageSize }。 + * @return {Promise} { rows, total, page, pageSize };rows 每条含 barcode/item_name 与 + * images: [{ id: file_id, url }]。 * @throws {Error} 未传任务ID或明细ID时抛出业务错误(错误码 400)。 */ async recordList(params = {}) { @@ -934,6 +2383,9 @@ class StockCheckService extends Service { raw: true, }); + // 挂载作业记录图片(FileReference business_type=stock_check_record,与收货 receivingItem 口径一致) + await this._attachRecordImages(rows); + // 商品快照列(item_code/item_name)从明细表补齐 const detailIds = [ ...new Set(rows.map(row => Number(row.detail_id))) ]; let itemByDetailId = new Map(); @@ -948,22 +2400,525 @@ class StockCheckService extends Service { const formattedRows = rows.map(row => { const item = itemByDetailId.get(Number(row.detail_id)) || {}; + const recordStockId = Number(row.stock_id); + const isUnknownGoods = !Number.isInteger(recordStockId) || recordStockId <= 0; return { ...row, // 空串表示"无库位"分组,接口返回口径统一为 null location_code: String(row.location_code || '').trim() !== '' ? row.location_code : null, - item_code: item.item_code || null, - item_name: item.item_name || null, + // 未知商品(stock_id 为空):商品编码列显示扫描条码、名称列显示上报名称快照; + // 已知商品维持现有口径(从明细表商品快照补齐) + item_code: isUnknownGoods + ? (String(row.barcode || '').trim() || null) + : (item.item_code || null), + item_name: isUnknownGoods + ? (String(row.item_name || row.barcode || '').trim() || null) + : (item.item_name || null), }; }); return { rows: formattedRows, total: count, page, pageSize }; } + /** + * 拉取盘点作业数据(单接口三视图,view 入参驱动)。 + * view=location:库位结构,以任务库位范围行(scope_type=location)为列表, + * 行内挂该库位的盘点作业记录(goods=已知商品子列表 / unknown=未知商品子列表); + * view=goods:商品结构,以任务商品范围行(scope_type=goods)为列表,行内挂按库位聚合的作业记录, + * 明盘(mode=open)返回账面快照/已盘合计/差异,盲盘(mode=blind)不返回任何数量字段; + * view=space:商品结构,以任务商品所在库位为列表(按拣货路径 pick_sequence 升序、 + * pick_priority 降序排序),行内挂该库位的任务商品与账面/实盘数量,盲盘不返回数量字段; + * 若任务无对应范围行(如 location 视图无库位范围行),rows 返回空数组。 + * + * @param {Object} params 查询参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {number} params.id 盘点任务ID。 + * @param {string} params.view 视图类型:location/goods/space。 + * @return {Promise} { check, rows, total };rows 结构按 view 不同: + * location 行含 detail_id/location_id/location_code/location_name/status/has_unknown/ + * checked_at/checkers/goods/unknown;goods 行含 detail_id/stock_id/item_code/item_name/spec/ + * store_id/store_name/barcode/images/locations(明盘另含 system_quantity/checked_quantity/ + * diff_quantity/is_diff);space 行含 location_id/location_code/location_name/goods。 + * @throws {Error} 任务不存在、view 非法或任务状态非 approved/checking 时抛出业务错误(错误码 400)。 + */ + async workData(params = {}) { + const { warehouseId, id, view } = params; + + const checkId = Number(id); + if (!Number.isInteger(checkId) || checkId <= 0) { + throw this.createBusinessError('盘点任务ID不能为空'); + } + const normalizedView = String(view || '').trim(); + if (!STOCK_CHECK_WORK_VIEWS.includes(normalizedView)) { + throw this.createBusinessError('视图类型非法(仅支持 location/goods/space)'); + } + + const check = await this._findCheck(warehouseId, checkId); + if (!check) { + throw this.createBusinessError('盘点任务不存在'); + } + if (!REPORT_ALLOWED_STATUSES.includes(check.status)) { + throw this.createBusinessError(`当前状态(${STOCK_CHECK_STATUS_LABELS[check.status] || check.status})不允许拉取盘点作业数据,仅审核完成(approved)或盘点作业中(checking)的任务可拉取`); + } + + const rows = normalizedView === 'location' + ? await this._buildLocationWorkRows(warehouseId, checkId) + : (normalizedView === 'goods' + ? await this._buildGoodsWorkRows(warehouseId, checkId, check.mode) + : await this._buildSpaceWorkRows(warehouseId, checkId, check.mode)); + + return { + check: this._formatCheckRow(check.get({ plain: true })), + rows, + total: rows.length, + }; + } + + /** + * 构建 location 视图行:以任务库位范围行为列表,行内挂该库位的盘点作业记录。 + * 已知商品子列表 goods 的商品基础信息(item_code/item_name/条码/图片/货主)批量取自 + * stockWarehouse.getStockDetails,货主名经 _resolveStoreNameMap 解析; + * 未知商品子列表 unknown 输出记录快照字段(barcode/item_name/images,图片经 _attachRecordImages 挂载); + * 库位名称 custom_name 兜底 space_code,库位编码优先明细快照、缺失时回退库位表。 + * + * @param {number} warehouseId 仓库ID。 + * @param {number} checkId 盘点任务ID。 + * @return {Promise>} 库位视图行列表(按明细 id 升序)。 + */ + async _buildLocationWorkRows(warehouseId, checkId) { + const { ctx } = this; + + const detailRows = await ctx.model.StockCheckDetail.findAll({ + where: { check_id: checkId, warehouse_id: Number(warehouseId), scope_type: 'location' }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + const records = await ctx.model.StockCheckRecord.findAll({ + where: { check_id: checkId, warehouse_id: Number(warehouseId) }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + // 挂载作业记录图片(FileReference business_type=stock_check_record,与 result 口径一致) + await this._attachRecordImages(records); + + // 库位名称(custom_name 兜底 space_code),库位编码优先明细快照、缺失时回退库位表 + const locationIds = [ ...new Set(detailRows + .map(row => Number(row.location_id)) + .filter(locationId => Number.isInteger(locationId) && locationId > 0)) ]; + let locationMap = new Map(); + if (locationIds.length > 0) { + const locationRows = await ctx.model.LocationSpace.findAll({ + where: { id: { [ctx.app.Sequelize.Op.in]: locationIds } }, + attributes: [ 'id', 'space_code', 'custom_name' ], + raw: true, + }); + locationMap = new Map(locationRows.map(row => [ Number(row.id), row ])); + } + + // 按明细聚合作业记录 + const recordsByDetail = new Map(); + for (const record of records) { + const detailId = Number(record.detail_id); + if (!recordsByDetail.has(detailId)) { + recordsByDetail.set(detailId, []); + } + recordsByDetail.get(detailId).push(record); + } + + // 已知商品基础信息批量取(getStockDetails 带缓存)与货主名映射 + const stockIds = [ ...new Set(records + .map(record => Number(record.stock_id)) + .filter(stockId => Number.isInteger(stockId) && stockId > 0)) ]; + let stockDetailMap = new Map(); + if (stockIds.length > 0) { + const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { + warehouseId: Number(warehouseId), + }); + stockDetailMap = new Map(stockDetails.map(item => [ Number(item.id), item ])); + } + const storeIds = [ ...stockDetailMap.values() ] + .map(item => Number(item.store_id)) + .filter(storeId => Number.isInteger(storeId) && storeId > 0); + const storeNameMap = await this._resolveStoreNameMap(storeIds, warehouseId); + + return detailRows.map(detailRow => { + const detailId = Number(detailRow.id); + const detailRecords = recordsByDetail.get(detailId) || []; + const locationRow = locationMap.get(Number(detailRow.location_id) || 0); + const locationCode = String( + detailRow.location_code || (locationRow && locationRow.space_code) || '' + ).trim() || null; + const locationName = locationCode + ? ((locationRow && (locationRow.custom_name || locationRow.space_code)) || locationCode) + : null; + + const goods = []; + const unknown = []; + const checkerSet = new Set(); + let lastCheckedAt = null; + let hasUnknown = false; + for (const record of detailRecords) { + const checkerName = String(record.checker_name || '').trim(); + if (checkerName) { + checkerSet.add(checkerName); + } + if (record.checked_at && (!lastCheckedAt || new Date(record.checked_at) > new Date(lastCheckedAt))) { + lastCheckedAt = record.checked_at; + } + const stockId = Number(record.stock_id); + if (Number.isInteger(stockId) && stockId > 0) { + const stockDetail = stockDetailMap.get(stockId) || {}; + const barcodes = Array.isArray(stockDetail.barcodes) ? stockDetail.barcodes : []; + const storeId = stockDetail.store_id != null ? Number(stockDetail.store_id) : null; + goods.push({ + record_id: record.id, + stock_id: stockId, + item_code: stockDetail.item_code || null, + item_name: stockDetail.item_name || null, + barcode: (barcodes[0] && barcodes[0].barcode) || null, + images: stockDetail.image_url || [], + store_id: storeId, + store_name: storeNameMap.get(storeId) || null, + quantity: Number(record.quantity) || 0, + checked_at: record.checked_at || null, + checker_name: checkerName || null, + }); + } else { + hasUnknown = true; + unknown.push({ + record_id: record.id, + barcode: String(record.barcode || '').trim() || null, + item_name: String(record.item_name || record.barcode || '').trim() || null, + images: Array.isArray(record.images) ? record.images : [], + quantity: Number(record.quantity) || 0, + checked_at: record.checked_at || null, + checker_name: checkerName || null, + }); + } + } + + return { + detail_id: detailId, + location_id: detailRow.location_id !== null && detailRow.location_id !== undefined + ? detailRow.location_id + : null, + location_code: locationCode, + location_name: locationName, + status: detailRecords.length > 0 ? 'checked' : 'unchecked', + has_unknown: hasUnknown, + checked_at: lastCheckedAt, + checkers: [ ...checkerSet ], + goods, + unknown, + }; + }); + } + + /** + * 构建 goods 视图行:以任务商品范围行为列表,行内挂按库位聚合的作业记录。 + * 明盘(mode=open)返回 system_quantity(账面快照)/checked_quantity(已盘合计)/diff_quantity/is_diff, + * 库位聚合项含 quantity(该库位实盘合计);盲盘(mode=blind)不返回任何数量字段; + * 商品基础信息批量取自 stockWarehouse.getStockDetails(未命中回退明细商品快照), + * 货主名经 _resolveStoreNameMap 解析;无作业记录的行 locations 为空数组, + * 已盘合计/差异按 0 处理(避免未盘行误显盘亏差异)。 + * + * @param {number} warehouseId 仓库ID。 + * @param {number} checkId 盘点任务ID。 + * @param {string} mode 盘点方式:open=明盘/blind=盲盘。 + * @return {Promise>} 商品视图行列表(按明细 id 升序)。 + */ + async _buildGoodsWorkRows(warehouseId, checkId, mode) { + const { ctx } = this; + + const detailRows = await ctx.model.StockCheckDetail.findAll({ + where: { check_id: checkId, warehouse_id: Number(warehouseId), scope_type: 'goods' }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + const records = await ctx.model.StockCheckRecord.findAll({ + where: { check_id: checkId, warehouse_id: Number(warehouseId) }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + const isOpen = mode !== 'blind'; + + // 商品基础信息批量取(getStockDetails 带缓存,未命中回退明细商品快照)与货主名映射 + const stockIds = [ ...new Set(detailRows + .map(row => Number(row.stock_id)) + .filter(stockId => Number.isInteger(stockId) && stockId > 0)) ]; + let stockDetailMap = new Map(); + if (stockIds.length > 0) { + const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { + warehouseId: Number(warehouseId), + }); + stockDetailMap = new Map(stockDetails.map(item => [ Number(item.id), item ])); + } + const storeIds = [ ...stockDetailMap.values() ] + .map(item => Number(item.store_id)) + .filter(storeId => Number.isInteger(storeId) && storeId > 0); + const storeNameMap = await this._resolveStoreNameMap(storeIds, warehouseId); + + // 按明细聚合作业记录 + const recordsByDetail = new Map(); + for (const record of records) { + const detailId = Number(record.detail_id); + if (!recordsByDetail.has(detailId)) { + recordsByDetail.set(detailId, []); + } + recordsByDetail.get(detailId).push(record); + } + + return detailRows.map(detailRow => { + const detailId = Number(detailRow.id); + const stockId = Number(detailRow.stock_id); + const detailRecords = recordsByDetail.get(detailId) || []; + const stockDetail = stockDetailMap.get(stockId) || {}; + const barcodes = Array.isArray(stockDetail.barcodes) ? stockDetail.barcodes : []; + const storeId = stockDetail.store_id != null ? Number(stockDetail.store_id) : null; + + const row = { + detail_id: detailId, + stock_id: stockId, + item_code: stockDetail.item_code || detailRow.item_code || null, + item_name: stockDetail.item_name || detailRow.item_name || null, + spec: stockDetail.sku_property || detailRow.spec || null, + store_id: storeId, + store_name: storeNameMap.get(storeId) || null, + barcode: (barcodes[0] && barcodes[0].barcode) || null, + images: stockDetail.image_url || [], + locations: [], + }; + if (isOpen) { + row.system_quantity = Number(detailRow.system_quantity) || 0; + row.checked_quantity = 0; + row.diff_quantity = 0; + row.is_diff = 0; + } + + // 按库位聚合该明细的作业记录(库位为空归入"无库位"分组,按首条记录 id 升序) + const locationGroups = new Map(); + for (const record of detailRecords) { + const recordLocationCode = record.location_code !== null && record.location_code !== undefined + ? String(record.location_code).trim() + : ''; + if (!locationGroups.has(recordLocationCode)) { + locationGroups.set(recordLocationCode, { + location_code: recordLocationCode || null, + quantity: 0, + first_record_id: Number(record.id) || 0, + checked_at: null, + checker_name: null, + }); + } + const group = locationGroups.get(recordLocationCode); + group.quantity += Number(record.quantity) || 0; + if (record.checked_at && (!group.checked_at || new Date(record.checked_at) > new Date(group.checked_at))) { + group.checked_at = record.checked_at; + group.checker_name = String(record.checker_name || '').trim() || null; + } + } + + row.locations = [ ...locationGroups.values() ] + .sort((left, right) => left.first_record_id - right.first_record_id) + .map(group => { + const locationItem = { + location_code: group.location_code, + checked_at: group.checked_at, + checker_name: group.checker_name, + }; + if (isOpen) { + locationItem.quantity = group.quantity; + } + return locationItem; + }); + + if (isOpen && row.locations.length > 0) { + row.checked_quantity = row.locations.reduce((sum, item) => sum + (Number(item.quantity) || 0), 0); + row.diff_quantity = row.checked_quantity - row.system_quantity; + row.is_diff = row.diff_quantity !== 0 ? 1 : 0; + } + + return row; + }); + } + + /** + * 构建 space 视图行:以任务商品(scope_type=goods 的 stock_id 集合)所在的库位为列表。 + * 库位集合取 wms_storage(warehouse_id + stock_id 在集合内 + is_enabled=1 且未删除,DISTINCT space_id), + * 库位按拣货路径排序:pick_sequence 升序、pick_priority 降序(同值按库位 id 升序兜底); + * 行内 goods 为该库位下的任务商品:明盘含 system_quantity(wms_storage space+stock SUM(quantity)) + * 与 checked_quantity(该商品在该库位的实盘合计),盲盘不返回任何数量字段; + * status 已盘口径:该 (detail_id, location_code) 存在作业记录; + * 未在 wms_storage 有库位的商品不入列表(无库位可聚)。 + * + * @param {number} warehouseId 仓库ID。 + * @param {number} checkId 盘点任务ID。 + * @param {string} mode 盘点方式:open=明盘/blind=盲盘。 + * @return {Promise>} 聚合库位视图行列表(按拣货路径排序)。 + */ + async _buildSpaceWorkRows(warehouseId, checkId, mode) { + const { ctx } = this; + const { Op, fn, col } = ctx.app.Sequelize; + + const detailRows = await ctx.model.StockCheckDetail.findAll({ + where: { check_id: checkId, warehouse_id: Number(warehouseId), scope_type: 'goods' }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + const stockIds = [ ...new Set(detailRows + .map(row => Number(row.stock_id)) + .filter(stockId => Number.isInteger(stockId) && stockId > 0)) ]; + if (stockIds.length === 0) { + return []; + } + + const isOpen = mode !== 'blind'; + + const records = await ctx.model.StockCheckRecord.findAll({ + where: { check_id: checkId, warehouse_id: Number(warehouseId) }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + // 商品基础信息批量取(getStockDetails 带缓存,未命中回退明细商品快照)与货主名映射 + const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { + warehouseId: Number(warehouseId), + }); + const stockDetailMap = new Map(stockDetails.map(item => [ Number(item.id), item ])); + const storeIds = [ ...stockDetailMap.values() ] + .map(item => Number(item.store_id)) + .filter(storeId => Number.isInteger(storeId) && storeId > 0); + const storeNameMap = await this._resolveStoreNameMap(storeIds, warehouseId); + const detailByStockId = new Map(detailRows.map(row => [ Number(row.stock_id), row ])); + + // 任务商品所在库位:wms_storage(warehouse + stock_id 在集合 + 启用未删除)DISTINCT space_id, + // 同时按 (space_id, stock_id) 汇总账面数量 + const storageRows = await ctx.model.Storage.findAll({ + where: { + warehouse_id: Number(warehouseId), + stock_id: { [Op.in]: stockIds }, + is_enabled: 1, + }, + attributes: [ + 'space_id', + 'stock_id', + [ fn('SUM', col('quantity')), 'totalQuantity' ], + ], + group: [ 'space_id', 'stock_id' ], + raw: true, + }); + if (storageRows.length === 0) { + return []; + } + + const spaceIds = [ ...new Set(storageRows.map(row => Number(row.space_id))) ]; + const locationRows = await ctx.model.LocationSpace.findAll({ + where: { id: { [Op.in]: spaceIds } }, + attributes: [ 'id', 'space_code', 'custom_name', 'pick_sequence', 'pick_priority' ], + raw: true, + }); + + // 库位按拣货路径排序:pick_sequence 升序、pick_priority 降序(同值按库位 id 升序兜底) + const sortedLocations = locationRows.sort((left, right) => { + const sequenceDiff = Number(left.pick_sequence || 0) - Number(right.pick_sequence || 0); + if (sequenceDiff !== 0) { + return sequenceDiff; + } + const priorityDiff = Number(right.pick_priority || 0) - Number(left.pick_priority || 0); + if (priorityDiff !== 0) { + return priorityDiff; + } + return Number(left.id) - Number(right.id); + }); + + // 库位商品账面映射(键 `${space_id}_${stock_id}`) + const storageQuantityMap = new Map(); + for (const storageRow of storageRows) { + storageQuantityMap.set( + `${Number(storageRow.space_id)}_${Number(storageRow.stock_id)}`, + Number(storageRow.totalQuantity) || 0 + ); + } + + // 按库位归集任务商品存储行 + const storageBySpace = new Map(); + for (const storageRow of storageRows) { + const spaceId = Number(storageRow.space_id); + if (!storageBySpace.has(spaceId)) { + storageBySpace.set(spaceId, []); + } + storageBySpace.get(spaceId).push(storageRow); + } + + // 按 (detail_id, location_code) 聚合作业记录(已盘口径与实盘合计用) + const recordsByDetailLocation = new Map(); + for (const record of records) { + const detailId = Number(record.detail_id); + const locationCode = String(record.location_code || '').trim(); + const key = `${detailId}_${locationCode}`; + if (!recordsByDetailLocation.has(key)) { + recordsByDetailLocation.set(key, []); + } + recordsByDetailLocation.get(key).push(record); + } + + return sortedLocations.map(locationRow => { + const spaceId = Number(locationRow.id); + const spaceCode = String(locationRow.space_code || '').trim(); + const goods = (storageBySpace.get(spaceId) || []) + .sort((left, right) => Number(left.stock_id) - Number(right.stock_id)) + .map(storageRow => { + const stockId = Number(storageRow.stock_id); + const detailRow = detailByStockId.get(stockId); + if (!detailRow) { + return null; + } + const stockDetail = stockDetailMap.get(stockId) || {}; + const barcodes = Array.isArray(stockDetail.barcodes) ? stockDetail.barcodes : []; + const storeId = stockDetail.store_id != null ? Number(stockDetail.store_id) : null; + const detailId = Number(detailRow.id); + const locationRecords = recordsByDetailLocation.get(`${detailId}_${spaceCode}`) || []; + const item = { + detail_id: detailId, + stock_id: stockId, + item_code: stockDetail.item_code || detailRow.item_code || null, + item_name: stockDetail.item_name || detailRow.item_name || null, + spec: stockDetail.sku_property || detailRow.spec || null, + store_id: storeId, + store_name: storeNameMap.get(storeId) || null, + barcode: (barcodes[0] && barcodes[0].barcode) || null, + images: stockDetail.image_url || [], + }; + if (isOpen) { + item.system_quantity = storageQuantityMap.get(`${spaceId}_${stockId}`) || 0; + item.checked_quantity = locationRecords.reduce( + (sum, record) => sum + (Number(record.quantity) || 0), + 0 + ); + } + item.status = locationRecords.length > 0 ? 'checked' : 'unchecked'; + return item; + }) + .filter(item => item !== null); + + return { + location_id: spaceId, + location_code: spaceCode || null, + location_name: String(locationRow.custom_name || locationRow.space_code || '').trim() || null, + goods, + }; + }); + } + /** * 删除盘点作业记录。 * 仅主表状态 approved/checking 允许删除;记录不存在或不属于该任务/仓库时报 400; - * 删除后重算 checked_items/diff_items/detail_status(明细记录删光后该明细回到未盘),主表状态不回退。 + * 删除后重算 checked_items/diff_items/detail_status(明细记录删光后该明细回到未盘),主表状态不回退; + * 同时清理该记录的图片引用(FileReference business_type=stock_check_record,失败仅告警不影响主流程)。 * * @param {Object} params 删除参数。 * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 @@ -1006,20 +2961,56 @@ class StockCheckService extends Service { await record.destroy(); + // 清理该记录的图片引用(图片独立维护,仿收货口径):失败仅告警,不影响主流程 + try { + await ctx.model.FileReference.destroy({ + where: { + business_type: 'stock_check_record', + business_id: String(normalizedRecordId), + }, + }); + } catch (error) { + ctx.logger.warn(`[stock.check.recordDelete] 清理作业记录图片引用失败: ${error && error.message ? error.message : error}`); + } + // 重算 checked_items / diff_items / detail_status(明细记录删光后该明细回到未盘),主表状态不回退 const summary = await this._recalcCheckSummary(checkId); + // 写入操作日志(失败不影响主流程) + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'stock_check', + businessId: checkId, + operationCode: 'STOCK_CHECK_DELETE_RECORD', + operationAction: 'UPDATE', + changeSummary: `删除盘点作业记录 ${normalizedRecordId}`, + operator: { + id: ctx.user?.employees_id || ctx.user?.id || '', + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + checkNo: check.check_no, + recordId: normalizedRecordId, + message: `删除盘点作业记录 ${normalizedRecordId}`, + }, + }); + return { record_id: normalizedRecordId, deleted: true, - ...summary, + total_items: summary.total_items, + checked_items: summary.checked_items, + diff_items: summary.diff_items, + detail_status: summary.detail_status, }; } /** * 完成盘点作业(允许部分未盘完成)。 - * 仅 approved/checking 状态允许;未盘明细按实盘 0 处理(差异 = -账面快照,计入盘亏与 diff_items); - * 已盘明细按作业记录聚合差异(盘盈合计 / 盘亏合计); + * 仅 approved/checking 状态允许;未盘商品明细按实盘 0 处理(差异 = -账面快照,计入盘亏与 diff_items); + * 已盘明细按作业记录聚合差异(盘盈合计 / 盘亏合计):商品行聚合 vs system_quantity 快照, + * 库位行按商品聚合 vs wms_storage 账面(space_id 为空时账面按 0,未盘库位行因无法枚举商品不计差异); + * 未知商品(stock_id 为空)无账面:差异 = 实盘 - 0 = 盘盈,计入盘盈合计与 diff_items; * 完成后主表置 completed、写 end_time、detail_status=all_checked,并返回差异汇总与未盘明细数。 * * @param {Object} params 完成参数。 @@ -1059,29 +3050,65 @@ class StockCheckService extends Service { const checkedItems = Number(checkedCountRows && checkedCountRows[0] && checkedCountRows[0].checkedCount) || 0; const uncheckedItems = totalItems - checkedItems; - // 差异汇总:按明细聚合实盘数量与账面快照对比,盘盈合计 / 盘亏合计 + // 差异汇总:商品行聚合 vs 账面快照;库位行按商品聚合 vs wms_storage 账面;未知商品按条码归组无账面 const summary = await this._recalcCheckSummary(checkId); const checkedQuantityByDetail = summary.checked_quantity_by_detail || new Map(); + const stockQuantityByDetail = summary.stock_quantity_by_detail || new Map(); + const unknownQuantityByDetail = summary.unknown_quantity_by_detail || new Map(); const detailRows = await ctx.model.StockCheckDetail.findAll({ where: { check_id: checkId }, - attributes: [ 'id', 'system_quantity' ], + attributes: [ 'id', 'scope_type', 'system_quantity' ], raw: true, }); let profitTotal = 0; let lossTotal = 0; let diffItems = 0; for (const detailRow of detailRows) { - const checkedQuantity = checkedQuantityByDetail.get(Number(detailRow.id)); - const systemQuantity = Number(detailRow.system_quantity || 0); - // 已盘明细按记录聚合差异;未盘明细按实盘 0 处理(差异 = -账面快照,即盘亏) - const diffQuantity = checkedQuantity === undefined - ? -systemQuantity - : checkedQuantity - systemQuantity; - if (diffQuantity > 0) { - profitTotal += diffQuantity; - diffItems++; - } else if (diffQuantity < 0) { - lossTotal += Math.abs(diffQuantity); + const detailId = Number(detailRow.id); + const scopeType = (detailRow.scope_type || 'goods') === 'location' ? 'location' : 'goods'; + if (scopeType === 'goods') { + const systemQuantity = Number(detailRow.system_quantity || 0); + const checkedQuantity = checkedQuantityByDetail.get(detailId); + // 已盘商品行按记录聚合差异;未盘商品行按实盘 0 处理(差异 = -账面快照,即盘亏) + const diffQuantity = checkedQuantity === undefined + ? -systemQuantity + : checkedQuantity - systemQuantity; + if (diffQuantity !== 0) { + diffItems++; + if (diffQuantity > 0) { + profitTotal += diffQuantity; + } else { + lossTotal += Math.abs(diffQuantity); + } + } + continue; + } + // 库位行:按商品聚合 vs wms_storage 账面;未盘库位行无法枚举商品,不计差异 + const byStock = stockQuantityByDetail.get(detailId); + const byUnknown = unknownQuantityByDetail.get(detailId); + if ((!byStock || byStock.size === 0) && (!byUnknown || byUnknown.size === 0)) { + continue; + } + let rowDiff = false; + for (const agg of (byStock ? byStock.values() : [])) { + const diffQuantity = agg.checked - (agg.system || 0); + if (diffQuantity !== 0) { + rowDiff = true; + if (diffQuantity > 0) { + profitTotal += diffQuantity; + } else { + lossTotal += Math.abs(diffQuantity); + } + } + } + // 未知商品无账面:实盘 > 0 即盘盈、必然计入差异 + for (const agg of (byUnknown ? byUnknown.values() : [])) { + if (agg.checked > 0) { + rowDiff = true; + profitTotal += agg.checked; + } + } + if (rowDiff) { diffItems++; } } @@ -1094,6 +3121,29 @@ class StockCheckService extends Service { diff_items: diffItems, }); + // 写入操作日志(失败不影响主流程) + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'stock_check', + businessId: checkId, + operationCode: 'STOCK_CHECK_FINISH', + operationAction: 'UPDATE', + changeSummary: `完成盘点:差异明细 ${diffItems},盘盈 ${profitTotal},盘亏 ${lossTotal},未盘 ${uncheckedItems}`, + operator: { + id: ctx.user?.employees_id || ctx.user?.id || '', + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + checkNo: check.check_no, + diffItems, + profitTotal, + lossTotal, + checkedItems, + uncheckedItems, + message: `完成盘点:差异 ${diffItems} 项,盘盈 ${profitTotal},盘亏 ${lossTotal}`, + }, + }); + return { id: checkId, status: 'completed', @@ -1118,6 +3168,7 @@ class StockCheckService extends Service { */ async submit(params = {}) { const { warehouseId, id } = params; + const { ctx } = this; const checkId = Number(id); if (!Number.isInteger(checkId) || checkId <= 0) { @@ -1137,6 +3188,24 @@ class StockCheckService extends Service { await check.update({ status: 'submitted' }); + // 写入操作日志(失败不影响主流程) + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'stock_check', + businessId: checkId, + operationCode: 'STOCK_CHECK_SUBMIT', + operationAction: 'UPDATE', + changeSummary: `提交审核盘点任务 ${check.check_no}`, + operator: { + id: ctx.user?.employees_id || ctx.user?.id || '', + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + checkNo: check.check_no, + message: `提交审核盘点任务 ${check.check_no}`, + }, + }); + return { id: checkId, status: 'submitted', @@ -1155,6 +3224,7 @@ class StockCheckService extends Service { */ async cancel(params = {}) { const { warehouseId, id } = params; + const { ctx } = this; const checkId = Number(id); if (!Number.isInteger(checkId) || checkId <= 0) { @@ -1171,6 +3241,24 @@ class StockCheckService extends Service { await check.update({ status: 'cancelled' }); + // 写入操作日志(失败不影响主流程) + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'stock_check', + businessId: checkId, + operationCode: 'STOCK_CHECK_CANCEL', + operationAction: 'UPDATE', + changeSummary: `取消盘点任务 ${check.check_no}`, + operator: { + id: ctx.user?.employees_id || ctx.user?.id || '', + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + checkNo: check.check_no, + message: `取消盘点任务 ${check.check_no}`, + }, + }); + return { id: checkId, status: 'cancelled', @@ -1191,6 +3279,7 @@ class StockCheckService extends Service { */ async audit(params = {}) { const { warehouseId, id, action, reason } = params; + const { ctx } = this; const checkId = Number(id); if (!Number.isInteger(checkId) || checkId <= 0) { @@ -1210,18 +3299,44 @@ class StockCheckService extends Service { throw this.createBusinessError(`当前状态(${check.status})不允许审核`); } + // 驳回原因:入参优先,为空时回退主表现有备注 + const reasonValue = reason !== undefined && reason !== null && String(reason).trim() !== '' + ? String(reason).trim() + : check.remark; + if (actionValue === 'approve') { await check.update({ status: 'approved' }); } else { - const reasonValue = reason !== undefined && reason !== null && String(reason).trim() !== '' - ? String(reason).trim() - : check.remark; await check.update({ status: 'rejected', remark: reasonValue, }); } + // 写入操作日志(失败不影响主流程) + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'stock_check', + businessId: checkId, + operationCode: 'STOCK_CHECK_AUDIT', + operationAction: 'UPDATE', + changeSummary: actionValue === 'approve' + ? `审核通过盘点任务 ${check.check_no}` + : `审核驳回盘点任务 ${check.check_no}${reasonValue ? `,原因:${reasonValue}` : ''}`, + operator: { + id: ctx.user?.employees_id || ctx.user?.id || '', + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + checkNo: check.check_no, + action: actionValue, + reason: actionValue === 'reject' ? reasonValue : '', + message: actionValue === 'approve' + ? `审核通过盘点任务 ${check.check_no}` + : `审核驳回盘点任务 ${check.check_no}${reasonValue ? `,原因:${reasonValue}` : ''}`, + }, + }); + return { id: checkId, status: actionValue === 'approve' ? 'approved' : 'rejected', @@ -1229,9 +3344,117 @@ class StockCheckService extends Service { } /** - * 盘点任务导出:查询任务与明细 → Sheet1「盘点单」一行一个盘点任务、 - * Sheet2「盘点明细」一行一条明细(首列盘点单号)→ 流式生成 Excel → COS 上传。 - * 通过 onProgress 回调实时推送进度。 + * 批量删除盘点任务(仅删除已作废任务,非作废或查不到的任务跳过)。 + * 入参 ids 归一化为去重后的正整数(单次上限 200); + * 按 id in ids + warehouse_id 查询主表做仓库隔离; + * 状态分流:status=cancelled 的任务级联删除,其他状态及查不到的任务计入 skipped_ids; + * 删除级联顺序(事务内):先删作业记录(StockCheckRecord where check_id in 删除集), + * 再删明细(StockCheckDetail where check_id in 删除集),最后删主表(StockCheck where id in 删除集)。 + * + * @param {Object} params 批量删除参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {Array|number} params.ids 盘点任务ID(数组或单个数值)。 + * @return {Promise} { total, deleted_count, skipped_count, deleted_ids, skipped_ids }; + * total=入参去重后数量,deleted_ids/skipped_ids 均保持入参顺序。 + * @throws {Error} 缺少仓库上下文、ids 为空或超过单次上限时抛出业务错误(错误码 400)。 + */ + async batchDelete(params = {}) { + const { warehouseId, ids } = params; + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + + const normalizedWarehouseId = Number(warehouseId); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + throw this.createBusinessError('无法获取当前仓库上下文'); + } + + const numericIds = this._normalizeIdList(ids); + if (numericIds.length === 0) { + throw this.createBusinessError('ids 不能为空'); + } + if (numericIds.length > 200) { + throw this.createBusinessError('单次最多删除 200 个盘点任务'); + } + + // 仓库隔离查询主表:id in ids + warehouse_id + const checkRows = await ctx.model.StockCheck.findAll({ + where: { + id: { [Op.in]: numericIds }, + warehouse_id: normalizedWarehouseId, + }, + attributes: [ 'id', 'status' ], + raw: true, + }); + const checkMap = new Map(checkRows.map(row => [ Number(row.id), row ])); + + // 状态分流:仅 cancelled 删除;其他状态及查不到的任务计入 skipped_ids(保持入参顺序) + const deletedIds = []; + const skippedIds = []; + for (const checkId of numericIds) { + const row = checkMap.get(checkId); + if (row && row.status === 'cancelled') { + deletedIds.push(checkId); + } else { + skippedIds.push(checkId); + } + } + + // 级联删除(事务):作业记录 → 明细 → 主表 + if (deletedIds.length > 0) { + await ctx.model.transaction(async transaction => { + await ctx.model.StockCheckRecord.destroy({ + where: { check_id: { [Op.in]: deletedIds } }, + transaction, + }); + await ctx.model.StockCheckDetail.destroy({ + where: { check_id: { [Op.in]: deletedIds } }, + transaction, + }); + await ctx.model.StockCheck.destroy({ + where: { id: { [Op.in]: deletedIds } }, + transaction, + }); + }); + } + + // 事务提交后写入操作日志(不随事务回滚残留,失败不影响主流程) + if (deletedIds.length > 0) { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'stock_check', + businessId: deletedIds[0], + operationCode: 'STOCK_CHECK_BATCH_DELETE', + operationAction: 'DELETE', + changeSummary: `批量删除盘点任务:删除 ${deletedIds.length} 个,跳过 ${skippedIds.length} 个`, + operator: { + id: ctx.user?.employees_id || ctx.user?.id || '', + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId: normalizedWarehouseId, + deletedIds, + skippedIds, + deletedCount: deletedIds.length, + skippedCount: skippedIds.length, + message: `批量删除盘点任务:删除 ${deletedIds.length} 个,跳过 ${skippedIds.length} 个`, + }, + }); + } + + return { + total: numericIds.length, + deleted_count: deletedIds.length, + skipped_count: skippedIds.length, + deleted_ids: deletedIds, + skipped_ids: skippedIds, + }; + } + + /** + * 盘点任务导出:查询任务与作业记录 → Sheet1「盘点单」一行一个盘点任务、 + * Sheet2「盘点明细」一行一条实际盘点记录(商品/库位/实盘数量/盘点人/时间, + * 不导出未盘的任务范围行)→ 流式生成 Excel → COS 上传。 + * 未知商品(stock_id 为空)商品编码列显示扫描条码(barcode)、商品名称列显示上报名称快照 + * (item_name);已知商品维持现有口径。通过 onProgress 回调实时推送进度。 * * @param {Object} params 导出参数。 * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 @@ -1270,64 +3493,50 @@ class StockCheckService extends Service { throw this.createBusinessError('未找到可导出的盘点任务'); } - // 明细与作业记录统一拉取,明细行聚合作业记录(已盘数量/差异/库位列表) - const detailRows = await ctx.model.StockCheckDetail.findAll({ + // 盘点明细导出:直接拉作业记录(实际盘过的库位+数量),不按任务范围行展开(任务明细不导出) + const recordRows = await ctx.model.StockCheckRecord.findAll({ where: { check_id: { [Op.in]: numericIds } }, order: [[ 'check_id', 'ASC' ], [ 'id', 'ASC' ]], raw: true, }); - const recordRows = await ctx.model.StockCheckRecord.findAll({ - where: { check_id: { [Op.in]: numericIds } }, - order: [[ 'detail_id', 'ASC' ], [ 'id', 'ASC' ]], - raw: true, - }); - const recordsByDetail = new Map(); - for (const record of recordRows) { - const detailRowId = Number(record.detail_id); - if (!recordsByDetail.has(detailRowId)) { - recordsByDetail.set(detailRowId, []); - } - recordsByDetail.get(detailRowId).push(record); + + // 商品快照(item_code/item_name)从 wms_stock_warehouse 补齐(库位行的记录没有商品快照) + const stockIds = [ ...new Set(recordRows.map(row => Number(row.stock_id)).filter(id => Number.isInteger(id) && id > 0)) ]; + let stockMap = new Map(); + if (stockIds.length > 0) { + const stockRows = await ctx.model.StockWarehouse.findAll({ + where: { id: { [Op.in]: stockIds } }, + attributes: [ 'id', 'item_code', 'item_name' ], + raw: true, + }); + stockMap = new Map(stockRows.map(item => [ Number(item.id), item ])); } - const detailsGrouped = new Map(); - for (const row of detailRows) { + const recordsGrouped = new Map(); + for (const row of recordRows) { + const recordStockId = Number(row.stock_id); + const isUnknownGoods = !Number.isInteger(recordStockId) || recordStockId <= 0; + const stock = stockMap.get(recordStockId) || {}; const checkId = Number(row.check_id); - if (!detailsGrouped.has(checkId)) { - detailsGrouped.set(checkId, []); + if (!recordsGrouped.has(checkId)) { + recordsGrouped.set(checkId, []); } - const detailRecords = recordsByDetail.get(Number(row.id)) || []; - const checkedQuantity = detailRecords.length > 0 - ? detailRecords.reduce((sum, record) => sum + (Number(record.quantity) || 0), 0) - : null; - const diffQuantity = checkedQuantity === null - ? null - : checkedQuantity - Number(row.system_quantity || 0); - detailsGrouped.get(checkId).push({ + recordsGrouped.get(checkId).push({ ...row, - checked_quantity: checkedQuantity, - diff_quantity: diffQuantity, - is_diff: checkedQuantity === null ? 0 : (diffQuantity !== 0 ? 1 : 0), - status: detailRecords.length > 0 ? 'checked' : 'unchecked', - location_codes: [ ...new Set(detailRecords - .map(record => String(record.location_code || '').trim()) - .filter(Boolean)) ], - checkers: [ ...new Set(detailRecords - .map(record => String(record.checker_name || '').trim()) - .filter(Boolean)) ], - last_checked_at: detailRecords.length > 0 - ? detailRecords[detailRecords.length - 1].checked_at - : null, + // 未知商品(stock_id 为空):商品编码列显示扫描条码、商品名称列显示上报名称快照; + // 已知商品维持现有口径(wms_stock_warehouse 商品快照) + item_code: isUnknownGoods ? (String(row.barcode || '').trim() || null) : (stock.item_code || null), + item_name: isUnknownGoods ? (String(row.item_name || row.barcode || '').trim() || null) : (stock.item_name || null), }); } - const totalCount = detailRows.length; - await reportProgress('running', 10, `共 ${checks.length} 个盘点任务、${totalCount} 条明细,开始导出...`, { + const totalCount = recordRows.length; + await reportProgress('running', 10, `共 ${checks.length} 个盘点任务、${totalCount} 条盘点明细,开始导出...`, { totalCount, currentCount: 0, }); - const exportResult = await this._generateAndUploadStockCheckExcel(checks, detailsGrouped, { + const exportResult = await this._generateAndUploadStockCheckExcel(checks, recordsGrouped, { totalCount, onProgress, }); @@ -1346,17 +3555,18 @@ class StockCheckService extends Service { } /** - * 生成盘点导出 Excel(Sheet1=盘点单行,Sheet2=明细行)并上传 COS,返回下载信息。 + * 生成盘点导出 Excel(Sheet1=盘点单行,Sheet2=盘点明细(作业记录:库位+数量+盘点人+时间)) + * 并上传 COS,返回下载信息。 * 与售后/退回拆包导出口径一致:流式写临时文件 → uploadFile → uploadSuccessNotify。 * * @param {Array} checks 盘点任务主表行。 - * @param {Map>} detailsGrouped 按 check_id 分组的明细行。 + * @param {Map>} recordsGrouped 按 check_id 分组的作业记录行(含 item_code/item_name 快照)。 * @param {Object} [options] 附加选项。 - * @param {number} [options.totalCount] 明细总行数(用于进度计算)。 + * @param {number} [options.totalCount] 作业记录总行数(用于进度计算)。 * @param {Function} [options.onProgress] 进度回调。 * @return {Promise} { filename, fileKey, url, cdnUrl, cosUrl }。 */ - async _generateAndUploadStockCheckExcel(checks = [], detailsGrouped = new Map(), options = {}) { + async _generateAndUploadStockCheckExcel(checks = [], recordsGrouped = new Map(), options = {}) { const { totalCount = 0, onProgress } = options; const { ctx } = this; @@ -1388,7 +3598,6 @@ class StockCheckService extends Service { '盘点方式', '盘点状态', '盘点进度', - '盘点日期', '货主ID', '创建人', '明细行数', @@ -1407,7 +3616,6 @@ class StockCheckService extends Service { STOCK_CHECK_MODE_LABELS[check.mode] || check.mode || '', STOCK_CHECK_STATUS_LABELS[check.status] || check.status || '', STOCK_CHECK_DETAIL_PROGRESS_LABELS[check.detail_status] || check.detail_status || '', - this._formatLocalDateTime(check.check_date), check.store_id === null || check.store_id === undefined ? '' : Number(check.store_id), check.creator_name || '', Number(check.total_items) || 0, @@ -1420,40 +3628,32 @@ class StockCheckService extends Service { } checksSheet.commit(); - // ---- Sheet2:明细行(一行一条明细,首列带盘点单号便于对照) ---- + // ---- Sheet2:盘点明细(作业记录:一行一条实际盘点记录,不含未盘的任务范围行) ---- const detailsSheet = workbook.addWorksheet('盘点明细'); detailsSheet.addRow([ '盘点单号', '商品编码', '商品名称', - '规格', - '账面数量', - '已盘数量', - '差异数量', - '是否有差异', '库位编码', + '实盘数量', '盘点人', - '最近盘点时间', + '盘点时间', ]).commit(); let currentCount = 0; for (const check of checks) { const checkId = Number(check.id); - const rows = detailsGrouped.get(checkId) || []; + const rows = recordsGrouped.get(checkId) || []; for (const row of rows) { detailsSheet.addRow([ check.check_no || '', row.item_code || '', row.item_name || '', - row.spec || '', - Number(row.system_quantity) || 0, - row.checked_quantity === null || row.checked_quantity === undefined ? '' : Number(row.checked_quantity), - row.diff_quantity === null || row.diff_quantity === undefined ? '' : Number(row.diff_quantity), - Number(row.is_diff) === 1 ? '是' : '否', - Array.isArray(row.location_codes) ? row.location_codes.join('、') : '', - Array.isArray(row.checkers) ? row.checkers.join('、') : '', - this._formatLocalDateTime(row.last_checked_at), + String(row.location_code || '').trim() !== '' ? row.location_code : '', + Number(row.quantity) || 0, + row.checker_name || '', + this._formatLocalDateTime(row.checked_at), ]).commit(); currentCount++; @@ -1504,7 +3704,7 @@ class StockCheckService extends Service { fileSize: stat.size, category: 'document', businessType: 'stockCheckExport', - description: `库存盘点导出,共 ${checks.length} 个盘点任务、${totalCount} 条明细`, + description: `库存盘点导出,共 ${checks.length} 个盘点任务、${totalCount} 条盘点明细`, }); } diff --git a/app/service/systems/stock_check_patterns.js b/app/service/systems/stock_check_patterns.js new file mode 100644 index 0000000..ddddb20 --- /dev/null +++ b/app/service/systems/stock_check_patterns.js @@ -0,0 +1,445 @@ +'use strict'; + +const Service = require('egg').Service; + +/** 静态盘点:仓库未配置 stock_static_hours 时使用的默认阈值小时数 */ +const DEFAULT_STATIC_HOURS = 168; + +/** + * 盘点定式定义集合(代码注册,不建表)。 + * 字段说明: + * - id:定式唯一标识(method 层 pattern_id 入参); + * - name:定式名称(创建任务时作为默认标题); + * - description:定式描述(含对象收集口径); + * - type:对应盘点任务 type(location=按库位 / goods=按商品); + * - collect:对象收集函数名(本服务内实现,入参 { warehouseId }, + * 返回 { locations: [{location_id, location_code}] } 或 { stock_ids: [...] })。 + */ +const STOCK_CHECK_PATTERNS = Object.freeze([ + Object.freeze({ + id: 'empty_location', + name: '空库位盘点', + description: '自动收集当前仓库所有「账面为空」的启用库位:wms_location_space(warehouse_id 匹配且 is_enabled=1)中,在 wms_storage 不存在任何 quantity>0 库存记录的库位(LEFT JOIN 判空)', + type: 'location', + collect: 'collectEmptyLocation', + }), + Object.freeze({ + id: 'mis_shipment', + name: '错发盘点', + description: '自动收集所有登记过错发工单(wms_after_sale.type=order 且 sub_type=mis_shipment)关联订单的商品:工单状态口径为「凡登记过即纳入,排除已关闭(closed)/已取消(cancelled)工单」,取工单 order_id 集合查询订单明细分表(OrderItemsFactory.getCurrentModel)后按 stock_id 去重', + type: 'goods', + collect: 'collectMisShipment', + }), + Object.freeze({ + id: 'expiring', + name: '临期盘点', + description: '自动收集所有开启保质期管理(wms_stock_warehouse.is_shelf_life_mgmt=Y)且存在临期库存的商品:在 wms_storage 存在 quantity>0 且 expiry_date 非空、expiry_date <= 当前时间+该商品 remaining_threshold_days 天的库存记录(商品维度去重;remaining_threshold_days 为 0 时按已到期 expiry_date <= 当前时间处理)', + type: 'goods', + collect: 'collectExpiring', + }), + Object.freeze({ + id: 'static', + name: '静态盘点', + description: '自动收集所有停收停发超过时间的商品:商品最后一次 INBOUND/OUTBOUND 流水(wms_stock_transaction)距今超过仓库配置 stock_static_hours 小时(默认 168 小时),无流水的商品按 wms_stock_warehouse.create_at 计算;已存在 wms_stock_static_check_task 记录的 stock_id(已进入静态已盘点商品)自动排除,创建任务成功后把命中的 stock_id 写入该表', + type: 'goods', + collect: 'collectStatic', + }), + Object.freeze({ + id: 'warning', + name: '预警盘点', + description: '自动收集所有到达库存预警线的商品:wms_stock_warehouse.quantity < 仓库配置 stock_warning_quantity(商品维度去重);要求仓库配置 stock_warning_enabled=true 才可执行,未开启时返回 400「未开启库存预警」', + type: 'goods', + collect: 'collectWarning', + }), +]); + +/** + * 盘点定式注册服务(供 systems.stockCheck 转调)。 + * 职责:维护定式清单、提供定式对象收集函数,不直接落库盘点主表。 + */ +class StockCheckPatternsService extends Service { + /** + * 创建带业务错误码的异常对象。 + * + * @param {string} message 错误信息。 + * @param {number} [code=400] 业务错误码。 + * @return {Error} 包含 code 的异常对象。 + */ + createBusinessError(message, code = 400) { + const error = new Error(`${message}`); + error.code = code; + return error; + } + + /** + * 判断是否为普通对象(非数组、非 null)。 + * + * @param {*} value 待判断值。 + * @return {boolean} 是普通对象返回 true。 + */ + _isPlainObject(value) { + return value !== null && typeof value === 'object' && !Array.isArray(value); + } + + /** + * 归一化 subject_config(兼容 JSON 字符串与对象)。 + * + * @param {*} raw 原始配置值。 + * @return {Object} 配置对象,非法时返回空对象。 + */ + _normalizeSubjectConfig(raw) { + if (this._isPlainObject(raw)) { + return raw; + } + if (typeof raw === 'string') { + const trimmed = raw.trim(); + if (!trimmed) { + return {}; + } + try { + const parsed = JSON.parse(trimmed); + return this._isPlainObject(parsed) ? parsed : {}; + } catch { + return {}; + } + } + return {}; + } + + /** + * 判断布尔标志是否开启(兼容 true / 1 / '1' / 'true')。 + * + * @param {*} value 标志值。 + * @return {boolean} 开启返回 true。 + */ + _isTruthyFlag(value) { + return value === true + || value === 1 + || value === '1' + || String(value || '').trim().toLowerCase() === 'true'; + } + + /** + * 读取当前仓库设置(wms_store.subject_config)。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise} subject_config 对象,读取失败返回空对象。 + */ + async _getWarehouseSubjectConfig(warehouseId) { + const { ctx } = this; + try { + const storeModel = ctx.model && ctx.model.Store; + if (!storeModel || typeof storeModel.findByPk !== 'function') { + return {}; + } + const store = await storeModel.findByPk(Number(warehouseId), { + attributes: [ 'id', 'subject_config' ], + raw: true, + }); + return this._normalizeSubjectConfig(store && store.subject_config); + } catch (error) { + ctx.logger && ctx.logger.warn && ctx.logger.warn( + `[stockCheckPatterns] 读取仓库设置失败 warehouseId=${warehouseId}: ${error && error.message}` + ); + return {}; + } + } + + /** + * 读取静态盘点阈值小时数(仓库配置 stock_static_hours,默认 168)。 + * + * @param {number} warehouseId 仓库ID。 + * @return {Promise} 阈值小时数。 + */ + async _resolveStaticHours(warehouseId) { + const subjectConfig = await this._getWarehouseSubjectConfig(warehouseId); + const configHours = Number(subjectConfig.stock_static_hours || 0); + return Number.isFinite(configHours) && configHours > 0 ? configHours : DEFAULT_STATIC_HOURS; + } + + /** + * 执行裸 SQL 查询并返回行数组。 + * + * @param {string} sql 查询语句(命名占位符 :name)。 + * @param {Object} [replacements={}] 占位符替换值。 + * @return {Promise>} 查询结果行数组。 + */ + async _queryRows(sql, replacements = {}) { + const { ctx } = this; + const rows = await ctx.model.query(sql, { + replacements, + type: ctx.model.QueryTypes.SELECT, + }); + return Array.isArray(rows) ? rows : []; + } + + /** + * 将 ID 列表归一化为去重后的正整数列表。 + * + * @param {Array<*>} values 原始 ID 列表。 + * @return {Array} 去重后的正整数列表。 + */ + _normalizePositiveIntegerList(values) { + const list = Array.isArray(values) ? values : []; + return [ ...new Set( + list + .map(value => Number(value)) + .filter(value => Number.isInteger(value) && value > 0) + ) ]; + } + + /** + * 拉取定式清单(仅对外字段,不含内部执行函数)。 + * + * @return {Array} 定式数组,每项含 id/name/description/type。 + */ + listPatterns() { + return STOCK_CHECK_PATTERNS.map(pattern => ({ + id: pattern.id, + name: pattern.name, + description: pattern.description, + type: pattern.type, + })); + } + + /** + * 按定式 ID 查询定式定义。 + * + * @param {string|number} patternId 定式ID。 + * @return {Object|null} 定式定义,不存在返回 null。 + */ + getPatternById(patternId) { + const normalized = String(patternId || '').trim(); + return STOCK_CHECK_PATTERNS.find(pattern => pattern.id === normalized) || null; + } + + /** + * 按定式 ID 收集盘点对象(goods 型返回 stock_ids,location 型返回库位列表)。 + * + * @param {string|number} patternId 定式ID。 + * @param {Object} [context={}] 收集上下文。 + * @param {number} context.warehouseId 仓库ID。 + * @return {Promise} { stock_ids } 或 { locations },定式不存在返回 null。 + */ + async collectById(patternId, context = {}) { + const pattern = this.getPatternById(patternId); + if (!pattern || typeof this[pattern.collect] !== 'function') { + return null; + } + return this[pattern.collect](context); + } + + /** + * 空库位定式:收集账面为空的启用库位。 + * 口径:wms_location_space(warehouse_id 匹配、is_enabled=1、未删除)在 + * wms_storage 不存在任何 quantity>0 且未删除的库存记录(LEFT JOIN 判空)。 + * + * @param {Object} context 收集上下文。 + * @param {number} context.warehouseId 仓库ID。 + * @return {Promise} { locations: [{ location_id, location_code }] }。 + */ + async collectEmptyLocation(context = {}) { + const warehouseId = Number(context.warehouseId); + const rows = await this._queryRows( + ` + SELECT ls.id AS location_id, ls.space_code AS location_code + FROM wms_location_space ls + LEFT JOIN wms_storage st + ON st.space_id = ls.id + AND st.delete_at IS NULL + AND st.quantity > 0 + WHERE ls.warehouse_id = :warehouseId + AND ls.is_enabled = 1 + AND ls.deleted_at IS NULL + AND st.id IS NULL + ORDER BY ls.id ASC + `, + { warehouseId } + ); + const locations = rows + .filter(row => row && row.location_id) + .map(row => ({ + location_id: Number(row.location_id), + location_code: String(row.location_code || '').trim(), + })); + return { locations }; + } + + /** + * 错发定式:收集登记过错发工单的订单关联商品。 + * 口径:wms_after_sale(warehouse_id 匹配、type=order、sub_type=mis_shipment、未删除) + * 中排除已关闭(closed)/已取消(cancelled)工单,其余状态一律纳入; + * 取 order_id 集合查询订单明细分表(OrderItemsFactory.getCurrentModel)后按 stock_id 去重。 + * + * @param {Object} context 收集上下文。 + * @param {number} context.warehouseId 仓库ID。 + * @return {Promise} { stock_ids: number[] }。 + */ + async collectMisShipment(context = {}) { + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + const warehouseId = Number(context.warehouseId); + + const afterSaleRows = await ctx.model.AfterSale.findAll({ + where: { + warehouse_id: warehouseId, + type: 'order', + sub_type: 'mis_shipment', + status: { [Op.notIn]: [ 'closed', 'cancelled' ] }, + deleted_at: null, + }, + attributes: [ 'order_id' ], + raw: true, + }); + const orderIds = this._normalizePositiveIntegerList( + (Array.isArray(afterSaleRows) ? afterSaleRows : []).map(row => row && row.order_id) + ); + if (orderIds.length === 0) { + return { stock_ids: [] }; + } + + const orderItemsModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); + const itemRows = await orderItemsModel.findAll({ + where: { order_id: { [Op.in]: orderIds } }, + attributes: [ 'stock_id' ], + raw: true, + }); + const stockIds = this._normalizePositiveIntegerList( + (Array.isArray(itemRows) ? itemRows : []).map(row => row && row.stock_id) + ); + return { stock_ids: stockIds }; + } + + /** + * 临期定式:收集开启保质期管理且存在临期库存的商品。 + * 口径:wms_stock_warehouse(warehouse_id 匹配、is_valid=Y、未删除、is_shelf_life_mgmt=Y) + * 关联 wms_storage(quantity>0、expiry_date 非空、未删除)按 stock_id 取最早到期日: + * remaining_threshold_days>0 时最早到期日 <= 当前时间+阈值天数, + * remaining_threshold_days<=0(含空)时按已到期处理(最早到期日 <= 当前时间),商品维度去重。 + * + * @param {Object} context 收集上下文。 + * @param {number} context.warehouseId 仓库ID。 + * @return {Promise} { stock_ids: number[] }。 + */ + async collectExpiring(context = {}) { + const warehouseId = Number(context.warehouseId); + const rows = await this._queryRows( + ` + SELECT sw.id AS stock_id + FROM wms_stock_warehouse sw + INNER JOIN ( + SELECT stock_id, MIN(expiry_date) AS min_expiry_date + FROM wms_storage + WHERE warehouse_id = :warehouseId + AND quantity > 0 + AND expiry_date IS NOT NULL + AND delete_at IS NULL + GROUP BY stock_id + ) st ON st.stock_id = sw.id + WHERE sw.warehouse_id = :warehouseId + AND sw.is_valid = 'Y' + AND sw.deleted_at IS NULL + AND sw.is_shelf_life_mgmt = 'Y' + AND ( + (COALESCE(sw.remaining_threshold_days, 0) > 0 + AND st.min_expiry_date <= DATE_ADD(NOW(), INTERVAL COALESCE(sw.remaining_threshold_days, 0) DAY)) + OR + (COALESCE(sw.remaining_threshold_days, 0) <= 0 + AND st.min_expiry_date <= NOW()) + ) + ORDER BY sw.id ASC + `, + { warehouseId } + ); + return { stock_ids: this._normalizePositiveIntegerList(rows.map(row => row && row.stock_id)) }; + } + + /** + * 静态定式:收集停收停发超过阈值的商品。 + * 口径:商品最后一次 INBOUND/OUTBOUND 流水(wms_stock_transaction,命中 + * warehouse_id+transaction_type+stock_id 索引)距今超过仓库配置 + * stock_static_hours 小时(默认 168 小时),无流水的商品按 + * wms_stock_warehouse.create_at 计算;排除 wms_stock_static_check_task + * 已有记录(未删除)的 stock_id,商品维度去重。 + * + * @param {Object} context 收集上下文。 + * @param {number} context.warehouseId 仓库ID。 + * @return {Promise} { stock_ids: number[] }。 + */ + async collectStatic(context = {}) { + const warehouseId = Number(context.warehouseId); + const staticHours = await this._resolveStaticHours(warehouseId); + const cutoff = new Date(Date.now() - staticHours * 3600 * 1000); + const rows = await this._queryRows( + ` + SELECT sw.id AS stock_id + FROM wms_stock_warehouse sw + LEFT JOIN ( + SELECT stock_id, MAX(last_flow_at) AS last_flow_at + FROM ( + SELECT stock_id, MAX(created_at) AS last_flow_at + FROM wms_stock_transaction + WHERE warehouse_id = :warehouseId + AND transaction_type = 'INBOUND' + GROUP BY stock_id + UNION ALL + SELECT stock_id, MAX(created_at) AS last_flow_at + FROM wms_stock_transaction + WHERE warehouse_id = :warehouseId + AND transaction_type = 'OUTBOUND' + GROUP BY stock_id + ) flow_union + GROUP BY stock_id + ) t ON t.stock_id = sw.id + WHERE sw.warehouse_id = :warehouseId + AND sw.is_valid = 'Y' + AND sw.deleted_at IS NULL + AND COALESCE(t.last_flow_at, sw.create_at) < :cutoff + AND NOT EXISTS ( + SELECT 1 + FROM wms_stock_static_check_task sct + WHERE sct.stock_id = sw.id + AND sct.deleted_at IS NULL + ) + ORDER BY sw.id ASC + `, + { warehouseId, cutoff } + ); + return { stock_ids: this._normalizePositiveIntegerList(rows.map(row => row && row.stock_id)) }; + } + + /** + * 预警定式:收集到达库存预警线的商品。 + * 口径:仓库配置 stock_warning_enabled=true 时才可执行(未开启抛 400「未开启库存预警」), + * 收集 wms_stock_warehouse(warehouse_id 匹配、is_valid=Y、未删除)中 + * quantity < stock_warning_quantity 的商品,商品维度去重。 + * + * @param {Object} context 收集上下文。 + * @param {number} context.warehouseId 仓库ID。 + * @return {Promise} { stock_ids: number[] }。 + * @throws {Error} 未开启库存预警时抛出业务错误(错误码 400)。 + */ + async collectWarning(context = {}) { + const warehouseId = Number(context.warehouseId); + const subjectConfig = await this._getWarehouseSubjectConfig(warehouseId); + if (!this._isTruthyFlag(subjectConfig.stock_warning_enabled)) { + throw this.createBusinessError('未开启库存预警'); + } + const threshold = Number(subjectConfig.stock_warning_quantity || 0); + const rows = await this._queryRows( + ` + SELECT id AS stock_id + FROM wms_stock_warehouse + WHERE warehouse_id = :warehouseId + AND is_valid = 'Y' + AND deleted_at IS NULL + AND quantity < :threshold + ORDER BY id ASC + `, + { warehouseId, threshold } + ); + return { stock_ids: this._normalizePositiveIntegerList(rows.map(row => row && row.stock_id)) }; + } +} + +module.exports = StockCheckPatternsService; diff --git a/app/service/systems/stock_store.js b/app/service/systems/stock_store.js index de3681f..ad8c5c1 100644 --- a/app/service/systems/stock_store.js +++ b/app/service/systems/stock_store.js @@ -2588,7 +2588,7 @@ class stockStoreService extends Service { const { ctx, app } = this; const { Op } = app.Sequelize; - const canChangeFlide = [ 'brand_name', 'prohibited_id', 'gross_weight', 'packing_requirements', 'pick_requirements', 'recheck_requirements', 'merge_requirements', 'managementFlags', 'stock_unit', 'need_recheck' ]; + const canChangeFlide = [ 'brand_name', 'prohibited_id', 'gross_weight', 'packing_requirements', 'pick_requirements', 'recheck_requirements', 'merge_requirements', 'managementFlags', 'stock_unit', 'need_recheck', 'warning_quantity' ]; const { ids, method, value } = ctx.request.body; @@ -2671,6 +2671,18 @@ class stockStoreService extends Service { update_by: ctx.user.id || ctx.user.username, }; + } else if (method === 'warning_quantity') { + // 库存预警数量:必须为非负整数 + const updateValue = parseInt(value, 10); + if (isNaN(updateValue) || updateValue < 0 || !Number.isInteger(Number(value))) { + return { message: '库存预警数量必须是非负整数', code: 405 }; + } + updateData = { + warning_quantity: updateValue, + update_at: new Date(), + update_by: ctx.user.id || ctx.user.username, + }; + } else if (method === 'merge_requirements') { // 要求是否合并:Y=合并,N=不合并 const updateValue = String(value).trim().toUpperCase(); @@ -3114,6 +3126,7 @@ class stockStoreService extends Service { 'width', 'enable_box_spec', 'quantity_per_box', + 'warning_quantity', 'box_gross_weight', 'box_net_weight', 'box_length', @@ -3162,6 +3175,7 @@ class stockStoreService extends Service { box_volume_m3, boxVolumeM3, shelf_life_days, inbound_min_days, outbound_min_days, remaining_threshold_days, need_recheck, + warning_quantity, } = data; const normalizedVolume = volume ?? volume_cm3 ?? volumeCm3; const normalizedBoxVolume = box_volume ?? box_volume_m3 ?? boxVolumeM3; @@ -3255,6 +3269,7 @@ class stockStoreService extends Service { inbound_min_days, outbound_min_days, remaining_threshold_days, + warning_quantity, updated_at: new Date(), }; // 5. 清除空值 @@ -3330,6 +3345,7 @@ class stockStoreService extends Service { box_gross_weight, box_net_weight, box_length, box_width, box_height, box_volume, box_remark, need_recheck, + warning_quantity, } = data; // 1. 参数验证 @@ -3374,6 +3390,7 @@ class stockStoreService extends Service { quantity_per_box, box_gross_weight, box_net_weight, + warning_quantity, item_type: 'ZC', level: 'C', store_id, @@ -3438,7 +3455,7 @@ class stockStoreService extends Service { } // 数值类型验证 - const numericFields = [ 'length', 'width', 'height', 'volume', 'gross_weight', 'net_weight' ]; + const numericFields = [ 'length', 'width', 'height', 'volume', 'gross_weight', 'net_weight', 'warning_quantity' ]; for (const field of numericFields) { if (data[field] && isNaN(Number(data[field]))) { throw new Error(`${field} 必须是有效的数字`); diff --git a/app/service/systems/stock_transaction.js b/app/service/systems/stock_transaction.js index 33e1b97..93f9891 100644 --- a/app/service/systems/stock_transaction.js +++ b/app/service/systems/stock_transaction.js @@ -190,7 +190,89 @@ class StockTransactionService extends Service { created_at: data.created_at || new Date(), }; - return ctx.model.StockTransaction.create(payload, options); + const row = await ctx.model.StockTransaction.create(payload, options); + + // 订单出入库(收/发)后商品离开静态状态:硬删除静态通知/盘点任务关联记录(失败不影响主流程) + if (data.transaction_type === 'INBOUND' || data.transaction_type === 'OUTBOUND') { + await Promise.all([ + this.clearStaticNoticeByStockId(data.stock_id, options), + this.clearStaticCheckTaskByStockId(data.stock_id, options), + ]); + } + + return row; + } + + /** + * 硬删除指定商品的静态通知记录。 + * + * 商品一旦有新的收/发流水即离开静态状态,历史通知记录不再有意义, + * 因此在流水写入成功后直接物理删除(不走软删)。 + * 清理失败不影响出入库主流程(仅记录 warn)。 + * + * @param {number} stockId 商品库存ID + * @param {Object} [options] 写入选项 + * @param {Object} [options.transaction] 数据库事务(建议与流水写入同一事务) + * @return {Promise} 删除行数(异常时返回 0) + */ + async clearStaticNoticeByStockId(stockId, options = {}) { + const { ctx } = this; + const numericStockId = Number(stockId); + if (!Number.isFinite(numericStockId) || numericStockId <= 0) { + return 0; + } + try { + const noticeModel = ctx.model && ctx.model.StockStaticNotice; + if (!noticeModel) { + return 0; + } + return await noticeModel.destroy({ + where: { stock_id: numericStockId }, + force: true, // 硬删除(paranoid 表需 force 才能物理删除) + ...(options && options.transaction ? { transaction: options.transaction } : {}), + }); + } catch (err) { + ctx.logger && ctx.logger.warn && ctx.logger.warn( + `[stockTransaction.clearStaticNoticeByStockId] 清理静态通知记录失败 stockId=${numericStockId}: ${err && err.message}` + ); + return 0; + } + } + + /** + * 硬删除指定商品的静态盘点任务关联记录。 + * + * 商品一旦有新的收/发流水即离开静态状态,已创建的盘点任务关联不再有意义, + * 因此在流水写入成功后直接物理删除(不走软删)。 + * 清理失败不影响出入库主流程(仅记录 warn)。 + * + * @param {number} stockId 商品库存ID + * @param {Object} [options] 写入选项 + * @param {Object} [options.transaction] 数据库事务(建议与流水写入同一事务) + * @return {Promise} 删除行数(异常时返回 0) + */ + async clearStaticCheckTaskByStockId(stockId, options = {}) { + const { ctx } = this; + const numericStockId = Number(stockId); + if (!Number.isFinite(numericStockId) || numericStockId <= 0) { + return 0; + } + try { + const taskModel = ctx.model && ctx.model.StockStaticCheckTask; + if (!taskModel) { + return 0; + } + return await taskModel.destroy({ + where: { stock_id: numericStockId }, + force: true, // 硬删除(paranoid 表需 force 才能物理删除) + ...(options && options.transaction ? { transaction: options.transaction } : {}), + }); + } catch (err) { + ctx.logger && ctx.logger.warn && ctx.logger.warn( + `[stockTransaction.clearStaticCheckTaskByStockId] 清理静态盘点任务关联记录失败 stockId=${numericStockId}: ${err && err.message}` + ); + return 0; + } } /** diff --git a/app/service/systems/stock_warehouse.js b/app/service/systems/stock_warehouse.js index ebea2e6..69100bd 100644 --- a/app/service/systems/stock_warehouse.js +++ b/app/service/systems/stock_warehouse.js @@ -257,6 +257,225 @@ class StockWarehouseService extends Service { // 删除缓存失败不影响主流程 } } + + /** + * 读取商品库存预警数量(内部方法)。 + * + * 优先级: + * 1. 商品单独设置了预警数量(warning_quantity > 0)→ 取商品设置数; + * 2. 货主(stock.store_id 对应 wms_store)开启库存预警(stock_warning_enabled) + * 且配置了预警数量(stock_warning_quantity > 0)→ 取货主设置数; + * 3. 以上均不满足 → 返回 0(不预警)。 + * + * @param {number|string} stockId 仓库商品ID(wms_stock_warehouse.id)。 + * @return {Promise} 库存预警数量(非负整数),读取异常时返回 0。 + */ + async getStockWarningQuantity(stockId) { + const { ctx } = this; + const normalizedStockId = Number(stockId || 0); + if (!Number.isFinite(normalizedStockId) || normalizedStockId <= 0) { + return 0; + } + + try { + const stockModel = ctx.model && ctx.model.StockWarehouse; + if (!stockModel || typeof stockModel.findOne !== 'function') { + return 0; + } + + const stock = await stockModel.findOne({ + where: { id: normalizedStockId, is_valid: 'Y', deleted_at: null }, + attributes: [ 'id', 'store_id', 'warning_quantity' ], + raw: true, + }); + if (!stock) { + return 0; + } + + // 商品单独设置优先 + const productWarningQuantity = Number(stock.warning_quantity || 0); + if (Number.isInteger(productWarningQuantity) && productWarningQuantity > 0) { + return productWarningQuantity; + } + + // 货主配置:开启且数量 > 0 才生效 + const storeId = Number(stock.store_id || 0); + if (storeId > 0) { + const storeModel = ctx.model && ctx.model.Store; + if (storeModel && typeof storeModel.findByPk === 'function') { + const store = await storeModel.findByPk(storeId, { + attributes: [ 'id', 'subject_config' ], + raw: true, + }); + const subjectConfig = store && store.subject_config + ? store.subject_config + : {}; + const enabled = subjectConfig.stock_warning_enabled === true + || subjectConfig.stock_warning_enabled === 1 + || String(subjectConfig.stock_warning_enabled || '').trim().toLowerCase() === 'true'; + const storeWarningQuantity = Number(subjectConfig.stock_warning_quantity || 0); + if (enabled && Number.isInteger(storeWarningQuantity) && storeWarningQuantity > 0) { + return storeWarningQuantity; + } + } + } + + return 0; + } catch (err) { + ctx.logger && ctx.logger.warn && ctx.logger.warn( + `[stockWarehouse.getStockWarningQuantity] 读取库存预警数量失败 stockId=${normalizedStockId}: ${err && err.message}` + ); + return 0; + } + } + + /** + * 查询静态商品列表(仓库级)。 + * + * 静态判定:商品最后一个收(INBOUND)/发(OUTBOUND)流水时间超过阈值小时数 + * 即视为进入静态;无收发流水记录的商品以创建时间(create_at)为基准。 + * 阈值优先取入参 hours,缺省读仓库配置 subject_config.stock_static_hours(默认 168 小时)。 + * + * @param {Object} [options={}] 选项。 + * @param {number} [options.warehouseId] 仓库ID,缺省取 ctx.user.store_id。 + * @param {number} [options.hours] 静态时间阈值(小时),缺省读仓库配置。 + * @param {number} [options.page=1] 页码。 + * @param {number} [options.pageSize=20] 每页条数。 + * @return {Promise<{list: Array, pagination: {page:number, pageSize:number, total:number, totalPages:number}}>} + * list 每项含 id/item_code/item_name/sku_property/stock_unit/store_id/quantity/locked_quantity/ + * gross_weight/warning_quantity/create_at/last_flow_at/static_hours/is_static。 + */ + async getStaticStockList(options = {}) { + const { ctx } = this; + const requestData = options && typeof options === 'object' ? options : {}; + const warehouseId = Number(requestData.warehouseId || (ctx.user && ctx.user.store_id) || 0); + const page = Number(requestData.page || 1) > 0 ? Math.floor(Number(requestData.page)) : 1; + const pageSize = Number(requestData.pageSize || 20) > 0 + ? Math.min(500, Math.floor(Number(requestData.pageSize))) + : 20; + const emptyPagination = { + page, + pageSize, + total: 0, + totalPages: 0, + }; + + if (!Number.isFinite(warehouseId) || warehouseId <= 0) { + return { list: [], pagination: emptyPagination }; + } + + // 阈值小时数:入参优先,否则仓库配置(默认 168) + let staticHours = Number(requestData.hours); + if (!Number.isFinite(staticHours) || staticHours <= 0) { + staticHours = 168; + try { + const storeModel = ctx.model && ctx.model.Store; + if (storeModel && typeof storeModel.findByPk === 'function') { + const store = await storeModel.findByPk(warehouseId, { + attributes: [ 'id', 'subject_config' ], + raw: true, + }); + const subjectConfig = store && store.subject_config ? store.subject_config : {}; + const configHours = Number(subjectConfig.stock_static_hours || 0); + if (Number.isFinite(configHours) && configHours > 0) { + staticHours = configHours; + } + } + } catch (err) { + ctx.logger && ctx.logger.warn && ctx.logger.warn( + `[stockWarehouse.getStaticStockList] 读取仓库静态时间配置失败,按默认 168 小时: ${err && err.message}` + ); + } + } + + const cutoff = new Date(Date.now() - staticHours * 3600 * 1000); + + const fromSql = ` + FROM wms_stock_warehouse sw + LEFT JOIN ( + SELECT stock_id, MAX(last_flow_at) AS last_flow_at + FROM ( + SELECT stock_id, MAX(created_at) AS last_flow_at + FROM wms_stock_transaction + WHERE warehouse_id = :warehouseId + AND transaction_type = 'INBOUND' + GROUP BY stock_id + UNION ALL + SELECT stock_id, MAX(created_at) AS last_flow_at + FROM wms_stock_transaction + WHERE warehouse_id = :warehouseId + AND transaction_type = 'OUTBOUND' + GROUP BY stock_id + ) flow_union + GROUP BY stock_id + ) t ON t.stock_id = sw.id + WHERE sw.warehouse_id = :warehouseId + AND sw.is_valid = 'Y' + AND sw.deleted_at IS NULL + AND COALESCE(t.last_flow_at, sw.create_at) < :cutoff + `; + const listSql = ` + SELECT sw.id, sw.item_code, sw.item_name, sw.sku_property, sw.stock_unit, + sw.store_id, sw.quantity, sw.locked_quantity, sw.gross_weight, + sw.warning_quantity, sw.create_at, t.last_flow_at + ${fromSql} + ORDER BY COALESCE(t.last_flow_at, sw.create_at) ASC + LIMIT :limit OFFSET :offset + `; + const countSql = ` + SELECT COUNT(1) AS total + ${fromSql} + `; + + const { QueryTypes } = ctx.model; + const baseReplacements = { + warehouseId, + cutoff, + }; + const offset = (page - 1) * pageSize; + + const [ countRows, listRows ] = await Promise.all([ + ctx.model.query(countSql, { + replacements: baseReplacements, + type: QueryTypes.SELECT, + }), + ctx.model.query(listSql, { + replacements: { ...baseReplacements, limit: pageSize, offset }, + type: QueryTypes.SELECT, + }), + ]); + + const total = Number( + (Array.isArray(countRows) && countRows.length > 0 ? countRows[0].total : 0) || 0 + ); + const totalPages = pageSize > 0 ? Math.ceil(total / pageSize) : 0; + const list = (Array.isArray(listRows) ? listRows : []).map(row => ({ + id: Number(row && row.id || 0), + item_code: String(row && row.item_code || '').trim(), + item_name: String(row && row.item_name || '').trim(), + sku_property: String(row && row.sku_property || '').trim(), + stock_unit: String(row && row.stock_unit || '').trim(), + store_id: row && row.store_id != null ? Number(row.store_id) : 0, + quantity: Number(row && row.quantity || 0), + locked_quantity: Number(row && row.locked_quantity || 0), + gross_weight: Number(row && row.gross_weight || 0), + warning_quantity: Number(row && row.warning_quantity || 0), + create_at: row && row.create_at ? row.create_at : null, + last_flow_at: row && row.last_flow_at ? row.last_flow_at : null, + static_hours: staticHours, + is_static: true, + })); + + return { + list, + pagination: { + page, + pageSize, + total, + totalPages, + }, + }; + } } module.exports = StockWarehouseService; diff --git a/database/migrations/20260930110000-add-warning-quantity-to-wms-stock-warehouse.js b/database/migrations/20260930110000-add-warning-quantity-to-wms-stock-warehouse.js new file mode 100644 index 0000000..84e5cb1 --- /dev/null +++ b/database/migrations/20260930110000-add-warning-quantity-to-wms-stock-warehouse.js @@ -0,0 +1,17 @@ +'use strict'; + +module.exports = { + async up(queryInterface, Sequelize) { + await queryInterface.addColumn('wms_stock_warehouse', 'warning_quantity', { + type: Sequelize.INTEGER(11), + allowNull: true, + defaultValue: 0, + comment: '库存预警数量', + after: 'locked_quantity', + }); + }, + + async down(queryInterface) { + await queryInterface.removeColumn('wms_stock_warehouse', 'warning_quantity'); + }, +}; diff --git a/database/migrations/20260930110000-support-location-scope-in-stock-check-detail.js b/database/migrations/20260930110000-support-location-scope-in-stock-check-detail.js new file mode 100644 index 0000000..cbe0979 --- /dev/null +++ b/database/migrations/20260930110000-support-location-scope-in-stock-check-detail.js @@ -0,0 +1,131 @@ +'use strict'; + +/** + * 库存盘点范围类型改造:盘点明细表支持「商品」与「库位」两种盘点范围行。 + * 注:原计划时间戳 20260930100000 已被 add-packages-weight-to-wms-order-delivery 占用, + * 故本迁移使用 20260930110000 保证确定性排序。 + * + * wms_stock_check_detail: + * 1. 新增 scope_type(盘点范围类型:goods=商品,location=库位)。 + * 2. stock_id / item_code 改为可空(库位行无商品快照)。 + * 3. 重新引入 location_id / location_code(库位行专用;商品行为空)。 + * 4. 更新表注释。 + * 5. 防御性合并历史重复明细(同 check_id+stock_id 保留 id 最大行,旧行作业记录重指向保留行)。 + * 6. 新增唯一索引 uk_check_stock(check_id, stock_id) 与 uk_check_location(check_id, location_code) + * (MySQL 唯一索引允许多个 NULL:商品行 location_code=NULL、库位行 stock_id=NULL 互不干扰)。 + * + * wms_stock_check_record: + * 1. 移除唯一索引 uk_detail_location(detail_id, location_code)。 + * 2. 防御性合并重复(同 detail_id+stock_id+location_code 组保留 id 最大一条,raw SQL)。 + * 3. 新增唯一索引 uk_detail_stock_location(detail_id, stock_id, location_code)。 + * 原因:按库位盘点时同一库位明细行下会有多个商品的记录, + * 覆盖式语义应升级为「同明细 + 同商品 + 同库位」。 + */ + +const DETAIL_TABLE_NAME = 'wms_stock_check_detail'; +const RECORD_TABLE_NAME = 'wms_stock_check_record'; + +module.exports = { + up: async queryInterface => { + // ===== wms_stock_check_detail ===== + + // 1) 新增字段(raw SQL 保证列位置与注释精确) + await queryInterface.sequelize.query(` + ALTER TABLE \`${DETAIL_TABLE_NAME}\` + ADD COLUMN \`scope_type\` VARCHAR(20) NOT NULL DEFAULT 'goods' COMMENT '盘点范围类型:goods=商品,location=库位' AFTER \`warehouse_id\`, + ADD COLUMN \`location_id\` BIGINT(20) UNSIGNED NULL COMMENT '库位ID,关联 wms_location_space.id;库位盘点行为空' AFTER \`stock_id\`, + ADD COLUMN \`location_code\` VARCHAR(50) NULL COMMENT '库位编码(space_code);库位盘点行为空' AFTER \`location_id\` + `); + + // 2) stock_id / item_code 改为可空 + await queryInterface.sequelize.query(` + ALTER TABLE \`${DETAIL_TABLE_NAME}\` + MODIFY COLUMN \`stock_id\` BIGINT(20) UNSIGNED NULL COMMENT '库存商品ID,关联 wms_stock_warehouse.id;库位盘点行为空', + MODIFY COLUMN \`item_code\` VARCHAR(50) NULL COMMENT '商品编码快照;库位盘点行为空' + `); + + // 3) 更新表注释 + await queryInterface.sequelize.query( + `ALTER TABLE \`${DETAIL_TABLE_NAME}\` COMMENT='库存盘点明细表(盘点范围行:商品或库位)'` + ); + + // 4) 防御性合并重复明细:同 (check_id, stock_id) 保留 id 最大行,旧行的作业记录重指向保留行 + await queryInterface.sequelize.query(` + UPDATE \`${RECORD_TABLE_NAME}\` r + JOIN \`${DETAIL_TABLE_NAME}\` d ON r.detail_id = d.id + JOIN ( + SELECT check_id, stock_id, MAX(id) AS keep_id + FROM \`${DETAIL_TABLE_NAME}\` + WHERE stock_id IS NOT NULL + GROUP BY check_id, stock_id + HAVING COUNT(*) > 1 + ) g ON g.check_id = d.check_id AND g.stock_id = d.stock_id AND d.id <> g.keep_id + SET r.detail_id = g.keep_id + `); + await queryInterface.sequelize.query(` + DELETE d FROM \`${DETAIL_TABLE_NAME}\` d + JOIN ( + SELECT check_id, stock_id, MAX(id) AS keep_id + FROM \`${DETAIL_TABLE_NAME}\` + WHERE stock_id IS NOT NULL + GROUP BY check_id, stock_id + HAVING COUNT(*) > 1 + ) g ON g.check_id = d.check_id AND g.stock_id = d.stock_id AND d.id < g.keep_id + `); + + // 5) 新增唯一索引 + await queryInterface.addIndex(DETAIL_TABLE_NAME, [ 'check_id', 'stock_id' ], { + unique: true, + name: 'uk_check_stock', + }); + await queryInterface.addIndex(DETAIL_TABLE_NAME, [ 'check_id', 'location_code' ], { + unique: true, + name: 'uk_check_location', + }); + + // ===== wms_stock_check_record ===== + + // 1) 移除旧唯一索引 uk_detail_location + await queryInterface.removeIndex(RECORD_TABLE_NAME, 'uk_detail_location'); + + // 2) 合并重复:同 (detail_id, stock_id, location_code) 组保留 id 最大一条 + await queryInterface.sequelize.query(` + DELETE r1 FROM \`${RECORD_TABLE_NAME}\` r1 + JOIN \`${RECORD_TABLE_NAME}\` r2 + ON r1.detail_id = r2.detail_id + AND r1.stock_id = r2.stock_id + AND r1.location_code = r2.location_code + AND r1.id < r2.id + `); + + // 3) 新增唯一索引 uk_detail_stock_location + await queryInterface.addIndex(RECORD_TABLE_NAME, [ 'detail_id', 'stock_id', 'location_code' ], { + unique: true, + name: 'uk_detail_stock_location', + }); + }, + + down: async queryInterface => { + // 回退 wms_stock_check_record + await queryInterface.removeIndex(RECORD_TABLE_NAME, 'uk_detail_stock_location'); + await queryInterface.addIndex(RECORD_TABLE_NAME, [ 'detail_id', 'location_code' ], { + unique: true, + name: 'uk_detail_location', + }); + + // 回退 wms_stock_check_detail + await queryInterface.removeIndex(DETAIL_TABLE_NAME, 'uk_check_location'); + await queryInterface.removeIndex(DETAIL_TABLE_NAME, 'uk_check_stock'); + await queryInterface.sequelize.query( + `ALTER TABLE \`${DETAIL_TABLE_NAME}\` COMMENT='库存盘点明细表(盘点商品清单)'` + ); + await queryInterface.removeColumn(DETAIL_TABLE_NAME, 'location_code'); + await queryInterface.removeColumn(DETAIL_TABLE_NAME, 'location_id'); + await queryInterface.removeColumn(DETAIL_TABLE_NAME, 'scope_type'); + await queryInterface.sequelize.query(` + ALTER TABLE \`${DETAIL_TABLE_NAME}\` + MODIFY COLUMN \`stock_id\` BIGINT(20) UNSIGNED NOT NULL COMMENT '库存商品ID,关联 wms_stock_warehouse.id', + MODIFY COLUMN \`item_code\` VARCHAR(50) NOT NULL COMMENT '商品编码快照' + `); + }, +}; diff --git a/database/migrations/20260930120000-add-index-wh-type-stock-time-to-wms-stock-transaction.js b/database/migrations/20260930120000-add-index-wh-type-stock-time-to-wms-stock-transaction.js new file mode 100644 index 0000000..d0a67d7 --- /dev/null +++ b/database/migrations/20260930120000-add-index-wh-type-stock-time-to-wms-stock-transaction.js @@ -0,0 +1,16 @@ +'use strict'; + +module.exports = { + async up(queryInterface) { + // 静态商品查询优化:覆盖索引,支撑 warehouse_id + transaction_type 过滤、stock_id 分组、created_at 取 MAX + await queryInterface.addIndex( + 'wms_stock_transaction', + [ 'warehouse_id', 'transaction_type', 'stock_id', 'created_at' ], + { name: 'idx_wh_type_stock_time' } + ); + }, + + async down(queryInterface) { + await queryInterface.removeIndex('wms_stock_transaction', 'idx_wh_type_stock_time'); + }, +}; diff --git a/database/migrations/20260930130000-create-wms-stock-static-notice.js b/database/migrations/20260930130000-create-wms-stock-static-notice.js new file mode 100644 index 0000000..c116334 --- /dev/null +++ b/database/migrations/20260930130000-create-wms-stock-static-notice.js @@ -0,0 +1,63 @@ +'use strict'; + +const TABLE_NAME = 'wms_stock_static_notice'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME); + if (exists) return; + + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + stock_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '商品ID,关联 wms_stock_warehouse.id', + }, + notice_time: { + type: Sequelize.DATE, + allowNull: false, + 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: '软删除时间', + }, + }, { + comment: '静态商品通知关联表(记录静态商品已通知时间,避免重复通知)', + }); + + // 核心查询:查某商品最近一次通知时间 + await queryInterface.addIndex(TABLE_NAME, [ 'stock_id', 'notice_time' ], { + name: 'idx_stock_notice_time', + }); + // 时间范围扫描:按通知时间清理/统计 + await queryInterface.addIndex(TABLE_NAME, [ 'notice_time' ], { + name: 'idx_notice_time', + }); + }, + + down: async queryInterface => { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260930140000-create-wms-stock-static-check-task.js b/database/migrations/20260930140000-create-wms-stock-static-check-task.js new file mode 100644 index 0000000..8393461 --- /dev/null +++ b/database/migrations/20260930140000-create-wms-stock-static-check-task.js @@ -0,0 +1,63 @@ +'use strict'; + +const TABLE_NAME = 'wms_stock_static_check_task'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : t.tableName) === TABLE_NAME); + if (exists) return; + + await queryInterface.createTable(TABLE_NAME, { + id: { + type: Sequelize.BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键ID', + }, + stock_id: { + type: Sequelize.BIGINT(20).UNSIGNED, + allowNull: false, + comment: '商品ID,关联 wms_stock_warehouse.id', + }, + task_time: { + type: Sequelize.DATE, + allowNull: false, + 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: '软删除时间', + }, + }, { + comment: '静态商品盘点任务关联表(记录是否已为静态商品创建盘点任务,避免重复创建)', + }); + + // 核心查询:查某商品最近一次创建盘点任务时间 + await queryInterface.addIndex(TABLE_NAME, [ 'stock_id', 'task_time' ], { + name: 'idx_stock_task_time', + }); + // 时间范围扫描:按任务创建时间清理/统计 + await queryInterface.addIndex(TABLE_NAME, [ 'task_time' ], { + name: 'idx_task_time', + }); + }, + + down: async queryInterface => { + await queryInterface.dropTable(TABLE_NAME); + }, +}; diff --git a/database/migrations/20260930150000-remove-check-date-from-wms-stock-check.js b/database/migrations/20260930150000-remove-check-date-from-wms-stock-check.js new file mode 100644 index 0000000..aba1d95 --- /dev/null +++ b/database/migrations/20260930150000-remove-check-date-from-wms-stock-check.js @@ -0,0 +1,56 @@ +'use strict'; + +/** + * 盘点主表时间字段调整: + * 1. 移除盘点日期 check_date(及其联合索引 idx_warehouse_check_date)—— + * 创建任务不再传盘点时间,盘点时间线由 start_time/end_time 表达。 + * 2. start_time(盘点开始时间:第一个盘点明细写入时间)与 + * end_time(盘点结束时间:完成盘点时间)注释对齐新语义,类型不变。 + */ + +const TABLE_NAME = 'wms_stock_check'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const { DATE } = Sequelize; + + // 先删索引再删列 + await queryInterface.removeIndex(TABLE_NAME, 'idx_warehouse_check_date'); + await queryInterface.removeColumn(TABLE_NAME, 'check_date'); + + await queryInterface.changeColumn(TABLE_NAME, 'start_time', { + type: DATE, + allowNull: true, + comment: '盘点开始时间(第一个盘点明细写入的时间)', + }); + await queryInterface.changeColumn(TABLE_NAME, 'end_time', { + type: DATE, + allowNull: true, + comment: '盘点结束时间(完成盘点的时间)', + }); + }, + + down: async (queryInterface, Sequelize) => { + const { DATE } = Sequelize; + + await queryInterface.addColumn(TABLE_NAME, 'check_date', { + type: DATE, + allowNull: false, + comment: '盘点日期', + }); + await queryInterface.addIndex(TABLE_NAME, [ 'warehouse_id', 'check_date' ], { + name: 'idx_warehouse_check_date', + }); + + await queryInterface.changeColumn(TABLE_NAME, 'start_time', { + type: DATE, + allowNull: true, + comment: '实际开始时间', + }); + await queryInterface.changeColumn(TABLE_NAME, 'end_time', { + type: DATE, + allowNull: true, + comment: '实际结束时间', + }); + }, +}; diff --git a/database/migrations/20261001100000-support-unknown-goods-in-stock-check-record.js b/database/migrations/20261001100000-support-unknown-goods-in-stock-check-record.js new file mode 100644 index 0000000..10f8557 --- /dev/null +++ b/database/migrations/20261001100000-support-unknown-goods-in-stock-check-record.js @@ -0,0 +1,40 @@ +'use strict'; + +/** + * 库存盘点作业记录表支持未知商品(仿收货明细口径:stock_id 可空 + barcode + item_name): + * + * wms_stock_check_record: + * 1. stock_id 改为可空(NULL=未知商品;唯一索引 uk_detail_stock_location 中 NULL 不参与唯一约束, + * MySQL 语义允许多个 NULL 行,索引保持不动)。 + * 2. 新增 barcode(扫描到的条码/编码,STRING(100) 可空,已知商品可为空)。 + * 3. 新增 item_name(未知商品名称快照,缺省为条码,STRING(255) 可空,已知商品为空)。 + * + * 未知商品无账面:盘点差异 = 实盘数量 - 0 = 盘盈; + * 覆盖式查重由应用层按(detail_id + stock_id IS NULL + barcode + location_code)保证。 + */ + +const TABLE_NAME = 'wms_stock_check_record'; + +module.exports = { + up: async queryInterface => { + await queryInterface.sequelize.query(` + ALTER TABLE \`${TABLE_NAME}\` + MODIFY COLUMN \`stock_id\` BIGINT(20) UNSIGNED NULL COMMENT '库存商品ID(冗余,商品维度查询),关联 wms_stock_warehouse.id;NULL=未知商品', + ADD COLUMN \`barcode\` VARCHAR(100) NULL COMMENT '扫描到的条码/编码(未知商品上报使用;已知商品可为空)' AFTER \`stock_id\`, + ADD COLUMN \`item_name\` VARCHAR(255) NULL COMMENT '未知商品名称快照(缺省为条码);已知商品为空' AFTER \`barcode\` + `); + }, + + down: async queryInterface => { + // 回退前先清理未知商品记录(stock_id 为 NULL 的行),保证恢复 NOT NULL 不失败 + await queryInterface.sequelize.query( + `DELETE FROM \`${TABLE_NAME}\` WHERE \`stock_id\` IS NULL` + ); + await queryInterface.removeColumn(TABLE_NAME, 'item_name'); + await queryInterface.removeColumn(TABLE_NAME, 'barcode'); + await queryInterface.sequelize.query(` + ALTER TABLE \`${TABLE_NAME}\` + MODIFY COLUMN \`stock_id\` BIGINT(20) UNSIGNED NOT NULL COMMENT '库存商品ID(冗余,商品维度查询),关联 wms_stock_warehouse.id' + `); + }, +}; diff --git a/methods/changes/system.json b/methods/changes/system.json index 14027d8..3106d98 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,408 @@ [ + { + "version": "2026.10.02-system-platform-header-miniprogram", + "date": "2026-10-02", + "type": "updated", + "summary": "docs 全局 Header 的 platform 下拉修正:「微信端」取值由 wx 改为 miniprogram,并移除重复的「小程序端」(miniProgram)选项", + "methods": [ + "/api/docs" + ], + "notes": [ + "依据:app/service/system.js#ALLOWED_PLATFORMS 含小写 miniprogram(校验前 toLowerCase,实际建议使用规范值);app/service/systems/wechat.js 登录链路 platform_code 兜底为 'miniprogram';接口日志实测客户端 platform 取值只有 web/pda/miniprogram,从未出现 wx/miniProgram。", + "文档变更范围:methods/system.json 根 headers 的 platform.list——「微信端」value 由 wx 改为 miniprogram,删除「小程序端」(value=miniProgram,与微信端同义且大小写与规范不一致);platform 描述示例补充 miniprogram;project 列表及其它 header 不变;根版本 0.3.226 → 0.3.227、updatedAt 保持 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);所有 method 条目未改动。", + "库表维护源说明:wms_method_doc_meta.headers 与 version 同步更新后按 import→export 往返校验,保持库与文件一致。" + ] + }, + { + "version": "2026.10.02-stock-check-work-data-status-guard", + "date": "2026-10-02", + "type": "updated", + "summary": "workData 新增状态限制:仅 approved/checking 任务可拉取盘点作业数据,其他状态返回 400 并说明原因", + "methods": [ + "stock.check.workData" + ], + "notes": [ + "代码依据:app/service/systems/stock_check.js#workData 在任务存在校验之后新增状态守卫——check.status 不在 REPORT_ALLOWED_STATUSES(approved/checking,与 report/finish 一致)内时抛 400(createBusinessError(message, 400)),文案『当前状态({STOCK_CHECK_STATUS_LABELS 中文标签,无标签回退状态值})不允许拉取盘点作业数据,仅审核完成(approved)或盘点作业中(checking)的任务可拉取』;本次仅同步文档,未改动任何代码(代码变更已通过 ESLint 与 193 条集成测试)。", + "状态限制口径:仅任务状态 approved(审核完成)或 checking(盘点作业中)可拉取盘点作业数据;created 已创建/submitted 待审核/rejected 已驳回/completed 已完成/cancelled 已取消 均返回 400;与 report(盘点作业上报,approved 首次上报自动转 checking)及 finish(完成盘点)使用同一 REPORT_ALLOWED_STATUSES 常量。", + "400 文案:盘点任务ID不能为空 / 视图类型非法(仅支持 location/goods/space)→ 当前状态(xx)不允许拉取盘点作业数据,仅审核完成(approved)或盘点作业中(checking)的任务可拉取 → 盘点任务不存在(校验顺序:id → view → 任务存在 → 状态守卫)。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 一条(errors 的 400 拆分三条并新增状态限制文案、description/notes 补充状态限制口径);根版本 0.3.225 → 0.3.226、updatedAt 保持 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);其余 19 条 method 未改动(stock.check 分组仍为 20 条)。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库(显式 WMS_DB_TARGET=local)与生产库(NODE_ENV=production + --env production 双设置)——import 当前 system.json → export 回写往返校验,保持库与文件一致;stock.check 分组共 20 条 method 无损。" + ] + }, + { + "version": "2026.10.02-stock-check-work-data", + "date": "2026-10-02", + "type": "added", + "summary": "新增 stock.check.workData 盘点作业数据接口:一个接口按 view 入参驱动三种视图(location 库位结构含未知商品子列表;goods 商品列表按库位子列表;space 聚合库位列表按拣货路径排序),明盘显示数量、盲盘隐藏数量", + "methods": [ + "stock.check.workData" + ], + "notes": [ + "代码依据:app/service/systems/stock_check.js#workData(id 非正整数抛 400『盘点任务ID不能为空』;view 非 location/goods/space 抛 400『视图类型非法(仅支持 location/goods/space)』;任务不存在(按 id+warehouse_id 查 wms_stock_check)抛 400『盘点任务不存在』;按 view 分派 _buildLocationWorkRows/_buildGoodsWorkRows/_buildSpaceWorkRows,统一返回 { check: _formatCheckRow 口径, rows, total: rows.length })+ app/service/systemMethods/stock/check.js#workData(warehouse_id 由服务端从 ctx.user.store_id 自动注入,前端无需传递);本次仅同步文档,未改动任何代码。", + "三视图口径:location=库位结构,以任务库位范围行(scope_type=location)为列表(按明细 id 升序),行内挂该库位盘点作业记录——goods 已知商品子列表(stock_id 有值,商品信息批量取自 stockWarehouse.getStockDetails 带缓存、货主名 _resolveStoreNameMap 解析、图片 image_url)与 unknown 未知商品子列表(stock_id 为空,输出记录快照 barcode/item_name/images,图片经 _attachRecordImages 挂载 FileReference business_type=stock_check_record);goods=商品结构,以任务商品范围行(scope_type=goods)为列表(按明细 id 升序),行内挂按库位聚合的 locations(空库位归 location_code=null 组,按首条记录 id 升序);space=聚合库位列表,以任务商品(scope_type=goods 的 stock_id 集合)所在库位为列表——wms_storage(warehouse_id + stock_id 在集合 + is_enabled=1 未删除)DISTINCT space_id,行内 goods 为该库位下的任务商品,未在 wms_storage 有库位的商品不入列表。", + "明盘/盲盘数量控制:明盘(mode=open)goods 视图行返回 system_quantity(明细账面快照)/checked_quantity(已盘合计=locations.quantity 合计)/diff_quantity(已盘-账面)/is_diff(差异非 0 为 1),locations 各项含 quantity(该库位实盘合计);space 视图 goods 各项含 system_quantity(wms_storage space+stock SUM(quantity) 账面)/checked_quantity(该商品在该库位的实盘合计);盲盘(mode=blind)不返回任何数量字段(goods 视图 locations 仅 location_code/checked_at/checker_name,space 视图 goods 仅商品信息+status);无作业记录时 locations 为空数组、明盘已盘合计/差异按 0(避免未盘行误显盘亏差异)。", + "排序口径:space 视图库位按拣货路径排序——pick_sequence 升序、pick_priority 降序、同值按库位 id 升序兜底;space 行内 goods 按 stock_id 升序;location/goods 视图行按明细 id 升序;goods 视图 locations 按首条记录 id 升序。", + "权限口径:随 ALL_METHOD_NAMES(20 个:create/list/addDetail/addLocationDetail/detailDelete/detail/result/workData/report/recordList/recordDelete/finish/submit/cancel/audit/batchDelete/export/exportTaskProgress/patternList/patternCreate)免 API 权限(isNeedAuth=false)、免仓库有效期鉴权(_noNeedAuth)、必须登录(isNeedLogin=true,免登录清单为空);为查询类方法,加入免日志清单 _noNeedLog(list/detail/result/workData/recordList/export/exportTaskProgress/patternList),不记录操作日志。", + "文档变更范围:methods/system.json 的 module=stock.check 分组新增 stock.check.workData 一条(位于 stock.check.result 之后);根版本 0.3.224 → 0.3.225、updatedAt 2026-10-01 → 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);其余 19 条 method 未改动(stock.check 分组由 19 条增至 20 条)。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库(显式 WMS_DB_TARGET=local)与生产库(NODE_ENV=production + --env production 双设置)——import 当前 system.json → export 回写往返校验,保持库与文件一致;stock.check 分组共 20 条 method 无损。" + ] + }, + { + "version": "2026.10.01-stock-check-detail-delete-batch", + "date": "2026-10-01", + "type": "updated", + "summary": "detailDelete 支持批量删除:入参 detail_ids(兼容旧 detail_id 单值),返回改为 { deleted_count, deleted_ids, skipped_ids, total_items },未命中跳过不报错", + "methods": [ + "stock.check.detailDelete" + ], + "notes": [ + "代码依据:app/service/systems/stock_check.js(detailDelete:id 非法抛 400『盘点任务ID不能为空』、任务不存在抛 400『盘点任务不存在』、状态非 created/rejected 抛 400『当前状态(xxx)不允许删除明细』、_normalizeIdList 归一化(单值自动转数组、去重、仅保留正整数)后为空抛 400『请至少选择一个明细』、超过 200 抛 400『单次最多删除 200 条明细』;按 id in ids + check_id + warehouse_id 仓库隔离查询,未命中 ID 计入 skipped_ids 不报错;命中明细批量 destroy 并防御性清理 wms_stock_check_record,重算主表 total_items;返回 { deleted_count, deleted_ids, skipped_ids, total_items },deleted_ids/skipped_ids 保持入参顺序)+ app/service/systemMethods/stock/check.js(detailDelete 入参改为 detail_ids 数组,兼容 detailIds 驼峰与旧 detail_id 单值,优先级 detail_ids > detailIds > detail_id,单值自动转数组);本次仅同步文档,未改动任何代码。", + "批量口径:单次上限 200;单值自动转数组并去重;未命中的明细ID计入 skipped_ids 不报错;命中批量删除并防御清理作业记录(正常流程 created/rejected 不应有记录);删除后重算 total_items;deleted_ids/skipped_ids 保持入参顺序。", + "响应结构变更(兼容性影响):由旧版 { detail_id, deleted, total_items } 变更为 { deleted_count, deleted_ids, skipped_ids, total_items },旧前端需按新结构适配。", + "文档变更范围:methods/system.json 的 module=stock.check 分组更新 stock.check.detailDelete(params 改为 detail_ids 数组+兼容字段 detailIds/detail_id、response 改为批量结构、errors 同步批量文案、description/notes 同步);根版本 0.3.223 → 0.3.224、updatedAt 保持 2026-10-01;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动(stock.check 分组仍为 19 条)。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库(显式 WMS_DB_TARGET=local)与生产库(NODE_ENV=production + --env production 双设置)——import 当前 system.json → export 回写往返校验,保持库与文件一致;stock.check 分组共 19 条 method 无损。" + ] + }, + { + "version": "2026.10.01-stock-check-add-detail-location-ids", + "date": "2026-10-01", + "type": "updated", + "summary": "addDetail 支持 location_ids 按库位ID直查添加(与 stock_ids 按任务类型区分维度),addLocationDetail 转调 addDetail 保留兼容", + "methods": [ + "stock.check.addDetail", + "stock.check.addLocationDetail" + ], + "notes": [ + "代码依据:app/service/systems/stock_check.js(addDetail 新增 locationIds 入参与 _addLocationRowsByIds 库位ID直查路径、addLocationDetail 薄封装转调 addDetail 并映射返回结构)+ app/service/systemMethods/stock/check.js(addDetail/addLocationDetail 新增 location_ids 入参并兼容 locationIds 驼峰,location_ids 优先);本次仅同步文档,未改动任何代码。", + "分派口径:addDetail 按任务盘点类型区分维度——type=store/goods 接受 stock_ids(传 locations 报 400『当前盘点类型按商品盘点,请传 stock_ids』、传 location_ids 报 400『当前盘点类型按商品盘点,不能添加库位明细』);type=all/location 接受 locations 或 location_ids(传 stock_ids 报 400『当前盘点类型按库位盘点,请传 locations 或 location_ids(如需按商品盘点请创建 type=goods 任务)』)。", + "ID 直查与幂等口径:location_ids 优先于 locations(两者都传时 locations 忽略),按 wms_location_space.id+warehouse_id 直查校验(不再按 space_code 二次解析),查不到的 ID 记入新增返回字段 invalid_location_ids(不报错);幂等按 check_id+location_code(uk_check_location 唯一索引),location_ids 路径跳过项按库位ID记入 skipped;商品行幂等仍按 uk_check_stock。", + "兼容说明:addLocationDetail 保留旧接口名与返回结构 { added, skipped, invalid_location_ids, total_items },薄封装转调 addDetail 库位ID直查路径(stockIds/locations 置空、传 locationIds),返回结构过滤 invalid_locations/invalid_stock_ids;转发前保留旧口径参数校验(任务ID不能为空、库位ID不能为空、单次上限 200)。", + "文档变更范围:methods/system.json 的 module=stock.check 分组更新 stock.check.addDetail(params 新增 location_ids、response 新增 invalid_location_ids、description/errors/notes 同步新口径)并新增 stock.check.addLocationDetail 一条(此前未登记,分组由 18 条增至 19 条);根版本 0.3.222 → 0.3.223、updatedAt 保持 2026-10-01;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),保持库与文件一致;stock.check 分组共 19 条 method 无损。" + ] + }, + { + "version": "2026.10.01-stock-check-unknown-goods", + "date": "2026-10-01", + "type": "updated", + "summary": "盘点作业上报支持未知商品(stock_id 可空 + barcode/item_name,仿收货明细);图片独立维护(上传 businessType=stock_check_record,查询挂载 images,删除清理)", + "methods": [ + "stock.check.report", + "stock.check.result", + "stock.check.recordList", + "stock.check.recordDelete", + "stock.check.export" + ], + "notes": [ + "代码依据:app/service/systems/stock_check.js(report/_resolveStockIdByBarcode/result/_buildDetailAggregations/_formatDetailAggregationRow/_attachRecordImages/recordList/recordDelete/exportStockChecks/_generateAndUploadStockCheckExcel)+ app/service/systemMethods/stock/check.js(report 新增入参 barcode/item_name 透传);未改动任何业务代码之外的逻辑。", + "迁移依据:database/migrations/20261001100000-support-unknown-goods-in-stock-check-record.js(wms_stock_check_record:stock_id 改可空(NULL=未知商品,唯一索引 uk_detail_stock_location 中 NULL 不参与唯一约束)+ 新增 barcode VARCHAR(100) 可空/item_name VARCHAR(255) 可空),本地与生产均已执行。", + "未知商品上报口径:report 新增入参 barcode/item_name;stock_id 与 barcode 至少传一项——仅传 barcode 先按条码匹配系统商品(wms_stock_barcodes 按 barcode+本仓库,关联 StockWarehouse 校验商品属于本仓库),命中回填 stock_id 走已知商品逻辑(商品明细行校验与明细商品一致),未命中记录未知商品(stock_id=NULL+barcode+item_name,item_name 缺省为 barcode);都未传沿用原报错口径;未知商品覆盖式查重 where { detail_id, stock_id:null, barcode, location_code }(应用层查重,唯一索引不约束 NULL 行,并发兜底逻辑对未知商品同样降级更新)。", + "差异口径:未知商品账面 0,实盘=盘盈(差异=实盘-0),必然计入 diff_items;result 行级新增 unknown_items [{ barcode, item_name, checked_quantity }](stock_id 为空的记录按条码归组、条码升序,已计入行级 checked_quantity/diff_quantity/is_diff);finish 未知商品实盘>0 计入盘盈合计与差异行数。", + "图片独立维护口径:上传走通用上传接口(businessType='stock_check_record' + businessId=作业记录ID,建 FileReference,仿收货 receivingItem);result 的 records 与 recordList 的 rows 每条挂载 images [{ id, url }](wms_file_reference 关联 wms_file.file_url,无图片返回空数组);recordDelete 删除记录后清理关联图片引用(失败仅告警不影响主流程);report 不接收图片。", + "查询/导出显示口径:recordList 与 export Sheet2 未知商品(stock_id 为空)item_code 显示扫描条码(barcode)、item_name 显示上报名称快照(item_name 或 barcode 兜底);已知商品维持原口径(明细表/wms_stock_warehouse 商品快照)。", + "文档变更范围:methods/system.json 的 module=stock.check 分组更新 stock.check.report/result/recordList/recordDelete/export 五条(report 新增 params barcode/item_name、response record 补充 barcode/item_name/stock_id 可空;result 新增 response unknown_items 与 records.images;recordList 补充 rows barcode/item_name/images 口径;export 补充 Sheet2 未知商品列口径;recordDelete 补充图片清理说明);根版本 0.3.221 → 0.3.222、updatedAt 保持 2026-10-01;methods/changes/system.json 新增本条(插入数组首位);其余 13 条 method 未改动。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),stock.check 分组共 18 条 method 无损。" + ] + }, + { + "version": "2026.10.01-stock-check-detail-stock-mount", + "date": "2026-10-01", + "type": "updated", + "summary": "stock.check.detail 商品行新增挂载 stock 对象(stockWarehouse.getStockDetails 全局商品信息:条码/图片/管理标识等,带缓存),库位行不挂载", + "methods": [ + "stock.check.detail" + ], + "notes": [ + "代码依据:app/service/systems/stock_check.js#detail(对 scope_type=goods 行按 stock_id 去重后批量调用 ctx.service.systems.stockWarehouse.getStockDetails(goodsStockIds, { warehouseId }),结果按 stock_id 挂载到各行 stock 字段,未命中为 null;库位行不挂载)与 app/service/systems/storage/stock_warehouse.js#getStockDetails(带缓存批量取商品详情,key=cache:stock_detail:{warehouseId}:{stockId},默认 TTL 300 秒);未改动任何业务代码。", + "挂载口径:stock 为 wms_stock_warehouse 全局商品信息,含 id/item_code/item_name/sku_property/quantity 库存数量/locked_quantity 锁定数量/is_batch_mgmt 批次管理/is_shelf_life_mgmt 效期管理/image_url 商品图片/is_images/need_recheck 是否需要复核/store_id 货主ID/packing_requirements 打包要求/pick_requirements 拣货要求/recheck_requirements 复核要求/merge_requirements 要求合并开关/stock_unit 库存单位/barcodes 条码数组;仅 scope_type=goods 商品行挂载(未命中 stock=null),scope_type=location 库位行不挂载;范围行原有 15 字段与其余返回结构不变。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.detail 一条(description/response.rows/notes 补充商品行 stock 挂载口径);根版本 0.3.220 → 0.3.221、updatedAt 保持 2026-10-01;methods/changes/system.json 新增本条(插入数组首位);其余 17 条 method 未改动。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),stock.check 分组共 18 条 method 无损。" + ] + }, + { + "version": "2026.10.01-stock-check-list-store-name", + "date": "2026-10-01", + "type": "updated", + "summary": "stock.check.list 返回行新增 store_name 货主名称(合约货主备注 store_remask 优先、公司全称 company_name 兜底)", + "methods": [ + "stock.check.list" + ], + "notes": [ + "代码依据:app/service/systems/stock_check.js#list(返回前调用 _resolveStoreNameMap() 批量解析货主名称,每行新增 store_name 字段)与 #_resolveStoreNameMap(货主名称解析方法);未改动任何业务代码。", + "解析口径:优先 wms_store_warehouse.store_remask(合约货主备注,按 store_id+warehouse_id 匹配);无合约或备注为空时回退 wms_store.company_name(公司全称);两者均查不到时返回空字符串 ''。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.list 一条(response.rows 描述新增 store_name 货主名称与解析口径,description/notes 同步;params/errors/headers/鉴权不变);根版本 0.3.219 → 0.3.220、updatedAt 保持 2026-10-01;methods/changes/system.json 新增本条(插入数组首位);其余 17 条 method 未改动。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),stock.check 分组共 18 条 method 无损。" + ] + }, + { + "version": "2026.10.01-stock-check-list-filters", + "date": "2026-10-01", + "type": "updated", + "summary": "stock.check.list 查询条件扩展:修复 type 筛选不生效,新增 mode/货主 store_id/创建时间 created_at/盘点开始时间 start_time/盘点结束时间 end_time 筛选(时间支持单值 gte 与 [from,to] 区间)", + "methods": [ + "stock.check.list" + ], + "notes": [ + "代码依据:app/service/systems/stock_check.js#list(新增 type/mode 枚举筛选与 created_at/start_time/end_time 时间筛选,status/store_id/keyword 已有不变)与 app/service/systemMethods/stock/check.js#list(prepareWhereContext 提取 where,支持 {operator,value} 标准结构);未改动任何业务代码。", + "修复点:原方法层 list 未从 where 提取 type(where.type 传入不生效);本次方法层补齐 type/mode/created_at/start_time/end_time 提取(whereValue 优先、data 顶层字段兜底兼容),status/keyword 已有逻辑不变。", + "筛选口径:status/type/mode 单值 eq、数组 in(归一化去重);store_id 数值 eq;keyword 对 check_no/title 模糊匹配;全部筛选叠加仓库隔离(ctx.user.store_id)。", + "时间范围语义:created_at/start_time/end_time 口径一致——单值=gte 从该值起;[from,to] 两端合法=between 闭区间、仅 from=gte、仅 to=lte;非法时间值静默忽略。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.list 一条(params 新增 where.type/where.mode/where.created_at/where.start_time/where.end_time);根版本 0.3.218 → 0.3.219、updatedAt 更新为 2026-10-01;methods/changes/system.json 新增本条(插入数组首位);其余 17 条 method 未改动。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;写入 JSON 后同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),stock.check 分组共 18 条 method 无损。" + ] + }, + { + "version": "2026.09.30-stock-check-time-fields", + "date": "2026-09-30", + "type": "updated", + "summary": "盘点主表移除盘点日期 check_date,改用 start_time(第一个盘点明细写入时间)/end_time(完成盘点时间)表达盘点时间线;导出 Sheet1 移除盘点日期列", + "methods": [ + "stock.check.create", + "stock.check.patternCreate", + "stock.check.report", + "stock.check.finish", + "stock.check.detail", + "stock.check.result", + "stock.check.list", + "stock.check.export" + ], + "notes": [ + "代码依据:app/service/systems/stock_check.js——create/patternCreate 不再写 check_date;_formatCheckRow 不再返回 check_date(保留 start_time/end_time);report 首次写入明细时主表 start_time 为空则补写(盘点开始时间=第一个盘点明细写入的时间);finish 写 end_time(盘点结束时间=完成盘点的时间);_generateAndUploadStockCheckExcel 的 Sheet1 表头已移除「盘点日期」列(保留开始时间/结束时间列)。", + "迁移文件:database/migrations/20260930150000-remove-check-date-from-wms-stock-check.js——移除 wms_stock_check 的 check_date 字段与 idx_warehouse_check_date 联合索引,start_time/end_time 注释对齐新语义(类型不变);本地与生产均已执行。", + "语义口径:盘点时间线由 start_time/end_time 表达——start_time=盘点开始时间(第一个盘点明细写入的时间,report 首次写入明细时补写)、end_time=盘点结束时间(完成盘点的时间,finish 时写入);create/patternCreate 均不传盘点时间。", + "接口兼容性影响:create/patternCreate 响应移除 check_date 字段(主表已无该字段);detail/result/list 返回主表行的字段清单移除 check_date;finish 响应结构不变(不返回 end_time,语义体现在主表回填与 description);export Sheet1 列移除「盘点日期」(保留开始/结束时间列);入参、errors、headers、鉴权(isNeedAuth=false、isNeedLogin=true)均不变;未改动任何业务代码。", + "文档变更范围:methods/system.json 的 module=stock.check 分组更新 8 条(create/patternCreate/report/finish/detail/result/list/export);根版本 0.3.217 → 0.3.218、updatedAt 保持 2026-09-30;methods/changes/system.json 新增本条(插入数组首位);其余 10 条 method 未改动。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),保持库与文件一致;stock.check 分组共 18 条 method 无损。" + ] + }, + { + "version": "2026.09.30-stock-check-create-no-date", + "date": "2026-09-30", + "type": "updated", + "summary": "create 移除 check_date 入参,盘点日期固定为今天(与 patternCreate 口径一致)", + "methods": [ + "stock.check.create" + ], + "notes": [ + "代码依据:app/service/systems/stock_check.js#create——入参解析已无 check_date(仅 warehouseId/title/type/mode/storeId/remark/creatorId/creatorName),checkDateValue = new Date() 后 setHours(0,0,0,0) 固定今天 00:00:00 写入主表 check_date;app/service/systemMethods/stock/check.js#create——data 解构已无 check_date,JSDoc 同步「盘点日期固定为今天,前端不传」;与 patternCreate 口径一致(systems 层 #patternCreate 同样 setHours(0,0,0,0) 固定今天)。", + "规则口径:盘点日期固定为今天 00:00:00,前端不传 check_date(响应中仍返回 check_date 字段);创建后主表 status=created、detail_status=none_checked,其余创建口径(单号生成、范围类型语义、盘点方式规则)均不变。", + "接口兼容性影响:params 移除 check_date(原为必填项,现前端不传;若前端仍传会被方法层忽略,不影响接口可用性与既有调用);errors 400 文案移除「盘点日期不能为空且格式必须合法」;headers/response 结构/鉴权(isNeedAuth=false、isNeedLogin=true)均不变;未改动任何业务代码。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.create 一条(params 移除 check_date、description/notes/errors 同步口径);根版本 0.3.216 → 0.3.217、updatedAt 保持 2026-09-30;methods/changes/system.json 新增本条(插入数组首位);其余 17 条 method 未改动。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),保持库与文件一致;stock.check 分组共 18 条 method 无损。" + ] + }, + { + "version": "2026.09.30-stock-check-location-blind-only", + "date": "2026-09-30", + "type": "updated", + "summary": "create 按库位盘点(all/location)一律盲盘,忽略前端传入的 mode;按商品盘点(store/goods)仍按传入值", + "methods": [ + "stock.check.create" + ], + "notes": [ + "代码依据:app/service/systems/stock_check.js#create——normalizedType 校验通过后,type 为 all/location 时强制 normalizedMode='blind'(忽略前端传入的 mode);type 为 store/goods 时保持传入值(缺省 open);method 层 JSDoc 已同步该口径(按库位盘点一律盲盘)。", + "规则口径:按库位盘点(type=all/location,明细为库位行 scope_type=location)一律盲盘(blind),前端传入的 mode 不生效;按商品盘点(type=store/goods,明细为商品行 scope_type=goods)按传入值,默认明盘(open)。", + "接口兼容性影响:mode 仍为可选字符串参数(open/blind),入参结构、必填项、响应结构、errors、headers、鉴权(isNeedAuth=false、isNeedLogin=true)均不变;仅 all/location 场景服务端强制覆盖 mode 为 blind(前端传 blind 行为不变,传 open 落库值为 blind),对既有调用完全兼容。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.create 一条(mode 参数描述补充规则、notes 补充规则说明);根版本 0.3.215 → 0.3.216、updatedAt 保持 2026-09-30;methods/changes/system.json 新增本条(插入数组首位);未改动任何业务代码。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),保持库与文件一致;stock.check 分组共 18 条 method 无损。" + ] + }, + { + "version": "2026.09.30-stock-check-pattern-fixed-mode", + "date": "2026-09-30", + "type": "updated", + "summary": "patternCreate 移除 mode/check_date 入参:库位类定式一律盲盘、商品类定式一律明盘,盘点日期固定为今天", + "methods": [ + "stock.check.patternCreate" + ], + "notes": [ + "代码依据:app/service/systemMethods/stock/check.js#patternCreate(入参仅 pattern_id/patternId 驼峰别名/title/remark,不再解析 mode/check_date)+ app/service/systems/stock_check.js#patternCreate(normalizedMode=pattern.type==='location'?'blind':'open';checkDateValue=new Date() 后 setHours(0,0,0,0) 固定今天;主表 mode/check_date 直接取服务端固定值)。", + "固定规则:库位类定式(type=location,即 empty_location)一律盲盘(blind)、商品类定式(type=goods,其余 4 个定式)一律明盘(open);盘点日期固定为今天 00:00:00;前端不再传 mode/check_date。", + "接口兼容性影响:params 移除 mode/check_date 两个可选参数(前端若仍传会被忽略,不影响接口可用性与既有调用);errors 400 文案移除「盘点方式不合法,仅支持 open/blind」与「盘点日期格式不合法」;headers/response 结构/鉴权(isNeedAuth=false、isNeedLogin=true)均不变。", + "文档变更范围:methods/system.json 的 stock.check.patternCreate 条目更新(description/params/errors/notes);根版本 0.3.214 → 0.3.215、updatedAt 保持 2026-09-30;methods/changes/system.json 插入本条(数组首位);未改动任何业务代码。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),保持库与文件一致;stock.check 分组共 18 条 method 无损。" + ] + }, + { + "version": "2026.09.30-stock-check-patterns", + "date": "2026-09-30", + "type": "added", + "summary": "新增定式快速创建盘点任务:patternList 拉取 5 个注册定式(空库位/错发/临期/静态/预警),patternCreate 按定式 id 收集对象创建盘点任务并直接进入待审核(submitted);静态盘点写入 wms_stock_static_check_task 并排除已盘商品", + "methods": [ + "stock.check.patternList", + "stock.check.patternCreate" + ], + "notes": [ + "代码依据:app/service/systems/stock_check_patterns.js(STOCK_CHECK_PATTERNS 注册 5 个定式 empty_location/mis_shipment/expiring/static/warning,collectEmptyLocation/collectMisShipment/collectExpiring/collectStatic/collectWarning 五个收集函数)+ app/service/systems/stock_check.js#patternList/#patternCreate(收集对象、创建主表 status=submitted、写明细、static 写 wms_stock_static_check_task)+ app/service/systemMethods/stock/check.js(ALL_METHOD_NAMES 扩为 18 个含 patternList/patternCreate;patternList 在免日志清单 _noNeedLog;warehouseId/创建人从登录上下文注入;统一 _call 捕获业务错误码)。", + "5 个定式口径(与 stock_check_patterns.js 代码注释一致):空库位=启用且未删除、在 wms_storage 不存在 quantity>0 库存的账面空库位(type=location,其余为 goods);错发=登记过错发工单(wms_after_sale type=order+sub_type=mis_shipment,排除 closed/cancelled)关联订单商品按 stock_id 去重;临期=开启保质期管理且最早到期日 <= 当前时间+remaining_threshold_days 天(阈值 <=0 按已到期)的商品;静态=最后一次 INBOUND/OUTBOUND 流水距今超过 stock_static_hours 小时(默认 168,无流水按建档时间)且未进入 wms_stock_static_check_task 的商品;预警=quantity < stock_warning_quantity 的商品(需仓库配置 stock_warning_enabled=true,未开启报 400「未开启库存预警」)。", + "状态口径:patternCreate 创建后主表 status 直接 submitted(进入待审核)、detail_status=none_checked、total_items 按明细重算,无需再调 stock.check.submit;无符合条件对象报 400(location 型报「当前仓库没有账面为空的库位」,goods 型报「没有符合条件的商品」)。", + "静态记录表口径:收集阶段排除 wms_stock_static_check_task 已有记录(未删除)的 stock_id(已进入静态已盘点商品);任务创建成功后把命中 stock_id 批量写入该表(task_time=创建时间),写入失败仅告警不影响主流程。", + "权限口径:两个新 method 均随 ALL_METHOD_NAMES(18 个)免 API 权限(isNeedAuth=false)、免仓库有效期鉴权,必须登录(isNeedLogin=true);patternList 为查询类在免日志清单(_noNeedLog)不记操作日志,patternCreate 为写操作保留操作日志。", + "文档变更范围:methods/system.json 的 module=stock.check 分组新增 stock.check.patternList/patternCreate 两条(追加在 exportTaskProgress 之后,与代码 ALL_METHOD_NAMES 顺序一致);根版本 0.3.213 → 0.3.214、updatedAt 保持 2026-09-30;methods/changes/system.json 新增本条(插入数组首位);未改动任何业务代码。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),保持库与文件一致;stock.check 分组共 18 条 method 无损。" + ] + }, + { + "version": "2026.09.30-stock-check-operation-log", + "date": "2026-09-30", + "type": "updated", + "summary": "库存盘点 10 个写操作补齐业务操作日志:成功路径写入 wms_operation_log(businessType=stock_check,operationCode STOCK_CHECK_*),失败不写、日志异常不影响主流程", + "methods": [ + "stock.check.create", + "stock.check.addDetail", + "stock.check.detailDelete", + "stock.check.report", + "stock.check.recordDelete", + "stock.check.finish", + "stock.check.submit", + "stock.check.cancel", + "stock.check.audit", + "stock.check.batchDelete" + ], + "notes": [ + "代码依据:app/service/systems/stock_check.js 的 10 个写操作(create/addDetail/detailDelete/report/recordDelete/finish/submit/cancel/audit/batchDelete)在主流程写入成功后调用 ctx.service.systems.operationLog.createOperationLog 写入 wms_operation_log(businessType=stock_check);operationCode 前缀 STOCK_CHECK_*,对应 CREATE/ADD_DETAIL/DELETE_DETAIL/REPORT/DELETE_RECORD/FINISH/SUBMIT/CANCEL/AUDIT/BATCH_DELETE;operationAction 对应 CREATE/UPDATE/UPDATE/UPDATE/UPDATE/UPDATE/UPDATE/UPDATE/UPDATE/DELETE。", + "日志口径:businessId=盘点任务 id(create 取新建记录 plainRecord.id,其余取 checkId);operator 取登录上下文 ctx.user(id=employees_id 回退 user.id,name=employees_name);extras 统一携带 warehouseId、checkNo(create 用 plainRecord.check_no)与 message,report/finish/audit/batchDelete 等另带业务关键字段(明细/库位/实盘数量、差异/盘盈/盘亏、审核动作与原因、deletedIds/skippedIds 等);changeSummary 为中文变更描述。", + "batchDelete 特殊口径:仅删除集非空(deletedIds.length>0)时写日志(全跳过不写);businessId 取首个删除 id(deletedIds[0]);extras 附 deletedIds/skippedIds/deletedCount/skippedCount;日志在事务提交后写入,不随事务回滚残留。", + "失败不写与降级:10 个日志调用点全部位于主流程成功路径之后(各写操作失败时先抛业务错误码 400,不会执行到日志写入);createOperationLog 内部 try/catch,日志写入失败仅记录 error 日志并返回 null,不影响主流程(业务已提交的变更不受日志失败影响)。", + "接口契约不变:本次仅服务层行为变更(补充业务操作日志),10 个 method 的入参/响应/错误码/鉴权均未变化,methods/system.json 接口条目与根版本号均不修改(不 bump);本条仅追加到 methods/changes/system.json 数组首位;changes 不入库表,无需回填 wms_api_method_doc。" + ] + }, + { + "version": "2026.09.30-stock-check-doc-polish", + "date": "2026-09-30", + "type": "updated", + "summary": "盘点接口文档文案修正:detail 字段计数 14→15、result 权限注释方法数 15→16、recordList/detailDelete 免日志清单补 result、export errors 补「未找到可导出的盘点任务」400", + "methods": [ + "stock.check.detail", + "stock.check.result", + "stock.check.recordList", + "stock.check.detailDelete", + "stock.check.export" + ], + "notes": [ + "修正点明细:① stock.check.detail 的 description/response/notes 中「纯范围行 14 字段」改为「15 字段」(_formatDetailScopeRow 实际枚举 id/check_id/warehouse_id/scope_type/stock_id/location_id/location_code/item_code/item_name/spec/batch_no/system_quantity/remark/created_at/updated_at 共 15 个,枚举清单原本完整,仅计数文案错误);② stock.check.result notes 首条「随 ALL_METHOD_NAMES(15 个)免 API 权限」改为「16 个」;③ stock.check.recordList 与 stock.check.detailDelete 的免日志清单枚举补 result;④ stock.check.export errors 补 400「未找到可导出的盘点任务」。", + "代码依据:app/service/systemMethods/stock/check.js(ALL_METHOD_NAMES 共 16 个:create/list/addDetail/detailDelete/detail/result/report/recordList/recordDelete/finish/submit/cancel/audit/batchDelete/export/exportTaskProgress;_noNeedLog='list,detail,result,recordList,export,exportTaskProgress';export 超 50 上限校验)+ app/service/systems/stock_check.js#_formatDetailScopeRow(15 字段返回对象)与 #exportStockChecks(checks.length===0 时抛「未找到可导出的盘点任务」400)。", + "文档变更范围:methods/system.json 的 module=stock.check 分组更新 stock.check.detail/result/recordList/detailDelete/export 五条;根版本 0.3.212 → 0.3.213、updatedAt 保持 2026-09-30;methods/changes/system.json 新增本条(插入数组首位);仅文档文案与错误码清单修正,未改动任何业务代码。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),保持库与文件一致。" + ] + }, + { + "version": "2026.09.30-wavePickTaskDetail-pick-requirements", + "date": "2026-09-30", + "type": "updated", + "summary": "pick.wavePickTaskDetail 的 picking_view.items 新增 pick_requirements(拣货要求),团购形态(pick_mode=1/5)不返回 picking_details,前端改由 items 展示拣货要求", + "methods": [ + "pick.wavePickTaskDetail" + ], + "notes": [ + "代码依据:app/service/systems/pick.js#buildPickingView——items 聚合行新增 pick_requirements,取值自商品资料链路(getStockDetails)的 stock.pick_requirements(merge_requirements=Y 时已按打包要求回退),空值兜底为空字符串。", + "背景:团购小波次/大波次(pick_mode=1/5)不返回 picking_details,此前 picking_view.items 缺拣货要求字段,前端无法展示拣货要求。", + "picking_view.items 其余字段不变;picking_details 的 stock 对象本就含该字段,本次仅补齐 items 层。", + "文档变更范围:methods/system.json 的 pick.wavePickTaskDetail 响应 picking_view.items 新增 pick_requirements 字段描述;根版本 0.3.211 → 0.3.212、updatedAt 保持 2026-09-30;methods/changes/system.json 新增本条(插入数组首位)。" + ] + }, + { + "version": "2026.09.30-stock-check-batch-delete", + "date": "2026-09-30", + "type": "added", + "summary": "新增 stock.check.batchDelete:批量删除盘点任务(入参 ids,上限 200),仅作废(cancelled)任务删除,非作废任务跳过;级联删除作业记录与明细(事务)", + "methods": [ + "stock.check.batchDelete" + ], + "notes": [ + "代码依据:app/service/systems/stock_check.js#batchDelete(入参归一化 _normalizeIdList:单值兼容、去重、正整数过滤、上限 200;仓库隔离查询主表 id in ids + warehouse_id;状态分流与级联删除事务)+ app/service/systemMethods/stock/check.js#batchDelete(ALL_METHOD_NAMES 扩为 16 个含 batchDelete;warehouseId 从登录上下文注入;走统一 _call 捕获业务错误码)。", + "状态分流口径:仅 status=cancelled(作废)任务执行删除;其他状态及仓库内查不到的任务跳过(计入 skipped_ids,保持入参顺序),不报错。", + "级联删除顺序(事务内):先删作业记录(wms_stock_check_record where check_id in 删除集),再删明细(wms_stock_check_detail where check_id in 删除集),最后删主表(wms_stock_check where id in 删除集)。", + "权限口径:batchDelete 随 ALL_METHOD_NAMES(16 个)免 API 权限(isNeedAuth=false)、免仓库有效期鉴权(免鉴权清单)、必须登录(isNeedLogin=true);为写操作,不在免日志清单 _noNeedLog,保留操作日志。", + "文档变更范围:methods/system.json 的 module=stock.check 分组新增 stock.check.batchDelete(插入 audit 之后,与代码 ALL_METHOD_NAMES 顺序一致);根版本 0.3.210 → 0.3.211、updatedAt 保持 2026-09-30;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),保持库与文件一致。" + ] + }, + { + "version": "2026.09.30-wavePickTaskDetail-pick-mode-enum", + "date": "2026-09-30", + "type": "updated", + "summary": "pick.wavePickTaskDetail 响应 task.pick_mode 描述补全枚举:1-团购小波次 2-散单单品单件 3-散单先拣后分 4-边拣边分 5-团购大波次", + "methods": [ + "pick.wavePickTaskDetail" + ], + "notes": [ + "原描述仅「拣货模式」,缺少 pick_mode=5 为大团购(团购大波次)的枚举说明;现与 pick.query、order.recheckOrder 等接口的 pick_mode 描述对齐。", + "仅更新 methods/system.json 的 pick.wavePickTaskDetail 响应字段描述,不修改任何业务实现。" + ] + }, + { + "version": "2026.09.30-stock-check-export-records", + "date": "2026-09-30", + "type": "updated", + "summary": "盘点导出口径调整:Sheet2 导出盘点明细(作业记录:一行一条实际盘点记录,含商品/库位/实盘数量/盘点人/时间),不再导出任务明细(未盘范围行)", + "methods": [ + "stock.check.export" + ], + "notes": [ + "代码依据:app/service/systems/stock_check.js#exportStockChecks/_generateAndUploadStockCheckExcel——Sheet2 直接拉 wms_stock_check_record 作业记录(不按任务范围行展开,任务明细与未盘范围行不导出),商品快照(item_code/item_name)从 wms_stock_warehouse 补齐,totalCount=作业记录总数;app/service/systemMethods/stock/check.js#export 异步任务入口与 Redis 进度缓存机制不变。", + "口径变化:Sheet2「盘点明细」由「按任务范围行展开(含未盘空行,账面按 wms_storage 现算)」改为「一行一条实际盘点记录(作业记录)」——列:盘点单号/商品编码/商品名称/库位编码(空库位输出为空)/实盘数量/盘点人/盘点时间;未盘的任务范围行不再导出;进度 totalCount=作业记录总数(导出前即确定),进度按已写明细行数/总数计算。", + "Sheet1 不变说明:Sheet1「盘点单」保持一行一个盘点任务(盘点单号/盘点名称/盘点范围/盘点方式/盘点状态/盘点进度/盘点日期/货主ID/创建人/明细行数/已盘行数/差异行数/开始时间/结束时间/备注)。", + "文档变更范围:methods/system.json 的 stock.check.export 更新 description/response(total_count/current_count 口径)/notes;根版本 0.3.208 → 0.3.209、updatedAt 保持 2026-09-30;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),保持库与文件一致。" + ] + }, + { + "version": "2026.09.30-stock-check-detail-result-split", + "date": "2026-09-30", + "type": "updated", + "summary": "任务明细与盘点结果接口拆分:detail 只返回任务范围行(商品/库位),新增 result 返回盘点结果聚合(商品行 checked/diff/records/locations,库位行 stocks 按商品聚合账面查 wms_storage)", + "methods": [ + "stock.check.detail", + "stock.check.result" + ], + "notes": [ + "代码依据:app/service/systemMethods/stock/check.js(ALL_METHOD_NAMES 扩为 15 个含 result;新增 result() 从登录上下文注入 warehouseId、入参 id、走统一 _call 捕获业务错误码;_noNeedLog 扩为 list/detail/result/recordList/export/exportTaskProgress)+ app/service/systems/stock_check.js(detail() 改为只返回纯范围行(_formatDetailScopeRow 14 字段,不再调 _buildDetailAggregations);新增 result() 查询全部明细与作业记录后调 _buildDetailAggregations/_formatDetailAggregationRow 聚合)。", + "拆分口径:detail 只返回任务范围行(商品/库位原始字段 14 个,不含任何盘点作业聚合);新增 result 返回盘点结果聚合——商品行 checked_quantity/diff_quantity/is_diff/status/location_codes/checkers/last_checked_at + records + locations,库位行 checked_quantity(行级合计)/diff_quantity(差异代数和)+ records/locations + stocks(按商品聚合,账面查 wms_storage)。", + "接口兼容性影响:旧 detail 的商品行聚合字段(checked_quantity/diff_quantity/is_diff/status/location_codes/checkers/last_checked_at)、records、locations 与库位行 stocks 全部迁移到新接口 result;detail 仅用于任务范围行展示,需要盘点结果的调用方改调 stock.check.result(入参同为 id,返回同为 { check, rows, total })。", + "权限口径:result 随 ALL_METHOD_NAMES(15 个)免 API 权限(isNeedAuth=false)、免仓库有效期鉴权(免鉴权清单)、必须登录(isNeedLogin=true);为查询类方法,加入免日志清单 _noNeedLog。", + "文档变更范围:methods/system.json 的 module=stock.check 分组新增 stock.check.result(放在 detail 之后,与代码 ALL_METHOD_NAMES 顺序一致)、更新 stock.check.detail 的 description/response/notes(纯范围行 14 字段,移除聚合字段描述);根版本 0.3.207 → 0.3.208、updatedAt 保持 2026-09-30;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta);本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),保持库与文件一致。" + ] + }, + { + "version": "2026.09.30-stock-check-add-detail-compat", + "date": "2026-09-30", + "type": "updated", + "summary": "addDetail 兼容历史任务:type=all 且已存在商品明细行(改造前创建)时继续按商品模式接受 stock_ids,避免旧调用 400;全新 type=all 任务维持按库位语义", + "methods": [ + "stock.check.addDetail" + ], + "notes": [ + "代码依据:app/service/systems/stock_check.js#addDetail——type=all 且 wms_stock_check_detail 已存在 scope_type='goods' 明细行(count>0)时置 isGoodsScope=true/isLocationScope=false,继续按商品模式接受 stock_ids;全新 type=all 任务维持按库位语义;入参维度互斥校验的库位错误文案更新为『当前盘点类型按库位盘点,请传 locations(如需按商品盘点请创建 type=goods 任务)』。", + "兼容判定口径:以 wms_stock_check_detail 中 check_id 对应 scope_type='goods' 行是否存在为准(改造前 type=all 任务按商品添加明细,明细行 scope_type='goods');仅 type=all 任务走兼容判定,store/goods/location 类型判定逻辑不变。", + "新任务语义保持:全新 type=all 任务(无任何商品明细行)维持按库位盘点语义——传 stock_ids 报 400『当前盘点类型按库位盘点,请传 locations(如需按商品盘点请创建 type=goods 任务)』;历史任务(按商品模式)传 locations 报 400『当前盘点类型按商品盘点,请传 stock_ids』。", + "文档变更范围:methods/system.json 的 stock.check.addDetail 更新 description/errors/notes(历史任务兼容口径 + 库位错误码文案);根版本 0.3.206 → 0.3.207、updatedAt 保持 2026-09-30;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),保持库与文件一致。" + ] + }, + { + "version": "2026.09.30-stock-check-location-scope", + "date": "2026-09-30", + "type": "updated", + "summary": "盘点明细支持商品/库位两种范围行:all/location 按库位盘点、store/goods 按商品盘点;添加商品限制非本货主商品;库位行作业上报指定商品,账面来源 wms_storage", + "methods": [ + "stock.check.create", + "stock.check.addDetail", + "stock.check.report", + "stock.check.detail", + "stock.check.finish", + "stock.check.export" + ], + "notes": [ + "代码依据:app/service/systems/stock_check.js(create/addDetail/_addGoodsDetailRows/_addLocationDetailRows/detail/_buildDetailAggregations/report/finish/exportStockChecks)+ app/service/systemMethods/stock/check.js(入参透传与 locations/location_codes、stock_id 兼容)+ app/model/stock_check_detail.js / app/model/stock_check_record.js(模型与索引定义)。", + "迁移文件:database/migrations/20260930110000-support-location-scope-in-stock-check-detail.js(本地+生产已执行)——明细表新增 scope_type/location_id/location_code、stock_id/item_code 改可空、防御性合并重复明细并新增唯一索引 uk_check_stock(check_id, stock_id) 与 uk_check_location(check_id, location_code);记录表移除 uk_detail_location(detail_id, location_code)、防御性合并重复记录并新增 uk_detail_stock_location(detail_id, stock_id, location_code)(覆盖式语义升级为同明细+同商品+同库位)。", + "语义变化明细:①create.type 语义明确——all=按库位盘点(未传库位自动全仓库启用库位生成范围)/ location=按库位盘点 / store=按货主按商品盘点 / goods=按商品盘点;②addDetail 新增 locations 入参(兼容 location_codes),按任务 type 与 stock_ids 二选一,响应新增 invalid_locations,商品货主必须与任务 store_id 一致否则计入 invalid_stock_ids;③report 新增可选 stock_id 入参(库位行必填且商品须本仓库),覆盖式查重升级为 detail_id+stock_id+location_code;④detail 库位行输出 scope_type='location' + stocks 数组(按商品聚合,账面查 wms_storage);⑤finish 库位行账面来源 wms_storage(space_id+stock_id SUM(quantity));⑥export Sheet2 按盘点项展开(goods 1 行、location 按商品 N 行)。", + "接口兼容性影响:向后兼容——create.type 枚举不变(all/store/goods/location);addDetail 原 stock_ids 入参与响应字段保留(新增 invalid_locations,非法商品仍走 invalid_stock_ids);report 原入参不变(stock_id 为新增可选参数,商品行不传保持原行为);detail 商品行响应结构不变(库位行为新输出形态);finish/export 响应结构不变。", + "文档变更范围:methods/system.json 的 module=stock.check 分组更新 stock.check.create/addDetail/report/detail/finish/export 六条 description/params/response/errors;根版本 0.3.205 → 0.3.206、updatedAt 保持 2026-09-30;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),保持库与文件一致。" + ] + }, { "version": "2026.09.30-manual-waybill-express-code", "date": "2026-09-30", diff --git a/methods/system.json b/methods/system.json index 2a78687..101d98b 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,14 +1,14 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.205", - "updatedAt": "2026-09-30", + "version": "0.3.227", + "updatedAt": "2026-10-02", "headers": [ { "name": "platform", "type": "string", "required": true, - "description": "客户端平台标识,如 web/pda/app", + "description": "客户端平台标识,如 web/pda/app/miniprogram", "list": [ { "value": "web", @@ -23,13 +23,9 @@ "name": "APP端" }, { - "value": "wx", + "value": "miniprogram", "name": "微信端" }, - { - "value": "miniProgram", - "name": "小程序端" - }, { "value": "other", "name": "其他" @@ -21459,6 +21455,12 @@ "description": "该库位该商品的总需拣货数量", "required": false }, + { + "name": "pick_requirements", + "type": "string", + "description": "拣货要求(商品资料维护;merge_requirements=Y 时回退为打包要求),团购形态(pick_mode=1/5)不返回 picking_details,前端以此字段展示拣货要求", + "required": false + }, { "name": "box_allocations", "type": "array", @@ -37784,7 +37786,7 @@ "list": [ { "method": "stock.check.create", - "description": "创建盘点任务(空任务):生成盘点单号(PD+YYYYMMDD+6位序号,序号全局递增(不按仓库隔离),并发下撞 uk_check_no 唯一键自动重取重试(最多 5 次),口径与收货单 receiving_number 一致),初始状态 created、明细进度 none_checked;warehouse_id 由服务端从当前登录上下文(ctx.user.store_id)自动注入,前端无需传递。", + "description": "创建盘点任务(空任务):生成盘点单号(PD+YYYYMMDD+6位序号,序号全局递增(不按仓库隔离),并发下撞 uk_check_no 唯一键自动重取重试(最多 5 次),口径与收货单 receiving_number 一致),初始状态 created、明细进度 none_checked;warehouse_id 由服务端从当前登录上下文(ctx.user.store_id)自动注入,前端无需传递。盘点范围类型语义:all=按库位盘点(添加明细时未传库位自动拉取全仓库启用库位生成范围)/ location=按库位盘点 / store=按货主按商品盘点(必须指定货主)/ goods=按商品盘点;type=all/location 时明细为库位行(scope_type=location),type=store/goods 时明细为商品行(scope_type=goods)。盘点时间不传(主表已无 check_date):start_time=盘点开始时间(第一个盘点明细写入的时间,report 首次写入明细时补写)、end_time=盘点结束时间(完成盘点的时间,finish 时写入),与 patternCreate 口径一致。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -37808,28 +37810,21 @@ "type": "string", "required": false, "source": "body", - "description": "盘点范围类型,缺省 all:all=全盘 / store=按货主 / goods=按商品 / location=按库位" + "description": "盘点范围类型,缺省 all:all=按库位盘点(未传库位时自动全仓库启用库位生成盘点范围)/ location=按库位盘点 / store=按货主按商品盘点 / goods=按商品盘点;all/location 走库位明细行(scope_type=location),store/goods 走商品明细行(scope_type=goods)" }, { "name": "mode", "type": "string", "required": false, "source": "body", - "description": "盘点方式,缺省 open:open=明盘(可见账面数量)/ blind=盲盘(不可见账面数量)" + "description": "盘点方式,缺省 open:open=明盘(可见账面数量)/ blind=盲盘(不可见账面数量);按库位盘点(all/location)一律盲盘,忽略前端传入;按商品盘点(store/goods)按传入值(默认明盘)" }, { "name": "store_id", "type": "number", "required": false, "source": "body", - "description": "货主ID(type=store 按货主盘点时必填)" - }, - { - "name": "check_date", - "type": "string", - "required": true, - "source": "body", - "description": "盘点日期(必填,格式必须可被 Date 解析)" + "description": "货主ID(type=store 按货主按商品盘点时必填;添加商品明细时商品货主必须与该货主一致)" }, { "name": "remark", @@ -37888,23 +37883,17 @@ "required": true, "description": "明细盘点进度:none_checked/partial_checked/all_checked(新建为 none_checked)" }, - { - "name": "check_date", - "type": "string", - "required": false, - "description": "盘点日期" - }, { "name": "start_time", "type": "string", "required": false, - "description": "实际开始时间(开始盘点作业后回填)" + "description": "盘点开始时间(第一个盘点明细写入的时间,创建时为空)" }, { "name": "end_time", "type": "string", "required": false, - "description": "实际结束时间(完成盘点后回填)" + "description": "盘点结束时间(完成盘点的时间,创建时为空)" }, { "name": "creator_id", @@ -37958,7 +37947,7 @@ "errors": [ { "code": 400, - "message": "无法获取当前仓库上下文 / 盘点范围类型不合法 / 盘点方式不合法 / 按货主盘点时必须指定货主 / 盘点日期不能为空且格式必须合法" + "message": "无法获取当前仓库上下文 / 盘点范围类型不合法(仅支持 all/store/goods/location)/ 盘点方式不合法(仅支持 open/blind)/ 按货主盘点时必须指定货主" }, { "code": 500, @@ -37970,13 +37959,16 @@ "原因说明:uk_check_no 为全局唯一索引(不区分仓库),原按仓库隔离序号各自从 1 起会跨仓撞号;改为全局递增后并发创建仍有极小概率撞号,由唯一键重试兜底。", "收货单参照口径:与收货单 receiving_number 一致——按全局最大序号 +1 生成 + 撞唯一键自动重取重试。", "并发重试说明:每次重试都重新调用 generateCheckNo() 取最新全局最大序号;仅 ER_DUP_ENTRY 且命中 uk_check_no 的错误才重试,其它错误不重试直接抛出。", - "文档变更范围:methods/system.json 的 module=stock.check 分组更新 stock.check.create 的 description 与 notes;根版本 0.3.203 → 0.3.204、updatedAt 保持 2026-09-29;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。", - "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta);本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),保持库与文件一致。" + "范围类型语义:type=all/location 为按库位盘点(明细为库位行 scope_type=location,all 未传库位时自动全仓库启用库位生成范围);type=store/goods 为按商品盘点(明细为商品行 scope_type=goods,store 必须指定货主)。", + "文档变更范围:methods/system.json 的 module=stock.check 分组更新 stock.check.create/addDetail/report/detail/finish/export 六条(范围类型语义与库位行支持);根版本 0.3.205 → 0.3.206、updatedAt 保持 2026-09-30;methods/changes/system.json 新增本条(插入数组首位);其余 method 未改动。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta);本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),保持库与文件一致。", + "盘点方式规则:按库位盘点(type=all/location,明细为库位行)一律盲盘(blind),忽略前端传入的 mode;按商品盘点(type=store/goods,明细为商品行)按传入值,默认明盘(open)。代码依据:app/service/systems/stock_check.js#create 在 mode 合法性校验(仅支持 open/blind)通过后、写库前,normalizedType 为 all/location 时强制 normalizedMode='blind'。", + "盘点时间口径(主表无 check_date):create 不写盘点时间(入参与主表均无 check_date,迁移 20260930150000-remove-check-date-from-wms-stock-check.js 已移除字段与索引);start_time=盘点开始时间(第一个盘点明细写入的时间,report 首次写入明细时补写)、end_time=盘点结束时间(完成盘点的时间,finish 时写入);_formatCheckRow 不再返回 check_date(仅返回 start_time/end_time);代码依据:app/service/systems/stock_check.js#create(不再写 check_date)、#report(start_time 为空补写)、#finish(写 end_time)、#_formatCheckRow(仅返回 start_time/end_time)。" ] }, { "method": "stock.check.list", - "description": "拉取盘点任务列表:按当前用户仓库(ctx.user.store_id)限定数据范围,支持 status 状态筛选(单值或数组)、store_id 货主筛选、keyword 关键字(盘点单号/标题模糊)与分页。", + "description": "拉取盘点任务列表:按当前用户仓库(ctx.user.store_id)限定数据范围,支持 status 状态筛选(单值或数组)、type 范围类型筛选(单值或数组)、mode 盘点方式筛选(单值或数组)、store_id 货主筛选、created_at 创建时间筛选、start_time 盘点开始时间筛选、end_time 盘点结束时间筛选(时间条件:单值=该字段 >= 该值,数组 [from,to]=between 区间)、keyword 关键字(盘点单号/标题模糊)与分页。 每行返回新增 store_name 货主名称(优先合约货主备注 store_remask、兜底公司全称 company_name,详见 response.rows)。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -38000,7 +37992,21 @@ "type": "string", "required": false, "source": "body", - "description": "状态筛选(单值或数组):created/submitted/rejected/approved/checking/completed/cancelled" + "description": "状态筛选(单值或数组,自动去重):created/submitted/rejected/approved/checking/completed/cancelled" + }, + { + "name": "where.type", + "type": "string", + "required": false, + "source": "body", + "description": "盘点范围类型筛选(单值或数组,自动去重):all=按库位盘点 / location=按库位盘点 / store=按货主按商品盘点 / goods=按商品盘点" + }, + { + "name": "where.mode", + "type": "string", + "required": false, + "source": "body", + "description": "盘点方式筛选(单值或数组,自动去重):open=明盘(可见账面数量)/ blind=盲盘(不可见账面数量)" }, { "name": "where.store_id", @@ -38009,6 +38015,27 @@ "source": "body", "description": "货主筛选" }, + { + "name": "where.created_at", + "type": "string", + "required": false, + "source": "body", + "description": "创建时间筛选:单值=created_at >= 该值(从该值起);数组 [from,to]=between 闭区间(from <= created_at <= to,仅传 from=gte、仅传 to=lte);非法时间值静默忽略(不加入筛选条件)" + }, + { + "name": "where.start_time", + "type": "string", + "required": false, + "source": "body", + "description": "盘点开始时间筛选(start_time,第一个盘点明细写入的时间),口径同 created_at:单值=start_time >= 该值(从该值起);数组 [from,to]=between 闭区间;非法时间值静默忽略" + }, + { + "name": "where.end_time", + "type": "string", + "required": false, + "source": "body", + "description": "盘点结束时间筛选(end_time,完成盘点的时间),口径同 created_at:单值=end_time >= 该值(从该值起);数组 [from,to]=between 闭区间;非法时间值静默忽略" + }, { "name": "where.keyword", "type": "string", @@ -38022,7 +38049,7 @@ "name": "rows", "type": "array", "required": true, - "description": "盘点任务行列表(主表全字段,含 check_no/title/type/mode/store_id/status/detail_status/check_date/start_time/end_time/creator_id/creator_name/total_items/checked_items/diff_items/remark/created_at/updated_at)" + "description": "盘点任务行列表(主表全字段,含 check_no/title/type/mode/store_id/status/detail_status/start_time/end_time/creator_id/creator_name/total_items/checked_items/diff_items/remark/created_at/updated_at,每行新增 store_name 货主名称;start_time=盘点开始时间(第一个盘点明细写入的时间)、end_time=盘点结束时间(完成盘点的时间));store_name=货主名称:优先 wms_store_warehouse.store_remask(合约货主备注,按 store_id+warehouse_id 匹配);无合约或备注为空时回退 wms_store.company_name(公司全称);两者均查不到返回空字符串" }, { "name": "total", @@ -38048,11 +38075,20 @@ "code": 500, "message": "服务器内部错误" } + ], + "notes": [ + "store_name 代码依据:app/service/systems/stock_check.js#list 返回 rows 前调用 _resolveStoreNameMap()(按 store_id+warehouse_id 查 wms_store_warehouse.store_remask,无合约或备注为空回退 wms_store.company_name),每行新增 store_name 货主名称,查不到返回空字符串;未改动任何业务逻辑。", + "代码依据:app/service/systems/stock_check.js#list——新增 type/mode 枚举筛选(_normalizeEnumValues 归一化 trim 去重,单值 eq、多值 Op.in)、store_id 数值 eq、created_at/start_time/end_time 时间筛选(_buildTimeRangeCondition:数组 [from,to] 两端合法=Op.between、仅 from=Op.gte、仅 to=Op.lte,单值=Op.gte,非法时间值返回 null 静默忽略);app/service/systemMethods/stock/check.js#list——经 prepareWhereContext 提取 where(支持 {operator,value} 标准结构,between 对象值归一为 [from,to])后传给 systems 层,并保留 data 顶层字段兜底(whereValue 优先、data 顶层兼容)。", + "修复点:原方法层 list 未从 where 提取 type(方法层解构仅有 status/store_id/keyword,where.type 传入不生效);本次方法层补齐 type/mode/created_at/start_time/end_time 提取,status/keyword 已有逻辑不变。", + "筛选口径:status/type/mode 支持单值 eq 或数组 in(归一化 trim 后自动去重,空值忽略);store_id 经 Number 归一化后 eq;keyword 对盘点单号 check_no 与标题 title 做 OR 模糊匹配;所有筛选均叠加在 warehouse_id(ctx.user.store_id 仓库隔离)之上。", + "时间范围语义:created_at/start_time/end_time 三列口径一致——单值=该字段 >= 该值(从该值起);数组 [from,to] 两端都合法=between 闭区间,仅 from 合法=gte、仅 to 合法=lte;空值/无法解析的日期静默忽略(不加入 where 条件)。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库与生产库(import 当前 system.json → export 回写往返校验),保持库与文件一致;stock.check 分组共 18 条 method 无损。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.list 一条(response.rows 描述新增 store_name 货主名称与解析口径,description/notes 同步;params/errors/headers/鉴权不变);根版本 0.3.219 → 0.3.220、updatedAt 保持 2026-10-01;methods/changes/system.json 新增本条(插入数组首位);其余 17 条 method 未改动。" ] }, { "method": "stock.check.addDetail", - "description": "添加盘点明细:按 stock_ids 查询 wms_stock_warehouse 生成明细快照行(商品编码/名称/规格/账面数量等);仅 created/rejected 状态允许;已存在同 stock_id 的明细自动跳过(幂等),完成后重算主表 total_items。", + "description": "添加盘点明细(商品或库位,按任务盘点类型决定):type=store/goods 按 stock_ids 添加商品行(scope_type=goods,从 wms_stock_warehouse 生成商品快照:编码/名称/规格/账面数量),商品必须属于本仓库,且任务 store_id 非空时商品货主必须与任务货主一致(不一致的商品记入 invalid_stock_ids);type=all/location 按 locations(库位编码)或 location_ids(库位ID)添加库位行(scope_type=location),location_ids 优先(两者都传时 locations 忽略)——库位ID路径直接按 wms_location_space.id+warehouse_id 查库校验(不再按编码二次解析),查不到的 ID 记入 invalid_location_ids,编码路径按 warehouse_id+space_code 匹配 wms_location_space,不存在的编码记入 invalid_locations;type=all 未传库位且未传库位ID时自动拉取全仓库启用库位生成盘点范围;兼容历史任务:type=all 且已存在商品明细行(scope_type=goods,改造前创建)时继续按商品模式接受 stock_ids,避免旧调用报 400;stock_ids 与 locations/location_ids 按任务类型二选一(传错维度报 400:按库位盘点传 stock_ids 报『当前盘点类型按库位盘点,请传 locations 或 location_ids(如需按商品盘点请创建 type=goods 任务)』,按商品盘点传 locations 报『当前盘点类型按商品盘点,请传 stock_ids』、传 location_ids 报『当前盘点类型按商品盘点,不能添加库位明细』),locations 兼容 location_codes 写法(locations 优先)、location_ids 兼容 locationIds 驼峰写法(location_ids 优先);仅 created/rejected 状态允许;已存在同盘点项(商品行 stock_id / 库位行 location_code)自动跳过(幂等);完成后重算主表 total_items。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -38074,9 +38110,30 @@ { "name": "stock_ids", "type": "array", - "required": true, + "required": false, "source": "body", - "description": "商品库存ID列表(wms_stock_warehouse.id)" + "description": "商品库存ID列表(wms_stock_warehouse.id);type=store/goods 按商品盘点时使用,与 locations/location_ids 按任务类型二选一" + }, + { + "name": "locations", + "type": "array", + "required": false, + "source": "body", + "description": "库位编码列表(wms_location_space.space_code);type=all/location 按库位盘点时使用,与 stock_ids 按任务类型二选一;与 location_ids 同时传入时被忽略(location_ids 优先);type=all 未传库位且未传 location_ids 时自动拉取全仓库启用库位生成盘点范围" + }, + { + "name": "location_codes", + "type": "array", + "required": false, + "source": "body", + "description": "库位编码列表(兼容别名;locations 优先,两者都传时以 locations 为准)" + }, + { + "name": "location_ids", + "type": "array", + "required": false, + "source": "body", + "description": "库位ID列表(wms_location_space.id);type=all/location 按库位盘点时使用,直接按 id+warehouse_id 查库校验(不再按编码二次解析),查不到的 ID 记入 invalid_location_ids(不报错);与 locations 同时传入时 location_ids 优先、locations 忽略;兼容 locationIds 驼峰写法(location_ids 优先)" } ], "response": [ @@ -38090,13 +38147,25 @@ "name": "skipped", "type": "number", "required": true, - "description": "已存在被跳过(幂等)的 stock_id 数" + "description": "已存在被跳过(幂等)的盘点项数" }, { "name": "invalid_stock_ids", "type": "array", "required": true, - "description": "无效商品库存ID列表(不存在或不属于当前仓库)" + "description": "无效商品库存ID列表(不存在、不属于当前仓库或商品货主与任务货主不一致)" + }, + { + "name": "invalid_locations", + "type": "array", + "required": true, + "description": "无效库位编码列表(当前仓库不存在对应库位编码)" + }, + { + "name": "invalid_location_ids", + "type": "array", + "required": true, + "description": "无效库位ID列表(按 wms_location_space.id 直查当前仓库不存在)" }, { "name": "total_items", @@ -38108,17 +38177,25 @@ "errors": [ { "code": 400, - "message": "盘点任务ID不能为空 / 盘点任务不存在 / 当前状态(非 created/rejected)不允许添加明细 / 请至少选择一个商品" + "message": "盘点任务ID不能为空 / 盘点任务不存在 / 当前状态(非 created/rejected)不允许添加明细 / 请至少选择一个商品 / 当前盘点类型按商品盘点,请传 stock_ids / 当前盘点类型按商品盘点,不能添加库位明细 / 当前盘点类型按库位盘点,请传 locations 或 location_ids(如需按商品盘点请创建 type=goods 任务) / 请至少选择一个库位 / 当前仓库没有启用库位,无法按全盘自动生成盘点范围" }, { "code": 500, "message": "服务器内部错误" } + ], + "notes": [ + "按类型二选一:type=store/goods 传 stock_ids(传 locations 报『当前盘点类型按商品盘点,请传 stock_ids』、传 location_ids 报『当前盘点类型按商品盘点,不能添加库位明细』);type=all/location 传 locations 或 location_ids(传 stock_ids 报『当前盘点类型按库位盘点,请传 locations 或 location_ids(如需按商品盘点请创建 type=goods 任务)』)。", + "location_ids 优先:两者都传时忽略 locations,直接按 wms_location_space.id+warehouse_id 查库校验(不再按 space_code 二次解析),查不到的 ID 记入 invalid_location_ids(不报错)。", + "历史任务兼容:改造前创建的 type=all 任务按商品添加明细(明细行 scope_type='goods');判定口径为该任务在 wms_stock_check_detail 中 scope_type='goods' 行存在(count>0)即继续按商品模式接受 stock_ids(此时传 locations/location_ids 分别报『当前盘点类型按商品盘点,请传 stock_ids』/『当前盘点类型按商品盘点,不能添加库位明细』);全新 type=all 任务(无任何商品明细行)维持按库位语义,只能传 locations/location_ids。仅 type=all 走兼容判定,store/goods/location 类型判定不变。", + "商品货主限制:任务 store_id 非空时商品 store_id 必须与之一致,不一致计入 invalid_stock_ids(限制非本货主商品加入盘点)。", + "全盘自动范围:type=all 且未传库位且未传 location_ids 时,自动拉取当前仓库全部启用库位(is_enabled=true)的 space_code 生成库位行;无启用库位时报 400。", + "幂等:商品行按 check_id+stock_id 跳过、库位行按 check_id+location_code 跳过(对应唯一索引 uk_check_stock / uk_check_location);location_ids 路径跳过项按库位ID记入 skipped。" ] }, { "method": "stock.check.detailDelete", - "description": "删除盘点明细(从任务中移除某个商品):入参 id(盘点任务ID)+ detail_id(盘点明细ID,兼容 detailId 驼峰写法,detail_id 优先);仅主表状态 created/rejected 允许删除;明细存在作业记录(wms_stock_check_record)时防御性一并删除(正常流程该状态不应有记录);删除后重算主表 total_items,返回 { detail_id, deleted, total_items }。", + "description": "批量删除盘点明细:入参 id(盘点任务ID)+ detail_ids(盘点明细ID数组,单次上限 200;兼容 detailIds 驼峰写法与旧版 detail_id 单值写法,单值自动转数组,优先级 detail_ids > detailIds > detail_id);仅主表状态 created/rejected 允许删除;未命中(明细不存在或不属于当前仓库)的明细ID计入 skipped_ids 不报错;命中明细批量删除并对 wms_stock_check_record 防御性清理作业记录(正常流程该状态不应有记录);删除后重算主表 total_items,返回 { deleted_count, deleted_ids, skipped_ids, total_items }。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -38138,32 +38215,45 @@ "description": "盘点任务ID" }, { - "name": "detail_id", - "type": "number", + "name": "detail_ids", + "type": "array", "required": true, "source": "body", - "description": "盘点明细ID(与 detailId 二选一,detail_id 优先)" + "description": "盘点明细ID数组(单次上限 200;兼容 detailIds 驼峰写法与旧版 detail_id 单值写法,单值自动转数组;优先级 detail_ids > detailIds > detail_id)" }, { - "name": "detailId", + "name": "detailIds", + "type": "array", + "required": false, + "source": "body", + "description": "盘点明细ID数组(驼峰别名,兼容写法,单值自动转数组;detail_ids 优先)" + }, + { + "name": "detail_id", "type": "number", "required": false, "source": "body", - "description": "盘点明细ID(驼峰别名,兼容写法)" + "description": "盘点明细ID(旧版单值写法,自动转数组;detail_ids/detailIds 优先)" } ], "response": [ { - "name": "detail_id", + "name": "deleted_count", "type": "number", "required": true, - "description": "被删除的盘点明细ID" + "description": "实际删除的明细数量" }, { - "name": "deleted", - "type": "boolean", + "name": "deleted_ids", + "type": "array", "required": true, - "description": "是否删除成功(true)" + "description": "实际删除的明细ID列表(保持入参顺序)" + }, + { + "name": "skipped_ids", + "type": "array", + "required": true, + "description": "未命中被跳过的明细ID列表(明细不存在或不属于当前仓库,不报错;保持入参顺序)" }, { "name": "total_items", @@ -38175,7 +38265,7 @@ "errors": [ { "code": 400, - "message": "盘点任务ID不能为空 / 盘点明细ID不能为空 / 盘点任务不存在 / 当前状态(非 created/rejected)不允许删除明细 / 盘点明细不存在" + "message": "盘点任务ID不能为空 / 盘点任务不存在 / 当前状态(非 created/rejected)不允许删除明细 / 请至少选择一个明细 / 单次最多删除 200 条明细" }, { "code": 500, @@ -38183,14 +38273,15 @@ } ], "notes": [ - "写操作,记录操作日志(不在免日志清单 list/detail/recordList/export/exportTaskProgress 中)。", - "detail_id 与 detailId 兼容:detail_id 非空时优先,否则取 detailId。", - "删除后对 wms_stock_check_record 按 { detail_id, check_id, warehouse_id } 防御性清理作业记录,并重算主表 total_items。" + "写操作,记录操作日志(不在免日志清单 list/detail/result/recordList/export/exportTaskProgress/patternList 中)。", + "入参兼容:detail_ids 优先于 detailIds、detail_id;detailIds/detail_id 为旧版兼容写法,单值自动转数组。", + "批量口径:未命中(明细不存在或不属于当前仓库)的明细ID计入 skipped_ids 不报错;命中明细批量删除后对 wms_stock_check_record 按 { detail_id, check_id, warehouse_id } 防御性清理作业记录,并重算主表 total_items;deleted_ids/skipped_ids 均保持入参顺序。", + "响应结构变更(兼容性影响):由旧版 { detail_id, deleted, total_items } 变更为 { deleted_count, deleted_ids, skipped_ids, total_items },前端需按新结构取值。" ] }, { "method": "stock.check.detail", - "description": "拉取盘点任务的全部明细行(商品清单)与盘点作业记录:返回主表信息(check)与全部明细(rows);rows 每条含商品快照(id/check_id/warehouse_id/stock_id/item_code/item_name/spec/batch_no/system_quantity/remark/created_at/updated_at)+ 已盘聚合字段(checked_quantity=作业记录数量合计、diff_quantity=实盘-账面、is_diff、status=checked|unchecked、location_codes、checkers、last_checked_at)+ records(该明细在 wms_stock_check_record 的全部作业记录:库位+数量+盘点人)+ locations(按库位聚合 [{ location_id, location_code, quantity }],空库位归 location_code=null 组)。", + "description": "拉取盘点任务明细(任务范围行,不含盘点作业聚合):返回主表信息(check)与全部明细(rows);rows 每条为纯范围行 15 字段(id/check_id/warehouse_id/scope_type/stock_id/location_id/location_code/item_code/item_name/spec/batch_no/system_quantity/remark/created_at/updated_at),不返回任何盘点作业聚合字段(盘点结果聚合请调用 stock.check.result);scope_type=goods 为商品行(stock_id 有值、location 相关字段为 null,另挂载 stock 全局商品信息对象,见 response.rows),scope_type=location 为库位行(location_id/location_code 有值、stock_id 与商品快照字段为 null,不挂载 stock)。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -38215,13 +38306,13 @@ "name": "check", "type": "object", "required": true, - "description": "盘点主表信息(id/check_no/title/type/mode/store_id/status/detail_status/check_date/start_time/end_time/creator_id/creator_name/total_items/checked_items/diff_items/remark/created_at/updated_at)" + "description": "盘点主表信息(id/check_no/title/type/mode/store_id/status/detail_status/start_time/end_time/creator_id/creator_name/total_items/checked_items/diff_items/remark/created_at/updated_at;start_time=盘点开始时间(第一个盘点明细写入的时间)、end_time=盘点结束时间(完成盘点的时间))" }, { "name": "rows", "type": "array", "required": true, - "description": "明细行列表:每条含商品快照(id/check_id/warehouse_id/stock_id/item_code/item_name/spec/batch_no/system_quantity 账面快照/remark/created_at/updated_at)+ 已盘聚合(checked_quantity 已盘数量=作业记录 quantity 合计、diff_quantity 差异数量=已盘-账面、is_diff 是否有差异 0|1、status=checked|unchecked、location_codes 库位编码数组去重、checkers 盘点人数组去重、last_checked_at 最近上报时间)+ records(该明细全部盘点作业记录,每条含 id/check_id/warehouse_id/detail_id/stock_id/location_id/location_code/quantity/checker_id/checker_name/checked_at/remark/created_at/updated_at)+ locations(按库位聚合数组,每项含 location_id/location_code/quantity,quantity 为该库位下作业记录数量合计;空库位记录归 location_code=null 组;按首条记录 id 升序);无作业记录时 records/locations 为空数组、聚合字段为 null" + "description": "明细行列表(纯范围行,不含盘点作业聚合):每条为 15 个范围行字段——id 明细ID / check_id 盘点任务ID / warehouse_id 仓库ID / scope_type 范围类型(goods=商品行 | location=库位行)/ stock_id 商品库存ID(wms_stock_warehouse.id,仅商品行有值,库位行为 null)/ location_id 库位ID(wms_location_space.id,仅库位行有值,商品行为 null)/ location_code 库位编码(仅库位行有值,商品行为 null)/ item_code 商品编码(商品快照,库位行为 null)/ item_name 商品名称(商品快照,库位行为 null)/ spec 规格(商品快照,库位行为 null)/ batch_no 批次号(商品快照,库位行为 null)/ system_quantity 账面数量快照(商品行为快照值,库位行为 0)/ remark 备注 / created_at 创建时间 / updated_at 更新时间;不返回 checked_quantity/diff_quantity/is_diff/status/location_codes/checkers/last_checked_at/records/locations/stocks 等作业聚合字段(见 stock.check.result);scope_type=goods 商品行另挂载 stock 对象(来源 stockWarehouse.getStockDetails,带缓存):完整全局商品信息——id 商品库存ID / item_code 商品编码 / item_name 商品名称 / sku_property SKU属性 / quantity 库存数量 / locked_quantity 锁定数量 / is_batch_mgmt 批次管理 Y|N / is_shelf_life_mgmt 效期管理 Y|N / image_url 商品图片 / is_images 是否有图 Y|N / need_recheck 是否需要复核 Y|N / store_id 货主ID / packing_requirements 打包要求 / pick_requirements 拣货要求 / recheck_requirements 复核要求 / merge_requirements 要求合并开关 Y|N / stock_unit 库存单位 / barcodes 条码数组([{ id, barcode, sku_property }]);未命中(库存不存在或不属于本仓库)stock=null;库位行(scope_type=location)不挂载 stock" }, { "name": "total", @@ -38239,11 +38330,156 @@ "code": 500, "message": "服务器内部错误" } + ], + "notes": [ + "商品行 stock 挂载口径:detail 返回时对 scope_type=goods 行按 stock_id 去重后批量调用 stockWarehouse.getStockDetails(stockIds, { warehouseId }),结果按 stock_id 挂载到各行 stock 字段;stock 为 wms_stock_warehouse 全局商品信息(id/item_code/item_name/sku_property/quantity/locked_quantity/is_batch_mgmt/is_shelf_life_mgmt/image_url/is_images/need_recheck/store_id/packing_requirements/pick_requirements/recheck_requirements/merge_requirements/stock_unit/barcodes),带 Redis 缓存(key=cache:stock_detail:{warehouseId}:{stockId},默认 TTL 300 秒);未命中(库存不存在或不属于本仓库)stock=null;库位行不挂载 stock;范围行原有 15 字段与其余返回结构不变。", + "拆分口径:detail 只返回任务范围行(纯 15 字段),原商品行已盘聚合(checked_quantity/diff_quantity/is_diff/status/location_codes/checkers/last_checked_at)、records(作业记录列表)、locations(按库位聚合)与库位行 stocks(按商品聚合)全部迁移到新接口 stock.check.result,调用方按需分别拉取。", + "查询类方法,不记录操作日志(免日志清单:list/detail/result/recordList/export/exportTaskProgress)。" + ] + }, + { + "method": "stock.check.result", + "description": "拉取盘点明细结果(按范围行聚合作业记录):入参 id(盘点任务ID);返回 { check, rows, total };商品行(scope_type=goods)含商品快照 + 已盘聚合(checked_quantity=作业记录数量合计、diff_quantity=实盘-账面、is_diff、status=checked|unchecked、location_codes、checkers、last_checked_at)+ records(该明细在 wms_stock_check_record 的全部作业记录,每条含 barcode/item_name 与 images 图片列表)+ locations(按库位聚合 [{ location_id, location_code, quantity }],空库位归 location_code=null 组,按首条记录 id 升序)+ unknown_items(未知商品按条码聚合 [{ barcode, item_name, checked_quantity }],无账面、差异=实盘-0=盘盈);库位行(scope_type=location)含 checked_quantity(行级合计=行内商品实盘合计)、diff_quantity(行内各商品差异代数和)、is_diff、status + records/locations + stocks(按商品聚合 [{ stock_id, item_code, item_name, system_quantity, checked_quantity, diff_quantity }],按 stock_id 升序,账面 system_quantity 查 wms_storage(space_id+stock_id SUM(quantity)),location_id 为空时账面按 0)+ unknown_items(口径同商品行);每条作业记录挂载 images(FileReference business_type=stock_check_record,仿收货 receivingItem 口径);无作业记录时聚合字段为 null、records/locations/stocks 为空数组。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(正常登录 token,携带仓库上下文)" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "盘点任务ID" + } + ], + "response": [ + { + "name": "check", + "type": "object", + "required": true, + "description": "盘点主表信息(id/check_no/title/type/mode/store_id/status/detail_status/start_time/end_time/creator_id/creator_name/total_items/checked_items/diff_items/remark/created_at/updated_at;start_time=盘点开始时间(第一个盘点明细写入的时间)、end_time=盘点结束时间(完成盘点的时间))" + }, + { + "name": "rows", + "type": "array", + "required": true, + "description": "明细结果行列表:商品行(scope_type=goods)含范围行字段 + 已盘聚合字段(checked_quantity 已盘数量=作业记录 quantity 合计,无记录为 null;diff_quantity 差异数量=已盘-账面快照,无记录为 null;is_diff 是否有差异 0|1;status 盘点状态 checked|unchecked;location_codes 库位编码数组去重;checkers 盘点人数组去重;last_checked_at 最近上报时间,无记录为 null)+ records(该明细全部盘点作业记录,每条含 id/check_id/warehouse_id/detail_id/stock_id/location_id/location_code/quantity/checker_id/checker_name/checked_at/remark/barcode/item_name/created_at/updated_at + images 图片列表 [{ id: file_id, url }],FileReference business_type=stock_check_record)+ locations(按库位聚合数组 [{ location_id, location_code, quantity }],quantity 为该库位下作业记录数量合计,空库位记录归 location_code=null 组,按首条记录 id 升序)+ unknown_items(未知商品聚合数组 [{ barcode, item_name, checked_quantity }],按条码升序;记录 stock_id 为空的未知商品按条码归组,无账面、差异=实盘-0=盘盈,已计入行级 checked_quantity/diff_quantity/is_diff;无未知商品为空数组);库位行(scope_type=location)含范围行字段 + stocks(按商品聚合数组 [{ stock_id, item_code, item_name, system_quantity, checked_quantity, diff_quantity }],按 stock_id 升序,仅含存在作业记录的已知商品;system_quantity 为 wms_storage 账面(space_id+stock_id SUM(quantity)),location_id 为空时按 0)+ checked_quantity(行级合计=行内商品实盘合计,无记录为 null)/ diff_quantity(行内各商品差异代数和,无记录为 null)/ is_diff / status + location_codes / checkers / last_checked_at + records / locations + unknown_items(口径同商品行);无作业记录时 records/locations/stocks/unknown_items 为空数组、checked_quantity/diff_quantity/last_checked_at 为 null" + }, + { + "name": "total", + "type": "number", + "required": true, + "description": "明细总条数" + } + ], + "errors": [ + { + "code": 400, + "message": "盘点任务ID不能为空 / 盘点任务不存在" + }, + { + "code": 500, + "message": "服务器内部错误" + } + ], + "notes": [ + "权限口径:随 ALL_METHOD_NAMES(16 个)免 API 权限(isNeedAuth=false)、免仓库有效期鉴权(免鉴权清单)、必须登录(isNeedLogin=true,免登录清单为空);为查询类方法,加入免日志清单 _noNeedLog(list/detail/result/recordList/export/exportTaskProgress)。", + "商品行聚合口径:checked_quantity=该明细全部作业记录 quantity 合计;diff_quantity=已盘-账面(账面为明细 system_quantity 快照);is_diff=存在记录且差异非 0 时为 1;status=存在记录 checked,否则 unchecked。", + "库位行账面口径:wms_storage 按 (space_id, stock_id) SUM(quantity) 现算(与 finish/export 汇总口径一致),location_id 为空时账面按 0;库位行 stocks 仅含存在作业记录的已知商品(stock_id 有值,无记录时为空数组),商品快照 item_code/item_name 从 wms_stock_warehouse 补齐。", + "无作业记录时:checked_quantity/diff_quantity/last_checked_at 为 null、records/locations/stocks 为空数组、status=unchecked、is_diff=0。", + "未知商品聚合口径:stock_id 为空的作业记录按 barcode 维度归组输出行级 unknown_items [{ barcode, item_name, checked_quantity }](按条码升序,item_name 为上报名称快照);未知商品无账面,差异=实盘-0=盘盈,已计入行级 checked_quantity/diff_quantity/is_diff;stocks 保持只输出已知商品(stock_id 有值)。代码依据:app/service/systems/stock_check.js#_formatDetailAggregationRow。", + "图片挂载口径(图片独立维护,仿收货 receivingItem):_attachRecordImages 查询 wms_file_reference(business_type=stock_check_record,business_id in 记录ID)并关联 wms_file 取 file_url,每条作业记录挂载 images [{ id: file_id, url }],无图片返回空数组;上传走通用上传接口(uploadSuccessNotify 传 businessType=stock_check_record + businessId=作业记录ID,建 FileReference)。代码依据:app/service/systems/stock_check.js#result/#_attachRecordImages。" + ] + }, + { + "method": "stock.check.workData", + "description": "拉取盘点作业数据(单接口三视图,view 入参驱动):入参 id(盘点任务ID)+ view(视图类型,仅支持 location/goods/space);返回 { check, rows, total },check 为盘点主表信息(_formatCheckRow 口径),rows 结构随 view 不同、total=rows.length,任务无对应范围行时 rows 返回空数组。view=location(库位结构):以任务库位范围行(scope_type=location)为列表(按明细 id 升序),行内挂该库位的盘点作业记录——goods(已知商品子列表,stock_id 有值)/unknown(未知商品子列表,stock_id 为空);view=goods(商品结构):以任务商品范围行(scope_type=goods)为列表(按明细 id 升序),行内挂按库位聚合的 locations 作业记录,明盘(mode=open)返回账面快照/已盘合计/差异,盲盘(mode=blind)不返回任何数量字段;view=space(聚合库位列表):以任务商品所在库位(wms_storage 中任务 stock_id 集合的启用未删除存储 DISTINCT space_id)为列表,按拣货路径排序(pick_sequence 升序、pick_priority 降序、库位 id 升序兜底),行内 goods 为该库位下的任务商品,明盘含库位账面与已盘数量、盲盘不含数量。状态限制:仅任务状态为 approved(审核完成)或 checking(盘点作业中)时可拉取盘点作业数据,其他状态(created 已创建/submitted 待审核/rejected 已驳回/completed 已完成/cancelled 已取消)返回 400「当前状态(xx)不允许拉取盘点作业数据,仅审核完成(approved)或盘点作业中(checking)的任务可拉取」。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(正常登录 token,携带仓库上下文)" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "盘点任务ID(wms_stock_check.id)" + }, + { + "name": "view", + "type": "string", + "required": true, + "source": "body", + "description": "视图类型,仅支持 location/goods/space:location=库位结构(任务库位范围行为列表,行内挂该库位 goods/unknown 作业记录子列表);goods=商品结构(任务商品范围行为列表,行内挂按库位聚合的 locations 作业记录);space=聚合库位列表(任务商品所在库位,按拣货路径排序,行内挂该库位的任务商品)" + } + ], + "response": [ + { + "name": "check", + "type": "object", + "required": true, + "description": "盘点主表信息(id/check_no/title/type/mode/store_id/status/detail_status/start_time/end_time/creator_id/creator_name/total_items/checked_items/diff_items/remark/created_at/updated_at;start_time=盘点开始时间(第一个盘点明细写入的时间)、end_time=盘点结束时间(完成盘点的时间))" + }, + { + "name": "rows", + "type": "array", + "required": true, + "description": "盘点作业数据行列表,结构随 view 不同——location 视图行:detail_id 明细ID / location_id 库位ID / location_code 库位编码(优先明细快照,缺失回退库位表 space_code)/ location_name 库位名称(custom_name 兜底 space_code)/ status 盘点状态(checked=存在作业记录,unchecked=无)/ has_unknown 是否含未知商品记录 / checked_at 该库位最近上报时间(无记录为 null)/ checkers 盘点人去重数组 + goods 已知商品子列表(stock_id 有值:record_id/stock_id/item_code/item_name/barcode/images/store_id/store_name/quantity 实盘数量/checked_at/checker_name,商品信息批量取自 stockWarehouse.getStockDetails 带缓存、货主名经 _resolveStoreNameMap 解析)+ unknown 未知商品子列表(stock_id 为空:record_id/barcode/item_name/images/quantity/checked_at/checker_name,图片经 _attachRecordImages 挂载 FileReference business_type=stock_check_record);goods 视图行:detail_id/stock_id/item_code/item_name/spec/store_id/store_name/barcode/images + locations 按库位聚合数组([{ location_code, checked_at, checker_name }],空库位归 location_code=null 组,按首条记录 id 升序),明盘(mode=open)另含 system_quantity 账面快照/checked_quantity 已盘合计/diff_quantity 差异=已盘-账面/is_diff 是否差异 0|1,locations 各项另含 quantity 该库位实盘合计,盲盘(mode=blind)不返回任何数量字段(locations 仅 location_code/checked_at/checker_name);space 视图行:location_id/location_code/location_name + goods 该库位下的任务商品子列表(detail_id/stock_id/item_code/item_name/spec/store_id/store_name/barcode/images + status 已盘状态(该 detail_id+location_code 存在作业记录即 checked,否则 unchecked)),明盘 goods 各项另含 system_quantity(wms_storage space+stock SUM(quantity) 账面)/checked_quantity(该商品在该库位的实盘合计),盲盘不含数量" + }, + { + "name": "total", + "type": "number", + "required": true, + "description": "行总数(=rows.length,任务无对应范围行时为 0)" + } + ], + "errors": [ + { + "code": 400, + "message": "盘点任务ID不能为空 / 视图类型非法(仅支持 location/goods/space)" + }, + { + "code": 400, + "message": "当前状态(xx)不允许拉取盘点作业数据,仅审核完成(approved)或盘点作业中(checking)的任务可拉取" + }, + { + "code": 400, + "message": "盘点任务不存在" + }, + { + "code": 500, + "message": "服务器内部错误" + } + ], + "notes": [ + "代码依据:app/service/systems/stock_check.js#workData(id 非正整数抛 400『盘点任务ID不能为空』;view 非 location/goods/space 抛 400『视图类型非法(仅支持 location/goods/space)』;任务不存在(按 id+warehouse_id 查 wms_stock_check)抛 400『盘点任务不存在』;新增状态守卫:任务状态非 REPORT_ALLOWED_STATUSES(approved/checking)时抛 400『当前状态(xx)不允许拉取盘点作业数据,仅审核完成(approved)或盘点作业中(checking)的任务可拉取』,即与 report/finish 一致的口径;按 view 分派 _buildLocationWorkRows/_buildGoodsWorkRows/_buildSpaceWorkRows,统一返回 { check: _formatCheckRow 口径, rows, total: rows.length })+ app/service/systemMethods/stock/check.js#workData(warehouse_id 由服务端从 ctx.user.store_id 自动注入,前端无需传递);本次仅同步文档,未改动任何代码。", + "三视图口径:location=库位结构,以任务库位范围行(scope_type=location)为列表(按明细 id 升序),行内挂该库位盘点作业记录——goods 已知商品子列表(stock_id 有值,商品信息批量取自 stockWarehouse.getStockDetails 带缓存、货主名 _resolveStoreNameMap 解析、图片 image_url)与 unknown 未知商品子列表(stock_id 为空,输出记录快照 barcode/item_name/images,图片经 _attachRecordImages 挂载 FileReference business_type=stock_check_record);goods=商品结构,以任务商品范围行(scope_type=goods)为列表(按明细 id 升序),行内挂按库位聚合的 locations(空库位归 location_code=null 组,按首条记录 id 升序);space=聚合库位列表,以任务商品(scope_type=goods 的 stock_id 集合)所在库位为列表——wms_storage(warehouse_id + stock_id 在集合 + is_enabled=1 未删除)DISTINCT space_id,行内 goods 为该库位下的任务商品,未在 wms_storage 有库位的商品不入列表。", + "明盘/盲盘数量控制:明盘(mode=open)goods 视图行返回 system_quantity(明细账面快照)/checked_quantity(已盘合计=locations.quantity 合计)/diff_quantity(已盘-账面)/is_diff(差异非 0 为 1),locations 各项含 quantity(该库位实盘合计);space 视图 goods 各项含 system_quantity(wms_storage space+stock SUM(quantity) 账面)/checked_quantity(该商品在该库位的实盘合计);盲盘(mode=blind)不返回任何数量字段(goods 视图 locations 仅 location_code/checked_at/checker_name,space 视图 goods 仅商品信息+status);无作业记录时 locations 为空数组、明盘已盘合计/差异按 0(避免未盘行误显盘亏差异)。", + "排序口径:space 视图库位按拣货路径排序——pick_sequence 升序、pick_priority 降序、同值按库位 id 升序兜底;space 行内 goods 按 stock_id 升序;location/goods 视图行按明细 id 升序;goods 视图 locations 按首条记录 id 升序。", + "权限口径:随 ALL_METHOD_NAMES(20 个:create/list/addDetail/addLocationDetail/detailDelete/detail/result/workData/report/recordList/recordDelete/finish/submit/cancel/audit/batchDelete/export/exportTaskProgress/patternList/patternCreate)免 API 权限(isNeedAuth=false)、免仓库有效期鉴权(_noNeedAuth)、必须登录(isNeedLogin=true,免登录清单为空);为查询类方法,加入免日志清单 _noNeedLog(list/detail/result/workData/recordList/export/exportTaskProgress/patternList),不记录操作日志。", + "文档变更范围:methods/system.json 的 module=stock.check 分组新增 stock.check.workData 一条(位于 stock.check.result 之后);根版本 0.3.224 → 0.3.225、updatedAt 2026-10-01 → 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);其余 19 条 method 未改动(stock.check 分组由 19 条增至 20 条)。", + "状态限制口径:仅任务状态为 approved(审核完成)或 checking(盘点作业中)可拉取盘点作业数据;其他状态(created 已创建/submitted 待审核/rejected 已驳回/completed 已完成/cancelled 已取消)返回 400,message 为『当前状态({状态中文标签,无标签时回退状态值})不允许拉取盘点作业数据,仅审核完成(approved)或盘点作业中(checking)的任务可拉取』,状态标签取 STOCK_CHECK_STATUS_LABELS。状态守卫复用 REPORT_ALLOWED_STATUSES 常量,与 report(盘点作业上报)及 finish(完成盘点)一致。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 一条(errors 的 400 新增状态限制文案并拆分为独立条目、description/notes 补充状态限制口径;headers/params/response/isNeedAuth/isNeedLogin 不变);根版本 0.3.225 → 0.3.226、updatedAt 保持 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);其余 19 条 method 未改动(stock.check 分组仍为 20 条)。", + "库表维护源说明:维护源为库表(wms_api_method_doc + wms_method_doc_meta),methods/system.json 是导出产物;本次按 docs/api-doc-update-workflow.md 走 npm run doc:api:update 写入 JSON 后,同步回填开发库(显式 WMS_DB_TARGET=local)与生产库(NODE_ENV=production + --env production 双设置)——import 当前 system.json → export 回写往返校验,保持库与文件一致;stock.check 分组共 20 条 method 无损。" ] }, { "method": "stock.check.report", - "description": "盘点作业上报(覆盖式):同明细 + 同库位编码重复上报时更新已有记录(quantity/checker_id/checker_name/checked_at,保留原 location_id,若本次新匹配到 location_id 则回填),不再新增;未传库位归入\"无库位\"分组(location_code 存空串 ''),同分组重复上报同样覆盖更新;仅 approved/checking 状态允许;库位编码匹配 wms_location_space.space_code 时回填 location_id;主表 approved 首次上报自动转 checking;完成后重算 checked_items/diff_items/detail_status(已盘口径=存在记录的明细数,差异=记录数量合计-账面快照);数据库层由唯一索引 uk_detail_location(detail_id, location_code) 保证覆盖式上报并发安全(并发下不产生重复记录)。", + "description": "盘点作业上报(覆盖式):商品明细行(scope_type=goods)固定上报明细商品(入参 stock_id 与明细商品不一致报错),库位可选(未传归入\"无库位\"分组,location_code 存空串 '');库位明细行(scope_type=location)必须指定商品(stock_id 或 barcode 至少一项),库位以明细库位为准(入参库位与明细库位不一致报错,不传时默认明细库位);覆盖式查重:已知商品维度 detail_id+stock_id+location_code、未知商品维度 detail_id+stock_id IS NULL+barcode+location_code,同明细+同商品+同库位重复上报时更新已有记录(quantity/checker_id/checker_name/checked_at,保留原 location_id,本次新匹配到 location_id 则回填),不再新增;仅 approved/checking 状态允许;库位编码匹配 wms_location_space.space_code 时回填 location_id;主表 approved 首次上报自动转 checking;完成后重算 checked_items/diff_items/detail_status(已盘口径=存在记录的明细数,差异=记录数量合计-账面:商品行 vs system_quantity 快照、库位行按商品 vs wms_storage 账面;未知商品无账面,实盘>0 即盘盈、必然计入差异);数据库层由唯一索引 uk_detail_stock_location(detail_id, stock_id, location_code) 保证已知商品覆盖式上报并发安全(并发下不产生重复记录),未知商品(stock_id=NULL)唯一索引不约束 NULL 行、应用层查重兜底。主表 start_time 为空时以本次明细写入时间补写(首个盘点明细写入时间记录为 start_time,即盘点开始时间)。未知商品上报(stock_id 与 barcode 至少传一项):仅传 barcode → 先按条码匹配系统商品(wms_stock_barcodes 按 barcode+本仓库,关联 StockWarehouse 校验商品属于本仓库),命中回填 stock_id 走已知商品逻辑;未命中记录未知商品(stock_id=NULL+barcode+item_name,item_name 缺省为 barcode);都未传沿用原报错口径。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -38274,7 +38510,7 @@ "type": "string", "required": false, "source": "body", - "description": "库位编码(可空;写入作业记录 location_code,匹配 space_code 时回填 location_id;未传或为空归入无库位分组(存空串 ''))" + "description": "库位编码(可空;商品明细行:未传归入无库位分组(存空串 '');库位明细行:以明细库位为准,传入时必须与明细库位一致)" }, { "name": "quantity", @@ -38282,6 +38518,27 @@ "required": true, "source": "body", "description": "实盘数量(不小于 0 的整数)" + }, + { + "name": "stock_id", + "type": "number", + "required": false, + "source": "body", + "description": "商品库存ID(wms_stock_warehouse.id);商品明细行可选(传入必须与明细商品一致,否则报错);库位明细行必填(或改传 barcode 按条码匹配),商品必须属于本仓库" + }, + { + "name": "barcode", + "type": "string", + "required": false, + "source": "body", + "description": "扫描到的条码/编码(可选):未传 stock_id 时按条码匹配系统商品(wms_stock_barcodes 按 barcode+本仓库匹配并校验商品属于本仓库,关联 StockWarehouse),命中回填 stock_id 按已知商品处理;未命中记为未知商品(stock_id=NULL+barcode+item_name)" + }, + { + "name": "item_name", + "type": "string", + "required": false, + "source": "body", + "description": "未知商品名称快照(可选):仅未知商品记录落库,缺省为 barcode;已知商品忽略" } ], "response": [ @@ -38289,7 +38546,7 @@ "name": "record", "type": "object", "required": true, - "description": "新增或更新的盘点作业记录(wms_stock_check_record 行:id/check_id/warehouse_id/detail_id/stock_id/location_id/location_code/quantity/checker_id/checker_name/checked_at/remark/created_at/updated_at)" + "description": "新增或更新的盘点作业记录(wms_stock_check_record 行:id/check_id/warehouse_id/detail_id/stock_id/location_id/location_code/quantity/checker_id/checker_name/checked_at/remark/barcode/item_name/created_at/updated_at);stock_id 可空:NULL=未知商品(此时 barcode=扫描条码、item_name=未知商品名称快照(缺省为条码)),已知商品 barcode/item_name 可能为空" }, { "name": "detail_id", @@ -38301,7 +38558,7 @@ "name": "mode", "type": "string", "required": true, - "description": "本次上报模式:created=首次上报新增记录 / updated=同明细+同库位重复上报更新已有记录" + "description": "本次上报模式:created=首次上报新增记录 / updated=同明细+同商品+同库位重复上报更新已有记录(未知商品为同明细+同条码+同库位)" }, { "name": "total_items", @@ -38319,7 +38576,7 @@ "name": "diff_items", "type": "number", "required": true, - "description": "差异行数(实盘合计与账面快照不一致的明细数)" + "description": "差异行数(实盘合计与账面不一致的明细数;未知商品无账面,实盘>0 即盘盈、必然计入差异)" }, { "name": "detail_status", @@ -38331,7 +38588,7 @@ "errors": [ { "code": 400, - "message": "盘点任务ID不能为空 / 盘点明细ID不能为空 / 盘点任务不存在 / 当前状态(非 approved/checking)不允许盘点作业 / 实盘数量必须为不小于0的整数 / 盘点明细不存在" + "message": "盘点任务ID不能为空 / 盘点明细ID不能为空 / 盘点任务不存在 / 当前状态(非 approved/checking)不允许盘点作业 / 实盘数量必须为不小于0的整数 / 盘点明细不存在 / 盘点明细缺少商品信息 / 上报商品与盘点明细商品不一致 / 按库位盘点时必须指定商品 / 上报商品不属于本仓库 / 盘点明细缺少库位信息 / 上报库位与盘点明细库位不一致" }, { "code": 500, @@ -38339,13 +38596,18 @@ } ], "notes": [ - "覆盖口径:同 detail_id + 同 location_code(未传库位存储空串 '',即\"无库位\"分组)视为同一作业记录,重复上报只更新不新增。", - "并发保证:数据库层唯一索引 uk_detail_location(detail_id, location_code) 兜底,并发上报同一明细+库位时不产生重复记录(模型 location_code allowNull=false 默认空串)。" + "覆盖口径:同 detail_id + 同 stock_id + 同 location_code(未传库位存储空串 '',即\"无库位\"分组)视为同一作业记录,重复上报只更新不新增。", + "并发保证:数据库层唯一索引 uk_detail_stock_location(detail_id, stock_id, location_code) 兜底,并发上报同一明细+商品+库位时不产生重复记录(模型 location_code allowNull=false 默认空串)。", + "库位行上报:商品必填(按库位盘点时必须指定商品,stock_id 或 barcode 至少一项)且商品须属于本仓库(wms_stock_warehouse.id + warehouse_id),库位以明细库位为准(detail.location_code)。", + "start_time 口径:主表 start_time 为空时以本次明细写入时间补写(首个盘点明细写入时间记录为 start_time=盘点开始时间);代码依据 app/service/systems/stock_check.js#report(start_time 为空则补写,保证任何状态下首个明细落盘时间都被记录)。", + "未知商品上报口径(stock_id 与 barcode 至少传一项):传了 stock_id 按已知商品走现有逻辑(本仓库校验等);未传 stock_id 但传了 barcode,先按条码匹配系统商品(_resolveStockIdByBarcode:wms_stock_barcodes 按 barcode+本仓库匹配,再校验 wms_stock_warehouse 中该商品属于本仓库),命中回填 stock_id 按已知商品处理(商品明细行还会校验与明细商品一致),未命中记录未知商品(stock_id=NULL + barcode + item_name,item_name 缺省为 barcode);都未传沿用现有报错口径(商品行缺商品信息报 400 / 库位行缺商品报 400)。", + "未知商品覆盖式查重:已知商品 where { detail_id, stock_id, location_code } 不变;未知商品 where { detail_id, stock_id: null, barcode, location_code } 应用层查重(唯一索引 uk_detail_stock_location 不约束 NULL 行,并发下撞索引/冲突时同样按查重条件降级更新兜底)。", + "迁移依据:database/migrations/20261001100000-support-unknown-goods-in-stock-check-record.js(wms_stock_check_record:stock_id 改可空(NULL=未知商品)+ 新增 barcode VARCHAR(100)/item_name VARCHAR(255),本地与生产均已执行)。" ] }, { "method": "stock.check.recordList", - "description": "拉取盘点作业记录列表:至少传 id(盘点任务ID)或 detail_id(明细ID)之一(可同时传,detail_id 生效时只查该明细的作业记录);按当前用户仓库(ctx.user.store_id)限定数据范围;rows 每条为作业记录(wms_stock_check_record)全字段 + 商品快照列(item_code/item_name,从明细表补齐);按记录 id 倒序,分页返回。", + "description": "拉取盘点作业记录列表:至少传 id(盘点任务ID)或 detail_id(明细ID)之一(可同时传,detail_id 生效时只查该明细的作业记录);按当前用户仓库(ctx.user.store_id)限定数据范围;rows 每条为作业记录(wms_stock_check_record)全字段 + 商品快照列(item_code/item_name);未知商品(stock_id 为空)商品编码列显示扫描条码(barcode)、名称列显示上报名称快照(item_name);每条记录挂载 images(FileReference business_type=stock_check_record,仿收货 receivingItem 口径);按记录 id 倒序,分页返回。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -38384,7 +38646,7 @@ "name": "rows", "type": "array", "required": true, - "description": "作业记录行列表:每条为 wms_stock_check_record 全字段(id/check_id/warehouse_id/detail_id/stock_id/location_id/location_code/quantity/checker_id/checker_name/checked_at/remark/created_at/updated_at)+ 商品快照列 item_code/item_name;location_code 口径:库中空串(\"无库位\"分组)返回时归一为 null(接口返回口径不变)" + "description": "作业记录行列表:每条为 wms_stock_check_record 全字段(id/check_id/warehouse_id/detail_id/stock_id/location_id/location_code/quantity/checker_id/checker_name/checked_at/remark/barcode/item_name/created_at/updated_at)+ 商品快照列 item_code/item_name + images 图片列表 [{ id: file_id, url }](FileReference business_type=stock_check_record);stock_id 可空(NULL=未知商品);item_code/item_name 口径:未知商品(stock_id 为空)item_code=扫描条码(barcode,空则 null)、item_name=上报名称快照(item_name 或 barcode 兜底),已知商品从明细表(wms_stock_check_detail)商品快照补齐;location_code 口径:库中空串(\"无库位\"分组)返回时归一为 null(接口返回口径不变)" }, { "name": "total", @@ -38416,14 +38678,16 @@ } ], "notes": [ - "查询类方法,不记录操作日志(免日志清单:list/detail/recordList/export/exportTaskProgress)。", + "查询类方法,不记录操作日志(免日志清单:list/detail/result/recordList/export/exportTaskProgress)。", "rows 按记录 id 倒序返回。", - "location_code 返回口径:库中空串(无库位分组)归一为 null,接口返回口径不变(与 detail 的 locations/location_codes 空库位组 location_code=null 一致)。" + "location_code 返回口径:库中空串(无库位分组)归一为 null,接口返回口径不变(与 detail 的 locations/location_codes 空库位组 location_code=null 一致)。", + "未知商品显示口径:stock_id 为空的记录 item_code 显示扫描条码(barcode,空则 null)、item_name 显示上报名称快照(item_name 或 barcode 兜底);已知商品维持从明细表(wms_stock_check_detail)商品快照补齐。代码依据:app/service/systems/stock_check.js#recordList。", + "图片挂载口径(图片独立维护,仿收货 receivingItem):查询 wms_file_reference(business_type=stock_check_record)+ wms_file.file_url,每条记录挂载 images [{ id, url }],无图片返回空数组;上传走通用上传接口(businessType=stock_check_record + businessId=作业记录ID,建 FileReference)。" ] }, { "method": "stock.check.recordDelete", - "description": "删除盘点作业记录:仅主表状态 approved/checking 允许删除;记录必须属于该盘点任务与当前仓库,删除后重算 checked_items/diff_items/detail_status(该明细作业记录删光后回到未盘口径),主表状态不回退。", + "description": "删除盘点作业记录:仅主表状态 approved/checking 允许删除;记录必须属于该盘点任务与当前仓库,删除后重算 checked_items/diff_items/detail_status(该明细作业记录删光后回到未盘口径),主表状态不回退;同时清理该记录的图片引用(FileReference business_type=stock_check_record,失败仅告警不影响主流程)。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -38486,7 +38750,7 @@ "name": "diff_items", "type": "number", "required": true, - "description": "重算后的差异行数(实盘合计与账面快照不一致的明细数)" + "description": "重算后的差异行数(实盘合计与账面快照不一致的明细数;未知商品无账面,实盘>0 即盘盈、必然计入差异)" }, { "name": "detail_status", @@ -38507,12 +38771,13 @@ ], "notes": [ "删除为写操作,记录操作日志(不在免日志清单)。", - "删除后仅重算盘点进度汇总(checked_items/diff_items/detail_status),主表状态不回退。" + "删除后仅重算盘点进度汇总(checked_items/diff_items/detail_status),主表状态不回退。", + "图片清理口径(图片独立维护,仿收货):删除作业记录后同步清理 wms_file_reference(business_type=stock_check_record + business_id=记录ID),失败仅告警(warn 日志)不影响主流程。代码依据:app/service/systems/stock_check.js#recordDelete。" ] }, { "method": "stock.check.finish", - "description": "完成盘点作业(允许部分未盘完成):仅 approved/checking 状态允许;未盘明细=无作业记录(wms_stock_check_record)的明细,按实盘 0 处理(差异=-账面快照,计入盘亏与差异行数);已盘明细按作业记录数量合计与账面快照(system_quantity)对比聚合(盘盈=正差异合计、盘亏=负差异绝对值合计);完成后主表置 completed、回填 end_time、detail_status=all_checked,返回差异汇总(盘盈/盘亏合计)与未盘明细数(unchecked_items)。", + "description": "完成盘点作业(允许部分未盘完成):仅 approved/checking 状态允许;未盘商品明细=无作业记录(wms_stock_check_record)的明细,按实盘 0 处理(差异=-账面快照,计入盘亏与差异行数);未盘库位明细行因无法枚举商品不计差异;已盘商品明细按作业记录数量合计与账面快照(system_quantity)对比聚合;已盘库位明细按商品聚合实盘 vs wms_storage 账面(space_id+stock_id SUM(quantity),space_id 为空时账面按 0)对比聚合;盘盈=正差异合计、盘亏=负差异绝对值合计;完成后主表置 completed、回填 end_time(完成盘点的时间)、detail_status=all_checked,返回差异汇总(盘盈/盘亏合计)与未盘明细数(unchecked_items)。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -38561,25 +38826,25 @@ "name": "unchecked_items", "type": "number", "required": true, - "description": "未盘明细数(无作业记录的明细数,完成时按实盘 0 处理计为盘亏)" + "description": "未盘明细数(无作业记录的明细数;未盘商品明细按实盘 0 处理计为盘亏,未盘库位明细不计差异)" }, { "name": "diff_items", "type": "number", "required": true, - "description": "差异行数(实盘合计与账面快照不一致的明细数,未盘明细按实盘 0 计入)" + "description": "差异行数(商品行实盘合计与账面快照不一致、库位行任一商品实盘与账面不一致的明细数,未盘商品明细按实盘 0 计入)" }, { "name": "profit_total", "type": "number", "required": true, - "description": "盘盈合计(作业记录数量合计大于账面快照的差异合计)" + "description": "盘盈合计(商品行:作业记录数量合计大于账面快照的差异合计;库位行:按商品实盘大于 wms_storage 账面的差异合计)" }, { "name": "loss_total", "type": "number", "required": true, - "description": "盘亏合计(实盘小于账面快照的差异绝对值合计,含未盘明细的账面快照数)" + "description": "盘亏合计(商品行:实盘小于账面快照的差异绝对值合计,含未盘明细的账面快照数;库位行:按商品实盘小于 wms_storage 账面的差异绝对值合计)" } ], "errors": [ @@ -38591,6 +38856,11 @@ "code": 500, "message": "服务器内部错误" } + ], + "notes": [ + "库位行账面口径:wms_storage 按 (space_id, stock_id) SUM(quantity),与 detail 接口的 stocks 账面一致。", + "未盘库位明细行无法枚举商品(无作业记录即无商品维度),完成时不计差异、不计盘盈盘亏。", + "end_time 语义:完成盘点时主表写入 end_time(完成盘点的时间);接口响应不返回 end_time(响应结构不变:id/status/total_items/checked_items/unchecked_items/diff_items/profit_total/loss_total),主表时间字段请通过 detail/result/list 查看。" ] }, { @@ -38748,9 +39018,79 @@ } ] }, + { + "method": "stock.check.batchDelete", + "description": "批量删除盘点任务(仅删除已作废任务,非作废或查不到的任务跳过):入参 ids(盘点任务ID数组,兼容单值,服务端归一化为去重后的正整数,单次上限 200),warehouse_id 由服务端从当前登录上下文(ctx.user.store_id)自动注入,前端无需传递;按 id in ids + warehouse_id 查询主表做仓库隔离;状态分流:status=cancelled(作废)的任务级联删除,其他状态及查不到的任务跳过(计入 skipped_ids);删除级联顺序(事务内):先删作业记录(wms_stock_check_record,where check_id in 删除集),再删明细(wms_stock_check_detail,where check_id in 删除集),最后删主表(wms_stock_check,where id in 删除集);返回 { total, deleted_count, skipped_count, deleted_ids, skipped_ids },deleted_ids/skipped_ids 保持入参顺序。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(正常登录 token,携带仓库上下文)" + } + ], + "params": [ + { + "name": "ids", + "type": "array", + "required": true, + "source": "body", + "description": "盘点任务ID数组(兼容单值;服务端归一化为去重后的正整数,单次上限 200)" + } + ], + "response": [ + { + "name": "total", + "type": "number", + "required": true, + "description": "入参去重后的任务ID数量" + }, + { + "name": "deleted_count", + "type": "number", + "required": true, + "description": "实际删除的任务数量(仅作废任务)" + }, + { + "name": "skipped_count", + "type": "number", + "required": true, + "description": "跳过的任务数量(非作废状态或查不到的任务)" + }, + { + "name": "deleted_ids", + "type": "array", + "required": true, + "description": "已删除的任务ID列表(保持入参顺序)" + }, + { + "name": "skipped_ids", + "type": "array", + "required": true, + "description": "跳过的任务ID列表(保持入参顺序)" + } + ], + "errors": [ + { + "code": 400, + "message": "无法获取当前仓库上下文 / ids 不能为空 / 单次最多删除 200 个盘点任务" + }, + { + "code": 500, + "message": "服务器内部错误" + } + ], + "notes": [ + "仅作废(status=cancelled)任务执行删除;其他状态及仓库内查不到的任务跳过(计入 skipped_ids,保持入参顺序),不视为业务错误。", + "级联删除在事务内执行,顺序为:作业记录(StockCheckRecord)→ 明细(StockCheckDetail)→ 主表(StockCheck)。", + "写操作:随 ALL_METHOD_NAMES(16 个 method)免 API 权限(isNeedAuth=false)、免仓库有效期鉴权,需登录(isNeedLogin=true);不在免日志清单(_noNeedLog),保留操作日志。" + ] + }, { "method": "stock.check.export", - "description": "提交盘点任务导出任务(异步):Excel 分两个 Sheet 生成——Sheet1「盘点单」一行一个盘点任务(单号/名称/范围/方式/状态/进度/货主/创建人/汇总数/起止时间/备注),Sheet2「盘点明细」一行一条明细(商品级聚合,首列盘点单号:商品编码/商品名称/规格/账面数量/已盘数量(作业记录数量合计)/差异数量/是否有差异/库位编码(多个库位顿号「、」合并)/盘点人(合并)/最近盘点时间);ExcelJS 流式生成后上传 COS;进度通过 Redis 缓存(key stock_check_export_task_*,TTL 1800 秒)追踪,立即返回任务ID;单次最多 50 个盘点任务。", + "description": "提交盘点任务导出任务(异步):Excel 分两个 Sheet 生成——Sheet1「盘点单」一行一个盘点任务(盘点单号/盘点名称/盘点范围/盘点方式/盘点状态/盘点进度/货主ID/创建人/明细行数/已盘行数/差异行数/开始时间/结束时间/备注;主表移除 check_date 后已移除「盘点日期」列,保留开始/结束时间列);Sheet2「盘点明细」一行一条实际盘点记录(作业记录 wms_stock_check_record,列:盘点单号/商品编码/商品名称/库位编码(空库位输出为空)/实盘数量/盘点人/盘点时间;未知商品(stock_id 为空)商品编码列显示扫描条码(barcode)、商品名称列显示上报名称快照(item_name),已知商品快照从 wms_stock_warehouse 补齐),未盘的任务范围行不再导出;ExcelJS 流式生成后上传 COS;进度通过 Redis 缓存(key stock_check_export_task_*,TTL 1800 秒)追踪,立即返回任务ID;单次最多 50 个盘点任务。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -38800,13 +39140,13 @@ "name": "current_count", "type": "number", "required": true, - "description": "当前已处理明细数" + "description": "当前已处理明细行数(Sheet2 已写入的作业记录行数)" }, { "name": "total_count", "type": "number", "required": true, - "description": "明细总行数" + "description": "Sheet2 盘点明细总行数(作业记录总数,导出前即确定)" }, { "name": "message", @@ -38838,6 +39178,10 @@ "code": 400, "message": "请至少选择一个盘点任务 / 单次最多导出 50 个盘点任务" }, + { + "code": 400, + "message": "未找到可导出的盘点任务" + }, { "code": 500, "message": "服务器内部错误" @@ -38845,8 +39189,10 @@ ], "notes": [ "兼容 ids / task_ids 两种入参写法,ids 优先;自动去重并过滤非正整数。", - "异步执行:查询任务与明细(按盘点作业记录聚合已盘数量/差异/库位/盘点人)→ ExcelJS 流式写入(Sheet1「盘点单」一行一个盘点任务,Sheet2「盘点明细」一行一条明细,首列盘点单号)→ COS 上传。", - "进度缓存 Redis key stock_check_export_task_{taskId},TTL 1800 秒。" + "异步执行:查询任务与作业记录(wms_stock_check_record,不按任务范围行展开)→ 商品快照从 wms_stock_warehouse 补齐(item_code/item_name)→ ExcelJS 流式写入(Sheet1「盘点单」一行一个盘点任务;Sheet2「盘点明细」一行一条实际盘点记录,列:盘点单号/商品编码/商品名称/库位编码(空库位输出为空)/实盘数量/盘点人/盘点时间,未盘的任务范围行不导出)→ COS 上传。", + "进度缓存 Redis key stock_check_export_task_{taskId},TTL 1800 秒;totalCount=作业记录总数(导出前即确定),进度按已写入明细行数/总数计算(每 200 行汇报一次)。", + "Sheet1「盘点单」一行一个盘点任务,列:盘点单号/盘点名称/盘点范围/盘点方式/盘点状态/盘点进度/货主ID/创建人/明细行数/已盘行数/差异行数/开始时间/结束时间/备注(主表移除 check_date 后不再导出「盘点日期」列,保留开始/结束时间列);Sheet2「盘点明细」由『按任务范围行展开(含未盘空行)』调整为『一行一条实际盘点记录(作业记录)』,未盘的任务范围行不再导出。", + "未知商品导出口径:stock_id 为空的记录商品编码列输出扫描条码(barcode,空则留空)、商品名称列输出上报名称快照(item_name 或 barcode 兜底);已知商品维持 wms_stock_warehouse 商品快照(item_code/item_name)。代码依据:app/service/systems/stock_check.js#exportStockChecks/#_generateAndUploadStockCheckExcel。" ] }, { @@ -38950,6 +39296,225 @@ "任务不存在为正常响应(status=not_found),非业务错误。", "进度缓存 Redis key stock_check_export_task_{taskId},TTL 1800 秒。" ] + }, + { + "method": "stock.check.patternList", + "description": "拉取盘点定式清单(供前端选择定式快速创建盘点任务):返回代码注册的 5 个内置定式(注册于 app/service/systems/stock_check_patterns.js,不建表),每条含 id/name/description/type;无入参。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(正常登录 token,携带仓库上下文)" + } + ], + "params": [], + "response": [ + { + "name": "patterns", + "type": "array", + "required": true, + "description": "盘点定式列表(共 5 条:空库位/错发/临期/静态/预警),每条含 id/name/description/type", + "children": [ + { + "name": "id", + "type": "string", + "required": true, + "description": "定式唯一标识(patternCreate 的 pattern_id 入参):empty_location=空库位盘点 / mis_shipment=错发盘点 / expiring=临期盘点 / static=静态盘点 / warning=预警盘点" + }, + { + "name": "name", + "type": "string", + "required": true, + "description": "定式名称(创建任务时作为默认标题)" + }, + { + "name": "description", + "type": "string", + "required": true, + "description": "定式描述(含对象收集口径,详见 notes)" + }, + { + "name": "type", + "type": "string", + "required": true, + "description": "对应盘点任务 type:location=按库位(仅 empty_location)/ goods=按商品(其余 4 个)" + } + ] + }, + { + "name": "total", + "type": "number", + "required": true, + "description": "定式总数(当前为 5)" + } + ], + "errors": [ + { + "code": 500, + "message": "服务器内部错误" + } + ], + "notes": [ + "5 个定式口径(与代码注释一致):① empty_location 空库位盘点(type=location):wms_location_space 中启用且未删除、在 wms_storage 不存在任何 quantity>0 库存记录的账面空库位;② mis_shipment 错发盘点(type=goods):登记过错发工单(wms_after_sale type=order 且 sub_type=mis_shipment,凡登记过即纳入、排除 closed/cancelled 状态)关联订单的商品按 stock_id 去重;③ expiring 临期盘点(type=goods):开启保质期管理(wms_stock_warehouse.is_shelf_life_mgmt=Y)且存在临期库存(最早到期日 <= 当前时间+该商品 remaining_threshold_days 天,阈值 <=0 时按已到期)的商品维度去重;④ static 静态盘点(type=goods):最后一次 INBOUND/OUTBOUND 流水(wms_stock_transaction)距今超过仓库配置 stock_static_hours 小时(默认 168,无流水按 wms_stock_warehouse.create_at)且未进入 wms_stock_static_check_task 的商品;⑤ warning 预警盘点(type=goods):库存 quantity < 仓库配置 stock_warning_quantity 的商品(要求仓库配置 stock_warning_enabled=true 才可执行)。", + "查询类接口:免 API 权限(isNeedAuth=false)、免仓库有效期鉴权、必须登录(isNeedLogin=true);在免日志清单(_noNeedLog)中,不记录操作日志。", + "返回字段仅对外 4 个(id/name/description/type),不含内部执行函数。" + ] + }, + { + "method": "stock.check.patternCreate", + "description": "按定式快速创建盘点任务:入参 pattern_id(兼容 patternId 驼峰写法,pattern_id 优先)+ 可选 title/remark;warehouse_id 与创建人由服务端从登录上下文(ctx.user.store_id / ctx.user.id / employees_name)自动注入,前端无需传递;盘点方式由定式范围类型固定:库位类定式(empty_location,type=location)一律盲盘 blind、商品类定式(type=goods,其余 4 个)一律明盘 open;盘点方式与盘点时间均无需前端传入(主表已无 check_date,start_time=盘点开始时间(第一个盘点明细写入的时间)、end_time=盘点结束时间(完成盘点的时间),由盘点作业流程自动回填);按定式收集盘点对象(goods 型得到 stock_ids、location 型得到库位列表),无符合条件对象报 400;创建后主表状态直接 submitted(进入待审核)、detail_status=none_checked、total_items 按明细重算;static 定式在任务创建成功后把命中的 stock_id 批量写入 wms_stock_static_check_task(失败不影响主流程);写操作,记录操作日志。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(正常登录 token,携带仓库上下文)" + } + ], + "params": [ + { + "name": "pattern_id", + "type": "string", + "required": true, + "source": "body", + "description": "定式ID:empty_location=空库位盘点 / mis_shipment=错发盘点 / expiring=临期盘点 / static=静态盘点 / warning=预警盘点(兼容 patternId 驼峰写法,两者都传时 pattern_id 优先)" + }, + { + "name": "patternId", + "type": "string", + "required": false, + "source": "body", + "description": "定式ID(驼峰别名,兼容写法)" + }, + { + "name": "title", + "type": "string", + "required": false, + "source": "body", + "description": "盘点名称/主题,缺省取定式 name" + }, + { + "name": "remark", + "type": "string", + "required": false, + "source": "body", + "description": "备注" + } + ], + "response": [ + { + "name": "check", + "type": "object", + "required": true, + "description": "创建后的盘点任务信息(_formatCheckRow 口径:id/check_no/title/type/mode/store_id/status/detail_status/start_time/end_time/creator_id/creator_name/total_items/checked_items/diff_items/remark/created_at/updated_at,无 check_date);status 直接为 submitted(待审核),mode 由定式范围类型固定(location→blind、goods→open),start_time/end_time 创建时为空(分别由首个盘点明细写入与完成盘点回填)" + }, + { + "name": "total_items", + "type": "number", + "required": true, + "description": "明细总行数(创建明细后按 wms_stock_check_detail 重算)" + }, + { + "name": "pattern_id", + "type": "string", + "required": true, + "description": "本次创建使用的定式ID" + } + ], + "errors": [ + { + "code": 400, + "message": "无法获取当前仓库上下文 / 盘点定式不存在 / 当前仓库没有账面为空的库位 / 没有符合条件的商品 / 未开启库存预警" + }, + { + "code": 500, + "message": "服务器内部错误" + } + ], + "notes": [ + "5 个定式口径(与代码注释一致):① empty_location 空库位盘点(type=location):wms_location_space 中启用且未删除、在 wms_storage 不存在任何 quantity>0 库存记录的账面空库位;② mis_shipment 错发盘点(type=goods):登记过错发工单(wms_after_sale type=order 且 sub_type=mis_shipment,凡登记过即纳入、排除 closed/cancelled 状态)关联订单的商品按 stock_id 去重;③ expiring 临期盘点(type=goods):开启保质期管理(is_shelf_life_mgmt=Y)且存在临期库存(最早到期日 <= 当前时间+remaining_threshold_days 天,阈值 <=0 时按已到期)的商品维度去重;④ static 静态盘点(type=goods):最后一次 INBOUND/OUTBOUND 流水距今超过仓库配置 stock_static_hours 小时(默认 168,无流水按 wms_stock_warehouse.create_at)且未进入 wms_stock_static_check_task 的商品;⑤ warning 预警盘点(type=goods):库存 quantity < 仓库配置 stock_warning_quantity 的商品(要求仓库配置 stock_warning_enabled=true 才可执行,未开启报 400「未开启库存预警」)。", + "盘点方式与盘点时间固定规则(前端不传):盘点方式由定式范围类型固定——库位类定式(type=location,即 empty_location)一律盲盘(blind)、商品类定式(type=goods,其余 4 个定式)一律明盘(open);盘点时间不传(主表已无 check_date,start_time=盘点开始时间(第一个盘点明细写入的时间)、end_time=盘点结束时间(完成盘点的时间),由盘点作业流程自动回填);入参已移除 mode/check_date。", + "状态口径:创建后主表 status 直接 submitted(进入待审核)、detail_status=none_checked,无需再调 stock.check.submit;store_id/scope_snapshot 为空,type 取定式类型(location/goods),mode 由定式范围类型固定(location→blind、goods→open),start_time/end_time 创建时为空。", + "static 定式静态记录表口径:收集阶段排除 wms_stock_static_check_task 已有记录(未删除)的 stock_id(已进入静态已盘点商品);任务创建成功后把本次命中的 stock_id 批量写入该表(task_time=创建时间),写入失败仅记告警日志、不影响主流程。", + "权限口径:免 API 权限(isNeedAuth=false)、免仓库有效期鉴权、必须登录(isNeedLogin=true);patternCreate 为写操作,不在免日志清单(_noNeedLog)中,记录操作日志(patternList 为查询类,免日志)。", + "单号生成:check_no=PD+YYYYMMDD+6 位序号(全局递增不按仓库隔离),并发下撞 uk_check_no 唯一键自动重取重试(最多 5 次)。" + ] + }, + { + "method": "stock.check.addLocationDetail", + "description": "批量添加库位明细(兼容入口,薄封装转调 addDetail 的库位ID直查路径):入参 id(盘点任务ID)+ location_ids(库位ID列表,兼容 locationIds 驼峰写法);服务端直接按 wms_location_space.id+warehouse_id 查库校验,不经过 space_code 二次解析;转发前保留旧口径参数校验(任务ID不能为空、库位ID不能为空、单次上限 200),任务存在性/状态/类型分派校验统一由 addDetail 处理;幂等添加 scope_type=location 明细行,已存在的同库位明细自动跳过;返回结构从 addDetail 映射为 { added, skipped, invalid_location_ids, total_items }(过滤 invalid_locations/invalid_stock_ids),保持原返回口径不变。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(正常登录 token,携带仓库上下文)" + } + ], + "params": [ + { + "name": "id", + "type": "number", + "required": true, + "source": "body", + "description": "盘点任务ID" + }, + { + "name": "location_ids", + "type": "array", + "required": true, + "source": "body", + "description": "库位ID列表(wms_location_space.id,单次上限 200;兼容 locationIds 驼峰写法,location_ids 优先)" + } + ], + "response": [ + { + "name": "added", + "type": "number", + "required": true, + "description": "本次新增明细数" + }, + { + "name": "skipped", + "type": "number", + "required": true, + "description": "已存在被跳过(幂等)的盘点项数" + }, + { + "name": "invalid_location_ids", + "type": "array", + "required": true, + "description": "无效库位ID列表(按 wms_location_space.id 直查当前仓库不存在)" + }, + { + "name": "total_items", + "type": "number", + "required": true, + "description": "重算后的明细总行数" + } + ], + "errors": [ + { + "code": 400, + "message": "盘点任务ID不能为空 / 请至少选择一个库位 / 单次最多添加 200 个库位 / 盘点任务不存在 / 当前状态(非 created/rejected)不允许添加明细 / 当前盘点类型按商品盘点,不能添加库位明细" + }, + { + "code": 500, + "message": "服务器内部错误" + } + ], + "notes": [ + "兼容入口:保留旧接口名与返回结构({ added, skipped, invalid_location_ids, total_items }),内部转调 addDetail 库位ID直查路径(stockIds/locations 置空、传 locationIds),返回结构过滤 invalid_locations/invalid_stock_ids 保持原口径。", + "转发前校验:任务ID不能为空、库位ID不能为空(请至少选择一个库位)、单次上限 200(超过报『单次最多添加 200 个库位』);任务不存在/状态不允许/商品任务不可添加库位明细由 addDetail 透传同款错误。", + "ID 直查:按 wms_location_space.id+warehouse_id 直查校验(仓库隔离),查不到的 ID 记入 invalid_location_ids(不报错);幂等按 check_id+location_code(uk_check_location 唯一索引),已存在同库位明细跳过。" + ] } ] },