'use strict'; const MainService = require('../main'); /** 通知事件码(需与 notice 固定订阅、notification_webhook 事件注册保持一致) */ const NOTICE_EVENT = 'receiving_pending_inbound'; /** 默认提醒时间(HH:mm) */ const DEFAULT_NOTICE_TIME = '08:30'; /** 默认超时下限(小时):创建时间距今超过该值才提醒 */ const DEFAULT_MIN_HOURS = 24; /** 默认超时上限(小时):创建时间距今超过该值不再提醒 */ const DEFAULT_MAX_HOURS = 48; /** 提醒时间命中宽限(分钟):覆盖 5 分钟调度间隔的抖动,配合当日锁保证一天只提醒一次 */ const DEFAULT_GRACE_MINUTES = 10; /** 单条通知最多列出的收货单行数(超出只提示剩余数量,避免消息过长) */ const MAX_NOTICE_ITEMS = 20; /** 当日执行锁 key 前缀 */ const DAILY_LOCK_KEY_PREFIX = 'receiving_pending_notice:lock:'; /** 当日执行锁 TTL(秒) */ const DAILY_LOCK_TTL_SECONDS = 24 * 60 * 60; /** 单小时毫秒数 */ const HOUR_MS = 60 * 60 * 1000; /** 通知短语最大长度(与仓库设置校验保持一致) */ const NOTICE_TEMPLATE_MAX_LENGTH = 500; /** 默认通知短语(仓库/客服群):短语 + 换行 + 明细(一行一条) */ const DEFAULT_NOTICE_TEMPLATE = '【收货未入库提醒】以下 {count} 个收货单已超过 {min_hours} 小时且不足 {max_hours} 小时,仍未完成入库,请及时跟进:'; /** 默认通知短语(货主群) */ const DEFAULT_STORE_NOTICE_TEMPLATE = '【收货未入库提醒】以下 {count} 个收货单已超过 {min_hours} 小时仍未完成入库,请尽快完成收货入库:'; const TIME_PATTERN = /^([01]\d|2[0-3]):[0-5]\d$/; const TEMPLATE_VARIABLE_PATTERN = /\{([a-zA-Z_][a-zA-Z0-9_]*)\}/g; const RECEIVING_STATUS_LABEL = Object.freeze({ receiving: '收货中', completed: '收货完成', cancelled: '已作废', }); const STORAGE_STATUS_LABEL = Object.freeze({ none: '未入库', waiting: '待入库', partial: '部分入库', all: '已全部入库', }); /** * 两位补零。 * @param {number} value 数值 * @return {string} 补零后的字符串 */ function pad2(value) { return String(value).padStart(2, '0'); } /** * 生成本地日期键,格式为 `YYYYMMDD`。 * @param {Date} dateValue 日期对象 * @return {string} 日期键 */ function buildDateKey(dateValue) { return `${dateValue.getFullYear()}${pad2(dateValue.getMonth() + 1)}${pad2(dateValue.getDate())}`; } /** * 将 `HH:mm` 转为当日分钟数。 * @param {string} timeText `HH:mm` 文本 * @return {number} 分钟数,格式非法返回 -1 */ function toMinutes(timeText) { if (!TIME_PATTERN.test(String(timeText || ''))) { return -1; } const [ hour, minute ] = String(timeText).split(':'); return Number(hour) * 60 + Number(minute); } /** * 规范化正整数,非法或空值回退默认值。 * @param {*} value 原始值 * @param {number} fallback 兜底值 * @return {number} 正整数 */ function toPositiveInteger(value, fallback) { const numberValue = Number(value); if (!Number.isInteger(numberValue) || numberValue <= 0) { return fallback; } return numberValue; } /** * 规范化通知短语:空值回退默认短语,超长截断。 * @param {*} value 原始短语 * @param {string} fallback 默认短语 * @return {string} 规范化后的短语 */ function normalizeTemplateText(value, fallback) { const text = String(value === undefined || value === null ? '' : value).trim(); if (!text) { return fallback; } return text.length > NOTICE_TEMPLATE_MAX_LENGTH ? text.slice(0, NOTICE_TEMPLATE_MAX_LENGTH) : text; } /** * 渲染通知短语:替换支持的变量({warehouse}/{store}/{count}/...),未识别的占位符原样保留。 * @param {string} template 短语模板 * @param {Object} variables 变量键值对(键为小写变量名) * @return {string} 渲染后的短语 */ function renderNoticeTemplate(template, variables) { const source = String(template || ''); if (!source) { return ''; } const values = variables && typeof variables === 'object' ? variables : {}; return source.replace(TEMPLATE_VARIABLE_PATTERN, (match, name) => { const key = String(name || '').toLowerCase(); if (!Object.prototype.hasOwnProperty.call(values, key)) { return match; } const value = values[key]; return value === undefined || value === null ? '' : String(value); }); } /** * 规范化「收货未入库提醒」配置(读取路径不抛错,非法值回退默认)。 * @param {Object|string|null} rawConfig 原始配置 * @return {Object} 规范化配置 */ function normalizeNoticeConfig(rawConfig) { let parsed = rawConfig; if (typeof parsed === 'string') { try { parsed = JSON.parse(parsed); } catch (error) { parsed = null; } } if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { parsed = {}; } const noticeTime = TIME_PATTERN.test(String(parsed.notice_time || '').trim()) ? String(parsed.notice_time).trim() : DEFAULT_NOTICE_TIME; const minHours = toPositiveInteger(parsed.min_hours, DEFAULT_MIN_HOURS); const rawMaxHours = toPositiveInteger(parsed.max_hours, DEFAULT_MAX_HOURS); const maxHours = rawMaxHours > minHours ? rawMaxHours : Math.max(DEFAULT_MAX_HOURS, minHours + 1); return { enabled: parsed.enabled === true || parsed.enabled === 1 || parsed.enabled === '1', noticeTime, minHours, maxHours, noticeTemplate: normalizeTemplateText(parsed.notice_template, DEFAULT_NOTICE_TEMPLATE), storeNoticeTemplate: normalizeTemplateText(parsed.store_notice_template, DEFAULT_STORE_NOTICE_TEMPLATE), }; } /** * 从仓库 subject_config 中读取「收货未入库提醒」配置(兼容 JSON 字符串与缺失字段)。 * @param {Object|string|null} rawSubject 原始 subject_config * @return {Object} 规范化配置 */ function readNoticeConfigFromSubject(rawSubject) { let parsed = rawSubject; if (typeof parsed === 'string') { try { parsed = JSON.parse(parsed); } catch (error) { parsed = null; } } if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { return normalizeNoticeConfig(null); } return normalizeNoticeConfig(parsed.receiving_pending_inbound_notice); } /** * 判断当前时刻是否命中提醒时间(含宽限窗口,宽限不超过 1 天)。 * @param {string} noticeTime 提醒时间 `HH:mm` * @param {Date} now 当前时刻(进程本地时间,与仓库配置口径一致) * @param {number} graceMinutes 宽限分钟 * @return {boolean} 是否命中 */ function isNoticeTimeHit(noticeTime, now, graceMinutes) { const targetMinutes = toMinutes(noticeTime); if (targetMinutes < 0) { return false; } const grace = Math.max(1, Math.min(24 * 60, Math.floor(Number(graceMinutes) || DEFAULT_GRACE_MINUTES))); const nowMinutes = now.getHours() * 60 + now.getMinutes(); const diff = nowMinutes - targetMinutes; return (diff >= 0 && diff < grace) || (nowMinutes + 24 * 60 - targetMinutes < grace); } /** * 格式化时间用于消息展示,优先使用应用内格式化器。 * @param {Object} ctx Egg 上下文 * @param {*} value 原始时间值 * @return {string} `YYYY-MM-DD HH:mm:ss`,非法值返回空串 */ function formatDateTime(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(); } /** * 收货未入库提醒服务。 * * 按仓库设置 `subject_config.receiving_pending_inbound_notice` 扫描「创建时间超过 * min_hours 且不足 max_hours 仍未完成入库」的收货单: * - 绑定货主:通知货主收货群(未配群回退仓库客服群,由 notice 固定订阅回退链实现); * - 未绑定货主:直接通知仓库客服群。 * 通知时间(notice_time)与超时区间(min_hours / max_hours)均可在仓库设置中配置。 */ class ReceivingPendingNoticeService extends MainService { constructor(ctx) { super(ctx); this.memoryDailyLocks = new Set(); } /** * 读取全部启用仓库的提醒配置。 * * @return {Promise>} 仓库配置列表 */ async getWarehouseNoticeConfigs() { const { ctx } = this; const storeModel = ctx.model && ctx.model.Store; if (!storeModel || typeof storeModel.findAll !== 'function') { ctx.logger.warn('[receiving-pending-notice] Store 模型不可用,跳过扫描'); return []; } const rows = await storeModel.findAll({ where: { status: 1, deleted_at: null }, attributes: [ 'id', 'company_name', 'subject_config' ], order: [[ 'id', 'ASC' ]], // 取 raw 行:避免模型 getter 对历史脏配置抛错导致整轮扫描中断,缺失字段由 normalizeNoticeConfig 兜默认值 raw: true, }); return (Array.isArray(rows) ? rows : []) .map(row => { const warehouseId = Number(row.id) || 0; if (warehouseId <= 0) { return null; } return { warehouseId, warehouseName: String(row.company_name || '').trim(), config: readNoticeConfigFromSubject(row.subject_config), }; }) .filter(item => item && item.config.enabled); } /** * 查询指定仓库在超时区间内仍未完成入库的收货单。 * * @param {number} warehouseId 仓库 ID * @param {Object} config 规范化后的提醒配置 * @param {Date} now 当前时刻 * @return {Promise>} 收货单列表(raw) */ async findPendingReceivings(warehouseId, config, now) { const { ctx, app } = this; const { Op } = app.Sequelize; const receivingModel = ctx.model && ctx.model.Receiving; if (!receivingModel || typeof receivingModel.findAll !== 'function') { return []; } const nowTime = now.getTime(); return await receivingModel.findAll({ where: { warehouse_id: warehouseId, is_deleted: false, status: { [Op.ne]: 'cancelled' }, // 超过 min_hours 且不足 max_hours created_at: { [Op.gte]: new Date(nowTime - config.maxHours * HOUR_MS), [Op.lte]: new Date(nowTime - config.minHours * HOUR_MS), }, [Op.or]: [ { status: 'receiving' }, { storage_status: { [Op.ne]: 'all' } }, ], }, attributes: [ 'id', 'receiving_number', 'store_id', 'store_name', 'status', 'storage_status', 'created_at', 'delivery_method', 'total_quantity', 'total_boxes', ], order: [[ 'created_at', 'ASC' ], [ 'id', 'ASC' ]], raw: true, }); } /** * 按货主分组收货单(未绑定货主归入 storeId=0 组)。 * * @param {Array} rows 收货单列表 * @return {Array<{storeId: number, storeName: string, rows: Array}>} 分组结果 */ groupByStore(rows) { const grouped = new Map(); for (const row of Array.isArray(rows) ? rows : []) { const storeId = Number(row && row.store_id) > 0 ? Number(row.store_id) : 0; if (!grouped.has(storeId)) { grouped.set(storeId, { storeId, storeName: String(row && row.store_name || '').trim(), rows: [], }); } grouped.get(storeId).rows.push(row); } return [ ...grouped.values() ]; } /** * 构造单行收货单展示文本。 * * @param {Object} row 收货单记录 * @param {number} index 序号 * @param {Object} ctx Egg 上下文 * @param {boolean} includeStore 是否展示货主(仓库/客服版展示,货主版不展示) * @return {string} 展示行 */ buildRowLine(row, index, ctx, includeStore) { const number = String(row.receiving_number || row.id || '').trim(); const createdText = formatDateTime(ctx, row.created_at); const statusText = String(row.status || '') === 'receiving' ? RECEIVING_STATUS_LABEL.receiving : `${RECEIVING_STATUS_LABEL.completed}·${STORAGE_STATUS_LABEL[row.storage_status] || '未入库'}`; const quantity = Number(row.total_quantity || 0); const parts = [ `${index}.${number}`, includeStore ? `货主:${String(row.store_name || '').trim() || (Number(row.store_id) > 0 ? `ID${row.store_id}` : '未绑定')}` : '', includeStore && quantity > 0 ? `数量:${quantity}` : '', createdText ? `创建时间:${createdText}` : '', `状态:${statusText}`, ].filter(Boolean); return parts.join(' '); } /** * 格式化日期(YYYY-MM-DD),优先使用应用内格式化器。 * * @param {Object} ctx Egg 上下文 * @param {*} value 原始时间值 * @return {string} 日期文本 */ formatDateOnly(ctx, value) { 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, 'YYYY-MM-DD'); } return `${dateValue.getFullYear()}-${pad2(dateValue.getMonth() + 1)}-${pad2(dateValue.getDate())}`; } /** * 构造通知短语的替换变量(未识别的占位符在渲染时原样保留)。 * * 可用变量:{warehouse} 仓库名 / {warehouse_id} 仓库ID / {store} 货主名(未绑定为「未绑定货主」) * / {store_id} 货主ID / {count} 本批单数 / {min_hours} / {max_hours} / {date} 提醒日期 * / {numbers} 本批收货单号(最多 20 个,超出以「等 N 单」结尾)。 * * @param {Object} options 变量来源 * @param {Array} options.rows 收货单列表 * @param {Object} options.config 规范化后的提醒配置 * @param {string} options.warehouseName 仓库名称 * @param {number} options.warehouseId 仓库 ID * @param {number} options.storeId 货主 ID(0 表示未绑定) * @param {string} options.storeName 货主名称 * @param {Date} options.now 当前时刻 * @param {Object} options.ctx Egg 上下文 * @return {Object} 变量键值对 */ buildTemplateVariables({ rows, config, warehouseName, warehouseId, storeId, storeName, now, ctx }) { const list = Array.isArray(rows) ? rows : []; const hasStore = Number(storeId) > 0; const numbers = list .slice(0, MAX_NOTICE_ITEMS) .map(row => String(row && (row.receiving_number || row.id) || '').trim()) .filter(Boolean); return { warehouse: String(warehouseName || '').trim() || `仓库${warehouseId}`, warehouse_id: String(warehouseId), store: hasStore ? (String(storeName || '').trim() || `货主${storeId}`) : '未绑定货主', store_id: hasStore ? String(storeId) : '0', count: String(list.length), min_hours: String(config.minHours), max_hours: String(config.maxHours), date: this.formatDateOnly(ctx, now), numbers: numbers.length > 0 ? `${numbers.join('、')}${list.length > numbers.length ? ` 等 ${list.length} 单` : ''}` : '', }; } /** * 构造消息正文:短语(模板变量替换)+ 换行 + 明细(一行一条)+ 查看链接。 * * 短语来自仓库设置(notice_template 仓库/客服群版、store_notice_template 货主群版), * 为空时回退默认短语。 * * @param {Object} options 构造参数 * @param {Array} options.rows 收货单列表 * @param {Object} options.config 规范化后的提醒配置 * @param {string} options.warehouseName 仓库名称 * @param {number} options.warehouseId 仓库 ID * @param {number} options.storeId 货主 ID(0 表示未绑定) * @param {string} options.storeName 货主名称 * @param {boolean} options.forStore 是否货主版文案 * @param {string} options.viewUrl 查看链接 * @param {Date} options.now 当前时刻 * @param {Object} options.ctx Egg 上下文 * @return {string} 消息正文 */ buildContent({ rows, config, warehouseName, warehouseId, storeId, storeName, forStore, viewUrl, now, ctx }) { const list = Array.isArray(rows) ? rows : []; const template = forStore ? config.storeNoticeTemplate : config.noticeTemplate; const phrase = renderNoticeTemplate(template, this.buildTemplateVariables({ rows: list, config, warehouseName, warehouseId, storeId, storeName, now, ctx, })); const lines = [ phrase ]; list.slice(0, MAX_NOTICE_ITEMS).forEach((row, index) => { lines.push(this.buildRowLine(row, index + 1, ctx, !forStore)); }); if (list.length > MAX_NOTICE_ITEMS) { lines.push(`…… 其余 ${list.length - MAX_NOTICE_ITEMS} 单未列出`); } lines.push(`${forStore ? '详情查看' : '快速查看'}:${viewUrl}`); return lines.join('\n'); } /** * 解析通知发送方法,优先 `send`,其次兼容 `index.send`。 * * @return {Function|null} 可执行的发送方法 */ resolveNoticeSendMethod() { const { ctx } = this; 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} options 发送参数 * @param {number} options.warehouseId 仓库 ID * @param {string} options.warehouseName 仓库名称 * @param {number} options.storeId 货主 ID,0 表示未绑定货主 * @param {string} options.storeName 货主名称 * @param {Array} options.rows 该货主的收货单列表 * @param {Object} options.config 规范化后的提醒配置 * @param {Date} options.now 当前时刻 * @return {Promise} 通知结果 */ async sendPendingNotice({ warehouseId, warehouseName, storeId, storeName, rows, config, now }) { const { ctx, app } = this; const sendMethod = this.resolveNoticeSendMethod(); if (typeof sendMethod !== 'function') { ctx.logger.warn('[receiving-pending-notice] 通知服务不可用,跳过发送'); return null; } const warehouseFrontendUrl = String(app.config.frontendUrl || '').trim(); const storeFrontendUrl = String(app.config.storeFrontendUrl || app.config.frontendUrl || '').trim(); const hasStore = Number(storeId) > 0; const content = this.buildContent({ rows, config, warehouseName, warehouseId, storeId, storeName, forStore: false, viewUrl: `${warehouseFrontendUrl}/storage/receiving`, now, ctx, }); const storeContent = hasStore ? this.buildContent({ rows, config, warehouseName, warehouseId, storeId, storeName, forStore: true, viewUrl: `${storeFrontendUrl}/storage/receiving_owner`, now, ctx, }) : undefined; return await sendMethod({ warehouseId, // 未绑定货主时不带 storeId,由 notice 固定订阅回退到仓库客服群 storeId: hasStore ? Number(storeId) : undefined, messageType: 'text', businessName: 'receiving', event: NOTICE_EVENT, channel: 'warehouse', title: `收货未入库提醒(${rows.length} 单)`, content, ...(storeContent ? { storeContent } : {}), // 幂等键:同仓库+同货主+同一天只落一条消息记录 businessId: `receiving-pending:${warehouseId}:${hasStore ? Number(storeId) : 0}:${buildDateKey(now)}`, subject: { id: warehouseId, type: 'warehouse', name: warehouseName, }, sender: { id: null, name: '系统提醒', }, metadata: { warehouseId, warehouseName, storeId: hasStore ? Number(storeId) : null, storeName: String(storeName || '').trim(), minHours: config.minHours, maxHours: config.maxHours, receivingIds: rows.map(row => Number(row.id)).filter(id => id > 0), receivingNumbers: rows.map(row => String(row.receiving_number || '')).filter(Boolean), }, }); } /** * 扫描并通知单个仓库的超时未入库收货单。 * * @param {Object} options 执行参数 * @param {number} options.warehouseId 仓库 ID * @param {string} options.warehouseName 仓库名称 * @param {Object} options.config 规范化后的提醒配置 * @param {Date} options.now 当前时刻 * @return {Promise} 执行汇总 */ async notifyWarehouse({ warehouseId, warehouseName, config, now }) { const { ctx } = this; const rows = await this.findPendingReceivings(warehouseId, config, now); const summary = { warehouseId, warehouseName, pendingCount: rows.length, groupCount: 0, sentCount: 0, failedCount: 0, }; if (rows.length === 0) { ctx.logger.info(`[receiving-pending-notice] 仓库 ${warehouseId} 无超时未入库收货单`); return summary; } const groups = this.groupByStore(rows); for (const group of groups) { const result = await this.sendPendingNotice({ warehouseId, warehouseName, storeId: group.storeId, storeName: group.storeName, rows: group.rows, config, now, }); summary.groupCount += 1; if (result && result.success) { summary.sentCount += 1; } else { summary.failedCount += 1; } } ctx.logger.info( `[receiving-pending-notice] 仓库 ${warehouseId} 提醒完成:未入库 ${summary.pendingCount} 单,` + `通知 ${summary.groupCount} 个批次,成功 ${summary.sentCount},失败 ${summary.failedCount}` ); return summary; } /** * 获取 Redis 缓存客户端。 * * @return {Object|null} Redis 客户端或 null */ getRedisClient() { const { app } = this; try { return app && app.redis && typeof app.redis.get === 'function' ? app.redis.get('cache') : null; } catch (error) { return null; } } /** * 申请当日执行锁(Redis NX;Redis 不可用时降级为进程内集合)。 * * @param {string} lockKey 锁 key * @return {Promise} 是否申请成功 */ async acquireDailyLock(lockKey) { const { ctx } = this; const redisClient = this.getRedisClient(); if (redisClient && typeof redisClient.set === 'function') { try { const result = await redisClient.set(lockKey, '1', 'EX', DAILY_LOCK_TTL_SECONDS, 'NX'); if (result === 'OK') { return true; } if (result !== null && result !== undefined) { return false; } } catch (error) { ctx.logger.warn(`[receiving-pending-notice] 当日锁申请失败,降级进程内锁: ${error.message}`); } } if (this.memoryDailyLocks.has(lockKey)) { return false; } this.memoryDailyLocks.add(lockKey); return true; } /** * 释放当日执行锁(发送异常时释放,允许宽限窗口内下一轮重试)。 * * @param {string} lockKey 锁 key * @return {Promise} 无返回值 */ async releaseDailyLock(lockKey) { const { ctx } = this; this.memoryDailyLocks.delete(lockKey); const redisClient = this.getRedisClient(); if (redisClient && typeof redisClient.del === 'function') { try { await redisClient.del(lockKey); } catch (error) { ctx.logger.warn(`[receiving-pending-notice] 当日锁释放失败: ${error.message}`); } } } /** * 执行一轮收货未入库提醒(供定时任务调用)。 * * 命中条件:仓库开启提醒 + 当前时刻落在 notice_time 宽限窗口内 + 当日未执行过。 * * @param {Object|null} options 执行参数 * @param {Date} [options.now] 指定当前时刻(测试用) * @param {number} [options.graceMinutes] 提醒时间宽限分钟(测试用) * @return {Promise} 执行汇总 */ async execute(options = null) { const { ctx } = this; const params = options || {}; const now = params.now instanceof Date ? params.now : new Date(); const graceMinutes = Number.isFinite(Number(params.graceMinutes)) && Number(params.graceMinutes) > 0 ? Number(params.graceMinutes) : DEFAULT_GRACE_MINUTES; const enabledConfigs = await this.getWarehouseNoticeConfigs(); const dateKey = buildDateKey(now); const summary = { checkedWarehouseCount: enabledConfigs.length, executedWarehouseCount: 0, pendingCount: 0, sentCount: 0, failedCount: 0, results: [], }; for (const item of enabledConfigs) { if (!isNoticeTimeHit(item.config.noticeTime, now, graceMinutes)) { continue; } const lockKey = `${DAILY_LOCK_KEY_PREFIX}${item.warehouseId}:${dateKey}`; const acquired = await this.acquireDailyLock(lockKey); if (!acquired) { continue; } try { const result = await this.notifyWarehouse({ warehouseId: item.warehouseId, warehouseName: item.warehouseName, config: item.config, now, }); summary.executedWarehouseCount += 1; summary.pendingCount += result.pendingCount; summary.sentCount += result.sentCount; summary.failedCount += result.failedCount; summary.results.push(result); } catch (error) { // 执行失败释放锁,宽限窗口内的下一轮仍可重试 await this.releaseDailyLock(lockKey); summary.failedCount += 1; ctx.logger.error(`[receiving-pending-notice] 仓库 ${item.warehouseId} 提醒执行失败: ${error.message}`); } } return summary; } } module.exports = ReceivingPendingNoticeService;