From 8c27cd08edb420b7ac7f7a1c45a045abf1727782 Mon Sep 17 00:00:00 2001 From: liufumingren Date: Wed, 30 Sep 2026 03:08:23 +0800 Subject: [PATCH] =?UTF-8?q?feat(stock):=20=E7=9B=98=E7=82=B9=E4=BD=9C?= =?UTF-8?q?=E4=B8=9A=E8=AE=B0=E5=BD=95=E6=8B=86=E5=88=86=EF=BC=8C=E6=98=8E?= =?UTF-8?q?=E7=BB=86=E4=BB=85=E5=AD=98=E5=95=86=E5=93=81=E5=BF=AB=E7=85=A7?= =?UTF-8?q?=E3=80=81=E5=BA=93=E4=BD=8D/=E6=95=B0=E9=87=8F=E5=85=A5=20wms?= =?UTF-8?q?=5Fstock=5Fcheck=5Frecord?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- app/model/stock_check_detail.js | 67 +- app/model/stock_check_record.js | 111 ++ app/service/systemMethods/stock/check.js | 624 +++++++ app/service/systems/stock_check.js | 1539 +++++++++++++++++ ...110000-align-stock-check-status-machine.js | 43 + ...-split-stock-check-detail-create-record.js | 184 ++ ...ique-stock-check-record-detail-location.js | 58 + 7 files changed, 2571 insertions(+), 55 deletions(-) create mode 100644 app/model/stock_check_record.js create mode 100644 app/service/systemMethods/stock/check.js create mode 100644 app/service/systems/stock_check.js create mode 100644 database/migrations/20260929110000-align-stock-check-status-machine.js create mode 100644 database/migrations/20260929120000-split-stock-check-detail-create-record.js create mode 100644 database/migrations/20260929130000-unique-stock-check-record-detail-location.js diff --git a/app/model/stock_check_detail.js b/app/model/stock_check_detail.js index 3df1e01..5c90d03 100644 --- a/app/model/stock_check_detail.js +++ b/app/model/stock_check_detail.js @@ -1,12 +1,13 @@ 'use strict'; /** - * 库存盘点明细表模型。 + * 库存盘点明细表模型(仅存盘点商品:stock_id + 商品快照)。 + * 库位/数量等盘点作业信息存放在 wms_stock_check_record。 * @param {import('egg').Application} app Egg 应用实例。 * @return {import('sequelize').ModelCtor} Sequelize 模型。 */ module.exports = app => { - const { BIGINT, STRING, INTEGER, DATE, TINYINT } = app.Sequelize; + const { BIGINT, STRING, INTEGER } = app.Sequelize; const StockCheckDetail = app.model.define('wms_stock_check_detail', { id: { @@ -30,16 +31,6 @@ module.exports = app => { allowNull: false, comment: '库存商品ID,关联 wms_stock_warehouse.id', }, - location_id: { - type: BIGINT(20).UNSIGNED, - allowNull: true, - comment: '库位ID,关联 wms_location_space.id;无库位商品为空', - }, - location_code: { - type: STRING(50), - allowNull: true, - comment: '库位编码快照(space_code)', - }, item_code: { type: STRING(50), allowNull: false, @@ -64,53 +55,16 @@ module.exports = app => { type: INTEGER(12), allowNull: false, defaultValue: 0, - comment: '账面数量(生成盘点任务时的系统库存快照)', - }, - check_quantity: { - type: INTEGER(12), - allowNull: true, - comment: '实盘数量;未盘点时为空', - }, - diff_quantity: { - type: INTEGER(12), - allowNull: true, - comment: '差异数量 = 实盘数量 - 账面数量;正数盘盈,负数盘亏;未盘点时为空', - }, - is_diff: { - type: TINYINT(1), - allowNull: false, - defaultValue: 0, - comment: '是否有差异:1=有差异,0=无差异', - }, - status: { - type: STRING(20), - allowNull: false, - defaultValue: 'unchecked', - comment: '明细状态:unchecked=未盘,checked=已盘,confirmed=已确认', - }, - checker_id: { - type: BIGINT(20).UNSIGNED, - allowNull: true, - comment: '盘点人账户ID', - }, - checker_name: { - type: STRING(50), - allowNull: true, - comment: '盘点人名称快照', - }, - checked_at: { - type: DATE, - allowNull: true, - comment: '盘点时间', + comment: '账面数量快照(生成盘点明细时的系统库存,用于差异对比)', }, remark: { type: STRING(500), allowNull: true, - comment: '备注(如差异原因说明)', + comment: '备注', }, }, { tableName: 'wms_stock_check_detail', - comment: '库存盘点明细表', + comment: '库存盘点明细表(盘点商品清单)', timestamps: true, createdAt: 'created_at', updatedAt: 'updated_at', @@ -119,13 +73,11 @@ 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: 'idx_location_id', fields: [ 'location_id' ] }, - { name: 'idx_is_diff', fields: [ 'is_diff' ] }, ], }); StockCheckDetail.associate = function() { - const { StockCheck, StockWarehouse } = app.model; + const { StockCheck, StockWarehouse, StockCheckRecord } = app.model; // 关联盘点主表 StockCheckDetail.belongsTo(StockCheck, { foreignKey: 'check_id', @@ -136,6 +88,11 @@ module.exports = app => { foreignKey: 'stock_id', as: 'stockWarehouse', }); + // 一条明细对应多条盘点作业记录 + StockCheckDetail.hasMany(StockCheckRecord, { + foreignKey: 'detail_id', + as: 'records', + }); }; return StockCheckDetail; diff --git a/app/model/stock_check_record.js b/app/model/stock_check_record.js new file mode 100644 index 0000000..8bc0451 --- /dev/null +++ b/app/model/stock_check_record.js @@ -0,0 +1,111 @@ +'use strict'; + +/** + * 库存盘点作业记录表模型(存储盘点的库位、数量信息)。 + * 一个盘点明细(商品)可在多个库位多次上报,每次上报一条记录。 + * @param {import('egg').Application} app Egg 应用实例。 + * @return {import('sequelize').ModelCtor} Sequelize 模型。 + */ +module.exports = app => { + const { BIGINT, STRING, INTEGER, DATE } = app.Sequelize; + + const StockCheckRecord = app.model.define('wms_stock_check_record', { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + comment: '主键', + }, + check_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '关联盘点主表 wms_stock_check.id(冗余,便于按任务查记录)', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID(冗余,隔离查询)', + }, + detail_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '关联盘点明细 wms_stock_check_detail.id', + }, + stock_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '库存商品ID(冗余,商品维度查询),关联 wms_stock_warehouse.id', + }, + location_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '库位ID,关联 wms_location_space.id;库位编码匹配时回填,未匹配为空', + }, + location_code: { + type: STRING(50), + allowNull: false, + defaultValue: '', + comment: '库位编码(盘点上报的库位,空串表示无库位分组)', + }, + quantity: { + type: INTEGER(12), + allowNull: false, + defaultValue: 0, + comment: '实盘数量(不小于0的整数)', + }, + checker_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '盘点人账户ID', + }, + checker_name: { + type: STRING(50), + allowNull: true, + comment: '盘点人名称快照', + }, + checked_at: { + type: DATE, + allowNull: true, + comment: '上报时间', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + }, { + tableName: 'wms_stock_check_record', + comment: '库存盘点作业记录表(库位+数量)', + timestamps: true, + createdAt: 'created_at', + updatedAt: 'updated_at', + paranoid: false, + indexes: [ + { name: 'idx_check_id', fields: [ 'check_id' ] }, + { name: 'idx_detail_id', fields: [ 'detail_id' ] }, + { name: 'idx_stock_id', fields: [ 'stock_id' ] }, + { name: 'idx_warehouse_location', fields: [ 'warehouse_id', 'location_code' ] }, + ], + }); + + StockCheckRecord.associate = function() { + const { StockCheck, StockCheckDetail, StockWarehouse } = app.model; + // 关联盘点主表 + StockCheckRecord.belongsTo(StockCheck, { + foreignKey: 'check_id', + as: 'check', + }); + // 关联盘点明细 + StockCheckRecord.belongsTo(StockCheckDetail, { + foreignKey: 'detail_id', + as: 'detail', + }); + // 关联库存商品 + StockCheckRecord.belongsTo(StockWarehouse, { + foreignKey: 'stock_id', + as: 'stockWarehouse', + }); + }; + + return StockCheckRecord; +}; diff --git a/app/service/systemMethods/stock/check.js b/app/service/systemMethods/stock/check.js new file mode 100644 index 0000000..6bb1b90 --- /dev/null +++ b/app/service/systemMethods/stock/check.js @@ -0,0 +1,624 @@ +'use strict'; + +const MainService = require('../../main'); + +const STOCK_CHECK_EXPORT_TASK_CACHE_KEY_PREFIX = 'stock_check_export_task_'; +const STOCK_CHECK_EXPORT_TASK_CACHE_TTL_SECONDS = 1800; + +/** 单次导出任务允许的最大盘点任务数量 */ +const STOCK_CHECK_EXPORT_MAX_TASK_IDS = 50; + +/** 全部 14 个 method 名(免权限/免鉴权清单共用) */ +const ALL_METHOD_NAMES = 'create,list,addDetail,detailDelete,detail,report,recordList,recordDelete,finish,submit,cancel,audit,export,exportTaskProgress'; + +/** + * 系统方法层:stock.check(库存盘点模块接口包装层)。 + * 主要职责:统一包装系统方法接口,处理权限、日志、where 解析等公共逻辑, + * 将具体业务逻辑下沉到 systems.stockCheck 中。 + */ +class StockCheckMethodService extends MainService { + constructor(ctx) { + super(ctx); + // 免登录方法列表:空(全部需要登录) + const _noNeedLogin = ''; + // 免权限方法列表:全部 14 个方法免 API 权限校验(与 stock/transaction.js 口径一致) + const _noNeedRight = ALL_METHOD_NAMES; + // 免日志方法列表:查询类与导出类不记录操作日志(recordDelete 为写操作,保留操作日志) + const _noNeedLog = 'list,detail,recordList,export,exportTaskProgress'; + // 免鉴权(仓库有效期检查)方法列表:全部方法免鉴权(与 stock/transaction.js 口径一致) + const _noNeedAuth = ALL_METHOD_NAMES; + this.systemInit(_noNeedLogin, _noNeedRight, _noNeedLog, _noNeedAuth); + } + + /** + * 统一调用库存盘点业务服务,并捕获业务错误码。 + * + * @param {Function} fn 业务调用函数。 + * @param {string} fallbackMessage 兜底错误文案。 + * @return {Promise} 统一 success/fail 包装。 + */ + async _call(fn, fallbackMessage) { + try { + const result = await fn(); + return this.success('ok', result); + } catch (error) { + const code = Number(error && error.code); + if (Number.isInteger(code) && code >= 400 && code < 600) { + return this.fail(error.message || fallbackMessage, {}, code); + } + this.ctx.logger.error(`[stock.check] ${fallbackMessage}: ${error && error.message ? error.message : error}`); + return this.fail('服务器内部错误', {}, 500); + } + } + + /** + * 创建盘点任务(空任务)。 + * warehouse_id 由服务端从当前上下文自动注入,前端无需传递。 + * + * @param {Object} data 请求体。 + * @param {string} [data.title] 盘点名称/主题。 + * @param {string} [data.type] 盘点范围类型:all/store/goods/location。 + * @param {string} [data.mode] 盘点方式:open=明盘/blind=盲盘。 + * @param {number} [data.store_id] 货主ID(按货主盘点时必填)。 + * @param {string} [data.check_date] 盘点日期。 + * @param {string} [data.remark] 备注。 + * @return {Promise} 统一 success 包装,返回新建的盘点任务信息。 + */ + async create(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const creatorId = ctx.user ? (ctx.user.id || ctx.user.user_id || 0) : 0; + const creatorName = ctx.user ? (ctx.user.employees_name || ctx.user.real_name || '') : ''; + const { title, type, mode, store_id: storeId, check_date: checkDate, remark } = data || {}; + + return this._call( + () => this.service.systems.stockCheck.create({ + warehouseId, + title, + type, + mode, + storeId, + checkDate, + remark, + creatorId, + creatorName, + }), + '创建盘点任务失败' + ); + } + + /** + * 拉取盘点任务列表。 + * 按当前用户仓库(ctx.user.store_id)限定数据范围。 + * + * @param {Object} data 请求体。 + * @param {Object} [data.pagination] 分页参数。 + * @param {Object} [data.where] 查询条件。 + * @param {string|Array} [data.where.status] 状态筛选(单值或数组)。 + * @param {number} [data.where.store_id] 货主筛选。 + * @param {string} [data.where.keyword] 关键字(单号/标题模糊)。 + * @return {Promise} 统一 success 包装,返回 rows/total。 + */ + async list(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const { pagination } = data || {}; + + return this._call(async () => { + const { whereValue = {} } = this.prepareWhereContext(data); + const status = whereValue.status !== undefined ? whereValue.status : data.status; + const storeId = whereValue.store_id !== undefined ? whereValue.store_id : data.store_id; + const keyword = whereValue.keyword !== undefined ? whereValue.keyword : data.keyword; + return this.service.systems.stockCheck.list({ + warehouseId, + status, + storeId, + keyword, + pagination, + }); + }, '查询盘点任务列表失败'); + } + + /** + * 添加盘点明细。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 盘点任务ID。 + * @param {Array} data.stock_ids 商品库存ID列表(wms_stock_warehouse.id)。 + * @return {Promise} 统一 success 包装,返回新增数与跳过数。 + */ + async addDetail(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const { id, stock_ids: stockIds } = data || {}; + + return this._call( + () => this.service.systems.stockCheck.addDetail({ warehouseId, id, stockIds }), + '添加盘点明细失败' + ); + } + + /** + * 删除盘点明细(从任务中移除某个商品)。 + * 仅主表状态 created/rejected 允许删除;明细存在作业记录时一并防御性删除; + * 删除后重算主表 total_items。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 盘点任务ID。 + * @param {number} data.detail_id 盘点明细ID(兼容 detailId 驼峰写法)。 + * @param {number} [data.detailId] 盘点明细ID(驼峰别名)。 + * @return {Promise} 统一 success 包装,返回 { detail_id, deleted, total_items }。 + */ + async detailDelete(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const { id, detail_id: detailIdRaw, detailId: detailIdAlias } = data || {}; + const detailId = detailIdRaw !== undefined && detailIdRaw !== null && detailIdRaw !== '' + ? detailIdRaw + : detailIdAlias; + + return this._call( + () => this.service.systems.stockCheck.detailDelete({ + warehouseId, + id, + detailId, + }), + '删除盘点明细失败' + ); + } + + /** + * 拉取盘点任务的全部明细行(商品清单)及每条明细的盘点作业记录(库位+数量)。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 盘点任务ID。 + * @return {Promise} 统一 success 包装,返回 { check, rows, total };rows 每条含商品快照 + + * 已盘聚合(checked_quantity/diff_quantity/is_diff/location_codes/checkers/last_checked_at)、 + * records(作业记录列表)与 locations(按库位聚合 [{ location_id, location_code, quantity }])。 + */ + async detail(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const { id } = data || {}; + + return this._call( + () => this.service.systems.stockCheck.detail({ warehouseId, id }), + '查询盘点明细失败' + ); + } + + /** + * 盘点作业上报(覆盖式)。 + * 同明细 + 同库位编码重复上报时更新已有记录(未传库位归入"无库位"分组,location_code 为 null),不再新增。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 盘点任务ID。 + * @param {number} data.detail_id 明细ID。 + * @param {string} [data.location] 库位编码(可空)。 + * @param {number} data.quantity 实盘数量(>=0)。 + * @return {Promise} 统一 success 包装,返回 { record, detail_id, mode: 'created'|'updated', ...summary }。 + */ + async report(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const checkerId = ctx.user ? (ctx.user.id || ctx.user.user_id || 0) : 0; + const checkerName = ctx.user ? (ctx.user.employees_name || ctx.user.real_name || '') : ''; + const { id, detail_id: detailId, location, quantity } = data || {}; + + return this._call( + () => this.service.systems.stockCheck.report({ + warehouseId, + id, + detailId, + location, + quantity, + checkerId, + checkerName, + }), + '盘点作业上报失败' + ); + } + + /** + * 拉取盘点作业记录列表。 + * 至少传 id(盘点任务ID)或 detail_id(明细ID)之一;按记录 id 倒序,返回分页结果。 + * + * @param {Object} data 请求体。 + * @param {number} [data.id] 盘点任务ID(可选)。 + * @param {number} [data.detail_id] 明细ID(可选,传了只查该明细)。 + * @param {Object} [data.pagination] 分页参数。 + * @return {Promise} 统一 success 包装,返回 { rows, total, page, pageSize }; + * rows 每条为记录表全字段 + 商品快照列(item_code/item_name)。 + */ + async recordList(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const { id, detail_id: detailId, pagination } = data || {}; + + return this._call( + () => this.service.systems.stockCheck.recordList({ + warehouseId, + id, + detailId, + pagination, + }), + '查询盘点作业记录失败' + ); + } + + /** + * 删除盘点作业记录。 + * 仅主表状态 approved/checking 允许删除;删除后重算盘点进度汇总,主表状态不回退。 + * + * @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 }。 + */ + 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; + + return this._call( + () => this.service.systems.stockCheck.recordDelete({ + warehouseId, + id, + recordId, + }), + '删除盘点作业记录失败' + ); + } + + /** + * 完成盘点作业(允许部分未盘完成,未盘明细按实盘 0 处理计为盘亏)。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 盘点任务ID。 + * @return {Promise} 统一 success 包装,返回差异汇总(含 unchecked_items 未盘明细数)。 + */ + async finish(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const { id } = data || {}; + + return this._call( + () => this.service.systems.stockCheck.finish({ warehouseId, id }), + '完成盘点作业失败' + ); + } + + /** + * 完成盘点任务(提交审核)。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 盘点任务ID。 + * @return {Promise} 统一 success 包装,返回最新状态。 + */ + async submit(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const { id } = data || {}; + + return this._call( + () => this.service.systems.stockCheck.submit({ warehouseId, id }), + '提交盘点任务失败' + ); + } + + /** + * 取消盘点任务。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 盘点任务ID。 + * @return {Promise} 统一 success 包装,返回最新状态。 + */ + async cancel(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const { id } = data || {}; + + return this._call( + () => this.service.systems.stockCheck.cancel({ warehouseId, id }), + '取消盘点任务失败' + ); + } + + /** + * 审核盘点任务。 + * + * @param {Object} data 请求体。 + * @param {number} data.id 盘点任务ID。 + * @param {string} data.action 审核动作:approve=通过,reject=驳回。 + * @param {string} [data.reason] 驳回原因(写入备注)。 + * @return {Promise} 统一 success 包装,返回最新状态。 + */ + async audit(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const { id, action, reason } = data || {}; + + return this._call( + () => this.service.systems.stockCheck.audit({ warehouseId, id, action, reason }), + '审核盘点任务失败' + ); + } + + /** + * 提交盘点任务导出任务。 + * 异步执行:查询任务与明细 → ExcelJS 流式写入(Sheet1=盘点单行,Sheet2=明细行)→ COS 上传。 + * 进度通过 Redis 缓存追踪,立即返回任务ID。 + * + * @param {Object} data 请求体。 + * @param {Array} [data.ids] 盘点任务ID数组(兼容 task_ids 写法,上限 50)。 + * @param {Array} [data.task_ids] 盘点任务ID数组(兼容别名)。 + * @return {Promise} 统一 success 包装,返回任务ID。 + */ + async export(data = {}) { + const { ctx } = this; + const warehouseId = Number(ctx.user && ctx.user.store_id) || 0; + const { ids, task_ids: taskIdsRaw } = data || {}; + + const idSource = ids !== undefined ? ids : taskIdsRaw; + const idList = Array.isArray(idSource) ? idSource : (idSource !== undefined ? [ idSource ] : []); + const numericIds = [ ...new Set(idList.map(value => Number(value)).filter(value => Number.isInteger(value) && value > 0)) ]; + if (numericIds.length === 0) { + return this.fail('请至少选择一个盘点任务', {}, 400); + } + if (numericIds.length > STOCK_CHECK_EXPORT_MAX_TASK_IDS) { + return this.fail(`单次最多导出 ${STOCK_CHECK_EXPORT_MAX_TASK_IDS} 个盘点任务`, {}, 400); + } + + const taskId = this.generateExportTaskId(); + const taskPayload = { + task_id: taskId, + status: 'submitted', + progress: 0, + current_count: 0, + total_count: 0, + message: '导出任务已提交', + result: null, + error: '', + }; + + await this.setExportTaskProgress(taskId, taskPayload); + + setImmediate(async () => { + try { + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'running', + progress: 5, + current_count: 0, + total_count: 0, + message: '导出任务执行中', + result: null, + error: '', + }); + + const result = await this.service.systems.stockCheck.exportStockChecks({ + warehouseId, + ids: numericIds, + onProgress: async progress => { + const safeProgress = this.isPlainObject(progress) ? progress : {}; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: safeProgress.status || 'running', + progress: safeProgress.progress, + current_count: safeProgress.currentCount || 0, + total_count: safeProgress.totalCount || 0, + message: safeProgress.message || '导出任务执行中', + result: safeProgress.result || null, + error: '', + }); + }, + }); + + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'success', + progress: 100, + current_count: result.current_count || 0, + total_count: result.total_count || 0, + message: '导出任务完成', + result, + error: '', + }); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + await this.setExportTaskProgress(taskId, { + task_id: taskId, + status: 'failed', + progress: 100, + current_count: 0, + total_count: 0, + message: '导出任务失败', + result: null, + error: errorMessage, + }); + } + }); + + return this.success('ok', { + ...taskPayload, + update_time: Date.now(), + }); + } + + /** + * 查询盘点任务导出进度。 + * + * @param {Object} data 请求体。 + * @param {string} [data.task_id] 任务ID(下划线写法)。 + * @param {string} [data.taskId] 任务ID(驼峰写法)。 + * @return {Promise} 统一 success 包装,包含进度与下载链接。 + */ + async exportTaskProgress(data = {}) { + const taskId = this.normalizeExportTaskId(data); + if (!taskId) { + return this.success('ok', { + task_id: '', + status: 'not_found', + progress: 0, + current_count: 0, + total_count: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const cachedTask = await this.getExportTaskProgress(taskId); + if (!cachedTask) { + return this.success('ok', { + task_id: taskId, + status: 'not_found', + progress: 0, + current_count: 0, + total_count: 0, + message: '任务不存在', + result: null, + error: '', + download_url: '', + update_time: Date.now(), + }); + } + + const safeResult = this.isPlainObject(cachedTask.result) ? cachedTask.result : {}; + const downloadUrl = String( + safeResult.url + || safeResult.cdnUrl + || safeResult.cosUrl + || safeResult.fileKey + || '' + ); + + return this.success('ok', { + task_id: taskId, + ...cachedTask, + download_url: downloadUrl, + }); + } + + // =========================== + // 导出任务辅助方法 + // =========================== + + /** + * 生成导出任务ID。 + * + * @return {string} 导出任务ID。 + */ + generateExportTaskId() { + const warehouseId = this.ctx && this.ctx.user && this.ctx.user.store_id + ? this.ctx.user.store_id + : 'unknown'; + const timestamp = Date.now(); + const randomToken = Math.random().toString(36).slice(2, 10); + return `stock_check_export_${warehouseId}_${timestamp}_${randomToken}`; + } + + /** + * 归一化导出任务ID(兼容 task_id / taskId)。 + * + * @param {Object} data 请求体。 + * @param {string} [data.task_id] 任务ID(下划线写法)。 + * @param {string} [data.taskId] 任务ID(驼峰写法)。 + * @return {string} 归一化后的任务ID。 + */ + normalizeExportTaskId(data = {}) { + const normalizedData = this.isPlainObject(data) ? data : {}; + return String(normalizedData.task_id || normalizedData.taskId || '').trim(); + } + + /** + * 获取导出任务缓存键。 + * + * @param {string} taskId 任务ID。 + * @return {string} 缓存键。 + */ + getExportTaskCacheKey(taskId = '') { + const normalizedTaskId = String(taskId || '').trim(); + if (!normalizedTaskId) { + return ''; + } + return `${STOCK_CHECK_EXPORT_TASK_CACHE_KEY_PREFIX}${normalizedTaskId}`; + } + + /** + * 写入导出任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @param {Object} payload 任务状态载荷。 + * @return {Promise} 无返回值。 + */ + async setExportTaskProgress(taskId = '', payload = {}) { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.setCacheAsync !== 'function') { + return; + } + + const safePayload = this.isPlainObject(payload) ? payload : {}; + const normalizeCount = value => { + const numericValue = Number(value); + return Number.isFinite(numericValue) && numericValue >= 0 ? Math.round(numericValue) : 0; + }; + const progressPayload = { + task_id: String(taskId || '').trim(), + status: String(safePayload.status || 'submitted').trim() || 'submitted', + progress: Number.isFinite(Number(safePayload.progress)) + ? Math.min(100, Math.max(0, Math.round(Number(safePayload.progress)))) + : 0, + current_count: normalizeCount(safePayload.current_count), + total_count: normalizeCount(safePayload.total_count), + message: String(safePayload.message || ''), + result: safePayload.result ?? null, + error: String(safePayload.error || ''), + update_time: Date.now(), + }; + + try { + await this.app.setCacheAsync( + cacheKey, + progressPayload, + STOCK_CHECK_EXPORT_TASK_CACHE_TTL_SECONDS + ); + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.warn(`[stock.check.export] 写入导出任务缓存失败: ${errorMessage}`); + } + } + + /** + * 读取导出任务进度缓存。 + * + * @param {string} taskId 任务ID。 + * @return {Promise} 任务缓存,不存在则返回 null。 + */ + async getExportTaskProgress(taskId = '') { + const cacheKey = this.getExportTaskCacheKey(taskId); + if (!cacheKey || typeof this.app.getCacheAsync !== 'function') { + return null; + } + + try { + const cached = await this.app.getCacheAsync(cacheKey); + if (!this.isPlainObject(cached)) { + return null; + } + return cached; + } catch (error) { + const errorMessage = error && error.message ? error.message : `${error}`; + this.ctx.logger.warn(`[stock.check.export] 读取导出任务缓存失败: ${errorMessage}`); + return null; + } + } +} + +module.exports = StockCheckMethodService; diff --git a/app/service/systems/stock_check.js b/app/service/systems/stock_check.js new file mode 100644 index 0000000..9b00b47 --- /dev/null +++ b/app/service/systems/stock_check.js @@ -0,0 +1,1539 @@ +'use strict'; + +const crypto = require('node:crypto'); +const fs = require('node:fs'); +const fsp = require('node:fs/promises'); +const os = require('node:os'); +const path = require('node:path'); +const ExcelJS = require('exceljs'); +const Service = require('egg').Service; + +/** 盘点范围类型枚举(wms_stock_check.type) */ +const STOCK_CHECK_TYPES = Object.freeze([ 'all', 'store', 'goods', 'location' ]); +/** 盘点方式枚举(wms_stock_check.mode) */ +const STOCK_CHECK_MODES = Object.freeze([ 'open', 'blind' ]); +/** 允许添加明细的主表状态 */ +const ADD_DETAIL_ALLOWED_STATUSES = Object.freeze([ 'created', 'rejected' ]); +/** 允许盘点作业上报/完成的主表状态 */ +const REPORT_ALLOWED_STATUSES = Object.freeze([ 'approved', 'checking' ]); +/** 允许提交审核的主表状态 */ +const SUBMIT_ALLOWED_STATUSES = Object.freeze([ 'created', 'rejected' ]); +/** 允许取消的主表状态 */ +const CANCEL_ALLOWED_STATUSES = Object.freeze([ 'created', 'submitted', 'rejected' ]); + +/** 盘点范围类型中文标签 */ +const STOCK_CHECK_TYPE_LABELS = Object.freeze({ + all: '全盘', + store: '按货主', + goods: '按商品', + location: '按库位', +}); +/** 盘点方式中文标签 */ +const STOCK_CHECK_MODE_LABELS = Object.freeze({ + open: '明盘', + blind: '盲盘', +}); +/** 主表状态中文标签 */ +const STOCK_CHECK_STATUS_LABELS = Object.freeze({ + created: '已创建', + submitted: '待审核', + rejected: '已驳回', + approved: '审核完成', + checking: '盘点作业中', + completed: '已完成', + cancelled: '已取消', +}); +/** 明细盘点进度中文标签(主表 detail_status) */ +const STOCK_CHECK_DETAIL_PROGRESS_LABELS = Object.freeze({ + none_checked: '未盘', + partial_checked: '部分已盘', + all_checked: '全部已盘', +}); + +/** + * 库存盘点模块业务逻辑层。 + * 负责 wms_stock_check(主表)/ wms_stock_check_detail(明细)的状态机流转与增删查, + * 以及导出 Excel 生成与 COS 上传等核心操作。 + * 所有数据库交互集中在此层,供 systemMethods/stock/check.js 调用。 + */ +class StockCheckService extends Service { + /** + * 创建带业务错误码的异常对象。 + * + * @param {string} message 错误信息。 + * @param {number} [code=400] 业务错误码。 + * @return {Error} 包含 code 的异常对象。 + */ + createBusinessError(message, code = 400) { + const error = new Error(`${message}`); + error.code = code; + return error; + } + + /** + * 获取当前日期片段(YYYYMMDD)。 + * + * @return {string} 当前日期片段。 + */ + _getCurrentDatePart() { + const now = new Date(); + const year = now.getFullYear(); + const month = String(now.getMonth() + 1).padStart(2, '0'); + const day = String(now.getDate()).padStart(2, '0'); + return `${year}${month}${day}`; + } + + /** + * 生成盘点单号。 + * 格式:PD + YYYYMMDD + 6位序号(如 PD20260929000001)。 + * 序号全局递增(不按仓库隔离):uk_check_no 为全局唯一索引,按仓各自从 1 起会跨仓撞号; + * 并发创建时的撞号由 create 方法的唯一键重试兜底(参照收货单 receiving_number 口径)。 + * + * @return {Promise} 盘点单号。 + */ + async generateCheckNo() { + const { ctx } = this; + const datePart = this._getCurrentDatePart(); + const prefix = 'PD'; + const pattern = `${prefix}${datePart}%`; + + const rows = await ctx.model.query( + ` + SELECT check_no + FROM wms_stock_check + WHERE check_no LIKE :pattern + ORDER BY check_no DESC + LIMIT 1 + `, + { + replacements: { pattern }, + type: ctx.model.QueryTypes.SELECT, + } + ); + + const latestNo = String(rows && rows[0] && rows[0].check_no || '').trim(); + let sequence = 1; + if (latestNo) { + const match = latestNo.match(/(\d{6})$/); + const lastSequence = match ? Number(match[1]) : 0; + if (Number.isInteger(lastSequence) && lastSequence > 0) { + sequence = lastSequence + 1; + } + } + + return `${prefix}${datePart}${String(sequence).padStart(6, '0')}`; + } + + /** + * 判断创建盘点任务异常是否由单号唯一键冲突引起。 + * 参照收货单 isReceivingNumberDuplicateError 口径:ER_DUP_ENTRY 且命中 check_no 唯一索引。 + * + * @param {Error} error 创建异常。 + * @return {boolean} 是单号重复错误返回 true。 + */ + isCheckNoDuplicateError(error) { + const parentCode = error && error.parent && error.parent.code; + const sqlMessage = String((error && error.parent && error.parent.sqlMessage) || error.message || ''); + return parentCode === 'ER_DUP_ENTRY' && /uk_check_no|check_no/i.test(sqlMessage); + } + + /** + * 将主表行格式化为对外输出结构(补齐可空字段默认值)。 + * + * @param {Object} row 主表原始行数据。 + * @return {Object} 格式化后的主表行。 + */ + _formatCheckRow(row = {}) { + return { + id: row.id, + check_no: row.check_no, + title: row.title || '', + type: row.type || 'all', + mode: row.mode || 'open', + store_id: row.store_id || null, + status: row.status || 'created', + detail_status: row.detail_status || 'none_checked', + check_date: row.check_date || null, + start_time: row.start_time || null, + end_time: row.end_time || null, + creator_id: row.creator_id || 0, + creator_name: row.creator_name || '', + total_items: row.total_items || 0, + checked_items: row.checked_items || 0, + diff_items: row.diff_items || 0, + remark: row.remark || '', + created_at: row.created_at || null, + updated_at: row.updated_at || null, + }; + } + + /** + * 将 ID 入参(单值或数组)归一化为去重后的正整数列表。 + * + * @param {number|Array} values 原始 ID 入参。 + * @return {Array} 去重后的正整数 ID 列表。 + */ + _normalizeIdList(values) { + const list = Array.isArray(values) ? values : [ values ]; + return [ ...new Set(list.map(value => Number(value)).filter(value => Number.isInteger(value) && value > 0)) ]; + } + + /** + * 将日期值格式化为本地时间字符串(YYYY-MM-DD HH:mm:ss),供 Excel 导出使用。 + * + * @param {*} value 日期值(Date 实例或可解析字符串/数字)。 + * @return {string} 格式化后的本地时间字符串,非法值返回空字符串。 + */ + _formatLocalDateTime(value) { + if (!value) { + return ''; + } + const date = value instanceof Date ? value : new Date(value); + if (Number.isNaN(date.getTime())) { + return ''; + } + const year = date.getFullYear(); + const month = String(date.getMonth() + 1).padStart(2, '0'); + const day = String(date.getDate()).padStart(2, '0'); + const hours = String(date.getHours()).padStart(2, '0'); + const minutes = String(date.getMinutes()).padStart(2, '0'); + const seconds = String(date.getSeconds()).padStart(2, '0'); + return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`; + } + + /** + * 按仓库隔离维度查询盘点主表。 + * + * @param {number} warehouseId 仓库ID。 + * @param {number} id 主表ID。 + * @return {Promise} 主表模型实例,不存在时返回 null。 + */ + async _findCheck(warehouseId, id) { + return this.ctx.model.StockCheck.findOne({ + where: { id: Number(id), warehouse_id: Number(warehouseId) }, + }); + } + + /** + * 重算盘点主表的盘点进度汇总(checked_items / diff_items / detail_status)。 + * 明细已盘口径:该明细存在盘点作业记录(wms_stock_check_record); + * 差异口径:明细实盘合计(记录 quantity 求和)与账面快照 system_quantity 不一致。 + * detail_status 按已盘明细占比自动重算:none_checked → partial_checked → all_checked。 + * + * @param {number} checkId 盘点任务ID。 + * @return {Promise} 重算后的汇总信息。 + */ + async _recalcCheckSummary(checkId) { + const { ctx } = this; + const { fn, col } = ctx.app.Sequelize; + + const detailWhere = { check_id: Number(checkId) }; + const totalItems = await ctx.model.StockCheckDetail.count({ where: detailWhere }); + + // 有作业记录的明细数(DISTINCT detail_id) + const checkedCountRows = await ctx.model.StockCheckRecord.findAll({ + where: { check_id: Number(checkId) }, + attributes: [[ fn('COUNT', fn('DISTINCT', col('detail_id'))), 'checkedCount' ]], + raw: true, + }); + const checkedItems = Number(checkedCountRows && checkedCountRows[0] && checkedCountRows[0].checkedCount) || 0; + + // 差异明细数:实盘合计与账面不一致的明细数 + const diffCountRows = await ctx.model.StockCheckRecord.findAll({ + where: { check_id: Number(checkId) }, + attributes: [ + 'detail_id', + [ fn('SUM', col('quantity')), 'checkedQuantity' ], + ], + group: [ 'detail_id' ], + raw: true, + }); + const checkedQuantityByDetail = new Map(); + for (const row of diffCountRows) { + checkedQuantityByDetail.set(Number(row.detail_id), Number(row.checkedQuantity) || 0); + } + + let diffItems = 0; + if (checkedQuantityByDetail.size > 0) { + const detailRows = await ctx.model.StockCheckDetail.findAll({ + where: detailWhere, + attributes: [ 'id', 'system_quantity' ], + raw: true, + }); + for (const detailRow of detailRows) { + const checkedQuantity = checkedQuantityByDetail.get(Number(detailRow.id)); + if (checkedQuantity === undefined) continue; + const diffQuantity = checkedQuantity - Number(detailRow.system_quantity || 0); + if (diffQuantity !== 0) { + diffItems++; + } + } + } + + const detailStatus = totalItems === 0 || checkedItems === 0 + ? 'none_checked' + : (checkedItems >= totalItems ? 'all_checked' : 'partial_checked'); + + await ctx.model.StockCheck.update( + { + checked_items: checkedItems, + diff_items: diffItems, + detail_status: detailStatus, + }, + { where: { id: Number(checkId) } } + ); + + return { + total_items: totalItems, + checked_items: checkedItems, + diff_items: diffItems, + detail_status: detailStatus, + checked_quantity_by_detail: checkedQuantityByDetail, + }; + } + + /** + * 创建盘点任务(空任务)。 + * 生成单号 PD+YYYYMMDD+6位序号,初始状态 created,明细进度 none_checked。 + * + * @param {Object} params 创建参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {string} [params.title] 盘点名称/主题。 + * @param {string} [params.type='all'] 盘点范围类型:all/store/goods/location。 + * @param {string} [params.mode='open'] 盘点方式:open=明盘/blind=盲盘。 + * @param {number} [params.storeId] 货主ID(按货主盘点时必填)。 + * @param {string} [params.checkDate] 盘点日期。 + * @param {string} [params.remark] 备注。 + * @param {number} params.creatorId 创建人账户ID(由方法层从上下文注入)。 + * @param {string} [params.creatorName] 创建人名称快照(由方法层从上下文注入)。 + * @return {Promise} 新建的盘点任务信息。 + * @throws {Error} 参数非法时抛出业务错误(错误码 400)。 + */ + async create(params = {}) { + const { + warehouseId, + title, + type, + mode, + storeId, + checkDate, + remark, + creatorId, + creatorName, + } = params; + const { ctx } = this; + + const normalizedWarehouseId = Number(warehouseId); + if (!Number.isInteger(normalizedWarehouseId) || normalizedWarehouseId <= 0) { + throw this.createBusinessError('无法获取当前仓库上下文'); + } + + const normalizedType = type ? String(type).trim() : 'all'; + if (!STOCK_CHECK_TYPES.includes(normalizedType)) { + throw this.createBusinessError(`盘点范围类型不合法,仅支持 ${STOCK_CHECK_TYPES.join('/')}`); + } + + const normalizedMode = mode ? String(mode).trim() : 'open'; + if (!STOCK_CHECK_MODES.includes(normalizedMode)) { + throw this.createBusinessError(`盘点方式不合法,仅支持 ${STOCK_CHECK_MODES.join('/')}`); + } + + const normalizedStoreId = storeId !== undefined && storeId !== null && storeId !== '' + ? Number(storeId) + : null; + if (normalizedType === 'store' && (!Number.isInteger(normalizedStoreId) || normalizedStoreId <= 0)) { + throw this.createBusinessError('按货主盘点时必须指定货主'); + } + + const checkDateValue = checkDate ? new Date(checkDate) : null; + if (!checkDateValue || Number.isNaN(checkDateValue.getTime())) { + throw this.createBusinessError('盘点日期不能为空且格式必须合法'); + } + + // 创建盘点任务(并发下撞 uk_check_no 唯一键时自动重取单号,参照收货单口径,最多重试 5 次) + const maxCreateRetries = 5; + let record = null; + for (let attempt = 1; attempt <= maxCreateRetries; attempt++) { + const checkNo = await this.generateCheckNo(); + try { + record = await ctx.model.StockCheck.create({ + warehouse_id: normalizedWarehouseId, + check_no: checkNo, + title: title ? String(title).trim() : null, + type: normalizedType, + mode: normalizedMode, + store_id: normalizedStoreId, + scope_snapshot: null, + status: 'created', + detail_status: 'none_checked', + check_date: checkDateValue, + creator_id: creatorId ? Number(creatorId) : 0, + creator_name: creatorName || null, + remark: remark ? String(remark).trim() : null, + }); + break; + } catch (error) { + if (this.isCheckNoDuplicateError(error) && attempt < maxCreateRetries) { + ctx.logger.warn(`[StockCheckCreateRetry] check_no 冲突,准备重试第 ${attempt + 1} 次`, { + warehouse_id: normalizedWarehouseId, + }); + continue; + } + throw error; + } + } + + return this._formatCheckRow(record.get({ plain: true })); + } + + /** + * 拉取盘点任务列表。 + * 支持 status 筛选(单值或数组)、store_id 货主筛选、keyword(单号/标题模糊)、分页。 + * + * @param {Object} params 查询参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {string|Array} [params.status] 状态筛选。 + * @param {number|string} [params.storeId] 货主筛选。 + * @param {string} [params.keyword] 关键字(盘点单号/标题模糊匹配)。 + * @param {Object} [params.pagination] 分页参数。 + * @return {Promise} { rows, total, page, pageSize }。 + */ + async list(params = {}) { + const { warehouseId, status, storeId, keyword, pagination = {} } = params; + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + + const page = Math.max(1, Number(pagination.page) || 1); + const pageSize = Math.min(200, Math.max(1, Number(pagination.pageSize) || 20)); + + const where = { warehouse_id: Number(warehouseId) }; + + if (status !== undefined && status !== null && status !== '') { + if (Array.isArray(status)) { + const statusList = status.map(item => String(item).trim()).filter(Boolean); + if (statusList.length > 0) { + where.status = { [Op.in]: statusList }; + } + } else { + where.status = String(status).trim(); + } + } + + if (storeId !== undefined && storeId !== null && storeId !== '') { + where.store_id = Number(storeId); + } + + const keywordValue = keyword ? String(keyword).trim() : ''; + if (keywordValue) { + where[Op.or] = [ + { check_no: { [Op.like]: `%${keywordValue}%` } }, + { title: { [Op.like]: `%${keywordValue}%` } }, + ]; + } + + const { count, rows } = await ctx.model.StockCheck.findAndCountAll({ + where, + order: [[ 'id', 'DESC' ]], + offset: (page - 1) * pageSize, + limit: pageSize, + raw: true, + }); + + return { rows, total: count, page, pageSize }; + } + + /** + * 添加盘点明细。 + * 仅 created/rejected 状态允许;按 stock_ids 查询 wms_stock_warehouse 生成明细快照行, + * 已存在同 stock_id 的明细跳过(幂等),重算主表 total_items。 + * + * @param {Object} params 添加明细参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {number} params.id 盘点任务ID。 + * @param {number|Array} params.stockIds 商品库存ID列表(wms_stock_warehouse.id)。 + * @return {Promise} { added, skipped, invalid_stock_ids, total_items }。 + * @throws {Error} 状态不允许或参数非法时抛出业务错误(错误码 400)。 + */ + async addDetail(params = {}) { + const { warehouseId, id, stockIds } = params; + const { ctx } = this; + const { Op } = 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 (!ADD_DETAIL_ALLOWED_STATUSES.includes(check.status)) { + throw this.createBusinessError(`当前状态(${check.status})不允许添加明细`); + } + + const numericStockIds = this._normalizeIdList(stockIds); + if (numericStockIds.length === 0) { + throw this.createBusinessError('请至少选择一个商品'); + } + + // 按 stock_ids 查询库存商品快照(限定当前仓库,自动过滤已删除) + const stockRows = await ctx.model.StockWarehouse.findAll({ + where: { + id: { [Op.in]: numericStockIds }, + warehouse_id: Number(warehouseId), + }, + raw: true, + }); + const stockMap = new Map(stockRows.map(item => [ Number(item.id), item ])); + + // 幂等:已存在同 stock_id 的明细跳过 + const existingRows = await ctx.model.StockCheckDetail.findAll({ + where: { + check_id: checkId, + stock_id: { [Op.in]: numericStockIds }, + }, + attributes: [ 'stock_id' ], + raw: true, + }); + const existingStockIds = new Set(existingRows.map(item => Number(item.stock_id))); + + const toCreate = []; + const skippedStockIds = []; + const invalidStockIds = []; + for (const stockId of numericStockIds) { + const stock = stockMap.get(stockId); + if (!stock) { + invalidStockIds.push(stockId); + continue; + } + if (existingStockIds.has(stockId)) { + skippedStockIds.push(stockId); + continue; + } + toCreate.push({ + check_id: checkId, + warehouse_id: Number(warehouseId), + 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, + }); + } + + if (toCreate.length > 0) { + await ctx.model.StockCheckDetail.bulkCreate(toCreate); + } + + // 重算主表 total_items + const totalItems = await ctx.model.StockCheckDetail.count({ + where: { check_id: checkId }, + }); + await check.update({ total_items: totalItems }); + + return { + added: toCreate.length, + skipped: skippedStockIds.length, + invalid_stock_ids: invalidStockIds, + total_items: totalItems, + }; + } + + /** + * 删除盘点明细(从任务中移除某个商品)。 + * 仅主表状态 created/rejected(ADD_DETAIL_ALLOWED_STATUSES)允许删除; + * 明细存在作业记录(wms_stock_check_record)时一并防御性删除(正常流程该状态不应有记录); + * 删除后重算主表 total_items。 + * + * @param {Object} params 删除参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {number} params.id 盘点任务ID。 + * @param {number} params.detailId 盘点明细ID(方法层已兼容 detail_id/detailId 写法)。 + * @return {Promise} { detail_id, deleted, total_items }。 + * @throws {Error} 参数非法、任务/明细不存在或状态不允许时抛出业务错误(错误码 400)。 + */ + async detailDelete(params = {}) { + const { warehouseId, id, detailId } = params; + const { ctx } = this; + + const checkId = Number(id); + const normalizedDetailId = Number(detailId); + if (!Number.isInteger(checkId) || checkId <= 0) { + throw this.createBusinessError('盘点任务ID不能为空'); + } + if (!Number.isInteger(normalizedDetailId) || normalizedDetailId <= 0) { + throw this.createBusinessError('盘点明细ID不能为空'); + } + + const check = await this._findCheck(warehouseId, checkId); + if (!check) { + throw this.createBusinessError('盘点任务不存在'); + } + if (!ADD_DETAIL_ALLOWED_STATUSES.includes(check.status)) { + throw this.createBusinessError(`当前状态(${check.status})不允许删除明细`); + } + + const detail = await ctx.model.StockCheckDetail.findOne({ + where: { + id: normalizedDetailId, + check_id: checkId, + warehouse_id: Number(warehouseId), + }, + }); + if (!detail) { + throw this.createBusinessError('盘点明细不存在'); + } + + await detail.destroy(); + + // 防御性处理:若该明细存在作业记录(正常流程 created/rejected 不应有记录),一并删除 + await ctx.model.StockCheckRecord.destroy({ + where: { + detail_id: normalizedDetailId, + check_id: checkId, + warehouse_id: Number(warehouseId), + }, + }); + + // 删除明细后重算主表 total_items + const totalItems = await ctx.model.StockCheckDetail.count({ + where: { check_id: checkId }, + }); + await check.update({ total_items: totalItems }); + + return { + detail_id: normalizedDetailId, + deleted: true, + total_items: totalItems, + }; + } + + /** + * 拉取盘点任务的全部明细行(商品清单)及其盘点作业记录(库位+数量)。 + * + * @param {Object} params 查询参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {number} params.id 盘点任务ID。 + * @return {Promise} { check, rows, total };rows 每条含商品快照 + 已盘聚合 + * (checked_quantity=记录数量合计、diff_quantity=实盘-账面、is_diff、location_codes、 + * checkers、last_checked_at)、records(该明细全部作业记录)与 locations + * (按库位聚合 [{ location_id, location_code, quantity }],按首条记录 id 升序)。 + * @throws {Error} 任务不存在时抛出业务错误(错误码 400)。 + */ + async detail(params = {}) { + const { warehouseId, id } = params; + const { ctx } = this; + + const checkId = Number(id); + if (!Number.isInteger(checkId) || checkId <= 0) { + throw this.createBusinessError('盘点任务ID不能为空'); + } + + const check = await this._findCheck(warehouseId, checkId); + if (!check) { + throw this.createBusinessError('盘点任务不存在'); + } + + const detailRows = await ctx.model.StockCheckDetail.findAll({ + where: { check_id: checkId, warehouse_id: Number(warehouseId) }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + const records = await ctx.model.StockCheckRecord.findAll({ + where: { check_id: checkId, warehouse_id: Number(warehouseId) }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + + // 按明细聚合作业记录 + const recordsByDetail = new Map(); + for (const record of records) { + const detailRowId = Number(record.detail_id); + if (!recordsByDetail.has(detailRowId)) { + recordsByDetail.set(detailRowId, []); + } + recordsByDetail.get(detailRowId).push(record); + } + + const rows = detailRows.map(detailRow => { + const detailRowId = Number(detailRow.id); + const detailRecords = recordsByDetail.get(detailRowId) || []; + const checkedQuantity = detailRecords.reduce((sum, record) => sum + (Number(record.quantity) || 0), 0); + const diffQuantity = checkedQuantity - Number(detailRow.system_quantity || 0); + const locationCodes = [ ...new Set(detailRecords + .map(record => String(record.location_code || '').trim()) + .filter(Boolean)) ]; + const checkers = [ ...new Set(detailRecords + .map(record => String(record.checker_name || '').trim()) + .filter(Boolean)) ]; + const lastCheckedAt = detailRecords.length > 0 + ? detailRecords[detailRecords.length - 1].checked_at + : null; + + // 按库位聚合作业记录(库位为空归入"无库位"分组,location_code 为 null),按首条记录 id 升序 + const locationGroups = new Map(); + for (const record of detailRecords) { + const recordLocationCode = record.location_code !== null && record.location_code !== undefined + ? String(record.location_code).trim() + : ''; + if (!locationGroups.has(recordLocationCode)) { + locationGroups.set(recordLocationCode, { + location_id: recordLocationCode ? (Number(record.location_id) || null) : null, + location_code: recordLocationCode || null, + quantity: 0, + first_record_id: Number(record.id) || 0, + }); + } + const locationGroup = locationGroups.get(recordLocationCode); + locationGroup.quantity += Number(record.quantity) || 0; + } + const locations = [ ...locationGroups.values() ] + .sort((left, right) => left.first_record_id - right.first_record_id) + .map(locationGroup => ({ + location_id: locationGroup.location_id, + location_code: locationGroup.location_code, + quantity: locationGroup.quantity, + })); + + return { + ...detailRow, + checked_quantity: detailRecords.length > 0 ? checkedQuantity : null, + diff_quantity: detailRecords.length > 0 ? diffQuantity : null, + is_diff: detailRecords.length > 0 && diffQuantity !== 0 ? 1 : 0, + status: detailRecords.length > 0 ? 'checked' : 'unchecked', + location_codes: locationCodes, + checkers, + last_checked_at: lastCheckedAt, + records: detailRecords, + locations, + }; + }); + + return { + check: this._formatCheckRow(check.get({ plain: true })), + rows, + total: rows.length, + }; + } + + /** + * 盘点作业上报(覆盖式)。 + * 仅 approved/checking 状态允许;同明细 + 同库位编码重复上报时更新已有记录的 + * quantity/checker_id/checker_name/checked_at(保留原 location_id,若本次新匹配到 location_id 则回填), + * 不再新增;未传库位归入"无库位"分组(location_code 存空串); + * 库位编码匹配 wms_location_space.space_code 时回填 location_id; + * 主表 approved 自动转 checking;重算 checked_items / diff_items / detail_status。 + * 数据库层由唯一索引 uk_detail_location(detail_id, location_code) 保证并发下不产生重复记录。 + * + * @param {Object} params 上报参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {number} params.id 盘点任务ID。 + * @param {number} params.detailId 明细ID。 + * @param {string} [params.location] 库位编码(可空)。 + * @param {number} params.quantity 实盘数量(>=0)。 + * @param {number} [params.checkerId] 盘点人账户ID(由方法层从上下文注入)。 + * @param {string} [params.checkerName] 盘点人名称快照(由方法层从上下文注入)。 + * @return {Promise} { record, detail_id, mode, total_items, checked_items, diff_items, detail_status }。 + * @throws {Error} 状态不允许或参数非法时抛出业务错误(错误码 400)。 + */ + async report(params = {}) { + const { + warehouseId, + id, + detailId, + location, + quantity, + checkerId, + checkerName, + } = params; + const { ctx } = this; + + 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 quantityValue = Number(quantity); + if (!Number.isInteger(quantityValue) || quantityValue < 0) { + throw this.createBusinessError('实盘数量必须为不小于0的整数'); + } + + const detail = await ctx.model.StockCheckDetail.findOne({ + where: { id: detailRowId, check_id: checkId, warehouse_id: Number(warehouseId) }, + }); + if (!detail) { + throw this.createBusinessError('盘点明细不存在'); + } + + // 库位编码匹配 wms_location_space.space_code 时回填 location_id; + // 未传库位归一为空串("无库位"分组,配合 uk_detail_location 唯一索引) + const locationCode = location !== undefined && location !== null && String(location).trim() !== '' + ? String(location).trim() + : ''; + let locationId = null; + if (locationCode) { + const space = await ctx.model.LocationSpace.findOne({ + where: { + warehouse_id: Number(warehouseId), + space_code: locationCode, + }, + attributes: [ 'id' ], + raw: true, + }); + if (space) { + locationId = space.id; + } + } + + const now = new Date(); + + // 覆盖式上报:同明细 + 同库位编码(未传库位为空串"无库位"分组)更新已有记录; + // 依赖唯一索引 uk_detail_location(detail_id, location_code) 保证并发安全 + const existingRecordWhere = { detail_id: detailRowId, location_code: locationCode }; + const existingRecord = await ctx.model.StockCheckRecord.findOne({ + where: existingRecordWhere, + }); + + const normalizedCheckerId = checkerId ? Number(checkerId) : null; + const normalizedCheckerName = checkerName || null; + let record = null; + let mode = 'created'; + if (existingRecord) { + // 保留原 location_id,若本次新匹配到 location_id 则回填 + const resolvedLocationId = locationId !== null && locationId !== undefined + ? locationId + : existingRecord.location_id; + await existingRecord.update({ + quantity: quantityValue, + checker_id: normalizedCheckerId, + checker_name: normalizedCheckerName, + checked_at: now, + location_id: resolvedLocationId, + }); + record = existingRecord.get({ plain: true }); + mode = 'updated'; + } else { + try { + const createdRecord = await ctx.model.StockCheckRecord.create({ + check_id: checkId, + warehouse_id: Number(warehouseId), + detail_id: detailRowId, + stock_id: Number(detail.stock_id), + location_id: locationId, + location_code: locationCode, + quantity: quantityValue, + checker_id: normalizedCheckerId, + checker_name: normalizedCheckerName, + checked_at: now, + }); + record = createdRecord.get({ plain: true }); + } catch (error) { + // 并发下撞唯一索引 uk_detail_location:降级为更新已有记录,避免调用方收到 500 + const isDuplicate = (error && error.name === 'SequelizeUniqueConstraintError') + || (error && error.original && error.original.code === 'ER_DUP_ENTRY'); + if (!isDuplicate) { + throw error; + } + const latestRecord = await ctx.model.StockCheckRecord.findOne({ + where: existingRecordWhere, + }); + if (!latestRecord) { + throw error; + } + const resolvedLocationId = locationId !== null && locationId !== undefined + ? locationId + : latestRecord.location_id; + await latestRecord.update({ + quantity: quantityValue, + checker_id: normalizedCheckerId, + checker_name: normalizedCheckerName, + checked_at: now, + location_id: resolvedLocationId, + }); + record = latestRecord.get({ plain: true }); + mode = 'updated'; + } + } + + // 主表 approved → checking 自动转移(首次上报) + if (check.status === 'approved') { + await check.update({ + status: 'checking', + start_time: check.start_time || now, + }); + } + + // 重算 checked_items / diff_items / detail_status + const summary = await this._recalcCheckSummary(checkId); + + return { + record, + detail_id: detailRowId, + mode, + ...summary, + }; + } + + /** + * 拉取盘点作业记录列表。 + * 至少传 id(盘点任务ID)或 detail_id(明细ID)之一;rows 每条为作业记录全字段 + + * 商品快照列(item_code/item_name,从明细表查得);按记录 id 倒序。 + * + * @param {Object} params 查询参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {number} [params.id] 盘点任务ID(可选)。 + * @param {number} [params.detailId] 明细ID(可选)。 + * @param {Object} [params.pagination] 分页参数。 + * @return {Promise} { rows, total, page, pageSize }。 + * @throws {Error} 未传任务ID或明细ID时抛出业务错误(错误码 400)。 + */ + async recordList(params = {}) { + const { warehouseId, id, detailId, pagination = {} } = params; + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + + const checkId = id !== undefined && id !== null && id !== '' ? Number(id) : 0; + const normalizedDetailId = detailId !== undefined && detailId !== null && detailId !== '' ? Number(detailId) : 0; + const hasCheckId = Number.isInteger(checkId) && checkId > 0; + const hasDetailId = Number.isInteger(normalizedDetailId) && normalizedDetailId > 0; + if (!hasCheckId && !hasDetailId) { + throw this.createBusinessError('请至少提供盘点任务ID或明细ID'); + } + + const page = Math.max(1, Number(pagination.page) || 1); + const pageSize = Math.min(200, Math.max(1, Number(pagination.pageSize) || 20)); + + const where = { warehouse_id: Number(warehouseId) }; + if (hasCheckId) { + where.check_id = checkId; + } + if (hasDetailId) { + where.detail_id = normalizedDetailId; + } + + const { count, rows } = await ctx.model.StockCheckRecord.findAndCountAll({ + where, + order: [[ 'id', 'DESC' ]], + offset: (page - 1) * pageSize, + limit: pageSize, + raw: true, + }); + + // 商品快照列(item_code/item_name)从明细表补齐 + 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' ], + raw: true, + }); + itemByDetailId = new Map(detailRows.map(item => [ Number(item.id), item ])); + } + + const formattedRows = rows.map(row => { + const item = itemByDetailId.get(Number(row.detail_id)) || {}; + return { + ...row, + // 空串表示"无库位"分组,接口返回口径统一为 null + location_code: String(row.location_code || '').trim() !== '' ? row.location_code : null, + item_code: item.item_code || null, + item_name: item.item_name || null, + }; + }); + + return { rows: formattedRows, total: count, page, pageSize }; + } + + /** + * 删除盘点作业记录。 + * 仅主表状态 approved/checking 允许删除;记录不存在或不属于该任务/仓库时报 400; + * 删除后重算 checked_items/diff_items/detail_status(明细记录删光后该明细回到未盘),主表状态不回退。 + * + * @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)。 + */ + async recordDelete(params = {}) { + const { warehouseId, id, recordId } = params; + const { ctx } = this; + + 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) { + throw this.createBusinessError('盘点任务不存在'); + } + if (!REPORT_ALLOWED_STATUSES.includes(check.status)) { + throw this.createBusinessError(`当前状态(${check.status})不允许删除作业记录`); + } + + const record = await ctx.model.StockCheckRecord.findOne({ + where: { + id: normalizedRecordId, + check_id: checkId, + warehouse_id: Number(warehouseId), + }, + }); + if (!record) { + throw this.createBusinessError('作业记录不存在或不属于该盘点任务'); + } + + await record.destroy(); + + // 重算 checked_items / diff_items / detail_status(明细记录删光后该明细回到未盘),主表状态不回退 + const summary = await this._recalcCheckSummary(checkId); + + return { + record_id: normalizedRecordId, + deleted: true, + ...summary, + }; + } + + /** + * 完成盘点作业(允许部分未盘完成)。 + * 仅 approved/checking 状态允许;未盘明细按实盘 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; + + // 差异汇总:按明细聚合实盘数量与账面快照对比,盘盈合计 / 盘亏合计 + const summary = await this._recalcCheckSummary(checkId); + const checkedQuantityByDetail = summary.checked_quantity_by_detail || new Map(); + const detailRows = await ctx.model.StockCheckDetail.findAll({ + where: { check_id: checkId }, + attributes: [ 'id', 'system_quantity' ], + raw: true, + }); + let profitTotal = 0; + let lossTotal = 0; + let diffItems = 0; + for (const detailRow of detailRows) { + const checkedQuantity = checkedQuantityByDetail.get(Number(detailRow.id)); + const systemQuantity = Number(detailRow.system_quantity || 0); + // 已盘明细按记录聚合差异;未盘明细按实盘 0 处理(差异 = -账面快照,即盘亏) + const diffQuantity = checkedQuantity === undefined + ? -systemQuantity + : checkedQuantity - systemQuantity; + if (diffQuantity > 0) { + profitTotal += diffQuantity; + diffItems++; + } else if (diffQuantity < 0) { + lossTotal += Math.abs(diffQuantity); + diffItems++; + } + } + + await check.update({ + status: 'completed', + end_time: new Date(), + detail_status: 'all_checked', + checked_items: checkedItems, + diff_items: diffItems, + }); + + return { + id: checkId, + status: 'completed', + total_items: totalItems, + checked_items: checkedItems, + unchecked_items: uncheckedItems, + diff_items: diffItems, + profit_total: profitTotal, + loss_total: lossTotal, + }; + } + + /** + * 完成盘点任务(提交审核)。 + * 仅 created/rejected 状态允许;校验 total_items>0 后置为 submitted。 + * + * @param {Object} params 提交参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {number} params.id 盘点任务ID。 + * @return {Promise} { id, status }。 + * @throws {Error} 状态不允许或没有明细时抛出业务错误(错误码 400)。 + */ + async submit(params = {}) { + const { warehouseId, id } = 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 (!SUBMIT_ALLOWED_STATUSES.includes(check.status)) { + throw this.createBusinessError(`当前状态(${check.status})不允许提交审核`); + } + if (Number(check.total_items) <= 0) { + throw this.createBusinessError('盘点任务还没有明细行,无法提交审核'); + } + + await check.update({ status: 'submitted' }); + + return { + id: checkId, + status: 'submitted', + }; + } + + /** + * 取消盘点任务。 + * 仅 created/submitted/rejected 状态允许;取消后置为 cancelled(终态)。 + * + * @param {Object} params 取消参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {number} params.id 盘点任务ID。 + * @return {Promise} { id, status }。 + * @throws {Error} 状态不允许时抛出业务错误(错误码 400)。 + */ + async cancel(params = {}) { + const { warehouseId, id } = 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 (!CANCEL_ALLOWED_STATUSES.includes(check.status)) { + throw this.createBusinessError(`当前状态(${check.status})不允许取消`); + } + + await check.update({ status: 'cancelled' }); + + return { + id: checkId, + status: 'cancelled', + }; + } + + /** + * 审核盘点任务。 + * 仅 submitted 状态允许;approve → approved,reject → rejected(reason 可选写入备注)。 + * + * @param {Object} params 审核参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {number} params.id 盘点任务ID。 + * @param {string} params.action 审核动作:approve=通过,reject=驳回。 + * @param {string} [params.reason] 驳回原因(写入备注)。 + * @return {Promise} { id, status }。 + * @throws {Error} 状态不允许或动作非法时抛出业务错误(错误码 400)。 + */ + async audit(params = {}) { + const { warehouseId, id, action, reason } = params; + + const checkId = Number(id); + if (!Number.isInteger(checkId) || checkId <= 0) { + throw this.createBusinessError('盘点任务ID不能为空'); + } + + const actionValue = action ? String(action).trim() : ''; + if (actionValue !== 'approve' && actionValue !== 'reject') { + throw this.createBusinessError('审核动作仅支持 approve/reject'); + } + + const check = await this._findCheck(warehouseId, checkId); + if (!check) { + throw this.createBusinessError('盘点任务不存在'); + } + if (check.status !== 'submitted') { + throw this.createBusinessError(`当前状态(${check.status})不允许审核`); + } + + if (actionValue === 'approve') { + await check.update({ status: 'approved' }); + } else { + const reasonValue = reason !== undefined && reason !== null && String(reason).trim() !== '' + ? String(reason).trim() + : check.remark; + await check.update({ + status: 'rejected', + remark: reasonValue, + }); + } + + return { + id: checkId, + status: actionValue === 'approve' ? 'approved' : 'rejected', + }; + } + + /** + * 盘点任务导出:查询任务与明细 → Sheet1「盘点单」一行一个盘点任务、 + * Sheet2「盘点明细」一行一条明细(首列盘点单号)→ 流式生成 Excel → COS 上传。 + * 通过 onProgress 回调实时推送进度。 + * + * @param {Object} params 导出参数。 + * @param {number} params.warehouseId 仓库ID(由方法层从上下文注入)。 + * @param {Array} params.ids 盘点任务ID数组。 + * @param {Function} [params.onProgress] 进度回调。 + * @return {Promise} 导出结果,包含文件下载信息与数量统计。 + * @throws {Error} 没有可导出的任务时抛出业务错误(错误码 400)。 + */ + async exportStockChecks(params = {}) { + const { warehouseId, ids, onProgress } = params; + const { ctx } = this; + const { Op } = ctx.app.Sequelize; + + const reportProgress = async (status, progress, message, extra = {}) => { + if (typeof onProgress === 'function') { + await onProgress({ status, progress, message, ...extra }); + } + }; + + await reportProgress('running', 5, '正在准备导出数据...'); + + const numericIds = this._normalizeIdList(ids); + if (numericIds.length === 0) { + throw this.createBusinessError('请至少选择一个盘点任务'); + } + + const checks = await ctx.model.StockCheck.findAll({ + where: { + id: { [Op.in]: numericIds }, + warehouse_id: Number(warehouseId), + }, + order: [[ 'id', 'ASC' ]], + raw: true, + }); + if (checks.length === 0) { + throw this.createBusinessError('未找到可导出的盘点任务'); + } + + // 明细与作业记录统一拉取,明细行聚合作业记录(已盘数量/差异/库位列表) + const detailRows = await ctx.model.StockCheckDetail.findAll({ + where: { check_id: { [Op.in]: numericIds } }, + order: [[ 'check_id', 'ASC' ], [ 'id', 'ASC' ]], + raw: true, + }); + const recordRows = await ctx.model.StockCheckRecord.findAll({ + where: { check_id: { [Op.in]: numericIds } }, + order: [[ 'detail_id', 'ASC' ], [ 'id', 'ASC' ]], + raw: true, + }); + const recordsByDetail = new Map(); + for (const record of recordRows) { + const detailRowId = Number(record.detail_id); + if (!recordsByDetail.has(detailRowId)) { + recordsByDetail.set(detailRowId, []); + } + recordsByDetail.get(detailRowId).push(record); + } + + const detailsGrouped = new Map(); + for (const row of detailRows) { + const checkId = Number(row.check_id); + if (!detailsGrouped.has(checkId)) { + detailsGrouped.set(checkId, []); + } + const detailRecords = recordsByDetail.get(Number(row.id)) || []; + const checkedQuantity = detailRecords.length > 0 + ? detailRecords.reduce((sum, record) => sum + (Number(record.quantity) || 0), 0) + : null; + const diffQuantity = checkedQuantity === null + ? null + : checkedQuantity - Number(row.system_quantity || 0); + detailsGrouped.get(checkId).push({ + ...row, + checked_quantity: checkedQuantity, + diff_quantity: diffQuantity, + is_diff: checkedQuantity === null ? 0 : (diffQuantity !== 0 ? 1 : 0), + status: detailRecords.length > 0 ? 'checked' : 'unchecked', + location_codes: [ ...new Set(detailRecords + .map(record => String(record.location_code || '').trim()) + .filter(Boolean)) ], + checkers: [ ...new Set(detailRecords + .map(record => String(record.checker_name || '').trim()) + .filter(Boolean)) ], + last_checked_at: detailRecords.length > 0 + ? detailRecords[detailRecords.length - 1].checked_at + : null, + }); + } + + const totalCount = detailRows.length; + await reportProgress('running', 10, `共 ${checks.length} 个盘点任务、${totalCount} 条明细,开始导出...`, { + totalCount, + currentCount: 0, + }); + + const exportResult = await this._generateAndUploadStockCheckExcel(checks, detailsGrouped, { + totalCount, + onProgress, + }); + + await reportProgress('success', 100, '导出完成', { + totalCount, + currentCount: totalCount, + result: exportResult, + }); + + return { + ...exportResult, + total_count: totalCount, + current_count: totalCount, + }; + } + + /** + * 生成盘点导出 Excel(Sheet1=盘点单行,Sheet2=明细行)并上传 COS,返回下载信息。 + * 与售后/退回拆包导出口径一致:流式写临时文件 → uploadFile → uploadSuccessNotify。 + * + * @param {Array} checks 盘点任务主表行。 + * @param {Map>} detailsGrouped 按 check_id 分组的明细行。 + * @param {Object} [options] 附加选项。 + * @param {number} [options.totalCount] 明细总行数(用于进度计算)。 + * @param {Function} [options.onProgress] 进度回调。 + * @return {Promise} { filename, fileKey, url, cdnUrl, cosUrl }。 + */ + async _generateAndUploadStockCheckExcel(checks = [], detailsGrouped = new Map(), options = {}) { + const { totalCount = 0, onProgress } = options; + const { ctx } = this; + + const reportProgress = async (status, progress, message, extra = {}) => { + if (typeof onProgress === 'function') { + await onProgress({ status, progress, message, ...extra }); + } + }; + + const tempDir = await fsp.mkdtemp(path.join(os.tmpdir(), 'wms-stock-check-export-')); + const now = new Date(); + const dateToken = `${now.getFullYear()}${String(now.getMonth() + 1).padStart(2, '0')}${String(now.getDate()).padStart(2, '0')}${String(now.getHours()).padStart(2, '0')}${String(now.getMinutes()).padStart(2, '0')}${String(now.getSeconds()).padStart(2, '0')}`; + const filename = `库存盘点导出_${dateToken}.xlsx`; + const filePath = path.join(tempDir, filename); + + const workbook = new ExcelJS.stream.xlsx.WorkbookWriter({ + filename: filePath, + useStyles: false, + useSharedStrings: false, + }); + + try { + // ---- Sheet1:盘点单行(一行一个盘点任务) ---- + const checksSheet = workbook.addWorksheet('盘点单'); + checksSheet.addRow([ + '盘点单号', + '盘点名称', + '盘点范围', + '盘点方式', + '盘点状态', + '盘点进度', + '盘点日期', + '货主ID', + '创建人', + '明细行数', + '已盘行数', + '差异行数', + '开始时间', + '结束时间', + '备注', + ]).commit(); + + for (const check of checks) { + checksSheet.addRow([ + check.check_no || '', + check.title || '', + STOCK_CHECK_TYPE_LABELS[check.type] || check.type || '', + STOCK_CHECK_MODE_LABELS[check.mode] || check.mode || '', + STOCK_CHECK_STATUS_LABELS[check.status] || check.status || '', + STOCK_CHECK_DETAIL_PROGRESS_LABELS[check.detail_status] || check.detail_status || '', + this._formatLocalDateTime(check.check_date), + check.store_id === null || check.store_id === undefined ? '' : Number(check.store_id), + check.creator_name || '', + Number(check.total_items) || 0, + Number(check.checked_items) || 0, + Number(check.diff_items) || 0, + this._formatLocalDateTime(check.start_time), + this._formatLocalDateTime(check.end_time), + check.remark || '', + ]).commit(); + } + checksSheet.commit(); + + // ---- Sheet2:明细行(一行一条明细,首列带盘点单号便于对照) ---- + const detailsSheet = workbook.addWorksheet('盘点明细'); + detailsSheet.addRow([ + '盘点单号', + '商品编码', + '商品名称', + '规格', + '账面数量', + '已盘数量', + '差异数量', + '是否有差异', + '库位编码', + '盘点人', + '最近盘点时间', + ]).commit(); + + let currentCount = 0; + for (const check of checks) { + const checkId = Number(check.id); + const rows = detailsGrouped.get(checkId) || []; + + for (const row of rows) { + detailsSheet.addRow([ + check.check_no || '', + row.item_code || '', + row.item_name || '', + row.spec || '', + Number(row.system_quantity) || 0, + row.checked_quantity === null || row.checked_quantity === undefined ? '' : Number(row.checked_quantity), + row.diff_quantity === null || row.diff_quantity === undefined ? '' : Number(row.diff_quantity), + Number(row.is_diff) === 1 ? '是' : '否', + Array.isArray(row.location_codes) ? row.location_codes.join('、') : '', + Array.isArray(row.checkers) ? row.checkers.join('、') : '', + this._formatLocalDateTime(row.last_checked_at), + ]).commit(); + + currentCount++; + // 每 200 行汇报一次进度 + if (currentCount % 200 === 0 || currentCount === totalCount) { + const progress = 10 + Math.floor((currentCount / Math.max(1, totalCount)) * 80); + await reportProgress('running', progress, `正在导出... (${currentCount}/${totalCount})`, { + totalCount, + currentCount, + }); + } + } + } + detailsSheet.commit(); + + await workbook.commit(); + + await reportProgress('running', 90, '正在上传文件...', { totalCount, currentCount: totalCount }); + + // ---- 上传文件(与 afterSale/return_unpack 导出口径一致)---- + const uploadService = ctx && ctx.service && ctx.service.systems && ctx.service.systems.upload; + if (!uploadService || typeof uploadService.uploadFile !== 'function') { + throw new Error('上传服务不可用'); + } + + const stat = await fsp.stat(filePath); + const randomToken = crypto.randomBytes(6).toString('hex'); + const uploadKey = `exports/stock_check/${Date.now()}_${randomToken}.xlsx`; + const uploadStream = fs.createReadStream(filePath); + uploadStream.filename = filename; + uploadStream.mimeType = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'; + uploadStream.fileSize = stat.size; + + const uploadResult = await uploadService.uploadFile(uploadStream, { + key: uploadKey, + category: 'document', + mimetype: 'xls,xlsx,csv', + }); + + let fileRecord = null; + if (typeof uploadService.uploadSuccessNotify === 'function') { + fileRecord = await uploadService.uploadSuccessNotify({ + url: uploadResult.fileName, + fileKey: uploadResult.fileName, + fileName: filename, + fileType: 'document', + mimeType: uploadStream.mimeType, + fileSize: stat.size, + category: 'document', + businessType: 'stockCheckExport', + description: `库存盘点导出,共 ${checks.length} 个盘点任务、${totalCount} 条明细`, + }); + } + + // 优先取 uploadFile 返回的完整 URL,其次取 uploadSuccessNotify 落库记录,最后回退 COS key + const safeUploadResult = typeof uploadResult === 'object' && uploadResult !== null ? uploadResult : {}; + const resolvedFileRecord = (fileRecord && (fileRecord.data || fileRecord)) || null; + const fileUrlFromRecord = resolvedFileRecord + ? (resolvedFileRecord.file_url || resolvedFileRecord.fileUrl || resolvedFileRecord.url || '') + : ''; + const uploadResultUrl = safeUploadResult.url || safeUploadResult.cdnUrl || safeUploadResult.cosUrl || ''; + + return { + filename, + fileKey: safeUploadResult.fileName || uploadKey, + url: uploadResultUrl || fileUrlFromRecord || safeUploadResult.fileName || uploadKey, + cdnUrl: safeUploadResult.cdnUrl || safeUploadResult.url || '', + cosUrl: safeUploadResult.cosUrl || '', + }; + } catch (error) { + const workbookStream = workbook.stream; + if (workbookStream && typeof workbookStream.destroy === 'function') { + workbookStream.destroy(); + } + ctx.logger.error(`[stock.check.export] 生成/上传 Excel 失败: ${error.message}`); + throw error; + } finally { + await fsp.rm(tempDir, { recursive: true, force: true }); + } + } +} + +module.exports = StockCheckService; diff --git a/database/migrations/20260929110000-align-stock-check-status-machine.js b/database/migrations/20260929110000-align-stock-check-status-machine.js new file mode 100644 index 0000000..952accc --- /dev/null +++ b/database/migrations/20260929110000-align-stock-check-status-machine.js @@ -0,0 +1,43 @@ +'use strict'; + +const CHECK_TABLE_NAME = 'wms_stock_check'; +const DETAIL_TABLE_NAME = 'wms_stock_check_detail'; + +/** + * 库存盘点状态机对齐迁移。 + * 主表 wms_stock_check.status 的 defaultValue 由 'pending' 改为 'created', + * 注释更新为新状态机枚举;detail_status 与明细表 status 的注释同步更新(字段类型不变)。 + */ +module.exports = { + up: async queryInterface => { + // 主表 status:默认值 pending → created,注释更新为新状态机枚举 + await queryInterface.sequelize.query( + `ALTER TABLE \`${CHECK_TABLE_NAME}\` MODIFY COLUMN \`status\` VARCHAR(20) NOT NULL DEFAULT 'created' COMMENT '盘点状态机:created=已创建(空任务),submitted=待审核,rejected=已驳回,approved=审核完成(待盘点作业),checking=盘点作业中,completed=已完成,cancelled=已取消'` + ); + + // 主表 detail_status:注释同步更新(类型与默认值不变) + await queryInterface.sequelize.query( + `ALTER TABLE \`${CHECK_TABLE_NAME}\` MODIFY COLUMN \`detail_status\` VARCHAR(30) NOT NULL DEFAULT 'none_checked' COMMENT '明细盘点进度(按已盘明细占比自动重算):none_checked=未盘,partial_checked=部分已盘,all_checked=全部已盘'` + ); + + // 明细表 status:注释同步更新(类型与默认值不变) + await queryInterface.sequelize.query( + `ALTER TABLE \`${DETAIL_TABLE_NAME}\` MODIFY COLUMN \`status\` VARCHAR(20) NOT NULL DEFAULT 'unchecked' COMMENT '明细状态:unchecked=未盘,checked=已盘'` + ); + }, + + down: async queryInterface => { + // 回退:恢复旧默认值与旧注释 + await queryInterface.sequelize.query( + `ALTER TABLE \`${CHECK_TABLE_NAME}\` MODIFY COLUMN \`status\` VARCHAR(20) NOT NULL DEFAULT 'pending' COMMENT '盘点状态:pending=待盘点,in_progress=盘点中,checked=已盘待确认,confirmed=已确认,completed=已完成,cancelled=已取消'` + ); + + await queryInterface.sequelize.query( + `ALTER TABLE \`${CHECK_TABLE_NAME}\` MODIFY COLUMN \`detail_status\` VARCHAR(30) NOT NULL DEFAULT 'none_checked' COMMENT '明细盘点进度:none_checked=未盘,partial_checked=部分已盘,all_checked=全部已盘'` + ); + + await queryInterface.sequelize.query( + `ALTER TABLE \`${DETAIL_TABLE_NAME}\` MODIFY COLUMN \`status\` VARCHAR(20) NOT NULL DEFAULT 'unchecked' COMMENT '明细状态:unchecked=未盘,checked=已盘,confirmed=已确认'` + ); + }, +}; diff --git a/database/migrations/20260929120000-split-stock-check-detail-create-record.js b/database/migrations/20260929120000-split-stock-check-detail-create-record.js new file mode 100644 index 0000000..9fe1150 --- /dev/null +++ b/database/migrations/20260929120000-split-stock-check-detail-create-record.js @@ -0,0 +1,184 @@ +'use strict'; + +/** + * 拆分盘点明细表:明细表只保留盘点商品(stock_id + 商品快照), + * 盘点作业产生的库位/数量信息下沉到新建的 wms_stock_check_record(盘点作业记录表)。 + * + * 变更内容: + * 1. wms_stock_check_detail 移除作业字段: + * location_id / location_code(库位信息) + * check_quantity / diff_quantity / is_diff(实盘数量与差异) + * status / checker_id / checker_name / checked_at(盘点状态与盘点人) + * 2. 新建 wms_stock_check_record(盘点作业记录,一个明细可在多个库位多次上报): + * check_id(关联主表,冗余)、warehouse_id(冗余隔离)、detail_id(关联明细)、 + * stock_id(冗余,商品维度查询)、location_id(space_code 匹配时回填)、 + * location_code(库位编码)、quantity(实盘数量)、checker_id / checker_name、 + * checked_at(上报时间)、remark、created_at / updated_at。 + * + * 索引(wms_stock_check_record): + * idx_check_id(按任务查记录) + * idx_detail_id(按明细查记录) + * idx_stock_id(按商品反查) + * idx_warehouse_location(仓库+库位) + */ + +const DETAIL_TABLE_NAME = 'wms_stock_check_detail'; +const RECORD_TABLE_NAME = 'wms_stock_check_record'; + +/** 明细表需要移除的作业字段 */ +const DROP_COLUMNS = [ + 'location_id', + 'location_code', + 'check_quantity', + 'diff_quantity', + 'is_diff', + 'status', + 'checker_id', + 'checker_name', + 'checked_at', +]; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const { BIGINT, STRING, INTEGER, DATE } = Sequelize; + + // 1) 明细表移除作业字段 + for (const columnName of DROP_COLUMNS) { + await queryInterface.removeColumn(DETAIL_TABLE_NAME, columnName); + } + + // 2) 新建盘点作业记录表 + const tables = await queryInterface.showAllTables(); + const exists = tables.some(t => (typeof t === 'string' ? t : (t.tableName || t.name)) === RECORD_TABLE_NAME); + if (!exists) { + await queryInterface.createTable(RECORD_TABLE_NAME, { + id: { + type: BIGINT(20).UNSIGNED, + primaryKey: true, + autoIncrement: true, + allowNull: false, + comment: '主键', + }, + check_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '关联盘点主表 wms_stock_check.id(冗余,便于按任务查记录)', + }, + warehouse_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '仓库ID(冗余,隔离查询)', + }, + detail_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '关联盘点明细 wms_stock_check_detail.id', + }, + stock_id: { + type: BIGINT(20).UNSIGNED, + allowNull: false, + comment: '库存商品ID(冗余,商品维度查询),关联 wms_stock_warehouse.id', + }, + location_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '库位ID,关联 wms_location_space.id;库位编码匹配时回填,未匹配为空', + }, + location_code: { + type: STRING(50), + allowNull: true, + comment: '库位编码(盘点上报的库位)', + }, + quantity: { + type: INTEGER(12), + allowNull: false, + defaultValue: 0, + comment: '实盘数量(不小于0的整数)', + }, + checker_id: { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '盘点人账户ID', + }, + checker_name: { + type: STRING(50), + allowNull: true, + comment: '盘点人名称快照', + }, + checked_at: { + type: DATE, + allowNull: true, + comment: '上报时间', + }, + remark: { + type: STRING(500), + allowNull: true, + comment: '备注', + }, + created_at: { type: DATE, allowNull: false }, + updated_at: { type: DATE, allowNull: false }, + }); + + await queryInterface.addIndex(RECORD_TABLE_NAME, [ 'check_id' ], { name: 'idx_check_id' }); + await queryInterface.addIndex(RECORD_TABLE_NAME, [ 'detail_id' ], { name: 'idx_detail_id' }); + await queryInterface.addIndex(RECORD_TABLE_NAME, [ 'stock_id' ], { name: 'idx_stock_id' }); + await queryInterface.addIndex(RECORD_TABLE_NAME, [ 'warehouse_id', 'location_code' ], { name: 'idx_warehouse_location' }); + } + }, + + down: async (queryInterface, Sequelize) => { + const { BIGINT, STRING, INTEGER, DATE, TINYINT } = Sequelize; + + // 删除记录表 + await queryInterface.dropTable(RECORD_TABLE_NAME); + + // 恢复明细表作业字段 + await queryInterface.addColumn(DETAIL_TABLE_NAME, 'location_id', { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '库位ID,关联 wms_location_space.id;无库位商品为空', + }); + await queryInterface.addColumn(DETAIL_TABLE_NAME, 'location_code', { + type: STRING(50), + allowNull: true, + comment: '库位编码快照(space_code)', + }); + await queryInterface.addColumn(DETAIL_TABLE_NAME, 'check_quantity', { + type: INTEGER(12), + allowNull: true, + comment: '实盘数量;未盘点时为空', + }); + await queryInterface.addColumn(DETAIL_TABLE_NAME, 'diff_quantity', { + type: INTEGER(12), + allowNull: true, + comment: '差异数量 = 实盘数量 - 账面数量;正数盘盈,负数盘亏;未盘点时为空', + }); + await queryInterface.addColumn(DETAIL_TABLE_NAME, 'is_diff', { + type: TINYINT(1), + allowNull: false, + defaultValue: 0, + comment: '是否有差异:1=有差异,0=无差异', + }); + await queryInterface.addColumn(DETAIL_TABLE_NAME, 'status', { + type: STRING(20), + allowNull: false, + defaultValue: 'unchecked', + comment: '明细状态:unchecked=未盘,checked=已盘,confirmed=已确认', + }); + await queryInterface.addColumn(DETAIL_TABLE_NAME, 'checker_id', { + type: BIGINT(20).UNSIGNED, + allowNull: true, + comment: '盘点人账户ID', + }); + await queryInterface.addColumn(DETAIL_TABLE_NAME, 'checker_name', { + type: STRING(50), + allowNull: true, + comment: '盘点人名称快照', + }); + await queryInterface.addColumn(DETAIL_TABLE_NAME, 'checked_at', { + type: DATE, + allowNull: true, + comment: '盘点时间', + }); + }, +}; diff --git a/database/migrations/20260929130000-unique-stock-check-record-detail-location.js b/database/migrations/20260929130000-unique-stock-check-record-detail-location.js new file mode 100644 index 0000000..8dd21d7 --- /dev/null +++ b/database/migrations/20260929130000-unique-stock-check-record-detail-location.js @@ -0,0 +1,58 @@ +'use strict'; + +/** + * 盘点作业记录表覆盖式语义加固: + * 1. location_code 归一:NULL → ''(空串表示"无库位"分组,使唯一索引可约束空库位场景)。 + * 2. 合并历史重复记录:同一 (detail_id, location_code) 组保留 id 最大(最新)的一条,其余删除。 + * 3. location_code 改为 NOT NULL DEFAULT ''。 + * 4. 新增唯一索引 uk_detail_location(detail_id, location_code),从数据库层面保证 + * report 覆盖式上报(同明细+同库位更新而非新增)在并发下不产生重复记录。 + */ + +const TABLE_NAME = 'wms_stock_check_record'; + +module.exports = { + up: async (queryInterface, Sequelize) => { + const { STRING } = Sequelize; + + // 1) NULL → '' + await queryInterface.sequelize.query( + `UPDATE ${TABLE_NAME} SET location_code = '' WHERE location_code IS NULL` + ); + + // 2) 合并重复:每组保留 id 最大的记录 + await queryInterface.sequelize.query(` + DELETE r1 FROM ${TABLE_NAME} r1 + JOIN ${TABLE_NAME} r2 + ON r1.detail_id = r2.detail_id + AND r1.location_code = r2.location_code + AND r1.id < r2.id + `); + + // 3) 列定义调整 + await queryInterface.changeColumn(TABLE_NAME, 'location_code', { + type: STRING(50), + allowNull: false, + defaultValue: '', + comment: '库位编码(盘点上报的库位,空串表示无库位分组)', + }); + + // 4) 唯一索引(覆盖式语义的数据库层保证) + await queryInterface.addIndex(TABLE_NAME, [ 'detail_id', 'location_code' ], { + unique: true, + name: 'uk_detail_location', + }); + }, + + down: async (queryInterface, Sequelize) => { + const { STRING } = Sequelize; + + await queryInterface.removeIndex(TABLE_NAME, 'uk_detail_location'); + await queryInterface.changeColumn(TABLE_NAME, 'location_code', { + type: STRING(50), + allowNull: true, + defaultValue: null, + comment: '库位编码(盘点上报的库位)', + }); + }, +};