liufumingren 9c2b254206 1
Co-authored-by: Copilot <copilot@github.com>
2026-05-11 08:44:27 +08:00

900 lines
30 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 { 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',
'order_cancel_intercepted',
'wave_strategy_quick_scan_failed',
'store_warehouse_print_quantity_adjusted',
]);
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 ? 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 ? 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<void>}
*/
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<void>}
*/
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<object>} 发送结果
*/
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<object>} 货主信息
*/
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 || ''),
};
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 || '');
return {
id: normalizedStore.id,
name: String(cachedStore.name || cachedStore.companyName || cachedStore.company_name || normalizedStore.name || ''),
businessLicense,
storeRemask,
};
}
} 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' ],
})
: null,
]);
const businessLicense = normalizedStore.businessLicense || String(storeRecord && storeRecord.business_license || '');
const storeRemask = normalizedStore.storeRemask || String(relationRecord && relationRecord.store_remask || '');
const resolvedStore = {
id: normalizedStore.id,
name: normalizedStore.name || String(storeRecord && storeRecord.company_name || ''),
businessLicense,
storeRemask,
};
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<object>} 主体配置
*/
async resolveSubjectConfig(options = {}, subject = {}) {
const storeModel = this.ctx.model && this.ctx.model.Store;
const deliveryOrderService = 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<object>} 标准化后的 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,
},
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。
* @param {object} payload 标准化后的消息载荷
* @return {Promise<object[]>} 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);
}
const webhookModel = this.ctx.model && this.ctx.model.NotificationWebhook;
if (!webhookModel || typeof webhookModel.findAll !== 'function') {
return [];
}
const warehouseId = Number(payload.warehouseId || (payload.subject && payload.subject.id) || 0);
const storeId = Number(payload.storeId || (payload.store && payload.store.id) || 0);
const targetSubjectIds = [];
if (Number.isFinite(warehouseId) && warehouseId > 0) {
targetSubjectIds.push(warehouseId);
}
if (Number.isFinite(storeId) && storeId > 0 && !targetSubjectIds.includes(storeId)) {
targetSubjectIds.push(storeId);
}
if (targetSubjectIds.length === 0) {
return [];
}
const webhookGroups = await Promise.all(targetSubjectIds.map(async currentSubjectId => {
const where = {
store_id: currentSubjectId,
status: 1,
};
if (payload.hookType) {
where.hook_type = payload.hookType;
}
const webhooks = await webhookModel.findAll({
where,
order: [[ 'id', 'ASC' ]],
});
return webhooks
.filter(item => this.matchesEvents(item && item.events, payload))
.slice(0, webhookLimit);
}));
const flattenedWebhooks = webhookGroups.flat();
const seen = new Set();
return flattenedWebhooks.filter(item => {
const dedupeKey = item && item.id ? `id:${item.id}` : `url:${String(item && item.hook_url || '')}`;
if (seen.has(dedupeKey)) {
return false;
}
seen.add(dedupeKey);
return true;
});
}
/**
* 统一通知发送入口:规范化消息、匹配 webhook 并执行分发。
* @param {object} [options={}] 发送入参
* @return {Promise<object>} 发送汇总结果
*/
async send(options = {}) {
const payload = await this.normalizePayload(options);
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;