WMS_MAIN/app/model/notification_webhook.js
liufumingren 1571de341c feat(storage): 新增收货未入库提醒定时任务(货主/客服群通知,短语可配置)
- 新增 app/service/systems/receiving_pending_notice.js:扫描「创建时间超过 min_hours 且不足 max_hours 仍未完成入库」的收货单(wms_receiving 未作废、is_deleted=0,且 status=receiving 或 storage_status<>all),
  按货主聚合成一条消息;未绑定货主的单独一批
- 新增 app/schedule/notice_receiving_pending_inbound.js:每 5 分钟单 worker 检查,按各仓库配置的提醒时间(默认 08:30,宽限 10 分钟覆盖调度抖动)执行,
  进程内防重入 + Redis 当日锁 receiving_pending_notice🔒{warehouseId}:{YYYYMMDD}(NX/EX 24h,执行异常释放锁允许窗口内重试),保证每仓库每天只提醒一次
- 仓库设置新增字段 wms_store.subject_config.receiving_pending_inbound_notice:
  enabled(是否通知收货未入库,flag,默认 0 关闭)/ notice_time(提醒时间 HH:mm,默认 08:30)/ min_hours(超时下限,默认 24)/ max_hours(超时上限,默认 48,须大于 min_hours)
  / notice_template(仓库客服群通知短语)/ store_notice_template(货主群通知短语)
- 通知短语可配置并支持变量替换:{warehouse} {warehouse_id} {store} {store_id} {count} {min_hours} {max_hours} {date} {numbers};
  未识别占位符原样保留,留空回退默认短语,最长 500 字符(超长 400)
- 消息结构统一为「短语 + 换行 + 明细(一行一条,最多 20 行,超出提示剩余单数)+ 快速查看/详情查看链接」,不再在结尾追加句号
- 新增通知事件 receiving_pending_inbound(notification_webhook 事件注册 + notice DEFAULT_REGISTERED_EVENT_CODES)与固定群订阅:
  store:receiving,fallbackTargets=warehouse:customer_service —— 有货主推货主收货群,无货主或货主未配收货群时推仓库客服群(出站仍走 notify.reply,落 wms_inbox_message)
- 文档:methods/system.json 的 setting.warehouse.getSettings/saveSettings 补充该配置字段(版本 0.3.129 -> 0.3.131),
  变更记录新增 2026.09.15-warehouse-pending-receiving-notice / -notice-template(system)、2026-09-15-warehouse-01 / -02(warehouse,事件注册与文案结构);
  AI_METHOD_ROUTING.md 同步刷新(新服务 14 个方法)
- 单测 test/app/service/systems/receiving_pending_notice.test.js(11 用例:开关关闭/未命中提醒时间不执行、超时窗口查询条件、货主群通知、无货主回退客服群、
  当日只提醒一次、推送失败不重复、扫描异常释放锁重试、行数截断、非法配置回退默认、短语变量替换与明细逐行、未识别占位符保留)全部通过;npx eslint 无告警

同时提交上一轮未提交的 camera/PTZ 改动(app/lib/ptz_client.js 新增、systems/camera.js 与 systemMethods/camera.js:PTZ 下发给打印服务时请求体统一携带 cameraId),
其文档与路由清单改动与本提交共用 methods/system.json 等文件,无法按行安全拆分,故合并为一次提交。
2026-09-15 23:49:34 +08:00

325 lines
11 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: 'receiving_pending_inbound', 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;
};