WMS_MAIN/app/schedule/notice_stock_remaining.js
2026-04-17 19:21:57 +08:00

734 lines
24 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const CACHE_KEY_PREFIX = 'notice_stock_remaining_notified';
const LEGACY_CACHE_KEY = 'notice_stock_remaining_notified_list';
const CACHE_TTL_SECONDS = 24 * 60 * 60;
const DAY_MS = 24 * 60 * 60 * 1000;
const NOTICE_EVENT = 'storage_transfer_completed';
/**
* 生成本地日期键,格式为 `YYYYMMDD`。
* @param {Date} [dateValue=new Date()] 日期对象
* @return {string} 日期键
*/
function buildDateKey(dateValue = new Date()) {
const year = String(dateValue.getFullYear());
const month = String(dateValue.getMonth() + 1).padStart(2, '0');
const day = String(dateValue.getDate()).padStart(2, '0');
return `${year}${month}${day}`;
}
/**
* 生成商品维度的日粒度缓存键。
* @param {number} stockId 商品ID
* @param {Date} [dateValue=new Date()] 日期对象
* @return {string} 缓存键
*/
function buildStockDayCacheKey(stockId, dateValue = new Date()) {
const normalizedStockId = toNumber(stockId, 0);
if (normalizedStockId <= 0) {
return '';
}
return `${CACHE_KEY_PREFIX}:stock:${normalizedStockId}:${buildDateKey(dateValue)}`;
}
/**
* 从记录对象中安全读取字段,兼容下划线和驼峰命名。
* @param {object} record 记录对象
* @param {string[]} fieldNames 候选字段名列表
* @return {*} 命中的字段值
*/
function readRecordValue(record, fieldNames) {
if (!record || !Array.isArray(fieldNames)) {
return undefined;
}
for (const fieldName of fieldNames) {
if (!fieldName) {
continue;
}
if (Object.prototype.hasOwnProperty.call(record, fieldName)) {
return record[fieldName];
}
if (record.dataValues && Object.prototype.hasOwnProperty.call(record.dataValues, fieldName)) {
return record.dataValues[fieldName];
}
if (typeof record.getDataValue === 'function') {
try {
const dataValue = record.getDataValue(fieldName);
if (dataValue !== undefined) {
return dataValue;
}
} catch (error) {
// 忽略单个字段读取失败,继续尝试其他候选字段。
}
}
if (typeof record.get === 'function') {
try {
const getterValue = record.get(fieldName);
if (getterValue !== undefined) {
return getterValue;
}
} catch (error) {
// 忽略单个字段读取失败,继续尝试其他候选字段。
}
}
}
return undefined;
}
/**
* 将数值安全转换为数字。
* @param {*} value 原始值
* @param {number} [fallback=0] 转换失败时的兜底值
* @return {number} 数值结果
*/
function toNumber(value, fallback = 0) {
const numberValue = Number(value);
return Number.isFinite(numberValue) ? numberValue : fallback;
}
/**
* 归一化历史全局缓存中的已通知列表。
*
* 注意:该方法仅用于兼容旧格式的观测或迁移,不再参与新去重逻辑,
* 避免旧的全局列表继续抑制当天的通知。
*
* @param {*} rawValue 缓存原始值
* @return {string[]} 标准化后的通知键列表
*/
function normalizeNotifiedList(rawValue) {
if (!rawValue) {
return [];
}
let parsedValue = rawValue;
if (typeof rawValue === 'string') {
try {
parsedValue = JSON.parse(rawValue);
} catch (error) {
return [];
}
}
const list = Array.isArray(parsedValue)
? parsedValue
: (typeof parsedValue === 'object' && parsedValue !== null
? Object.values(parsedValue)
: []);
return list.map(item => {
if (item && typeof item === 'object') {
const stockId = readRecordValue(item, [ 'stock_id', 'stockId' ]);
if (stockId !== undefined && stockId !== null && String(stockId).trim() !== '') {
return `stock:${String(stockId)}`;
}
const itemId = readRecordValue(item, [ 'id', 'storage_id', 'storageId' ]);
if (itemId !== undefined && itemId !== null && String(itemId).trim() !== '') {
return `storage:${String(itemId)}`;
}
}
const normalizedValue = String(item || '').trim();
if (!normalizedValue) {
return '';
}
if (normalizedValue.startsWith('storage:')) {
return normalizedValue;
}
if (/^\d+$/.test(normalizedValue)) {
return `storage:${normalizedValue}`;
}
return normalizedValue;
}).filter(Boolean);
}
/**
* 生成库存记录对应的商品级通知去重键。
* @param {object} storageRecord 库存记录
* @return {string} 去重键
*/
function buildStockNotifyKey(storageRecord) {
const stockId = toNumber(readRecordValue(storageRecord, [ 'stock_id', 'stockId' ]), 0);
return stockId > 0 ? `stock:${stockId}` : '';
}
/**
* 按商品 ID 对库存记录进行分组。
* @param {object[]} storageRows 库存记录列表
* @return {Map<number, object[]>} 分组后的库存记录映射
*/
function groupStorageRowsByStockId(storageRows) {
const groupedStorageRows = new Map();
if (!Array.isArray(storageRows)) {
return groupedStorageRows;
}
for (const storageRow of storageRows) {
const stockId = toNumber(readRecordValue(storageRow, [ 'stock_id', 'stockId' ]), 0);
if (stockId <= 0) {
continue;
}
const stockStorageRows = groupedStorageRows.get(stockId) || [];
stockStorageRows.push(storageRow);
groupedStorageRows.set(stockId, stockStorageRows);
}
return groupedStorageRows;
}
/**
* 格式化日期字符串,优先使用应用内格式化器。
* @param {object} ctx Egg 上下文
* @param {*} value 原始日期值
* @return {string} 格式化后的日期字符串
*/
function formatDate(ctx, value) {
if (!value) {
return '';
}
const dateValue = value instanceof Date ? value : new Date(value);
if (Number.isNaN(dateValue.getTime())) {
return '';
}
if (ctx && ctx.app && typeof ctx.app.formatDate === 'function') {
return ctx.app.formatDate(dateValue);
}
return dateValue.toISOString();
}
/**
* 生成库存效期预警通知内容。
* @param {object} params 参数对象
* @param {object} params.ctx Egg 上下文
* @param {object} params.storageRecord 库存记录
* @param {object} params.stockRecord 商品主数据
* @param {number} params.remainingDays 剩余天数
* @param {number} params.thresholdDays 预警阈值天数
* @return {string} 通知正文
*/
function buildNoticeContent({ ctx, storageRecord, stockRecord, remainingDays, thresholdDays }) {
const storageId = toNumber(readRecordValue(storageRecord, [ 'id', 'storage_id', 'storageId' ]), 0);
const stockId = toNumber(readRecordValue(storageRecord, [ 'stock_id', 'stockId' ]), 0);
const itemCode = String(readRecordValue(stockRecord, [ 'item_code', 'itemCode' ]) || '').trim() || String(stockId || storageId);
const itemName = String(readRecordValue(stockRecord, [ 'item_name', 'itemName' ]) || '').trim() || '未命名商品';
const batchNo = String(readRecordValue(storageRecord, [ 'batch_no', 'batchNo' ]) || '').trim() || '无';
const warehouseId = toNumber(readRecordValue(storageRecord, [ 'warehouse_id', 'warehouseId' ]), 0);
const storeId = toNumber(readRecordValue(storageRecord, [ 'store_id', 'storeId' ]), 0);
const expiryDate = formatDate(ctx, readRecordValue(storageRecord, [ 'expiry_date', 'expiryDate' ]));
const inboundTime = formatDate(ctx, readRecordValue(storageRecord, [ 'inbound_time', 'inboundTime' ]));
const quantity = toNumber(readRecordValue(storageRecord, [ 'quantity' ]), 0);
const availableQuantity = toNumber(readRecordValue(storageRecord, [ 'available_quantity', 'availableQuantity' ]), quantity);
const spaceRecord = readRecordValue(storageRecord, [ 'space' ]) || storageRecord.space || {};
const spaceCode = String(readRecordValue(spaceRecord, [ 'space_code', 'spaceCode' ]) || '').trim();
const spaceName = String(readRecordValue(spaceRecord, [ 'custom_name', 'customName' ]) || '').trim();
const spaceLabel = [ spaceCode, spaceName ].filter(Boolean).join(' / ') || '无';
return [
`库存效期预警:${itemName}`,
`商品编码:${itemCode}`,
`库存ID:${storageId || '未知'}`,
`批次号:${batchNo}`,
`仓库ID:${warehouseId || '未知'}`,
`货主ID:${storeId || '未知'}`,
`库位:${spaceLabel}`,
`库存数量:${quantity}`,
`可用数量:${availableQuantity}`,
`效期日期:${expiryDate || '未知'}`,
`剩余天数:${remainingDays}`,
`预警阈值:${thresholdDays}`,
`入库时间:${inboundTime || '未知'}`,
].join('\n');
}
/**
* 解析库存效期预警通知的发送方法,优先使用 `send`,其次兼容 `index.send`。
* @param {object} ctx Egg 上下文
* @return {Function|null} 可执行的发送方法
*/
function resolveNoticeSendMethod(ctx) {
const noticeService = ctx && ctx.service && ctx.service.systems && ctx.service.systems.notice;
if (!noticeService) {
return null;
}
if (typeof noticeService.send === 'function') {
return noticeService.send.bind(noticeService);
}
if (noticeService.index && typeof noticeService.index.send === 'function') {
return noticeService.index.send.bind(noticeService.index);
}
return null;
}
/**
* 发送库存效期预警通知。
* @param {object} ctx Egg 上下文
* @param {object} payload 通知参数
* @return {Promise<object>} 通知发送结果
*/
async function sendStockRemainingNotice(ctx, payload) {
const sendMethod = resolveNoticeSendMethod(ctx);
if (typeof sendMethod !== 'function') {
throw new Error('通知服务不可用');
}
return await sendMethod(payload);
}
module.exports = {
schedule: {
interval: '30s',
type: 'worker',
immediate: false,
disable: false,
},
/**
* 执行库存效期预警扫描。
* @param {object} ctx Egg 上下文
* @return {Promise<void>}
*/
async task(ctx) {
const scheduleName = 'notice_stock_remaining';
let stockCount = 0;
let storageCount = 0;
let sentCount = 0;
let skippedCount = 0;
const today = new Date();
ctx.logger.info(`[${scheduleName}] 本轮任务启动`, {
scheduleName,
cacheKeyPrefix: CACHE_KEY_PREFIX,
running: Boolean(ctx.app._noticeStockRemainingRunning),
});
if (ctx.app._noticeStockRemainingRunning) {
ctx.logger.info(`[${scheduleName}] 本轮任务跳过,上一轮尚未结束`, {
scheduleName,
cacheKeyPrefix: CACHE_KEY_PREFIX,
running: Boolean(ctx.app._noticeStockRemainingRunning),
});
return;
}
ctx.app._noticeStockRemainingRunning = true;
try {
const legacyCachedValue = typeof ctx.app.getCacheAsync === 'function'
? await ctx.app.getCacheAsync(LEGACY_CACHE_KEY)
: null;
const legacyCacheHit = legacyCachedValue !== null && legacyCachedValue !== undefined;
const legacyNotifiedList = normalizeNotifiedList(legacyCachedValue);
ctx.logger.info('[notice_stock_remaining] 已检查历史通知缓存', {
legacyCacheKey: LEGACY_CACHE_KEY,
cacheHit: legacyCacheHit,
cachedValueType: Array.isArray(legacyCachedValue) ? 'array' : typeof legacyCachedValue,
rawCacheCount: Array.isArray(legacyCachedValue) ? legacyCachedValue.length : 0,
normalizedCount: legacyNotifiedList.length,
cacheKeyMode: 'stock-day',
});
if (legacyCacheHit) {
ctx.logger.warn('[notice_stock_remaining] 检测到旧的全局去重缓存,当前版本不再使用该缓存参与拦截', {
legacyCacheKey: LEGACY_CACHE_KEY,
normalizedCount: legacyNotifiedList.length,
});
}
ctx.logger.debug('[notice_stock_remaining] 日粒度去重已启用', {
cacheKeyPrefix: CACHE_KEY_PREFIX,
dateKey: buildDateKey(today),
});
const stockWhere = {
is_shelf_life_mgmt: 'Y',
remaining_threshold_days: {
[ctx.app.Sequelize.Op.gt]: 0,
},
};
const stockRows = await ctx.model.StockWarehouse.findAll({
attributes: [
'id',
'item_code',
'item_name',
'store_id',
'warehouse_id',
'remaining_threshold_days',
],
where: stockWhere,
order: [[ 'remaining_threshold_days', 'ASC' ], [ 'id', 'ASC' ]],
raw: true,
});
stockCount = Array.isArray(stockRows) ? stockRows.length : 0;
ctx.logger.info('[notice_stock_remaining] 完成商品候选查询', {
stockCount,
});
if (Array.isArray(stockRows)) {
for (const stockRow of stockRows) {
ctx.logger.debug('[notice_stock_remaining] 商品候选明细', {
id: toNumber(readRecordValue(stockRow, [ 'id' ]), 0),
item_code: String(readRecordValue(stockRow, [ 'item_code', 'itemCode' ]) || '').trim(),
remaining_threshold_days: Math.max(0, Math.floor(toNumber(readRecordValue(stockRow, [ 'remaining_threshold_days', 'remainingThresholdDays' ]), 0))),
});
}
}
if (!Array.isArray(stockRows) || stockRows.length === 0) {
ctx.logger.info('[notice_stock_remaining] 未找到开启效期管理且阈值大于 0 的商品');
return;
}
const stockMap = new Map();
let maxThresholdDays = 0;
for (const stockRow of stockRows) {
const stockId = toNumber(readRecordValue(stockRow, [ 'id' ]), 0);
const thresholdDays = Math.max(0, Math.floor(toNumber(readRecordValue(stockRow, [ 'remaining_threshold_days', 'remainingThresholdDays' ]), 0)));
if (stockId <= 0 || thresholdDays <= 0) {
continue;
}
stockMap.set(stockId, {
id: stockId,
item_code: String(readRecordValue(stockRow, [ 'item_code', 'itemCode' ]) || '').trim(),
item_name: String(readRecordValue(stockRow, [ 'item_name', 'itemName' ]) || '').trim(),
store_id: toNumber(readRecordValue(stockRow, [ 'store_id', 'storeId' ]), 0),
warehouse_id: toNumber(readRecordValue(stockRow, [ 'warehouse_id', 'warehouseId' ]), 0),
remaining_threshold_days: thresholdDays,
});
if (thresholdDays > maxThresholdDays) {
maxThresholdDays = thresholdDays;
}
}
const stockIds = Array.from(stockMap.keys());
if (stockIds.length === 0 || maxThresholdDays <= 0) {
ctx.logger.info('[notice_stock_remaining] 商品数据中没有可用的效期预警阈值', {
stockCount,
validStockCount: stockIds.length,
maxThresholdDays,
});
return;
}
const now = new Date();
const maxExpiryDate = new Date(now.getTime() + (maxThresholdDays * DAY_MS));
const storageWhere = {
stock_id: {
[ctx.app.Sequelize.Op.in]: stockIds,
},
is_enabled: 1,
delete_at: null,
quantity: {
[ctx.app.Sequelize.Op.gt]: 0,
},
expiry_date: {
[ctx.app.Sequelize.Op.ne]: null,
[ctx.app.Sequelize.Op.lte]: maxExpiryDate,
},
};
const storageRows = await ctx.model.Storage.findAll({
where: storageWhere,
include: [
{
model: ctx.model.LocationSpace,
as: 'space',
attributes: [ 'space_code', 'custom_name' ],
required: false,
},
],
order: [[ 'expiry_date', 'ASC' ], [ 'inbound_time', 'ASC' ], [ 'id', 'ASC' ]],
});
storageCount = Array.isArray(storageRows) ? storageRows.length : 0;
ctx.logger.info('[notice_stock_remaining] 完成库存候选查询', {
stockCount: stockIds.length,
storageCount,
maxThresholdDays,
});
if (Array.isArray(storageRows)) {
for (const storageRow of storageRows) {
ctx.logger.debug('[notice_stock_remaining] 库存候选明细', {
id: toNumber(readRecordValue(storageRow, [ 'id', 'storage_id', 'storageId' ]), 0),
stock_id: toNumber(readRecordValue(storageRow, [ 'stock_id', 'stockId' ]), 0),
expiry_date: formatDate(ctx, readRecordValue(storageRow, [ 'expiry_date', 'expiryDate' ])),
quantity: toNumber(readRecordValue(storageRow, [ 'quantity' ]), 0),
available_quantity: toNumber(readRecordValue(storageRow, [ 'available_quantity', 'availableQuantity' ]), toNumber(readRecordValue(storageRow, [ 'quantity' ]), 0)),
});
}
}
const groupedStorageRows = groupStorageRowsByStockId(storageRows);
const representativeStorageRows = Array.from(groupedStorageRows.values()).map(stockStorageRows => stockStorageRows[0]);
for (const storageRecord of representativeStorageRows) {
const storageId = toNumber(readRecordValue(storageRecord, [ 'id', 'storage_id', 'storageId' ]), 0);
const stockId = toNumber(readRecordValue(storageRecord, [ 'stock_id', 'stockId' ]), 0);
const notifyKey = buildStockNotifyKey(storageRecord);
const stockDayCacheKey = buildStockDayCacheKey(stockId, today);
const stockRecord = stockMap.get(stockId);
const thresholdDays = stockRecord ? toNumber(readRecordValue(stockRecord, [ 'remaining_threshold_days', 'remainingThresholdDays' ]), 0) : 0;
if (!notifyKey) {
skippedCount += 1;
ctx.logger.debug('[notice_stock_remaining] 跳过代表库存', {
storageId,
stockId,
notifyKey,
reason: 'notifyKey 为空',
});
continue;
}
if (!stockDayCacheKey) {
skippedCount += 1;
ctx.logger.debug('[notice_stock_remaining] 跳过代表库存', {
storageId,
stockId,
notifyKey,
reason: '日粒度缓存键为空',
});
continue;
}
if (!stockRecord) {
skippedCount += 1;
ctx.logger.debug('[notice_stock_remaining] 跳过代表库存', {
storageId,
stockId,
notifyKey,
reason: '未找到对应商品记录',
});
continue;
}
if (typeof ctx.app.getCacheAsync === 'function') {
const cachedNotifiedValue = await ctx.app.getCacheAsync(stockDayCacheKey);
if (cachedNotifiedValue !== null && cachedNotifiedValue !== undefined) {
skippedCount += 1;
ctx.logger.debug('[notice_stock_remaining] 跳过代表库存', {
storageId,
stockId,
notifyKey,
stockDayCacheKey,
reason: '当日已通知过该商品',
});
continue;
}
}
if (thresholdDays <= 0) {
skippedCount += 1;
ctx.logger.debug('[notice_stock_remaining] 跳过代表库存', {
storageId,
stockId,
notifyKey,
thresholdDays,
reason: '商品阈值小于等于 0',
});
continue;
}
const expiryDateValue = readRecordValue(storageRecord, [ 'expiry_date', 'expiryDate' ]);
if (!expiryDateValue) {
skippedCount += 1;
ctx.logger.debug('[notice_stock_remaining] 跳过代表库存', {
storageId,
stockId,
notifyKey,
thresholdDays,
reason: '缺少效期日期',
});
continue;
}
const expiryDate = expiryDateValue instanceof Date ? expiryDateValue : new Date(expiryDateValue);
if (Number.isNaN(expiryDate.getTime())) {
ctx.logger.warn('[notice_stock_remaining] 跳过非法效期日期', {
storageId,
stockId,
expiryDate: String(expiryDateValue),
});
skippedCount += 1;
ctx.logger.debug('[notice_stock_remaining] 跳过代表库存', {
storageId,
stockId,
notifyKey,
thresholdDays,
reason: '效期日期非法',
});
continue;
}
const remainingDays = Math.max(0, Math.ceil((expiryDate.getTime() - now.getTime()) / DAY_MS));
if (remainingDays > thresholdDays) {
skippedCount += 1;
ctx.logger.debug('[notice_stock_remaining] 跳过代表库存', {
storageId,
stockId,
notifyKey,
thresholdDays,
remainingDays,
reason: '剩余天数大于阈值',
});
continue;
}
const warehouseId = toNumber(readRecordValue(storageRecord, [ 'warehouse_id', 'warehouseId' ]) || stockRecord.warehouse_id, 0);
const storeId = toNumber(readRecordValue(storageRecord, [ 'store_id', 'storeId' ]) || stockRecord.store_id, 0);
const title = `库存效期预警:${stockRecord.item_name || '未命名商品'}`;
const content = buildNoticeContent({
ctx,
storageRecord,
stockRecord,
remainingDays,
thresholdDays,
});
ctx.logger.info('[notice_stock_remaining] 进入发送分支', {
storageId,
stockId,
notifyKey,
remainingDays,
thresholdDays,
warehouseId,
storeId,
});
try {
const noticeResult = await sendStockRemainingNotice(ctx, {
warehouseId,
storeId,
subject: {
id: warehouseId,
type: 'warehouse',
name: `仓库${warehouseId || '未知'}`,
},
businessName: 'storage',
event: NOTICE_EVENT,
title,
content,
businessId: stockId,
messageType: 'text',
metadata: {
cacheKey: stockDayCacheKey,
storageId,
stockId,
notifyKey,
businessId: stockId,
thresholdDays,
remainingDays,
warehouseId,
storeId,
stock: {
id: stockRecord.id,
item_code: stockRecord.item_code,
item_name: stockRecord.item_name,
},
storage: {
id: storageId,
batch_no: readRecordValue(storageRecord, [ 'batch_no', 'batchNo' ]) || '',
expiry_date: expiryDate.toISOString(),
},
},
});
if (noticeResult && noticeResult.success === false) {
ctx.logger.warn('[notice_stock_remaining] 通知发送失败,保留待重试状态', {
storageId,
stockId,
notifyKey,
stockDayCacheKey,
remainingDays,
thresholdDays,
result: noticeResult,
});
continue;
}
if (typeof ctx.app.setCacheAsync === 'function') {
await ctx.app.setCacheAsync(stockDayCacheKey, {
notifiedAt: today.toISOString(),
stockId,
notifyKey,
}, CACHE_TTL_SECONDS);
}
sentCount += 1;
ctx.logger.info('[notice_stock_remaining] 库存效期预警已发送', {
storageId,
stockId,
notifyKey,
stockDayCacheKey,
remainingDays,
thresholdDays,
result: noticeResult,
});
} catch (noticeError) {
ctx.logger.error('[notice_stock_remaining] 库存效期预警发送异常', {
storageId,
stockId,
notifyKey,
stockDayCacheKey,
remainingDays,
thresholdDays,
error: noticeError.message,
stack: noticeError.stack,
});
}
}
ctx.logger.info('[notice_stock_remaining] 本轮通知缓存按商品日粒度独立写入,无需整体回写', {
cacheKeyPrefix: CACHE_KEY_PREFIX,
sentCount,
skippedCount,
ttlSeconds: CACHE_TTL_SECONDS,
});
} catch (error) {
ctx.logger.error('[notice_stock_remaining] 执行失败', {
error: error.message,
stack: error.stack,
});
} finally {
ctx.app._noticeStockRemainingRunning = false;
ctx.logger.info('[notice_stock_remaining] 本轮任务结束', {
scheduleName,
cacheKeyPrefix: CACHE_KEY_PREFIX,
stockCount,
storageCount,
sentCount,
skippedCount,
running: Boolean(ctx.app._noticeStockRemainingRunning),
});
}
},
};