WMS_MAIN/app/model/notification_webhook.js
liufumingren b5e5d4d588 feat(storeWarehouse,report,notice,order): 签约导出与代开户备注兜底、报表meta下线、入库完成通知与编码规范化
- storeWarehouse: 货主签约列表异步导出 export/exportTaskProgress(26列中文表头Excel+进度回写);openAccount 代开户未传 store_remask(或传空)时默认取公司全称前50字符填充,保证货主名称在列表/导出中始终有值

- report: 下线 report.meta(破坏性),窗口参数改由 definition.typeList、勾选字段经 definition.list 提供;报表投递目标货主状态放宽为 1/2(正常/审核中);reportDelivery 实体展示名称兼容下划线/驼峰并优雅回退 ID

- notice/order: 入库单完成通知货主(entry_order_completed,固定订阅回退链:收货组→售后组→仓库异常群);入库明细 itemId 规范化(非法值降级按 item_code 精确/归一化条码匹配,剥离中文后缀,多命中报错防错配);库存预警定时任务与 webhook 模型调整

- storage: 快捷直入/入库单基本信息等相关小改(inbound_direct_log、storage/entry、storage/inventory)

- docs: methods/system 0.3.62→0.3.63、openapi/qimen 同步,AI_METHOD_ROUTING 与 report-config-guide 同步,methods/changes/*.json 补变更记录
2026-08-31 17:17:48 +08:00

324 lines
10 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';
module.exports = app => {
const { BIGINT, STRING, TINYINT, DATE, JSON: JSON_TYPE, Op } = app.Sequelize;
const normalizeJsonObject = (value, fieldName, { allowArray = false } = {}) => {
if (value === undefined || value === null || value === '') {
return value;
}
if (typeof value === 'string') {
try {
const parsed = JSON.parse(value);
return normalizeJsonObject(parsed, fieldName, { allowArray });
} catch (error) {
throw new Error(`${fieldName} 必须是合法 JSON`);
}
}
if (Array.isArray(value)) {
if (allowArray) {
return value;
}
throw new Error(`${fieldName} 必须是对象`);
}
if (typeof value !== 'object') {
throw new Error(`${fieldName} 必须是对象`);
}
return value;
};
const SPECIAL_EVENT_CODES = new Set([ 'all', '*' ]);
const EVENT_CODE_PATTERN = /^[a-z_][a-z0-9_]*$/;
const isValidEventCode = value => SPECIAL_EVENT_CODES.has(value) || EVENT_CODE_PATTERN.test(value);
const AVAILABLE_EVENTS = Object.freeze([
Object.freeze({ code: 'all', name: '全部事件', business: 'all', description: '订阅后接收所有通知事件' }),
Object.freeze({ code: '*', name: '全部事件(兼容别名)', business: 'all', description: '兼容旧配置,等价于 all' }),
Object.freeze({ code: 'receiving_completed', name: '收货完成', business: 'receiving', description: '收货单完成后的通知' }),
Object.freeze({ code: 'receiving_rejected', name: '收货驳回', business: 'receiving', description: '收货单被驳回并恢复为收货中后的通知' }),
Object.freeze({ code: 'receiving_reviewed', name: '收货审核完成', business: 'receiving', description: '收货单批量审核通过后的通知' }),
Object.freeze({ code: 'receiving_store_bound', name: '收货单创建/绑定货主', business: 'receiving', description: '收货单创建或首次绑定货主时的通知(展示车牌号/快递单号登记状态,未登记显示无)' }),
Object.freeze({ code: 'receiving_store_unmatched', name: '收货完成未匹配商品提醒', business: 'receiving', description: '收货单完成时存在未匹配商品明细,通知货主核实商品资料' }),
Object.freeze({ code: 'entry_order_completed', name: '入库单完成入库', business: 'entry_order', description: '入库单完成入库后的通知,提示货主入库单已完成入库请注意查收' }),
Object.freeze({ code: 'order_sync_completed', name: '订单同步完成', business: 'order', description: '本地创建入口同步完成后的通知' }),
Object.freeze({ code: 'order_cancel_intercepted', name: '订单取消拦截', business: 'order', description: '订单取消失败并触发拦截执行后的通知' }),
Object.freeze({ code: 'wave_strategy_quick_scan_failed', name: '波次策略兜底扫描失败', business: 'order', description: '定时兜底扫描任务在仓库维度触发失败时通知' }),
Object.freeze({
code: 'store_warehouse_print_quantity_adjusted',
name: '货主面单余额调整',
business: 'store_warehouse',
description: '货主-仓库签约下的面单余额被人工调整后的通知',
}),
Object.freeze({
code: 'storage_transfer_completed',
name: '移库操作完成',
business: 'storage',
description: '库存库位转移操作完成后的通知',
}),
]);
const AVAILABLE_EVENT_CODE_SET = new Set(AVAILABLE_EVENTS.map(item => item.code));
const getAvailableEvents = () => AVAILABLE_EVENTS.map(item => ({ ...item }));
const normalizeEvents = value => {
if (value === undefined || value === null || value === '') {
return [];
}
if (Array.isArray(value)) {
return value.map(item => String(item || '').trim()).filter(Boolean);
}
if (typeof value === 'string') {
const trimmed = value.trim();
if (!trimmed) {
return [];
}
try {
const parsed = JSON.parse(trimmed);
if (parsed !== value) {
return normalizeEvents(parsed);
}
} catch (_) {
// ignore parse failure and continue with string split
}
return trimmed.split(/[\s,;|]+/).map(item => item.trim()).filter(Boolean);
}
if (typeof value === 'object') {
if (value.all === true) {
return [ 'all' ];
}
return normalizeEvents(value.include || value.events || []);
}
throw new Error('events 必须是字符串数组或对象');
};
const validateEvents = value => {
if (value === undefined || value === null || value === '') {
return;
}
normalizeJsonObject(value, 'events', { allowArray: true });
const normalizedEvents = normalizeEvents(value);
const invalidFormatEvents = normalizedEvents.filter(item => !isValidEventCode(item));
if (invalidFormatEvents.length > 0) {
throw new Error(`events 中包含非法事件编码(仅支持小写字母、数字、下划线,且首字符不能为数字): ${invalidFormatEvents.join(', ')}`);
}
const invalidEvents = normalizedEvents.filter(item => !AVAILABLE_EVENT_CODE_SET.has(item));
if (invalidEvents.length > 0) {
throw new Error(`events 中包含不支持的事件: ${invalidEvents.join(', ')}`);
}
};
AVAILABLE_EVENTS.forEach(item => {
if (!isValidEventCode(item.code)) {
throw new Error(`通知事件编码不合法: ${item.code}`);
}
});
const NotificationWebhook = app.model.define('notification_webhook', {
id: {
type: BIGINT.UNSIGNED,
primaryKey: true,
autoIncrement: true,
allowNull: false,
comment: '主键ID',
},
store_id: {
type: BIGINT.UNSIGNED,
allowNull: false,
comment: '主体ID,对应 wms_store.id',
references: {
model: 'store',
key: 'id',
},
},
hook_name: {
type: STRING(100),
allowNull: true,
comment: 'Webhook 名称',
},
hook_type: {
type: STRING(50),
allowNull: false,
validate: {
notEmpty: {
msg: 'hook_type 不能为空',
},
len: {
args: [ 1, 50 ],
msg: 'hook_type 长度应在1-50个字符之间',
},
},
comment: 'Webhook 类型,用于区分回调通道,当前支持 customize / wecom',
},
hook_url: {
type: STRING(500),
allowNull: false,
validate: {
notEmpty: {
msg: 'hook_url 不能为空',
},
len: {
args: [ 1, 500 ],
msg: 'hook_url 长度应在1-500个字符之间',
},
},
comment: 'Webhook 链接地址',
},
events: {
type: JSON_TYPE,
allowNull: true,
comment: '订阅事件列表,可从 NotificationWebhook.getAvailableEvents() 拉取',
validate: {
isValidEvents(value) {
validateEvents(value);
},
},
},
status: {
type: TINYINT(4),
allowNull: false,
defaultValue: 1,
validate: {
isIn: {
args: [[ 0, 1 ]],
msg: '状态值不合法,0-禁用,1-启用',
},
},
comment: '状态:0-禁用,1-启用',
},
remark: {
type: STRING(255),
allowNull: true,
comment: '备注',
},
created_by: {
type: BIGINT.UNSIGNED,
allowNull: true,
comment: '创建人',
},
created_at: {
type: DATE,
allowNull: false,
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '创建时间',
},
updated_at: {
type: DATE,
allowNull: false,
defaultValue: app.Sequelize.literal('CURRENT_TIMESTAMP'),
comment: '更新时间',
},
deleted_at: {
type: DATE,
allowNull: true,
comment: '删除时间',
},
}, {
validate: {
async withinStoreWebhookLimit() {
const storeId = Number(this.store_id || 0);
if (!Number.isFinite(storeId) || storeId <= 0) {
return;
}
const store = await app.model.Store.findByPk(storeId, {
attributes: [ 'subject_config' ],
});
const subjectConfig = app.model.Store && typeof app.model.Store.normalizeSubjectConfig === 'function'
? app.model.Store.normalizeSubjectConfig(store && store.subject_config)
: {
max_notice_webhook_count: 5,
default_express_code: 'STO',
default_platform_code: 'TB',
};
const maxWebhookCount = Number(subjectConfig.max_notice_webhook_count || 5);
const where = {
store_id: storeId,
};
if (this.id) {
where.id = {
[Op.ne]: this.id,
};
}
const currentCount = await app.model.NotificationWebhook.count({ where });
if (currentCount >= maxWebhookCount) {
throw new Error(`当前主体最多允许绑定 ${maxWebhookCount} 个消息推送接口`);
}
},
},
tableName: 'wms_notification_webhook',
freezeTableName: true,
underscored: true,
timestamps: true,
createdAt: 'created_at',
updatedAt: 'updated_at',
paranoid: true,
deletedAt: 'deleted_at',
comment: '外部通知 WebHook 配置表',
indexes: [
{
name: 'idx_notification_webhook_store_id',
fields: [ 'store_id' ],
},
{
name: 'idx_notification_webhook_hook_type',
fields: [ 'hook_type' ],
},
{
name: 'idx_notification_webhook_status',
fields: [ 'status' ],
},
{
name: 'idx_notification_webhook_store_type',
fields: [ 'store_id', 'hook_type' ],
},
{
name: 'uk_notification_webhook_store_type_url',
unique: true,
fields: [ 'store_id', 'hook_type', 'hook_url' ],
},
],
});
NotificationWebhook.associate = function() {
const { Store, Account } = app.model;
NotificationWebhook.belongsTo(Store, {
foreignKey: 'store_id',
targetKey: 'id',
as: 'store',
});
NotificationWebhook.belongsTo(Account, {
foreignKey: 'created_by',
targetKey: 'id',
as: 'creator',
constraints: false,
});
};
NotificationWebhook.AVAILABLE_EVENTS = getAvailableEvents();
NotificationWebhook.getAvailableEvents = getAvailableEvents;
NotificationWebhook.getAvailableEventCodes = () => getAvailableEvents().map(item => item.code);
NotificationWebhook.normalizeEvents = normalizeEvents;
NotificationWebhook.prototype.isEnabled = function() {
return Number(this.status) === 1;
};
return NotificationWebhook;
};