From 97434161871a31162b0744262174735b09d22ed0 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Tue, 6 Oct 2026 03:24:41 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E7=9B=98=E7=82=B9=E4=BD=9C=E4=B8=9A?= =?UTF-8?q?=E6=95=B0=E6=8D=AE=E6=8E=A5=E5=8F=A3=E6=94=B9=E9=80=A0=E4=B8=8E?= =?UTF-8?q?=E8=B4=A6=E9=9D=A2=E5=8F=A3=E5=BE=84=E5=85=A8=E9=87=8F=E7=BB=9F?= =?UTF-8?q?=E4=B8=80=EF=BC=88=E5=8F=AF=E7=94=A8+=E9=94=81=E5=AE=9A?= =?UTF-8?q?=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - workData 三视图:goods 视图 locations=商品所在全部库位列表(明盘每库位 system_quantity 账面/quantity 盘点、盲盘只显示库位);space 视图同口径;新增 workDataSpaceDetails 分页版 - workDataDetail 增加 goods 分支(单行结构,复用视图构建器);detail 补 profit_total/loss_total 差异汇总 - 库位账面全量统一为 SUM(available_quantity+locked_quantity)(可用+锁定)并标记 locked_quantity:result/report/finish/detail/addDetail 拆行快照与作业视图一致 - 未盘行不误显盘亏:diff/is_diff 仅存在作业记录时计算 - 文档 methods/system.json 0.3.249 + changes 变更记录,开发/生产库已回填 --- app/model/stock_check_detail.js | 4 +- app/model/stock_check_record.js | 8 +- app/service/systemMethods/stock/check.js | 219 ++- app/service/systems/stock_check.js | 1301 +++++++++++++---- ...0000-add-is-empty-to-stock-check-record.js | 25 + ...02170000-split-goods-detail-by-location.js | 47 + methods/changes/system.json | 104 ++ methods/system.json | 617 +++++++- 8 files changed, 2010 insertions(+), 315 deletions(-) create mode 100644 database/migrations/20261002160000-add-is-empty-to-stock-check-record.js create mode 100644 database/migrations/20261002170000-split-goods-detail-by-location.js diff --git a/app/model/stock_check_detail.js b/app/model/stock_check_detail.js index d621bd9..58be00d 100644 --- a/app/model/stock_check_detail.js +++ b/app/model/stock_check_detail.js @@ -91,8 +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' ] }, + { name: 'uk_check_stock_location', unique: true, fields: [ 'check_id', 'stock_id', 'location_id' ] }, + { name: 'idx_check_location', fields: [ 'check_id', 'location_code' ] }, ], }); diff --git a/app/model/stock_check_record.js b/app/model/stock_check_record.js index 42bcf7a..f556d71 100644 --- a/app/model/stock_check_record.js +++ b/app/model/stock_check_record.js @@ -10,7 +10,7 @@ * @return {import('sequelize').ModelCtor} Sequelize 模型。 */ module.exports = app => { - const { BIGINT, STRING, INTEGER, DATE } = app.Sequelize; + const { BIGINT, STRING, INTEGER, DATE, BOOLEAN } = app.Sequelize; const StockCheckRecord = app.model.define('wms_stock_check_record', { id: { @@ -49,6 +49,12 @@ module.exports = app => { allowNull: true, comment: '未知商品名称快照(缺省为条码);已知商品为空', }, + is_empty: { + type: BOOLEAN, + allowNull: false, + defaultValue: false, + comment: '是否空库位标记(true=确认库位为空,stock_id/barcode/item_name 均为空、quantity=0)', + }, location_id: { type: BIGINT(20).UNSIGNED, allowNull: true, diff --git a/app/service/systemMethods/stock/check.js b/app/service/systemMethods/stock/check.js index 408a419..23bcc99 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; -/** 全部 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'; +/** 全部 23 个 method 名(免权限/免鉴权清单共用) */ +const ALL_METHOD_NAMES = 'create,list,addDetail,addLocationDetail,detailDelete,detail,result,workData,workDataSpaceDetails,workDataDetail,report,markEmpty,recordList,recordDelete,recheckClearLocation,finish,submit,cancel,audit,batchDelete,export,exportTaskProgress,patternList,patternCreate'; /** * 系统方法层:stock.check(库存盘点模块接口包装层)。 @@ -24,7 +24,7 @@ class StockCheckMethodService extends MainService { // 免权限方法列表:全部 20 个方法免 API 权限校验(与 stock/transaction.js 口径一致) const _noNeedRight = ALL_METHOD_NAMES; // 免日志方法列表:查询类与导出类不记录操作日志(recordDelete/patternCreate 为写操作,保留操作日志) - const _noNeedLog = 'list,detail,result,workData,recordList,export,exportTaskProgress,patternList'; + const _noNeedLog = 'list,detail,result,workData,workDataSpaceDetails,workDataDetail,recordList,export,exportTaskProgress,patternList'; // 免鉴权(仓库有效期检查)方法列表:全部方法免鉴权(与 stock/transaction.js 口径一致) const _noNeedAuth = ALL_METHOD_NAMES; this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); @@ -32,22 +32,24 @@ class StockCheckMethodService extends MainService { /** * 统一调用库存盘点业务服务,并捕获业务错误码。 + * 成功/失败均按统一 data 层封装:{ flag, code, message, data }, + * 与项目 toSuccess/toFailure 常规口径一致(业务数据整体放入 data)。 * * @param {Function} fn 业务调用函数。 * @param {string} fallbackMessage 兜底错误文案。 - * @return {Promise} 统一 success/fail 包装。 + * @return {Promise} 统一 { flag, code, message, data } 包装。 */ async _call(fn, fallbackMessage) { try { const result = await fn(); - return this.success('ok', result); + return { flag: 'success', code: 1, message: 'ok', data: result }; } catch (error) { const code = Number(error && error.code); if (Number.isInteger(code) && code >= 400 && code < 600) { - return this.fail(error.message || fallbackMessage, {}, code); + return { flag: 'failure', code, message: error.message || fallbackMessage, data: null }; } this.ctx.logger.error(`[stock.check] ${fallbackMessage}: ${error && error.message ? error.message : error}`); - return this.fail('服务器内部错误', {}, 500); + return { flag: 'failure', code: 500, message: '服务器内部错误', data: null }; } } @@ -282,15 +284,16 @@ class StockCheckMethodService extends MainService { } /** - * 拉取盘点任务明细(任务范围行:商品或库位)。 - * 只返回范围行,不包含盘点作业聚合与作业记录(作业聚合见 result; - * 作业记录的 barcode/item_name/images 口径见 result/recordList)。 + * 拉取盘点任务详情(只返回任务本身信息)。 + * 不返回明细范围行(明细范围行/盘点结果请调用 result)、作业记录(recordList) + * 与盘点作业数据(workData)。 * * @param {Object} data 请求体。 * @param {number} data.id 盘点任务ID。 - * @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。 + * @return {Promise} 统一 success 包装,返回 { check }; + * check 为盘点主表信息(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)。 */ async detail(data = {}) { const { ctx } = this; @@ -329,30 +332,106 @@ class StockCheckMethodService extends MainService { } /** - * 拉取盘点作业数据(单接口三视图,view 入参驱动)。 + * 拉取盘点作业数据(视图由任务类型与 is_goods 驱动)。 * warehouse_id 由服务端从当前上下文自动注入,前端无需传递。 + * 视图规则:任务范围为库位(type=location/all)时一律按库位视图返回(无视 view/is_goods); + * 任务范围为商品(type=goods/store)时默认聚合库位视图(space), + * 仅传入 is_goods=true 时按商品视图(goods)返回。 + * 分页:data.pagination.{page,pageSize}(与 stock.check.list 口径一致, + * 未传或非法时默认 page=1、pageSize=20,上限 200); + * 响应 rows 为当前页行、total 为全部行数,并返回 page/pageSize。 + * 不返回任务主表信息(check)——任务信息请调用 stock.check.detail; + * 响应返回 view(服务端实际解析出的视图类型 location/goods/space),供调用方判断 rows 行结构。 * * @param {Object} data 请求体。 * @param {number} data.id 盘点任务ID。 - * @param {string} data.view 视图类型:location/goods/space。 - * @return {Promise} 统一 success 包装,返回 { check, rows, total };rows 结构按 view 不同: + * @param {boolean} [data.is_goods] 商品任务是否按商品视图返回(true=goods); + * 缺省 false=聚合库位视图(space);库位任务无视该参数(兼容 isGoods 驼峰写法)。 + * @param {string} [data.keyword] 关键字(仅库位任务 location 视图生效):按行 + * location_code/location_name 模糊匹配(不区分大小写)过滤任务明细后返回;非库位任务忽略。 + * @param {Object} [data.pagination] 分页配置 { page, pageSize }。 + * @return {Promise} 统一 success 包装,返回 { view, rows, total, page, pageSize };rows 结构按视图不同: * location=库位结构(任务库位范围行为列表,行内挂 goods/unknown 作业记录子列表); * goods=商品结构(任务商品范围行为列表,行内挂按库位聚合的 locations 作业记录, * 明盘返回数量与差异,盲盘不返回数量字段); - * space=商品结构(任务商品所在库位为列表,按拣货路径排序,行内挂该库位的任务商品, + * space=聚合库位结构(任务商品所在库位为列表,按拣货路径排序,行内挂该库位的任务商品, * 明盘返回账面/实盘数量,盲盘不返回数量字段)。 */ async workData(data = {}) { const { ctx } = this; const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; - const { id, view } = data || {}; + const { + id, + is_goods: isGoodsSnake, + isGoods: isGoodsCamel, + keyword, + pagination, + } = data || {}; + const isGoods = isGoodsSnake !== undefined ? isGoodsSnake : isGoodsCamel; return this._call( - () => this.service.systems.stockCheck.workData({ warehouseId, id, view }), + () => this.service.systems.stockCheck.workData({ warehouseId, id, isGoods, keyword, pagination }), '拉取盘点作业数据失败' ); } + /** + * 拉取盘点作业数据(space 视图分页版)。 + * warehouse_id 由服务端从当前上下文自动注入,前端无需传递。 + * 行结构与 workData space 视图行一致(id=库位ID/space_code/custom_barcode/custom_name/goods, + * goods 行含 detail_id/stock_id/item_code/item_name/spec/store_id/store_name/barcode/images/ + * record_ids,明盘另含 system_quantity/checked_quantity,status=checked/unchecked); + * 传入 location_id 时只返回该库位行(total=1),不传时按分页返回全部库位行。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 盘点任务ID。 + * @param {number} [data.location_id] 库位ID(兼容 locationId 驼峰写法)。 + * @param {Object} [data.pagination] 分页配置 { page, pageSize }。 + * @return {Promise} 统一 success 包装,返回 { view:'space', rows, total, page, pageSize }。 + */ + async workDataSpaceDetails(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const { + id, + location_id: locationIdSnake, + locationId: locationIdCamel, + pagination, + } = data || {}; + const locationId = locationIdSnake !== undefined ? locationIdSnake : locationIdCamel; + + return this._call( + () => this.service.systems.stockCheck.workDataSpaceDetails({ warehouseId, id, locationId, pagination }), + '拉取盘点作业数据失败' + ); + } + + /** + * 拉取单条盘点明细的作业数据(workData 单行版)。 + * warehouse_id 由服务端从当前上下文自动注入,前端无需传递。 + * 按明细范围类型分流,均返回单行对象(与对应视图单行结构一致): + * 库位明细(scope_type=location)行结构同 workData location 视图单行 + * (detail_id/location_id/location_code/location_name/status/has_unknown/is_empty/ + * checked_at/checkers/goods);商品明细(scope_type=goods)行结构同 workData 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,盲盘不含数量字段)。 + * + * @param {Object} data 请求体。 + * @param {number} data.detail_id 盘点明细ID(库位范围行或商品范围行;兼容 detailId 驼峰写法)。 + * @return {Promise} 统一 success 包装,data 为单行作业数据(结构随明细范围类型)。 + */ + async workDataDetail(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const { detail_id: detailIdSnake, detailId: detailIdCamel } = data || {}; + const detailId = detailIdSnake !== undefined ? detailIdSnake : detailIdCamel; + + return this._call( + () => this.service.systems.stockCheck.workDataDetail({ warehouseId, detailId }), + '拉取盘点明细作业数据失败' + ); + } + /** * 盘点作业上报(覆盖式)。 * 同明细 + 同商品 + 同库位编码重复上报时更新已有记录(未传库位归入"无库位"分组,location_code 为 null),不再新增; @@ -376,7 +455,16 @@ class StockCheckMethodService extends MainService { 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, stock_id: stockId, barcode, item_name: itemName } = data || {}; + const { + id, + detail_id: detailId, + location, + quantity, + stock_id: stockId, + barcode, + item_name: itemName, + is_empty: isEmpty, + } = data || {}; return this._call( () => this.service.systems.stockCheck.report({ @@ -388,6 +476,7 @@ class StockCheckMethodService extends MainService { stockId, barcode, itemName, + is_empty: isEmpty, checkerId, checkerName, }), @@ -395,6 +484,37 @@ class StockCheckMethodService extends MainService { ); } + /** + * 标记库位为空(库位盘点模式专属)。 + * warehouse_id 由服务端从当前上下文自动注入;仅任务范围为库位(type=location/all)时允许, + * 非库位任务报 400;状态仅 approved/checking;明细必须属于本任务且为库位范围行。 + * 行为与 report(is_empty=true) 一致:写/更新空标记记录、清除该明细商品记录、重算汇总。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 盘点任务ID。 + * @param {number} data.detail_id 库位明细ID。 + * @return {Promise} 统一 success 包装,返回 + * { record, detail_id, mode, total_items, checked_items, diff_items, detail_status }。 + */ + async markEmpty(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 } = data || {}; + + return this._call( + () => this.service.systems.stockCheck.markEmpty({ + warehouseId, + id, + detailId, + checkerId, + checkerName, + }), + '标记空库位失败' + ); + } + /** * 拉取盘点作业记录列表。 * 至少传 id(盘点任务ID)或 detail_id(明细ID)之一;按记录 id 倒序,返回分页结果。 @@ -424,30 +544,69 @@ class StockCheckMethodService extends MainService { } /** - * 删除盘点作业记录。 + * 批量删除盘点作业记录(按行清除盘点信息)。 * 仅主表状态 approved/checking 允许删除;删除后重算盘点进度汇总,主表状态不回退。 + * 查不到的记录 ID 计入 skipped_ids 不报错;deleted_ids/skipped_ids 保持入参顺序。 * * @param {Object} data 请求体。 * @param {number} data.id 盘点任务ID。 - * @param {number} data.record_id 作业记录ID(兼容 recordId 写法)。 - * @param {number} [data.recordId] 作业记录ID(驼峰别名)。 - * @return {Promise} 统一 success 包装,返回 { record_id, deleted, ...summary }。 + * @param {Array|number} data.record_ids 作业记录ID数组(单次上限 200; + * 兼容 recordIds 驼峰写法;兼容旧版单值 record_id 写法,单值自动转数组)。 + * @return {Promise} 统一 success 包装,返回 + * { deleted_count, deleted_ids, skipped_ids, total_items, checked_items, diff_items, detail_status }; + * 注意:本接口已由旧版单值删除升级为批量删除,响应结构由旧版 + * { record_id, deleted, ...summary } 变更为上述结构。 */ async recordDelete(data = {}) { const { ctx } = this; const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; - const { id, record_id: recordIdRaw, recordId: recordIdAlias } = data || {}; - const recordId = recordIdRaw !== undefined && recordIdRaw !== null && recordIdRaw !== '' - ? recordIdRaw - : recordIdAlias; + const { + id, + record_ids: recordIdsRaw, + recordIds: recordIdsArrayAlias, + recordId: recordIdSingleAlias, + record_id: recordIdSingleSnake, + } = data || {}; + const recordIds = recordIdsRaw !== undefined + ? recordIdsRaw + : (recordIdsArrayAlias !== undefined + ? recordIdsArrayAlias + : (recordIdSingleAlias !== undefined ? recordIdSingleAlias : recordIdSingleSnake)); return this._call( () => this.service.systems.stockCheck.recordDelete({ warehouseId, id, - recordId, + recordIds, }), - '删除盘点作业记录失败' + '批量删除盘点作业记录失败' + ); + } + + /** + * 重盘清除库位(按库位清除盘点信息,库位盘点模式专属)。 + * 传入任务ID与库位ID,清除该库位范围内明细的全部作业记录(含空库位标记),该库位回到未盘; + * 仅任务范围为库位(type=location/all)且状态 approved/checking 时允许,非库位任务报 400。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 盘点任务ID。 + * @param {number} data.location_id 库位ID(wms_location_space.id;兼容 locationId 驼峰写法)。 + * @return {Promise} 统一 success 包装,返回 + * { detail_id, location_id, deleted_count, total_items, checked_items, diff_items, detail_status }。 + */ + async recheckClearLocation(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const { id, location_id: locationIdRaw, locationId: locationIdAlias } = data || {}; + const locationId = locationIdRaw !== undefined ? locationIdRaw : locationIdAlias; + + return this._call( + () => this.service.systems.stockCheck.recheckClearLocation({ + warehouseId, + id, + locationId, + }), + '重盘清除库位失败' ); } diff --git a/app/service/systems/stock_check.js b/app/service/systems/stock_check.js index 0e085be..2a76b77 100644 --- a/app/service/systems/stock_check.js +++ b/app/service/systems/stock_check.js @@ -12,8 +12,6 @@ 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数量 */ @@ -246,7 +244,7 @@ class StockCheckService extends Service { */ async _recalcCheckSummary(checkId) { const { ctx } = this; - const { fn, col, Op } = ctx.app.Sequelize; + const { fn, col, Op, literal } = ctx.app.Sequelize; const checkIdNumber = Number(checkId); const detailWhere = { check_id: checkIdNumber }; @@ -268,7 +266,7 @@ class StockCheckService extends Service { }); const recordRows = await ctx.model.StockCheckRecord.findAll({ where: { check_id: checkIdNumber }, - attributes: [ 'detail_id', 'stock_id', 'barcode', 'item_name', 'quantity' ], + attributes: [ 'detail_id', 'stock_id', 'barcode', 'item_name', 'quantity', 'is_empty' ], raw: true, }); @@ -276,8 +274,14 @@ class StockCheckService extends Service { const checkedQuantityByDetail = new Map(); const stockQuantityByDetail = new Map(); const unknownQuantityByDetail = new Map(); + const emptyDetailIds = new Set(); for (const record of recordRows) { const detailId = Number(record.detail_id); + // 空库位标记:不参与商品/数量聚合(差异按该库位账面单独判断) + if (record.is_empty) { + emptyDetailIds.add(detailId); + continue; + } const stockId = Number(record.stock_id); const quantity = Number(record.quantity) || 0; checkedQuantityByDetail.set(detailId, (checkedQuantityByDetail.get(detailId) || 0) + quantity); @@ -306,7 +310,7 @@ class StockCheckService extends Service { byStock.set(stockId, agg); } - // 库位行账面:wms_storage 按 (space_id, stock_id) SUM(quantity),并附到按商品聚合 + // 库位行账面:wms_storage 按 (space_id, stock_id) SUM(可用+锁定),并附到按商品聚合 const storageQuantityMap = new Map(); const locationDetailRows = detailRows.filter(row => (row.scope_type || 'goods') === 'location'); if (locationDetailRows.length > 0) { @@ -332,7 +336,7 @@ class StockCheckService extends Service { attributes: [ 'space_id', 'stock_id', - [ fn('SUM', col('quantity')), 'totalQuantity' ], + [ literal('SUM(available_quantity + locked_quantity)'), 'totalQuantity' ], ], group: [ 'space_id', 'stock_id' ], raw: true, @@ -357,17 +361,59 @@ class StockCheckService extends Service { } } + // 空库位标记明细的库位账面汇总(差异口径:账面有库存即盘亏) + const emptyLocationSystemMap = new Map(); + if (emptyDetailIds.size > 0) { + const emptyDetailRows = detailRows.filter(row => emptyDetailIds.has(Number(row.id))); + const emptyLocationIds = [ ...new Set(emptyDetailRows + .filter(row => row.location_id) + .map(row => Number(row.location_id))) ]; + if (emptyLocationIds.length > 0) { + const emptyStorageRows = await ctx.model.Storage.findAll({ + where: { space_id: { [Op.in]: emptyLocationIds } }, + attributes: [ + 'space_id', + [ literal('SUM(available_quantity + locked_quantity)'), 'totalQuantity' ], + ], + group: [ 'space_id' ], + raw: true, + }); + const systemBySpace = new Map(emptyStorageRows.map(row => [ + Number(row.space_id), + Number(row.totalQuantity) || 0, + ])); + for (const emptyRow of emptyDetailRows) { + const emptyLocationId = emptyRow.location_id ? Number(emptyRow.location_id) : 0; + emptyLocationSystemMap.set( + Number(emptyRow.id), + emptyLocationId > 0 ? (systemBySpace.get(emptyLocationId) || 0) : 0 + ); + } + } else { + for (const emptyRow of emptyDetailRows) { + emptyLocationSystemMap.set(Number(emptyRow.id), 0); + } + } + } + // 差异明细数:明细行内任一商品「实盘合计 ≠ 账面」即该行有差异,按明细去重计数; - // 未知商品(stock_id 为空)无账面,实盘 > 0 即盘盈、必然计入差异 + // 未知商品(stock_id 为空)无账面,实盘 > 0 即盘盈、必然计入差异; + // 空库位标记明细:账面有库存即盘亏差异(标记空与实际不符) let diffItems = 0; for (const detailRow of detailRows) { const detailId = Number(detailRow.id); + const scopeType = (detailRow.scope_type || 'goods') === 'location' ? 'location' : 'goods'; + if (scopeType === 'location' && emptyDetailIds.has(detailId)) { + if ((emptyLocationSystemMap.get(detailId) || 0) > 0) { + diffItems++; + } + continue; + } 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); @@ -1173,7 +1219,7 @@ class StockCheckService extends Service { invalidStockIds, } = params; const { ctx } = this; - const { Op } = ctx.app.Sequelize; + const { Op, literal } = ctx.app.Sequelize; // 按 stock_ids 查询库存商品快照(限定当前仓库,自动过滤已删除) const stockRows = await ctx.model.StockWarehouse.findAll({ @@ -1185,7 +1231,7 @@ class StockCheckService extends Service { }); const stockMap = new Map(stockRows.map(item => [ Number(item.id), item ])); - // 幂等:已存在同 stock_id 的明细跳过 + // 幂等:已存在同 stock_id 的明细跳过(同商品整体跳过,兼容历史单行与拆行) const existingRows = await ctx.model.StockCheckDetail.findAll({ where: { check_id: checkId, @@ -1196,6 +1242,44 @@ class StockCheckService extends Service { }); const existingStockIds = new Set(existingRows.map(item => Number(item.stock_id))); + // 商品在本仓库的启用库存库位(按库位拆分明细行:商品任务必须按库位盘点, + // 一个商品多个库位对应多行,各行账面 = 该库位库存 SUM(可用+锁定);无库存库位商品不可盘点) + const storageRows = await ctx.model.Storage.findAll({ + where: { + warehouse_id: Number(warehouseId), + stock_id: { [Op.in]: numericStockIds }, + is_enabled: 1, + }, + attributes: [ + 'stock_id', + 'space_id', + [ literal('SUM(available_quantity + locked_quantity)'), 'totalQuantity' ], + ], + group: [ 'stock_id', 'space_id' ], + raw: true, + }); + const stockStorageMap = new Map(); + for (const storageRow of storageRows) { + const stockId = Number(storageRow.stock_id); + if (!stockStorageMap.has(stockId)) { + stockStorageMap.set(stockId, []); + } + stockStorageMap.get(stockId).push({ + spaceId: Number(storageRow.space_id), + quantity: Number(storageRow.totalQuantity) || 0, + }); + } + const storageSpaceIds = [ ...new Set(storageRows.map(row => Number(row.space_id))) ]; + let spaceCodeMap = new Map(); + if (storageSpaceIds.length > 0) { + const spaceRows = await ctx.model.LocationSpace.findAll({ + where: { id: { [Op.in]: storageSpaceIds } }, + attributes: [ 'id', 'space_code' ], + raw: true, + }); + spaceCodeMap = new Map(spaceRows.map(item => [ Number(item.id), String(item.space_code || '').trim() ])); + } + // 货主限制:任务货主非空时,商品货主必须与任务货主一致(限制非本货主商品加入盘点) const checkStoreId = check.store_id !== null && check.store_id !== undefined ? Number(check.store_id) @@ -1215,19 +1299,27 @@ class StockCheckService extends Service { 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, - }); + const stockLocations = stockStorageMap.get(stockId) || []; + if (stockLocations.length === 0) { + // 商品在仓库中没有启用库存库位 → 不可加入盘点 + invalidStockIds.push(stockId); + continue; + } + for (const stockLocation of stockLocations) { + 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: stockLocation.quantity, + location_id: stockLocation.spaceId, + location_code: spaceCodeMap.get(stockLocation.spaceId) || null, + }); + } } } @@ -1504,24 +1596,19 @@ class StockCheckService extends Service { } /** - * 拉取盘点任务明细(任务范围行:商品或库位)。 - * 只返回范围行原始字段,不包含盘点作业聚合结果(作业聚合请调用 result); - * 商品行(scope_type=goods)额外挂载 stock 对象(stock_warehouse 全局商品信息: - * item_code/item_name/sku_property/库存数量/管理标识/条码 barcodes/图片 image_url 等, - * 来自 stockWarehouse.getStockDetails,未命中为 null)。 + * 拉取盘点任务详情(只返回任务本身信息)。 + * 不返回明细范围行与盘点作业聚合(明细范围行/盘点结果请调用 result, + * 作业记录明细请调用 recordList,盘点作业数据请调用 workData)。 * * @param {Object} params 查询参数。 * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 * @param {number} params.id 盘点任务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 挂载。 + * @return {Promise} { check },check 为盘点主表信息(_formatCheckRow 口径), + * 并附 profit_total(盘盈合计数量)/loss_total(盘亏合计数量,正数口径,与 finish 一致)。 * @throws {Error} 任务不存在时抛出业务错误(错误码 400)。 */ async detail(params = {}) { const { warehouseId, id } = params; - const { ctx } = this; const checkId = Number(id); if (!Number.isInteger(checkId) || checkId <= 0) { @@ -1533,35 +1620,15 @@ class StockCheckService extends Service { throw this.createBusinessError('盘点任务不存在'); } - const detailRows = await ctx.model.StockCheckDetail.findAll({ - where: { check_id: checkId, warehouse_id: Number(warehouseId) }, - order: [[ 'id', 'ASC' ]], - 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; - } - } - } + // 数量差异汇总(盘盈/盘亏数量,口径与 finish 一致;无作业记录时均为 0) + const diffSummary = await this._calcQuantityDiffSummary(checkId); return { - check: this._formatCheckRow(check.get({ plain: true })), - rows, - total: rows.length, + check: { + ...this._formatCheckRow(check.get({ plain: true })), + profit_total: diffSummary.profit_total, + loss_total: diffSummary.loss_total, + }, }; } @@ -1580,7 +1647,7 @@ class StockCheckService extends Service { * (按库位聚合 [{ 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 为行内合计、 + * 账面数量查 wms_storage SUM(available_quantity+locked_quantity)(=可用+锁定),行级 checked_quantity 为行内合计、 * diff_quantity 为行内各商品差异代数和; * 未知商品单独输出行级 unknown_items [{ barcode, item_name, checked_quantity }] * (无账面,差异 = 实盘 - 0 = 盘盈,已计入行级 checked_quantity/diff_quantity/is_diff)。 @@ -1624,33 +1691,6 @@ 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)并关联 @@ -1714,7 +1754,7 @@ class StockCheckService extends Service { async _buildDetailAggregations(params = {}) { const { detailRows, recordRows } = params; const { ctx } = this; - const { Op, fn, col } = ctx.app.Sequelize; + const { Op, literal } = ctx.app.Sequelize; // 按明细聚合作业记录 const recordsByDetail = new Map(); @@ -1757,7 +1797,7 @@ class StockCheckService extends Service { stockMap = new Map(stockRows.map(item => [ Number(item.id), item ])); } - // 库位行账面:wms_storage 按 (space_id, stock_id) SUM(quantity) + // 库位行账面:wms_storage 按 (space_id, stock_id) SUM(可用+锁定) const storageQuantityMap = new Map(); if (locationRows.length > 0 && stockIds.size > 0) { const locationIds = [ ...new Set(locationRows @@ -1772,7 +1812,7 @@ class StockCheckService extends Service { attributes: [ 'space_id', 'stock_id', - [ fn('SUM', col('quantity')), 'totalQuantity' ], + [ literal('SUM(available_quantity + locked_quantity)'), 'totalQuantity' ], ], group: [ 'space_id', 'stock_id' ], raw: true, @@ -1786,12 +1826,12 @@ class StockCheckService extends Service { } } - return detailRows.map(detailRow => this._formatDetailAggregationRow({ + return Promise.all(detailRows.map(detailRow => this._formatDetailAggregationRow({ detailRow, recordsByDetail, stockMap, storageQuantityMap, - })); + }))); } /** @@ -1809,8 +1849,10 @@ class StockCheckService extends Service { * @param {Map} params.storageQuantityMap 库位商品账面数量映射(键 `${space_id}_${stock_id}`)。 * @return {Object} 格式化后的明细行。 */ - _formatDetailAggregationRow(params = {}) { + async _formatDetailAggregationRow(params = {}) { const { detailRow, recordsByDetail, stockMap, storageQuantityMap } = params; + const { ctx } = this; + const { literal } = ctx.app.Sequelize; const detailRowId = Number(detailRow.id); const scopeType = (detailRow.scope_type || 'goods') === 'location' ? 'location' : 'goods'; const detailRecords = recordsByDetail.get(detailRowId) || []; @@ -1850,9 +1892,13 @@ class StockCheckService extends Service { quantity: locationGroup.quantity, })); - // 未知商品(stock_id 为空)按 barcode 维度归组(无账面,差异 = 实盘 - 0 = 盘盈) + // 未知商品(stock_id 为空)按 barcode 维度归组(无账面,差异 = 实盘 - 0 = 盘盈); + // 空库位标记记录不参与未知商品聚合 const unknownByBarcode = new Map(); for (const record of detailRecords) { + if (record.is_empty) { + continue; + } const recordStockId = Number(record.stock_id); if (Number.isInteger(recordStockId) && recordStockId > 0) { continue; @@ -1898,7 +1944,34 @@ class StockCheckService extends Service { }; } - // 库位行:按商品聚合记录,账面从 wms_storage 取(location_id 为空时账面按 0) + // 库位行:按商品聚合记录,账面从 wms_storage 取(location_id 为空时账面按 0); + // 空库位标记:无商品聚合,账面有库存即盘亏(差异 = -账面总量) + const isEmptyLocation = detailRecords.some(record => record.is_empty); + const locationId = detailRow.location_id !== null && detailRow.location_id !== undefined + ? Number(detailRow.location_id) + : 0; + let locationSystemTotal = 0; + if (isEmptyLocation && locationId > 0) { + const emptyStorageRows = await ctx.model.Storage.findAll({ + where: { space_id: locationId }, + attributes: [[ literal('SUM(available_quantity + locked_quantity)'), 'totalQuantity' ]], + raw: true, + }); + locationSystemTotal = Number(emptyStorageRows[0] && emptyStorageRows[0].totalQuantity) || 0; + } + if (isEmptyLocation) { + return { + ...base, + is_empty: true, + checked_quantity: 0, + diff_quantity: locationSystemTotal > 0 ? -locationSystemTotal : 0, + is_diff: locationSystemTotal > 0 ? 1 : 0, + status: 'checked', + stocks: [], + unknown_items: unknownItems, + }; + } + const quantityByStock = new Map(); for (const record of detailRecords) { const stockId = Number(record.stock_id); @@ -1909,9 +1982,6 @@ class StockCheckService extends Service { 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; @@ -1950,6 +2020,7 @@ class StockCheckService extends Service { return { ...base, + is_empty: false, stocks, unknown_items: unknownItems, checked_quantity: detailRecords.length > 0 ? checkedQuantity : null, @@ -2022,12 +2093,77 @@ class StockCheckService extends Service { * @param {string} [params.barcode] 扫描到的条码/编码(未传 stock_id 时按条码匹配系统商品, * 未命中记为未知商品)。 * @param {string} [params.itemName] 未知商品名称(缺省为 barcode;已知商品忽略)。 + * @param {boolean} [params.is_empty] 空库位标记(仅库位盘点明细支持;标记空时商品/条码/数量均不参与)。 * @param {number} [params.checkerId] 盘点人账户ID(由方法层从上下文注入)。 * @param {string} [params.checkerName] 盘点人名称快照(由方法层从上下文注入)。 * @return {Promise} { record, detail_id, mode, total_items, checked_items, diff_items, detail_status }; * record 为作业记录全字段(含 barcode/item_name)。 * @throws {Error} 状态不允许或参数非法时抛出业务错误(错误码 400)。 */ + + /** + * 标记库位为空(库位盘点模式专属,转调 report 的空库位标记口径)。 + * 仅任务范围为库位(type=location/all)时允许:非库位任务报 400; + * 状态仅 approved/checking;明细必须属于本任务且为库位范围行(scope_type=location)。 + * 行为与 report(is_empty=true) 完全一致:写/更新空标记记录(stock_id/barcode/item_name 为空、 + * quantity=0、is_empty=1)、清除该明细商品记录、主表 approved→checking、 + * 重算 checked_items/diff_items/detail_status、写入操作日志。 + * + * @param {Object} params 查询参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {number} params.id 盘点任务ID。 + * @param {number} params.detailId 库位明细ID。 + * @param {number} [params.checkerId] 盘点人账户ID(由方法层从上下文注入)。 + * @param {string} [params.checkerName] 盘点人名称快照(由方法层从上下文注入)。 + * @return {Promise} 与 report 一致:{ record, detail_id, mode, total_items, checked_items, diff_items, detail_status }。 + * @throws {Error} 任务不存在、状态不允许、非库位任务、明细不存在或明细非库位行时抛出业务错误(错误码 400)。 + */ + async markEmpty(params = {}) { + const { warehouseId, id, detailId, checkerId, checkerName } = params; + + const checkId = Number(id); + const detailRowId = Number(detailId); + if (!Number.isInteger(checkId) || checkId <= 0) { + throw this.createBusinessError('盘点任务ID不能为空'); + } + if (!Number.isInteger(detailRowId) || detailRowId <= 0) { + throw this.createBusinessError('盘点明细ID不能为空'); + } + + const check = await this._findCheck(warehouseId, checkId); + if (!check) { + throw this.createBusinessError('盘点任务不存在'); + } + if (!REPORT_ALLOWED_STATUSES.includes(check.status)) { + throw this.createBusinessError(`当前状态(${check.status})不允许盘点作业`); + } + const normalizedType = String(check.type || '').trim(); + if (normalizedType !== 'location' && normalizedType !== 'all') { + throw this.createBusinessError('仅库位盘点任务支持空库位标记'); + } + + // 明细必须属于本任务且为库位范围行(scope_type=location) + const detail = await this.ctx.model.StockCheckDetail.findOne({ + where: { id: detailRowId, check_id: checkId, warehouse_id: Number(warehouseId) }, + }); + if (!detail) { + throw this.createBusinessError('盘点明细不存在'); + } + if ((detail.scope_type || 'goods') !== 'location') { + throw this.createBusinessError('仅库位盘点明细支持空库位标记'); + } + + // 转调 report 空库位标记口径(查重/互斥/汇总/日志统一) + return this.report({ + warehouseId, + id: checkId, + detailId: detailRowId, + is_empty: true, + checkerId, + checkerName, + }); + } + async report(params = {}) { const { warehouseId, @@ -2038,11 +2174,15 @@ class StockCheckService extends Service { stockId, barcode, itemName, + is_empty: isEmptyInput, checkerId, checkerName, } = params; const { ctx } = this; + // 空库位标记:仅库位明细行支持;标记空时商品/条码/数量均不参与(数量恒为 0) + const normalizedIsEmpty = isEmptyInput === true || isEmptyInput === 'true' || isEmptyInput === 1; + const checkId = Number(id); const detailRowId = Number(detailId); if (!Number.isInteger(checkId) || checkId <= 0) { @@ -2060,8 +2200,8 @@ class StockCheckService extends Service { throw this.createBusinessError(`当前状态(${check.status})不允许盘点作业`); } - const quantityValue = Number(quantity); - if (!Number.isInteger(quantityValue) || quantityValue < 0) { + const quantityValue = normalizedIsEmpty ? 0 : Number(quantity); + if (!normalizedIsEmpty && (!Number.isInteger(quantityValue) || quantityValue < 0)) { throw this.createBusinessError('实盘数量必须为不小于0的整数'); } @@ -2073,6 +2213,9 @@ class StockCheckService extends Service { } const scopeType = (detail.scope_type || 'goods') === 'location' ? 'location' : 'goods'; + if (normalizedIsEmpty && scopeType !== 'location') { + throw this.createBusinessError('仅库位盘点明细支持空库位标记'); + } const inputStockId = stockId !== undefined && stockId !== null && stockId !== '' ? Number(stockId) : 0; @@ -2136,11 +2279,30 @@ class StockCheckService extends Service { } } } else { - // 库位行:必须指定商品(stock_id 或 barcode 至少一项);库位以明细库位为准 - if (inputStockId <= 0 && !inputBarcode) { - throw this.createBusinessError('按库位盘点时必须指定商品'); + // 库位行:以明细库位为准 + locationCode = String(detail.location_code || '').trim(); + if (!locationCode) { + throw this.createBusinessError('盘点明细缺少库位信息'); } - if (inputStockId <= 0 && inputBarcode) { + 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; + + if (normalizedIsEmpty) { + // 空库位标记:不要求商品,stock_id/barcode/item_name 均为空、quantity=0 + normalizedStockId = 0; + normalizedBarcode = null; + normalizedItemName = null; + isUnknownGoods = false; + } else if (inputStockId <= 0 && !inputBarcode) { + throw this.createBusinessError('按库位盘点时必须指定商品'); + } else if (inputStockId <= 0 && inputBarcode) { // 仅传条码:先尝试回填系统商品;命中按已知商品处理,未命中记为未知商品 const matchedStockId = await this._resolveStockIdByBarcode(inputBarcode, Number(warehouseId)); if (matchedStockId > 0) { @@ -2170,38 +2332,32 @@ class StockCheckService extends Service { 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_stock_location(detail_id, stock_id, location_code) 保证并发安全; - // 未知商品唯一索引不约束 NULL 行,按同明细 + 同条码 + 同库位编码在应用层查重 - const existingRecordWhere = isUnknownGoods + // 未知商品唯一索引不约束 NULL 行,按同明细 + 同条码 + 同库位编码在应用层查重; + // 空库位标记按(detail_id + is_empty=1 + location_code)应用层查重覆盖更新 + const existingRecordWhere = normalizedIsEmpty ? { detail_id: detailRowId, - stock_id: null, - barcode: normalizedBarcode, + is_empty: true, location_code: locationCode, } - : { - detail_id: detailRowId, - stock_id: normalizedStockId, - location_code: locationCode, - }; + : (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, }); @@ -2237,9 +2393,10 @@ class StockCheckService extends Service { check_id: checkId, warehouse_id: Number(warehouseId), detail_id: detailRowId, - stock_id: isUnknownGoods ? null : normalizedStockId, + stock_id: (isUnknownGoods || normalizedIsEmpty) ? null : normalizedStockId, barcode: normalizedBarcode, item_name: normalizedItemName, + is_empty: normalizedIsEmpty, location_id: locationId, location_code: locationCode, quantity: quantityValue, @@ -2284,6 +2441,17 @@ class StockCheckService extends Service { } } + // 空库位标记与商品记录互斥:确认库位为空后清除该明细下商品记录;上报商品后清除该明细下空标记 + if (normalizedIsEmpty) { + await ctx.model.StockCheckRecord.destroy({ + where: { detail_id: detailRowId, is_empty: false }, + }); + } else { + await ctx.model.StockCheckRecord.destroy({ + where: { detail_id: detailRowId, is_empty: true }, + }); + } + // 主表 approved → checking 自动转移;盘点开始时间=第一个盘点明细写入的时间 // (start_time 为空则补写,保证任何状态下首个明细落盘时间都被记录) const checkPatch = {}; @@ -2306,7 +2474,9 @@ class StockCheckService extends Service { businessId: checkId, operationCode: 'STOCK_CHECK_REPORT', operationAction: 'UPDATE', - changeSummary: `盘点作业上报:明细 ${detailRowId},库位 ${locationCode || '未指定'},实盘 ${quantityValue}${normalizedBarcode ? `,条码 ${normalizedBarcode}` : ''}(${mode === 'created' ? '新增' : '更新'})`, + changeSummary: normalizedIsEmpty + ? `盘点作业上报:明细 ${detailRowId} 确认库位 ${locationCode || '未指定'} 为空` + : `盘点作业上报:明细 ${detailRowId},库位 ${locationCode || '未指定'},实盘 ${quantityValue}${normalizedBarcode ? `,条码 ${normalizedBarcode}` : ''}(${mode === 'created' ? '新增' : '更新'})`, operator: { id: ctx.user?.employees_id || ctx.user?.id || '', name: ctx.user?.employees_name || '', @@ -2319,8 +2489,11 @@ class StockCheckService extends Service { quantity: quantityValue, barcode: normalizedBarcode, isUnknownGoods, + is_empty: normalizedIsEmpty, mode, - message: `盘点作业上报:明细 ${detailRowId} 实盘 ${quantityValue}`, + message: normalizedIsEmpty + ? `盘点作业上报:明细 ${detailRowId} 确认库位为空` + : `盘点作业上报:明细 ${detailRowId} 实盘 ${quantityValue}`, }, }); @@ -2386,34 +2559,60 @@ class StockCheckService extends Service { // 挂载作业记录图片(FileReference business_type=stock_check_record,与收货 receivingItem 口径一致) await this._attachRecordImages(rows); - // 商品快照列(item_code/item_name)从明细表补齐 + // 商品快照列从明细表补齐(未命中 getStockDetails 时兜底) const detailIds = [ ...new Set(rows.map(row => Number(row.detail_id))) ]; let itemByDetailId = new Map(); if (detailIds.length > 0) { const detailRows = await ctx.model.StockCheckDetail.findAll({ where: { id: { [Op.in]: detailIds } }, - attributes: [ 'id', 'item_code', 'item_name' ], + attributes: [ 'id', 'item_code', 'item_name', 'spec' ], raw: true, }); itemByDetailId = new Map(detailRows.map(item => [ Number(item.id), item ])); } + // 商品基础信息批量取(与 workData 口径一致:getStockDetails 带缓存)+ 货主名映射 + const stockIds = [ ...new Set(rows + .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 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; + const stockDetail = isUnknownGoods ? {} : (stockDetailMap.get(recordStockId) || {}); + const barcodes = Array.isArray(stockDetail.barcodes) ? stockDetail.barcodes : []; + const storeId = !isUnknownGoods && stockDetail.store_id != null ? Number(stockDetail.store_id) : null; return { ...row, // 空串表示"无库位"分组,接口返回口径统一为 null location_code: String(row.location_code || '').trim() !== '' ? row.location_code : null, - // 未知商品(stock_id 为空):商品编码列显示扫描条码、名称列显示上报名称快照; - // 已知商品维持现有口径(从明细表商品快照补齐) + // 未知商品(stock_id 为空):商品编码列显示扫描条码、名称列显示上报名称快照,无商品/货主信息; + // 已知商品按 workData 口径:商品信息批量取自 getStockDetails(未命中回退明细商品快照), + // 货主名经 _resolveStoreNameMap 解析 item_code: isUnknownGoods ? (String(row.barcode || '').trim() || null) - : (item.item_code || null), + : (stockDetail.item_code || item.item_code || null), item_name: isUnknownGoods ? (String(row.item_name || row.barcode || '').trim() || null) - : (item.item_name || null), + : (stockDetail.item_name || item.item_name || null), + spec: isUnknownGoods ? null : (stockDetail.sku_property || item.spec || null), + store_id: storeId, + store_name: storeId ? (storeNameMap.get(storeId) || null) : null, + barcode: isUnknownGoods + ? (String(row.barcode || '').trim() || null) + : ((barcodes[0] && barcodes[0].barcode) || (String(row.barcode || '').trim() || null)), }; }); @@ -2421,37 +2620,50 @@ class StockCheckService extends Service { } /** - * 拉取盘点作业数据(单接口三视图,view 入参驱动)。 - * view=location:库位结构,以任务库位范围行(scope_type=location)为列表, - * 行内挂该库位的盘点作业记录(goods=已知商品子列表 / unknown=未知商品子列表); - * view=goods:商品结构,以任务商品范围行(scope_type=goods)为列表,行内挂按库位聚合的作业记录, + * 拉取盘点作业数据(视图由任务类型与 is_goods 驱动,view 入参已废弃忽略)。 + * 视图解析规则: + * - 任务范围为库位(type=location/all):一律按库位视图(location)返回,无视 view/is_goods 入参; + * - 任务范围为商品(type=goods/store):默认聚合库位视图(space);仅 is_goods=true 时按商品视图(goods)返回。 + * 三视图行结构: + * location=库位结构,以任务库位范围行(scope_type=location)为列表, + * 行内挂该库位的盘点作业记录 goods 子列表(已知商品与未知商品均入内, + * has_unknown 标记是否含未知商品); + * goods=商品结构,以任务商品范围行(scope_type=goods)为列表,行内挂按库位聚合的作业记录, * 明盘(mode=open)返回账面快照/已盘合计/差异,盲盘(mode=blind)不返回任何数量字段; - * view=space:商品结构,以任务商品所在库位为列表(按拣货路径 pick_sequence 升序、 + * space=聚合库位列表,以任务商品所在库位为列表(按拣货路径 pick_sequence 升序、 * pick_priority 降序排序),行内挂该库位的任务商品与账面/实盘数量,盲盘不返回数量字段; * 若任务无对应范围行(如 location 视图无库位范围行),rows 返回空数组。 + * 分页:pagination.{page,pageSize}(与 stock_check.list 口径一致;未传或非法时默认 page=1、 + * pageSize=20,上限 200),先构建全量行再按页切片;rows 为当前页行、total 为全部行数, + * 并返回 page/pageSize。 + * + * 不返回任务主表信息(check)——任务信息请调用 detail; + * 响应返回 view(服务端实际解析出的视图类型 location/goods/space),供调用方判断 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 不同: + * @param {boolean} [params.isGoods] 商品任务是否按商品视图返回(true=goods 视图); + * 缺省为 false(聚合库位 space 视图);库位任务无视该参数。 + * @param {string} [params.keyword] 关键字(仅库位任务 location 视图生效):按行 + * location_code/location_name 模糊匹配(不区分大小写)过滤后返回;非库位任务忽略。 + * @param {Object} [params.pagination] 分页配置 { page, pageSize }。 + * @return {Promise} { view, rows, total, page, pageSize };view 为解析后的视图类型 + * (location=库位结构/goods=商品结构/space=聚合库位结构);rows 结构按解析后的视图不同: * 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/ + * checked_at/checkers/goods(已知商品与未知商品记录均入 goods,未知商品 stock_id=null); + * 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)。 + * diff_quantity/is_diff);space 行含 id/space_code/custom_barcode/custom_name/goods。 + * @throws {Error} 任务不存在或任务状态非 approved/checking 时抛出业务错误(错误码 400)。 */ async workData(params = {}) { - const { warehouseId, id, view } = params; + const { warehouseId, id, isGoods, keyword, pagination = {} } = 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) { @@ -2461,19 +2673,161 @@ class StockCheckService extends Service { throw this.createBusinessError(`当前状态(${STOCK_CHECK_STATUS_LABELS[check.status] || check.status})不允许拉取盘点作业数据,仅审核完成(approved)或盘点作业中(checking)的任务可拉取`); } - const rows = normalizedView === 'location' + // 视图解析:库位范围任务一律 location 视图(无视 view/is_goods); + // 商品范围任务默认 space(聚合库位),仅 is_goods=true 时 goods 视图 + const normalizedType = String(check.type || '').trim(); + const goodsViewRequested = isGoods === true || isGoods === 'true' || isGoods === 1; + const resolvedView = normalizedType === 'location' || normalizedType === 'all' + ? 'location' + : (goodsViewRequested ? 'goods' : 'space'); + + const allRows = resolvedView === 'location' ? await this._buildLocationWorkRows(warehouseId, checkId) - : (normalizedView === 'goods' + : (resolvedView === 'goods' ? await this._buildGoodsWorkRows(warehouseId, checkId, check.mode) : await this._buildSpaceWorkRows(warehouseId, checkId, check.mode)); + // keyword 过滤:仅库位任务(location 视图)启用,按行 location_code/location_name + // 模糊匹配(不区分大小写)过滤任务明细后再分页;非库位任务忽略该参数 + const normalizedKeyword = String(keyword || '').trim().toLowerCase(); + const filteredRows = resolvedView === 'location' && normalizedKeyword + ? allRows.filter(row => + String(row.location_code || '').toLowerCase().includes(normalizedKeyword) + || String(row.location_name || '').toLowerCase().includes(normalizedKeyword)) + : allRows; + + // 分页切片:page 默认 1、pageSize 默认 20(上限 200),非法值回退默认 + const page = Math.max(1, Number(pagination.page) || 1); + const pageSize = Math.min(200, Math.max(1, Number(pagination.pageSize) || 20)); + const offset = (page - 1) * pageSize; + return { - check: this._formatCheckRow(check.get({ plain: true })), - rows, - total: rows.length, + view: resolvedView, + rows: filteredRows.slice(offset, offset + pageSize), + total: filteredRows.length, + page, + pageSize, }; } + /** + * 拉取盘点作业数据(space 视图分页版)。 + * 行结构与 workData space 视图行一致(id=库位ID/space_code/custom_barcode/custom_name/goods), + * 商品任务(scope_type=goods)按库位聚合;传入 location_id 时只返回该库位行(total=1), + * 不传时按分页返回全部库位行。 + * + * @param {Object} params 查询参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {number} params.id 盘点任务ID。 + * @param {number|string} [params.locationId] 库位ID(wms_location_space.id), + * 传入时只返回该库位行(兼容 location_id 写法)。 + * @param {Object} [params.pagination] 分页配置 { page, pageSize }。 + * @return {Promise} { view:'space', rows, total, page, pageSize }。 + * @throws {Error} 任务不存在或任务状态非 approved/checking 时抛出业务错误(错误码 400)。 + */ + async workDataSpaceDetails(params = {}) { + const { warehouseId, id, locationId, pagination = {} } = params; + + 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('盘点任务不存在'); + } + if (!REPORT_ALLOWED_STATUSES.includes(check.status)) { + throw this.createBusinessError(`当前状态(${STOCK_CHECK_STATUS_LABELS[check.status] || check.status})不允许拉取盘点作业数据,仅审核完成(approved)或盘点作业中(checking)的任务可拉取`); + } + + const normalizedLocationId = Number(locationId); + const hasLocationFilter = Number.isInteger(normalizedLocationId) && normalizedLocationId > 0; + + const allRows = await this._buildSpaceWorkRows(warehouseId, checkId, check.mode); + + // 库位过滤:传入 location_id 时只保留该库位行 + const filteredRows = hasLocationFilter + ? allRows.filter(row => Number(row.id) === normalizedLocationId) + : allRows; + + // 分页切片:page 默认 1、pageSize 默认 20(上限 200),非法值回退默认 + const page = Math.max(1, Number(pagination.page) || 1); + const pageSize = Math.min(200, Math.max(1, Number(pagination.pageSize) || 20)); + const offset = (page - 1) * pageSize; + + return { + view: 'space', + rows: filteredRows.slice(offset, offset + pageSize), + total: filteredRows.length, + page, + pageSize, + }; + } + + /** + * 拉取单条盘点明细的作业数据(workData 单行版)。 + * + * 按明细范围类型分流,均返回单行对象(与对应视图单行结构一致): + * - 库位明细(scope_type=location):行结构与 workData location 视图单行一致 + * (detail_id/location_id/location_code/location_name/status/has_unknown/is_empty/ + * checked_at/checkers/goods),便于作业端按明细ID刷新单行数据; + * - 商品明细(scope_type=goods):行结构与 workData 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,盲盘不含数量字段)。 + * + * @param {Object} params 查询参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {number} params.detailId 盘点明细ID(库位范围行或商品范围行)。 + * @return {Promise} 单行作业数据(结构随明细范围类型与 workData 对应视图单行一致)。 + * @throws {Error} 明细不存在或任务状态非 approved/checking 时抛业务错误(错误码 400)。 + */ + async workDataDetail(params = {}) { + const { ctx } = this; + const { warehouseId, detailId } = params; + + const normalizedDetailId = Number(detailId); + if (!Number.isInteger(normalizedDetailId) || normalizedDetailId <= 0) { + throw this.createBusinessError('盘点明细ID不能为空'); + } + + const detailRow = await ctx.model.StockCheckDetail.findOne({ + where: { id: normalizedDetailId, warehouse_id: Number(warehouseId) }, + raw: true, + }); + if (!detailRow) { + throw this.createBusinessError('盘点明细不存在'); + } + + const check = await this._findCheck(warehouseId, Number(detailRow.check_id)); + 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 scopeType = (detailRow.scope_type || 'goods') === 'location' ? 'location' : 'goods'; + + // 商品明细:返回 goods 视图单行(与 location 分支结构对称) + if (scopeType === 'goods') { + const goodsRows = await this._buildGoodsWorkRows(warehouseId, Number(detailRow.check_id), check.mode); + const goodsRow = goodsRows.find(item => Number(item.detail_id) === normalizedDetailId); + if (!goodsRow) { + throw this.createBusinessError('盘点明细不存在'); + } + return goodsRow; + } + + // 库位明细:返回 location 视图单行 + const rows = await this._buildLocationWorkRows(warehouseId, Number(detailRow.check_id)); + const row = rows.find(item => Number(item.detail_id) === normalizedDetailId); + if (!row) { + throw this.createBusinessError('盘点明细不存在'); + } + return row; + } + /** * 构建 location 视图行:以任务库位范围行为列表,行内挂该库位的盘点作业记录。 * 已知商品子列表 goods 的商品基础信息(item_code/item_name/条码/图片/货主)批量取自 @@ -2555,10 +2909,10 @@ class StockCheckService extends Service { : null; const goods = []; - const unknown = []; const checkerSet = new Set(); let lastCheckedAt = null; let hasUnknown = false; + let isEmptyLocation = false; for (const record of detailRecords) { const checkerName = String(record.checker_name || '').trim(); if (checkerName) { @@ -2567,6 +2921,11 @@ class StockCheckService extends Service { if (record.checked_at && (!lastCheckedAt || new Date(record.checked_at) > new Date(lastCheckedAt))) { lastCheckedAt = record.checked_at; } + // 空库位标记记录:不计入 goods 子列表,行级输出 is_empty 标记 + if (record.is_empty) { + isEmptyLocation = true; + continue; + } const stockId = Number(record.stock_id); if (Number.isInteger(stockId) && stockId > 0) { const stockDetail = stockDetailMap.get(stockId) || {}; @@ -2578,7 +2937,7 @@ class StockCheckService extends Service { item_code: stockDetail.item_code || null, item_name: stockDetail.item_name || null, barcode: (barcodes[0] && barcodes[0].barcode) || null, - images: stockDetail.image_url || [], + images: Array.isArray(record.images) ? record.images : [], store_id: storeId, store_name: storeNameMap.get(storeId) || null, quantity: Number(record.quantity) || 0, @@ -2586,12 +2945,17 @@ class StockCheckService extends Service { checker_name: checkerName || null, }); } else { + // 未知商品(stock_id 为空)同样进入 goods 子列表,输出记录快照字段 hasUnknown = true; - unknown.push({ + goods.push({ record_id: record.id, - barcode: String(record.barcode || '').trim() || null, + stock_id: null, + item_code: String(record.barcode || '').trim() || null, item_name: String(record.item_name || record.barcode || '').trim() || null, + barcode: String(record.barcode || '').trim() || null, images: Array.isArray(record.images) ? record.images : [], + store_id: null, + store_name: null, quantity: Number(record.quantity) || 0, checked_at: record.checked_at || null, checker_name: checkerName || null, @@ -2608,21 +2972,26 @@ class StockCheckService extends Service { location_name: locationName, status: detailRecords.length > 0 ? 'checked' : 'unchecked', has_unknown: hasUnknown, + is_empty: isEmptyLocation, checked_at: lastCheckedAt, checkers: [ ...checkerSet ], goods, - unknown, }; }); } /** - * 构建 goods 视图行:以任务商品范围行为列表,行内挂按库位聚合的作业记录。 - * 明盘(mode=open)返回 system_quantity(账面快照)/checked_quantity(已盘合计)/diff_quantity/is_diff, - * 库位聚合项含 quantity(该库位实盘合计);盲盘(mode=blind)不返回任何数量字段; + * 构建 goods 视图行:以任务商品范围行为列表,行内挂商品所在库位列表(locations)。 + * locations 为商品所在全部库位(wms_storage 中该商品的 space_id 集合,按拣货路径排序): + * 明盘(mode=open)每库位含 system_quantity(该库位账面数量,wms_storage space+stock + * SUM(available_quantity+locked_quantity),无库存记录库位为 0)、locked_quantity(该库位锁定数量, + * wms_storage space+stock SUM(locked_quantity))与 quantity(该库位盘点数量=实盘合计,未盘库位为 0),三者区分开; + * 盲盘(mode=blind)只显示库位(location_code)不含任何数量字段;已盘库位额外含 + * checked_at/checker_name/record_ids/images,未盘库位这些字段为 null/空数组; + * 商品库存已无记录但已盘的库位(仅记录库位)追加在末尾。 + * 明盘行级返回 system_quantity(账面快照)/checked_quantity(已盘合计)/diff_quantity/is_diff; * 商品基础信息批量取自 stockWarehouse.getStockDetails(未命中回退明细商品快照), - * 货主名经 _resolveStoreNameMap 解析;无作业记录的行 locations 为空数组, - * 已盘合计/差异按 0 处理(避免未盘行误显盘亏差异)。 + * 货主名经 _resolveStoreNameMap 解析。 * * @param {number} warehouseId 仓库ID。 * @param {number} checkId 盘点任务ID。 @@ -2631,6 +3000,7 @@ class StockCheckService extends Service { */ async _buildGoodsWorkRows(warehouseId, checkId, mode) { const { ctx } = this; + const { Op, fn, col, literal } = ctx.app.Sequelize; const detailRows = await ctx.model.StockCheckDetail.findAll({ where: { check_id: checkId, warehouse_id: Number(warehouseId), scope_type: 'goods' }, @@ -2644,6 +3014,9 @@ class StockCheckService extends Service { raw: true, }); + // 挂载作业记录图片(FileReference business_type=stock_check_record,与 result 口径一致) + await this._attachRecordImages(records); + const isOpen = mode !== 'blind'; // 商品基础信息批量取(getStockDetails 带缓存,未命中回退明细商品快照)与货主名映射 @@ -2662,6 +3035,88 @@ class StockCheckService extends Service { .filter(storeId => Number.isInteger(storeId) && storeId > 0); const storeNameMap = await this._resolveStoreNameMap(storeIds, warehouseId); + // 商品所在库位:wms_storage(warehouse + stock_id 在集合 + 启用未删除)DISTINCT space_id + // 同时按 stock+space 汇总账面数量(该库位系统库存,口径=可用+锁定)与锁定数量, + // 供明盘 locations.system_quantity / locked_quantity 使用 + const stockSpaceIdsMap = new Map(); + const stockSpaceQuantityMap = new Map(); + const allSpaceIds = new Set(); + if (stockIds.length > 0) { + const storageRows = await ctx.model.Storage.findAll({ + where: { + warehouse_id: Number(warehouseId), + stock_id: { [Op.in]: stockIds }, + is_enabled: 1, + }, + attributes: [ + 'stock_id', + 'space_id', + [ literal('SUM(available_quantity + locked_quantity)'), 'system_quantity' ], + [ fn('SUM', col('locked_quantity')), 'locked_quantity' ], + ], + group: [ 'stock_id', 'space_id' ], + raw: true, + }); + for (const storageRow of storageRows) { + const stockId = Number(storageRow.stock_id); + if (!stockSpaceIdsMap.has(stockId)) { + stockSpaceIdsMap.set(stockId, []); + stockSpaceQuantityMap.set(stockId, new Map()); + } + const spaceId = Number(storageRow.space_id); + stockSpaceIdsMap.get(stockId).push(spaceId); + stockSpaceQuantityMap.get(stockId).set(spaceId, { + system_quantity: Number(storageRow.system_quantity) || 0, + locked_quantity: Number(storageRow.locked_quantity) || 0, + }); + allSpaceIds.add(spaceId); + } + } + + // 库位表(space_code + 拣货路径),按拣货路径排序:pick_sequence 升序、pick_priority 降序(同值按 id 升序兜底) + let sortedSpaceRows = []; + if (allSpaceIds.size > 0) { + const locationRows = await ctx.model.LocationSpace.findAll({ + where: { id: { [Op.in]: [ ...allSpaceIds ] } }, + attributes: [ 'id', 'space_code', 'pick_sequence', 'pick_priority' ], + raw: true, + }); + sortedSpaceRows = 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); + }); + } + const spaceCodeByStockMap = new Map(); + const spaceQuantityByStockMap = new Map(); + for (const [ stockId, spaceIds ] of stockSpaceIdsMap.entries()) { + const spaceRowMap = new Map(sortedSpaceRows.map(row => [ Number(row.id), row ])); + const orderedRows = spaceIds + .map(spaceId => spaceRowMap.get(spaceId)) + .filter(Boolean) + .sort((left, right) => sortedSpaceRows.indexOf(left) - sortedSpaceRows.indexOf(right)); + spaceCodeByStockMap.set( + stockId, + orderedRows.map(row => String(row.space_code || '').trim()) + ); + const quantityByCode = new Map(); + for (const row of orderedRows) { + const spaceCode = String(row.space_code || '').trim(); + const spaceQuantity = (stockSpaceQuantityMap.get(stockId) || new Map()).get(Number(row.id)) || {}; + quantityByCode.set(spaceCode, { + system_quantity: Number(spaceQuantity.system_quantity) || 0, + locked_quantity: Number(spaceQuantity.locked_quantity) || 0, + }); + } + spaceQuantityByStockMap.set(stockId, quantityByCode); + } + // 按明细聚合作业记录 const recordsByDetail = new Map(); for (const record of records) { @@ -2712,34 +3167,73 @@ class StockCheckService extends Service { first_record_id: Number(record.id) || 0, checked_at: null, checker_name: null, + record_ids: [], + images: [], }); } const group = locationGroups.get(recordLocationCode); group.quantity += Number(record.quantity) || 0; + group.record_ids.push(Number(record.id) || 0); + for (const image of (Array.isArray(record.images) ? record.images : [])) { + if (!group.images.some(item => item && Number(item.id) === Number(image.id))) { + group.images.push(image); + } + } 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; - }); + // locations:商品所在全部库位(基础列表),已盘库位合并作业信息,未盘库位为空信息; + // 商品库存已无记录但已盘的库位(仅记录库位)追加在末尾 + const baseLocationCodes = (spaceCodeByStockMap.get(stockId) || []).filter(code => code !== ''); + const mergedLocationCodes = new Set(baseLocationCodes); + const extraGroups = []; + for (const [ code, group ] of locationGroups.entries()) { + if (code && !mergedLocationCodes.has(code)) { + extraGroups.push(group); + } + } + + const buildLocationItem = (code, group) => { + const locationItem = { + location_code: code || null, + checked_at: group ? group.checked_at : null, + checker_name: group ? group.checker_name : null, + record_ids: group ? group.record_ids : [], + images: group ? group.images : [], + }; + if (isOpen) { + // 明盘:库位账面数量(可用+锁定)、库位锁定数量与库位盘点数量(实盘合计)区分输出 + const spaceQuantity = (spaceQuantityByStockMap.get(stockId) || new Map()).get(code || '') || {}; + locationItem.system_quantity = Number(spaceQuantity.system_quantity) || 0; + locationItem.locked_quantity = Number(spaceQuantity.locked_quantity) || 0; + locationItem.quantity = group ? group.quantity : 0; + } + return locationItem; + }; + + row.locations = [ + ...baseLocationCodes.map(code => buildLocationItem(code, locationGroups.get(code) || null)), + ...extraGroups + .sort((left, right) => left.first_record_id - right.first_record_id) + .map(group => buildLocationItem(group.location_code, group)), + ]; + + // "无库位"分组(记录 location_code 为空)追加在末尾 + const emptyLocationGroup = locationGroups.get(''); + if (emptyLocationGroup) { + row.locations.push(buildLocationItem(null, emptyLocationGroup)); + } 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; + // 差异仅对存在作业记录的行计算(未盘行差异保持 0,避免误显盘亏) + if (detailRecords.length > 0) { + row.diff_quantity = row.checked_quantity - row.system_quantity; + row.is_diff = row.diff_quantity !== 0 ? 1 : 0; + } } return row; @@ -2750,7 +3244,8 @@ class StockCheckService extends Service { * 构建 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)) + * 行内 goods 为该库位下的任务商品:明盘含 system_quantity(wms_storage space+stock + * SUM(available_quantity+locked_quantity))、locked_quantity(wms_storage space+stock SUM(locked_quantity)) * 与 checked_quantity(该商品在该库位的实盘合计),盲盘不返回任何数量字段; * status 已盘口径:该 (detail_id, location_code) 存在作业记录; * 未在 wms_storage 有库位的商品不入列表(无库位可聚)。 @@ -2762,7 +3257,7 @@ class StockCheckService extends Service { */ async _buildSpaceWorkRows(warehouseId, checkId, mode) { const { ctx } = this; - const { Op, fn, col } = ctx.app.Sequelize; + const { Op, fn, col, literal } = ctx.app.Sequelize; const detailRows = await ctx.model.StockCheckDetail.findAll({ where: { check_id: checkId, warehouse_id: Number(warehouseId), scope_type: 'goods' }, @@ -2784,6 +3279,9 @@ class StockCheckService extends Service { raw: true, }); + // 挂载作业记录图片(FileReference business_type=stock_check_record,与 result 口径一致) + await this._attachRecordImages(records); + // 商品基础信息批量取(getStockDetails 带缓存,未命中回退明细商品快照)与货主名映射 const stockDetails = await ctx.service.systems.stockWarehouse.getStockDetails(stockIds, { warehouseId: Number(warehouseId), @@ -2796,7 +3294,7 @@ class StockCheckService extends Service { const detailByStockId = new Map(detailRows.map(row => [ Number(row.stock_id), row ])); // 任务商品所在库位:wms_storage(warehouse + stock_id 在集合 + 启用未删除)DISTINCT space_id, - // 同时按 (space_id, stock_id) 汇总账面数量 + // 同时按 (space_id, stock_id) 汇总账面数量(口径=可用+锁定)与锁定数量 const storageRows = await ctx.model.Storage.findAll({ where: { warehouse_id: Number(warehouseId), @@ -2806,19 +3304,56 @@ class StockCheckService extends Service { attributes: [ 'space_id', 'stock_id', - [ fn('SUM', col('quantity')), 'totalQuantity' ], + [ literal('SUM(available_quantity + locked_quantity)'), 'totalQuantity' ], + [ fn('SUM', col('locked_quantity')), 'totalLockedQuantity' ], ], group: [ 'space_id', 'stock_id' ], raw: true, }); - if (storageRows.length === 0) { + // 作业记录库位:优先已回填 location_id;未回填的按库位编码匹配 wms_location_space 补查, + // 保证商品库存已无记录时(如盘点前库存已出空)space 视图仍能展示已盘库位行。 + const recordSpaceIds = []; + const recordLocationCodes = []; + for (const record of records) { + const recordSpaceId = Number(record.location_id) || 0; + if (recordSpaceId > 0) { + if (!recordSpaceIds.includes(recordSpaceId)) { + recordSpaceIds.push(recordSpaceId); + } + } else { + const locationCode = String(record.location_code || '').trim(); + if (locationCode && !recordLocationCodes.includes(locationCode)) { + recordLocationCodes.push(locationCode); + } + } + } + let codeMatchedLocationRows = []; + if (recordLocationCodes.length > 0) { + codeMatchedLocationRows = await ctx.model.LocationSpace.findAll({ + where: { + warehouse_id: Number(warehouseId), + space_code: { [Op.in]: recordLocationCodes }, + }, + attributes: [ 'id', 'space_code', 'custom_barcode', 'custom_name', 'pick_sequence', 'pick_priority' ], + raw: true, + }); + for (const row of codeMatchedLocationRows) { + const matchedSpaceId = Number(row.id); + if (!recordSpaceIds.includes(matchedSpaceId)) { + recordSpaceIds.push(matchedSpaceId); + } + } + } + + const storageSpaceIds = [ ...new Set(storageRows.map(row => Number(row.space_id))) ]; + const spaceIds = [ ...new Set([ ...storageSpaceIds, ...recordSpaceIds ]) ]; + if (spaceIds.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' ], + attributes: [ 'id', 'space_code', 'custom_barcode', 'custom_name', 'pick_sequence', 'pick_priority' ], raw: true, }); @@ -2835,12 +3370,15 @@ class StockCheckService extends Service { return Number(left.id) - Number(right.id); }); - // 库位商品账面映射(键 `${space_id}_${stock_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 + { + system_quantity: Number(storageRow.totalQuantity) || 0, + locked_quantity: Number(storageRow.totalLockedQuantity) || 0, + } ); } @@ -2866,10 +3404,49 @@ class StockCheckService extends Service { recordsByDetailLocation.get(key).push(record); } + // 按 (detail_id, space_id) 聚合作业记录(库位编码大小写/回填差异时兜底按库位ID命中) + const codeToSpaceIdMap = new Map( + codeMatchedLocationRows.map(row => [ String(row.space_code || '').trim(), Number(row.id) ]) + ); + const recordsByDetailSpace = new Map(); + // 仅记录库位(当前库存无该商品)按库位归集记录,供 space 视图补行 + const recordsBySpace = new Map(); + for (const record of records) { + let spaceId = Number(record.location_id) || 0; + if (!spaceId) { + spaceId = codeToSpaceIdMap.get(String(record.location_code || '').trim()) || 0; + } + if (!spaceId) { + continue; + } + const detailId = Number(record.detail_id); + const detailSpaceKey = `${detailId}_${spaceId}`; + if (!recordsByDetailSpace.has(detailSpaceKey)) { + recordsByDetailSpace.set(detailSpaceKey, []); + } + recordsByDetailSpace.get(detailSpaceKey).push(record); + + if (!recordsBySpace.has(spaceId)) { + recordsBySpace.set(spaceId, []); + } + recordsBySpace.get(spaceId).push(record); + } + return sortedLocations.map(locationRow => { const spaceId = Number(locationRow.id); const spaceCode = String(locationRow.space_code || '').trim(); - const goods = (storageBySpace.get(spaceId) || []) + // 库存行 + 仅记录库位(当前库存已无该商品)的已知商品补行 + const spaceStorageRows = storageBySpace.get(spaceId) || []; + const knownStorageStockIds = new Set(spaceStorageRows.map(row => Number(row.stock_id))); + const mergedRows = [ ...spaceStorageRows ]; + for (const record of recordsBySpace.get(spaceId) || []) { + const recordStockId = Number(record.stock_id) || 0; + if (recordStockId > 0 && !knownStorageStockIds.has(recordStockId)) { + mergedRows.push({ space_id: spaceId, stock_id: recordStockId, totalQuantity: 0, totalLockedQuantity: 0 }); + knownStorageStockIds.add(recordStockId); + } + } + const goods = mergedRows .sort((left, right) => Number(left.stock_id) - Number(right.stock_id)) .map(storageRow => { const stockId = Number(storageRow.stock_id); @@ -2881,7 +3458,20 @@ class StockCheckService extends Service { 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 locationRecords = recordsByDetailSpace.get(`${detailId}_${spaceId}`) + || recordsByDetailLocation.get(`${detailId}_${spaceCode}`) + || []; + // 作业照片与记录ID(供前端展示与编辑/移除记录) + const recordImages = []; + const recordIds = []; + for (const record of locationRecords) { + recordIds.push(Number(record.id) || 0); + for (const image of (Array.isArray(record.images) ? record.images : [])) { + if (!recordImages.some(item => item && Number(item.id) === Number(image.id))) { + recordImages.push(image); + } + } + } const item = { detail_id: detailId, stock_id: stockId, @@ -2891,10 +3481,13 @@ class StockCheckService extends Service { store_id: storeId, store_name: storeNameMap.get(storeId) || null, barcode: (barcodes[0] && barcodes[0].barcode) || null, - images: stockDetail.image_url || [], + images: recordImages, + record_ids: recordIds, }; if (isOpen) { - item.system_quantity = storageQuantityMap.get(`${spaceId}_${stockId}`) || 0; + const storageQuantity = storageQuantityMap.get(`${spaceId}_${stockId}`) || {}; + item.system_quantity = Number(storageQuantity.system_quantity) || 0; + item.locked_quantity = Number(storageQuantity.locked_quantity) || 0; item.checked_quantity = locationRecords.reduce( (sum, record) => sum + (Number(record.quantity) || 0), 0 @@ -2906,39 +3499,46 @@ class StockCheckService extends Service { .filter(item => item !== null); return { - location_id: spaceId, - location_code: spaceCode || null, - location_name: String(locationRow.custom_name || locationRow.space_code || '').trim() || null, + // 库位字段对齐库位查询惯例(index.searchSpace:id/space_code/custom_barcode/custom_name) + id: spaceId, + space_code: spaceCode || null, + custom_barcode: locationRow.custom_barcode != null && String(locationRow.custom_barcode).trim() !== '' + ? String(locationRow.custom_barcode).trim() + : null, + custom_name: locationRow.custom_name != null && String(locationRow.custom_name).trim() !== '' + ? String(locationRow.custom_name).trim() + : null, goods, }; }); } /** - * 删除盘点作业记录。 - * 仅主表状态 approved/checking 允许删除;记录不存在或不属于该任务/仓库时报 400; + * 批量删除盘点作业记录(按行清除盘点信息)。 + * 仅主表状态 approved/checking 允许删除;记录不存在或不属于该任务/仓库时计入 skipped_ids 不报错; * 删除后重算 checked_items/diff_items/detail_status(明细记录删光后该明细回到未盘),主表状态不回退; - * 同时清理该记录的图片引用(FileReference business_type=stock_check_record,失败仅告警不影响主流程)。 + * 同时清理被删记录的图片引用(FileReference business_type=stock_check_record,失败仅告警不影响主流程)。 + * 注意:本接口已由旧版单值删除升级为批量删除,响应结构由旧版 { record_id, deleted, ...summary } + * 变更为 { deleted_count, deleted_ids, skipped_ids, ...summary }。 * * @param {Object} params 删除参数。 * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 * @param {number} params.id 盘点任务ID。 - * @param {number} params.recordId 作业记录ID(方法层已兼容 record_id/recordId 写法)。 - * @return {Promise} { record_id, deleted, total_items, checked_items, diff_items, detail_status }。 - * @throws {Error} 状态不允许或记录不存在时抛出业务错误(错误码 400)。 + * @param {Array|number} params.recordIds 作业记录ID数组(单值自动转数组,单次上限 200; + * 方法层已兼容 record_ids/recordIds/record_id 写法)。 + * @return {Promise} { deleted_count, deleted_ids, skipped_ids, total_items, checked_items, diff_items, detail_status }; + * deleted_ids/skipped_ids 均保持入参顺序。 + * @throws {Error} 参数非法、任务不存在或状态不允许时抛出业务错误(错误码 400)。 */ async recordDelete(params = {}) { - const { warehouseId, id, recordId } = params; + const { warehouseId, id, recordIds } = params; const { ctx } = this; + const { Op } = ctx.app.Sequelize; const checkId = Number(id); - const normalizedRecordId = Number(recordId); if (!Number.isInteger(checkId) || checkId <= 0) { throw this.createBusinessError('盘点任务ID不能为空'); } - if (!Number.isInteger(normalizedRecordId) || normalizedRecordId <= 0) { - throw this.createBusinessError('作业记录ID不能为空'); - } const check = await this._findCheck(warehouseId, checkId); if (!check) { @@ -2948,29 +3548,51 @@ class StockCheckService extends Service { throw this.createBusinessError(`当前状态(${check.status})不允许删除作业记录`); } - const record = await ctx.model.StockCheckRecord.findOne({ + const numericRecordIds = this._normalizeIdList(recordIds); + if (numericRecordIds.length === 0) { + throw this.createBusinessError('请至少选择一条作业记录'); + } + if (numericRecordIds.length > 200) { + throw this.createBusinessError('单次最多删除 200 条作业记录'); + } + + // 仓库隔离查询记录:id in ids + check_id + warehouse_id;查不到的 ID 计入 skipped_ids(不报错) + const recordRows = await ctx.model.StockCheckRecord.findAll({ where: { - id: normalizedRecordId, + id: { [Op.in]: numericRecordIds }, check_id: checkId, warehouse_id: Number(warehouseId), }, + attributes: [ 'id' ], + raw: true, }); - if (!record) { - throw this.createBusinessError('作业记录不存在或不属于该盘点任务'); + const foundIdSet = new Set(recordRows.map(row => Number(row.id))); + const deletedIds = []; + const skippedIds = []; + for (const recordId of numericRecordIds) { + if (foundIdSet.has(recordId)) { + deletedIds.push(recordId); + } else { + skippedIds.push(recordId); + } } - await record.destroy(); - - // 清理该记录的图片引用(图片独立维护,仿收货口径):失败仅告警,不影响主流程 - try { - await ctx.model.FileReference.destroy({ - where: { - business_type: 'stock_check_record', - business_id: String(normalizedRecordId), - }, + if (deletedIds.length > 0) { + await ctx.model.StockCheckRecord.destroy({ + where: { id: { [Op.in]: deletedIds } }, }); - } catch (error) { - ctx.logger.warn(`[stock.check.recordDelete] 清理作业记录图片引用失败: ${error && error.message ? error.message : error}`); + + // 清理被删记录的图片引用(图片独立维护,仿收货口径):失败仅告警,不影响主流程 + try { + await ctx.model.FileReference.destroy({ + where: { + business_type: 'stock_check_record', + business_id: { [Op.in]: deletedIds.map(String) }, + }, + }); + } catch (error) { + ctx.logger.warn(`[stock.check.recordDelete] 清理作业记录图片引用失败: ${error && error.message ? error.message : error}`); + } } // 重算 checked_items / diff_items / detail_status(明细记录删光后该明细回到未盘),主表状态不回退 @@ -2982,7 +3604,7 @@ class StockCheckService extends Service { businessId: checkId, operationCode: 'STOCK_CHECK_DELETE_RECORD', operationAction: 'UPDATE', - changeSummary: `删除盘点作业记录 ${normalizedRecordId}`, + changeSummary: `批量删除盘点作业记录 ${deletedIds.length} 条(跳过 ${skippedIds.length} 条)`, operator: { id: ctx.user?.employees_id || ctx.user?.id || '', name: ctx.user?.employees_name || '', @@ -2990,14 +3612,16 @@ class StockCheckService extends Service { extras: { warehouseId, checkNo: check.check_no, - recordId: normalizedRecordId, - message: `删除盘点作业记录 ${normalizedRecordId}`, + deletedIds, + skippedIds, + message: `批量删除盘点作业记录 ${deletedIds.length} 条`, }, }); return { - record_id: normalizedRecordId, - deleted: true, + deleted_count: deletedIds.length, + deleted_ids: deletedIds, + skipped_ids: skippedIds, total_items: summary.total_items, checked_items: summary.checked_items, diff_items: summary.diff_items, @@ -3006,57 +3630,146 @@ class StockCheckService extends Service { } /** - * 完成盘点作业(允许部分未盘完成)。 - * 仅 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,并返回差异汇总与未盘明细数。 + * 重盘清除库位(按库位清除盘点信息,库位盘点模式专属)。 + * 传入任务ID与库位ID,清除该库位范围内明细的全部作业记录(含空库位标记), + * 该库位回到未盘状态;仅任务范围为库位(type=location/all)且状态 approved/checking 时允许; + * 删除后重算 checked_items/diff_items/detail_status,主表状态不回退; + * 同时清理被删记录的图片引用(失败仅告警不影响主流程)。 * - * @param {Object} params 完成参数。 + * @param {Object} params 清除参数。 * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 * @param {number} params.id 盘点任务ID。 - * @return {Promise} { id, status, total_items, checked_items, unchecked_items, diff_items, profit_total, loss_total }。 - * @throws {Error} 状态不允许时抛出业务错误(错误码 400)。 + * @param {number} params.locationId 库位ID(wms_location_space.id)。 + * @return {Promise} { detail_id, location_id, deleted_count, total_items, checked_items, diff_items, detail_status }。 + * @throws {Error} 参数非法、任务不存在、状态不允许、非库位任务或库位不在任务范围内时抛出业务错误(错误码 400)。 */ - async finish(params = {}) { - const { warehouseId, id } = params; + async recheckClearLocation(params = {}) { + const { warehouseId, id, locationId } = params; const { ctx } = this; - const { fn, col } = ctx.app.Sequelize; + const { Op } = ctx.app.Sequelize; const checkId = Number(id); + const normalizedLocationId = Number(locationId); if (!Number.isInteger(checkId) || checkId <= 0) { throw this.createBusinessError('盘点任务ID不能为空'); } + if (!Number.isInteger(normalizedLocationId) || normalizedLocationId <= 0) { + throw this.createBusinessError('库位ID不能为空'); + } const check = await this._findCheck(warehouseId, checkId); if (!check) { throw this.createBusinessError('盘点任务不存在'); } if (!REPORT_ALLOWED_STATUSES.includes(check.status)) { - throw this.createBusinessError(`当前状态(${check.status})不允许完成盘点`); + throw this.createBusinessError(`当前状态(${check.status})不允许清除库位盘点信息`); + } + const normalizedType = String(check.type || '').trim(); + if (normalizedType !== 'location' && normalizedType !== 'all') { + throw this.createBusinessError('仅库位盘点任务支持重盘清除库位'); } - const totalItems = await ctx.model.StockCheckDetail.count({ - where: { check_id: checkId }, + const detail = await ctx.model.StockCheckDetail.findOne({ + where: { + check_id: checkId, + warehouse_id: Number(warehouseId), + location_id: normalizedLocationId, + scope_type: 'location', + }, + attributes: [ 'id', 'location_id', 'location_code' ], }); + if (!detail) { + throw this.createBusinessError('该库位不在盘点任务范围内'); + } + const detailId = Number(detail.id); - // 已盘明细数:存在作业记录(wms_stock_check_record)的明细数 - const checkedCountRows = await ctx.model.StockCheckRecord.findAll({ - where: { check_id: checkId }, - attributes: [[ fn('COUNT', fn('DISTINCT', col('detail_id'))), 'checkedCount' ]], + // 删除该明细全部作业记录(含空库位标记) + const recordRows = await ctx.model.StockCheckRecord.findAll({ + where: { detail_id: detailId, check_id: checkId }, + attributes: [ 'id' ], raw: true, }); - const checkedItems = Number(checkedCountRows && checkedCountRows[0] && checkedCountRows[0].checkedCount) || 0; - const uncheckedItems = totalItems - checkedItems; + const deletedCount = recordRows.length; + if (deletedCount > 0) { + await ctx.model.StockCheckRecord.destroy({ + where: { + detail_id: detailId, + check_id: checkId, + warehouse_id: Number(warehouseId), + }, + }); + + // 清理被删记录的图片引用:失败仅告警,不影响主流程 + try { + await ctx.model.FileReference.destroy({ + where: { + business_type: 'stock_check_record', + business_id: { [Op.in]: recordRows.map(row => String(row.id)) }, + }, + }); + } catch (error) { + ctx.logger.warn(`[stock.check.recheckClearLocation] 清理作业记录图片引用失败: ${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_CLEAR_LOCATION', + operationAction: 'UPDATE', + changeSummary: `重盘清除库位 ${String(detail.location_code || '').trim() || normalizedLocationId}:删除作业记录 ${deletedCount} 条`, + operator: { + id: ctx.user?.employees_id || ctx.user?.id || '', + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + checkNo: check.check_no, + detailId, + locationId: normalizedLocationId, + locationCode: String(detail.location_code || '').trim(), + message: `重盘清除库位:删除作业记录 ${deletedCount} 条`, + }, + }); + + return { + detail_id: detailId, + location_id: normalizedLocationId, + deleted_count: deletedCount, + total_items: summary.total_items, + checked_items: summary.checked_items, + diff_items: summary.diff_items, + detail_status: summary.detail_status, + }; + } + + /** + * 计算任务数量差异汇总(盘盈/盘亏/差异明细数,纯查询无副作用)。 + * + * 口径: + * - 商品行(scope_type=goods):聚合 vs 账面快照 system_quantity;未盘商品行按实盘 0 处理 + * (差异 = -账面快照,即盘亏); + * - 库位行(scope_type=location):按商品聚合 vs wms_storage 账面;未盘库位行无法枚举商品, + * 不计差异; + * - 未知商品(记录 stock_id 为空)无账面:实盘 > 0 即盘盈,必然计入差异。 + * 盘亏合计以正数返回(loss_total 为正数口径)。 + * + * @param {number} checkId 盘点任务ID。 + * @return {Promise} { diff_items, profit_total, loss_total }。 + */ + async _calcQuantityDiffSummary(checkId) { + const { ctx } = this; - // 差异汇总:商品行聚合 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 }, + where: { check_id: Number(checkId) }, attributes: [ 'id', 'scope_type', 'system_quantity' ], raw: true, }); @@ -3113,6 +3826,64 @@ class StockCheckService extends Service { } } + return { + diff_items: diffItems, + profit_total: profitTotal, + loss_total: lossTotal, + }; + } + + /** + * 完成盘点作业(允许部分未盘完成)。 + * 仅 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 完成参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {number} params.id 盘点任务ID。 + * @return {Promise} { id, status, total_items, checked_items, unchecked_items, diff_items, profit_total, loss_total }。 + * @throws {Error} 状态不允许时抛出业务错误(错误码 400)。 + */ + async finish(params = {}) { + const { warehouseId, id } = params; + const { ctx } = this; + const { fn, col } = ctx.app.Sequelize; + + 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('盘点任务不存在'); + } + if (!REPORT_ALLOWED_STATUSES.includes(check.status)) { + throw this.createBusinessError(`当前状态(${check.status})不允许完成盘点`); + } + + const totalItems = await ctx.model.StockCheckDetail.count({ + where: { check_id: checkId }, + }); + + // 已盘明细数:存在作业记录(wms_stock_check_record)的明细数 + const checkedCountRows = await ctx.model.StockCheckRecord.findAll({ + where: { check_id: checkId }, + attributes: [[ fn('COUNT', fn('DISTINCT', col('detail_id'))), 'checkedCount' ]], + raw: true, + }); + const checkedItems = Number(checkedCountRows && checkedCountRows[0] && checkedCountRows[0].checkedCount) || 0; + const uncheckedItems = totalItems - checkedItems; + + // 数量差异汇总(盘盈/盘亏/差异明细数,口径见 _calcQuantityDiffSummary) + const diffSummary = await this._calcQuantityDiffSummary(checkId); + const diffItems = diffSummary.diff_items; + const profitTotal = diffSummary.profit_total; + const lossTotal = diffSummary.loss_total; + await check.update({ status: 'completed', end_time: new Date(), @@ -3158,17 +3929,19 @@ class StockCheckService extends Service { /** * 完成盘点任务(提交审核)。 - * 仅 created/rejected 状态允许;校验 total_items>0 后置为 submitted。 + * 仅 created/rejected 状态允许;校验 total_items>0 后置为 submitted; + * 库位范围明细(scope_type=location)缺少库位(location_id 为空或 location_code 为空)时不可提交。 * * @param {Object} params 提交参数。 * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 * @param {number} params.id 盘点任务ID。 * @return {Promise} { id, status }。 - * @throws {Error} 状态不允许或没有明细时抛出业务错误(错误码 400)。 + * @throws {Error} 状态不允许、没有明细或存在缺少库位的明细时抛出业务错误(错误码 400)。 */ async submit(params = {}) { const { warehouseId, id } = params; const { ctx } = this; + const { Op } = ctx.app.Sequelize; const checkId = Number(id); if (!Number.isInteger(checkId) || checkId <= 0) { @@ -3186,6 +3959,22 @@ class StockCheckService extends Service { throw this.createBusinessError('盘点任务还没有明细行,无法提交审核'); } + // 盘点明细缺库位(location_id 为空或 location_code 为空)不可提交(脏数据防御): + // 库位范围明细天然必须带库位;商品范围明细按「商品 + 库位」拆行后同样必须带库位 + const missingLocationCount = await ctx.model.StockCheckDetail.count({ + where: { + check_id: checkId, + [Op.or]: [ + { location_id: null }, + { location_code: null }, + { location_code: '' }, + ], + }, + }); + if (missingLocationCount > 0) { + throw this.createBusinessError('存在缺少库位的盘点明细,无法提交审核'); + } + await check.update({ status: 'submitted' }); // 写入操作日志(失败不影响主流程) @@ -3648,10 +4437,10 @@ class StockCheckService extends Service { for (const row of rows) { detailsSheet.addRow([ check.check_no || '', - row.item_code || '', - row.item_name || '', + row.is_empty ? '(空库位)' : (row.item_code || ''), + row.is_empty ? '' : (row.item_name || ''), String(row.location_code || '').trim() !== '' ? row.location_code : '', - Number(row.quantity) || 0, + row.is_empty ? 0 : (Number(row.quantity) || 0), row.checker_name || '', this._formatLocalDateTime(row.checked_at), ]).commit(); diff --git a/database/migrations/20261002160000-add-is-empty-to-stock-check-record.js b/database/migrations/20261002160000-add-is-empty-to-stock-check-record.js new file mode 100644 index 0000000..2f89189 --- /dev/null +++ b/database/migrations/20261002160000-add-is-empty-to-stock-check-record.js @@ -0,0 +1,25 @@ +'use strict'; + +/** + * 库存盘点作业记录表支持空库位标记(库位盘点模式:确认库位为空时上报一条特殊记录): + * + * wms_stock_check_record 新增 is_empty(TINYINT(1) NOT NULL DEFAULT 0): + * - is_empty=1 的记录表示「确认该库位为空」:stock_id=NULL、barcode=NULL、item_name=NULL、quantity=0; + * - 与商品记录互斥(应用层保证):标记空时删除该明细下商品记录;上报商品时删除该明细下空记录; + * - 空记录按(detail_id + is_empty=1 + location_code)应用层查重覆盖更新(唯一索引不约束 NULL 行)。 + */ + +const TABLE_NAME = 'wms_stock_check_record'; + +module.exports = { + up: async queryInterface => { + await queryInterface.sequelize.query(` + ALTER TABLE \`${TABLE_NAME}\` + ADD COLUMN \`is_empty\` TINYINT(1) NOT NULL DEFAULT 0 COMMENT '是否空库位标记(1=确认为空,stock_id/barcode/item_name 均为空、quantity=0)' AFTER \`item_name\` + `); + }, + + down: async queryInterface => { + await queryInterface.removeColumn(TABLE_NAME, 'is_empty'); + }, +}; diff --git a/database/migrations/20261002170000-split-goods-detail-by-location.js b/database/migrations/20261002170000-split-goods-detail-by-location.js new file mode 100644 index 0000000..312df2f --- /dev/null +++ b/database/migrations/20261002170000-split-goods-detail-by-location.js @@ -0,0 +1,47 @@ +'use strict'; + +/** + * 商品盘点明细按「商品 + 库位」拆行(商品任务必须按库位盘点): + * + * wms_stock_check_detail: + * 1. 唯一索引 uk_check_stock(check_id, stock_id) 变更为 uk_check_stock_location(check_id, stock_id, location_id), + * 允许同一商品在该任务下按多个库存库位拆成多行(location_id 均为 NULL 的旧行不受唯一约束,MySQL NULL 语义)。 + * 2. 唯一索引 uk_check_location(check_id, location_code) 放宽为普通索引 idx_check_location: + * 商品拆行后同一任务同一库位可能对应多个商品行(location_code 相同),唯一约束不再成立; + * 库位明细行(scope_type=location)幂等由应用层查重保证。 + * 3. 商品明细行(scope_type=goods)将写入其库存库位快照(location_id/location_code/system_quantity=该库位账面), + * 应用层保证同商品重复添加整体跳过(幂等口径不变)。 + */ + +const TABLE_NAME = 'wms_stock_check_detail'; + +module.exports = { + up: async queryInterface => { + await queryInterface.sequelize.query(` + ALTER TABLE \`${TABLE_NAME}\` + DROP INDEX \`uk_check_stock\`, + DROP INDEX \`uk_check_location\`, + ADD UNIQUE INDEX \`uk_check_stock_location\` (\`check_id\`, \`stock_id\`, \`location_id\`), + ADD INDEX \`idx_check_location\` (\`check_id\`, \`location_code\`) + `); + }, + + down: async queryInterface => { + // 回退前清理同 (check_id, stock_id) 的多行重复(保留最小 id),保证恢复唯一索引不失败; + // 同任务同库位的多商品行(拆行产生)一并清理(保留最小 id),恢复 uk_check_location 不失败 + await queryInterface.sequelize.query(` + DELETE d1 FROM \`${TABLE_NAME}\` d1 + INNER JOIN \`${TABLE_NAME}\` d2 + ON d1.check_id = d2.check_id + AND ((d1.stock_id = d2.stock_id) OR (d1.location_code = d2.location_code)) + AND d1.id > d2.id + `); + await queryInterface.sequelize.query(` + ALTER TABLE \`${TABLE_NAME}\` + DROP INDEX \`uk_check_stock_location\`, + DROP INDEX \`idx_check_location\`, + ADD UNIQUE INDEX \`uk_check_stock\` (\`check_id\`, \`stock_id\`), + ADD UNIQUE INDEX \`uk_check_location\` (\`check_id\`, \`location_code\`) + `); + }, +}; diff --git a/methods/changes/system.json b/methods/changes/system.json index edef7ba..140e64f 100644 --- a/methods/changes/system.json +++ b/methods/changes/system.json @@ -1,4 +1,108 @@ [ + { + "version": "0.3.249", + "date": "2026-10-06", + "type": "updated", + "summary": "盘点账面口径全量统一为可用+锁定(SUM(available_quantity+locked_quantity)):result 库位行/空标记盘亏、report 重算、finish 差异汇总、detail 盘盈盘亏汇总、addDetail 拆行快照(0.3.248 → 0.3.249)", + "methods": [ + "stock.check.workData", + "stock.check.workDataDetail", + "stock.check.workDataSpaceDetails", + "stock.check.result", + "stock.check.report", + "stock.check.finish", + "stock.check.detail", + "stock.check.addDetail" + ], + "notes": [ + "变更内容:全部盘点账面口径统一为 wms_storage SUM(available_quantity+locked_quantity)(=可用+锁定)——①result 库位行 stocks 账面与空库位标记盘亏(_buildDetailAggregations/_formatDetailAggregationRow);②report 重算 diff_items 的库位行按商品账面与空标记库位账面(_recalcCheckSummary);③finish 差异汇总复用 _recalcCheckSummary 口径;④detail profit_total/loss_total 汇总复用同口径;⑤addDetail 按库位拆行写入的明细快照 system_quantity=该库位库存 SUM(可用+锁定);与盘点作业视图(workData/workDataDetail/workDataSpaceDetails,0.3.248 已改)完全一致。商品行差异仍以明细账面快照(system_quantity 列)对比。", + "代码依据:app/service/systems/stock_check.js#_recalcCheckSummary/#_buildDetailAggregations/#_formatDetailAggregationRow/#addDetail(attributes 全部改为 literal('SUM(available_quantity + locked_quantity)'));回归测试 222/222 通过、ESLint 0 错误(测试 helper fetchStorageQuantity/拆行断言/多库位拆行用例同步改口径)。", + "文档变更范围:methods/system.json 的 module=stock.check 分组更新 8 条 method(workData/workDataDetail/workDataSpaceDetails/result/report/finish/detail/addDetail 的 description/notes 同步库位账面=可用+锁定口径);根版本 0.3.248 → 0.3.249、updatedAt 2026-10-05 → 2026-10-06;methods/changes/system.json 新增本条(插入数组首位);其余 15 条 method 未改动(stock.check 分组仍为 23 条)。", + "库表维护源说明:维护源为库表(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,127.0.0.1:3307/wms)与生产库(WMS_DB_TARGET=production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致。" + ] + }, + { + "version": "0.3.248", + "date": "2026-10-05", + "type": "updated", + "summary": "盘点作业数据接口(stock.check.workData/workDataDetail/workDataSpaceDetails)库位账面改为可用+锁定(SUM(available_quantity+locked_quantity))并新增 locked_quantity 锁定数量字段(0.3.247 → 0.3.248)", + "methods": [ + "stock.check.workData", + "stock.check.workDataDetail", + "stock.check.workDataSpaceDetails" + ], + "notes": [ + "变更内容:goods 视图 locations 各项与 space 视图 goods 子项的库位账面 system_quantity 由 wms_storage SUM(quantity) 改为 SUM(available_quantity+locked_quantity)(=可用+锁定),并新增 locked_quantity(该库位锁定数量,SUM(locked_quantity));盘点数量 quantity/checked_quantity 口径不变;盲盘仍不返回任何数量字段。", + "代码依据:app/service/systems/stock_check.js#_buildGoodsWorkRows/#_buildSpaceWorkRows(Storage 查询 attributes 增加 literal('SUM(available_quantity + locked_quantity)') 与 fn('SUM', col('locked_quantity')));result/report/finish 的差异汇总口径不变(仍按 quantity 与明细快照);回归测试 222/222 通过、ESLint 0 错误。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData、stock.check.workDataDetail 与 stock.check.workDataSpaceDetails 三条(description/response.rows/notes 同步库位账面=可用+锁定口径与 locked_quantity 字段);根版本 0.3.247 → 0.3.248、updatedAt 保持 2026-10-05;methods/changes/system.json 新增本条(插入数组首位);其余 20 条 method 未改动(stock.check 分组仍为 23 条)。", + "库表维护源说明:维护源为库表(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,127.0.0.1:3307/wms)与生产库(WMS_DB_TARGET=production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致。" + ] + }, + { + "version": "0.3.247", + "date": "2026-10-05", + "type": "updated", + "summary": "stock.check.workData / workDataDetail 的 goods 视图明盘库位同时输出账面数量(system_quantity)与盘点数量(quantity)两个字段(0.3.246 → 0.3.247)", + "methods": [ + "stock.check.workData", + "stock.check.workDataDetail" + ], + "notes": [ + "变更内容:goods 视图明盘(mode=open)每库位由单一 quantity(实盘合计)改为同时输出 system_quantity(该库位账面数量,wms_storage 该库位 SUM(quantity),无库存记录库位为 0)与 quantity(该库位盘点数量=实盘合计,未盘库位为 0)两字段区分开;盲盘仍不返回任何数量字段。", + "代码依据:app/service/systems/stock_check.js#_buildGoodsWorkRows(Storage 查询 attributes 增加 fn('SUM', col('quantity')) 按 stock+space 分组汇总,构建 stockId→spaceCode→账面数量映射;buildLocationItem 明盘输出双数量字段);行级 checked_quantity 仍为 locations.quantity 合计、diff/is_diff 仅存在作业记录的行计算(口径不变);回归测试 222/222 通过、ESLint 0 错误。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 与 stock.check.workDataDetail 两条(description/response.rows/notes 同步明盘库位双数量字段口径);根版本 0.3.246 → 0.3.247、updatedAt 保持 2026-10-05;methods/changes/system.json 新增本条(插入数组首位);其余 21 条 method 未改动(stock.check 分组仍为 23 条)。", + "库表维护源说明:维护源为库表(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,127.0.0.1:3307/wms)与生产库(WMS_DB_TARGET=production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致。" + ] + }, + { + "version": "0.3.246", + "date": "2026-10-05", + "type": "updated", + "summary": "stock.check.workData / workDataDetail 的 goods 视图 locations 改为商品所在全部库位列表(明盘显示库位+数量、盲盘只显示库位;未盘行不误显盘亏差异)(0.3.245 → 0.3.246)", + "methods": [ + "stock.check.workData", + "stock.check.workDataDetail" + ], + "notes": [ + "变更内容:_buildGoodsWorkRows 的 locations 由「仅已盘库位(按首条记录 id 升序)」改为「商品所在全部库位列表」——基础库位取自 wms_storage(任务 stock_id 集合 + is_enabled=1 未删除,DISTINCT space_id)经库位表取 space_code 并按拣货路径排序(pick_sequence 升序、pick_priority 降序、库位 id 升序兜底);无库存但已有作业记录的库位按首条记录 id 升序追加在末尾;空库位(location_code 空)组仍排在最后;未盘库位输出空信息(checked_at/checker_name=null、record_ids/images 空数组、明盘 quantity=0)。", + "差异口径:明盘 checked_quantity=locations 各库位 quantity 合计(未盘行恒 0);diff_quantity/is_diff 仅对存在作业记录(detailRecords.length>0)的行计算,未盘行恒 0(避免未盘行误显盘亏差异——此前 locations 非空导致未盘行 diff_quantity=0-账面为负);盲盘仍不返回任何数量字段。", + "代码依据:app/service/systems/stock_check.js#_buildGoodsWorkRows(workData 与 workDataDetail goods 明细分支复用同一构建函数);回归测试 222/222 通过、ESLint 0 错误。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 与 stock.check.workDataDetail 两条(description/response.rows/notes 同步 goods 视图 locations 商品所在全部库位列表口径);根版本 0.3.245 → 0.3.246、updatedAt 2026-10-04 → 2026-10-05;methods/changes/system.json 新增本条(插入数组首位);其余 21 条 method 未改动(stock.check 分组仍为 23 条)。", + "库表维护源说明:维护源为库表(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,127.0.0.1:3307/wms)与生产库(WMS_DB_TARGET=production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致。" + ] + }, + { + "version": "0.3.245", + "date": "2026-10-04", + "type": "added", + "summary": "新增 stock.check.workDataDetail 盘点明细单行作业数据接口(workData 单行版,仅库位任务明细):入参 detail_id(库位范围行,兼容 detailId 驼峰),返回统一 success 包装、data 为单行作业数据(结构与 workData location 视图单行一致);仅任务状态 approved/checking 可拉取(0.3.244 → 0.3.245)", + "methods": [ + "stock.check.workDataDetail" + ], + "notes": [ + "变更内容:ALL_METHOD_NAMES 新增 workDataDetail(22→23)、_noNeedLog 查询类清单新增 workDataDetail;方法层 stock.check.workDataDetail 兼容 detail_id/detailId 驼峰写法、warehouse_id 服务端自动注入;系统层仅库位任务明细(scope_type=location)支持,返回结构与 workData location 视图单行一致(detail_id/location_id/location_code/location_name/status/has_unknown/is_empty/checked_at/checkers/goods)。", + "校验口径:detail_id 非正整数 400『盘点明细ID不能为空』;明细不存在 400『盘点明细不存在』;scope_type 非 location 400『仅库位任务明细支持拉取单行作业数据』;任务不存在 400『盘点任务不存在』;任务状态非 approved/checking 400 拒绝(与 stock.check.workData 同口径)。", + "代码依据:app/service/systemMethods/stock/check.js#workDataDetail + app/service/systems/stock_check.js#workDataDetail(复用 _buildLocationWorkRows);回归测试 216/216 通过、ESLint 0 错误。", + "文档变更范围:methods/system.json 的 module=stock.check 分组新增 stock.check.workDataDetail 一条(位于 stock.check.workData 之后);根版本 0.3.244 → 0.3.245、updatedAt 保持 2026-10-04;methods/changes/system.json 新增本条(插入数组首位);其余 22 条 method 未改动(stock.check 分组由 22 条增至 23 条)。", + "库表维护源说明:维护源为库表(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)与生产库(WMS_DB_TARGET=production)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致。" + ] + }, + { + "version": "0.3.244", + "date": "2026-10-04", + "type": "updated", + "summary": "stock.check.workData 新增 keyword 入参(可选,向后兼容):仅库位任务(location 视图)按行 location_code/location_name 模糊匹配(不区分大小写)过滤任务明细后再分页(0.3.243 → 0.3.244)", + "methods": [ + "stock.check.workData" + ], + "notes": [ + "变更内容:params 新增 keyword(string,可选,向后兼容)——先分流:仅库位任务(type=location/all,即服务端解析视图为 location)生效;生效时按 location 视图行字段 location_code(优先明细快照,缺失回退库位表 space_code)与 location_name(custom_name 兜底 space_code)做模糊匹配(contains、不区分大小写)过滤任务明细后再分页返回;非库位任务(goods/store,space/goods 视图)忽略该参数;keyword 为空/纯空白视为未传不过滤。", + "分页口径:过滤在分页切片之前完成,total 为过滤后的行数,rows 为过滤后的当前页行(分页仍按 pagination.{page,pageSize} 切片,与既有口径一致)。", + "代码依据:app/service/systemMethods/stock/check.js#workData(包装层透传 keyword)+ app/service/systems/stock_check.js#workData(normalizedKeyword=String(keyword||\"\").trim().toLowerCase(),resolvedView===\"location\" 且非空时按 location_code/location_name includes 过滤);回归测试 214/214 通过、ESLint 0 错误。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 一条(params 新增 keyword、description/response.rows/response.total 同步过滤口径;headers/errors/isNeedAuth/isNeedLogin 不变);根版本 0.3.243 → 0.3.244、updatedAt 保持 2026-10-04;methods/changes/system.json 新增本条(插入数组首位);其余 21 条 method 未改动(stock.check 分组仍为 22 条)。", + "库表维护源说明:维护源为库表(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 往返校验);生产库此前停留在 0.3.240,本次回填一并同步 0.3.241(detail 精简)、0.3.242(workData 返回 view)、0.3.243(waybill 主单号数组)三批累积差异。" + ] + }, { "version": "0.3.243", "date": "2026-10-04", diff --git a/methods/system.json b/methods/system.json index 03800da..e0292d4 100644 --- a/methods/system.json +++ b/methods/system.json @@ -1,8 +1,8 @@ { "module": "system", "description": "系统接口标准入口,method 对应系统内置方法,全部使用 POST 请求,参数统一放在 body 内", - "version": "0.3.243", - "updatedAt": "2026-10-04", + "version": "0.3.249", + "updatedAt": "2026-10-06", "headers": [ { "name": "platform", @@ -38289,7 +38289,7 @@ "商品货主限制:任务 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_location(check_id, stock_id, location_id),库位行原唯一约束 uk_check_location 已放宽为普通索引 idx_check_location、幂等由应用层查重保证);location_ids 路径跳过项按库位ID记入 skipped。", - "商品拆行口径(本次改造,商品任务必须按库位盘点):type=store/goods 传 stock_ids 后按商品在仓库的启用库存库位(wms_storage is_enabled=1,按 space_id 分组 SUM(quantity))拆行——每个「商品+库位」生成一条 scope_type=goods 明细行(location_id/location_code 快照绑定库存库位、system_quantity=该库位库存 SUM);一个商品多个库位对应多行;无启用库存库位的商品计入 invalid_stock_ids 不入明细;added/total_items 均为拆分明细行数。代码依据:app/service/systems/stock_check.js#_addGoodsDetailRows(Storage.findAll warehouse_id+stock_id in+is_enabled=1、attributes SUM(quantity)、group=[stock_id, space_id];LocationSpace 按 id 取 space_code 快照)。", + "商品拆行口径(本次改造,商品任务必须按库位盘点):type=store/goods 传 stock_ids 后按商品在仓库的启用库存库位(wms_storage is_enabled=1,按 space_id 分组 SUM(available_quantity+locked_quantity)(=可用+锁定))拆行——每个「商品+库位」生成一条 scope_type=goods 明细行(location_id/location_code 快照绑定库存库位、system_quantity=该库位库存 SUM(可用+锁定));一个商品多个库位对应多行;无启用库存库位的商品计入 invalid_stock_ids 不入明细;added/total_items 均为拆分明细行数。代码依据:app/service/systems/stock_check.js#_addGoodsDetailRows(Storage.findAll warehouse_id+stock_id in+is_enabled=1、attributes SUM(quantity)、group=[stock_id, space_id];LocationSpace 按 id 取 space_code 快照)。", "响应统一 data 层封装(2026-10-02 起):成功 { flag:\"success\", code:1, message:\"ok\", data:<业务数据整体>, timestamp };失败 { flag:\"failure\", code:<业务错误码>, message:<错误文案>, data:null, timestamp }。本方法业务数据整体位于 data 内,data 内字段口径与改造前一致(原顶层业务字段全部移入 data.children)。代码依据:app/service/systemMethods/stock/check.js#_call(22 个方法共用统一包装)+ app/lib/api_response.js#toSuccess(识别标准载荷后顶层补充 timestamp)。" ] }, @@ -38414,7 +38414,7 @@ }, { "method": "stock.check.detail", - "description": "拉取盘点任务详情(只返回任务本身信息):入参 id(盘点任务ID);返回 { check },check 为盘点主表信息(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=盘点结束时间(完成盘点的时间));不再返回明细范围行(rows)与明细总条数(total)——盘点明细范围行/盘点结果聚合请调用 stock.check.result,作业记录请调用 stock.check.recordList,盘点作业数据请调用 stock.check.workData;400 边界(任务ID为空/任务不存在)。", + "description": "拉取盘点任务详情(只返回任务本身信息):入参 id(盘点任务ID);返回 { check },check 为盘点主表信息(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=盘点结束时间(完成盘点的时间))+ 数量差异汇总 profit_total(盘盈合计数量)/loss_total(盘亏合计数量,正数口径,与 finish 一致;商品行聚合 vs 账面快照(未盘商品行按实盘 0 计盘亏)、库位行按商品聚合 vs wms_storage 账面(SUM(available_quantity+locked_quantity)=可用+锁定,未盘库位行不计差异)、未知商品按实盘计盘盈;无作业记录时均为 0);不再返回明细范围行(rows)与明细总条数(total)——盘点明细范围行/盘点结果聚合请调用 stock.check.result,作业记录请调用 stock.check.recordList,盘点作业数据请调用 stock.check.workData;400 边界(任务ID为空/任务不存在)。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -38463,7 +38463,7 @@ "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=盘点结束时间(完成盘点的时间))" + "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 + profit_total 盘盈合计数量 / loss_total 盘亏合计数量(正数口径,与 finish 一致;商品行聚合 vs 账面快照(未盘商品行按实盘 0 计盘亏)、库位行按商品聚合 vs wms_storage 账面(SUM(available_quantity+locked_quantity)=可用+锁定,未盘库位行不计差异)、未知商品按实盘计盘盈);start_time=盘点开始时间(第一个盘点明细写入的时间)、end_time=盘点结束时间(完成盘点的时间))" } ] }, @@ -38494,7 +38494,7 @@ }, { "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)含 is_empty(是否空库位标记)+ 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 口径);空库位标记(is_empty=true)时:stocks=[]、unknown_items=[]、checked_quantity=0、status=checked(视为已盘点),账面有库存时 diff_quantity 为负数(盘亏,差异=0-库位账面库存总量)、is_diff=1;无作业记录时聚合字段为 null、records/locations/stocks 为空数组。", + "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)含 is_empty(是否空库位标记)+ 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(available_quantity+locked_quantity)=可用+锁定),location_id 为空时账面按 0)+ unknown_items(口径同商品行);每条作业记录挂载 images(FileReference business_type=stock_check_record,仿收货 receivingItem 口径);空库位标记(is_empty=true)时:stocks=[]、unknown_items=[]、checked_quantity=0、status=checked(视为已盘点),账面有库存时 diff_quantity 为负数(盘亏,差异=0-库位账面库存总量)、is_diff=1;无作业记录时聚合字段为 null、records/locations/stocks 为空数组。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -38549,7 +38549,7 @@ "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)含范围行字段 + is_empty(是否空库位标记:该明细存在空标记记录(is_empty=1)时为 true)+ 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(口径同商品行);空库位标记(is_empty=true)时:stocks=[]、unknown_items=[]、checked_quantity=0、diff_quantity=0-库位账面库存总量(账面有库存时为负数=盘亏、账面为 0 时为 0)、is_diff=账面有库存时为 1、status=checked(视为已盘点);无作业记录时 records/locations/stocks/unknown_items 为空数组、checked_quantity/diff_quantity/last_checked_at 为 null" + "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)含范围行字段 + is_empty(是否空库位标记:该明细存在空标记记录(is_empty=1)时为 true)+ stocks(按商品聚合数组 [{ stock_id, item_code, item_name, system_quantity, checked_quantity, diff_quantity }],按 stock_id 升序,仅含存在作业记录的已知商品;system_quantity 为 wms_storage 账面(space_id+stock_id SUM(available_quantity+locked_quantity)=可用+锁定),location_id 为空时按 0)+ checked_quantity(行级合计=行内商品实盘合计,无记录为 null)/ diff_quantity(行内各商品差异代数和,无记录为 null)/ is_diff / status + location_codes / checkers / last_checked_at + records / locations + unknown_items(口径同商品行);空库位标记(is_empty=true)时:stocks=[]、unknown_items=[]、checked_quantity=0、diff_quantity=0-库位账面库存总量(账面有库存时为负数=盘亏、账面为 0 时为 0)、is_diff=账面有库存时为 1、status=checked(视为已盘点);无作业记录时 records/locations/stocks/unknown_items 为空数组、checked_quantity/diff_quantity/last_checked_at 为 null" }, { "name": "total", @@ -38579,19 +38579,19 @@ "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 补齐。", + "库位行账面口径:wms_storage 按 (space_id, stock_id) SUM(available_quantity+locked_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。", "响应统一 data 层封装(2026-10-02 起):成功 { flag:\"success\", code:1, message:\"ok\", data:<业务数据整体>, timestamp };失败 { flag:\"failure\", code:<业务错误码>, message:<错误文案>, data:null, timestamp }。本方法业务数据整体位于 data 内,data 内字段口径与改造前一致(原顶层业务字段全部移入 data.children)。代码依据:app/service/systemMethods/stock/check.js#_call(22 个方法共用统一包装)+ app/lib/api_response.js#toSuccess(识别标准载荷后顶层补充 timestamp)。", - "空库位标记口径(本次新增):库位行存在空标记记录(is_empty=1)时 is_empty=true——stocks 为空数组、unknown_items 为空数组、checked_quantity=0、status=checked(视为已盘点);账面口径:按 location_id 查 wms_storage SUM(quantity)(该库位全部库存账面总量,location_id 为空时按 0),账面>0 时 diff_quantity=-账面总量(盘亏)、is_diff=1,账面=0 时 diff_quantity=0、is_diff=0。代码依据:app/service/systems/stock_check.js#_formatDetailAggregationRow。", + "空库位标记口径(本次新增):库位行存在空标记记录(is_empty=1)时 is_empty=true——stocks 为空数组、unknown_items 为空数组、checked_quantity=0、status=checked(视为已盘点);账面口径:按 location_id 查 wms_storage SUM(available_quantity+locked_quantity)(该库位全部库存账面总量=可用+锁定,location_id 为空时按 0),账面>0 时 diff_quantity=-账面总量(盘亏)、is_diff=1,账面=0 时 diff_quantity=0、is_diff=0。代码依据:app/service/systems/stock_check.js#_formatDetailAggregationRow。", "文档变更范围:methods/system.json 的 module=stock.check 分组更新 5 条 method(stock.check.report:params 新增 is_empty 入参、errors 400 补「仅库位盘点明细支持空库位标记」、description/response/notes 补充空库位语义与互斥及汇总口径;stock.check.workData:description/response.rows 的 location 行新增 is_empty 字段说明;stock.check.result:description/response.rows 库位行新增 is_empty 与空标记盘亏口径;stock.check.recordList:response.rows 记录全字段说明新增 is_empty;stock.check.export:description/notes 补 Sheet2 空库位行输出口径);根版本 0.3.233 → 0.3.234、updatedAt 保持 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);其余 15 条 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,127.0.0.1:3307/wms)与生产库(显式 WMS_DB_TARGET=production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致;stock.check 分组共 20 条 method 无损。" ] }, { "method": "stock.check.workData", - "description": "拉取盘点作业数据(视图由任务范围与 is_goods 入参驱动,view 入参已废弃忽略):入参 id(盘点任务ID)+ is_goods(可选,商品任务是否按商品视图返回——true=goods 视图;缺省 false=聚合库位 space 视图;兼容 isGoods 驼峰写法;库位任务无视该参数);返回 { view, rows, total, page, pageSize }(view=服务端实际解析出的视图类型 location/goods/space,供调用方判断 rows 行结构;不返回任务主表信息 check——任务信息请调用 stock.check.detail),rows 结构随解析视图不同(先构建全量行再按页切片,rows 为当前页行)、total=全部行数(未分页口径)、page=当前页码(默认 1)、pageSize=每页数量(默认 20,上限 200),任务无对应范围行时 rows 返回空数组。分页:入参 data.pagination({ page, pageSize }),未传或非法时默认 page=1、pageSize=20(上限 200),分页口径与 stock.check.list 一致。视图解析:任务范围为库位(type=location/all)一律按 location 视图;任务范围为商品(type=goods/store)默认 space 视图、仅 is_goods=true 时 goods 视图。location(库位结构):以任务库位范围行(scope_type=location)为列表(按明细 id 升序),行内挂该库位的盘点作业记录 goods 子列表(已知商品与未知商品记录均入内,未知商品 stock_id=null、item_code 用条码兜底;每项含 record_id 作业记录 ID(单条记录直接定位,可调 recordDelete/recheckClearLocation 移除)与 images 作业记录照片——FileReference business_type=stock_check_record 经 _attachRecordImages 挂载,与 result/recordList 口径一致,无照片为空数组)+ has_unknown 标记(该库位是否含未知商品记录)+ is_empty 标记(该库位是否存在空库位标记记录:空标记记录不计入 goods 子列表,存在空标记后该行 status=checked 视为已盘点);goods(商品结构):以任务商品范围行(scope_type=goods)为列表(按明细 id 升序),行内挂按库位聚合的 locations 作业记录(每项含 record_ids 该库位该商品全部作业记录 ID(按记录 id 升序)与 images 该库位该商品全部作业照片(扁平去重),供前端编辑/移除记录),明盘(mode=open)返回账面快照/已盘合计/差异,盲盘(mode=blind)不返回任何数量字段(行级 images 仍为商品主图);space(聚合库位列表):库位集合=当前库存库位 ∪ 作业记录库位(当前库存库位:wms_storage 中任务 stock_id 集合的启用未删除存储 DISTINCT space_id;作业记录库位:wms_stock_check_record 的 location_id 已回填直接用、未回填的按 location_code 匹配 wms_location_space.space_code 补查,与库存库位去重后取并集),按拣货路径排序(pick_sequence 升序、pick_priority 降序、库位 id 升序兜底),行内 goods 为该库位下的任务商品(每项含 record_ids 该商品在该库位全部作业记录 ID(按记录 id 升序)与 images 该商品在该库位的作业照片聚合(扁平去重,不再输出商品主图),供前端编辑/移除记录),明盘含库位账面与已盘数量、盲盘不含数量;盘点前库存已出空但已有盘点作业记录的库位也能展示(该库位商品行账面 system_quantity 按 0、checked_quantity 按该库位实盘合计)。状态限制:仅任务状态为 approved(审核完成)或 checking(盘点作业中)时可拉取盘点作业数据,其他状态(created 已创建/submitted 待审核/rejected 已驳回/completed 已完成/cancelled 已取消)返回 400「当前状态(xx)不允许拉取盘点作业数据,仅审核完成(approved)或盘点作业中(checking)的任务可拉取」。", + "description": "拉取盘点作业数据(视图由任务范围与 is_goods 入参驱动,view 入参已废弃忽略):入参 id(盘点任务ID)+ is_goods(可选,商品任务是否按商品视图返回——true=goods 视图;缺省 false=聚合库位 space 视图;兼容 isGoods 驼峰写法;库位任务无视该参数)+ keyword(可选,关键字:仅库位任务 location 视图生效——按行 location_code/location_name 模糊匹配(不区分大小写)过滤任务明细后再分页;非库位任务忽略;空/纯空白视为未传);返回 { view, rows, total, page, pageSize }(view=服务端实际解析出的视图类型 location/goods/space,供调用方判断 rows 行结构;不返回任务主表信息 check——任务信息请调用 stock.check.detail),rows 结构随解析视图不同(先构建全量行——location 视图且 keyword 非空时先按 location_code/location_name 过滤,再按页切片,rows 为当前页行)、total=全部行数(未分页口径;location 视图 + keyword 时 total 为过滤后行数)、page=当前页码(默认 1)、pageSize=每页数量(默认 20,上限 200),任务无对应范围行时 rows 返回空数组。分页:入参 data.pagination({ page, pageSize }),未传或非法时默认 page=1、pageSize=20(上限 200),分页口径与 stock.check.list 一致。视图解析:任务范围为库位(type=location/all)一律按 location 视图;任务范围为商品(type=goods/store)默认 space 视图、仅 is_goods=true 时 goods 视图。location(库位结构):以任务库位范围行(scope_type=location)为列表(按明细 id 升序),行内挂该库位的盘点作业记录 goods 子列表(已知商品与未知商品记录均入内,未知商品 stock_id=null、item_code 用条码兜底;每项含 record_id 作业记录 ID(单条记录直接定位,可调 recordDelete/recheckClearLocation 移除)与 images 作业记录照片——FileReference business_type=stock_check_record 经 _attachRecordImages 挂载,与 result/recordList 口径一致,无照片为空数组)+ has_unknown 标记(该库位是否含未知商品记录)+ is_empty 标记(该库位是否存在空库位标记记录:空标记记录不计入 goods 子列表,存在空标记后该行 status=checked 视为已盘点);goods(商品结构):以任务商品范围行(scope_type=goods)为列表(按明细 id 升序),行内 locations 为商品所在全部库位列表(商品库存库位取自 wms_storage——启用未删除存储 DISTINCT space_id 按拣货路径排序,无库存但已有作业记录的库位追加在末尾;每项含 record_ids 该库位该商品全部作业记录 ID(按记录 id 升序)与 images 该库位该商品全部作业照片(扁平去重),供前端编辑/移除记录;未盘库位 checked_at=null、record_ids/images 为空数组),明盘(mode=open)返回账面快照/已盘合计/差异,每库位含 system_quantity(该库位账面数量=可用+锁定,wms_storage SUM(available_quantity+locked_quantity),无库存记录库位为 0)、locked_quantity(该库位锁定数量,wms_storage SUM(locked_quantity))与 quantity(该库位盘点数量,未盘库位为 0),盲盘(mode=blind)不返回任何数量字段(行级 images 仍为商品主图);space(聚合库位列表):库位集合=当前库存库位 ∪ 作业记录库位(当前库存库位:wms_storage 中任务 stock_id 集合的启用未删除存储 DISTINCT space_id;作业记录库位:wms_stock_check_record 的 location_id 已回填直接用、未回填的按 location_code 匹配 wms_location_space.space_code 补查,与库存库位去重后取并集),按拣货路径排序(pick_sequence 升序、pick_priority 降序、库位 id 升序兜底),行内 goods 为该库位下的任务商品(每项含 record_ids 该商品在该库位全部作业记录 ID(按记录 id 升序)与 images 该商品在该库位的作业照片聚合(扁平去重,不再输出商品主图),供前端编辑/移除记录),明盘含库位账面(可用+锁定)/锁定数量/已盘数量、盲盘不含数量;盘点前库存已出空但已有盘点作业记录的库位也能展示(该库位商品行账面 system_quantity 按 0、locked_quantity 按 0、checked_quantity 按该库位实盘合计)。状态限制:仅任务状态为 approved(审核完成)或 checking(盘点作业中)时可拉取盘点作业数据,其他状态(created 已创建/submitted 待审核/rejected 已驳回/completed 已完成/cancelled 已取消)返回 400「当前状态(xx)不允许拉取盘点作业数据,仅审核完成(approved)或盘点作业中(checking)的任务可拉取」。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -38617,6 +38617,13 @@ "source": "body", "description": "商品任务是否按商品视图返回(true=goods);缺省 false=聚合库位视图 space;库位任务无视该参数(兼容 isGoods 驼峰写法)" }, + { + "name": "keyword", + "type": "string", + "required": false, + "source": "body", + "description": "关键字(可选,向后兼容新增):仅库位任务(服务端解析视图为 location,即任务类型 location/all)生效——按行 location_code(优先明细快照,缺失回退库位表 space_code)与 location_name(custom_name 兜底 space_code)做模糊匹配(contains、不区分大小写)过滤任务明细后再分页返回;非库位任务(goods/store,space/goods 视图)忽略该参数;keyword 为空/纯空白视为未传不过滤" + }, { "name": "pagination", "type": "object", @@ -38660,13 +38667,13 @@ "name": "rows", "type": "array", "required": true, - "description": "盘点作业数据行列表(当前页行:先构建全量行再按页切片,total 为全部行数——未分页口径),结构随解析视图不同——location 视图行:detail_id 明细ID / location_id 库位ID / location_code 库位编码(优先明细快照,缺失回退库位表 space_code)/ location_name 库位名称(custom_name 兜底 space_code)/ status 盘点状态(checked=存在作业记录,unchecked=无)/ has_unknown 是否含未知商品记录(该库位存在 stock_id 为空的作业记录时为 true,未知商品同样计入 goods) / is_empty 是否空库位标记(该库位存在空库位标记记录(is_empty=1)时为 true;空标记记录不计入 goods 子列表;存在空标记后该行 status=checked 视为已盘点) / checked_at 该库位最近上报时间(无记录为 null)/ checkers 盘点人去重数组 + goods 作业记录子列表(已知商品与未知商品记录均入内,字段统一 record_id 作业记录ID(单条记录直接定位,可调 recordDelete/recheckClearLocation 移除)/stock_id/item_code/item_name/barcode/images 作业记录照片(已知商品与未知商品均经 _attachRecordImages 挂载 FileReference business_type=stock_check_record,与 result/recordList 口径一致,不再输出商品主图,无照片为空数组)/store_id/store_name/quantity 实盘数量/checked_at/checker_name——已知商品(stock_id 有值)商品信息批量取自 stockWarehouse.getStockDetails 带缓存、货主名经 _resolveStoreNameMap 解析;未知商品(stock_id=null)item_code 用条码兜底、item_name 用名称快照兜底条码、store_id/store_name 为 null);goods 视图行:detail_id/stock_id/item_code/item_name/spec/store_id/store_name/barcode/images(行级 images 仍为商品主图 image_url)+ locations 按库位聚合数组([{ location_code, checked_at, checker_name, record_ids 该库位该商品全部作业记录 ID(按记录 id 升序,供前端编辑/移除记录), images 该库位该商品全部记录的作业照片(扁平去重,无照片为空数组) }],空库位归 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/record_ids/images);space 视图行:id(库位ID wms_location_space.id)/space_code(库位编码)/custom_barcode(库位自定义条码,空为 null)/custom_name(库位自定义名称,空为 null 不兜底 space_code;库位字段对齐库位查询惯例 index.searchSpace)+ goods 该库位下的任务商品子列表(detail_id/stock_id/item_code/item_name/spec/store_id/store_name/barcode/images 该商品在该库位的作业照片聚合(扁平去重,不再输出商品主图,无照片为空数组)/record_ids 该商品在该库位的全部作业记录 ID(按记录 id 升序,供前端编辑/移除记录) + status 已盘状态(该 detail_id+location_code 存在作业记录即 checked,否则 unchecked)),明盘 goods 各项另含 system_quantity(wms_storage space+stock SUM(quantity) 账面,该库位无库存记录时按 0)/checked_quantity(该商品在该库位的实盘合计),盲盘不含数量;库位集合=当前库存库位 ∪ 作业记录库位(盘点前库存已出空但已有盘点作业记录的库位也能展示)" + "description": "盘点作业数据行列表(当前页行:先构建全量行——location 视图且 keyword 非空时先按行 location_code/location_name 模糊匹配(不区分大小写)过滤,再按页切片;total 为全部行数——未分页口径;location 视图 + keyword 时 rows 为过滤后的库位行、total 同步过滤口径;非库位任务(goods/store,space/goods 视图)忽略 keyword),结构随解析视图不同——location 视图行:detail_id 明细ID / location_id 库位ID / location_code 库位编码(优先明细快照,缺失回退库位表 space_code)/ location_name 库位名称(custom_name 兜底 space_code)/ status 盘点状态(checked=存在作业记录,unchecked=无)/ has_unknown 是否含未知商品记录(该库位存在 stock_id 为空的作业记录时为 true,未知商品同样计入 goods) / is_empty 是否空库位标记(该库位存在空库位标记记录(is_empty=1)时为 true;空标记记录不计入 goods 子列表;存在空标记后该行 status=checked 视为已盘点) / checked_at 该库位最近上报时间(无记录为 null)/ checkers 盘点人去重数组 + goods 作业记录子列表(已知商品与未知商品记录均入内,字段统一 record_id 作业记录ID(单条记录直接定位,可调 recordDelete/recheckClearLocation 移除)/stock_id/item_code/item_name/barcode/images 作业记录照片(已知商品与未知商品均经 _attachRecordImages 挂载 FileReference business_type=stock_check_record,与 result/recordList 口径一致,不再输出商品主图,无照片为空数组)/store_id/store_name/quantity 实盘数量/checked_at/checker_name——已知商品(stock_id 有值)商品信息批量取自 stockWarehouse.getStockDetails 带缓存、货主名经 _resolveStoreNameMap 解析;未知商品(stock_id=null)item_code 用条码兜底、item_name 用名称快照兜底条码、store_id/store_name 为 null);goods 视图行:detail_id/stock_id/item_code/item_name/spec/store_id/store_name/barcode/images(行级 images 仍为商品主图 image_url)+ locations 商品所在全部库位列表(商品库存库位取自 wms_storage——启用未删除存储 DISTINCT space_id 按拣货路径排序;无库存但已有作业记录的库位按首条记录 id 升序追加在末尾;空库位归 location_code=null 组排在最后。每项 [{ location_code, checked_at, checker_name, record_ids 该库位该商品全部作业记录 ID(按记录 id 升序,供前端编辑/移除记录), images 该库位该商品全部记录的作业照片(扁平去重,无照片为空数组) }],未盘库位 checked_at/checker_name 为 null、record_ids/images 为空数组),明盘(mode=open)另含 system_quantity 账面快照/checked_quantity 已盘合计(locations 各库位 quantity 合计,未盘行恒 0)/diff_quantity 差异=已盘-账面(仅存在作业记录的行计算,未盘行恒 0)/is_diff 是否差异 0|1(未盘行恒 0),locations 各项另含 system_quantity 该库位账面数量(wms_storage 该库位 SUM(available_quantity+locked_quantity),无库存记录库位 0)、locked_quantity 该库位锁定数量(wms_storage 该库位 SUM(locked_quantity))与 quantity 该库位盘点数量(实盘合计,未盘库位 0),盲盘(mode=blind)不返回任何数量字段(locations 仅 location_code/checked_at/checker_name/record_ids/images);space 视图行:id(库位ID wms_location_space.id)/space_code(库位编码)/custom_barcode(库位自定义条码,空为 null)/custom_name(库位自定义名称,空为 null 不兜底 space_code;库位字段对齐库位查询惯例 index.searchSpace)+ goods 该库位下的任务商品子列表(detail_id/stock_id/item_code/item_name/spec/store_id/store_name/barcode/images 该商品在该库位的作业照片聚合(扁平去重,不再输出商品主图,无照片为空数组)/record_ids 该商品在该库位的全部作业记录 ID(按记录 id 升序,供前端编辑/移除记录) + status 已盘状态(该 detail_id+location_code 存在作业记录即 checked,否则 unchecked)),明盘 goods 各项另含 system_quantity(wms_storage space+stock SUM(available_quantity+locked_quantity) 账面=可用+锁定,该库位无库存记录时按 0)/locked_quantity(该库位锁定数量,SUM(locked_quantity))/checked_quantity(该商品在该库位的实盘合计),盲盘不含数量;库位集合=当前库存库位 ∪ 作业记录库位(盘点前库存已出空但已有盘点作业记录的库位也能展示)" }, { "name": "total", "type": "number", "required": true, - "description": "行总数(全部行数——未分页口径,任务无对应范围行时为 0;分页时 rows 为当前页行、total 保持全部行数不变)" + "description": "行总数(全部行数——未分页口径,任务无对应范围行时为 0;分页时 rows 为当前页行、total 保持全部行数不变;location 视图 + keyword 非空时 total 为过滤后的行数)" }, { "name": "page", @@ -38709,8 +38716,8 @@ ], "notes": [ "代码依据:app/service/systemMethods/stock/check.js#workData(warehouse_id 由服务端从 ctx.user.store_id 自动注入,前端无需传递;const { id, is_goods: isGoodsSnake, isGoods: isGoodsCamel, pagination } = data || {},isGoods=is_goods 未定义时回退 isGoods(兼容 isGoods 驼峰写法);不再读取、不再校验 view,透传 { warehouseId, id, isGoods, pagination })+ app/service/systems/stock_check.js#workData(id 非正整数抛 400『盘点任务ID不能为空』;任务不存在(按 id+warehouse_id 查 wms_stock_check)抛 400『盘点任务不存在』;状态守卫:任务状态非 REPORT_ALLOWED_STATUSES(approved/checking)时抛 400『当前状态(xx)不允许拉取盘点作业数据,仅审核完成(approved)或盘点作业中(checking)的任务可拉取』;视图解析:normalizedType=String(check.type||'').trim(),type=location/all 一律 location 视图(无视 view/is_goods),否则 goodsViewRequested=isGoods===true||'true'||1 时 goods 视图、其余默认 space 视图;按解析视图分派 _buildLocationWorkRows/_buildGoodsWorkRows/_buildSpaceWorkRows,统一返回 { check: _formatCheckRow 口径, rows, total: rows.length, page, pageSize })。本次代码已改(view 入参废弃、is_goods 驱动视图)并测试通过 197/197、ESLint 0 错误。", - "三视图口径(由任务范围 + is_goods 解析后分派):location=库位结构(库位范围任务一律该视图),以任务库位范围行(scope_type=location)为列表(按明细 id 升序),行内挂该库位盘点作业记录 goods 子列表(已知商品与未知商品记录均入内:已知商品 stock_id 有值,商品信息批量取自 stockWarehouse.getStockDetails 带缓存、货主名 _resolveStoreNameMap 解析;未知商品 stock_id=null,item_code 用条码兜底、item_name 用名称快照兜底条码、store_id/store_name 为 null;已知/未知商品的 images 均为作业记录照片(经 _attachRecordImages 挂载 FileReference business_type=stock_check_record,已知商品不再输出商品主图 image_url)),has_unknown 标记该库位是否含未知商品记录;goods=商品结构(商品范围任务且 is_goods=true 时该视图),以任务商品范围行(scope_type=goods)为列表(按明细 id 升序),行内挂按库位聚合的 locations(空库位归 location_code=null 组,按首条记录 id 升序);space=聚合库位列表(商品范围任务默认该视图),库位集合=当前库存库位 ∪ 作业记录库位——当前库存库位:wms_storage(warehouse_id + stock_id 在集合 + is_enabled=1 未删除)DISTINCT space_id;作业记录库位:wms_stock_check_record 的 location_id 已回填直接用、未回填的按 location_code 匹配 wms_location_space.space_code 补查,与库存库位去重后并集;行内 goods 为该库位下的任务商品;盘点前库存已出空但已有盘点作业记录的库位也能展示(该库位商品行账面 system_quantity 按 0、checked_quantity 按该库位实盘合计)。", - "明盘/盲盘数量控制:明盘(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) 账面,该库位无库存记录时按 0)/checked_quantity(该商品在该库位的实盘合计);盲盘(mode=blind)不返回任何数量字段(goods 视图 locations 仅 location_code/checked_at/checker_name/record_ids/images,space 视图 goods 仅商品信息+images/record_ids/status);无作业记录时 locations 为空数组、明盘已盘合计/差异按 0(避免未盘行误显盘亏差异)。", + "三视图口径(由任务范围 + is_goods 解析后分派):location=库位结构(库位范围任务一律该视图),以任务库位范围行(scope_type=location)为列表(按明细 id 升序),行内挂该库位盘点作业记录 goods 子列表(已知商品与未知商品记录均入内:已知商品 stock_id 有值,商品信息批量取自 stockWarehouse.getStockDetails 带缓存、货主名 _resolveStoreNameMap 解析;未知商品 stock_id=null,item_code 用条码兜底、item_name 用名称快照兜底条码、store_id/store_name 为 null;已知/未知商品的 images 均为作业记录照片(经 _attachRecordImages 挂载 FileReference business_type=stock_check_record,已知商品不再输出商品主图 image_url)),has_unknown 标记该库位是否含未知商品记录;goods=商品结构(商品范围任务且 is_goods=true 时该视图),以任务商品范围行(scope_type=goods)为列表(按明细 id 升序),行内 locations 为商品所在全部库位列表(商品库存库位取自 wms_storage 启用未删除存储 DISTINCT space_id 按拣货路径排序,无库存但已有作业记录的库位按首条记录 id 升序追加在末尾,空库位归 location_code=null 组排在最后;明盘每库位含 system_quantity 该库位账面数量与 quantity 该库位盘点数量(未盘库位 0),盲盘仅 location_code/checked_at/checker_name/record_ids/images);space=聚合库位列表(商品范围任务默认该视图),库位集合=当前库存库位 ∪ 作业记录库位——当前库存库位:wms_storage(warehouse_id + stock_id 在集合 + is_enabled=1 未删除)DISTINCT space_id;作业记录库位:wms_stock_check_record 的 location_id 已回填直接用、未回填的按 location_code 匹配 wms_location_space.space_code 补查,与库存库位去重后并集;行内 goods 为该库位下的任务商品;盘点前库存已出空但已有盘点作业记录的库位也能展示(该库位商品行账面 system_quantity 按 0、checked_quantity 按该库位实盘合计)。", + "明盘/盲盘数量控制:明盘(mode=open)goods 视图行返回 system_quantity(明细账面快照)/checked_quantity(已盘合计=locations.quantity 合计)/diff_quantity(已盘-账面,仅存在作业记录的行计算)/is_diff(差异非 0 为 1),locations 各项含 system_quantity(该库位账面数量=可用+锁定,wms_storage 该库位 SUM(available_quantity+locked_quantity),无库存记录库位为 0)、locked_quantity(该库位锁定数量,wms_storage 该库位 SUM(locked_quantity))与 quantity(该库位盘点数量=实盘合计,未盘库位为 0);space 视图 goods 各项含 system_quantity(wms_storage space+stock SUM(available_quantity+locked_quantity) 账面,该库位无库存记录时按 0)/locked_quantity(wms_storage space+stock SUM(locked_quantity))/checked_quantity(该商品在该库位的实盘合计);盲盘(mode=blind)不返回任何数量字段(goods 视图 locations 仅 location_code/checked_at/checker_name/record_ids/images,space 视图 goods 仅商品信息+images/record_ids/status);goods 视图 locations 为商品所在全部库位列表(含未盘库位,无作业记录时各项为空信息),无作业记录的行明盘已盘合计恒 0、差异/is_diff 恒 0(避免未盘行误显盘亏差异)。", "排序口径:space 视图库位按拣货路径排序——pick_sequence 升序、pick_priority 降序、同值按库位 id 升序兜底;space 行内 goods 按 stock_id 升序;location/goods 视图行按明细 id 升序;goods 视图 locations 按首条记录 id 升序。", "权限口径:随 ALL_METHOD_NAMES(22 个:create/list/addDetail/addLocationDetail/detailDelete/detail/result/workData/report/markEmpty/recordList/recordDelete/recheckClearLocation/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 条)。", @@ -38746,7 +38753,249 @@ "view 取值口径:任务范围为库位(type=location/all)一律 location(无视 is_goods/view 入参);任务范围为商品(type=goods/store)默认 space,仅 is_goods=true(含 true/\"true\"/1)时为 goods。与视图解析规则一一对应。", "兼容性影响(破坏性变更):响应 data 移除 check 字段;新增 view 字段;rows/total/page/pageSize 与三视图行结构、明盘盲盘数量控制、状态限制均不变;前端如需任务主表信息改调 stock.check.detail。", "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 一条(description 同步 view/移除 check、response 的 data.children 以 view 替换 check、notes 补充 view 口径与兼容性说明;headers/params/errors/isNeedAuth/isNeedLogin 与 rows 三视图结构不变);根版本 0.3.241 → 0.3.242、updatedAt 保持 2026-10-03;methods/changes/system.json 新增本条(插入数组首位);其余 21 条 method 未改动(stock.check 分组仍为 22 条)。", - "库表维护源说明:维护源为库表(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 往返校验),保持库与文件一致。" + "库表维护源说明:维护源为库表(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 往返校验),保持库与文件一致。", + "keyword 过滤口径(本次新增):keyword(string,可选,向后兼容)仅库位任务(服务端解析视图为 location,即任务类型 location/all)生效——resolvedView===\"location\" 且 normalizedKeyword=String(keyword||\"\").trim().toLowerCase() 非空时,先按行 location_code/location_name 模糊匹配(contains、不区分大小写)过滤全量任务明细行,再按 pagination 切片;非库位任务(goods/store,space/goods 视图)忽略该参数;keyword 为空/纯空白视为未传不过滤;total=filteredRows.length(过滤后行数),rows 为过滤后当前页行。代码依据:app/service/systemMethods/stock/check.js#workData(透传 keyword)+ app/service/systems/stock_check.js#workData(filteredRows)。本次代码已改并测试通过 214/214、ESLint 0 错误。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 一条(params 新增 keyword(string,可选);description 与 response.rows/total 描述同步 keyword 过滤口径(location 视图 + keyword 时 rows 为过滤后的库位行、total 同步过滤口径;非库位任务忽略);headers/errors/isNeedAuth/isNeedLogin 与响应结构不变);根版本 0.3.243 → 0.3.244、updatedAt 保持 2026-10-04;methods/changes/system.json 新增本条(插入数组首位);其余 21 条 method 未改动(stock.check 分组仍为 22 条)。", + "库表维护源说明:维护源为库表(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)与生产库(WMS_DB_TARGET=production)(import 当前 system.json → export 往返校验),保持库与文件一致。", + "goods 视图 locations 商品库位列表口径(本次改造):_buildGoodsWorkRows 的 locations 由「仅已盘库位(按首条记录 id 升序)」改为「商品所在全部库位列表」——基础库位取自 wms_storage(任务 stock_id 集合 + is_enabled=1 未删除,DISTINCT space_id)经库位表取 space_code 并按拣货路径排序(pick_sequence 升序、pick_priority 降序、库位 id 升序兜底);无库存但已有作业记录的库位按首条记录 id 升序追加在末尾;空库位(location_code 空)组仍排在最后。未盘库位输出空信息(checked_at/checker_name=null、record_ids/images 空数组、明盘 quantity=0);明盘 checked_quantity=locations 各库位 quantity 合计(未盘行恒 0);diff_quantity/is_diff 仅对存在作业记录(detailRecords.length>0)的行计算,未盘行恒 0(避免未盘行误显盘亏差异)。盲盘仍不返回任何数量字段。代码依据:app/service/systems/stock_check.js#_buildGoodsWorkRows;回归测试 222/222 通过、ESLint 0 错误。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 一条(description/response.rows/notes 同步 goods 视图 locations 商品所在全部库位列表口径:未盘库位空信息、明盘每库位 quantity(未盘 0)、diff/is_diff 仅已有记录行计算);根版本 0.3.245 → 0.3.246、updatedAt 2026-10-04 → 2026-10-05;methods/changes/system.json 新增本条(插入数组首位);其余 22 条 method 未改动(stock.check 分组仍为 23 条)。", + "goods 视图 locations 明盘库位数量区分(本次改造):明盘每库位同时输出 system_quantity(该库位账面数量,wms_storage 该库位 SUM(quantity),无库存记录库位为 0)与 quantity(该库位盘点数量=实盘合计,未盘库位为 0)两字段区分开;盲盘仍不返回任何数量字段。Storage 查询改为 attributes 增加 fn('SUM', col('quantity')) 按 stock+space 分组汇总,构建 stockId→spaceCode→账面数量映射;行级 checked_quantity 仍为 locations.quantity 合计,diff/is_diff 计算条件不变。代码依据:app/service/systems/stock_check.js#_buildGoodsWorkRows;回归测试 222/222 通过、ESLint 0 错误。", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData 与 stock.check.workDataDetail 两条(description/response.rows/notes 同步 goods 视图明盘库位 system_quantity(账面)+quantity(盘点)双数量字段口径);根版本 0.3.246 → 0.3.247、updatedAt 保持 2026-10-05;methods/changes/system.json 新增本条(插入数组首位);其余 21 条 method 未改动(stock.check 分组仍为 23 条)。", + "库位账面口径改造(本次):盘点作业数据接口的库位账面 system_quantity 由 SUM(quantity) 改为 SUM(available_quantity+locked_quantity)(=可用+锁定),并新增 locked_quantity(该库位锁定数量,SUM(locked_quantity))——goods 视图 locations 各项与 space 视图 goods 子项(workData/workDataDetail/workDataSpaceDetails 共用构建器);盲盘仍不返回任何数量字段。代码依据:app/service/systems/stock_check.js#_buildGoodsWorkRows/#_buildSpaceWorkRows;回归测试 222/222 通过、ESLint 0 错误。(后续已按用户要求全部统一:result/report/finish/detail 差异汇总与 addDetail 拆行快照均改为可用+锁定口径,见 0.3.249 变更记录)", + "文档变更范围:methods/system.json 的 module=stock.check 分组仅更新 stock.check.workData、stock.check.workDataDetail 与 stock.check.workDataSpaceDetails 三条(description/response.rows/notes 同步库位账面=可用+锁定口径与 locked_quantity 字段);根版本 0.3.247 → 0.3.248、updatedAt 保持 2026-10-05;methods/changes/system.json 新增本条(插入数组首位);其余 20 条 method 未改动(stock.check 分组仍为 23 条)。", + "库位账面口径全量统一(本次,0.3.249 同步):全部盘点账面口径统一为 SUM(available_quantity+locked_quantity)(=可用+锁定)——result 库位行 stocks 账面与空库位标记盘亏、report 重算 diff_items 的库位行/空标记账面、finish 差异汇总、detail profit/loss 汇总、addDetail 按库位拆行的明细快照 system_quantity,与盘点作业视图(workData/workDataDetail/workDataSpaceDetails)一致;商品行仍以明细账面快照(system_quantity 列)对比。回归测试 222/222 通过、ESLint 0 错误。" + ] + }, + { + "method": "stock.check.workDataSpaceDetails", + "description": "拉取盘点作业数据(space 视图分页版):入参 id(盘点任务ID)+ location_id(库位ID,可选,兼容 locationId 驼峰写法)+ pagination({page,pageSize},缺省 page=1/pageSize=20,上限 200);warehouse_id 由服务端从当前上下文自动注入,前端无需传递。行结构与 workData space 视图行一致:id=库位ID(wms_location_space.id)/ space_code 库位编码 / custom_barcode 自定义条码 / custom_name 库位名称 / goods 该库位下的任务商品子列表(detail_id 明细ID / stock_id 商品库存ID / item_code 商品编码 / item_name 商品名称 / spec 规格 / store_id 货主ID / store_name 货主名 / barcode 条码 / images 作业照片 / record_ids 作业记录ID列表;明盘 mode=open 另含 system_quantity 账面数量(wms_storage 该库位该商品 SUM(available_quantity+locked_quantity))、locked_quantity 锁定数量(wms_storage 该库位该商品 SUM(locked_quantity))与 checked_quantity 已盘合计;盲盘 mode=blind 不返回任何数量字段;status=checked 该 (detail_id, location_code) 存在作业记录 / unchecked 未盘)。库位按拣货路径排序(pick_sequence 升序、pick_priority 降序,同值按库位 id 升序兜底);传入 location_id 时只返回该库位行(total=1),不传时按分页返回全部库位行;返回 { view:'space', rows, total, page, pageSize }(不返回任务主表信息,任务信息请调用 stock.check.detail)。仅任务状态 approved(审核完成)或 checking(盘点作业中)可拉取(与 workData 同口径)。权限口径:免 API 权限校验,仅需登录(与 stock.check 分组其他方法一致)。", + "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_id", + "type": "number", + "required": false, + "source": "body", + "description": "库位ID(wms_location_space.id,可选;传入时只返回该库位行,兼容 locationId 驼峰写法)" + }, + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页配置:page(页码,默认1)、pageSize(每页数量,默认20,上限200);传入 location_id 时分页参数仅影响返回结构,total 恒为 1" + } + ], + "response": [ + { + "name": "view", + "type": "string", + "required": true, + "description": "恒为 space(聚合库位视图)" + }, + { + "name": "rows", + "type": "array", + "required": true, + "description": "当前页库位行:每行含 id/space_code/custom_barcode/custom_name/goods(goods 结构与 workData space 视图一致,明盘含 system_quantity/checked_quantity/status,盲盘不含数量字段)" + }, + { + "name": "total / page / pageSize", + "type": "object", + "required": true, + "description": "total=全部库位行数(传入 location_id 时恒为 1),page/pageSize=当前分页" + } + ], + "errors": [ + { + "code": "400", + "message": "盘点任务ID不能为空" + }, + { + "code": "400", + "message": "盘点任务不存在" + }, + { + "code": "400", + "message": "当前状态不允许拉取盘点作业数据(仅 approved/checking 可拉取)" + }, + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "500", + "message": "拉取盘点作业数据失败" + } + ] + }, + { + "method": "stock.check.workDataDetail", + "description": "拉取单条盘点明细的作业数据(workData 单行版,按明细范围类型分流,均返回单行对象):入参 detail_id(盘点明细ID,兼容 detailId 驼峰写法);warehouse_id 由服务端从当前上下文自动注入,前端无需传递;返回统一 success 包装,data 为单行作业数据。① 库位明细(scope_type=location):行结构与 workData location 视图单行一致——detail_id 明细ID / location_id 库位ID(明细未绑定库位时为 null)/ location_code 库位编码(优先明细快照,缺失回退库位表 space_code)/ location_name 库位名称(custom_name 兜底 space_code,无库位编码时为 null)/ status 盘点状态(checked=存在作业记录(含空库位标记记录),unchecked=无作业记录)/ has_unknown 是否含未知商品记录 / is_empty 是否空库位标记(空标记记录不计入 goods 子列表)/ checked_at 该库位最近上报时间(无记录为 null)/ checkers 盘点人去重数组 + goods 作业记录子列表(已知商品与未知商品记录均入内,字段与 workData location 视图一致:record_id 作业记录ID(可调 stock.check.recordDelete / stock.check.recheckClearLocation 移除)/ stock_id 商品库存ID(未知商品为 null)/ item_code 商品编码(未知商品用条码兜底)/ item_name 商品名称(未知商品用名称快照兜底条码)/ barcode 条码 / images 作业记录照片(FileReference business_type=stock_check_record 经 _attachRecordImages 挂载,与 workData/result/recordList 口径一致,无照片为空数组)/ store_id 货主ID(未知商品为 null)/ store_name 货主名(未知商品为 null)/ quantity 实盘数量 / checked_at 上报时间 / checker_name 盘点人;空库位标记记录不计入 goods)。② 商品明细(scope_type=goods):行结构与 workData goods 视图行一致——detail_id 明细ID / stock_id 商品库存ID / item_code 商品编码 / item_name 商品名称 / spec 规格 / store_id 货主ID / store_name 货主名 / barcode 条码 / images 商品图片(URL 数组,与 workData goods 视图一致)/ locations 商品所在全部库位列表(商品库存库位按拣货路径排序在前,无库存但已有作业记录的库位按首条记录 id 升序追加在末尾,空库位归 location_code=null 组排在最后;每项 { location_code, checked_at, checker_name, record_ids, images },未盘库位 checked_at/checker_name 为 null、record_ids/images 为空数组;明盘另含 system_quantity 该库位账面数量(=可用+锁定)、locked_quantity 该库位锁定数量与 quantity 该库位盘点数量(未盘库位 0),盲盘只返回库位信息);明盘(mode=open)另含 system_quantity 账面快照 / checked_quantity 已盘合计 / diff_quantity 差异(仅存在作业记录时计算,未盘恒 0) / is_diff,盲盘(mode=blind)不返回任何数量字段。仅任务状态 approved(审核完成)或 checking(盘点作业中)可拉取(与 workData 同口径)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(正常登录 token,携带仓库上下文)" + } + ], + "params": [ + { + "name": "detail_id", + "type": "number", + "required": true, + "source": "body", + "description": "盘点明细ID(wms_stock_check_detail.id,scope_type=location 的库位范围行;兼容 detailId 驼峰写法)" + } + ], + "response": [ + { + "name": "flag", + "type": "string", + "required": true, + "description": "请求结果标记:success=成功 / failure=失败" + }, + { + "name": "code", + "type": "number", + "required": true, + "description": "业务码:成功为 1;失败为具体业务错误码(如 400/500)" + }, + { + "name": "message", + "type": "string", + "required": true, + "description": "提示信息:成功为 ok;失败为具体错误文案" + }, + { + "name": "data", + "type": "object", + "required": true, + "description": "业务数据对象(统一 data 层封装:本方法业务数据整体位于 data 内;失败时 data=null),为单行作业数据,结构与 stock.check.workData location 视图单行一致", + "children": [ + { + "name": "detail_id", + "type": "number", + "required": true, + "description": "盘点明细ID(wms_stock_check_detail.id)" + }, + { + "name": "location_id", + "type": "number", + "required": true, + "description": "库位ID(wms_location_space.id;明细未绑定库位时为 null)" + }, + { + "name": "location_code", + "type": "string", + "required": true, + "description": "库位编码(优先明细快照,缺失回退库位表 space_code;无库位时为 null)" + }, + { + "name": "location_name", + "type": "string", + "required": true, + "description": "库位名称(custom_name 兜底 space_code;无库位编码时为 null)" + }, + { + "name": "status", + "type": "string", + "required": true, + "description": "盘点状态:checked=存在作业记录(含空库位标记记录),unchecked=无作业记录" + }, + { + "name": "has_unknown", + "type": "boolean", + "required": true, + "description": "是否含未知商品记录(该库位存在 stock_id 为空的作业记录时为 true,未知商品同样计入 goods)" + }, + { + "name": "is_empty", + "type": "boolean", + "required": true, + "description": "是否空库位标记(该库位存在空库位标记记录(is_empty=1)时为 true;空标记记录不计入 goods 子列表)" + }, + { + "name": "checked_at", + "type": "string", + "required": true, + "description": "该库位最近上报时间(无记录为 null)" + }, + { + "name": "checkers", + "type": "array", + "required": true, + "description": "盘点人去重数组(字符串数组,无记录为空数组)" + }, + { + "name": "goods", + "type": "array", + "required": true, + "description": "该库位盘点作业记录子列表(已知商品与未知商品记录均入内,字段与 workData location 视图一致;空库位标记记录不计入;无记录为空数组):每项 record_id 作业记录ID(单条记录直接定位,可调 stock.check.recordDelete / stock.check.recheckClearLocation 移除)/ stock_id 商品库存ID(未知商品为 null)/ item_code 商品编码(未知商品用条码兜底)/ item_name 商品名称(未知商品用名称快照兜底条码)/ barcode 条码 / images 作业记录照片([{ id, url }],FileReference business_type=stock_check_record 经 _attachRecordImages 挂载,与 workData/result/recordList 口径一致,无照片为空数组)/ store_id 货主ID(未知商品为 null)/ store_name 货主名(未知商品为 null)/ quantity 实盘数量 / checked_at 上报时间 / checker_name 盘点人" + } + ] + }, + { + "name": "timestamp", + "type": "number", + "required": true, + "description": "服务器时间戳(秒)" + } + ], + "errors": [ + { + "code": 400, + "message": "盘点明细ID不能为空" + }, + { + "code": 400, + "message": "盘点明细不存在" + }, + { + "code": 400, + "message": "仅库位任务明细支持拉取单行作业数据" + }, + { + "code": 400, + "message": "盘点任务不存在" + }, + { + "code": 400, + "message": "当前状态(xx)不允许拉取盘点作业数据,仅审核完成(approved)或盘点作业中(checking)的任务可拉取" + }, + { + "code": 500, + "message": "服务器内部错误" + } + ], + "notes": [ + "代码依据:app/service/systemMethods/stock/check.js#workDataDetail(ALL_METHOD_NAMES 由 22 增至 23 个(create,list,addDetail,addLocationDetail,detailDelete,detail,result,workData,workDataDetail,report,markEmpty,recordList,recordDelete,recheckClearLocation,finish,submit,cancel,audit,batchDelete,export,exportTaskProgress,patternList,patternCreate);_noNeedLog 查询类清单新增 workDataDetail(list,detail,result,workData,workDataDetail,recordList,export,exportTaskProgress,patternList);const { detail_id: detailIdSnake, detailId: detailIdCamel } = data || {},detailId=detail_id 未定义时回退 detailId(兼容 detailId 驼峰写法);warehouse_id 由服务端从 ctx.user.store_id 自动注入,前端无需传递,透传 { warehouseId, detailId })+ app/service/systems/stock_check.js#workDataDetail(detailId 非正整数抛 400『盘点明细ID不能为空』;按 id+warehouse_id 查 wms_stock_check_detail 不存在抛 400『盘点明细不存在』;_findCheck 查不到任务抛 400『盘点任务不存在』;任务状态非 REPORT_ALLOWED_STATUSES(approved/checking)抛 400『当前状态(xx)不允许拉取盘点作业数据,仅审核完成(approved)或盘点作业中(checking)的任务可拉取』;按明细 scope_type 分流:location 走 _buildLocationWorkRows 构建全量库位行并 find 匹配该明细ID、goods 走 _buildGoodsWorkRows 构建全量商品行并 find 匹配该明细ID,未命中抛 400『盘点明细不存在』,命中返回该单行)。本次代码已改并测试通过 216/216、ESLint 0 错误;后续 goods 分支扩展与 locations 商品库位列表口径见下方变更说明。", + "单行口径:响应 data 为单行作业数据,与 stock.check.workData 对应视图单行完全一致(复用同一构建函数 _buildLocationWorkRows/_buildGoodsWorkRows),便于作业端按明细ID刷新单行数据;库位明细(scope_type=location)返回 location 视图单行(detail_id/location_id/location_code/location_name/status/has_unknown/is_empty/checked_at/checkers/goods),商品明细(scope_type=goods)返回 goods 视图单行(detail_id/stock_id/item_code/item_name/spec/store_id/store_name/barcode/images/locations 商品所在全部库位列表,明盘另含数量字段)。", + "权限口径:随 ALL_METHOD_NAMES(23 个)免 API 权限(isNeedAuth=false)、免仓库有效期鉴权(_noNeedAuth)、必须登录(isNeedLogin=true,免登录清单为空);为查询类方法,加入免日志清单 _noNeedLog,不记录操作日志。", + "状态限制口径:仅任务状态 approved(审核完成)或 checking(盘点作业中)可拉取,与 stock.check.workData / report / finish 同口径(REPORT_ALLOWED_STATUSES)。", + "文档变更范围:methods/system.json 的 module=stock.check 分组新增 stock.check.workDataDetail 一条(位于 stock.check.workData 之后);根版本 0.3.244 → 0.3.245、updatedAt 保持 2026-10-04;methods/changes/system.json 新增本条(插入数组首位);其余 22 条 method 未改动(stock.check 分组由 22 条增至 23 条)。", + "库表维护源说明:维护源为库表(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,127.0.0.1:3307/wms)与生产库(WMS_DB_TARGET=production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致。", + "goods 明细单行 locations 商品库位列表口径(本次同步 workData 改造):workDataDetail 商品明细分支复用 _buildGoodsWorkRows,locations 为商品所在全部库位列表(库存库位按拣货路径排序在前、无库存但已有作业记录的库位按首条记录 id 升序追加、空库位归 null 组排在最后;明盘每库位含 system_quantity 该库位账面数量(=可用+锁定)、locked_quantity 该库位锁定数量与 quantity 该库位盘点数量(未盘 0),盲盘只返回库位信息);未盘明细 checked_quantity 恒 0、diff_quantity/is_diff 仅存在作业记录时计算(未盘恒 0)。回归测试 222/222 通过、ESLint 0 错误。", + "库位账面口径(本次同步 workData 改造):goods 明细单行 locations 各项库位账面 system_quantity = wms_storage 该库位 SUM(available_quantity+locked_quantity)(可用+锁定),locked_quantity = 该库位 SUM(locked_quantity);盲盘仍不返回任何数量字段。回归测试 222/222 通过、ESLint 0 错误。" ] }, { @@ -38916,7 +39165,7 @@ "迁移依据: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),本地与生产均已执行)。", "响应统一 data 层封装(2026-10-02 起):成功 { flag:\"success\", code:1, message:\"ok\", data:<业务数据整体>, timestamp };失败 { flag:\"failure\", code:<业务错误码>, message:<错误文案>, data:null, timestamp }。本方法业务数据整体位于 data 内,data 内字段口径与改造前一致(原顶层业务字段全部移入 data.children)。代码依据:app/service/systemMethods/stock/check.js#_call(22 个方法共用统一包装)+ app/lib/api_response.js#toSuccess(识别标准载荷后顶层补充 timestamp)。", "空库位标记上报口径(本次新增):is_empty 仅库位明细行(scope_type=location)支持,商品明细行传 is_empty 报 400『仅库位盘点明细支持空库位标记』;标记空时不要求商品/条码,quantity 恒为 0(跳过『实盘数量必须为不小于0的整数』校验),写一条特殊作业记录(stock_id=null、barcode=null、item_name=null、quantity=0、is_empty=1);覆盖式查重按(detail_id + is_empty=1 + location_code)应用层查重覆盖更新。互斥口径:标记空时删除该明细下所有商品记录(is_empty=false,含未知商品),上报商品时删除该明细下空标记记录(is_empty=true),两者不会并存。代码依据:app/service/systems/stock_check.js#report。", - "汇总口径(本次同步 _recalcCheckSummary):空库位标记记录计入已盘明细(checked_items 按 DISTINCT detail_id 自然计入、detail_status 按已盘占比正常推进);差异口径:空标记明细的库位账面(wms_storage 按 space_id SUM(quantity))有库存即计盘亏差异(diff_items 加 1),账面无库存不计差异。代码依据:app/service/systems/stock_check.js#_recalcCheckSummary。", + "汇总口径(本次同步 _recalcCheckSummary):空库位标记记录计入已盘明细(checked_items 按 DISTINCT detail_id 自然计入、detail_status 按已盘占比正常推进);差异口径:空标记明细的库位账面(wms_storage 按 space_id SUM(available_quantity+locked_quantity)=可用+锁定)有库存即计盘亏差异(diff_items 加 1),账面无库存不计差异。代码依据:app/service/systems/stock_check.js#_recalcCheckSummary。", "迁移依据:database/migrations/20261002160000-add-is-empty-to-stock-check-record.js(wms_stock_check_record 新增 is_empty TINYINT(1) NOT NULL DEFAULT 0,COMMENT 是否空库位标记(1=确认为空),开发与生产库均已执行)。", "文档变更范围:methods/system.json 的 module=stock.check 分组更新 5 条 method(stock.check.report:params 新增 is_empty 入参、errors 400 补「仅库位盘点明细支持空库位标记」、description/response/notes 补充空库位语义与互斥及汇总口径;stock.check.workData:description/response.rows 的 location 行新增 is_empty 字段说明;stock.check.result:description/response.rows 库位行新增 is_empty 与空标记盘亏口径;stock.check.recordList:response.rows 记录全字段说明新增 is_empty;stock.check.export:description/notes 补 Sheet2 空库位行输出口径);根版本 0.3.233 → 0.3.234、updatedAt 保持 2026-10-02;methods/changes/system.json 新增本条(插入数组首位);其余 15 条 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,127.0.0.1:3307/wms)与生产库(显式 WMS_DB_TARGET=production,112.124.21.102:3306/wms)——import 当前 system.json → export 到临时文件往返校验,保持库与文件一致;stock.check 分组共 20 条 method 无损。" @@ -39502,7 +39751,7 @@ }, { "method": "stock.check.finish", - "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)。", + "description": "完成盘点作业(允许部分未盘完成):仅 approved/checking 状态允许;未盘商品明细=无作业记录(wms_stock_check_record)的明细,按实盘 0 处理(差异=-账面快照,计入盘亏与差异行数);未盘库位明细行因无法枚举商品不计差异;已盘商品明细按作业记录数量合计与账面快照(system_quantity)对比聚合;已盘库位明细按商品聚合实盘 vs wms_storage 账面(space_id+stock_id SUM(available_quantity+locked_quantity)=可用+锁定,space_id 为空时账面按 0)对比聚合;盘盈=正差异合计、盘亏=负差异绝对值合计;完成后主表置 completed、回填 end_time(完成盘点的时间)、detail_status=all_checked,返回差异汇总(盘盈/盘亏合计)与未盘明细数(unchecked_items)。", "isNeedAuth": false, "isNeedLogin": true, "headers": [ @@ -39587,7 +39836,7 @@ "name": "profit_total", "type": "number", "required": true, - "description": "盘盈合计(商品行:作业记录数量合计大于账面快照的差异合计;库位行:按商品实盘大于 wms_storage 账面的差异合计)" + "description": "盘盈合计(商品行:作业记录数量合计大于账面快照的差异合计;库位行:按商品实盘大于 wms_storage 账面(SUM(available_quantity+locked_quantity)=可用+锁定)的差异合计)" }, { "name": "loss_total", @@ -39615,7 +39864,7 @@ } ], "notes": [ - "库位行账面口径:wms_storage 按 (space_id, stock_id) SUM(quantity),与 detail 接口的 stocks 账面一致。", + "库位行账面口径:wms_storage 按 (space_id, stock_id) SUM(available_quantity+locked_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 查看。", "响应统一 data 层封装(2026-10-02 起):成功 { flag:\"success\", code:1, message:\"ok\", data:<业务数据整体>, timestamp };失败 { flag:\"failure\", code:<业务错误码>, message:<错误文案>, data:null, timestamp }。本方法业务数据整体位于 data 内,data 内字段口径与改造前一致(原顶层业务字段全部移入 data.children)。代码依据:app/service/systemMethods/stock/check.js#_call(22 个方法共用统一包装)+ app/lib/api_response.js#toSuccess(识别标准载荷后顶层补充 timestamp)。" @@ -47029,6 +47278,13 @@ "required": false, "source": "body", "description": "备注" + }, + { + "name": "return_received_task_id", + "type": "number", + "required": false, + "source": "body", + "description": "收件任务ID(wms_return_received_task.id),不传默认 1=系统预设「历史收件」;服务端缓存校验(return_received_task:{id}),任务不存在/非法/不属于当前仓库报 400" } ], "response": [ @@ -47318,7 +47574,7 @@ "type": "object", "required": false, "source": "body", - "description": "查询条件,语义与 returnReceived.list 的 where 一致(支持 {operator,value} 标准结构或直接值;字段含 waybill_code 模糊、scan_date/created_at/updated_at 范围、scanner_id/scanner_name/store_id/order_express_id/order_id 等值、is_original_return 是否原单退回);禁止传入 warehouse_id/warehouseId(服务端注入)" + "description": "查询条件,语义与 returnReceived.list 的 where 一致(支持 {operator,value} 标准结构或直接值;字段含 waybill_code 模糊、scan_date/created_at/updated_at 范围、scanner_id/scanner_name/store_id/order_express_id/order_id/return_received_task_id 等值、is_original_return 是否原单退回);禁止传入 warehouse_id/warehouseId(服务端注入)" }, { "name": "sort", @@ -47497,6 +47753,315 @@ } ] }, + { + "groupName": "收件任务模块", + "module": "returnReceivedTask", + "list": [ + { + "method": "returnReceivedTask.create", + "description": "创建收件任务。主键 id 自增从 10000 开始(表级 AUTO_INCREMENT);批次号 batch_no 一律由服务端自动生成(格式 RT+YYYYMMDD+5位序号,如 RT2026100500001,基于 wms_number_sequence 序列表原子取号、全局递增、并发不撞号,参考波次号机制),**不接收外部输入**(前端传入 batch_no/batchNo 均被忽略);warehouse_id 由服务端从当前登录上下文(ctx.user.store_id)自动注入,creator_id/creator_name 从上下文(账号ID/员工名称)自动注入,禁止前端传入。系统预设任务 id=1(历史收件,warehouse_id=0)用于承接历史退回收件登记。权限口径:需要登录,免 API 权限校验(无需 wms_permission 记录)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(正常登录 token,携带仓库上下文)" + } + ], + "params": [ + { + "name": "title", + "type": "string", + "required": false, + "source": "body", + "description": "标题(任务名称,最长 100 字符,缺省为空串)" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "收件任务ID(自增从 10000 开始)" + }, + { + "name": "batch_no", + "type": "string", + "required": true, + "description": "批次号" + }, + { + "name": "title", + "type": "string", + "required": true, + "description": "标题" + }, + { + "name": "warehouse_id", + "type": "number", + "required": true, + "description": "仓库ID(服务端注入)" + }, + { + "name": "creator_id", + "type": "number", + "required": true, + "description": "创建人账户ID(服务端注入)" + }, + { + "name": "creator_name", + "type": "string", + "required": true, + "description": "创建人名称快照(服务端注入)" + }, + { + "name": "created_at / updated_at", + "type": "string", + "required": true, + "description": "创建时间/更新时间(YYYY-MM-DD HH:mm:ss 格式化字符串)" + } + ], + "errors": [ + { + "code": "400", + "message": "无法获取当前仓库上下文" + }, + { + "code": "400", + "message": "标题过长(最多100字符)" + }, + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "500", + "message": "创建收件任务失败" + } + ] + }, + { + "method": "returnReceivedTask.list", + "description": "分页查询收件任务列表。warehouse_id 由服务端从当前登录上下文(ctx.user.store_id)自动注入(返回本仓库任务 + 系统级任务 warehouse_id=0,如系统预设「历史收件」),禁止前端传入。搜索关键词 where.quickWhere:在 title(标题)/batch_no(编号)/creator_name(创建人)三个字段中 OR 模糊匹配;title/batch_no/creator_name 也可传 {operator,value} 标准结构(like 模糊/eq 精确/in 等);has_register 是否有登记(true=仅看有登记任务,false=仅看无登记任务,按当前仓库的 wms_return_received.return_received_task_id 引用判定,不跨仓);其他字段 id/creator_id/created_at/updated_at。每行返回 register_count(该任务在当前仓库下的退回收件登记数量,按 wms_return_received.return_received_task_id + warehouse_id=当前仓库 分组统计,系统级任务如「历史收件」也只统计当前仓库,无登记为 0)。排序 sort:sortField 白名单 id/batch_no/created_at/updated_at,sortOrder asc/desc,默认 id desc;分页 pagination:page/pageSize(pageSize 上限 500)。时间字段返回格式化字符串(YYYY-MM-DD HH:mm:ss)。权限口径:需要登录,免 API 权限校验(无需 wms_permission 记录)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(正常登录 token,携带仓库上下文)" + } + ], + "params": [ + { + "name": "where", + "type": "object", + "required": false, + "source": "body", + "description": "查询条件:quickWhere 关键词在 title/batch_no/creator_name 三个字段中 OR 模糊匹配;title/batch_no/creator_name 支持 {operator,value} 标准结构(like/eq/in 等);has_register 是否有登记(true/false,按当前仓库判定不跨仓);id/creator_id 等值或 in;created_at/updated_at 范围;禁止传入 warehouse_id/warehouseId(服务端注入)" + }, + { + "name": "pagination", + "type": "object", + "required": false, + "source": "body", + "description": "分页参数:page(页码,默认1)、pageSize(每页数量,默认20,上限500)" + }, + { + "name": "sort", + "type": "object", + "required": false, + "source": "body", + "description": "排序参数:sortField 白名单 id/batch_no/created_at/updated_at,sortOrder asc/desc,默认 id desc" + } + ], + "response": [ + { + "name": "list", + "type": "array", + "required": true, + "description": "任务行列表,每行含 id/batch_no/title/warehouse_id/creator_id/creator_name/created_at/updated_at(时间字段为格式化字符串)及 register_count(该任务下的退回收件登记数量,无登记为 0)" + }, + { + "name": "pagination", + "type": "object", + "required": true, + "description": "分页信息:page/pageSize/total/totalPages/hasPrevious/hasNext" + } + ], + "errors": [ + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "500", + "message": "查询列表失败" + } + ] + }, + { + "method": "returnReceivedTask.delete", + "description": "删除收件任务(硬删除,物理删除行)。兼容两种入参:① ids(数组或单值,单次上限 200)批量删除——逐条分流不整体报错,任务不存在、系统预设 id=1(历史收件)、非当前仓库任务、已有收件登记(wms_return_received.return_received_task_id 引用)的任务计入 skipped_ids,其余硬删除并清理任务校验缓存(return_received_task:{id}),返回 { total, deleted_count, skipped_count, deleted_ids, skipped_ids }(保持入参顺序);② id(单值)单值删除——不满足条件抛出 404/409,返回 { id, deleted: true }。warehouse_id 由服务端从当前登录上下文(ctx.user.store_id)自动注入,禁止前端传入。权限口径:需要登录,免 API 权限校验(无需 wms_permission 记录)。", + "isNeedAuth": false, + "isNeedLogin": true, + "headers": [ + { + "name": "Authorization", + "type": "string", + "required": true, + "description": "Bearer token(正常登录 token,携带仓库上下文)" + } + ], + "params": [ + { + "name": "ids", + "type": "array", + "required": false, + "source": "body", + "description": "收件任务ID数组(批量删除,兼容单值,去重后单次上限 200;优先于 id)" + }, + { + "name": "id", + "type": "number", + "required": false, + "source": "body", + "description": "收件任务ID(单值删除,正整数)" + } + ], + "response": [ + { + "name": "id", + "type": "number", + "required": true, + "description": "单值删除:被删除的收件任务ID(批量删除时不返回)" + }, + { + "name": "deleted", + "type": "boolean", + "required": true, + "description": "单值删除:是否已删除(恒为 true;批量删除时不返回)" + }, + { + "name": "total / deleted_count / skipped_count / deleted_ids / skipped_ids", + "type": "object", + "required": true, + "description": "批量删除(传 ids)时返回:total=入参去重总数,deleted_count=实际删除数,skipped_count=跳过数(不存在/系统预设/非本仓库/已有登记),deleted_ids/skipped_ids 保持入参顺序" + } + ], + "errors": [ + { + "code": "400", + "message": "收件任务ID不合法" + }, + { + "code": "404", + "message": "收件任务不存在" + }, + { + "code": "404", + "message": "系统预设任务不可删除" + }, + { + "code": "404", + "message": "收件任务不存在或无权操作" + }, + { + "code": "409", + "message": "该任务已有收件登记,无法删除" + }, + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "500", + "message": "删除收件任务失败" + } + ] + }, + { + "method": "returnReceivedTask.batchDelete", + "description": "批量删除收件任务(硬删除,物理删除行)。逐条分流不整体报错:任务不存在、系统预设 id=1(历史收件)、非当前仓库任务、已有收件登记(wms_return_received.return_received_task_id 引用)的任务均计入 skipped_ids,其余任务硬删除并清理任务校验缓存(return_received_task:{id})。warehouse_id 由服务端从当前登录上下文(ctx.user.store_id)自动注入,禁止前端传入。入参 ids 支持数组或单值(去重后上限 200);返回 { total, deleted_count, skipped_count, deleted_ids, skipped_ids }(保持入参顺序)。权限口径:需要登录,免 API 权限校验(无需 wms_permission 记录)。", + "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 不能为空" + }, + { + "code": "400", + "message": "单次最多删除 200 个收件任务" + }, + { + "code": "400", + "message": "无法获取当前仓库上下文" + }, + { + "code": "401", + "message": "未提供有效的认证令牌" + }, + { + "code": "500", + "message": "批量删除收件任务失败" + } + ] + } + ] + }, { "groupName": "退回拆包模块", "module": "returnUnpack", @@ -48751,12 +49316,12 @@ ] }, { - "groupName": "运单退回登记模块", + "groupName": "未退登记模块", "module": "returnWaybill", "list": [ { "method": "returnWaybill.create", - "description": "运单退回登记(增):录入「货主 + 运单号」退回关系。waybill_code/store_id 必填;校验 wms_store_warehouse 存在 store_id + warehouse_id 货主合约,无合约拒绝写入;同仓库+货主+运单号已存在时幂等返回已有记录(duplicated=true,不重复插入)。写入 is_notified=0/is_back=0(由定时任务与拆包联动维护,登记接口不维护)。仓库隔离:warehouse_id 由服务端注入 ctx.user.store_id,禁止前端传入。", + "description": "未退登记(增):录入「货主 + 运单号」退回关系。waybill_code/store_id 必填;校验 wms_store_warehouse 存在 store_id + warehouse_id 货主合约,无合约拒绝写入;同仓库+货主+运单号已存在时幂等返回已有记录(duplicated=true,不重复插入)。写入 is_notified=0/is_back=0(由定时任务与拆包联动维护,登记接口不维护)。仓库隔离:warehouse_id 由服务端注入 ctx.user.store_id,禁止前端传入。", "isNeedAuth": true, "isNeedLogin": true, "headers": [], @@ -48917,7 +49482,7 @@ }, { "method": "returnWaybill.list", - "description": "运单退回登记分页列表。仓库隔离:warehouse_id 由服务端注入 ctx.user.store_id,禁止前端传入。支持按运单号模糊、货主、是否已通知、是否退回、登记时间范围筛选。is_notified/is_back 由定时任务与拆包联动维护,登记接口不维护。", + "description": "未退登记分页列表。仓库隔离:warehouse_id 由服务端注入 ctx.user.store_id,禁止前端传入。支持按运单号模糊、货主、是否已通知、是否退回、登记时间范围筛选。is_notified/is_back 由定时任务与拆包联动维护,登记接口不维护。", "isNeedAuth": true, "isNeedLogin": true, "headers": [], @@ -48984,7 +49549,7 @@ "name": "list", "type": "array", "required": true, - "description": "运单退回登记列表,每条含登记字段(id、warehouse_id、store_id、waybill_code、group_id、group_name、user_id、user_name、remark、is_notified、is_back)及格式化时间字段;group_id/group_name/user_id/user_name 为登记来源(站内信「查退回」触发时写入,后台登记为 null)" + "description": "未退登记列表,每条含登记字段(id、warehouse_id、store_id、waybill_code、group_id、group_name、user_id、user_name、remark、is_notified、is_back)及格式化时间字段;group_id/group_name/user_id/user_name 为登记来源(站内信「查退回」触发时写入,后台登记为 null)" }, { "name": "pagination", @@ -49010,7 +49575,7 @@ }, { "method": "returnWaybill.detail", - "description": "运单退回登记详情。免权限(复用列表权限),仅需登录 + 仓库隔离校验(仅本仓库记录)。", + "description": "未退登记详情。免权限(复用列表权限),仅需登录 + 仓库隔离校验(仅本仓库记录)。", "isNeedAuth": false, "isNeedLogin": true, "headers": [], @@ -49056,7 +49621,7 @@ }, { "method": "returnWaybill.delete", - "description": "删除运单退回登记(物理删除,表 paranoid:false)。仓库隔离校验(仅本仓库记录)。", + "description": "删除未退登记(物理删除,表 paranoid:false)。仓库隔离校验(仅本仓库记录)。", "isNeedAuth": true, "isNeedLogin": true, "headers": [],