Compare commits
No commits in common. "d0621dd4ec2a18469cbdfa98ac23da06f11f4050" and "e72274f222494339595461c17ab494ab57610d94" have entirely different histories.
d0621dd4ec
...
e72274f222
@ -1,51 +0,0 @@
|
||||
'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;
|
||||
}
|
||||
},
|
||||
};
|
||||
@ -26,8 +26,7 @@ class OrderPackingMethodService extends MainService {
|
||||
* @param {Object} [data.where] 筛选条件。
|
||||
* 支持字段:status(任务状态)、pack_mode(打包模式)、waybill_code(运单号)、wave_no(波次号)、
|
||||
* order_id(订单ID)、workbench_id(工作台ID)、quickWhere(快捷搜索:波次号直接匹配 + 运单号通过express→order→wave链路解析)、
|
||||
* start_time(开始打包时间范围,{operator:'between', value:[start,end]})、end_time(结束打包时间范围)、create_time(创建时间范围);
|
||||
* start_time_start / start_time_end 为开始时间范围的兼容旧写法。
|
||||
* start_time_start / start_time_end(开始打包时间范围)。
|
||||
* @param {Object} [data.sort] 排序参数 { sortField, sortOrder }
|
||||
* @return {Promise<Object>} 统一成功包装响应
|
||||
*/
|
||||
|
||||
@ -2510,9 +2510,6 @@ class ExpressService extends Service {
|
||||
step: {
|
||||
[Op.in]: [ 1, 2, 3, 4 ],
|
||||
},
|
||||
status: {
|
||||
[Op.ne]: 'cancel',
|
||||
},
|
||||
},
|
||||
attributes: [ 'id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'store_id', 'pay_no', 'from_key' ],
|
||||
raw: true,
|
||||
@ -2534,9 +2531,6 @@ class ExpressService extends Service {
|
||||
step: {
|
||||
[Op.in]: [ 4 ],
|
||||
},
|
||||
status: {
|
||||
[Op.ne]: 'cancel',
|
||||
},
|
||||
},
|
||||
attributes: [ 'id', 'sys_platform_code', 'logistics_code', 'sys_platform_name', 'logistics_name', 'store_id', 'pay_no', 'from_key' ],
|
||||
raw: true,
|
||||
@ -3031,33 +3025,10 @@ class ExpressService extends Service {
|
||||
};
|
||||
}
|
||||
|
||||
// 跳过已取消订单:已取消订单不允许取号,且不标记异常、不写失败日志。
|
||||
const cancelledOrderIdSet = new Set(
|
||||
allOrderDeliveryRows
|
||||
.filter(row => String(row.status || '').trim() === 'cancel')
|
||||
.map(row => Number(row.id))
|
||||
.filter(id => Number.isFinite(id) && id > 0)
|
||||
);
|
||||
let effectivePendingOrders = pendingOrders;
|
||||
if (cancelledOrderIdSet.size > 0) {
|
||||
effectivePendingOrders = pendingOrders.filter(order => !cancelledOrderIdSet.has(Number(order.order_id)));
|
||||
ctx.logger.info('[ExpressService.createWaybillCode] 跳过已取消订单取号', {
|
||||
traceId,
|
||||
skippedOrderIds: Array.from(cancelledOrderIdSet),
|
||||
});
|
||||
}
|
||||
|
||||
if (effectivePendingOrders.length === 0) {
|
||||
return {
|
||||
orders: [],
|
||||
waybill_codes: [],
|
||||
};
|
||||
}
|
||||
|
||||
const {
|
||||
relationGroupMap,
|
||||
missingOrderIds,
|
||||
} = this.buildWaybillCreateRelationGroups(effectivePendingOrders, allOrderDeliveryRows, currentWarehouseId);
|
||||
} = this.buildWaybillCreateRelationGroups(pendingOrders, allOrderDeliveryRows, currentWarehouseId);
|
||||
|
||||
const relationWhereList = Array.from(relationGroupMap.values()).map(group => ({
|
||||
store_id: group.store_id,
|
||||
@ -3112,7 +3083,7 @@ class ExpressService extends Service {
|
||||
ctx.logger.warn('[ExpressService.createWaybillCode] 余额不足但允许超额分配: %s', balanceWarnings.join(';'));
|
||||
}
|
||||
|
||||
const successOrders = effectivePendingOrders.filter(order => successOrderKeySet.has(`${order.order_id}:${order.business_key}`));
|
||||
const successOrders = pendingOrders.filter(order => successOrderKeySet.has(`${order.order_id}:${order.business_key}`));
|
||||
const existingRows = await orderExpressModel.findAll({
|
||||
where: {
|
||||
[Op.or]: successOrders.map(order => ({
|
||||
|
||||
@ -28,41 +28,6 @@ const DEFAULT_REGISTERED_EVENT_CODES = Object.freeze([
|
||||
'wave_strategy_quick_scan_failed',
|
||||
'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({
|
||||
custom: 'customize',
|
||||
customize: 'customize',
|
||||
@ -538,12 +503,6 @@ class NoticeService extends Service {
|
||||
name: String(directStore.name || directStore.companyName || directStore.company_name || ''),
|
||||
businessLicense: String(directStore.businessLicense || directStore.business_license || ''),
|
||||
storeRemask: String(directStore.storeRemask || directStore.store_remask || directStore.remask || ''),
|
||||
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) {
|
||||
@ -560,19 +519,11 @@ class NoticeService extends Service {
|
||||
if (cachedStore && Object.keys(cachedStore).length > 0) {
|
||||
const businessLicense = String(cachedStore.businessLicense || cachedStore.business_license || normalizedStore.businessLicense || '');
|
||||
const storeRemask = String(cachedStore.storeRemask || cachedStore.store_remask || cachedStore.remask || normalizedStore.storeRemask || '');
|
||||
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 {
|
||||
id: normalizedStore.id,
|
||||
name: String(cachedStore.name || cachedStore.companyName || cachedStore.company_name || normalizedStore.name || ''),
|
||||
businessLicense,
|
||||
storeRemask,
|
||||
warehouseUseStatus,
|
||||
authStatus,
|
||||
};
|
||||
}
|
||||
} catch (error) {
|
||||
@ -596,26 +547,18 @@ class NoticeService extends Service {
|
||||
warehouse_id: warehouseId,
|
||||
store_id: storeId,
|
||||
},
|
||||
attributes: [ 'store_remask', 'warehouse_use_status', 'auth_status' ],
|
||||
attributes: [ 'store_remask' ],
|
||||
})
|
||||
: null,
|
||||
]);
|
||||
|
||||
const businessLicense = normalizedStore.businessLicense || String(storeRecord && storeRecord.business_license || '');
|
||||
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 = {
|
||||
id: normalizedStore.id,
|
||||
name: normalizedStore.name || String(storeRecord && storeRecord.company_name || ''),
|
||||
businessLicense,
|
||||
storeRemask,
|
||||
warehouseUseStatus,
|
||||
authStatus,
|
||||
};
|
||||
|
||||
if (canUseCache && this.app && typeof this.app.setCacheAsync === 'function') {
|
||||
@ -637,7 +580,7 @@ class NoticeService extends Service {
|
||||
*/
|
||||
async resolveSubjectConfig(options = {}, subject = {}) {
|
||||
const storeModel = this.ctx.model && this.ctx.model.Store;
|
||||
const deliveryOrderService = this.ctx.service && this.ctx.service.systems && this.ctx.service.systems.deliveryOrder;
|
||||
const deliveryOrderService = this.ctx.service.systems && this.ctx.service.systems.deliveryOrder;
|
||||
const normalizeSubjectConfig = value => {
|
||||
if (storeModel && typeof storeModel.normalizeSubjectConfig === 'function') {
|
||||
return storeModel.normalizeSubjectConfig(value);
|
||||
@ -768,7 +711,6 @@ class NoticeService extends Service {
|
||||
mimeType: String(options.mimeType || options.contentType || ''),
|
||||
body: contentSource,
|
||||
},
|
||||
storeContent: String(options.storeContent || options.store_content || '').trim(),
|
||||
metadata: this.toObject(options.metadata, {}),
|
||||
raw: options,
|
||||
};
|
||||
@ -815,7 +757,7 @@ class NoticeService extends Service {
|
||||
}
|
||||
|
||||
/**
|
||||
* 筛选本次需要触达的 webhook(仅支持调用方显式传入的 hooks,不再读取 wms_notification_webhook 表)。
|
||||
* 根据主体、事件和上限筛选本次需要触达的 webhook。
|
||||
* @param {object} payload 标准化后的消息载荷
|
||||
* @return {Promise<object[]>} webhook 列表
|
||||
*/
|
||||
@ -831,360 +773,67 @@ class NoticeService extends Service {
|
||||
.slice(0, webhookLimit);
|
||||
}
|
||||
|
||||
const webhookModel = this.ctx.model && this.ctx.model.NotificationWebhook;
|
||||
if (!webhookModel || typeof webhookModel.findAll !== 'function') {
|
||||
return [];
|
||||
}
|
||||
|
||||
/**
|
||||
* 获取事件对应的固定群订阅配置。
|
||||
* @param {string} event 事件编码
|
||||
* @return {Array|null} 固定订阅目标数组,未配置返回 null
|
||||
*/
|
||||
getFixedGroupTargets(event) {
|
||||
const normalizedEvent = String(event || '').trim().toLowerCase();
|
||||
return FIXED_GROUP_SUBSCRIPTIONS[normalizedEvent] || null;
|
||||
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);
|
||||
}
|
||||
|
||||
/**
|
||||
* 根据固定订阅配置查询本次事件需要触达的群。
|
||||
* @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) {
|
||||
if (Number.isFinite(storeId) && storeId > 0 && !targetSubjectIds.includes(storeId)) {
|
||||
targetSubjectIds.push(storeId);
|
||||
}
|
||||
|
||||
if (targetSubjectIds.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 webhookGroups = await Promise.all(targetSubjectIds.map(async currentSubjectId => {
|
||||
const where = {
|
||||
store_id: currentSubjectId,
|
||||
status: 1,
|
||||
};
|
||||
|
||||
if (payload.hookType) {
|
||||
where.hook_type = payload.hookType;
|
||||
}
|
||||
|
||||
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,
|
||||
const webhooks = await webhookModel.findAll({
|
||||
where,
|
||||
order: [[ 'id', 'ASC' ]],
|
||||
});
|
||||
|
||||
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 || '',
|
||||
return webhooks
|
||||
.filter(item => this.matchesEvents(item && item.events, payload))
|
||||
.slice(0, webhookLimit);
|
||||
}));
|
||||
} catch (error) {
|
||||
this.ctx.logger.warn(`[NoticeService.findSubscribedGroups] 查询订阅群失败: ${error.message}`);
|
||||
return [];
|
||||
|
||||
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;
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* 解析降级通知中的货主名称:优先取合约表(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:双通道同时发送。
|
||||
* 统一通知发送入口:规范化消息、匹配 webhook 并执行分发。
|
||||
* @param {object} [options={}] 发送入参
|
||||
* @return {Promise<object>} 发送汇总结果
|
||||
*/
|
||||
async send(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);
|
||||
|
||||
if (webhooks.length === 0) {
|
||||
|
||||
@ -11,16 +11,6 @@ const TRANSACTION_LOCK_RETRY_BASE_DELAY_MS = 50;
|
||||
const DISPATCH_BATCH_SIZE = 20;
|
||||
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) {
|
||||
if (!requestId) return null;
|
||||
return `order:pending:sync_order_ids:request:${String(requestId).trim()}`;
|
||||
@ -720,18 +710,16 @@ async function processManualOrderInternal(service, orderModel, orderItemsModel,
|
||||
delivery_order_code: String(orderRow.delivery_order_code || '').trim(),
|
||||
store_id: Number(orderRow && orderRow.store_id) || 0,
|
||||
waybill_code: resolvedWaybillCodes,
|
||||
receiver_name: String(orderRow.name || '').trim(),
|
||||
receiver_phone: String(orderRow.mobile || orderRow.tel || '').trim(),
|
||||
warehouse_id: warehouseId,
|
||||
handler: 'syncManualOrders',
|
||||
sync_target: 'internal',
|
||||
route_state: 'accepted',
|
||||
status: 'success',
|
||||
message: '订单同步通知已合并排队',
|
||||
message: '订单同步通知已发送',
|
||||
success_count: 1,
|
||||
failed_count: 0,
|
||||
};
|
||||
const noticeResult = await enqueueOrderSyncNoticeInternal(service, noticeSyncResult, context);
|
||||
const noticeResult = await sendManualSyncNoticeInternal(service, noticeSyncResult, context);
|
||||
|
||||
if (!noticeResult || noticeResult.success !== true) {
|
||||
const noticeMessage = String(noticeResult && noticeResult.message || '通知发送失败').trim() || '通知发送失败';
|
||||
@ -940,10 +928,9 @@ function buildManualSyncNoticePayloadInternal(syncResult = {}, context = {}) {
|
||||
? syncResult.order_ids.map(orderId => Number(orderId)).filter(orderId => Number.isFinite(orderId) && orderId > 0)
|
||||
: [];
|
||||
const warehouseId = Number(context.warehouseId || syncResult.warehouse_id || 0);
|
||||
const noticeMessage = String(syncResult.message || '').trim() || '订单同步完成';
|
||||
const noticeStatus = String(syncResult.status || '').trim() || 'success';
|
||||
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)
|
||||
? syncResult.waybill_code.map(code => String(code || '').trim()).filter(code => !!code)
|
||||
: (Array.isArray(syncResult.waybill_code_list)
|
||||
@ -961,7 +948,11 @@ function buildManualSyncNoticePayloadInternal(syncResult = {}, context = {}) {
|
||||
},
|
||||
title: '订单同步完成',
|
||||
message: [
|
||||
`订单${deliveryOrderCode || '无'} 姓名:${receiverName} 电话:${receiverPhone} 运单号:${waybillCodeList.length > 0 ? waybillCodeList.join(',') : '无'}`,
|
||||
`仓库ID:${warehouseId || '未知'}`,
|
||||
`订单ID:${orderIds.join(',') || '无'}`,
|
||||
`发货单号:${deliveryOrderCode || '无'}`,
|
||||
`运单号:${waybillCodeList.length > 0 ? waybillCodeList.join(',') : '无'}`,
|
||||
`消息:${noticeMessage}`,
|
||||
].join('\n'),
|
||||
metadata: {
|
||||
create_channel: CREATE_CHANNEL_MANUAL,
|
||||
@ -978,509 +969,6 @@ 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) {
|
||||
if (!orderRow) {
|
||||
@ -1805,16 +1293,6 @@ class OrderAsyncService extends MainService {
|
||||
return await syncManualOrdersInternal(this, groupedOrder, context);
|
||||
}
|
||||
|
||||
/**
|
||||
* 冲刷合并的订单同步通知(由定时任务调用)。
|
||||
* 把 3 分钟去抖窗口已到期的「仓库:货主」维度订单统一推送一条消息。
|
||||
*
|
||||
* @return {Promise<Object>} 本轮冲刷结果。
|
||||
*/
|
||||
async flushDeferredOrderSyncNotices() {
|
||||
return await flushDeferredOrderSyncNoticesInternal(this);
|
||||
}
|
||||
|
||||
/**
|
||||
* API 创建入口处理。
|
||||
*
|
||||
|
||||
@ -53,11 +53,8 @@ class OrderPackingService extends Service {
|
||||
* @param {Object} [where.order_id] 订单ID(精确匹配)
|
||||
* @param {Object} [where.workbench_id] 工作台ID(精确匹配)
|
||||
* @param {Object} [where.quickWhere] 快捷搜索:支持波次号模糊匹配;运单号通过 express→order→wave 链路解析(团购按波次号查、散单按订单ID查)
|
||||
* @param {Object} [where.start_time] 开始打包时间范围,支持 {operator:'between', value:[start,end]}
|
||||
* @param {Object} [where.start_time_start] 开始打包时间起始(兼容旧写法)
|
||||
* @param {Object} [where.start_time_end] 开始打包时间结束(兼容旧写法)
|
||||
* @param {Object} [where.end_time] 结束打包时间范围,支持 {operator:'between', value:[start,end]}
|
||||
* @param {Object} [where.create_time] 创建时间范围,支持 {operator:'between', value:[start,end]}
|
||||
* @param {Object} [where.start_time_start] 开始打包时间起始
|
||||
* @param {Object} [where.start_time_end] 开始打包时间结束
|
||||
* @param {Object} pagination 分页参数 { page, pageSize }
|
||||
* @param {Object} sort 排序参数 { sortField, sortOrder }
|
||||
* @return {Promise<Object>} 打包任务列表与分页信息
|
||||
@ -303,27 +300,7 @@ class OrderPackingService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
// 时间范围筛选:start_time / end_time / create_time
|
||||
// 支持 {operator:'between', value:[start,end]} 或直接传 [start,end]
|
||||
const applyTimeRangeFilter = (field, cond) => {
|
||||
if (!cond) return;
|
||||
const operator = String(cond?.operator || '').toLowerCase();
|
||||
let range = cond?.value ?? cond;
|
||||
if (!Array.isArray(range) && operator === 'between' && range && typeof range === 'object') {
|
||||
range = [ range.start ?? range.from ?? range.begin, range.end ?? range.to ?? range.finish ];
|
||||
}
|
||||
if (!Array.isArray(range)) return;
|
||||
const [ startVal, endVal ] = range;
|
||||
if (startVal !== undefined && startVal !== null && String(startVal).trim() !== '') {
|
||||
queryWhere[field] = { ...(queryWhere[field] || {}), [Op.gte]: new Date(startVal) };
|
||||
}
|
||||
if (endVal !== undefined && endVal !== null && String(endVal).trim() !== '') {
|
||||
queryWhere[field] = { ...(queryWhere[field] || {}), [Op.lte]: new Date(endVal) };
|
||||
}
|
||||
};
|
||||
|
||||
// 开始打包时间范围(统一 between 写法 + 兼容旧拆分写法)
|
||||
applyTimeRangeFilter('start_time', where.start_time);
|
||||
// 开始打包时间范围
|
||||
if (where.start_time_start) {
|
||||
const startTimeStart = where.start_time_start?.value ?? where.start_time_start;
|
||||
if (startTimeStart) {
|
||||
@ -337,12 +314,6 @@ class OrderPackingService extends Service {
|
||||
}
|
||||
}
|
||||
|
||||
// 结束打包时间范围
|
||||
applyTimeRangeFilter('end_time', where.end_time);
|
||||
|
||||
// 创建时间范围
|
||||
applyTimeRangeFilter('create_time', where.create_time);
|
||||
|
||||
// 排序
|
||||
const sortField = sort.sortField || 'create_time';
|
||||
const sortOrder = String(sort.sortOrder || 'DESC').toUpperCase() === 'ASC' ? 'ASC' : 'DESC';
|
||||
|
||||
@ -4,7 +4,6 @@ const MainService = require('../main');
|
||||
|
||||
const STORAGE_STATUS_FIN = 'fin';
|
||||
const STORAGE_STATUS_ERROR = 'error';
|
||||
const ORDER_STATUS_CANCEL = 'cancel';
|
||||
const ORDER_STEP_EXCEPTION = 3;
|
||||
const ALLOCATION_LOG_SAMPLE_LIMIT = 20;
|
||||
|
||||
@ -614,20 +613,6 @@ class OrderStorageAllocationService extends MainService {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (String(orderRow.status || '').trim() === ORDER_STATUS_CANCEL) {
|
||||
skippedOrders.push({
|
||||
order_id: orderId,
|
||||
status: 'skipped',
|
||||
order_status: orderRow.status,
|
||||
skipped_reason: 'order_cancelled',
|
||||
});
|
||||
writeAllocationTextLog('[OrderStorageAllocationService.allocatePicking] 过滤订单结果', {
|
||||
orderId,
|
||||
skippedReason: 'order_cancelled',
|
||||
});
|
||||
continue;
|
||||
}
|
||||
|
||||
if (String(orderRow.storage_status || 'none') === STORAGE_STATUS_FIN) {
|
||||
skippedOrders.push({
|
||||
order_id: orderId,
|
||||
|
||||
@ -680,6 +680,25 @@ class InventoryService extends Service {
|
||||
// ────────── 7. 提交事务 ──────────
|
||||
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] 移库完成', {
|
||||
warehouse_id: warehouseId,
|
||||
storage_id: storageId,
|
||||
@ -1070,6 +1089,32 @@ class InventoryService extends Service {
|
||||
// ────────── 10. 提交事务 ──────────
|
||||
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] 按商品移库完成', {
|
||||
warehouse_id: warehouseId,
|
||||
space_id: spaceId,
|
||||
|
||||
@ -1009,7 +1009,6 @@ class ReceivingService extends Service {
|
||||
messageType: 'text',
|
||||
businessName: 'receiving',
|
||||
event: 'receiving_rejected',
|
||||
channel: 'warehouse',
|
||||
title: `收货单 ${item.receiving_number || item.id} 已被驳回`,
|
||||
content: [
|
||||
`驳回人:${reviewerName || '未知'}`,
|
||||
@ -1030,9 +1029,16 @@ class ReceivingService extends Service {
|
||||
name: reviewerName,
|
||||
},
|
||||
metadata: {
|
||||
id: item.id || null,
|
||||
ids: [ item.id || null ].filter(Boolean),
|
||||
receiving_id: item.id || null,
|
||||
receiving_ids: [ item.id || null ].filter(Boolean),
|
||||
receiving_number: item.receiving_number || '',
|
||||
receiving_creator: item.creator && item.creator.name ? item.creator.name : null,
|
||||
receiving_numbers: item.receiving_number ? [ item.receiving_number ] : [],
|
||||
receiving_creator: item.creator || null,
|
||||
receiving_creators: item.creator ? [ item.creator ] : [],
|
||||
receiving: item,
|
||||
receivings: [ item ],
|
||||
warehouseId: warehouse_id,
|
||||
remark: updateData.remark || '',
|
||||
},
|
||||
@ -1543,7 +1549,6 @@ class ReceivingService extends Service {
|
||||
messageType: reportUrl ? 'file' : 'text',
|
||||
businessName: 'receiving',
|
||||
event: 'receiving_reviewed',
|
||||
channel: 'warehouse',
|
||||
title: `收货单${receivingNumber}审核完成`,
|
||||
content,
|
||||
url: reportUrl || undefined,
|
||||
@ -4099,10 +4104,7 @@ class ReceivingService extends Service {
|
||||
const totalBoxWeight = normalizedDetails.reduce((sum, item) => sum + Number(item.box_weight || 0), 0);
|
||||
const title = `收货单${receivingNumber}已完成`;
|
||||
const contactLines = this.getCompletionContactFields(receiving).map(([ field, value ]) => `${field}:${value || '无'}`);
|
||||
// 仓库侧与货主侧前端地址/路径不同,分别拼快速查看链接
|
||||
const warehouseFrontendUrl = String(ctx.app.config.frontendUrl || '').trim();
|
||||
const storeFrontendUrl = String(ctx.app.config.storeFrontendUrl || ctx.app.config.frontendUrl || '').trim();
|
||||
const contentLines = [
|
||||
const content = [
|
||||
`收货单号:${receivingNumber} 已完成`,
|
||||
`货主:${receiving.store_name || '未知'}`,
|
||||
`来货方式:${this.formatDeliveryMethod(receiving.delivery_method) || '未知'}`,
|
||||
@ -4119,9 +4121,9 @@ class ReceivingService extends Service {
|
||||
`开始时间:${this.formatReportDate(receiving.created_at)}`,
|
||||
`完成时间:${this.formatReportDate(receiving.receiving_end_time)}`,
|
||||
`备注:${receiving.remark || '无'}`,
|
||||
].filter(Boolean);
|
||||
const content = [ ...contentLines, `快速查看:${warehouseFrontendUrl}/storage/receiving?id=${receivingNumber}` ].join('\n') + '。';
|
||||
const storeContent = [ ...contentLines, `快速查看:${storeFrontendUrl}/storage/receiving_owner?id=${receivingNumber}` ].join('\n') + '。';
|
||||
`快速查看:${ctx.app.config.frontendUrl || ''}/storage/receiving?id=${receivingNumber}`, // 替换为实际的前端地址
|
||||
|
||||
].filter(Boolean).join('\n') + '。';
|
||||
|
||||
return await noticeService.send({
|
||||
warehouseId,
|
||||
@ -4129,10 +4131,8 @@ class ReceivingService extends Service {
|
||||
messageType: reportUrl ? 'file' : 'text',
|
||||
businessName: 'receiving',
|
||||
event: 'receiving_completed',
|
||||
channel: 'warehouse',
|
||||
title,
|
||||
content,
|
||||
storeContent,
|
||||
url: reportUrl || undefined,
|
||||
fileName: reportUrl ? reportFileName : '',
|
||||
mimeType: reportUrl ? 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' : '',
|
||||
@ -4157,6 +4157,15 @@ class ReceivingService extends Service {
|
||||
unmatched_details: unmatchedDetails,
|
||||
total_quantity: totalQuantity,
|
||||
},
|
||||
details: normalizedDetails,
|
||||
boxSummary: {
|
||||
total_box_remainder: totalBoxRemainder,
|
||||
total_box_weight: totalBoxWeight,
|
||||
},
|
||||
completionReport: completionReport ? {
|
||||
fileKey: completionReport.fileKey || completionReport.key || '',
|
||||
url: reportUrl,
|
||||
} : null,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@ -1,342 +0,0 @@
|
||||
'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;
|
||||
@ -154,7 +154,7 @@ class WaybillService extends MainService {
|
||||
* 主单号通过 SELF JOIN 同 order_id 下 business_key=1 的记录获取。
|
||||
*
|
||||
* @param {Object} [options={}] 查询参数。
|
||||
* @param {Object} [options.where] 筛选条件,支持 waybillCode / mainWaybillCode / orderId / orderNo / logisticsCode / logisticsInterfaceId / platformCode / status / isBack / isIntercept / isGalaxyReceive / packageMaterialId / hasWeighingWeight / keyword / createdAt({operator:'between', value:[start,end]},兼容 createAt 别名)/ createdAtStart / createdAtEnd(旧写法兼容)。
|
||||
* @param {Object} [options.where] 筛选条件,支持 waybillCode / mainWaybillCode / orderId / orderNo / logisticsCode / logisticsInterfaceId / platformCode / status / isBack / isIntercept / isGalaxyReceive / packageMaterialId / hasWeighingWeight / keyword / createdAtStart / createdAtEnd。
|
||||
* @param {Object} [options.pagination] 分页参数 { page, pageSize },默认 page=1, pageSize=20。
|
||||
* @param {Object} [options.sort] 排序参数 { field, order },默认 create_at desc。
|
||||
* @return {Promise<Object>} 运单列表与分页信息 { list, pagination }。
|
||||
@ -322,18 +322,7 @@ class WaybillService extends MainService {
|
||||
queryWhere.waybill_code = { [Op.like]: `%${String(keyword).trim()}%` };
|
||||
}
|
||||
|
||||
// 创建时间范围:createdAt 支持 {operator:'between', value:[start,end]}(兼容 createAt 别名)
|
||||
const createdAtRange = val(where.createdAt) ?? val(where.createAt);
|
||||
if (Array.isArray(createdAtRange)) {
|
||||
const [ unifiedCreateAtStart, unifiedCreateAtEnd ] = createdAtRange;
|
||||
if (unifiedCreateAtStart && String(unifiedCreateAtStart).trim()) {
|
||||
queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.gte]: new Date(unifiedCreateAtStart) };
|
||||
}
|
||||
if (unifiedCreateAtEnd && String(unifiedCreateAtEnd).trim()) {
|
||||
queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.lte]: new Date(unifiedCreateAtEnd) };
|
||||
}
|
||||
}
|
||||
// 兼容旧写法:createdAtStart / createdAtEnd
|
||||
// 创建时间范围
|
||||
const createdAtStart = val(where.createdAtStart);
|
||||
if (createdAtStart && String(createdAtStart).trim()) {
|
||||
const startDate = this.normalizeDate(String(createdAtStart).trim(), false);
|
||||
@ -684,7 +673,7 @@ class WaybillService extends MainService {
|
||||
* 复用 list 的筛选逻辑,分批查询,支持进度回调。
|
||||
*
|
||||
* @param {Object} options 导出参数。
|
||||
* @param {Object} [options.where={}] 筛选条件(同 list,另支持 ids:运单ID数组,精确过滤)。
|
||||
* @param {Object} [options.where={}] 筛选条件(同 list)。
|
||||
* @param {Object} [options.sort={}] 排序参数(同 list)。
|
||||
* @param {string[]} [options.exportFields] 需要导出的字段列表,不传则导出全部字段。
|
||||
* @param {Function} [options.onProgress] 进度回调,接收 `{ status, progress, currentCount, totalCount, message, result }`。
|
||||
@ -722,17 +711,6 @@ class WaybillService extends MainService {
|
||||
// 构建查询条件(同 list)
|
||||
const queryWhere = { warehouse_id: warehouseId };
|
||||
|
||||
// 指定运单ID列表(勾选导出,按 wms_order_express.id 精确过滤)
|
||||
const idsExport = val(where.ids);
|
||||
if (Array.isArray(idsExport) && idsExport.length > 0) {
|
||||
const idList = idsExport
|
||||
.map(id => Number(id))
|
||||
.filter(id => Number.isFinite(id) && id > 0);
|
||||
if (idList.length > 0) {
|
||||
queryWhere.id = { [Op.in]: idList };
|
||||
}
|
||||
}
|
||||
|
||||
// 主单号查询
|
||||
const mainWaybillCodeExport = val(where.mainWaybillCode);
|
||||
if (mainWaybillCodeExport && String(mainWaybillCodeExport).trim()) {
|
||||
@ -824,18 +802,6 @@ class WaybillService extends MainService {
|
||||
if (keywordExport && String(keywordExport).trim()) {
|
||||
queryWhere.waybill_code = { [Op.like]: `%${String(keywordExport).trim()}%` };
|
||||
}
|
||||
// 创建时间范围:createdAt 支持 {operator:'between', value:[start,end]}(兼容 createAt 别名)
|
||||
const createdAtRangeExport = val(where.createdAt) ?? val(where.createAt);
|
||||
if (Array.isArray(createdAtRangeExport)) {
|
||||
const [ unifiedCreateAtStartExport, unifiedCreateAtEndExport ] = createdAtRangeExport;
|
||||
if (unifiedCreateAtStartExport && String(unifiedCreateAtStartExport).trim()) {
|
||||
queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.gte]: new Date(unifiedCreateAtStartExport) };
|
||||
}
|
||||
if (unifiedCreateAtEndExport && String(unifiedCreateAtEndExport).trim()) {
|
||||
queryWhere.create_at = { ...(queryWhere.create_at || {}), [Op.lte]: new Date(unifiedCreateAtEndExport) };
|
||||
}
|
||||
}
|
||||
// 兼容旧写法:createdAtStart / createdAtEnd
|
||||
const createdAtStartExport = val(where.createdAtStart);
|
||||
if (createdAtStartExport && String(createdAtStartExport).trim()) {
|
||||
const startDate = this.normalizeDate(String(createdAtStartExport).trim(), false);
|
||||
|
||||
@ -212,10 +212,6 @@ module.exports = appInfo => {
|
||||
config.printService = {
|
||||
url: 'http://printer.wms.gztbyc.com',
|
||||
};
|
||||
// 仓库侧前端地址(通知文案快速查看链接)
|
||||
config.frontendUrl = 'http://wms.wms.gztbyc.com';
|
||||
// 货主侧前端地址(货主群通知使用,与仓库侧不同)
|
||||
config.storeFrontendUrl = 'http://store.wms.gztbyc.com';
|
||||
config.printRetryCompensation = {
|
||||
enable: false,
|
||||
intervalMs: 60 * 1000,
|
||||
|
||||
@ -1,49 +1,4 @@
|
||||
[
|
||||
{
|
||||
"version": "2026.08.16-waybill-createAt-between",
|
||||
"date": "2026-08-16",
|
||||
"type": "enhanced",
|
||||
"summary": "waybill.warehouse.list / export 创建时间筛选统一为 between 区间写法:where.createdAt 支持 {operator:\"between\", value:[起始,结束]},保留 createdAtStart/createdAtEnd 旧写法兼容",
|
||||
"methods": [
|
||||
"waybill.warehouse.list",
|
||||
"waybill.warehouse.export"
|
||||
],
|
||||
"notes": [
|
||||
"app/service/systems/waybill.js list/export:createdAt 数组区间两端可单独为空,分别落 create_at gte/lte;同时兼容 createAt 别名与 createdAtStart/createdAtEnd 旧写法",
|
||||
"同步更新 methods/system.json 中 waybill.warehouse.list / export 的 where.createdAt 参数文档"
|
||||
],
|
||||
"module": "waybill.warehouse"
|
||||
},
|
||||
{
|
||||
"version": "2026.08.16-order-packing-list-time-filter",
|
||||
"date": "2026-08-16",
|
||||
"type": "enhanced",
|
||||
"summary": "order.packing.list 时间筛选统一为 between 区间写法:start_time / end_time / create_time 支持 {operator:\"between\", value:[起始,结束]},与已有 start_time_start/start_time_end 旧写法兼容",
|
||||
"methods": [
|
||||
"order.packing.list"
|
||||
],
|
||||
"notes": [
|
||||
"app/service/systems/order_packing.js list:新增 applyTimeRangeFilter,统一处理 start_time/end_time/create_time 的 between 区间条件(数组两端可单独为空,按 gte/lte 拼接),与 warehouse_id 隔离及其他筛选叠加",
|
||||
"保留 start_time_start/start_time_end 旧拆分写法的兼容处理",
|
||||
"同步更新 methods/system.json 中 order.packing.list 的 where 参数文档"
|
||||
],
|
||||
"module": "order.packing"
|
||||
},
|
||||
{
|
||||
"version": "2026.08.16-waybill-export-ids",
|
||||
"date": "2026-08-16",
|
||||
"type": "enhanced",
|
||||
"summary": "waybill.warehouse.export 新增 where.ids 入参:支持按运单ID列表(勾选)导出快递号,与仓库隔离条件叠加过滤",
|
||||
"methods": [
|
||||
"waybill.warehouse.export"
|
||||
],
|
||||
"notes": [
|
||||
"app/service/systems/waybill.js export:新增 where.ids 处理,数组值经 Number 转换并过滤非法值后生成 id IN (...) 条件,与 warehouse_id 隔离条件叠加,不影响其他筛选字段",
|
||||
"入口层 systemMethods/waybill/warehouse.js export 原样透传 where,无需改动",
|
||||
"同步更新 methods/system.json 中 waybill.warehouse.export 的 where.ids 参数文档"
|
||||
],
|
||||
"module": "waybill.warehouse"
|
||||
},
|
||||
{
|
||||
"version": "2026.08.15-packing-setEndTime-cap",
|
||||
"date": "2026-08-15",
|
||||
|
||||
@ -81,71 +81,5 @@
|
||||
"过滤点位于屏蔽检查之后、绑群码识别之前,仅拦截自动处理链路"
|
||||
],
|
||||
"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"
|
||||
}
|
||||
]
|
||||
|
||||
@ -6833,35 +6833,17 @@
|
||||
"required": false,
|
||||
"description": "快捷搜索:波次号模糊匹配 + 运单号通过 express→order→wave 链路解析"
|
||||
},
|
||||
{
|
||||
"name": "start_time",
|
||||
"type": "object",
|
||||
"required": false,
|
||||
"description": "开始打包时间范围:{operator:\"between\", value:[起始时间, 结束时间]},value 为 ISO 8601 或 \"YYYY-MM-DD HH:mm:ss\" 字符串数组"
|
||||
},
|
||||
{
|
||||
"name": "start_time_start",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"description": "开始打包时间范围起始(ISO 8601,兼容旧写法)"
|
||||
"description": "开始打包时间范围起始(ISO 8601)"
|
||||
},
|
||||
{
|
||||
"name": "start_time_end",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"description": "开始打包时间范围结束(ISO 8601,兼容旧写法)"
|
||||
},
|
||||
{
|
||||
"name": "end_time",
|
||||
"type": "object",
|
||||
"required": false,
|
||||
"description": "结束打包时间范围:{operator:\"between\", value:[起始时间, 结束时间]},value 为 ISO 8601 或 \"YYYY-MM-DD HH:mm:ss\" 字符串数组"
|
||||
},
|
||||
{
|
||||
"name": "create_time",
|
||||
"type": "object",
|
||||
"required": false,
|
||||
"description": "创建时间范围:{operator:\"between\", value:[起始时间, 结束时间]},value 为 ISO 8601 或 \"YYYY-MM-DD HH:mm:ss\" 字符串数组"
|
||||
"description": "开始打包时间范围结束(ISO 8601)"
|
||||
},
|
||||
{
|
||||
"name": "has_video",
|
||||
@ -30929,26 +30911,19 @@
|
||||
"source": "body.where",
|
||||
"description": "关键词搜索:同时匹配运单号(waybill_code)、主单号、订单号"
|
||||
},
|
||||
{
|
||||
"name": "where.createdAt",
|
||||
"type": "object",
|
||||
"required": false,
|
||||
"source": "body.where",
|
||||
"description": "创建时间范围:{operator:\"between\", value:[起始时间, 结束时间]},value 为 ISO 8601 或 \"YYYY-MM-DD HH:mm:ss\" 字符串数组"
|
||||
},
|
||||
{
|
||||
"name": "where.createdAtStart",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body.where",
|
||||
"description": "创建时间起始,格式 YYYY-MM-DD(兼容旧写法)"
|
||||
"description": "创建时间起始,格式 YYYY-MM-DD"
|
||||
},
|
||||
{
|
||||
"name": "where.createdAtEnd",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body.where",
|
||||
"description": "创建时间截止,格式 YYYY-MM-DD(兼容旧写法)"
|
||||
"description": "创建时间截止,格式 YYYY-MM-DD"
|
||||
},
|
||||
{
|
||||
"name": "sort",
|
||||
@ -31636,7 +31611,7 @@
|
||||
"type": "object",
|
||||
"required": false,
|
||||
"source": "body",
|
||||
"description": "筛选条件对象,同 waybill.warehouse.list 的 where 参数,另支持 ids(运单ID数组,勾选导出)"
|
||||
"description": "筛选条件对象,同 waybill.warehouse.list 的 where 参数"
|
||||
},
|
||||
{
|
||||
"name": "where.waybillCode",
|
||||
@ -31652,13 +31627,6 @@
|
||||
"source": "body.where",
|
||||
"description": "主单号(精确匹配)"
|
||||
},
|
||||
{
|
||||
"name": "where.ids",
|
||||
"type": "array",
|
||||
"required": false,
|
||||
"source": "body.where",
|
||||
"description": "运单ID列表(勾选导出,按 wms_order_express.id 精确过滤)"
|
||||
},
|
||||
{
|
||||
"name": "where.orderId",
|
||||
"type": "number",
|
||||
@ -31757,26 +31725,19 @@
|
||||
"source": "body.where",
|
||||
"description": "关键词搜索"
|
||||
},
|
||||
{
|
||||
"name": "where.createdAt",
|
||||
"type": "object",
|
||||
"required": false,
|
||||
"source": "body.where",
|
||||
"description": "创建时间范围:{operator:\"between\", value:[起始时间, 结束时间]},value 为 ISO 8601 或 \"YYYY-MM-DD HH:mm:ss\" 字符串数组"
|
||||
},
|
||||
{
|
||||
"name": "where.createdAtStart",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body.where",
|
||||
"description": "创建时间起始,格式 YYYY-MM-DD(兼容旧写法)"
|
||||
"description": "创建时间起始,格式 YYYY-MM-DD"
|
||||
},
|
||||
{
|
||||
"name": "where.createdAtEnd",
|
||||
"type": "string",
|
||||
"required": false,
|
||||
"source": "body.where",
|
||||
"description": "创建时间截止,格式 YYYY-MM-DD(兼容旧写法)"
|
||||
"description": "创建时间截止,格式 YYYY-MM-DD"
|
||||
},
|
||||
{
|
||||
"name": "sort",
|
||||
|
||||
@ -153,8 +153,7 @@
|
||||
"type=balance:绑群成功后自动推送面单余额",
|
||||
"type=error:AI 无法处理时的兜底回复",
|
||||
"AI silent(无需回复)时不推送",
|
||||
"ext_id 为 wms_inbox_message.id 主键,接收方应以 ext_id 做幂等去重,网络波动可能重推",
|
||||
"type=system:系统级业务事件通知(收货完成/驳回/审核等,不要求 user_id/user_name),data 仅携带 content(通知正文,接收方只处理该字段)与 ext_id(业务单号,用于幂等去重),其余协议字段为 group_id / group_name / timestamp"
|
||||
"ext_id 为 wms_inbox_message.id 主键,接收方应以 ext_id 做幂等去重,网络波动可能重推"
|
||||
],
|
||||
"example": {
|
||||
"query": "?app_key=AK001×tamp=1786100000&sign=abc",
|
||||
|
||||
@ -46,7 +46,6 @@
|
||||
"file-writer:pressure": "node ./temp/generated-tests/file-writer-pressure.generated.test.cjs",
|
||||
"debug:webhook:receiver": "node ./script/debug-webhook-receiver.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:dry": "node ./script/update-api-doc.cjs --dry-run",
|
||||
"deploy:precheck": "node ./script/deploy-precheck.cjs",
|
||||
|
||||
@ -1,116 +0,0 @@
|
||||
'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);
|
||||
});
|
||||
@ -1,206 +0,0 @@
|
||||
'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);
|
||||
});
|
||||
@ -1,217 +0,0 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
const ExpressService = require('../../../../app/service/systems/express');
|
||||
|
||||
/**
|
||||
* 创建 createWaybillCodePipeline 跳过取消订单的测试上下文。
|
||||
* 模拟数据库行为:current/dispatch 订单查询按 where(含 status != 'cancel')过滤。
|
||||
*
|
||||
* @param {Object} [options={}] 测试覆盖配置。
|
||||
* @return {{ ctx: Object, calls: Object }} 测试上下文与调用记录。
|
||||
*/
|
||||
function createPipelineSkipCancelledHarness(options = {}) {
|
||||
const calls = {
|
||||
orderDeliveryFindAllQueries: [],
|
||||
dispatchFindAllQueries: [],
|
||||
asyncTaskPayloads: [],
|
||||
};
|
||||
|
||||
const orderDeliveryRows = Array.isArray(options.orderDeliveryRows) ? options.orderDeliveryRows : [];
|
||||
const dispatchRows = Array.isArray(options.dispatchRows) ? options.dispatchRows : [];
|
||||
|
||||
const matchWhere = (row, where = {}) => {
|
||||
const idValues = Array.isArray(where.id)
|
||||
? where.id
|
||||
: (where.id && Array.isArray(where.id.in) ? where.id.in : []);
|
||||
if (idValues.length > 0 && !idValues.includes(Number(row.id))) {
|
||||
return false;
|
||||
}
|
||||
const stepValues = Array.isArray(where.step)
|
||||
? where.step
|
||||
: (where.step && Array.isArray(where.step.in) ? where.step.in : []);
|
||||
if (stepValues.length > 0 && !stepValues.includes(Number(row.step))) {
|
||||
return false;
|
||||
}
|
||||
const excludedStatus = where.status && where.status.ne ? String(where.status.ne).trim() : '';
|
||||
if (excludedStatus && String(row.status || '').trim() === excludedStatus) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
const ctx = {
|
||||
app: {
|
||||
Sequelize: {
|
||||
Op: {
|
||||
in: 'in',
|
||||
ne: 'ne',
|
||||
},
|
||||
},
|
||||
},
|
||||
user: {
|
||||
store_id: 100000,
|
||||
},
|
||||
model: {
|
||||
OrderDeliveryFactory: {
|
||||
async getCurrentModel() {
|
||||
return {
|
||||
async findAll(query = {}) {
|
||||
calls.orderDeliveryFindAllQueries.push(query);
|
||||
return orderDeliveryRows.filter(row => matchWhere(row, query.where)).map(row => ({ ...row }));
|
||||
},
|
||||
async update() {
|
||||
return [ 1 ];
|
||||
},
|
||||
};
|
||||
},
|
||||
async getDispatchModel() {
|
||||
return {
|
||||
async findAll(query = {}) {
|
||||
calls.dispatchFindAllQueries.push(query);
|
||||
return dispatchRows.filter(row => matchWhere(row, query.where)).map(row => ({ ...row }));
|
||||
},
|
||||
};
|
||||
},
|
||||
},
|
||||
PrintPlatform: {
|
||||
async findAll() {
|
||||
return [
|
||||
{
|
||||
id: 901,
|
||||
platform_code: 'PDD_PRINT',
|
||||
request_platform_code: 'OPEN_API',
|
||||
},
|
||||
];
|
||||
},
|
||||
},
|
||||
},
|
||||
service: {
|
||||
systems: {
|
||||
platform: {
|
||||
async getPlatformList() {
|
||||
return [
|
||||
{
|
||||
code: 'PDD',
|
||||
print_platform_id: 901,
|
||||
default_express_interface: 'POLYAPI',
|
||||
},
|
||||
];
|
||||
},
|
||||
},
|
||||
setting: {
|
||||
expressInterface: {
|
||||
async listByWarehousePlatformCode() {
|
||||
return {
|
||||
data: [
|
||||
{
|
||||
id: 22,
|
||||
sys_express_code: 'SF',
|
||||
express_code: 'SF',
|
||||
},
|
||||
],
|
||||
};
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
logger: {
|
||||
info() {},
|
||||
warn() {},
|
||||
error() {},
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
ctx,
|
||||
calls,
|
||||
};
|
||||
}
|
||||
|
||||
describe('test/app/service/systems/express.createWaybillCodePipeline.skipCancelled.test.js', () => {
|
||||
it('should exclude cancelled orders via status filter in current and dispatch queries', async () => {
|
||||
const { ctx, calls } = createPipelineSkipCancelledHarness({
|
||||
orderDeliveryRows: [
|
||||
{
|
||||
id: 1,
|
||||
warehouse_id: 100000,
|
||||
status: 'cancel',
|
||||
step: 4,
|
||||
sys_platform_code: 'PDD',
|
||||
logistics_code: 'SF',
|
||||
sys_platform_name: '拼多多',
|
||||
logistics_name: '顺丰',
|
||||
store_id: 100000,
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
warehouse_id: 100000,
|
||||
status: 'created',
|
||||
step: 2,
|
||||
sys_platform_code: 'PDD',
|
||||
logistics_code: 'SF',
|
||||
sys_platform_name: '拼多多',
|
||||
logistics_name: '顺丰',
|
||||
store_id: 100000,
|
||||
},
|
||||
],
|
||||
});
|
||||
const service = new ExpressService(ctx);
|
||||
service.asyncTask = (batch, options, matchedPlatform, expressInterfaceConfig) => {
|
||||
calls.asyncTaskPayloads.push({ batch, options, matchedPlatform, expressInterfaceConfig });
|
||||
};
|
||||
|
||||
const result = await service.createWaybillCodePipeline([
|
||||
{ order_id: 1, business_key: 1 },
|
||||
{ order_id: 2, business_key: 1 },
|
||||
]);
|
||||
|
||||
assert.deepEqual(result, { message: '分配快递任务已提交' });
|
||||
|
||||
// current 表查询必须携带 status != 'cancel' 过滤
|
||||
const currentQuery = calls.orderDeliveryFindAllQueries[0];
|
||||
assert.deepEqual(currentQuery.where.status, { ne: 'cancel' });
|
||||
assert.deepEqual(currentQuery.where.step, { in: [ 1, 2, 3, 4 ] });
|
||||
|
||||
// dispatch 补查同样必须携带 status != 'cancel' 过滤
|
||||
assert.equal(calls.dispatchFindAllQueries.length, 1);
|
||||
assert.deepEqual(calls.dispatchFindAllQueries[0].where.status, { ne: 'cancel' });
|
||||
|
||||
// 只有正常订单进入取号任务批次,取消订单被跳过
|
||||
assert.equal(calls.asyncTaskPayloads.length, 1);
|
||||
assert.deepEqual(
|
||||
calls.asyncTaskPayloads[0].batch.map(order => Number(order.id)),
|
||||
[ 2 ]
|
||||
);
|
||||
});
|
||||
|
||||
it('should not submit any waybill task when all orders are cancelled', async () => {
|
||||
const { ctx, calls } = createPipelineSkipCancelledHarness({
|
||||
orderDeliveryRows: [
|
||||
{
|
||||
id: 1,
|
||||
warehouse_id: 100000,
|
||||
status: 'cancel',
|
||||
step: 4,
|
||||
sys_platform_code: 'PDD',
|
||||
logistics_code: 'SF',
|
||||
sys_platform_name: '拼多多',
|
||||
logistics_name: '顺丰',
|
||||
store_id: 100000,
|
||||
},
|
||||
],
|
||||
});
|
||||
const service = new ExpressService(ctx);
|
||||
service.asyncTask = (batch, options, matchedPlatform, expressInterfaceConfig) => {
|
||||
calls.asyncTaskPayloads.push({ batch, options, matchedPlatform, expressInterfaceConfig });
|
||||
};
|
||||
|
||||
const result = await service.createWaybillCodePipeline([
|
||||
{ order_id: 1, business_key: 1 },
|
||||
]);
|
||||
|
||||
assert.deepEqual(result, { message: '所有订单均已分配运单号,无需处理' });
|
||||
assert.equal(calls.asyncTaskPayloads.length, 0);
|
||||
});
|
||||
});
|
||||
@ -53,8 +53,6 @@ describe('test/app/service/systems/notice.test.js', () => {
|
||||
|
||||
const service = new NoticeService(ctx);
|
||||
const result = await service.send({
|
||||
channel: 'webhook',
|
||||
hooks: webhookRows,
|
||||
messageType: '图片',
|
||||
businessName: 'receiving',
|
||||
event: 'receiving_completed',
|
||||
@ -276,23 +274,6 @@ describe('test/app/service/systems/notice.test.js', () => {
|
||||
|
||||
const service = new NoticeService(ctx);
|
||||
const result = await service.send({
|
||||
channel: 'webhook',
|
||||
hooks: [
|
||||
{
|
||||
id: 1,
|
||||
store_id: 100000,
|
||||
hook_type: 'custom',
|
||||
hook_url: 'https://example.com/webhook/warehouse',
|
||||
events: [ 'all' ],
|
||||
},
|
||||
{
|
||||
id: 2,
|
||||
store_id: 1000000,
|
||||
hook_type: 'custom',
|
||||
hook_url: 'https://example.com/webhook/store',
|
||||
events: [ 'receiving' ],
|
||||
},
|
||||
],
|
||||
messageType: '文本',
|
||||
businessName: 'receiving',
|
||||
event: 'receiving_completed',
|
||||
@ -353,8 +334,6 @@ describe('test/app/service/systems/notice.test.js', () => {
|
||||
|
||||
const service = new NoticeService(ctx);
|
||||
const result = await service.send({
|
||||
channel: 'webhook',
|
||||
hooks: webhookRows,
|
||||
messageType: '文本',
|
||||
businessName: 'receiving',
|
||||
event: 'receiving_completed',
|
||||
@ -465,8 +444,18 @@ describe('test/app/service/systems/notice.test.js', () => {
|
||||
app: {
|
||||
config: {},
|
||||
},
|
||||
service: {},
|
||||
model: {
|
||||
NotificationWebhook: {
|
||||
async findAll() {
|
||||
return [{
|
||||
id: 9,
|
||||
store_id: 1000000,
|
||||
hook_type: 'custom',
|
||||
hook_url: 'https://example.com/webhook/fail',
|
||||
events: [ 'all' ],
|
||||
}];
|
||||
},
|
||||
},
|
||||
NotificationSendLog: {
|
||||
async create(data) {
|
||||
failureLogs.push(data);
|
||||
@ -492,14 +481,6 @@ describe('test/app/service/systems/notice.test.js', () => {
|
||||
};
|
||||
|
||||
const result = await service.send({
|
||||
channel: 'webhook',
|
||||
hooks: [{
|
||||
id: 9,
|
||||
store_id: 1000000,
|
||||
hook_type: 'custom',
|
||||
hook_url: 'https://example.com/webhook/fail',
|
||||
events: [ 'all' ],
|
||||
}],
|
||||
messageType: '文本',
|
||||
businessName: 'receiving',
|
||||
event: 'receiving_completed',
|
||||
@ -524,7 +505,6 @@ describe('test/app/service/systems/notice.test.js', () => {
|
||||
app: {
|
||||
config: {},
|
||||
},
|
||||
service: {},
|
||||
model: {
|
||||
NotificationWebhook: {
|
||||
getAvailableEventCodes() {
|
||||
@ -564,7 +544,6 @@ describe('test/app/service/systems/notice.test.js', () => {
|
||||
app: {
|
||||
config: {},
|
||||
},
|
||||
service: {},
|
||||
model: {
|
||||
NotificationWebhook: {
|
||||
getAvailableEventCodes() {
|
||||
@ -614,12 +593,20 @@ describe('test/app/service/systems/notice.test.js', () => {
|
||||
app: {
|
||||
config: {},
|
||||
},
|
||||
service: {},
|
||||
model: {
|
||||
NotificationWebhook: {
|
||||
getAvailableEventCodes() {
|
||||
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: {
|
||||
@ -641,14 +628,6 @@ describe('test/app/service/systems/notice.test.js', () => {
|
||||
|
||||
const service = new NoticeService(ctx);
|
||||
const result = await service.send({
|
||||
channel: 'webhook',
|
||||
hooks: [{
|
||||
id: 21,
|
||||
store_id: 1000000,
|
||||
hook_type: 'wecom',
|
||||
hook_url: 'https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=test-key',
|
||||
events: [ 'receiving_completed' ],
|
||||
}],
|
||||
warehouseId: 100000,
|
||||
businessName: 'receiving',
|
||||
event: 'receiving_completed',
|
||||
|
||||
@ -540,64 +540,6 @@ describe('test/app/service/systems/order_storage_allocation.test.js', () => {
|
||||
assert.equal(orders[1].storage_status, 'fin');
|
||||
});
|
||||
|
||||
it('should skip cancelled orders when allocating storage', async () => {
|
||||
const { service, captures, orders } = createHarness({
|
||||
orders: [
|
||||
{ id: 31, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 4, status: 'cancel' },
|
||||
{ id: 32, warehouse_id: 100000, storage_status: 'fin', order_flag: '', step: 4, status: 'cancel' },
|
||||
{ id: 33, warehouse_id: 100000, storage_status: 'none', order_flag: '', step: 2, status: 'created' },
|
||||
],
|
||||
orderItems: [
|
||||
{ id: 331, order_id: 33, stock_id: 3311, plan_qty: 1, order_line_no: '1' },
|
||||
],
|
||||
stockRows: [
|
||||
{ id: 3311, item_code: 'SKU-3311', item_name: '测试商品3311', warehouse_id: 100000, deleted_at: null, is_valid: 'Y', locked_quantity: 0 },
|
||||
],
|
||||
storageRows: [
|
||||
{
|
||||
id: 33301,
|
||||
warehouse_id: 100000,
|
||||
stock_id: 3311,
|
||||
is_enabled: 1,
|
||||
delete_at: null,
|
||||
available_quantity: 1,
|
||||
quantity: 1,
|
||||
locked_quantity: 0,
|
||||
production_date: null,
|
||||
inbound_time: '2026-04-15 08:00:00',
|
||||
space_id: 3501,
|
||||
space: {
|
||||
id: 3501,
|
||||
space_code: 'ST-331',
|
||||
custom_name: '存储位331',
|
||||
is_preferred_pick: false,
|
||||
locationType: {
|
||||
id: 1,
|
||||
allow_allocation: 1,
|
||||
is_active: 1,
|
||||
},
|
||||
},
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const result = await service.allocateStorage({
|
||||
allow_storage_location: true,
|
||||
order_ids: [ 31, 32, 33 ],
|
||||
});
|
||||
|
||||
assert.equal(result.code, 200);
|
||||
assert.deepEqual(result.data.pending_order_ids, [ 33 ]);
|
||||
assert.deepEqual(result.data.allocated_order_ids, [ 33 ]);
|
||||
|
||||
const cancelledSkips = result.data.skipped_orders.filter(item => item.skipped_reason === 'order_cancelled');
|
||||
assert.equal(cancelledSkips.length, 2);
|
||||
assert.deepEqual(cancelledSkips.map(item => item.order_id), [ 31, 32 ]);
|
||||
assert.equal(captures.pickingRows.length, 1);
|
||||
assert.equal(captures.pickingRows[0].order_id, 33);
|
||||
assert.equal(orders[2].storage_status, 'fin');
|
||||
});
|
||||
|
||||
it('should group syncable orders by create_channel and mark them pending sync', async () => {
|
||||
const { service, captures } = createHarness({
|
||||
orders: [
|
||||
|
||||
Loading…
x
Reference in New Issue
Block a user