WMS_MAIN/test/app/service/systems/notice.test.js
liufumingren 7ad08e488d feat(notice): 统一通知仓库接口通道与订单同步通知去抖
- warehouseNotify: 按固定群订阅经 wms_api_app 回调推送(MD5 验签),消息表登记+失败重试
- notice: 货主群缺失时降级发仓库异常群(前缀标记失败),合约停用/已解除货主不发货主群也不降级
- order_async: 订单同步通知 3 分钟去抖合并,Redis 队列+定时冲刷+失败重试
- receiving: 收货完成/驳回/审核通知走仓库通道,仓库/货主侧文案分离
- storage/inventory: 移除移库完成群通知(事件码保留,库存余量提醒仍复用)
- 新增 debug:warehouse:push-receiver 调试接收服务与文档/变更记录
2026-08-17 02:03:34 +08:00

719 lines
20 KiB
JavaScript

'use strict';
const assert = require('node:assert/strict');
const NoticeService = require('../../../../app/service/systems/notice');
const defineNotificationWebhook = require('../../../../app/model/notification_webhook');
describe('test/app/service/systems/notice.test.js', () => {
it('should normalize payload and send only matching webhooks', async () => {
const sentRequests = [];
const webhookRows = [
{
id: 1,
store_id: 100000,
hook_type: 'custom',
hook_url: 'https://example.com/webhook/a',
events: [ 'receiving_completed' ],
},
{
id: 2,
store_id: 100000,
hook_type: 'custom',
hook_url: 'https://example.com/webhook/b',
events: [ 'stock.low' ],
},
];
const ctx = {
app: {
config: {},
},
model: {
NotificationWebhook: {
async findAll({ where }) {
assert.equal(Number(where.store_id), 100000);
assert.equal(Number(where.status), 1);
return webhookRows;
},
},
},
logger: {
info() {},
warn() {},
error() {},
},
async curl(url, options) {
sentRequests.push({ url, options });
return {
status: 200,
data: { ok: true },
};
},
};
const service = new NoticeService(ctx);
const result = await service.send({
channel: 'webhook',
hooks: webhookRows,
messageType: '图片',
businessName: 'receiving',
event: 'receiving_completed',
subject: {
id: 100000,
type: 'warehouse',
name: '测试主体',
},
subjectConfig: {
webhook_enabled: true,
callback_strategy: 'async',
max_notice_webhook_count: 5,
},
title: '收货完成',
content: '本次收货已完成',
url: 'https://cdn.example.com/demo.png',
businessId: 256,
metadata: {
source: 'unit-test',
},
});
assert.equal(result.success, true);
assert.equal(Number(result.data.matchedHookCount), 1);
assert.equal(Number(result.data.sentCount), 1);
assert.equal(sentRequests.length, 1);
assert.equal(sentRequests[0].url, 'https://example.com/webhook/a');
assert.equal(sentRequests[0].options.method, 'POST');
assert.equal(sentRequests[0].options.data.event, 'receiving_completed');
assert.equal(sentRequests[0].options.data.message.type, 'image');
assert.equal(sentRequests[0].options.data.message.url, 'https://cdn.example.com/demo.png');
assert.equal(sentRequests[0].options.data.subject.config.webhook_enabled, true);
assert.equal(sentRequests[0].options.data.subject.config.callback_strategy, 'async');
assert.equal(Number(sentRequests[0].options.data.subject.config.max_notice_webhook_count), 5);
});
it('should enrich payload with store info from cache before querying database', async () => {
let storeLookupCount = 0;
let relationLookupCount = 0;
const ctx = {
app: {
config: {},
async getCacheAsync(cacheKey) {
assert.equal(cacheKey, 'warehouse:100000store:1000000:info');
return {
id: 1000000,
name: '缓存货主',
businessLicense: 'BL-CACHE-001',
storeRemask: '缓存备注',
};
},
},
model: {
Store: {
async findByPk() {
storeLookupCount += 1;
return null;
},
},
StoreWarehouse: {
async findOne() {
relationLookupCount += 1;
return null;
},
},
},
logger: {
info() {},
warn() {},
error() {},
},
};
const service = new NoticeService(ctx);
const payload = await service.normalizePayload({
messageType: '文本',
businessName: 'receiving',
event: 'receiving_completed',
subject: {
id: 100000,
type: 'warehouse',
},
subjectConfig: {
max_notice_webhook_count: 5,
},
storeId: 1000000,
content: '缓存优先',
});
assert.equal(payload.store.id, 1000000);
assert.equal(payload.store.name, '缓存货主');
assert.equal(payload.store.businessLicense, 'BL-CACHE-001');
assert.equal(payload.store.storeRemask, '缓存备注');
assert.equal(Object.prototype.hasOwnProperty.call(payload.store, 'business_license'), false);
assert.equal(Object.prototype.hasOwnProperty.call(payload.store, 'store_remask'), false);
assert.equal(storeLookupCount, 0);
assert.equal(relationLookupCount, 0);
});
it('should load store info from database and cache it when cache is empty', async () => {
let cachedPayload = null;
const ctx = {
app: {
config: {},
async getCacheAsync(cacheKey) {
assert.equal(cacheKey, 'warehouse:100000store:1000000:info');
return null;
},
async setCacheAsync(cacheKey, data, ttl) {
cachedPayload = { cacheKey, data, ttl };
},
},
model: {
Store: {
async findByPk(id) {
assert.equal(Number(id), 1000000);
return {
id: 1000000,
company_name: '测试货主',
business_license: 'BL-DB-001',
};
},
},
StoreWarehouse: {
async findOne({ where }) {
assert.equal(Number(where.store_id), 1000000);
assert.equal(Number(where.warehouse_id), 100000);
return {
store_remask: '数据库备注',
};
},
},
},
logger: {
info() {},
warn() {},
error() {},
},
};
const service = new NoticeService(ctx);
const payload = await service.normalizePayload({
messageType: '文本',
businessName: 'receiving',
event: 'receiving_completed',
subject: {
id: 100000,
type: 'warehouse',
},
subjectConfig: {
max_notice_webhook_count: 5,
},
ownerId: 1000000,
content: '查库回填',
});
assert.equal(payload.store.id, 1000000);
assert.equal(payload.store.name, '测试货主');
assert.equal(payload.store.businessLicense, 'BL-DB-001');
assert.equal(payload.store.storeRemask, '数据库备注');
assert.equal(Object.prototype.hasOwnProperty.call(payload.store, 'business_license'), false);
assert.equal(Object.prototype.hasOwnProperty.call(payload.store, 'store_remask'), false);
assert.equal(cachedPayload.cacheKey, 'warehouse:100000store:1000000:info');
assert.equal(cachedPayload.ttl, 600);
assert.equal(cachedPayload.data.businessLicense, 'BL-DB-001');
assert.equal(Object.prototype.hasOwnProperty.call(cachedPayload.data, 'business_license'), false);
});
it('should send to both warehouse and owner webhooks when events match or are set to all', async () => {
const sentRequests = [];
const ctx = {
app: {
config: {},
},
model: {
NotificationWebhook: {
async findAll({ where }) {
if (Number(where.store_id) === 100000) {
return [
{
id: 1,
store_id: 100000,
hook_type: 'custom',
hook_url: 'https://example.com/webhook/warehouse',
events: [ 'all' ],
},
];
}
if (Number(where.store_id) === 1000000) {
return [
{
id: 2,
store_id: 1000000,
hook_type: 'custom',
hook_url: 'https://example.com/webhook/store',
events: [ 'receiving' ],
},
];
}
return [];
},
},
},
logger: {
info() {},
warn() {},
error() {},
},
async curl(url, options) {
sentRequests.push({ url, options });
return {
status: 200,
data: { ok: true },
};
},
};
const service = new NoticeService(ctx);
const result = await service.send({
channel: 'webhook',
hooks: [
{
id: 1,
store_id: 100000,
hook_type: 'custom',
hook_url: 'https://example.com/webhook/warehouse',
events: [ 'all' ],
},
{
id: 2,
store_id: 1000000,
hook_type: 'custom',
hook_url: 'https://example.com/webhook/store',
events: [ 'receiving' ],
},
],
messageType: '文本',
businessName: 'receiving',
event: 'receiving_completed',
warehouseId: 100000,
storeId: 1000000,
subject: {
id: 100000,
type: 'warehouse',
},
subjectConfig: {
max_notice_webhook_count: 5,
},
content: '仓库和货主都应接收',
});
assert.equal(result.success, true);
assert.equal(Number(result.data.matchedHookCount), 2);
assert.equal(Number(result.data.sentCount), 2);
assert.equal(sentRequests.length, 2);
assert.ok(sentRequests.some(item => item.url === 'https://example.com/webhook/warehouse'));
assert.ok(sentRequests.some(item => item.url === 'https://example.com/webhook/store'));
});
it('should only send up to the configured webhook limit', async () => {
const sentRequests = [];
const webhookRows = Array.from({ length: 6 }).map((_, index) => ({
id: index + 1,
store_id: 100000,
hook_type: 'custom',
hook_url: `https://example.com/webhook/${index + 1}`,
events: [ 'receiving_completed' ],
}));
const ctx = {
app: {
config: {},
},
model: {
NotificationWebhook: {
async findAll() {
return webhookRows;
},
},
},
logger: {
info() {},
warn() {},
error() {},
},
async curl(url, options) {
sentRequests.push({ url, options });
return {
status: 200,
data: { ok: true },
};
},
};
const service = new NoticeService(ctx);
const result = await service.send({
channel: 'webhook',
hooks: webhookRows,
messageType: '文本',
businessName: 'receiving',
event: 'receiving_completed',
subject: {
id: 100000,
type: 'warehouse',
},
subjectConfig: {
max_notice_webhook_count: 5,
},
content: '只允许发送前五个',
});
assert.equal(result.success, true);
assert.equal(Number(result.data.matchedHookCount), 5);
assert.equal(Number(result.data.sentCount), 5);
assert.equal(sentRequests.length, 5);
assert.equal(sentRequests[4].url, 'https://example.com/webhook/5');
});
it('should require url for image or file message', async () => {
const ctx = {
app: {
config: {},
},
model: {
NotificationWebhook: {
async findAll() {
return [];
},
},
},
logger: {
info() {},
warn() {},
error() {},
},
async curl() {
return { status: 200 };
},
};
const service = new NoticeService(ctx);
await assert.rejects(async () => {
await service.send({
messageType: '文件',
businessName: 'receiving',
warehouseId: 100000,
subject: { id: 100000 },
content: '请查看附件',
});
}, /url/);
});
it('should require warehouseId but allow empty ownerId', async () => {
const ctx = {
app: {
config: {},
},
model: {
NotificationWebhook: {
async findAll() {
return [];
},
},
},
logger: {
info() {},
warn() {},
error() {},
},
async curl() {
return { status: 200 };
},
};
const service = new NoticeService(ctx);
await assert.rejects(async () => {
await service.normalizePayload({
messageType: '文本',
businessName: 'receiving',
content: '未传仓库',
});
}, /warehouseId/);
const payload = await service.normalizePayload({
messageType: '文本',
businessName: 'receiving',
event: 'receiving_completed',
warehouseId: 100000,
content: '允许货主为空',
});
assert.equal(payload.subject.id, 100000);
assert.equal(payload.store.id, null);
assert.equal(payload.store.businessLicense, '');
assert.equal(payload.store.storeRemask, '');
});
it('should retry failed webhooks three times and persist final failures', async () => {
const sentRequests = [];
const sleepCalls = [];
const failureLogs = [];
let attempt = 0;
const ctx = {
app: {
config: {},
},
service: {},
model: {
NotificationSendLog: {
async create(data) {
failureLogs.push(data);
return data;
},
},
},
logger: {
info() {},
warn() {},
error() {},
},
async curl(url, options) {
sentRequests.push({ url, options });
attempt += 1;
throw new Error(`network fail ${attempt}`);
},
};
const service = new NoticeService(ctx);
service.sleep = async ms => {
sleepCalls.push(ms);
};
const result = await service.send({
channel: 'webhook',
hooks: [{
id: 9,
store_id: 1000000,
hook_type: 'custom',
hook_url: 'https://example.com/webhook/fail',
events: [ 'all' ],
}],
messageType: '文本',
businessName: 'receiving',
event: 'receiving_completed',
warehouseId: 100000,
content: '失败后重试',
});
assert.equal(result.success, false);
assert.equal(Number(result.data.matchedHookCount), 1);
assert.equal(Number(result.data.sentCount), 0);
assert.equal(Number(result.data.failedCount), 1);
assert.equal(sentRequests.length, 4);
assert.deepEqual(sleepCalls, [ 3000, 6000, 12000 ]);
assert.equal(failureLogs.length, 1);
assert.equal(Number(failureLogs[0].retry_count), 3);
assert.equal(String(failureLogs[0].event), 'receiving_completed');
assert.match(String(failureLogs[0].error_message || ''), /network fail/);
});
it('should reject sending unregistered event', async () => {
const ctx = {
app: {
config: {},
},
service: {},
model: {
NotificationWebhook: {
getAvailableEventCodes() {
return [ 'all', '*', 'receiving_completed' ];
},
async findAll() {
return [];
},
},
},
logger: {
info() {},
warn() {},
error() {},
},
async curl() {
return { status: 200, data: '1' };
},
};
const service = new NoticeService(ctx);
await assert.rejects(async () => {
await service.send({
warehouseId: 100000,
businessName: 'receiving',
event: 'receiving_image',
messageType: 'image',
title: '未注册事件测试',
content: '这条消息不应发出',
url: 'https://example.com/demo.jpg',
});
}, /未注册|不允许发送/);
});
it('should reject dotted or numeric-leading event names', async () => {
const ctx = {
app: {
config: {},
},
service: {},
model: {
NotificationWebhook: {
getAvailableEventCodes() {
return [ 'all', '*', 'receiving_completed' ];
},
async findAll() {
return [];
},
},
},
logger: {
info() {},
warn() {},
error() {},
},
async curl() {
return { status: 200, data: '1' };
},
};
const service = new NoticeService(ctx);
await assert.rejects(async () => {
await service.send({
warehouseId: 100000,
businessName: 'receiving',
event: 'receiving.completed',
messageType: 'text',
content: '点号事件名不合法',
});
}, /命名不合法/);
await assert.rejects(async () => {
await service.send({
warehouseId: 100000,
businessName: 'receiving',
event: '1receiving_completed',
messageType: 'text',
content: '数字开头事件名不合法',
});
}, /命名不合法/);
});
it('should send wecom webhook as enterprise wechat direct message', async () => {
const sentRequests = [];
const ctx = {
app: {
config: {},
},
service: {},
model: {
NotificationWebhook: {
getAvailableEventCodes() {
return [ 'all', '*', 'receiving_completed' ];
},
},
},
logger: {
info() {},
warn() {},
error() {},
},
async curl(url, options) {
sentRequests.push({ url, options });
return {
status: 200,
data: {
errcode: 0,
errmsg: 'ok',
},
};
},
};
const service = new NoticeService(ctx);
const result = await service.send({
channel: 'webhook',
hooks: [{
id: 21,
store_id: 1000000,
hook_type: 'wecom',
hook_url: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=test-key',
events: [ 'receiving_completed' ],
}],
warehouseId: 100000,
businessName: 'receiving',
event: 'receiving_completed',
messageType: 'text',
title: '收货完成通知',
content: '收货单已完成',
subject: {
id: 100000,
type: 'warehouse',
name: '测试仓',
},
});
assert.equal(result.success, true);
assert.equal(sentRequests.length, 1);
assert.equal(sentRequests[0].url, 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=test-key');
assert.equal(sentRequests[0].options.data.msgtype, 'text');
assert.match(String(sentRequests[0].options.data.text.content || ''), /收货完成通知/);
assert.equal(result.data.results[0].hookType, 'wecom');
});
it('should expose available webhook events and reject unsupported ones', () => {
const fakeType = () => ({});
const app = {
Sequelize: {
BIGINT: { UNSIGNED: {} },
STRING: fakeType,
TINYINT: fakeType,
DATE: {},
JSON: {},
Op: {
ne: Symbol('ne'),
},
literal: value => value,
},
model: {
define(name, attrs) {
return {
rawAttributes: attrs,
prototype: {},
belongsTo() {},
hasMany() {},
};
},
Store: {
normalizeSubjectConfig() {
return {
max_notice_webhook_count: 5,
};
},
},
},
};
const NotificationWebhook = defineNotificationWebhook(app);
const availableEvents = NotificationWebhook.getAvailableEvents();
assert.ok(Array.isArray(availableEvents));
assert.ok(availableEvents.some(item => item.code === 'all'));
assert.ok(availableEvents.some(item => item.code === 'receiving_completed'));
assert.ok(availableEvents.some(item => item.code === 'order_cancel_intercepted'));
assert.doesNotThrow(() => NotificationWebhook.rawAttributes.events.validate.isValidEvents([ 'all', 'receiving_completed' ]));
assert.throws(() => NotificationWebhook.rawAttributes.events.validate.isValidEvents([ 'receiving.completed' ]), /不支持|非法/);
assert.throws(() => NotificationWebhook.rawAttributes.events.validate.isValidEvents([ '1receiving_completed' ]), /不支持|非法/);
assert.throws(() => NotificationWebhook.rawAttributes.events.validate.isValidEvents([ 'unknown_event' ]), /不支持|非法/);
});
});