feat(notice): 统一通知仓库接口通道与订单同步通知去抖
- warehouseNotify: 按固定群订阅经 wms_api_app 回调推送(MD5 验签),消息表登记+失败重试 - notice: 货主群缺失时降级发仓库异常群(前缀标记失败),合约停用/已解除货主不发货主群也不降级 - order_async: 订单同步通知 3 分钟去抖合并,Redis 队列+定时冲刷+失败重试 - receiving: 收货完成/驳回/审核通知走仓库通道,仓库/货主侧文案分离 - storage/inventory: 移除移库完成群通知(事件码保留,库存余量提醒仍复用) - 新增 debug:warehouse:push-receiver 调试接收服务与文档/变更记录
This commit is contained in:
parent
d5c5c641d2
commit
7ad08e488d
51
app/schedule/order_sync_notice_flush.js
Normal file
51
app/schedule/order_sync_notice_flush.js
Normal file
@ -0,0 +1,51 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const FLUSH_TASK_NAME = 'order_sync_notice_flush';
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
schedule: {
|
||||||
|
interval: '30s',
|
||||||
|
type: 'worker',
|
||||||
|
immediate: false,
|
||||||
|
disable: false,
|
||||||
|
},
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 冲刷合并的订单同步通知。
|
||||||
|
* 订单同步完成后不立即通知,等待 3 分钟去抖窗口结束,
|
||||||
|
* 由本任务把同一「仓库:货主」维度的订单合并为一条消息统一推送。
|
||||||
|
*
|
||||||
|
* @param {Object} ctx Egg 上下文。
|
||||||
|
* @return {Promise<void>} 无返回值。
|
||||||
|
*/
|
||||||
|
async task(ctx) {
|
||||||
|
if (ctx.app._orderSyncNoticeFlushRunning) {
|
||||||
|
ctx.logger.info(`[${FLUSH_TASK_NAME}] 任务仍在运行中,跳过本轮调度`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
ctx.app._orderSyncNoticeFlushRunning = true;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const orderAsyncService = ctx.service && ctx.service.systems && ctx.service.systems.orderAsync;
|
||||||
|
if (!orderAsyncService || typeof orderAsyncService.flushDeferredOrderSyncNotices !== 'function') {
|
||||||
|
ctx.logger.warn(`[${FLUSH_TASK_NAME}] orderAsync 服务不可用,跳过本轮`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await orderAsyncService.flushDeferredOrderSyncNotices();
|
||||||
|
|
||||||
|
ctx.logger.info(`[${FLUSH_TASK_NAME}] 本轮完成`, {
|
||||||
|
skipped: !!(result && result.skipped),
|
||||||
|
reason: result && result.reason,
|
||||||
|
flushedCount: result && result.flushedCount,
|
||||||
|
failedCount: result && result.failedCount,
|
||||||
|
skippedCount: result && result.skippedCount,
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
ctx.logger.error(`[${FLUSH_TASK_NAME}] 执行失败: ${error && error.message || error}`);
|
||||||
|
} finally {
|
||||||
|
ctx.app._orderSyncNoticeFlushRunning = false;
|
||||||
|
}
|
||||||
|
},
|
||||||
|
};
|
||||||
@ -28,6 +28,41 @@ const DEFAULT_REGISTERED_EVENT_CODES = Object.freeze([
|
|||||||
'wave_strategy_quick_scan_failed',
|
'wave_strategy_quick_scan_failed',
|
||||||
'store_warehouse_print_quantity_adjusted',
|
'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' }),
|
||||||
|
Object.freeze({ groupType: 'store', subType: 'receiving' }),
|
||||||
|
]),
|
||||||
|
receiving_rejected: Object.freeze([
|
||||||
|
Object.freeze({ groupType: 'warehouse', subType: 'receiving' }),
|
||||||
|
Object.freeze({ groupType: 'store', subType: 'receiving' }),
|
||||||
|
]),
|
||||||
|
receiving_reviewed: Object.freeze([
|
||||||
|
Object.freeze({ groupType: 'warehouse', subType: 'receiving' }),
|
||||||
|
Object.freeze({ groupType: 'store', subType: 'receiving' }),
|
||||||
|
]),
|
||||||
|
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({
|
const DRIVER_TYPE_ALIASES = Object.freeze({
|
||||||
custom: 'customize',
|
custom: 'customize',
|
||||||
customize: 'customize',
|
customize: 'customize',
|
||||||
@ -503,6 +538,12 @@ class NoticeService extends Service {
|
|||||||
name: String(directStore.name || directStore.companyName || directStore.company_name || ''),
|
name: String(directStore.name || directStore.companyName || directStore.company_name || ''),
|
||||||
businessLicense: String(directStore.businessLicense || directStore.business_license || ''),
|
businessLicense: String(directStore.businessLicense || directStore.business_license || ''),
|
||||||
storeRemask: String(directStore.storeRemask || directStore.store_remask || directStore.remask || ''),
|
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) {
|
if (!Number.isFinite(storeId) || storeId <= 0) {
|
||||||
@ -519,11 +560,19 @@ class NoticeService extends Service {
|
|||||||
if (cachedStore && Object.keys(cachedStore).length > 0) {
|
if (cachedStore && Object.keys(cachedStore).length > 0) {
|
||||||
const businessLicense = String(cachedStore.businessLicense || cachedStore.business_license || normalizedStore.businessLicense || '');
|
const businessLicense = String(cachedStore.businessLicense || cachedStore.business_license || normalizedStore.businessLicense || '');
|
||||||
const storeRemask = String(cachedStore.storeRemask || cachedStore.store_remask || cachedStore.remask || normalizedStore.storeRemask || '');
|
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 {
|
return {
|
||||||
id: normalizedStore.id,
|
id: normalizedStore.id,
|
||||||
name: String(cachedStore.name || cachedStore.companyName || cachedStore.company_name || normalizedStore.name || ''),
|
name: String(cachedStore.name || cachedStore.companyName || cachedStore.company_name || normalizedStore.name || ''),
|
||||||
businessLicense,
|
businessLicense,
|
||||||
storeRemask,
|
storeRemask,
|
||||||
|
warehouseUseStatus,
|
||||||
|
authStatus,
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@ -547,18 +596,26 @@ class NoticeService extends Service {
|
|||||||
warehouse_id: warehouseId,
|
warehouse_id: warehouseId,
|
||||||
store_id: storeId,
|
store_id: storeId,
|
||||||
},
|
},
|
||||||
attributes: [ 'store_remask' ],
|
attributes: [ 'store_remask', 'warehouse_use_status', 'auth_status' ],
|
||||||
})
|
})
|
||||||
: null,
|
: null,
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const businessLicense = normalizedStore.businessLicense || String(storeRecord && storeRecord.business_license || '');
|
const businessLicense = normalizedStore.businessLicense || String(storeRecord && storeRecord.business_license || '');
|
||||||
const storeRemask = normalizedStore.storeRemask || String(relationRecord && relationRecord.store_remask || '');
|
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 = {
|
const resolvedStore = {
|
||||||
id: normalizedStore.id,
|
id: normalizedStore.id,
|
||||||
name: normalizedStore.name || String(storeRecord && storeRecord.company_name || ''),
|
name: normalizedStore.name || String(storeRecord && storeRecord.company_name || ''),
|
||||||
businessLicense,
|
businessLicense,
|
||||||
storeRemask,
|
storeRemask,
|
||||||
|
warehouseUseStatus,
|
||||||
|
authStatus,
|
||||||
};
|
};
|
||||||
|
|
||||||
if (canUseCache && this.app && typeof this.app.setCacheAsync === 'function') {
|
if (canUseCache && this.app && typeof this.app.setCacheAsync === 'function') {
|
||||||
@ -580,7 +637,7 @@ class NoticeService extends Service {
|
|||||||
*/
|
*/
|
||||||
async resolveSubjectConfig(options = {}, subject = {}) {
|
async resolveSubjectConfig(options = {}, subject = {}) {
|
||||||
const storeModel = this.ctx.model && this.ctx.model.Store;
|
const storeModel = this.ctx.model && this.ctx.model.Store;
|
||||||
const deliveryOrderService = this.ctx.service.systems && this.ctx.service.systems.deliveryOrder;
|
const deliveryOrderService = this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.deliveryOrder;
|
||||||
const normalizeSubjectConfig = value => {
|
const normalizeSubjectConfig = value => {
|
||||||
if (storeModel && typeof storeModel.normalizeSubjectConfig === 'function') {
|
if (storeModel && typeof storeModel.normalizeSubjectConfig === 'function') {
|
||||||
return storeModel.normalizeSubjectConfig(value);
|
return storeModel.normalizeSubjectConfig(value);
|
||||||
@ -711,6 +768,7 @@ class NoticeService extends Service {
|
|||||||
mimeType: String(options.mimeType || options.contentType || ''),
|
mimeType: String(options.mimeType || options.contentType || ''),
|
||||||
body: contentSource,
|
body: contentSource,
|
||||||
},
|
},
|
||||||
|
storeContent: String(options.storeContent || options.store_content || '').trim(),
|
||||||
metadata: this.toObject(options.metadata, {}),
|
metadata: this.toObject(options.metadata, {}),
|
||||||
raw: options,
|
raw: options,
|
||||||
};
|
};
|
||||||
@ -757,7 +815,7 @@ class NoticeService extends Service {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* 根据主体、事件和上限筛选本次需要触达的 webhook。
|
* 筛选本次需要触达的 webhook(仅支持调用方显式传入的 hooks,不再读取 wms_notification_webhook 表)。
|
||||||
* @param {object} payload 标准化后的消息载荷
|
* @param {object} payload 标准化后的消息载荷
|
||||||
* @return {Promise<object[]>} webhook 列表
|
* @return {Promise<object[]>} webhook 列表
|
||||||
*/
|
*/
|
||||||
@ -773,67 +831,360 @@ class NoticeService extends Service {
|
|||||||
.slice(0, webhookLimit);
|
.slice(0, webhookLimit);
|
||||||
}
|
}
|
||||||
|
|
||||||
const webhookModel = this.ctx.model && this.ctx.model.NotificationWebhook;
|
return [];
|
||||||
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 {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<object[]>} 目标群列表
|
||||||
|
*/
|
||||||
|
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,
|
||||||
|
},
|
||||||
|
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 || '',
|
||||||
|
}));
|
||||||
|
} catch (error) {
|
||||||
|
this.ctx.logger.warn(`[NoticeService.findSubscribedGroups] 查询订阅群失败: ${error.message}`);
|
||||||
|
return [];
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析降级通知中的货主名称:优先取合约表(wms_store_warehouse)货主备注 storeRemask,
|
||||||
|
* 其次货主名称,均缺失时按 storeId 回查合约表/货主表,查不到再回退「货主{storeId}」/「货主」。
|
||||||
|
* @param {object} payload 标准化后的消息载荷
|
||||||
|
* @return {Promise<string>} 货主名称
|
||||||
|
*/
|
||||||
|
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<object>} 发送汇总结果
|
||||||
|
*/
|
||||||
|
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 groups = await this.findSubscribedGroups(payload);
|
||||||
|
|
||||||
|
// 货主目标群未配置时,降级发送到仓库异常群,内容前缀标记失败
|
||||||
|
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);
|
||||||
|
|
||||||
|
const effectiveGroups = storeContractInactive
|
||||||
|
? groups.filter(group => group && group.group_type !== 'store')
|
||||||
|
: groups;
|
||||||
|
const storeGroupMatched = effectiveGroups.some(group => group && group.group_type === 'store');
|
||||||
|
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(effectiveGroups.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 = [ ...effectiveGroups, ...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(),
|
||||||
|
extId: payload.businessId || payload.traceId,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
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={}] 发送入参
|
* @param {object} [options={}] 发送入参
|
||||||
* @return {Promise<object>} 发送汇总结果
|
* @return {Promise<object>} 发送汇总结果
|
||||||
*/
|
*/
|
||||||
async send(options = {}) {
|
async send(options = {}) {
|
||||||
const payload = await this.normalizePayload(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<object>} 发送汇总结果
|
||||||
|
*/
|
||||||
|
async sendViaWebhooks(payload) {
|
||||||
const webhooks = await this.findMatchedWebhooks(payload);
|
const webhooks = await this.findMatchedWebhooks(payload);
|
||||||
|
|
||||||
if (webhooks.length === 0) {
|
if (webhooks.length === 0) {
|
||||||
|
|||||||
@ -11,6 +11,16 @@ const TRANSACTION_LOCK_RETRY_BASE_DELAY_MS = 50;
|
|||||||
const DISPATCH_BATCH_SIZE = 20;
|
const DISPATCH_BATCH_SIZE = 20;
|
||||||
const SYNC_ORDER_IDS_PROGRESS_CACHE_TTL = 7200;
|
const SYNC_ORDER_IDS_PROGRESS_CACHE_TTL = 7200;
|
||||||
|
|
||||||
|
// 订单同步通知合并去抖:最后一次同步后等待 3 分钟无新同步,再统一推送一条消息
|
||||||
|
const ORDER_SYNC_NOTICE_DEBOUNCE_MS = 3 * 60 * 1000;
|
||||||
|
const ORDER_SYNC_NOTICE_RETRY_MS = 2 * 60 * 1000;
|
||||||
|
const ORDER_SYNC_NOTICE_MAX_RETRIES = 5;
|
||||||
|
const ORDER_SYNC_NOTICE_KEY_PREFIX = 'order_sync_notice';
|
||||||
|
const ORDER_SYNC_NOTICE_FLUSH_BATCH_SIZE = 50;
|
||||||
|
const ORDER_SYNC_NOTICE_MAX_ORDER_LINES = 30;
|
||||||
|
const ORDER_SYNC_NOTICE_LIST_TTL_SECONDS = 24 * 60 * 60;
|
||||||
|
const ORDER_SYNC_NOTICE_LOCK_TTL_SECONDS = 120;
|
||||||
|
|
||||||
function getSyncOrderIdsProgressCacheKey(requestId) {
|
function getSyncOrderIdsProgressCacheKey(requestId) {
|
||||||
if (!requestId) return null;
|
if (!requestId) return null;
|
||||||
return `order:pending:sync_order_ids:request:${String(requestId).trim()}`;
|
return `order:pending:sync_order_ids:request:${String(requestId).trim()}`;
|
||||||
@ -710,16 +720,18 @@ async function processManualOrderInternal(service, orderModel, orderItemsModel,
|
|||||||
delivery_order_code: String(orderRow.delivery_order_code || '').trim(),
|
delivery_order_code: String(orderRow.delivery_order_code || '').trim(),
|
||||||
store_id: Number(orderRow && orderRow.store_id) || 0,
|
store_id: Number(orderRow && orderRow.store_id) || 0,
|
||||||
waybill_code: resolvedWaybillCodes,
|
waybill_code: resolvedWaybillCodes,
|
||||||
|
receiver_name: String(orderRow.name || '').trim(),
|
||||||
|
receiver_phone: String(orderRow.mobile || orderRow.tel || '').trim(),
|
||||||
warehouse_id: warehouseId,
|
warehouse_id: warehouseId,
|
||||||
handler: 'syncManualOrders',
|
handler: 'syncManualOrders',
|
||||||
sync_target: 'internal',
|
sync_target: 'internal',
|
||||||
route_state: 'accepted',
|
route_state: 'accepted',
|
||||||
status: 'success',
|
status: 'success',
|
||||||
message: '订单同步通知已发送',
|
message: '订单同步通知已合并排队',
|
||||||
success_count: 1,
|
success_count: 1,
|
||||||
failed_count: 0,
|
failed_count: 0,
|
||||||
};
|
};
|
||||||
const noticeResult = await sendManualSyncNoticeInternal(service, noticeSyncResult, context);
|
const noticeResult = await enqueueOrderSyncNoticeInternal(service, noticeSyncResult, context);
|
||||||
|
|
||||||
if (!noticeResult || noticeResult.success !== true) {
|
if (!noticeResult || noticeResult.success !== true) {
|
||||||
const noticeMessage = String(noticeResult && noticeResult.message || '通知发送失败').trim() || '通知发送失败';
|
const noticeMessage = String(noticeResult && noticeResult.message || '通知发送失败').trim() || '通知发送失败';
|
||||||
@ -928,9 +940,10 @@ function buildManualSyncNoticePayloadInternal(syncResult = {}, context = {}) {
|
|||||||
? syncResult.order_ids.map(orderId => Number(orderId)).filter(orderId => Number.isFinite(orderId) && orderId > 0)
|
? syncResult.order_ids.map(orderId => Number(orderId)).filter(orderId => Number.isFinite(orderId) && orderId > 0)
|
||||||
: [];
|
: [];
|
||||||
const warehouseId = Number(context.warehouseId || syncResult.warehouse_id || 0);
|
const warehouseId = Number(context.warehouseId || syncResult.warehouse_id || 0);
|
||||||
const noticeMessage = String(syncResult.message || '').trim() || '订单同步完成';
|
|
||||||
const noticeStatus = String(syncResult.status || '').trim() || 'success';
|
const noticeStatus = String(syncResult.status || '').trim() || 'success';
|
||||||
const deliveryOrderCode = String(syncResult.delivery_order_code || '').trim();
|
const deliveryOrderCode = String(syncResult.delivery_order_code || '').trim();
|
||||||
|
const receiverName = String(syncResult.receiver_name || '').trim() || '无';
|
||||||
|
const receiverPhone = String(syncResult.receiver_phone || '').trim() || '无';
|
||||||
const waybillCodeList = Array.isArray(syncResult.waybill_code)
|
const waybillCodeList = Array.isArray(syncResult.waybill_code)
|
||||||
? syncResult.waybill_code.map(code => String(code || '').trim()).filter(code => !!code)
|
? syncResult.waybill_code.map(code => String(code || '').trim()).filter(code => !!code)
|
||||||
: (Array.isArray(syncResult.waybill_code_list)
|
: (Array.isArray(syncResult.waybill_code_list)
|
||||||
@ -948,11 +961,7 @@ function buildManualSyncNoticePayloadInternal(syncResult = {}, context = {}) {
|
|||||||
},
|
},
|
||||||
title: '订单同步完成',
|
title: '订单同步完成',
|
||||||
message: [
|
message: [
|
||||||
`仓库ID:${warehouseId || '未知'}`,
|
`订单${deliveryOrderCode || '无'} 姓名:${receiverName} 电话:${receiverPhone} 运单号:${waybillCodeList.length > 0 ? waybillCodeList.join(',') : '无'}`,
|
||||||
`订单ID:${orderIds.join(',') || '无'}`,
|
|
||||||
`发货单号:${deliveryOrderCode || '无'}`,
|
|
||||||
`运单号:${waybillCodeList.length > 0 ? waybillCodeList.join(',') : '无'}`,
|
|
||||||
`消息:${noticeMessage}`,
|
|
||||||
].join('\n'),
|
].join('\n'),
|
||||||
metadata: {
|
metadata: {
|
||||||
create_channel: CREATE_CHANNEL_MANUAL,
|
create_channel: CREATE_CHANNEL_MANUAL,
|
||||||
@ -969,6 +978,509 @@ function buildManualSyncNoticePayloadInternal(syncResult = {}, context = {}) {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析订单同步通知合并维度中的货主 ID。
|
||||||
|
* 与 buildManualSyncNoticePayloadInternal 的 storeId 取值保持一致。
|
||||||
|
*
|
||||||
|
* @param {object} syncResult 单订单同步结果。
|
||||||
|
* @param {object} context 上下文。
|
||||||
|
* @return {number} 货主 ID。
|
||||||
|
*/
|
||||||
|
function resolveOrderSyncNoticeStoreIdInternal(syncResult = {}, context = {}) {
|
||||||
|
return Number(syncResult.store_id || context.storeId || context.warehouseId || 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 生成订单同步通知合并队列的成员标识。
|
||||||
|
* 按「仓库:货主」聚合,货主售后群按货主维度订阅。
|
||||||
|
*
|
||||||
|
* @param {number} warehouseId 仓库 ID。
|
||||||
|
* @param {number} storeId 货主 ID。
|
||||||
|
* @return {string} 队列成员标识。
|
||||||
|
*/
|
||||||
|
function buildOrderSyncNoticeMemberInternal(warehouseId, storeId) {
|
||||||
|
return `${warehouseId}:${storeId}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析订单同步通知合并队列的成员标识。
|
||||||
|
*
|
||||||
|
* @param {string} member 队列成员标识。
|
||||||
|
* @return {Object|null} 解析结果或 null。
|
||||||
|
*/
|
||||||
|
function parseOrderSyncNoticeMemberInternal(member) {
|
||||||
|
const normalized = String(member || '').trim();
|
||||||
|
if (!normalized) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const [ warehousePart, storePart ] = normalized.split(':');
|
||||||
|
const warehouseId = Number(warehousePart);
|
||||||
|
const storeId = Number(storePart);
|
||||||
|
|
||||||
|
if (!Number.isFinite(warehouseId) || warehouseId <= 0 || !Number.isFinite(storeId)) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
return { warehouseId, storeId };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 生成订单同步通知合并相关的 Redis 键集合。
|
||||||
|
*
|
||||||
|
* @param {number} warehouseId 仓库 ID。
|
||||||
|
* @param {number} storeId 货主 ID。
|
||||||
|
* @return {Object} Redis 键集合。
|
||||||
|
*/
|
||||||
|
function buildOrderSyncNoticeKeysInternal(warehouseId, storeId) {
|
||||||
|
const member = buildOrderSyncNoticeMemberInternal(warehouseId, storeId);
|
||||||
|
|
||||||
|
return {
|
||||||
|
member,
|
||||||
|
queueKey: `${ORDER_SYNC_NOTICE_KEY_PREFIX}:queue`,
|
||||||
|
listKey: `${ORDER_SYNC_NOTICE_KEY_PREFIX}:list:${member}`,
|
||||||
|
retryKey: `${ORDER_SYNC_NOTICE_KEY_PREFIX}:retry:${member}`,
|
||||||
|
lockKey: `${ORDER_SYNC_NOTICE_KEY_PREFIX}:lock:${member}`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取订单同步通知合并使用的 Redis 客户端。
|
||||||
|
*
|
||||||
|
* @param {object} service 服务实例。
|
||||||
|
* @return {Object|null} Redis 客户端或 null。
|
||||||
|
*/
|
||||||
|
function getOrderSyncNoticeRedisClientInternal(service) {
|
||||||
|
if (!service || !service.app || !service.app.redis || typeof service.app.redis.get !== 'function') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
return service.app.redis.get('cache') || null;
|
||||||
|
} catch (error) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 把单订单同步结果构建为合并队列条目。
|
||||||
|
*
|
||||||
|
* @param {object} syncResult 单订单同步结果。
|
||||||
|
* @return {Object} 合并队列条目。
|
||||||
|
*/
|
||||||
|
function buildOrderSyncNoticeEntryInternal(syncResult = {}) {
|
||||||
|
const orderIds = Array.isArray(syncResult.order_ids)
|
||||||
|
? syncResult.order_ids.map(orderId => Number(orderId)).filter(orderId => Number.isFinite(orderId) && orderId > 0)
|
||||||
|
: [];
|
||||||
|
const waybillCodes = Array.isArray(syncResult.waybill_code)
|
||||||
|
? syncResult.waybill_code.map(code => String(code || '').trim()).filter(code => !!code)
|
||||||
|
: (Array.isArray(syncResult.waybill_code_list)
|
||||||
|
? syncResult.waybill_code_list.map(code => String(code || '').trim()).filter(code => !!code)
|
||||||
|
: (String(syncResult.waybill_code || '').trim() ? [ String(syncResult.waybill_code || '').trim() ] : []));
|
||||||
|
|
||||||
|
return {
|
||||||
|
order_id: orderIds[0] || null,
|
||||||
|
delivery_order_code: String(syncResult.delivery_order_code || '').trim(),
|
||||||
|
receiver_name: String(syncResult.receiver_name || '').trim(),
|
||||||
|
receiver_phone: String(syncResult.receiver_phone || '').trim(),
|
||||||
|
waybill_codes: waybillCodes,
|
||||||
|
enqueue_at: Date.now(),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 解析合并队列中的原始条目。
|
||||||
|
*
|
||||||
|
* @param {*} rawEntry 原始条目。
|
||||||
|
* @return {Object|null} 解析结果或 null。
|
||||||
|
*/
|
||||||
|
function parseOrderSyncNoticeEntryInternal(rawEntry) {
|
||||||
|
if (!rawEntry) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const entry = typeof rawEntry === 'string' ? JSON.parse(rawEntry) : rawEntry;
|
||||||
|
if (!entry || typeof entry !== 'object') {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const orderId = Number(entry.order_id);
|
||||||
|
|
||||||
|
return {
|
||||||
|
order_id: Number.isFinite(orderId) && orderId > 0 ? orderId : null,
|
||||||
|
delivery_order_code: String(entry.delivery_order_code || '').trim(),
|
||||||
|
receiver_name: String(entry.receiver_name || '').trim(),
|
||||||
|
receiver_phone: String(entry.receiver_phone || '').trim(),
|
||||||
|
waybill_codes: Array.isArray(entry.waybill_codes)
|
||||||
|
? entry.waybill_codes.map(code => String(code || '').trim()).filter(code => !!code)
|
||||||
|
: [],
|
||||||
|
enqueue_at: Number(entry.enqueue_at) || null,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 订单同步通知入队:把单订单通知合并到 Redis 队列,
|
||||||
|
* 等待 3 分钟去抖窗口结束后由定时任务统一推送。
|
||||||
|
* Redis 不可用或入队失败时回退为立即发送(保持原有行为)。
|
||||||
|
*
|
||||||
|
* @param {object} service 服务实例。
|
||||||
|
* @param {object} syncResult 单订单同步结果。
|
||||||
|
* @param {object} context 上下文。
|
||||||
|
* @return {Promise<Object>} 入队或回退发送结果。
|
||||||
|
*/
|
||||||
|
async function enqueueOrderSyncNoticeInternal(service, syncResult = {}, context = {}) {
|
||||||
|
const warehouseId = Number(context.warehouseId || syncResult.warehouse_id || 0);
|
||||||
|
const storeId = resolveOrderSyncNoticeStoreIdInternal(syncResult, context);
|
||||||
|
const redis = getOrderSyncNoticeRedisClientInternal(service);
|
||||||
|
|
||||||
|
if (!redis) {
|
||||||
|
service.ctx.logger.warn('[OrderAsyncService.enqueueOrderSyncNotice] Redis 不可用,回退立即发送通知', {
|
||||||
|
warehouseId,
|
||||||
|
storeId,
|
||||||
|
});
|
||||||
|
|
||||||
|
return await sendManualSyncNoticeInternal(service, syncResult, context);
|
||||||
|
}
|
||||||
|
|
||||||
|
const keys = buildOrderSyncNoticeKeysInternal(warehouseId, storeId);
|
||||||
|
const entry = buildOrderSyncNoticeEntryInternal(syncResult);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const dueAtSeconds = Math.floor((Date.now() + ORDER_SYNC_NOTICE_DEBOUNCE_MS) / 1000);
|
||||||
|
await redis.rpush(keys.listKey, JSON.stringify(entry));
|
||||||
|
await redis.expire(keys.listKey, ORDER_SYNC_NOTICE_LIST_TTL_SECONDS);
|
||||||
|
await redis.zadd(keys.queueKey, dueAtSeconds, keys.member);
|
||||||
|
|
||||||
|
service.ctx.logger.info('[OrderAsyncService.enqueueOrderSyncNotice] 订单同步通知已入队,等待合并推送', {
|
||||||
|
warehouseId,
|
||||||
|
storeId,
|
||||||
|
orderId: entry.order_id,
|
||||||
|
dueAt: dueAtSeconds * 1000,
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: true,
|
||||||
|
message: '订单同步通知已合并排队,3 分钟内无新同步将统一推送',
|
||||||
|
data: {
|
||||||
|
mode: 'deferred',
|
||||||
|
warehouseId,
|
||||||
|
storeId,
|
||||||
|
due_at: dueAtSeconds * 1000,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
service.ctx.logger.warn('[OrderAsyncService.enqueueOrderSyncNotice] 合并入队失败,回退立即发送通知', {
|
||||||
|
warehouseId,
|
||||||
|
storeId,
|
||||||
|
error: String((error && error.message) || error || '').trim(),
|
||||||
|
});
|
||||||
|
|
||||||
|
return await sendManualSyncNoticeInternal(service, syncResult, context);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 构建合并后的订单同步通知载荷。
|
||||||
|
*
|
||||||
|
* @param {number} warehouseId 仓库 ID。
|
||||||
|
* @param {number} storeId 货主 ID。
|
||||||
|
* @param {Object[]} entries 合并队列条目。
|
||||||
|
* @return {Object} 通知载荷。
|
||||||
|
*/
|
||||||
|
function buildConsolidatedOrderSyncNoticePayloadInternal(warehouseId, storeId, entries = []) {
|
||||||
|
const normalizedEntries = (Array.isArray(entries) ? entries : []).filter(entry => !!entry);
|
||||||
|
const orderLines = normalizedEntries.map(entry => {
|
||||||
|
const code = String(entry.delivery_order_code || '').trim() || '无';
|
||||||
|
const name = String(entry.receiver_name || '').trim() || '无';
|
||||||
|
const phone = String(entry.receiver_phone || '').trim() || '无';
|
||||||
|
const waybillList = Array.isArray(entry.waybill_codes) ? entry.waybill_codes : [];
|
||||||
|
const waybill = waybillList.length > 0 ? waybillList.join(',') : '无';
|
||||||
|
|
||||||
|
return `订单${code} 姓名:${name} 电话:${phone} 运单号:${waybill}`;
|
||||||
|
});
|
||||||
|
|
||||||
|
const shownLines = orderLines.slice(0, ORDER_SYNC_NOTICE_MAX_ORDER_LINES);
|
||||||
|
const hiddenCount = orderLines.length - shownLines.length;
|
||||||
|
const lines = [
|
||||||
|
`订单同步完成(共 ${normalizedEntries.length} 单)`,
|
||||||
|
...shownLines,
|
||||||
|
];
|
||||||
|
|
||||||
|
if (hiddenCount > 0) {
|
||||||
|
lines.push(`……其余 ${hiddenCount} 单未列出`);
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
event: 'order_sync_completed',
|
||||||
|
businessName: 'order',
|
||||||
|
warehouseId,
|
||||||
|
storeId,
|
||||||
|
subject: {
|
||||||
|
id: warehouseId,
|
||||||
|
type: 'warehouse',
|
||||||
|
},
|
||||||
|
title: '订单同步完成',
|
||||||
|
message: lines.join('\n'),
|
||||||
|
metadata: {
|
||||||
|
create_channel: CREATE_CHANNEL_MANUAL,
|
||||||
|
sync_target: 'internal',
|
||||||
|
order_ids: normalizedEntries.map(entry => entry.order_id).filter(orderId => orderId),
|
||||||
|
order_count: normalizedEntries.length,
|
||||||
|
status: 'success',
|
||||||
|
route_state: 'accepted',
|
||||||
|
success_count: normalizedEntries.length,
|
||||||
|
failed_count: 0,
|
||||||
|
debounced: true,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 发送合并后的订单同步通知。
|
||||||
|
*
|
||||||
|
* @param {object} service 服务实例。
|
||||||
|
* @param {number} warehouseId 仓库 ID。
|
||||||
|
* @param {number} storeId 货主 ID。
|
||||||
|
* @param {Object[]} entries 合并队列条目。
|
||||||
|
* @return {Promise<Object>} 通知服务返回结果。
|
||||||
|
*/
|
||||||
|
async function sendConsolidatedOrderSyncNoticeInternal(service, warehouseId, storeId, entries = []) {
|
||||||
|
const rawNoticeService = service && service.ctx && service.ctx.service && service.ctx.service.systems && service.ctx.service.systems.notice;
|
||||||
|
const noticeService = rawNoticeService && typeof rawNoticeService.send === 'function'
|
||||||
|
? rawNoticeService
|
||||||
|
: (rawNoticeService && rawNoticeService.index && typeof rawNoticeService.index.send === 'function'
|
||||||
|
? rawNoticeService.index
|
||||||
|
: null);
|
||||||
|
if (!noticeService || typeof noticeService.send !== 'function') {
|
||||||
|
throw new Error('通知服务不可用');
|
||||||
|
}
|
||||||
|
|
||||||
|
const payload = buildConsolidatedOrderSyncNoticePayloadInternal(warehouseId, storeId, entries);
|
||||||
|
|
||||||
|
service.ctx.logger.info('[OrderAsyncService.flushDeferredOrderSyncNotices] 合并通知发送前', {
|
||||||
|
warehouseId,
|
||||||
|
storeId,
|
||||||
|
entryCount: entries.length,
|
||||||
|
});
|
||||||
|
|
||||||
|
const noticeResult = await noticeService.send(payload);
|
||||||
|
|
||||||
|
service.ctx.logger.info('[OrderAsyncService.flushDeferredOrderSyncNotices] 合并通知发送结果', {
|
||||||
|
warehouseId,
|
||||||
|
storeId,
|
||||||
|
entryCount: entries.length,
|
||||||
|
success: !!(noticeResult && noticeResult.success),
|
||||||
|
message: noticeResult && noticeResult.message,
|
||||||
|
});
|
||||||
|
|
||||||
|
return noticeResult;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 处理合并通知发送失败:放回队列并按重试策略推迟。
|
||||||
|
*
|
||||||
|
* @param {object} service 服务实例。
|
||||||
|
* @param {Object} redis Redis 客户端。
|
||||||
|
* @param {Object} keys 合并维度键集合。
|
||||||
|
* @param {string} queueKey 全局队列键。
|
||||||
|
* @param {string} member 队列成员。
|
||||||
|
* @param {Object[]} entries 合并队列条目。
|
||||||
|
* @return {Promise<void>} 无返回值。
|
||||||
|
*/
|
||||||
|
async function handleOrderSyncNoticeFlushFailureInternal(service, redis, keys, queueKey, member, entries) {
|
||||||
|
const retries = Number(await redis.incr(keys.retryKey)) || 1;
|
||||||
|
|
||||||
|
if (retries >= ORDER_SYNC_NOTICE_MAX_RETRIES) {
|
||||||
|
await redis.del(keys.listKey, keys.retryKey);
|
||||||
|
await redis.zrem(queueKey, member);
|
||||||
|
service.ctx.logger.error('[OrderAsyncService.flushDeferredOrderSyncNotices] 合并通知重试次数超限,放弃发送', {
|
||||||
|
member,
|
||||||
|
entryCount: entries.length,
|
||||||
|
retries,
|
||||||
|
});
|
||||||
|
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (entries.length > 0) {
|
||||||
|
await redis.rpush(keys.listKey, ...entries.map(entry => JSON.stringify(entry)));
|
||||||
|
await redis.expire(keys.listKey, ORDER_SYNC_NOTICE_LIST_TTL_SECONDS);
|
||||||
|
}
|
||||||
|
|
||||||
|
await redis.zadd(queueKey, Math.floor((Date.now() + ORDER_SYNC_NOTICE_RETRY_MS) / 1000), member);
|
||||||
|
service.ctx.logger.warn('[OrderAsyncService.flushDeferredOrderSyncNotices] 合并通知发送失败,已重新排队', {
|
||||||
|
member,
|
||||||
|
entryCount: entries.length,
|
||||||
|
retries,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 冲刷合并的订单同步通知:把 3 分钟去抖窗口已到期的「仓库:货主」维度订单统一推送。
|
||||||
|
* 由定时任务调用。
|
||||||
|
*
|
||||||
|
* @param {object} service 服务实例。
|
||||||
|
* @return {Promise<Object>} 本轮冲刷结果。
|
||||||
|
*/
|
||||||
|
async function flushDeferredOrderSyncNoticesInternal(service) {
|
||||||
|
const redis = getOrderSyncNoticeRedisClientInternal(service);
|
||||||
|
if (!redis) {
|
||||||
|
service.ctx.logger.warn('[OrderAsyncService.flushDeferredOrderSyncNotices] Redis 不可用,跳过本轮合并通知');
|
||||||
|
|
||||||
|
return {
|
||||||
|
skipped: true,
|
||||||
|
reason: 'redis_unavailable',
|
||||||
|
flushedCount: 0,
|
||||||
|
failedCount: 0,
|
||||||
|
skippedCount: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const queueKey = `${ORDER_SYNC_NOTICE_KEY_PREFIX}:queue`;
|
||||||
|
const nowSeconds = Math.floor(Date.now() / 1000);
|
||||||
|
let dueMembers = [];
|
||||||
|
|
||||||
|
try {
|
||||||
|
dueMembers = await redis.zrangebyscore(queueKey, '-inf', nowSeconds, 'LIMIT', 0, ORDER_SYNC_NOTICE_FLUSH_BATCH_SIZE);
|
||||||
|
} catch (error) {
|
||||||
|
service.ctx.logger.error('[OrderAsyncService.flushDeferredOrderSyncNotices] 读取到期队列失败', {
|
||||||
|
error: String((error && error.message) || error || '').trim(),
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
skipped: true,
|
||||||
|
reason: 'queue_read_failed',
|
||||||
|
flushedCount: 0,
|
||||||
|
failedCount: 0,
|
||||||
|
skippedCount: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!Array.isArray(dueMembers) || dueMembers.length === 0) {
|
||||||
|
return {
|
||||||
|
skipped: false,
|
||||||
|
flushedCount: 0,
|
||||||
|
failedCount: 0,
|
||||||
|
skippedCount: 0,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
let flushedCount = 0;
|
||||||
|
let failedCount = 0;
|
||||||
|
let skippedCount = 0;
|
||||||
|
|
||||||
|
for (const member of dueMembers) {
|
||||||
|
const parsedMember = parseOrderSyncNoticeMemberInternal(member);
|
||||||
|
if (!parsedMember) {
|
||||||
|
skippedCount += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const keys = buildOrderSyncNoticeKeysInternal(parsedMember.warehouseId, parsedMember.storeId);
|
||||||
|
let lockAcquired = false;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const lockResult = await redis.set(keys.lockKey, String(process.pid || ''), 'EX', ORDER_SYNC_NOTICE_LOCK_TTL_SECONDS, 'NX');
|
||||||
|
lockAcquired = lockResult === 'OK';
|
||||||
|
} catch (lockError) {
|
||||||
|
service.ctx.logger.warn('[OrderAsyncService.flushDeferredOrderSyncNotices] 获取合并锁失败,跳过本轮', {
|
||||||
|
member,
|
||||||
|
error: String((lockError && lockError.message) || lockError || '').trim(),
|
||||||
|
});
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!lockAcquired) {
|
||||||
|
skippedCount += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
// 加锁期间可能又有新订单入队把到期时间推后,重新校验到期时间
|
||||||
|
const currentScore = await redis.zscore(queueKey, member);
|
||||||
|
if (Number(currentScore) > nowSeconds) {
|
||||||
|
skippedCount += 1;
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const existsCount = Number(await redis.exists(keys.listKey)) || 0;
|
||||||
|
if (existsCount === 0) {
|
||||||
|
await redis.del(keys.listKey, keys.retryKey);
|
||||||
|
await redis.zrem(queueKey, member);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
// 原子搬走列表,避免与并发新入队条目互相污染
|
||||||
|
const processingKey = `${keys.listKey}:processing`;
|
||||||
|
await redis.rename(keys.listKey, processingKey);
|
||||||
|
const rawEntries = await redis.lrange(processingKey, 0, -1);
|
||||||
|
await redis.del(processingKey);
|
||||||
|
|
||||||
|
const entries = (Array.isArray(rawEntries) ? rawEntries : [])
|
||||||
|
.map(rawEntry => parseOrderSyncNoticeEntryInternal(rawEntry))
|
||||||
|
.filter(entry => !!entry);
|
||||||
|
|
||||||
|
if (entries.length === 0) {
|
||||||
|
await redis.del(keys.retryKey);
|
||||||
|
await redis.zrem(queueKey, member);
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const noticeResult = await sendConsolidatedOrderSyncNoticeInternal(
|
||||||
|
service,
|
||||||
|
parsedMember.warehouseId,
|
||||||
|
parsedMember.storeId,
|
||||||
|
entries
|
||||||
|
);
|
||||||
|
|
||||||
|
if (noticeResult && noticeResult.success === true) {
|
||||||
|
await redis.del(keys.retryKey);
|
||||||
|
await redis.zrem(queueKey, member);
|
||||||
|
flushedCount += 1;
|
||||||
|
} else {
|
||||||
|
await handleOrderSyncNoticeFlushFailureInternal(service, redis, keys, queueKey, member, entries);
|
||||||
|
failedCount += 1;
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
failedCount += 1;
|
||||||
|
service.ctx.logger.error('[OrderAsyncService.flushDeferredOrderSyncNotices] 冲刷合并通知失败', {
|
||||||
|
member,
|
||||||
|
error: String((error && error.message) || error || '').trim(),
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
await redis.zadd(queueKey, Math.floor((Date.now() + ORDER_SYNC_NOTICE_RETRY_MS) / 1000), member);
|
||||||
|
} catch (reQueueError) {
|
||||||
|
// 重新排队失败仅记录日志
|
||||||
|
}
|
||||||
|
} finally {
|
||||||
|
try {
|
||||||
|
await redis.del(keys.lockKey);
|
||||||
|
} catch (lockReleaseError) {
|
||||||
|
// 释放锁失败仅记录日志
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
service.ctx.logger.info('[OrderAsyncService.flushDeferredOrderSyncNotices] 本轮合并通知冲刷完成', {
|
||||||
|
dueMemberCount: dueMembers.length,
|
||||||
|
flushedCount,
|
||||||
|
failedCount,
|
||||||
|
skippedCount,
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
skipped: false,
|
||||||
|
flushedCount,
|
||||||
|
failedCount,
|
||||||
|
skippedCount,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
async function processQmOrderInternal(service, orderModel, orderItemsModel, qimenClient, orderId, warehouseId, orderRow, orderItems, context, waybillCode) {
|
async function processQmOrderInternal(service, orderModel, orderItemsModel, qimenClient, orderId, warehouseId, orderRow, orderItems, context, waybillCode) {
|
||||||
if (!orderRow) {
|
if (!orderRow) {
|
||||||
@ -1293,6 +1805,16 @@ class OrderAsyncService extends MainService {
|
|||||||
return await syncManualOrdersInternal(this, groupedOrder, context);
|
return await syncManualOrdersInternal(this, groupedOrder, context);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 冲刷合并的订单同步通知(由定时任务调用)。
|
||||||
|
* 把 3 分钟去抖窗口已到期的「仓库:货主」维度订单统一推送一条消息。
|
||||||
|
*
|
||||||
|
* @return {Promise<Object>} 本轮冲刷结果。
|
||||||
|
*/
|
||||||
|
async flushDeferredOrderSyncNotices() {
|
||||||
|
return await flushDeferredOrderSyncNoticesInternal(this);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* API 创建入口处理。
|
* API 创建入口处理。
|
||||||
*
|
*
|
||||||
|
|||||||
@ -680,25 +680,6 @@ class InventoryService extends Service {
|
|||||||
// ────────── 7. 提交事务 ──────────
|
// ────────── 7. 提交事务 ──────────
|
||||||
await transaction.commit();
|
await transaction.commit();
|
||||||
|
|
||||||
// ────────── 8. 发送通知(事务外) ──────────
|
|
||||||
try {
|
|
||||||
await ctx.service.systems.notice.send({
|
|
||||||
event: 'storage_transfer_completed',
|
|
||||||
businessName: 'storage',
|
|
||||||
warehouseId,
|
|
||||||
subjectId: warehouseId,
|
|
||||||
title: '移库操作完成',
|
|
||||||
content: `移库完成:库存${storageId} -> 库位${targetSpaceId}(数量:${transferQty})`,
|
|
||||||
data: { warehouse_id: warehouseId, storage_id: storageId, target_space_id: targetSpaceId, transfer_quantity: transferQty },
|
|
||||||
sender: {
|
|
||||||
id: ctx.user?.employees_id || ctx.user?.id,
|
|
||||||
name: ctx.user?.employees_name || '',
|
|
||||||
},
|
|
||||||
});
|
|
||||||
} catch (noticeErr) {
|
|
||||||
ctx.logger.warn('[inventory.transferLocation] 发送通知失败,不影响业务', noticeErr);
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx.logger.info('[inventory.transferLocation] 移库完成', {
|
ctx.logger.info('[inventory.transferLocation] 移库完成', {
|
||||||
warehouse_id: warehouseId,
|
warehouse_id: warehouseId,
|
||||||
storage_id: storageId,
|
storage_id: storageId,
|
||||||
@ -1089,32 +1070,6 @@ class InventoryService extends Service {
|
|||||||
// ────────── 10. 提交事务 ──────────
|
// ────────── 10. 提交事务 ──────────
|
||||||
await transaction.commit();
|
await transaction.commit();
|
||||||
|
|
||||||
// ────────── 11. 发送通知(事务外) ──────────
|
|
||||||
try {
|
|
||||||
await ctx.service.systems.notice.send({
|
|
||||||
event: 'storage_transfer_completed',
|
|
||||||
businessName: 'storage',
|
|
||||||
warehouseId,
|
|
||||||
subjectId: warehouseId,
|
|
||||||
title: '按商品移库操作完成',
|
|
||||||
content: `按商品移库完成:库位${spaceId} 商品${stockId} -> 库位${targetSpaceId}(数量:${quantity},涉及${affectedCount}条记录)`,
|
|
||||||
data: {
|
|
||||||
warehouse_id: warehouseId,
|
|
||||||
space_id: spaceId,
|
|
||||||
stock_id: stockId,
|
|
||||||
target_space_id: targetSpaceId,
|
|
||||||
transfer_quantity: quantity,
|
|
||||||
affected_storage_count: affectedCount,
|
|
||||||
},
|
|
||||||
sender: {
|
|
||||||
id: ctx.user?.employees_id || ctx.user?.id,
|
|
||||||
name: ctx.user?.employees_name || '',
|
|
||||||
},
|
|
||||||
});
|
|
||||||
} catch (noticeErr) {
|
|
||||||
ctx.logger.warn('[inventory.transferByProduct] 发送通知失败,不影响业务', noticeErr);
|
|
||||||
}
|
|
||||||
|
|
||||||
ctx.logger.info('[inventory.transferByProduct] 按商品移库完成', {
|
ctx.logger.info('[inventory.transferByProduct] 按商品移库完成', {
|
||||||
warehouse_id: warehouseId,
|
warehouse_id: warehouseId,
|
||||||
space_id: spaceId,
|
space_id: spaceId,
|
||||||
|
|||||||
@ -1009,6 +1009,7 @@ class ReceivingService extends Service {
|
|||||||
messageType: 'text',
|
messageType: 'text',
|
||||||
businessName: 'receiving',
|
businessName: 'receiving',
|
||||||
event: 'receiving_rejected',
|
event: 'receiving_rejected',
|
||||||
|
channel: 'warehouse',
|
||||||
title: `收货单 ${item.receiving_number || item.id} 已被驳回`,
|
title: `收货单 ${item.receiving_number || item.id} 已被驳回`,
|
||||||
content: [
|
content: [
|
||||||
`驳回人:${reviewerName || '未知'}`,
|
`驳回人:${reviewerName || '未知'}`,
|
||||||
@ -1029,16 +1030,9 @@ class ReceivingService extends Service {
|
|||||||
name: reviewerName,
|
name: reviewerName,
|
||||||
},
|
},
|
||||||
metadata: {
|
metadata: {
|
||||||
id: item.id || null,
|
|
||||||
ids: [ item.id || null ].filter(Boolean),
|
|
||||||
receiving_id: item.id || null,
|
receiving_id: item.id || null,
|
||||||
receiving_ids: [ item.id || null ].filter(Boolean),
|
|
||||||
receiving_number: item.receiving_number || '',
|
receiving_number: item.receiving_number || '',
|
||||||
receiving_numbers: item.receiving_number ? [ item.receiving_number ] : [],
|
receiving_creator: item.creator && item.creator.name ? item.creator.name : null,
|
||||||
receiving_creator: item.creator || null,
|
|
||||||
receiving_creators: item.creator ? [ item.creator ] : [],
|
|
||||||
receiving: item,
|
|
||||||
receivings: [ item ],
|
|
||||||
warehouseId: warehouse_id,
|
warehouseId: warehouse_id,
|
||||||
remark: updateData.remark || '',
|
remark: updateData.remark || '',
|
||||||
},
|
},
|
||||||
@ -1549,6 +1543,7 @@ class ReceivingService extends Service {
|
|||||||
messageType: reportUrl ? 'file' : 'text',
|
messageType: reportUrl ? 'file' : 'text',
|
||||||
businessName: 'receiving',
|
businessName: 'receiving',
|
||||||
event: 'receiving_reviewed',
|
event: 'receiving_reviewed',
|
||||||
|
channel: 'warehouse',
|
||||||
title: `收货单${receivingNumber}审核完成`,
|
title: `收货单${receivingNumber}审核完成`,
|
||||||
content,
|
content,
|
||||||
url: reportUrl || undefined,
|
url: reportUrl || undefined,
|
||||||
@ -4104,7 +4099,10 @@ class ReceivingService extends Service {
|
|||||||
const totalBoxWeight = normalizedDetails.reduce((sum, item) => sum + Number(item.box_weight || 0), 0);
|
const totalBoxWeight = normalizedDetails.reduce((sum, item) => sum + Number(item.box_weight || 0), 0);
|
||||||
const title = `收货单${receivingNumber}已完成`;
|
const title = `收货单${receivingNumber}已完成`;
|
||||||
const contactLines = this.getCompletionContactFields(receiving).map(([ field, value ]) => `${field}:${value || '无'}`);
|
const contactLines = this.getCompletionContactFields(receiving).map(([ field, value ]) => `${field}:${value || '无'}`);
|
||||||
const content = [
|
// 仓库侧与货主侧前端地址/路径不同,分别拼快速查看链接
|
||||||
|
const warehouseFrontendUrl = String(ctx.app.config.frontendUrl || '').trim();
|
||||||
|
const storeFrontendUrl = String(ctx.app.config.storeFrontendUrl || ctx.app.config.frontendUrl || '').trim();
|
||||||
|
const contentLines = [
|
||||||
`收货单号:${receivingNumber} 已完成`,
|
`收货单号:${receivingNumber} 已完成`,
|
||||||
`货主:${receiving.store_name || '未知'}`,
|
`货主:${receiving.store_name || '未知'}`,
|
||||||
`来货方式:${this.formatDeliveryMethod(receiving.delivery_method) || '未知'}`,
|
`来货方式:${this.formatDeliveryMethod(receiving.delivery_method) || '未知'}`,
|
||||||
@ -4121,9 +4119,9 @@ class ReceivingService extends Service {
|
|||||||
`开始时间:${this.formatReportDate(receiving.created_at)}`,
|
`开始时间:${this.formatReportDate(receiving.created_at)}`,
|
||||||
`完成时间:${this.formatReportDate(receiving.receiving_end_time)}`,
|
`完成时间:${this.formatReportDate(receiving.receiving_end_time)}`,
|
||||||
`备注:${receiving.remark || '无'}`,
|
`备注:${receiving.remark || '无'}`,
|
||||||
`快速查看:${ctx.app.config.frontendUrl || ''}/storage/receiving?id=${receivingNumber}`, // 替换为实际的前端地址
|
].filter(Boolean);
|
||||||
|
const content = [ ...contentLines, `快速查看:${warehouseFrontendUrl}/storage/receiving?id=${receivingNumber}` ].join('\n') + '。';
|
||||||
].filter(Boolean).join('\n') + '。';
|
const storeContent = [ ...contentLines, `快速查看:${storeFrontendUrl}/storage/receiving_owner?id=${receivingNumber}` ].join('\n') + '。';
|
||||||
|
|
||||||
return await noticeService.send({
|
return await noticeService.send({
|
||||||
warehouseId,
|
warehouseId,
|
||||||
@ -4131,8 +4129,10 @@ class ReceivingService extends Service {
|
|||||||
messageType: reportUrl ? 'file' : 'text',
|
messageType: reportUrl ? 'file' : 'text',
|
||||||
businessName: 'receiving',
|
businessName: 'receiving',
|
||||||
event: 'receiving_completed',
|
event: 'receiving_completed',
|
||||||
|
channel: 'warehouse',
|
||||||
title,
|
title,
|
||||||
content,
|
content,
|
||||||
|
storeContent,
|
||||||
url: reportUrl || undefined,
|
url: reportUrl || undefined,
|
||||||
fileName: reportUrl ? reportFileName : '',
|
fileName: reportUrl ? reportFileName : '',
|
||||||
mimeType: reportUrl ? 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' : '',
|
mimeType: reportUrl ? 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' : '',
|
||||||
@ -4157,15 +4157,6 @@ class ReceivingService extends Service {
|
|||||||
unmatched_details: unmatchedDetails,
|
unmatched_details: unmatchedDetails,
|
||||||
total_quantity: totalQuantity,
|
total_quantity: totalQuantity,
|
||||||
},
|
},
|
||||||
details: normalizedDetails,
|
|
||||||
boxSummary: {
|
|
||||||
total_box_remainder: totalBoxRemainder,
|
|
||||||
total_box_weight: totalBoxWeight,
|
|
||||||
},
|
|
||||||
completionReport: completionReport ? {
|
|
||||||
fileKey: completionReport.fileKey || completionReport.key || '',
|
|
||||||
url: reportUrl,
|
|
||||||
} : null,
|
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|||||||
342
app/service/systems/warehouseNotify.js
Normal file
342
app/service/systems/warehouseNotify.js
Normal file
@ -0,0 +1,342 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
const { Service } = require('egg');
|
||||||
|
const crypto = require('crypto');
|
||||||
|
|
||||||
|
/** 仓库接口类型 ID(interface_type_id=3) */
|
||||||
|
const WAREHOUSE_INTERFACE_TYPE_ID = 3;
|
||||||
|
/** 请求超时(毫秒) */
|
||||||
|
const REQUEST_TIMEOUT_MS = 10000;
|
||||||
|
/** 日志内容长度上限 */
|
||||||
|
const LOG_BODY_MAX = 65535;
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 仓库接口消息推送服务(出站方向:WMS → 外部系统)。
|
||||||
|
* 复用仓库开放接口出站协议(MD5 签名 + ApiApp.callback_url),
|
||||||
|
* 供统一通知服务与 inbox 回执复用同一套发送与日志链路。
|
||||||
|
*/
|
||||||
|
class WarehouseNotifyService extends Service {
|
||||||
|
/**
|
||||||
|
* 截断日志内容到上限长度。
|
||||||
|
* @param {*} value 原始值。
|
||||||
|
* @return {string} 截断后的字符串。
|
||||||
|
*/
|
||||||
|
truncateLogBody(value) {
|
||||||
|
const str = typeof value === 'string' ? value : JSON.stringify(value || '');
|
||||||
|
if (str.length > LOG_BODY_MAX) {
|
||||||
|
return str.substring(0, LOG_BODY_MAX);
|
||||||
|
}
|
||||||
|
return str;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 获取仓库 ApiApp 回调配置(URL + 签名凭证)。
|
||||||
|
* @param {number} warehouseId 仓库 ID。
|
||||||
|
* @return {Promise<{url: string|null, appKey: string|null, appSecret: string|null}>} 回调配置。
|
||||||
|
*/
|
||||||
|
async getCallbackConfig(warehouseId) {
|
||||||
|
const { ctx } = this;
|
||||||
|
if (!Number.isFinite(warehouseId) || warehouseId <= 0) {
|
||||||
|
return { url: null, appKey: null, appSecret: null };
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const apiApp = await ctx.model.ApiApp.findOne({
|
||||||
|
attributes: [ 'callback_url', 'self_app_key', 'self_app_secret' ],
|
||||||
|
where: {
|
||||||
|
warehouse_id: warehouseId,
|
||||||
|
interface_type_id: WAREHOUSE_INTERFACE_TYPE_ID,
|
||||||
|
is_enabled: 1,
|
||||||
|
},
|
||||||
|
raw: true,
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
url: (apiApp && apiApp.callback_url) || null,
|
||||||
|
appKey: (apiApp && apiApp.self_app_key) || null,
|
||||||
|
appSecret: (apiApp && apiApp.self_app_secret) || null,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
ctx.logger.warn(`[warehouseNotify] 查询回调配置失败: ${error.message}`);
|
||||||
|
return { url: null, appKey: null, appSecret: null };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 计算 MD5 签名:MD5(appSecret + timestamp + bodyJson)。
|
||||||
|
* @param {Object} options 签名参数。
|
||||||
|
* @param {string} options.appSecret 应用密钥。
|
||||||
|
* @param {number} options.timestamp Unix 秒时间戳。
|
||||||
|
* @param {string} options.bodyJson 请求体 JSON 字符串。
|
||||||
|
* @return {string} 签名 hex。
|
||||||
|
*/
|
||||||
|
buildSignature({ appSecret, timestamp, bodyJson }) {
|
||||||
|
return appSecret
|
||||||
|
? crypto.createHash('md5').update(appSecret + timestamp + bodyJson).digest('hex')
|
||||||
|
: '';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 写入仓库接口日志(失败仅记日志不抛出)。
|
||||||
|
* @param {Object} options 日志参数。
|
||||||
|
* @param {string} [options.appKey] API 应用 AppKey。
|
||||||
|
* @param {string} [options.method] 请求方法名。
|
||||||
|
* @param {number} [options.warehouseId] 仓库 ID。
|
||||||
|
* @param {string} [options.url] 请求 URL。
|
||||||
|
* @param {number} [options.httpStatus] HTTP 状态码。
|
||||||
|
* @param {*} [options.body] 请求体。
|
||||||
|
* @param {*} [options.result] 响应体。
|
||||||
|
* @param {number} [options.useTime] 耗时(毫秒)。
|
||||||
|
* @return {Promise<void>}
|
||||||
|
*/
|
||||||
|
async writeLog({
|
||||||
|
appKey,
|
||||||
|
method,
|
||||||
|
warehouseId,
|
||||||
|
url,
|
||||||
|
httpStatus,
|
||||||
|
body,
|
||||||
|
result,
|
||||||
|
useTime,
|
||||||
|
} = {}) {
|
||||||
|
const { ctx } = this;
|
||||||
|
const logModel = ctx.model && ctx.model.WarehouseLog;
|
||||||
|
if (!logModel || typeof logModel.create !== 'function') {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await logModel.create({
|
||||||
|
log_id: 'WN-' + Date.now() + '-' + crypto.randomBytes(3).toString('hex'),
|
||||||
|
app_key: appKey || null,
|
||||||
|
method,
|
||||||
|
warehouse_id: warehouseId || null,
|
||||||
|
url: url || null,
|
||||||
|
http_status: httpStatus || null,
|
||||||
|
body: this.truncateLogBody(body),
|
||||||
|
result: this.truncateLogBody(result),
|
||||||
|
use_time: useTime || null,
|
||||||
|
created_at: new Date(),
|
||||||
|
});
|
||||||
|
} catch (logErr) {
|
||||||
|
ctx.logger.error('[warehouseNotify] 日志写入失败: ' + logErr.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 向仓库 ApiApp 回调地址推送消息(MD5 签名 + POST)。
|
||||||
|
* @param {Object} options 推送参数。
|
||||||
|
* @param {number} options.warehouseId 仓库 ID。
|
||||||
|
* @param {string} [options.method='notify.reply'] 出站 method。
|
||||||
|
* @param {Object} [options.data={}] 消息数据(包裹在 body.data 中)。
|
||||||
|
* @return {Promise<Object>} 推送结果。
|
||||||
|
*/
|
||||||
|
async push({ warehouseId, method = 'notify.reply', data = {} } = {}) {
|
||||||
|
const { ctx } = this;
|
||||||
|
|
||||||
|
const config = await this.getCallbackConfig(warehouseId);
|
||||||
|
if (!config.url) {
|
||||||
|
ctx.logger.info(`[warehouseNotify] 仓库 ${warehouseId} 未配置回调地址,跳过推送 method=${method}`);
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
skipped: true,
|
||||||
|
reason: '未配置回调地址(wms_api_app.callback_url 为空)',
|
||||||
|
warehouseId,
|
||||||
|
method,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const body = { code: 200, data };
|
||||||
|
const bodyJson = JSON.stringify(body);
|
||||||
|
const timestamp = Math.floor(Date.now() / 1000);
|
||||||
|
const sign = this.buildSignature({
|
||||||
|
appSecret: config.appSecret,
|
||||||
|
timestamp,
|
||||||
|
bodyJson,
|
||||||
|
});
|
||||||
|
|
||||||
|
const queryString = [
|
||||||
|
`app_key=${encodeURIComponent(config.appKey || '')}`,
|
||||||
|
`method=${encodeURIComponent(method)}`,
|
||||||
|
`timestamp=${timestamp}`,
|
||||||
|
`sign=${encodeURIComponent(sign)}`,
|
||||||
|
].join('&');
|
||||||
|
const separator = config.url.includes('?') ? '&' : '?';
|
||||||
|
const url = `${config.url}${separator}${queryString}`;
|
||||||
|
const startTime = Date.now();
|
||||||
|
|
||||||
|
try {
|
||||||
|
const curlResult = await ctx.curl(url, {
|
||||||
|
method: 'POST',
|
||||||
|
dataType: 'json',
|
||||||
|
contentType: 'json',
|
||||||
|
data: body,
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
timeout: REQUEST_TIMEOUT_MS,
|
||||||
|
});
|
||||||
|
|
||||||
|
// HTTP 200 且 body.code=200(或未返回 code)→ 推送成功
|
||||||
|
const pushOk = curlResult && curlResult.status === 200
|
||||||
|
&& (!curlResult.data || curlResult.data.code === undefined || curlResult.data.code === 200);
|
||||||
|
|
||||||
|
await this.writeLog({
|
||||||
|
appKey: config.appKey,
|
||||||
|
method,
|
||||||
|
warehouseId,
|
||||||
|
url,
|
||||||
|
httpStatus: curlResult ? curlResult.status : null,
|
||||||
|
body: bodyJson,
|
||||||
|
result: curlResult ? curlResult.data || {} : {},
|
||||||
|
useTime: Date.now() - startTime,
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: pushOk,
|
||||||
|
skipped: false,
|
||||||
|
warehouseId,
|
||||||
|
method,
|
||||||
|
httpStatus: curlResult ? curlResult.status : null,
|
||||||
|
response: curlResult ? (curlResult.data || null) : null,
|
||||||
|
error: pushOk ? null : '回调返回非200或code非200',
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
await this.writeLog({
|
||||||
|
appKey: config.appKey,
|
||||||
|
method,
|
||||||
|
warehouseId,
|
||||||
|
url,
|
||||||
|
httpStatus: null,
|
||||||
|
body: bodyJson,
|
||||||
|
result: 'Error: ' + error.message,
|
||||||
|
useTime: Date.now() - startTime,
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
skipped: false,
|
||||||
|
warehouseId,
|
||||||
|
method,
|
||||||
|
httpStatus: null,
|
||||||
|
response: null,
|
||||||
|
error: error.message,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 向指定群推送系统级业务通知(复用 notify.reply,type=system)。
|
||||||
|
* 对方接口只处理 content 内容,推送体仅保留协议必需字段:
|
||||||
|
* type / content / ext_id / group_id / group_name / timestamp。
|
||||||
|
* 推送前写入 wms_inbox_message(direction=outbound,source_type=system),
|
||||||
|
* 推送后按结果回写 push_status(2=已送达 / 3=失败)与 push_response。
|
||||||
|
* @param {Object} options 推送参数。
|
||||||
|
* @param {number} options.warehouseId 仓库 ID。
|
||||||
|
* @param {number} [options.storeId] 货主 ID。
|
||||||
|
* @param {Object} options.group 目标群 { group_id, group_name }。
|
||||||
|
* @param {string} [options.content=''] 通知正文。
|
||||||
|
* @param {number|string} [options.extId] 业务单号(用于幂等 ext_id)。
|
||||||
|
* @return {Promise<Object>} 推送结果(含 messageId)。
|
||||||
|
*/
|
||||||
|
async pushSystemMessage({ warehouseId, storeId = null, group, content = '', extId = null } = {}) {
|
||||||
|
const { ctx } = this;
|
||||||
|
const groupId = String((group && group.group_id) || '').trim();
|
||||||
|
const groupName = String((group && group.group_name) || '').trim();
|
||||||
|
|
||||||
|
if (!groupId || !groupName) {
|
||||||
|
return {
|
||||||
|
success: false,
|
||||||
|
skipped: true,
|
||||||
|
reason: '目标群缺少 group_id 或 group_name',
|
||||||
|
warehouseId,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// 幂等 ext_id:业务单号 + 群维度,网络重推时复用同一条消息记录
|
||||||
|
const sourceExtId = String(extId || `sys:notice:${Date.now()}:${Math.random().toString(36).slice(2, 8)}`);
|
||||||
|
const uniqueExtId = `sys:notice:${sourceExtId}:${groupId}`;
|
||||||
|
|
||||||
|
const InboxMessage = ctx.model && ctx.model.InboxMessage;
|
||||||
|
const normalizedContent = String(content || '').trim() || '系统通知';
|
||||||
|
let messageId = null;
|
||||||
|
|
||||||
|
if (InboxMessage) {
|
||||||
|
try {
|
||||||
|
const existing = await InboxMessage.findOne({
|
||||||
|
where: { ext_id: uniqueExtId },
|
||||||
|
attributes: [ 'id' ],
|
||||||
|
paranoid: false,
|
||||||
|
});
|
||||||
|
if (existing) {
|
||||||
|
messageId = Number(existing.id);
|
||||||
|
} else {
|
||||||
|
const created = await InboxMessage.create({
|
||||||
|
ext_id: uniqueExtId,
|
||||||
|
warehouse_id: Number(warehouseId || 0),
|
||||||
|
store_id: Number(storeId || 0) > 0 ? Number(storeId) : null,
|
||||||
|
direction: 'outbound',
|
||||||
|
parent_id: null,
|
||||||
|
source_type: 'system',
|
||||||
|
source_extra: 'notice',
|
||||||
|
target_type: 'api',
|
||||||
|
group_id: groupId,
|
||||||
|
user_id: null,
|
||||||
|
group_name: groupName,
|
||||||
|
user_name: null,
|
||||||
|
content: normalizedContent,
|
||||||
|
ext_data: null,
|
||||||
|
flags: {},
|
||||||
|
push_status: 1,
|
||||||
|
push_started_at: new Date(),
|
||||||
|
});
|
||||||
|
messageId = Number(created.id);
|
||||||
|
}
|
||||||
|
} catch (messageErr) {
|
||||||
|
ctx.logger.warn('[warehouseNotify] 写消息表失败: ' + messageErr.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const result = await this.push({
|
||||||
|
warehouseId,
|
||||||
|
method: 'notify.reply',
|
||||||
|
data: {
|
||||||
|
type: 'system',
|
||||||
|
content: normalizedContent,
|
||||||
|
ext_id: sourceExtId,
|
||||||
|
group_id: groupId,
|
||||||
|
group_name: groupName,
|
||||||
|
timestamp: Math.floor(Date.now() / 1000),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// 回写推送状态(失败仅记日志,不影响业务)
|
||||||
|
if (InboxMessage && messageId) {
|
||||||
|
try {
|
||||||
|
if (result.success) {
|
||||||
|
await InboxMessage.update({
|
||||||
|
push_status: 2,
|
||||||
|
push_response: {
|
||||||
|
http_status: result.httpStatus,
|
||||||
|
body: result.response || null,
|
||||||
|
},
|
||||||
|
pushed_at: new Date(),
|
||||||
|
}, { where: { id: messageId } });
|
||||||
|
} else {
|
||||||
|
await InboxMessage.update({
|
||||||
|
push_status: 3,
|
||||||
|
push_response: {
|
||||||
|
http_status: result.httpStatus,
|
||||||
|
body: result.response || null,
|
||||||
|
error: result.error || result.reason || '推送失败',
|
||||||
|
},
|
||||||
|
}, { where: { id: messageId } });
|
||||||
|
}
|
||||||
|
} catch (updateErr) {
|
||||||
|
ctx.logger.warn('[warehouseNotify] 回写推送状态失败: ' + updateErr.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return { ...result, messageId };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
module.exports = WarehouseNotifyService;
|
||||||
@ -212,6 +212,10 @@ module.exports = appInfo => {
|
|||||||
config.printService = {
|
config.printService = {
|
||||||
url: 'http://printer.wms.gztbyc.com',
|
url: 'http://printer.wms.gztbyc.com',
|
||||||
};
|
};
|
||||||
|
// 仓库侧前端地址(通知文案快速查看链接)
|
||||||
|
config.frontendUrl = 'http://wms.wms.gztbyc.com';
|
||||||
|
// 货主侧前端地址(货主群通知使用,与仓库侧不同)
|
||||||
|
config.storeFrontendUrl = 'http://store.wms.gztbyc.com';
|
||||||
config.printRetryCompensation = {
|
config.printRetryCompensation = {
|
||||||
enable: false,
|
enable: false,
|
||||||
intervalMs: 60 * 1000,
|
intervalMs: 60 * 1000,
|
||||||
|
|||||||
@ -81,5 +81,71 @@
|
|||||||
"过滤点位于屏蔽检查之后、绑群码识别之前,仅拦截自动处理链路"
|
"过滤点位于屏蔽检查之后、绑群码识别之前,仅拦截自动处理链路"
|
||||||
],
|
],
|
||||||
"module": "inbox"
|
"module": "inbox"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "2026-08-16-warehouse-01",
|
||||||
|
"date": "2026-08-16",
|
||||||
|
"type": "changed",
|
||||||
|
"summary": "统一通知系统接入仓库接口消息推送通道:收货完成/驳回/审核通知不再依赖 wms_notification_webhook 配置,按固定群订阅直接推送到仓库收货群与货主收货群",
|
||||||
|
"methods": [
|
||||||
|
"notify.reply"
|
||||||
|
],
|
||||||
|
"notes": [
|
||||||
|
"新增 app/service/systems/warehouseNotify.js:仓库接口出站推送服务(MD5 签名 + wms_api_app.callback_url + wms_warehouse_log 日志),供统一通知复用",
|
||||||
|
"notice/index.js 新增 FIXED_GROUP_SUBSCRIPTIONS 固定订阅:receiving_completed / receiving_rejected / receiving_reviewed → warehouse:receiving + store:receiving(群类型定义见 inbox/groups.js GROUP_TYPES)",
|
||||||
|
"notice.send 支持 channel 路由:warehouse|group=走仓库接口通道(不查 webhook 配置)、webhook=默认订阅配置、both=双通道",
|
||||||
|
"receiving.js 三处通知(sendCompletionNotice/sendReviewNotice/rejectReceiving)已传 channel=warehouse,业务链路不再依赖 wms_notification_webhook 表",
|
||||||
|
"推送复用 notify.reply,data.type=system,data 仅携带 content(通知正文)与 ext_id(业务单号,幂等),接收方只处理 content",
|
||||||
|
"货主收货群匹配需要 store_id(来自收货单 receiving.store_id);无 store_id 或未配置群时仅推仓库收货群或静默跳过,不影响业务主流程"
|
||||||
|
],
|
||||||
|
"module": "warehouse"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "2026-08-16-warehouse-02",
|
||||||
|
"date": "2026-08-16",
|
||||||
|
"type": "changed",
|
||||||
|
"summary": "统一通知全面迁移仓库接口通道:移除对 wms_notification_webhook 表的读取,全部事件默认经 wms_api_app 配置按固定群订阅推送",
|
||||||
|
"methods": [
|
||||||
|
"notify.reply"
|
||||||
|
],
|
||||||
|
"notes": [
|
||||||
|
"notice.send 默认 channel 由 webhook 改为 warehouse:全部通知统一走仓库接口消息推送(wms_api_app.callback_url + 固定群订阅)",
|
||||||
|
"findMatchedWebhooks 移除 NotificationWebhook.findAll 数据库查询,webhook 通道仅支持调用方显式传入 hooks(channel=webhook 时)",
|
||||||
|
"FIXED_GROUP_SUBSCRIPTIONS 补齐全部事件:order_cancel_intercepted→warehouse:exception、order_sync_completed→store:after_sales(货主售后群,文案为每行一个订单:订单xx 姓名:xx 电话:xx 运单号:xx)、store_warehouse_print_quantity_adjusted→store:finance、storage_transfer_completed→warehouse:production、wave_strategy_quick_scan_failed→warehouse:exception",
|
||||||
|
"resolveSubjectConfig 增加 ctx.service 防御判断,兼容单元测试与最小上下文",
|
||||||
|
"test/app/service/systems/notice.test.js 适配新通道:webhook 行为用例改为显式 channel=webhook + hooks 入参,全部 12 用例通过"
|
||||||
|
],
|
||||||
|
"module": "warehouse"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "2026-08-17-warehouse-01",
|
||||||
|
"date": "2026-08-17",
|
||||||
|
"type": "changed",
|
||||||
|
"summary": "订单同步通知去抖合并:订单同步完成后不再逐单立即通知,等待 3 分钟无新同步后按「仓库:货主」维度合并为一条消息统一推送到货主售后群",
|
||||||
|
"methods": [
|
||||||
|
"notify.reply"
|
||||||
|
],
|
||||||
|
"notes": [
|
||||||
|
"order_async.js 新增合并队列:每次同步成功后把订单(单号/姓名/电话/运单号)写入 Redis(order_sync_notice:list:{warehouseId}:{storeId}),到期时间记录在 order_sync_notice:queue ZSET(最后一次同步 + 3 分钟)",
|
||||||
|
"新增定时任务 app/schedule/order_sync_notice_flush.js(每 30s,worker):扫描到期成员,加锁后原子 RENAME 取出列表,合并为「订单同步完成(共 N 单)+ 每单一行」的单条消息推送",
|
||||||
|
"发送失败重试:条目放回队列,2 分钟后重试,最多 5 次后放弃并记录错误日志;单条消息最多列 30 单,超出尾部提示「……其余 N 单未列出」",
|
||||||
|
"Redis 不可用或入队失败时回退为逐单立即通知(保持原有行为),订单同步流程不受影响",
|
||||||
|
"新增 test/app/service/systems/order_async.noticeDebounce.test.js:5 个用例覆盖入队不立即发、窗口内不冲刷、到期合并单条推送、多订单合并、发送失败重试"
|
||||||
|
],
|
||||||
|
"module": "order"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"version": "2026-08-17-warehouse-02",
|
||||||
|
"date": "2026-08-17",
|
||||||
|
"type": "removed",
|
||||||
|
"summary": "移除移库完成群通知:库存移库(transferLocation 按记录移库 / transferByProduct 按商品移库)完成后不再推送「移库操作完成/按商品移库操作完成」通知",
|
||||||
|
"methods": [
|
||||||
|
"notify.reply"
|
||||||
|
],
|
||||||
|
"notes": [
|
||||||
|
"app/service/systems/storage/inventory.js 删除 transferLocation 与 transferByProduct 事务提交后的 notice.send 调用,移库业务本身不受影响",
|
||||||
|
"事件码 storage_transfer_completed 仍保留注册:app/schedule/notice_stock_remaining.js 库存余量每日提醒复用该事件码,固定群映射 warehouse:production 不变"
|
||||||
|
],
|
||||||
|
"module": "storage"
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
|
|||||||
@ -153,7 +153,8 @@
|
|||||||
"type=balance:绑群成功后自动推送面单余额",
|
"type=balance:绑群成功后自动推送面单余额",
|
||||||
"type=error:AI 无法处理时的兜底回复",
|
"type=error:AI 无法处理时的兜底回复",
|
||||||
"AI silent(无需回复)时不推送",
|
"AI silent(无需回复)时不推送",
|
||||||
"ext_id 为 wms_inbox_message.id 主键,接收方应以 ext_id 做幂等去重,网络波动可能重推"
|
"ext_id 为 wms_inbox_message.id 主键,接收方应以 ext_id 做幂等去重,网络波动可能重推",
|
||||||
|
"type=system:系统级业务事件通知(收货完成/驳回/审核等,不要求 user_id/user_name),data 仅携带 content(通知正文,接收方只处理该字段)与 ext_id(业务单号,用于幂等去重),其余协议字段为 group_id / group_name / timestamp"
|
||||||
],
|
],
|
||||||
"example": {
|
"example": {
|
||||||
"query": "?app_key=AK001×tamp=1786100000&sign=abc",
|
"query": "?app_key=AK001×tamp=1786100000&sign=abc",
|
||||||
|
|||||||
@ -46,6 +46,7 @@
|
|||||||
"file-writer:pressure": "node ./temp/generated-tests/file-writer-pressure.generated.test.cjs",
|
"file-writer:pressure": "node ./temp/generated-tests/file-writer-pressure.generated.test.cjs",
|
||||||
"debug:webhook:receiver": "node ./script/debug-webhook-receiver.cjs",
|
"debug:webhook:receiver": "node ./script/debug-webhook-receiver.cjs",
|
||||||
"debug:webhook:receiving": "node ./script/debug-send-receiving-webhooks.cjs",
|
"debug:webhook:receiving": "node ./script/debug-send-receiving-webhooks.cjs",
|
||||||
|
"debug:warehouse:push-receiver": "node ./script/debug-warehouse-push-receiver.cjs",
|
||||||
"doc:api:update": "node ./script/update-api-doc.cjs",
|
"doc:api:update": "node ./script/update-api-doc.cjs",
|
||||||
"doc:api:update:dry": "node ./script/update-api-doc.cjs --dry-run",
|
"doc:api:update:dry": "node ./script/update-api-doc.cjs --dry-run",
|
||||||
"deploy:precheck": "node ./script/deploy-precheck.cjs",
|
"deploy:precheck": "node ./script/deploy-precheck.cjs",
|
||||||
|
|||||||
116
script/debug-complete-receiving.cjs
Normal file
116
script/debug-complete-receiving.cjs
Normal file
@ -0,0 +1,116 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 调试脚本:为指定账号铸造 JWT 并调用系统接口完成收货。
|
||||||
|
* 用法:
|
||||||
|
* node script/debug-complete-receiving.cjs --receiving-id=1512 --account-id=1
|
||||||
|
* node script/debug-complete-receiving.cjs --receiving-id=1512 --account-id=1 --host=127.0.0.1 --port=6060
|
||||||
|
*/
|
||||||
|
|
||||||
|
const http = require('node:http');
|
||||||
|
const jwt = require('jsonwebtoken');
|
||||||
|
|
||||||
|
const JWT_SECRET = 'E5#ex.g@,GfL_8?';
|
||||||
|
const JWT_EXPIRES_IN = 14400;
|
||||||
|
|
||||||
|
function parseArgs(argv) {
|
||||||
|
const options = {
|
||||||
|
receivingId: 0,
|
||||||
|
accountId: 1,
|
||||||
|
host: '127.0.0.1',
|
||||||
|
port: 6060,
|
||||||
|
remark: '',
|
||||||
|
};
|
||||||
|
|
||||||
|
for (const arg of argv) {
|
||||||
|
if (!arg.startsWith('--')) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
const [ rawKey, ...rest ] = arg.slice(2).split('=');
|
||||||
|
const value = rest.join('=');
|
||||||
|
switch (rawKey) {
|
||||||
|
case 'receiving-id':
|
||||||
|
options.receivingId = Number(value || options.receivingId);
|
||||||
|
break;
|
||||||
|
case 'account-id':
|
||||||
|
options.accountId = Number(value || options.accountId);
|
||||||
|
break;
|
||||||
|
case 'host':
|
||||||
|
options.host = value || options.host;
|
||||||
|
break;
|
||||||
|
case 'port':
|
||||||
|
options.port = Number(value || options.port);
|
||||||
|
break;
|
||||||
|
case 'remark':
|
||||||
|
options.remark = value || '';
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return options;
|
||||||
|
}
|
||||||
|
|
||||||
|
function postSystemMethod(options, token, method, body) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const bodyJson = JSON.stringify(body);
|
||||||
|
const path = `/system?method=${encodeURIComponent(method)}&v=1×tamp=${Math.floor(Date.now() / 1000)}`;
|
||||||
|
const req = http.request({
|
||||||
|
hostname: options.host,
|
||||||
|
port: options.port,
|
||||||
|
path,
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
platform: 'web',
|
||||||
|
project: 'wms',
|
||||||
|
Authorization: `Bearer ${token}`,
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
'Content-Length': Buffer.byteLength(bodyJson),
|
||||||
|
},
|
||||||
|
}, res => {
|
||||||
|
let data = '';
|
||||||
|
res.on('data', chunk => {
|
||||||
|
data += chunk;
|
||||||
|
});
|
||||||
|
res.on('end', () => {
|
||||||
|
resolve({ status: res.statusCode, body: data });
|
||||||
|
});
|
||||||
|
});
|
||||||
|
req.on('error', reject);
|
||||||
|
req.write(bodyJson);
|
||||||
|
req.end();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
const options = parseArgs(process.argv.slice(2));
|
||||||
|
if (!options.receivingId) {
|
||||||
|
console.error('缺少 --receiving-id');
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
|
||||||
|
const token = jwt.sign({
|
||||||
|
id: options.accountId,
|
||||||
|
platform_code: 'web',
|
||||||
|
current_store_id: 100000,
|
||||||
|
}, JWT_SECRET, { expiresIn: JWT_EXPIRES_IN });
|
||||||
|
|
||||||
|
console.log(`[debug-complete-receiving] accountId=${options.accountId} receivingId=${options.receivingId}`);
|
||||||
|
const result = await postSystemMethod(options, token, 'storage.receiving.completeReceiving', {
|
||||||
|
id: options.receivingId,
|
||||||
|
remark: options.remark || undefined,
|
||||||
|
});
|
||||||
|
|
||||||
|
console.log(`HTTP ${result.status}`);
|
||||||
|
try {
|
||||||
|
console.log(JSON.stringify(JSON.parse(result.body), null, 2).substring(0, 3000));
|
||||||
|
} catch (_) {
|
||||||
|
console.log(result.body.substring(0, 1000));
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch(error => {
|
||||||
|
console.error('[debug-complete-receiving] failed:', error.message);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
206
script/debug-warehouse-push-receiver.cjs
Normal file
206
script/debug-warehouse-push-receiver.cjs
Normal file
@ -0,0 +1,206 @@
|
|||||||
|
'use strict';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* 仓库接口消息推送 — 本地调试接收服务。
|
||||||
|
* 模拟外部适配器:接收 WMS 出站推送(notify.reply / notify.event 等),
|
||||||
|
* 打印完整回信(query 签名参数 + headers + body)到控制台与日志文件,方便调试。
|
||||||
|
*
|
||||||
|
* 默认配置匹配线上仓库「仓库管理系统oms」:
|
||||||
|
* app_key=APP2025011514315678
|
||||||
|
* app_secret=sec_xyz789uvw012abc345def678ghi901jkl234mno567pqr890
|
||||||
|
* callback_url=http://localhost:6061/push
|
||||||
|
*
|
||||||
|
* 用法:
|
||||||
|
* npm run debug:warehouse:push-receiver
|
||||||
|
* node script/debug-warehouse-push-receiver.cjs --port=6061 --path=/push --log-file=run/push.log
|
||||||
|
* node script/debug-warehouse-push-receiver.cjs --no-verify # 跳过 MD5 验签
|
||||||
|
*/
|
||||||
|
|
||||||
|
const http = require('node:http');
|
||||||
|
const fs = require('node:fs');
|
||||||
|
const path = require('node:path');
|
||||||
|
const crypto = require('node:crypto');
|
||||||
|
const { URL } = require('node:url');
|
||||||
|
|
||||||
|
const DEFAULT_HOST = '127.0.0.1';
|
||||||
|
const DEFAULT_PORT = 6061;
|
||||||
|
const DEFAULT_PATH = '/push';
|
||||||
|
const DEFAULT_APP_KEY = 'APP2025011514315678';
|
||||||
|
const DEFAULT_APP_SECRET = 'sec_xyz789uvw012abc345def678ghi901jkl234mno567pqr890';
|
||||||
|
const DEFAULT_LOG_FILE = path.join(process.cwd(), 'run', 'warehouse-push-receiver.log');
|
||||||
|
|
||||||
|
function parseArgs(argv) {
|
||||||
|
const options = {
|
||||||
|
host: process.env.PUSH_RECEIVER_HOST || DEFAULT_HOST,
|
||||||
|
port: Number(process.env.PUSH_RECEIVER_PORT || DEFAULT_PORT),
|
||||||
|
path: process.env.PUSH_RECEIVER_PATH || DEFAULT_PATH,
|
||||||
|
appKey: process.env.PUSH_RECEIVER_APP_KEY || DEFAULT_APP_KEY,
|
||||||
|
appSecret: process.env.PUSH_RECEIVER_APP_SECRET || DEFAULT_APP_SECRET,
|
||||||
|
logFile: process.env.PUSH_RECEIVER_LOG_FILE || DEFAULT_LOG_FILE,
|
||||||
|
verifySign: ![ '0', 'false' ].includes(String(process.env.PUSH_RECEIVER_VERIFY_SIGN || '1').toLowerCase()),
|
||||||
|
help: false,
|
||||||
|
};
|
||||||
|
|
||||||
|
for (const arg of argv) {
|
||||||
|
if (!arg.startsWith('--')) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
const [ rawKey, ...rest ] = arg.slice(2).split('=');
|
||||||
|
const value = rest.join('=');
|
||||||
|
switch (rawKey) {
|
||||||
|
case 'host':
|
||||||
|
options.host = value || options.host;
|
||||||
|
break;
|
||||||
|
case 'port':
|
||||||
|
options.port = Number(value || options.port);
|
||||||
|
break;
|
||||||
|
case 'path':
|
||||||
|
options.path = value.startsWith('/') ? value : `/${value}`;
|
||||||
|
break;
|
||||||
|
case 'app-key':
|
||||||
|
options.appKey = value || options.appKey;
|
||||||
|
break;
|
||||||
|
case 'app-secret':
|
||||||
|
options.appSecret = value || options.appSecret;
|
||||||
|
break;
|
||||||
|
case 'log-file':
|
||||||
|
options.logFile = value || options.logFile;
|
||||||
|
break;
|
||||||
|
case 'no-verify':
|
||||||
|
options.verifySign = false;
|
||||||
|
break;
|
||||||
|
case 'help':
|
||||||
|
options.help = true;
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return options;
|
||||||
|
}
|
||||||
|
|
||||||
|
function printHelp() {
|
||||||
|
console.log(`用法:
|
||||||
|
npm run debug:warehouse:push-receiver
|
||||||
|
node script/debug-warehouse-push-receiver.cjs --port=6061 --path=/push --log-file=run/push.log
|
||||||
|
node script/debug-warehouse-push-receiver.cjs --no-verify
|
||||||
|
|
||||||
|
参数:
|
||||||
|
--host=127.0.0.1 监听地址
|
||||||
|
--port=6061 监听端口
|
||||||
|
--path=/push 接收路径
|
||||||
|
--app-key=... 期望的 app_key(仅用于展示)
|
||||||
|
--app-secret=... 验签密钥(MD5(appSecret + timestamp + bodyJson))
|
||||||
|
--log-file=... 日志文件(默认 run/warehouse-push-receiver.log)
|
||||||
|
--no-verify 跳过 MD5 验签
|
||||||
|
|
||||||
|
环境变量:
|
||||||
|
PUSH_RECEIVER_HOST / PUSH_RECEIVER_PORT / PUSH_RECEIVER_PATH
|
||||||
|
PUSH_RECEIVER_APP_KEY / PUSH_RECEIVER_APP_SECRET / PUSH_RECEIVER_LOG_FILE
|
||||||
|
PUSH_RECEIVER_VERIFY_SIGN=0 关闭验签`);
|
||||||
|
}
|
||||||
|
|
||||||
|
function readRequestBody(req) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
const chunks = [];
|
||||||
|
req.on('data', chunk => chunks.push(chunk));
|
||||||
|
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
|
||||||
|
req.on('error', reject);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function writeLog(logFile, text) {
|
||||||
|
const line = text.endsWith('\n') ? text : text + '\n';
|
||||||
|
try {
|
||||||
|
fs.appendFileSync(logFile, line, 'utf8');
|
||||||
|
console.log(`[push-receiver] 已写入日志文件: ${logFile}`);
|
||||||
|
} catch (error) {
|
||||||
|
console.error('[push-receiver] 写日志文件失败:', error.message);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function md5(value) {
|
||||||
|
return crypto.createHash('md5').update(value).digest('hex');
|
||||||
|
}
|
||||||
|
|
||||||
|
async function start() {
|
||||||
|
const options = parseArgs(process.argv.slice(2));
|
||||||
|
if (options.help) {
|
||||||
|
printHelp();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
const logFile = path.resolve(options.logFile);
|
||||||
|
const logDir = path.dirname(logFile);
|
||||||
|
fs.mkdirSync(logDir, { recursive: true });
|
||||||
|
|
||||||
|
const server = http.createServer(async (req, res) => {
|
||||||
|
const url = new URL(req.url, `http://${req.headers.host || `${options.host}:${options.port}`}`);
|
||||||
|
const startedAt = new Date().toISOString();
|
||||||
|
const rawBody = await readRequestBody(req);
|
||||||
|
const query = Object.fromEntries(url.searchParams.entries());
|
||||||
|
|
||||||
|
if (url.pathname === '/health') {
|
||||||
|
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' });
|
||||||
|
res.end(JSON.stringify({ ok: true, service: 'warehouse-push-receiver' }));
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (req.method !== 'POST' || url.pathname !== options.path) {
|
||||||
|
res.writeHead(404, { 'content-type': 'text/plain; charset=utf-8' });
|
||||||
|
res.end(`404 Not Found(接收路径为 ${options.path})`);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
// MD5 验签:sign = MD5(appSecret + timestamp + bodyJson)
|
||||||
|
const timestamp = String(query.timestamp || '');
|
||||||
|
const providedSign = String(query.sign || '');
|
||||||
|
const expectedSign = options.appSecret ? md5(options.appSecret + timestamp + rawBody) : '';
|
||||||
|
const signOk = !options.verifySign || (timestamp && providedSign === expectedSign);
|
||||||
|
|
||||||
|
let parsedBody = rawBody;
|
||||||
|
try {
|
||||||
|
parsedBody = rawBody ? JSON.parse(rawBody) : null;
|
||||||
|
} catch (_) {
|
||||||
|
// keep raw text
|
||||||
|
}
|
||||||
|
|
||||||
|
const logText = [
|
||||||
|
'================ 收到仓库接口推送 ================',
|
||||||
|
`[time] ${startedAt}`,
|
||||||
|
`[route] POST ${url.pathname}`,
|
||||||
|
`[query] ${JSON.stringify(query, null, 2)}`,
|
||||||
|
options.verifySign
|
||||||
|
? `[sign] ${signOk ? '验签通过' : `验签失败(期望 ${expectedSign})`}`
|
||||||
|
: '[sign] 已关闭验签',
|
||||||
|
`[header] ${JSON.stringify(req.headers, null, 2)}`,
|
||||||
|
`[body] ${JSON.stringify(parsedBody, null, 2)}`,
|
||||||
|
'==================================================',
|
||||||
|
].join('\n');
|
||||||
|
|
||||||
|
console.log('\n' + logText);
|
||||||
|
writeLog(logFile, `${logText}\n`);
|
||||||
|
|
||||||
|
// 始终返回 HTTP 200 + code=200,便于 WMS 判定推送成功
|
||||||
|
const responseBody = JSON.stringify({ code: 200, message: 'ok', received_at: startedAt });
|
||||||
|
res.writeHead(200, { 'content-type': 'application/json; charset=utf-8' });
|
||||||
|
res.end(responseBody);
|
||||||
|
});
|
||||||
|
|
||||||
|
server.listen(options.port, options.host, () => {
|
||||||
|
console.log('[warehouse-push-receiver] listening on http://' + options.host + ':' + options.port + options.path);
|
||||||
|
console.log(`[warehouse-push-receiver] app_key=${options.appKey}`);
|
||||||
|
console.log(`[warehouse-push-receiver] app_secret=${options.appSecret ? options.appSecret.slice(0, 8) + '…' : '(空)'}`);
|
||||||
|
console.log(`[warehouse-push-receiver] 验签=${options.verifySign ? '开启' : '关闭'}`);
|
||||||
|
console.log(`[warehouse-push-receiver] 日志文件=${logFile}`);
|
||||||
|
console.log(`[warehouse-push-receiver] 健康检查: GET http://${options.host}:${options.port}/health`);
|
||||||
|
console.log('[warehouse-push-receiver] 按 Ctrl+C 停止');
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
start().catch(error => {
|
||||||
|
console.error('[warehouse-push-receiver] failed:', error);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
@ -53,6 +53,8 @@ describe('test/app/service/systems/notice.test.js', () => {
|
|||||||
|
|
||||||
const service = new NoticeService(ctx);
|
const service = new NoticeService(ctx);
|
||||||
const result = await service.send({
|
const result = await service.send({
|
||||||
|
channel: 'webhook',
|
||||||
|
hooks: webhookRows,
|
||||||
messageType: '图片',
|
messageType: '图片',
|
||||||
businessName: 'receiving',
|
businessName: 'receiving',
|
||||||
event: 'receiving_completed',
|
event: 'receiving_completed',
|
||||||
@ -274,6 +276,23 @@ describe('test/app/service/systems/notice.test.js', () => {
|
|||||||
|
|
||||||
const service = new NoticeService(ctx);
|
const service = new NoticeService(ctx);
|
||||||
const result = await service.send({
|
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: '文本',
|
messageType: '文本',
|
||||||
businessName: 'receiving',
|
businessName: 'receiving',
|
||||||
event: 'receiving_completed',
|
event: 'receiving_completed',
|
||||||
@ -334,6 +353,8 @@ describe('test/app/service/systems/notice.test.js', () => {
|
|||||||
|
|
||||||
const service = new NoticeService(ctx);
|
const service = new NoticeService(ctx);
|
||||||
const result = await service.send({
|
const result = await service.send({
|
||||||
|
channel: 'webhook',
|
||||||
|
hooks: webhookRows,
|
||||||
messageType: '文本',
|
messageType: '文本',
|
||||||
businessName: 'receiving',
|
businessName: 'receiving',
|
||||||
event: 'receiving_completed',
|
event: 'receiving_completed',
|
||||||
@ -444,18 +465,8 @@ describe('test/app/service/systems/notice.test.js', () => {
|
|||||||
app: {
|
app: {
|
||||||
config: {},
|
config: {},
|
||||||
},
|
},
|
||||||
|
service: {},
|
||||||
model: {
|
model: {
|
||||||
NotificationWebhook: {
|
|
||||||
async findAll() {
|
|
||||||
return [{
|
|
||||||
id: 9,
|
|
||||||
store_id: 1000000,
|
|
||||||
hook_type: 'custom',
|
|
||||||
hook_url: 'https://example.com/webhook/fail',
|
|
||||||
events: [ 'all' ],
|
|
||||||
}];
|
|
||||||
},
|
|
||||||
},
|
|
||||||
NotificationSendLog: {
|
NotificationSendLog: {
|
||||||
async create(data) {
|
async create(data) {
|
||||||
failureLogs.push(data);
|
failureLogs.push(data);
|
||||||
@ -481,6 +492,14 @@ describe('test/app/service/systems/notice.test.js', () => {
|
|||||||
};
|
};
|
||||||
|
|
||||||
const result = await service.send({
|
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: '文本',
|
messageType: '文本',
|
||||||
businessName: 'receiving',
|
businessName: 'receiving',
|
||||||
event: 'receiving_completed',
|
event: 'receiving_completed',
|
||||||
@ -505,6 +524,7 @@ describe('test/app/service/systems/notice.test.js', () => {
|
|||||||
app: {
|
app: {
|
||||||
config: {},
|
config: {},
|
||||||
},
|
},
|
||||||
|
service: {},
|
||||||
model: {
|
model: {
|
||||||
NotificationWebhook: {
|
NotificationWebhook: {
|
||||||
getAvailableEventCodes() {
|
getAvailableEventCodes() {
|
||||||
@ -544,6 +564,7 @@ describe('test/app/service/systems/notice.test.js', () => {
|
|||||||
app: {
|
app: {
|
||||||
config: {},
|
config: {},
|
||||||
},
|
},
|
||||||
|
service: {},
|
||||||
model: {
|
model: {
|
||||||
NotificationWebhook: {
|
NotificationWebhook: {
|
||||||
getAvailableEventCodes() {
|
getAvailableEventCodes() {
|
||||||
@ -593,20 +614,12 @@ describe('test/app/service/systems/notice.test.js', () => {
|
|||||||
app: {
|
app: {
|
||||||
config: {},
|
config: {},
|
||||||
},
|
},
|
||||||
|
service: {},
|
||||||
model: {
|
model: {
|
||||||
NotificationWebhook: {
|
NotificationWebhook: {
|
||||||
getAvailableEventCodes() {
|
getAvailableEventCodes() {
|
||||||
return [ 'all', '*', 'receiving_completed' ];
|
return [ 'all', '*', 'receiving_completed' ];
|
||||||
},
|
},
|
||||||
async findAll() {
|
|
||||||
return [{
|
|
||||||
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' ],
|
|
||||||
}];
|
|
||||||
},
|
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
logger: {
|
logger: {
|
||||||
@ -628,6 +641,14 @@ describe('test/app/service/systems/notice.test.js', () => {
|
|||||||
|
|
||||||
const service = new NoticeService(ctx);
|
const service = new NoticeService(ctx);
|
||||||
const result = await service.send({
|
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,
|
warehouseId: 100000,
|
||||||
businessName: 'receiving',
|
businessName: 'receiving',
|
||||||
event: 'receiving_completed',
|
event: 'receiving_completed',
|
||||||
|
|||||||
Loading…
x
Reference in New Issue
Block a user