diff --git a/app/dict/businessDict.js b/app/dict/businessDict.js index 4a7008e..eac415b 100644 --- a/app/dict/businessDict.js +++ b/app/dict/businessDict.js @@ -99,6 +99,7 @@ module.exports = { // 库存管理 STORAGE_TRANSFER_LOCATION: '库位调拨', STORAGE_TRANSFER_BY_PRODUCT: '商品调拨', + STORAGE_UPDATE_EXPIRY: '维护库存效期', STOCK_IN: '商品入库', STOCK_OUT: '商品出库', STOCK_ADJUST: '库存调整', diff --git a/app/service/systemMethods/storage/inventory.js b/app/service/systemMethods/storage/inventory.js index 175201c..e3711d0 100644 --- a/app/service/systemMethods/storage/inventory.js +++ b/app/service/systemMethods/storage/inventory.js @@ -48,6 +48,25 @@ class InventoryMethodService extends MainService { return this.success('ok', result); } + /** + * 维护库存效期:传入库存记录ID与生产日期/到期日期,更新当前库存批次的两个日期字段。 + * + * 仓库上下文来自当前登录用户(ctx.user.store_id),跨仓库的 storage_id 按不存在处理。 + * production_date / expiry_date 至少传一个,未传字段保持库内原值,传 null 或空串表示清空; + * 合并后生产日期不能晚于到期日期。 + * + * @param {Object} data 请求体 + * @param {number} data.storage_id 库存记录ID(wms_storage.id,必填) + * @param {string|null} [data.production_date] 生产日期(YYYY-MM-DD,null/空串清空) + * @param {string|null} [data.expiry_date] 到期日期(YYYY-MM-DD,null/空串清空) + * @return {Promise} 统一 success 包装(内层为 code/message/data 结构) + */ + async updateExpiry(data = {}) { + const { service } = this; + const result = await service.systems.storage.inventory.updateExpiry(data); + return this.success('ok', result); + } + /** * 提取 stock_query 虚拟筛选条件(与订单查询一致)。 * 将其从 where 中移除并返回清洗后的 where 与 stock_query 关键字。 diff --git a/app/service/systems/storage/inventory.js b/app/service/systems/storage/inventory.js index 0d01804..c81b000 100644 --- a/app/service/systems/storage/inventory.js +++ b/app/service/systems/storage/inventory.js @@ -244,6 +244,65 @@ async function enrichInventoryStockAttachments(ctx, list = []) { } } +/** + * 解析并规范化库存效期维护入参中的日期值(统一输出 'YYYY-MM-DD')。 + * + * 规则: + * - `undefined`:未传该字段(不更新,返回 provided=false); + * - `null` / 空串:清空该字段(provided=true 且 value=null); + * - `'YYYY-MM-DD'` / `'YYYY/MM/DD'` / `'YYYY-MM-DD HH:mm:ss'` / ISO 字符串 / Date: + * 仅取日期部分并校验为真实存在的日期,规范化为 'YYYY-MM-DD'; + * - 其它:视为非法(invalid=true),由调用方返回参数错误。 + * + * @param {unknown} value 待解析的日期值 + * @return {{provided: boolean, value: (string|null), invalid: boolean}} 解析结果 + */ +function parseStorageDateInput(value) { + if (value === undefined) { + return { provided: false, value: null, invalid: false }; + } + + if (value === null || (typeof value === 'string' && value.trim() === '')) { + return { provided: true, value: null, invalid: false }; + } + + let year; + let month; + let day; + + if (value instanceof Date) { + if (Number.isNaN(value.getTime())) { + return { provided: true, value: null, invalid: true }; + } + year = value.getFullYear(); + month = value.getMonth() + 1; + day = value.getDate(); + } else { + const matched = /^(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})([T\s].*)?$/.exec(String(value).trim()); + if (!matched) { + return { provided: true, value: null, invalid: true }; + } + year = Number(matched[1]); + month = Number(matched[2]); + day = Number(matched[3]); + } + + const parsed = new Date(year, month - 1, day); + const isValidDate = parsed.getFullYear() === year + && parsed.getMonth() === month - 1 + && parsed.getDate() === day; + + if (!isValidDate || year < 1900 || year > 2999) { + return { provided: true, value: null, invalid: true }; + } + + return { + provided: true, + value: `${year}-${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`, + invalid: false, + }; +} + class InventoryService extends Service { /** @@ -1158,6 +1217,195 @@ class InventoryService extends Service { } } + /** + * 维护当前库存的生产日期与到期日期(wms_storage.production_date / expiry_date)。 + * + * 口径说明: + * 1) 按库存记录维度维护(单条 storage_id),仓库上下文来自当前登录用户(ctx.user.store_id), + * 跨仓库的 storage_id 一律按「不存在」处理; + * 2) 两个日期字段至少传一个;未传的字段保持库内原值;传 null 或空串表示清空该字段; + * 3) 日期支持 'YYYY-MM-DD' / 'YYYY/MM/DD' / 'YYYY-MM-DD HH:mm:ss' / ISO 字符串, + * 内部统一按 'YYYY-MM-DD' 落库; + * 4) 校验合并后的生产日期不得晚于到期日期(未传字段取库内现值参与比较); + * 5) 更新前后完全一致时直接返回 changed=false,不写库、不记日志。 + * + * @param {Object} data 请求体 + * @param {number} data.storage_id 库存记录ID(wms_storage.id,必填) + * @param {string|Date|null} [data.production_date] 生产日期(传 null/空串表示清空) + * @param {string|Date|null} [data.expiry_date] 到期日期(传 null/空串表示清空) + * @return {Promise<{code: number, message: string, data: (Object|null)}>} 统一 code/message/data 结构 + */ + async updateExpiry(data = {}) { + const { ctx } = this; + const requestData = data && typeof data === 'object' ? data : {}; + + // ────────── 1. 参数校验 ────────── + const storageId = Number(requestData.storage_id || 0); + if (!Number.isInteger(storageId) || storageId <= 0) { + return { code: 400, message: 'storage_id 必填且必须为正整数', data: null }; + } + + const productionDateInput = parseStorageDateInput(requestData.production_date); + const expiryDateInput = parseStorageDateInput(requestData.expiry_date); + + if (productionDateInput.invalid) { + return { code: 400, message: 'production_date 格式非法,须为 YYYY-MM-DD', data: null }; + } + + if (expiryDateInput.invalid) { + return { code: 400, message: 'expiry_date 格式非法,须为 YYYY-MM-DD', data: null }; + } + + if (!productionDateInput.provided && !expiryDateInput.provided) { + return { code: 400, message: 'production_date 与 expiry_date 至少传入一个', data: null }; + } + + const warehouseId = Number(ctx.user && (ctx.user.store_id ?? ctx.user.warehouse_id)) || 0; + if (warehouseId <= 0) { + return { code: 400, message: '无法获取当前仓库信息', data: null }; + } + + // ────────── 2. 事务内加锁维护 ────────── + const transaction = await ctx.model.transaction(); + + try { + const storageRecord = await ctx.model.Storage.findOne({ + where: { + id: storageId, + warehouse_id: warehouseId, + is_enabled: 1, + delete_at: null, + }, + lock: transaction.LOCK.UPDATE, + transaction, + }); + + if (!storageRecord) { + await transaction.rollback(); + return { code: 404, message: `库存记录不存在或无权访问: storage_id=${storageId}`, data: null }; + } + + const beforeProductionDate = parseStorageDateInput(storageRecord.production_date).value; + const beforeExpiryDate = parseStorageDateInput(storageRecord.expiry_date).value; + + const nextProductionDate = productionDateInput.provided + ? productionDateInput.value + : beforeProductionDate; + const nextExpiryDate = expiryDateInput.provided + ? expiryDateInput.value + : beforeExpiryDate; + + // 合并后校验:生产日期不能晚于到期日期 + if (nextProductionDate && nextExpiryDate && nextProductionDate > nextExpiryDate) { + await transaction.rollback(); + return { + code: 400, + message: `生产日期(${nextProductionDate})不能晚于到期日期(${nextExpiryDate})`, + data: null, + }; + } + + const baseData = { + storage_id: storageId, + warehouse_id: warehouseId, + store_id: storageRecord.store_id, + space_id: storageRecord.space_id, + stock_id: storageRecord.stock_id, + batch_no: storageRecord.batch_no, + }; + + if (nextProductionDate === beforeProductionDate && nextExpiryDate === beforeExpiryDate) { + await transaction.rollback(); + return { + code: 200, + message: '生产日期与到期日期均无变化,未做修改', + data: { + ...baseData, + production_date: beforeProductionDate, + expiry_date: beforeExpiryDate, + changed: false, + }, + }; + } + + await ctx.model.Storage.update({ + production_date: nextProductionDate, + expiry_date: nextExpiryDate, + updated_at: new Date(), + }, { + where: { id: storageId }, + transaction, + }); + + const changeSummary = []; + if (nextProductionDate !== beforeProductionDate) { + changeSummary.push(`生产日期 ${beforeProductionDate || '空'} → ${nextProductionDate || '空'}`); + } + if (nextExpiryDate !== beforeExpiryDate) { + changeSummary.push(`到期日期 ${beforeExpiryDate || '空'} → ${nextExpiryDate || '空'}`); + } + + // ────────── 3. 记录操作日志(失败仅告警,不影响主流程) ────────── + try { + await ctx.service.systems.operationLog.createOperationLog({ + businessType: 'storage', + businessId: storageId, + operationCode: 'STORAGE_UPDATE_EXPIRY', + operator: { + id: ctx.user?.employees_id || ctx.user?.id, + name: ctx.user?.employees_name || '', + }, + extras: { + warehouseId, + message: changeSummary.join(';'), + }, + beforeChanges: { + ...baseData, + production_date: beforeProductionDate, + expiry_date: beforeExpiryDate, + }, + }); + } catch (logErr) { + ctx.logger.warn('[inventory.updateExpiry] 写入操作日志失败,不影响业务', logErr); + } + + await transaction.commit(); + + ctx.logger.info('[inventory.updateExpiry] 库存效期维护完成', { + warehouse_id: warehouseId, + storage_id: storageId, + production_date: nextProductionDate, + expiry_date: nextExpiryDate, + }); + + return { + code: 200, + message: '更新成功', + data: { + ...baseData, + production_date: nextProductionDate, + expiry_date: nextExpiryDate, + before_production_date: beforeProductionDate, + before_expiry_date: beforeExpiryDate, + changed: true, + }, + }; + } catch (error) { + await transaction.rollback(); + ctx.logger.error('[inventory.updateExpiry] 库存效期维护异常', { + storage_id: storageId, + error: error.message, + stack: error.stack, + }); + + if (error.name === 'SequelizeDatabaseError' && error.message.includes('Lock wait timeout')) { + return { code: 409, message: '库存记录被锁定,请稍后重试', data: null }; + } + + throw error; + } + } + /** * 根据商品快捷搜索关键字解析匹配的 stock_id 列表(仓库维度)。 * 支持按商品编码(item_code)、商品名称(item_name)、货物编码(goods_code)、