'use strict'; const { Service } = require('egg'); const CustomizeWebhookDriver = require('./drivers/generic'); const WecomWebhookDriver = require('./drivers/wecom'); const MESSAGE_TYPE_MAP = Object.freeze({ text: 'text', txt: 'text', message: 'text', 文本: 'text', image: 'image', img: 'image', picture: 'image', 图片: 'image', file: 'file', attachment: 'file', 文件: 'file', }); const DEFAULT_MAX_NOTICE_WEBHOOK_COUNT = 5; const DEFAULT_RETRY_DELAYS_MS = Object.freeze([ 3000, 6000, 12000 ]); const EVENT_CODE_PATTERN = /^[a-z_][a-z0-9_]*$/; const DEFAULT_REGISTERED_EVENT_CODES = Object.freeze([ 'all', '*', 'receiving_completed', 'receiving_rejected', 'receiving_reviewed', 'receiving_store_bound', 'receiving_store_unmatched', 'entry_order_completed', 'order_cancel_intercepted', 'wave_strategy_quick_scan_failed', 'store_warehouse_print_quantity_adjusted', ]); /** * 固定群订阅配置:事件 → 目标群类型/子类型(仓库接口消息推送通道,统一推送配置来源)。 * 群类型定义见 app/service/inbox/groups.js 的 GROUP_TYPES: * warehouse 子类型:receiving 收货 / production 生产 / stockout 出库 / finance 财务 / all 全体 / customer_service 客服 / exception 异常 * store 子类型:after_sales 售后 / finance 财务 / receiving 收货(需 store_id) */ const FIXED_GROUP_SUBSCRIPTIONS = Object.freeze({ receiving_completed: Object.freeze([ Object.freeze({ groupType: 'warehouse', subType: 'receiving' }), ]), receiving_rejected: Object.freeze([ Object.freeze({ groupType: 'warehouse', subType: 'receiving' }), ]), receiving_reviewed: Object.freeze([ Object.freeze({ groupType: 'warehouse', subType: 'receiving' }), Object.freeze({ groupType: 'store', subType: 'receiving', fallbackTargets: Object.freeze([ Object.freeze({ groupType: 'store', subType: 'after_sales' }), ]), }), ]), receiving_store_bound: Object.freeze([ Object.freeze({ groupType: 'store', subType: 'receiving', fallbackTargets: Object.freeze([ Object.freeze({ groupType: 'store', subType: 'after_sales' }), ]), }), ]), receiving_store_unmatched: Object.freeze([ Object.freeze({ groupType: 'store', subType: 'receiving', fallbackTargets: Object.freeze([ Object.freeze({ groupType: 'store', subType: 'after_sales' }), ]), }), ]), entry_order_completed: Object.freeze([ Object.freeze({ groupType: 'store', subType: 'receiving', fallbackTargets: Object.freeze([ Object.freeze({ groupType: 'store', subType: 'after_sales' }), ]), }), ]), order_cancel_intercepted: Object.freeze([ Object.freeze({ groupType: 'warehouse', subType: 'exception' }), ]), order_sync_completed: Object.freeze([ Object.freeze({ groupType: 'store', subType: 'after_sales' }), ]), store_warehouse_print_quantity_adjusted: Object.freeze([ Object.freeze({ groupType: 'store', subType: 'finance' }), ]), storage_transfer_completed: Object.freeze([ Object.freeze({ groupType: 'warehouse', subType: 'production' }), ]), wave_strategy_quick_scan_failed: Object.freeze([ Object.freeze({ groupType: 'warehouse', subType: 'exception' }), ]), }); const DRIVER_TYPE_ALIASES = Object.freeze({ custom: 'customize', customize: 'customize', generic: 'customize', wecom: 'wecom', }); class NoticeService extends Service { /** * 统一通知服务构造函数,初始化驱动缓存。 * @param {object} ctx Egg 上下文 */ constructor(ctx) { super(ctx); this.driverCache = new Map(); } /** * 根据 webhook 类型获取对应发送驱动。 * @param {string} [hookType='customize'] webhook 类型 * @return {object} webhook 驱动实例 */ getDriver(hookType = 'customize') { const normalizedHookType = String(hookType || 'customize').trim().toLowerCase() || 'customize'; const resolvedHookType = DRIVER_TYPE_ALIASES[normalizedHookType] || 'customize'; if (!this.driverCache.has(resolvedHookType)) { let driver = null; switch (resolvedHookType) { case 'wecom': driver = new WecomWebhookDriver(this.ctx, { hookType: resolvedHookType, }); break; case 'customize': default: driver = new CustomizeWebhookDriver(this.ctx, { hookType: resolvedHookType, }); break; } this.driverCache.set(resolvedHookType, driver); } return this.driverCache.get(resolvedHookType); } /** * 规范化消息类型,兼容中英文和别名写法。 * @param {string} [type='text'] 原始消息类型 * @return {string} 标准化后的消息类型 */ normalizeMessageType(type = 'text') { const rawType = String(type || 'text').trim(); const normalizedType = rawType.toLowerCase(); return MESSAGE_TYPE_MAP[rawType] || MESSAGE_TYPE_MAP[normalizedType] || 'text'; } /** * 将传入值安全转换为对象。 * @param {*} value 原始值 * @param {object} [fallback={}] 转换失败时的兜底对象 * @return {object} 转换后的对象 */ toObject(value, fallback = {}) { if (!value) { return fallback; } if (typeof value === 'object' && !Array.isArray(value)) { return value; } if (typeof value === 'string') { try { const parsed = JSON.parse(value); return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : fallback; } catch (_) { return fallback; } } return fallback; } /** * 规范化订阅事件列表,支持数组、字符串和对象格式。 * @param {*} rawEvents 原始事件配置 * @return {string[]} 事件编码数组 */ normalizeEventList(rawEvents) { if (!rawEvents) { return []; } if (Array.isArray(rawEvents)) { return rawEvents .map(item => String(item || '').trim().toLowerCase() .replace(/\./g, '_')) .filter(Boolean); } if (typeof rawEvents === 'string') { const trimmed = rawEvents.trim(); if (!trimmed) { return []; } try { const parsed = JSON.parse(trimmed); if (parsed !== rawEvents) { return this.normalizeEventList(parsed); } } catch (_) { // ignore parse failure and continue with string split } return trimmed.split(/[\s,;|]+/).map(item => item.trim().toLowerCase().replace(/\./g, '_')).filter(Boolean); } if (typeof rawEvents === 'object') { if (rawEvents.all === true) { return [ 'all' ]; } return this.normalizeEventList(rawEvents.include || rawEvents.events || []); } return []; } /** * 判断当前 webhook 是否命中本次消息事件。 * @param {*} rawEvents 订阅的事件配置 * @param {object} payload 统一消息载荷 * @return {boolean} 是否命中 */ matchesEvents(rawEvents, payload) { const eventList = this.normalizeEventList(rawEvents); if (eventList.length === 0) { return true; } const candidateEvents = new Set([ payload.event, payload.businessName, `${payload.businessName}_${payload.message.type}`, ].map(item => String(item || '').trim().toLowerCase()).filter(Boolean)); return eventList.some(item => item === '*' || item === 'all' || candidateEvents.has(item)); } /** * 生成本次通知的追踪 ID。 * @return {string} 追踪ID */ buildTraceId() { return `notice_${Date.now()}_${Math.random().toString(16).slice(2, 10)}`; } /** * 获取当前模型中已注册的事件编码列表。 * @return {string[]} 注册的事件编码列表 */ getRegisteredEventCodes() { const notificationWebhookModel = this.ctx.model && this.ctx.model.NotificationWebhook; if (!notificationWebhookModel) { return [ ...DEFAULT_REGISTERED_EVENT_CODES ]; } if (typeof notificationWebhookModel.getAvailableEventCodes === 'function') { const codes = notificationWebhookModel.getAvailableEventCodes() .map(item => String(item || '').trim().toLowerCase()) .filter(Boolean); // 默认注册事件码始终生效(与模型配置合并,便于服务内按现有模式追加新事件码) return codes.length > 0 ? [ ...new Set([ ...codes, ...DEFAULT_REGISTERED_EVENT_CODES ]) ] : [ ...DEFAULT_REGISTERED_EVENT_CODES ]; } if (Array.isArray(notificationWebhookModel.AVAILABLE_EVENTS)) { const codes = notificationWebhookModel.AVAILABLE_EVENTS .map(item => String(item && item.code || '').trim().toLowerCase()) .filter(Boolean); return codes.length > 0 ? [ ...new Set([ ...codes, ...DEFAULT_REGISTERED_EVENT_CODES ]) ] : [ ...DEFAULT_REGISTERED_EVENT_CODES ]; } return [ ...DEFAULT_REGISTERED_EVENT_CODES ]; } /** * 判断事件编码是否符合标识符式命名:仅允许小写字母、数字、下划线,且首字符不能为数字。 * @param {string} event 事件编码 * @return {boolean} 是否有效 */ isValidEventCode(event) { const normalizedEvent = String(event || '').trim().toLowerCase(); return normalizedEvent === 'all' || normalizedEvent === '*' || EVENT_CODE_PATTERN.test(normalizedEvent); } /** * 校验待发送事件是否已在通知模型中注册。 * @param {string} event 事件名 */ assertEventRegistered(event) { const normalizedEvent = String(event || '').trim().toLowerCase(); if (!normalizedEvent) { throw new Error('event 不能为空'); } if (!this.isValidEventCode(normalizedEvent)) { throw new Error(`event 命名不合法,仅支持小写字母、数字、下划线,且首字符不能为数字: ${normalizedEvent}`); } const registeredCodes = this.getRegisteredEventCodes(); if (registeredCodes.length > 0 && !registeredCodes.includes(normalizedEvent)) { throw new Error(`event 未注册,不允许发送: ${normalizedEvent}`); } } /** * 获取通知失败后的重试间隔,默认按 3 秒、6 秒、12 秒阶梯重试。 * @param {object} [options={}] 原始通知入参 * @return {number[]} 重试间隔数组 */ getRetryDelays(options = {}) { const customDelays = Array.isArray(options.retryDelaysMs) ? options.retryDelaysMs : (Array.isArray(this.app && this.app.config && this.app.config.noticeRetryDelaysMs) ? this.app.config.noticeRetryDelaysMs : DEFAULT_RETRY_DELAYS_MS); const normalizedDelays = customDelays .map(item => Number(item)) .filter(item => Number.isFinite(item) && item >= 0); return normalizedDelays.length > 0 ? normalizedDelays : [ ...DEFAULT_RETRY_DELAYS_MS ]; } /** * Promise 风格 sleep,用于统一重试等待。 * @param {number} [ms=0] 等待毫秒数 * @return {Promise} */ async sleep(ms = 0) { const waitMs = Math.max(0, Number(ms) || 0); await new Promise(resolve => setTimeout(resolve, waitMs)); } /** * 判断外部 webhook 返回是否可视为成功。 * @param {object} [result={}] 发送结果 * @return {boolean} 是否成功 */ isSuccessfulResponse(result = {}) { const status = Number(result && result.status || 0); if (status > 0 && (status < 200 || status >= 300)) { return false; } const response = result && Object.prototype.hasOwnProperty.call(result, 'response') ? result.response : null; if ([ 0, '0', false, 'false' ].includes(response)) { return false; } if (response && typeof response === 'object') { if (response.ok === false || response.success === false) { return false; } if (Object.prototype.hasOwnProperty.call(response, 'errcode')) { const errcode = Number(response.errcode); if (Number.isFinite(errcode) && errcode !== 0) { return false; } } if (Object.prototype.hasOwnProperty.call(response, 'code')) { const responseCode = Number(response.code); if (Number.isFinite(responseCode) && responseCode === 0) { return false; } } } return true; } /** * 归一化失败原因,便于日志记录与回写数据库。 * @param {object} params 参数对象 * @param {object|null} [params.result=null] 最近一次发送结果 * @param {Error|null} [params.error=null] 最近一次异常 * @return {string} 失败原因 */ getFailureMessage({ result = null, error = null } = {}) { if (error && error.message) { return error.message; } const status = Number(result && result.status || 0); if (status > 0 && (status < 200 || status >= 300)) { return `webhook 请求失败,HTTP 状态码 ${status}`; } const response = result && Object.prototype.hasOwnProperty.call(result, 'response') ? result.response : null; if ([ 0, '0' ].includes(response)) { return 'webhook 返回 0,判定为失败'; } if ([ false, 'false' ].includes(response)) { return 'webhook 返回 false,判定为失败'; } if (response && typeof response === 'object') { if (Object.prototype.hasOwnProperty.call(response, 'errcode')) { const errcode = Number(response.errcode); if (Number.isFinite(errcode) && errcode !== 0) { return String(response.errmsg || response.message || `企业微信 webhook 返回异常 errcode=${errcode}`); } } if (response.message) { return String(response.message); } if (response.msg) { return String(response.msg); } if (response.errmsg) { return String(response.errmsg); } } return 'webhook 推送失败'; } /** * 当 webhook 在重试后仍失败时,写入失败日志表。 * @param {object} params 失败日志参数 * @param {object} params.hook webhook 配置 * @param {object} params.payload 标准化后的 payload * @param {object|null} [params.result=null] 最近一次发送结果 * @param {Error|null} [params.error=null] 最近一次异常 * @param {number} [params.retryCount=0] 已执行重试次数 * @return {Promise} */ async persistFailureLog({ hook, payload, result = null, error = null, retryCount = 0 }) { const logModel = this.ctx.model && this.ctx.model.NotificationSendLog; if (!logModel || typeof logModel.create !== 'function') { return; } try { await logModel.create({ trace_id: String(payload.traceId || ''), webhook_id: Number(hook && hook.id || 0) || null, store_id: Number(hook && hook.store_id || (payload.subject && payload.subject.id) || 0) || null, warehouse_id: Number(payload.warehouseId || 0) || null, owner_store_id: Number(payload.storeId || 0) || null, business_name: String(payload.businessName || ''), event: String(payload.event || ''), hook_type: String(hook && hook.hook_type || ''), hook_url: String(hook && hook.hook_url || ''), request_payload: this.buildOutgoingPayload(hook || {}, payload), response_payload: result && Object.prototype.hasOwnProperty.call(result, 'response') ? result.response : null, http_status: Number(result && result.status || 0) || null, status: 'failed', error_message: this.getFailureMessage({ result, error }), retry_count: Number(retryCount || 0), created_by: Number(payload.sender && payload.sender.id || 0) || null, }); } catch (logError) { this.ctx.logger.error('[NoticeService.persistFailureLog] save failed: %s', logError.message); } } /** * 对单个 webhook 执行发送与阶梯重试。 * @param {object} params 发送参数 * @param {object} params.hook webhook 配置 * @param {object} params.payload 标准化后的 payload * @return {Promise} 发送结果 */ async sendWithRetry({ hook, payload }) { const driver = this.getDriver(hook && hook.hook_type); const outgoingPayload = this.buildOutgoingPayload(hook, payload); const retryDelays = this.getRetryDelays(payload.raw || {}); let lastResult = null; let lastError = null; for (let attemptIndex = 0; attemptIndex <= retryDelays.length; attemptIndex++) { try { const result = await driver.send({ hook, payload: outgoingPayload, }); lastResult = result; if (this.isSuccessfulResponse(result)) { return { success: true, retryCount: attemptIndex, attemptCount: attemptIndex + 1, ...(result || {}), }; } lastError = new Error(this.getFailureMessage({ result })); } catch (error) { lastError = error; } if (attemptIndex < retryDelays.length) { const waitMs = retryDelays[attemptIndex]; this.ctx.logger.warn( `[NoticeService.sendWithRetry] webhook send failed, retry in ${waitMs}ms (attempt ${attemptIndex + 1}/${retryDelays.length + 1}): ${this.getFailureMessage({ result: lastResult, error: lastError })}` ); await this.sleep(waitMs); } } await this.persistFailureLog({ hook, payload, result: lastResult, error: lastError, retryCount: retryDelays.length, }); return { success: false, hookId: Number(hook && hook.id || 0), hookType: String(hook && hook.hook_type || ''), hookUrl: String(hook && hook.hook_url || ''), status: Number(lastResult && lastResult.status || 0) || 0, response: lastResult && Object.prototype.hasOwnProperty.call(lastResult, 'response') ? lastResult.response : null, error: this.getFailureMessage({ result: lastResult, error: lastError }), retryCount: retryDelays.length, attemptCount: retryDelays.length + 1, }; } /** * 生成货主/仓库信息缓存键。 * @param {number|string} warehouseId 仓库主体 ID * @param {number|string} storeId 货主 ID * @return {string} 缓存键 */ getStoreInfoCacheKey(warehouseId, storeId) { return `warehouse:${Number(warehouseId || 0)}store:${Number(storeId || 0)}:info`; } /** * 解析货主信息,优先命中缓存,未命中时回查数据库并缓存 600 秒。 * @param {object} [options={}] 原始通知入参 * @param {object} [subject={}] 主体信息 * @return {Promise} 货主信息 */ async resolveStoreInfo(options = {}, subject = {}) { const directStore = this.toObject(options.store || options.owner, {}); const subjectType = String(subject.type || options.subjectType || '').trim().toLowerCase(); const warehouseId = Number( options.warehouseId || options.warehouse_id || subject.warehouseId || (subjectType === 'warehouse' ? subject.id : 0) || options.subjectId || options.subject_id || 0 ); const storeId = Number( options.ownerId || options.owner_id || options.storeOwnerId || options.store_owner_id || directStore.id || (subjectType === 'store' ? subject.id : 0) || (Number.isFinite(warehouseId) && warehouseId > 0 ? (options.storeId || options.store_id) : 0) || 0 ); const normalizedStore = { id: Number.isFinite(storeId) && storeId > 0 ? storeId : null, name: String(directStore.name || directStore.companyName || directStore.company_name || ''), businessLicense: String(directStore.businessLicense || directStore.business_license || ''), storeRemask: String(directStore.storeRemask || directStore.store_remask || directStore.remask || ''), warehouseUseStatus: directStore.warehouseUseStatus === undefined || directStore.warehouseUseStatus === null ? null : Number(directStore.warehouseUseStatus), authStatus: directStore.authStatus === undefined || directStore.authStatus === null ? null : Number(directStore.authStatus), }; if (!Number.isFinite(storeId) || storeId <= 0) { return normalizedStore; } const canUseCache = Number.isFinite(warehouseId) && warehouseId > 0; const cacheKey = canUseCache ? this.getStoreInfoCacheKey(warehouseId, storeId) : ''; if (canUseCache && this.app && typeof this.app.getCacheAsync === 'function') { try { const cachedValue = await this.app.getCacheAsync(cacheKey); const cachedStore = this.toObject(cachedValue, null); if (cachedStore && Object.keys(cachedStore).length > 0) { const businessLicense = String(cachedStore.businessLicense || cachedStore.business_license || normalizedStore.businessLicense || ''); const storeRemask = String(cachedStore.storeRemask || cachedStore.store_remask || cachedStore.remask || normalizedStore.storeRemask || ''); const warehouseUseStatus = cachedStore.warehouseUseStatus === undefined || cachedStore.warehouseUseStatus === null ? normalizedStore.warehouseUseStatus : Number(cachedStore.warehouseUseStatus); const authStatus = cachedStore.authStatus === undefined || cachedStore.authStatus === null ? normalizedStore.authStatus : Number(cachedStore.authStatus); return { id: normalizedStore.id, name: String(cachedStore.name || cachedStore.companyName || cachedStore.company_name || normalizedStore.name || ''), businessLicense, storeRemask, warehouseUseStatus, authStatus, }; } } catch (error) { this.ctx.logger.warn('[NoticeService.resolveStoreInfo] read cache failed: %s', error.message); } } const storeModel = this.ctx.model && this.ctx.model.Store; const storeWarehouseModel = this.ctx.model && this.ctx.model.StoreWarehouse; try { const [ storeRecord, relationRecord ] = await Promise.all([ storeModel && typeof storeModel.findByPk === 'function' ? storeModel.findByPk(storeId, { attributes: [ 'id', 'company_name', 'business_license' ], }) : null, canUseCache && storeWarehouseModel && typeof storeWarehouseModel.findOne === 'function' ? storeWarehouseModel.findOne({ where: { warehouse_id: warehouseId, store_id: storeId, }, attributes: [ 'store_remask', 'warehouse_use_status', 'auth_status' ], }) : null, ]); const businessLicense = normalizedStore.businessLicense || String(storeRecord && storeRecord.business_license || ''); const storeRemask = normalizedStore.storeRemask || String(relationRecord && relationRecord.store_remask || ''); const warehouseUseStatus = relationRecord && relationRecord.warehouse_use_status !== undefined && relationRecord.warehouse_use_status !== null ? Number(relationRecord.warehouse_use_status) : normalizedStore.warehouseUseStatus; const authStatus = relationRecord && relationRecord.auth_status !== undefined && relationRecord.auth_status !== null ? Number(relationRecord.auth_status) : normalizedStore.authStatus; const resolvedStore = { id: normalizedStore.id, name: normalizedStore.name || String(storeRecord && storeRecord.company_name || ''), businessLicense, storeRemask, warehouseUseStatus, authStatus, }; if (canUseCache && this.app && typeof this.app.setCacheAsync === 'function') { await this.app.setCacheAsync(cacheKey, resolvedStore, 600); } return resolvedStore; } catch (error) { this.ctx.logger.warn('[NoticeService.resolveStoreInfo] load store info failed: %s', error.message); return normalizedStore; } } /** * 解析主体配置,优先使用入参,缺失时回查主体表。 * @param {object} [options={}] 原始通知入参 * @param {object} [subject={}] 主体信息 * @return {Promise} 主体配置 */ async resolveSubjectConfig(options = {}, subject = {}) { const storeModel = this.ctx.model && this.ctx.model.Store; const deliveryOrderService = this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.deliveryOrder; const normalizeSubjectConfig = value => { if (storeModel && typeof storeModel.normalizeSubjectConfig === 'function') { return storeModel.normalizeSubjectConfig(value); } const config = this.toObject(value, {}); return { max_notice_webhook_count: DEFAULT_MAX_NOTICE_WEBHOOK_COUNT, default_express_code: 'STO', default_platform_code: 'TB', ...config, }; }; const directConfig = this.toObject(subject.config || options.subjectConfig || options.subject_config, null); if (directConfig && Object.keys(directConfig).length > 0) { return normalizeSubjectConfig(directConfig); } const subjectId = Number( options.subjectId || options.subject_id || subject.id || options.warehouseId || options.warehouse_id || options.storeId || options.store_id || 0 ); if (!Number.isFinite(subjectId) || subjectId <= 0) { return normalizeSubjectConfig(null); } try { if (!deliveryOrderService || typeof deliveryOrderService.getStoreSubjectConfig !== 'function') { return normalizeSubjectConfig(null); } const subjectConfig = await deliveryOrderService.getStoreSubjectConfig(subjectId); const nestedSubjectConfig = this.toObject(subjectConfig && subjectConfig.subject_config, null); const resolvedSubjectConfig = nestedSubjectConfig && Object.keys(nestedSubjectConfig).length > 0 ? nestedSubjectConfig : subjectConfig; return normalizeSubjectConfig(resolvedSubjectConfig); } catch (error) { this.ctx.logger.warn('[NoticeService.resolveSubjectConfig] load subject_config failed: %s', error.message); return normalizeSubjectConfig(null); } } /** * 将业务入参整理为统一通知 payload。 * @param {object} [options={}] 发送入参 * @return {Promise} 标准化后的 payload */ async normalizePayload(options = {}) { const subject = this.toObject(options.subject, {}); const messageType = this.normalizeMessageType( options.messageType || options.msgType || options.message_type || options.type ); const businessName = String( options.businessName || options.business || options.bussinessType || options.business_type || '' ).trim(); if (!businessName) { throw new Error('businessName / bussinessType 不能为空'); } const warehouseId = Number( options.warehouseId || options.warehouse_id || subject.warehouseId || (String(subject.type || options.subjectType || '').trim().toLowerCase() === 'warehouse' ? subject.id : 0) || 0 ); if (!Number.isFinite(warehouseId) || warehouseId <= 0) { throw new Error('warehouseId / warehouse_id 不能为空'); } const subjectId = Number( options.subjectId || options.subject_id || subject.id || warehouseId ); if (!Number.isFinite(subjectId) || subjectId <= 0) { throw new Error('subject.id / subjectId / warehouseId / warehouse_id 不能为空'); } const contentSource = options.content !== undefined ? options.content : (options.message !== undefined ? options.message : (options.messageBody !== undefined ? options.messageBody : options.body)); const content = typeof contentSource === 'string' ? contentSource : (contentSource == null ? '' : JSON.stringify(contentSource)); const url = String( options.url || options.fileUrl || options.file_url || options.imageUrl || options.image_url || '' ).trim(); if ([ 'image', 'file' ].includes(messageType) && !url) { throw new Error('图片/文件消息必须提供 url'); } const event = String(options.event || options.eventName || `${businessName}_${messageType}`).trim(); this.assertEventRegistered(event); const title = String(options.title || options.summary || businessName).trim() || businessName; const resolvedSubject = { ...subject, id: subjectId, }; const [ subjectConfig, storeInfo ] = await Promise.all([ this.resolveSubjectConfig(options, resolvedSubject), this.resolveStoreInfo(options, resolvedSubject), ]); return { traceId: String(options.traceId || this.buildTraceId()), hookType: String(options.hookType || options.webhookType || '').trim(), event, businessName, warehouseId, storeId: storeInfo && storeInfo.id ? Number(storeInfo.id) : null, businessId: options.businessId || options.bussinessId || null, occurredAt: options.occurredAt || new Date().toISOString(), sender: this.toObject(options.sender || options.operator, {}), receivers: Array.isArray(options.receivers) ? options.receivers : [], subject: { id: subjectId, type: String(subject.type || options.subjectType || 'store'), name: String(subject.name || options.subjectName || options.store_name || ''), code: String(subject.code || options.subjectCode || ''), config: subjectConfig, }, store: storeInfo, message: { type: messageType, title, content, url, fileName: String(options.fileName || options.filename || ''), mimeType: String(options.mimeType || options.contentType || ''), body: contentSource, }, storeContent: String(options.storeContent || options.store_content || '').trim(), metadata: this.toObject(options.metadata, {}), raw: options, }; } /** * 构建实际对外发送的统一消息体。 * @param {object} webhook webhook 配置 * @param {object} payload 标准化后的消息载荷 * @return {object} 对外发送载荷 */ buildOutgoingPayload(webhook, payload) { return { traceId: payload.traceId, event: payload.event, businessName: payload.businessName, businessId: payload.businessId, occurredAt: payload.occurredAt, subject: payload.subject, store: payload.store, sender: payload.sender, receivers: payload.receivers, message: payload.message, metadata: payload.metadata, }; } /** * 获取当前主体允许发送的 webhook 数量上限。 * @param {object} [payload={}] 标准化后的消息载荷 * @return {number} 上限数量 */ getWebhookLimit(payload = {}) { const rawLimit = payload && payload.subject && payload.subject.config ? payload.subject.config.max_notice_webhook_count : DEFAULT_MAX_NOTICE_WEBHOOK_COUNT; const normalizedLimit = Number(rawLimit); if (!Number.isInteger(normalizedLimit) || normalizedLimit < 0) { return DEFAULT_MAX_NOTICE_WEBHOOK_COUNT; } return Math.min(normalizedLimit, DEFAULT_MAX_NOTICE_WEBHOOK_COUNT); } /** * 筛选本次需要触达的 webhook(仅支持调用方显式传入的 hooks,不再读取 wms_notification_webhook 表)。 * @param {object} payload 标准化后的消息载荷 * @return {Promise} webhook 列表 */ async findMatchedWebhooks(payload) { const webhookLimit = this.getWebhookLimit(payload); if (webhookLimit <= 0) { return []; } if (Array.isArray(payload.raw.hooks)) { return payload.raw.hooks .filter(item => this.matchesEvents(item && item.events, payload)) .slice(0, webhookLimit); } return []; } /** * 获取事件对应的固定群订阅配置。 * @param {string} event 事件编码 * @return {Array|null} 固定订阅目标数组,未配置返回 null */ getFixedGroupTargets(event) { const normalizedEvent = String(event || '').trim().toLowerCase(); return FIXED_GROUP_SUBSCRIPTIONS[normalizedEvent] || null; } /** * 根据固定订阅配置查询本次事件需要触达的群。 * @param {object} payload 标准化后的消息载荷 * @param {Array|null} [targetsOverride] 可选,覆盖固定订阅目标(降级查找用) * @return {Promise} 目标群列表 */ async findSubscribedGroups(payload, targetsOverride = null) { const targets = targetsOverride || this.getFixedGroupTargets(payload.event); if (!targets || targets.length === 0) { return []; } const groupModel = this.ctx.model && this.ctx.model.InboxGroup; if (!groupModel || typeof groupModel.findAll !== 'function') { this.ctx.logger.warn('[NoticeService.findSubscribedGroups] InboxGroup 模型不可用'); return []; } const warehouseId = Number(payload.warehouseId || 0); const storeId = Number(payload.storeId || 0); const { Op } = this.app.Sequelize; const conditions = []; for (const target of targets) { const groupType = String(target && target.groupType || '').trim().toLowerCase(); const subType = String(target && target.subType || '').trim(); if (!groupType) { continue; } // 货主群必须定位到货主,无 store_id 时跳过 if (groupType === 'store' && (!Number.isFinite(storeId) || storeId <= 0)) { continue; } const condition = { group_type: groupType, is_blocked: 0 }; if (subType) { condition.sub_type = subType; } if (groupType === 'store') { condition.store_id = storeId; } conditions.push(condition); } if (conditions.length === 0) { return []; } try { const rows = await groupModel.findAll({ where: { warehouse_id: warehouseId, [Op.or]: conditions, }, order: [[ 'id', 'ASC' ]], raw: true, }); return (Array.isArray(rows) ? rows : []) .filter(row => row && row.group_id) .map(row => ({ group_id: row.group_id, group_name: row.group_name || '', group_type: row.group_type || '', sub_type: row.sub_type || '', ext_data: row.ext_data || null, })); } catch (error) { this.ctx.logger.warn(`[NoticeService.findSubscribedGroups] 查询订阅群失败: ${error.message}`); return []; } } /** * 解析降级通知中的货主名称:优先取合约表(wms_store_warehouse)货主备注 storeRemask, * 其次货主名称,均缺失时按 storeId 回查合约表/货主表,查不到再回退「货主{storeId}」/「货主」。 * @param {object} payload 标准化后的消息载荷 * @return {Promise} 货主名称 */ async resolveStoreLabelInternal(payload) { const storeRemask = String((payload.store && payload.store.storeRemask) || '').trim(); const directName = storeRemask || String((payload.store && payload.store.name) || '').trim(); if (directName) { return directName; } const storeId = Number(payload.storeId || 0); if (!Number.isFinite(storeId) || storeId <= 0) { return '货主'; } const warehouseId = Number(payload.warehouseId || 0); const storeModel = this.ctx.model && this.ctx.model.Store; const storeWarehouseModel = this.ctx.model && this.ctx.model.StoreWarehouse; try { const [ storeRecord, relationRecord ] = await Promise.all([ storeModel && typeof storeModel.findByPk === 'function' ? storeModel.findByPk(storeId, { attributes: [ 'id', 'company_name' ], }) : null, Number.isFinite(warehouseId) && warehouseId > 0 && storeWarehouseModel && typeof storeWarehouseModel.findOne === 'function' ? storeWarehouseModel.findOne({ where: { warehouse_id: warehouseId, store_id: storeId, }, attributes: [ 'store_remask' ], }) : null, ]); const contractRemask = String(relationRecord && relationRecord.store_remask || '').trim(); const companyName = String(storeRecord && storeRecord.company_name || '').trim(); if (contractRemask) { return contractRemask; } if (companyName) { return companyName; } } catch (error) { this.ctx.logger.warn('[NoticeService.resolveStoreLabelInternal] load store name failed: %s', error.message); } return `货主${storeId}`; } /** * 走仓库接口消息推送通道(不依赖 wms_notification_webhook 配置)。 * 按固定群订阅把通知推送到货主/仓库群,由外部适配器投递。 * @param {object} payload 标准化后的消息载荷 * @return {Promise} 发送汇总结果 */ async sendToWarehouseChannel(payload) { const { ctx } = this; const warehouseNotifyService = ctx.service && ctx.service.systems && ctx.service.systems.warehouseNotify; if (!warehouseNotifyService || typeof warehouseNotifyService.pushSystemMessage !== 'function') { ctx.logger.warn('[NoticeService.sendToWarehouseChannel] 仓库接口推送服务不可用', { traceId: payload.traceId, event: payload.event, warehouseId: payload.warehouseId, }); return { success: false, message: '仓库接口推送服务不可用', data: { traceId: payload.traceId, event: payload.event, matchedGroupCount: 0, sentCount: 0, failedCount: 0, results: [], }, }; } // 货主目标群未配置时,降级发送到仓库异常群,内容前缀标记失败 const fixedTargets = this.getFixedGroupTargets(payload.event) || []; const hasStoreTarget = fixedTargets.some( target => String(target && target.groupType || '').trim().toLowerCase() === 'store' ); // 合约已停用(warehouse_use_status=0)或已解除/拒绝/过期(auth_status≠2)的货主: // 不推货主群,也不降级到异常群(该货主本就不应被通知) const storeInfo = payload.store || {}; const warehouseUseStatus = storeInfo.warehouseUseStatus === undefined || storeInfo.warehouseUseStatus === null ? null : Number(storeInfo.warehouseUseStatus); const authStatus = storeInfo.authStatus === undefined || storeInfo.authStatus === null ? null : Number(storeInfo.authStatus); const storeContractInactive = warehouseUseStatus === 0 || (authStatus !== null && authStatus !== 2); // 主目标查询(store 目标的 fallbackTargets 不参与主查询,避免主目标命中时 fallback 群也被推送) const primaryTargets = fixedTargets .map(target => ({ groupType: String(target && target.groupType || '').trim().toLowerCase(), subType: String(target && target.subType || '').trim(), })) .filter(target => target.groupType); const groups = await this.findSubscribedGroups(payload, primaryTargets); const effectiveGroups = storeContractInactive ? groups.filter(group => group && group.group_type !== 'store') : groups; // store 目标回退链:主目标(如 store:receiving)未命中时,按 fallbackTargets 顺序逐级尝试(如 store:after_sales) const storeChains = fixedTargets.filter( target => String(target && target.groupType || '').trim().toLowerCase() === 'store' ); const extraStoreGroups = []; let storeChainMatchedCount = 0; if (!storeContractInactive) { for (const chain of storeChains) { const chainSubType = String(chain.subType || '').trim(); const primaryMatched = effectiveGroups.some( group => group && group.group_type === 'store' && (!chainSubType || String(group.sub_type || '').trim() === chainSubType) ); if (primaryMatched) { storeChainMatchedCount += 1; continue; } const fallbackTargets = Array.isArray(chain.fallbackTargets) ? chain.fallbackTargets : []; let chainMatched = false; for (const fallbackTarget of fallbackTargets) { const fallbackGroups = await this.findSubscribedGroups(payload, [ fallbackTarget ]); if (fallbackGroups.length > 0) { for (const fallbackGroup of fallbackGroups) { extraStoreGroups.push(fallbackGroup); } chainMatched = true; break; } } if (chainMatched) { storeChainMatchedCount += 1; } } } const mergedGroups = [ ...effectiveGroups, ...extraStoreGroups ]; const effectiveGroupsFinal = mergedGroups.filter( (group, index) => mergedGroups.findIndex(item => item.group_id === group.group_id) === index ); const storeGroupMatched = storeChains.length === 0 || storeChainMatchedCount >= storeChains.length; let fallbackGroups = []; let storeLabel = '货主'; if (hasStoreTarget && !storeGroupMatched && !storeContractInactive) { storeLabel = await this.resolveStoreLabelInternal(payload); const exceptionGroups = await this.findSubscribedGroups(payload, [ { groupType: 'warehouse', subType: 'exception' }, ]); const matchedGroupIds = new Set(effectiveGroupsFinal.map(group => group.group_id)); fallbackGroups = exceptionGroups.filter(group => !matchedGroupIds.has(group.group_id)); if (fallbackGroups.length > 0) { ctx.logger.warn('[NoticeService.sendToWarehouseChannel] 货主群未配置,降级发送到仓库异常群', { traceId: payload.traceId, event: payload.event, warehouseId: payload.warehouseId, storeId: payload.storeId, storeLabel, fallbackGroupCount: fallbackGroups.length, }); } } const pushGroups = [ ...effectiveGroupsFinal, ...fallbackGroups ]; if (pushGroups.length === 0) { ctx.logger.warn('[NoticeService.sendToWarehouseChannel] 未匹配到订阅群', { traceId: payload.traceId, event: payload.event, warehouseId: payload.warehouseId, storeId: payload.storeId, }); return { success: true, message: '未匹配到订阅群', data: { traceId: payload.traceId, event: payload.event, matchedGroupCount: 0, sentCount: 0, failedCount: 0, results: [], }, }; } const fallbackGroupIds = new Set(fallbackGroups.map(group => group.group_id)); const message = payload.message || {}; const fileUrl = String(message.url || '').trim(); const tasks = pushGroups.map(group => { // 货主群使用货主侧文案(货主端地址/路径),仓库群使用仓库侧文案 const baseContent = group.group_type === 'store' && payload.storeContent ? payload.storeContent : (message.content || ''); // 文件/图片类通知把资源链接以文本拼回 content,保持"接收方只处理 content"的协议 const fileLine = fileUrl ? `\n明细文件:${String(message.fileName || '').trim() ? `${String(message.fileName).trim()} ` : ''}${fileUrl}` : ''; // 货主群未配置降级到异常群时,内容前缀标记失败 const failPrefix = fallbackGroupIds.has(group.group_id) ? `通知货主【${storeLabel}】失败\n` : ''; return warehouseNotifyService.pushSystemMessage({ warehouseId: payload.warehouseId, // 仅货主群关联货主,仓库群不标记 store_id(避免仓库群消息被误标货主) storeId: group.group_type === 'store' ? payload.storeId : null, group, content: `${failPrefix}${baseContent}${fileLine}`.trim(), // ext_id 幂等键需含事件维度:同一业务单在不同事件(创建/完成/审核)应各落一条消息,避免被幂等复用吞掉 extId: payload.businessId ? `${payload.businessId}:${payload.event}` : payload.traceId, extData: group.ext_data || null, }); }); const results = await Promise.all(tasks); const sentCount = results.filter(item => item && item.success).length; const failedCount = results.length - sentCount; const summary = { traceId: payload.traceId, event: payload.event, warehouseId: payload.warehouseId, storeId: payload.storeId, matchedGroupCount: pushGroups.length, sentCount, failedCount, }; if (failedCount > 0) { ctx.logger.warn('[NoticeService.sendToWarehouseChannel] 群推送存在失败', summary); } else { ctx.logger.info('[NoticeService.sendToWarehouseChannel] 群推送完成', summary); } return { success: failedCount === 0, message: failedCount === 0 ? '通知已推送' : `部分群推送失败(${failedCount})`, data: { traceId: payload.traceId, event: payload.event, matchedGroupCount: pushGroups.length, sentCount, failedCount, results, }, }; } /** * 统一通知发送入口:按 channel 路由分发。 * channel=warehouse|group(默认):走仓库接口消息推送(wms_api_app 配置 + 固定群订阅); * channel=webhook:仅使用调用方显式传入的 hooks(不再读取 wms_notification_webhook 表); * channel=both:双通道同时发送。 * @param {object} [options={}] 发送入参 * @return {Promise} 发送汇总结果 */ async send(options = {}) { const payload = await this.normalizePayload(options); const channel = String(options.channel || 'warehouse').trim().toLowerCase(); if (channel === 'warehouse' || channel === 'group') { return await this.sendToWarehouseChannel(payload); } if (channel === 'both') { const [ webhookResult, warehouseResult ] = await Promise.all([ this.sendViaWebhooks(payload), this.sendToWarehouseChannel(payload), ]); const webhookData = (webhookResult && webhookResult.data) || {}; const warehouseData = (warehouseResult && warehouseResult.data) || {}; const sentCount = Number(webhookData.sentCount || 0) + Number(warehouseData.sentCount || 0); const failedCount = Number(webhookData.failedCount || 0) + Number(warehouseData.failedCount || 0); const results = [ ...(Array.isArray(webhookData.results) ? webhookData.results : []), ...(Array.isArray(warehouseData.results) ? warehouseData.results : []), ]; return { success: webhookResult.success && warehouseResult.success, message: `双通道发送完成(webhook ${webhookData.sentCount}/${webhookData.matchedHookCount || 0},群 ${warehouseData.sentCount}/${warehouseData.matchedGroupCount || 0})`, data: { traceId: payload.traceId, event: payload.event, matchedHookCount: Number(webhookData.matchedHookCount || 0), matchedGroupCount: Number(warehouseData.matchedGroupCount || 0), sentCount, failedCount, results, }, }; } return await this.sendViaWebhooks(payload); } /** * 通过调用方显式传入的 hooks 分发(不读取 wms_notification_webhook 表)。 * @param {object} payload 标准化后的消息载荷 * @return {Promise} 发送汇总结果 */ async sendViaWebhooks(payload) { const webhooks = await this.findMatchedWebhooks(payload); if (webhooks.length === 0) { this.ctx.logger.warn('[NoticeService.send] 未匹配到可用 webhook', { traceId: payload.traceId, event: payload.event, warehouseId: payload.warehouseId, storeId: payload.storeId, messageType: payload.message && payload.message.type, }); return { success: true, message: '未匹配到可用 webhook', data: { traceId: payload.traceId, event: payload.event, matchedHookCount: 0, sentCount: 0, failedCount: 0, results: [], }, }; } const tasks = webhooks.map(async hook => await this.sendWithRetry({ hook, payload })); const results = await Promise.all(tasks); const sentCount = results.filter(item => item && item.success).length; const failedCount = results.length - sentCount; const summary = { traceId: payload.traceId, event: payload.event, warehouseId: payload.warehouseId, storeId: payload.storeId, matchedHookCount: webhooks.length, sentCount, failedCount, messageType: payload.message && payload.message.type, }; if (failedCount > 0) { this.ctx.logger.warn('[NoticeService.send] webhook 发送存在失败', summary); } else { this.ctx.logger.info('[NoticeService.send] webhook 发送完成', summary); } return { success: failedCount === 0, message: failedCount === 0 ? '通知已发送' : `部分 webhook 发送失败(${failedCount})`, data: { traceId: payload.traceId, event: payload.event, matchedHookCount: webhooks.length, sentCount, failedCount, results, }, }; } } module.exports = NoticeService;