'use strict'; const Service = require('egg').Service; /** 静态盘点:仓库未配置 stock_static_hours 时使用的默认阈值小时数 */ const DEFAULT_STATIC_HOURS = 168; /** * 盘点定式定义集合(代码注册,不建表)。 * 字段说明: * - id:定式唯一标识(method 层 pattern_id 入参); * - name:定式名称(创建任务时作为默认标题); * - description:定式描述(含对象收集口径); * - type:对应盘点任务 type(location=按库位 / goods=按商品); * - collect:对象收集函数名(本服务内实现,入参 { warehouseId }, * 返回 { locations: [{location_id, location_code}] } 或 { stock_ids: [...] })。 */ const STOCK_CHECK_PATTERNS = Object.freeze([ Object.freeze({ id: 'empty_location', name: '空库位盘点', description: '自动收集当前仓库所有「账面为空」的启用库位:wms_location_space(warehouse_id 匹配且 is_enabled=1)中,在 wms_storage 不存在任何 quantity>0 库存记录的库位(LEFT JOIN 判空)', type: 'location', collect: 'collectEmptyLocation', }), Object.freeze({ id: 'mis_shipment', name: '错发盘点', description: '自动收集所有登记过错发工单(wms_after_sale.type=order 且 sub_type=mis_shipment)关联订单的商品:工单状态口径为「凡登记过即纳入,排除已关闭(closed)/已取消(cancelled)工单」,取工单 order_id 集合查询订单明细分表(OrderItemsFactory.getCurrentModel)后按 stock_id 去重', type: 'goods', collect: 'collectMisShipment', }), Object.freeze({ id: 'expiring', name: '临期盘点', description: '自动收集所有开启保质期管理(wms_stock_warehouse.is_shelf_life_mgmt=Y)且存在临期库存的商品:在 wms_storage 存在 quantity>0 且 expiry_date 非空、expiry_date <= 当前时间+该商品 remaining_threshold_days 天的库存记录(商品维度去重;remaining_threshold_days 为 0 时按已到期 expiry_date <= 当前时间处理)', type: 'goods', collect: 'collectExpiring', }), Object.freeze({ id: 'static', name: '静态盘点', description: '自动收集所有停收停发超过时间的商品:商品最后一次 INBOUND/OUTBOUND 流水(wms_stock_transaction)距今超过仓库配置 stock_static_hours 小时(默认 168 小时),无流水的商品按 wms_stock_warehouse.create_at 计算;已存在 wms_stock_static_check_task 记录的 stock_id(已进入静态已盘点商品)自动排除,创建任务成功后把命中的 stock_id 写入该表', type: 'goods', collect: 'collectStatic', }), Object.freeze({ id: 'warning', name: '预警盘点', description: '自动收集所有到达库存预警线的商品:wms_stock_warehouse.quantity < 仓库配置 stock_warning_quantity(商品维度去重);要求仓库配置 stock_warning_enabled=true 才可执行,未开启时返回 400「未开启库存预警」', type: 'goods', collect: 'collectWarning', }), ]); /** * 盘点定式注册服务(供 systems.stockCheck 转调)。 * 职责:维护定式清单、提供定式对象收集函数,不直接落库盘点主表。 */ class StockCheckPatternsService extends Service { /** * 创建带业务错误码的异常对象。 * * @param {string} message 错误信息。 * @param {number} [code=400] 业务错误码。 * @return {Error} 包含 code 的异常对象。 */ createBusinessError(message, code = 400) { const error = new Error(`${message}`); error.code = code; return error; } /** * 判断是否为普通对象(非数组、非 null)。 * * @param {*} value 待判断值。 * @return {boolean} 是普通对象返回 true。 */ _isPlainObject(value) { return value !== null && typeof value === 'object' && !Array.isArray(value); } /** * 归一化 subject_config(兼容 JSON 字符串与对象)。 * * @param {*} raw 原始配置值。 * @return {Object} 配置对象,非法时返回空对象。 */ _normalizeSubjectConfig(raw) { if (this._isPlainObject(raw)) { return raw; } if (typeof raw === 'string') { const trimmed = raw.trim(); if (!trimmed) { return {}; } try { const parsed = JSON.parse(trimmed); return this._isPlainObject(parsed) ? parsed : {}; } catch { return {}; } } return {}; } /** * 判断布尔标志是否开启(兼容 true / 1 / '1' / 'true')。 * * @param {*} value 标志值。 * @return {boolean} 开启返回 true。 */ _isTruthyFlag(value) { return value === true || value === 1 || value === '1' || String(value || '').trim().toLowerCase() === 'true'; } /** * 读取当前仓库设置(wms_store.subject_config)。 * * @param {number} warehouseId 仓库ID。 * @return {Promise} subject_config 对象,读取失败返回空对象。 */ async _getWarehouseSubjectConfig(warehouseId) { const { ctx } = this; try { const storeModel = ctx.model && ctx.model.Store; if (!storeModel || typeof storeModel.findByPk !== 'function') { return {}; } const store = await storeModel.findByPk(Number(warehouseId), { attributes: [ 'id', 'subject_config' ], raw: true, }); return this._normalizeSubjectConfig(store && store.subject_config); } catch (error) { ctx.logger && ctx.logger.warn && ctx.logger.warn( `[stockCheckPatterns] 读取仓库设置失败 warehouseId=${warehouseId}: ${error && error.message}` ); return {}; } } /** * 读取静态盘点阈值小时数(仓库配置 stock_static_hours,默认 168)。 * * @param {number} warehouseId 仓库ID。 * @return {Promise} 阈值小时数。 */ async _resolveStaticHours(warehouseId) { const subjectConfig = await this._getWarehouseSubjectConfig(warehouseId); const configHours = Number(subjectConfig.stock_static_hours || 0); return Number.isFinite(configHours) && configHours > 0 ? configHours : DEFAULT_STATIC_HOURS; } /** * 执行裸 SQL 查询并返回行数组。 * * @param {string} sql 查询语句(命名占位符 :name)。 * @param {Object} [replacements={}] 占位符替换值。 * @return {Promise>} 查询结果行数组。 */ async _queryRows(sql, replacements = {}) { const { ctx } = this; const rows = await ctx.model.query(sql, { replacements, type: ctx.model.QueryTypes.SELECT, }); return Array.isArray(rows) ? rows : []; } /** * 将 ID 列表归一化为去重后的正整数列表。 * * @param {Array<*>} values 原始 ID 列表。 * @return {Array} 去重后的正整数列表。 */ _normalizePositiveIntegerList(values) { const list = Array.isArray(values) ? values : []; return [ ...new Set( list .map(value => Number(value)) .filter(value => Number.isInteger(value) && value > 0) ) ]; } /** * 拉取定式清单(仅对外字段,不含内部执行函数)。 * * @return {Array} 定式数组,每项含 id/name/description/type。 */ listPatterns() { return STOCK_CHECK_PATTERNS.map(pattern => ({ id: pattern.id, name: pattern.name, description: pattern.description, type: pattern.type, })); } /** * 按定式 ID 查询定式定义。 * * @param {string|number} patternId 定式ID。 * @return {Object|null} 定式定义,不存在返回 null。 */ getPatternById(patternId) { const normalized = String(patternId || '').trim(); return STOCK_CHECK_PATTERNS.find(pattern => pattern.id === normalized) || null; } /** * 按定式 ID 收集盘点对象(goods 型返回 stock_ids,location 型返回库位列表)。 * * @param {string|number} patternId 定式ID。 * @param {Object} [context={}] 收集上下文。 * @param {number} context.warehouseId 仓库ID。 * @return {Promise} { stock_ids } 或 { locations },定式不存在返回 null。 */ async collectById(patternId, context = {}) { const pattern = this.getPatternById(patternId); if (!pattern || typeof this[pattern.collect] !== 'function') { return null; } return this[pattern.collect](context); } /** * 空库位定式:收集账面为空的启用库位。 * 口径:wms_location_space(warehouse_id 匹配、is_enabled=1、未删除、库位有效—— * 所属 zone 存在且未删除,排除无头库位)在 * wms_storage 不存在任何 quantity>0 且未删除的库存记录(LEFT JOIN 判空)。 * * @param {Object} context 收集上下文。 * @param {number} context.warehouseId 仓库ID。 * @return {Promise} { locations: [{ location_id, location_code }] }。 */ async collectEmptyLocation(context = {}) { const warehouseId = Number(context.warehouseId); const rows = await this._queryRows( ` SELECT ls.id AS location_id, ls.space_code AS location_code FROM wms_location_space ls JOIN wms_location_zone z ON z.id = ls.zone_id AND z.deleted_at IS NULL LEFT JOIN wms_storage st ON st.space_id = ls.id AND st.delete_at IS NULL AND st.quantity > 0 WHERE ls.warehouse_id = :warehouseId AND ls.is_enabled = 1 AND ls.deleted_at IS NULL AND st.id IS NULL ORDER BY ls.id ASC `, { warehouseId } ); const locations = rows .filter(row => row && row.location_id) .map(row => ({ location_id: Number(row.location_id), location_code: String(row.location_code || '').trim(), })); return { locations }; } /** * 错发定式:收集登记过错发工单的订单关联商品。 * 口径:wms_after_sale(warehouse_id 匹配、type=order、sub_type=mis_shipment、未删除) * 中排除已关闭(closed)/已取消(cancelled)工单,其余状态一律纳入; * 取 order_id 集合查询订单明细分表(OrderItemsFactory.getCurrentModel)后按 stock_id 去重。 * * @param {Object} context 收集上下文。 * @param {number} context.warehouseId 仓库ID。 * @return {Promise} { stock_ids: number[] }。 */ async collectMisShipment(context = {}) { const { ctx } = this; const { Op } = ctx.app.Sequelize; const warehouseId = Number(context.warehouseId); const afterSaleRows = await ctx.model.AfterSale.findAll({ where: { warehouse_id: warehouseId, type: 'order', sub_type: 'mis_shipment', status: { [Op.notIn]: [ 'closed', 'cancelled' ] }, deleted_at: null, }, attributes: [ 'order_id' ], raw: true, }); const orderIds = this._normalizePositiveIntegerList( (Array.isArray(afterSaleRows) ? afterSaleRows : []).map(row => row && row.order_id) ); if (orderIds.length === 0) { return { stock_ids: [] }; } const orderItemsModel = await ctx.model.OrderItemsFactory.getCurrentModel(warehouseId); const itemRows = await orderItemsModel.findAll({ where: { order_id: { [Op.in]: orderIds } }, attributes: [ 'stock_id' ], raw: true, }); const stockIds = this._normalizePositiveIntegerList( (Array.isArray(itemRows) ? itemRows : []).map(row => row && row.stock_id) ); return { stock_ids: stockIds }; } /** * 临期定式:收集开启保质期管理且存在临期库存的商品。 * 口径:wms_stock_warehouse(warehouse_id 匹配、is_valid=Y、未删除、is_shelf_life_mgmt=Y) * 关联 wms_storage(quantity>0、expiry_date 非空、未删除)按 stock_id 取最早到期日: * remaining_threshold_days>0 时最早到期日 <= 当前时间+阈值天数, * remaining_threshold_days<=0(含空)时按已到期处理(最早到期日 <= 当前时间),商品维度去重。 * * @param {Object} context 收集上下文。 * @param {number} context.warehouseId 仓库ID。 * @return {Promise} { stock_ids: number[] }。 */ async collectExpiring(context = {}) { const warehouseId = Number(context.warehouseId); const rows = await this._queryRows( ` SELECT sw.id AS stock_id FROM wms_stock_warehouse sw INNER JOIN ( SELECT stock_id, MIN(expiry_date) AS min_expiry_date FROM wms_storage WHERE warehouse_id = :warehouseId AND quantity > 0 AND expiry_date IS NOT NULL AND delete_at IS NULL GROUP BY stock_id ) st ON st.stock_id = sw.id WHERE sw.warehouse_id = :warehouseId AND sw.is_valid = 'Y' AND sw.deleted_at IS NULL AND sw.is_shelf_life_mgmt = 'Y' AND ( (COALESCE(sw.remaining_threshold_days, 0) > 0 AND st.min_expiry_date <= DATE_ADD(NOW(), INTERVAL COALESCE(sw.remaining_threshold_days, 0) DAY)) OR (COALESCE(sw.remaining_threshold_days, 0) <= 0 AND st.min_expiry_date <= NOW()) ) ORDER BY sw.id ASC `, { warehouseId } ); return { stock_ids: this._normalizePositiveIntegerList(rows.map(row => row && row.stock_id)) }; } /** * 静态定式:收集停收停发超过阈值的商品。 * 口径:商品最后一次 INBOUND/OUTBOUND 流水(wms_stock_transaction,命中 * warehouse_id+transaction_type+stock_id 索引)距今超过仓库配置 * stock_static_hours 小时(默认 168 小时),无流水的商品按 * wms_stock_warehouse.create_at 计算;排除 wms_stock_static_check_task * 已有记录(未删除)的 stock_id,商品维度去重。 * * @param {Object} context 收集上下文。 * @param {number} context.warehouseId 仓库ID。 * @return {Promise} { stock_ids: number[] }。 */ async collectStatic(context = {}) { const warehouseId = Number(context.warehouseId); const staticHours = await this._resolveStaticHours(warehouseId); const cutoff = new Date(Date.now() - staticHours * 3600 * 1000); const rows = await this._queryRows( ` SELECT sw.id AS stock_id FROM wms_stock_warehouse sw LEFT JOIN ( SELECT stock_id, MAX(last_flow_at) AS last_flow_at FROM ( SELECT stock_id, MAX(created_at) AS last_flow_at FROM wms_stock_transaction WHERE warehouse_id = :warehouseId AND transaction_type = 'INBOUND' GROUP BY stock_id UNION ALL SELECT stock_id, MAX(created_at) AS last_flow_at FROM wms_stock_transaction WHERE warehouse_id = :warehouseId AND transaction_type = 'OUTBOUND' GROUP BY stock_id ) flow_union GROUP BY stock_id ) t ON t.stock_id = sw.id WHERE sw.warehouse_id = :warehouseId AND sw.is_valid = 'Y' AND sw.deleted_at IS NULL AND COALESCE(t.last_flow_at, sw.create_at) < :cutoff AND NOT EXISTS ( SELECT 1 FROM wms_stock_static_check_task sct WHERE sct.stock_id = sw.id AND sct.deleted_at IS NULL ) ORDER BY sw.id ASC `, { warehouseId, cutoff } ); return { stock_ids: this._normalizePositiveIntegerList(rows.map(row => row && row.stock_id)) }; } /** * 预警定式:收集到达库存预警线的商品。 * 口径:仓库配置 stock_warning_enabled=true 时才可执行(未开启抛 400「未开启库存预警」), * 收集 wms_stock_warehouse(warehouse_id 匹配、is_valid=Y、未删除)中 * quantity < stock_warning_quantity 的商品,商品维度去重。 * * @param {Object} context 收集上下文。 * @param {number} context.warehouseId 仓库ID。 * @return {Promise} { stock_ids: number[] }。 * @throws {Error} 未开启库存预警时抛出业务错误(错误码 400)。 */ async collectWarning(context = {}) { const warehouseId = Number(context.warehouseId); const subjectConfig = await this._getWarehouseSubjectConfig(warehouseId); if (!this._isTruthyFlag(subjectConfig.stock_warning_enabled)) { throw this.createBusinessError('未开启库存预警'); } const threshold = Number(subjectConfig.stock_warning_quantity || 0); const rows = await this._queryRows( ` SELECT id AS stock_id FROM wms_stock_warehouse WHERE warehouse_id = :warehouseId AND is_valid = 'Y' AND deleted_at IS NULL AND quantity < :threshold ORDER BY id ASC `, { warehouseId, threshold } ); return { stock_ids: this._normalizePositiveIntegerList(rows.map(row => row && row.stock_id)) }; } } module.exports = StockCheckPatternsService;