fix(notice): 收货通知链路修复(幂等键含事件维度、ext_data 透传、审核模板与收货人行调整、商品编码反查兜底)

This commit is contained in:
liufumingren 2026-08-28 04:42:22 +08:00
parent 403a73b250
commit 15e109f992
4 changed files with 173 additions and 25 deletions

View File

@ -924,6 +924,7 @@ class NoticeService extends Service {
warehouse_id: warehouseId,
[Op.or]: conditions,
},
order: [[ 'id', 'ASC' ]],
raw: true,
});
@ -934,6 +935,7 @@ class NoticeService extends Service {
group_name: row.group_name || '',
group_type: row.group_type || '',
sub_type: row.sub_type || '',
ext_data: row.ext_data || null,
}));
} catch (error) {
this.ctx.logger.warn(`[NoticeService.findSubscribedGroups] 查询订阅群失败: ${error.message}`);
@ -1167,7 +1169,9 @@ class NoticeService extends Service {
storeId: group.group_type === 'store' ? payload.storeId : null,
group,
content: `${failPrefix}${baseContent}${fileLine}`.trim(),
extId: payload.businessId || payload.traceId,
// ext_id 幂等键需含事件维度:同一业务单在不同事件(创建/完成/审核)应各落一条消息,避免被幂等复用吞掉
extId: payload.businessId ? `${payload.businessId}:${payload.event}` : payload.traceId,
extData: group.ext_data || null,
});
});
const results = await Promise.all(tasks);

View File

@ -1249,7 +1249,7 @@ class ReceivingService extends Service {
if (excelService && typeof excelService.generateAndUpload === 'function') {
const receivingNumber = String(r.receiving_number || r.id).replace(/[\\/:*?"<>|]/g, '_');
reviewReport = await excelService.generateAndUpload({
filename: `审核明细_${receivingNumber}.xlsx`,
filename: `receiving_review_${receivingNumber}.xlsx`,
dir: `exports/receiving/reviewed/${warehouse_id}`,
category: 'document',
saveRecord: true,
@ -1535,10 +1535,13 @@ class ReceivingService extends Service {
trackingNumber ? `快递单号:${trackingNumber} 已登记` : '快递单号:无',
];
const receiverName = this.resolveReceivingCreatorName(receiving);
const contentLines = [
`收货单号:${receivingNumber} 正在收货`,
`货主:${storeLabel}`,
...vehicleInfoLines,
`收货人:${receiverName || '无'}`,
];
const content = [ ...contentLines ].join('\n') + '。';
const storeContent = [ ...contentLines, `快速查看:${storeFrontendUrl}/storage/receiving_owner?id=${receivingNumber}` ].join('\n') + '。';
@ -1572,6 +1575,34 @@ class ReceivingService extends Service {
});
}
/**
* 解析收货单创建人(收货人)姓名:优先 creator_snapshot 快照,回退当前操作人。
* @param {Object} receiving 收货单快照
* @return {string} 姓名,无则空字符串
*/
resolveReceivingCreatorName(receiving = {}) {
const { ctx } = this;
const rawSnapshot = receiving.creator_snapshot || null;
let name = '';
if (typeof rawSnapshot === 'string' && rawSnapshot.trim()) {
try {
const snapshot = JSON.parse(rawSnapshot);
name = String(snapshot && (snapshot.name || snapshot.employees_name || snapshot.real_name) || '').trim();
} catch (_) {
/* 快照解析失败忽略 */
}
} else if (rawSnapshot && typeof rawSnapshot === 'object') {
name = String(rawSnapshot.name || rawSnapshot.employees_name || rawSnapshot.real_name || '').trim();
}
if (!name) {
name = String((ctx.user && ctx.user.employees_name) || '').trim();
}
return name;
}
/**
* 发送审核完成通知(receiving_reviewed),支持文字/文件两种类型。
* @param {Object} options 发送参数
@ -1608,9 +1639,6 @@ class ReceivingService extends Service {
const reportUrl = String(
(reviewReport && (reviewReport.url || reviewReport.cdnUrl || reviewReport.cosUrl || reviewReport.fileUrl)) || ''
).trim();
const reportFileName = String(
(reviewReport && (reviewReport.filename || reviewReport.fileKey || reviewReport.key)) || `审核明细_${receivingNumber}.xlsx`
).trim();
const detailList = Array.isArray(details) ? details : [];
const codeMap = itemCodeMap instanceof Map ? itemCodeMap : new Map();
@ -1627,21 +1655,18 @@ class ReceivingService extends Service {
} else if (productLines.length > 0) {
contentLines.push('', '商品:', ...productLines);
}
contentLines.push('', '请及时提交入库单入库');
contentLines.push('', `请及时提交入库单入库,入库单务必备注${receivingNumber}`);
const content = contentLines.join('\n') + '。';
return await noticeService.send({
warehouseId,
storeId: Number.isFinite(storeId) && storeId > 0 ? storeId : undefined,
messageType: reportUrl ? 'file' : 'text',
messageType: 'text',
businessName: 'receiving',
event: 'receiving_reviewed',
channel: 'warehouse',
title: `收货单${receivingNumber}完成收货审核`,
content,
url: reportUrl || undefined,
fileName: reportUrl ? reportFileName : '',
mimeType: reportUrl ? 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' : '',
businessId: receiving.id,
subject: {
id: warehouseId,
@ -1662,7 +1687,8 @@ class ReceivingService extends Service {
}
/**
* 反查货主商品编码:收货明细 system_product_id 对应 wms_stock_store.stock_id,取 item_code 作为商品编码。
* 反查商品编码:收货明细 system_product_id 优先反查 wms_stock_store.stock_id 取 item_code;
* 无对应货主商品资料时兜底取 wms_stock_warehouse.item_code(库存商品维度)。
* @param {Array<Object>} details 收货明细列表(含 system_product_id)
* @return {Promise<Map<number, string>>} system_product_id → item_code
*/
@ -1677,15 +1703,21 @@ class ReceivingService extends Service {
) ];
if (stockIds.length === 0) return codeMap;
const rows = await ctx.model.StockStore.findAll({
where: {
stock_id: { [Op.in]: stockIds },
delete_at: null,
},
attributes: [ 'stock_id', 'item_code' ],
order: [[ 'id', 'ASC' ]],
raw: true,
});
// 1. 货主商品资料:wms_stock_store.stock_id → item_code(失败不影响主流程)
let rows = [];
try {
rows = await ctx.model.StockStore.findAll({
where: {
stock_id: { [Op.in]: stockIds },
delete_at: null,
},
attributes: [ 'stock_id', 'item_code' ],
order: [[ 'id', 'ASC' ]],
raw: true,
});
} catch (storeErr) {
ctx.logger.warn(`[resolveReviewDetailItemCodeMap] 反查货主商品资料失败: ${storeErr.message}`);
}
rows.forEach(row => {
const stockId = Number(row.stock_id);
@ -1694,6 +1726,30 @@ class ReceivingService extends Service {
if (itemCode) codeMap.set(stockId, itemCode);
});
// 2. 兜底:无对应 stock_store 时取 wms_stock_warehouse.item_code
const missingStockIds = stockIds.filter(id => !codeMap.has(id));
if (missingStockIds.length > 0) {
try {
const warehouseRows = await ctx.model.StockWarehouse.findAll({
where: {
id: { [Op.in]: missingStockIds },
deleted_at: null,
},
attributes: [ 'id', 'item_code' ],
raw: true,
});
warehouseRows.forEach(row => {
const stockId = Number(row.id);
if (!stockId || codeMap.has(stockId)) return;
const itemCode = String(row.item_code || '').trim();
if (itemCode) codeMap.set(stockId, itemCode);
});
} catch (warehouseErr) {
ctx.logger.warn(`[resolveReviewDetailItemCodeMap] 兜底反查仓库商品失败: ${warehouseErr.message}`);
}
}
return codeMap;
}
@ -2126,6 +2182,7 @@ class ReceivingService extends Service {
store_name: result.store_name,
license_plate: result.license_plate,
tracking_number: result.tracking_number,
creator_snapshot: result.creator_snapshot,
},
});
} catch (noticeErr) {
@ -2489,6 +2546,7 @@ class ReceivingService extends Service {
store_name: storeName,
license_plate: receiving.license_plate,
tracking_number: receiving.tracking_number,
creator_snapshot: receiving.creator_snapshot,
},
});
} catch (noticeErr) {
@ -3367,6 +3425,7 @@ class ReceivingService extends Service {
store_name: storeName,
license_plate: receiving.license_plate,
tracking_number: receiving.tracking_number,
creator_snapshot: receiving.creator_snapshot,
},
});
} catch (noticeErr) {

View File

@ -232,12 +232,13 @@ class WarehouseNotifyService extends Service {
* @param {Object} options 推送参数。
* @param {number} options.warehouseId 仓库 ID。
* @param {number} [options.storeId] 货主 ID。
* @param {Object} options.group 目标群 { group_id, group_name }。
* @param {Object} options.group 目标群 { group_id, group_name, ext_data }。
* @param {string} [options.content=''] 通知正文。
* @param {number|string} [options.extId] 业务单号(用于幂等 ext_id)。
* @param {Object} [options.extData] 群扩展数据(渠道信息,落库与推送透传)。
* @return {Promise<Object>} 推送结果(含 messageId)。
*/
async pushSystemMessage({ warehouseId, storeId = null, group, content = '', extId = null } = {}) {
async pushSystemMessage({ warehouseId, storeId = null, group, content = '', extId = null, extData = null } = {}) {
const { ctx } = this;
const groupId = String((group && group.group_id) || '').trim();
const groupName = String((group && group.group_name) || '').trim();
@ -251,9 +252,17 @@ class WarehouseNotifyService extends Service {
};
}
// 幂等 ext_id:业务单号 + 群维度,网络重推时复用同一条消息记录
// 幂等 ext_id:业务单号 + 事件 + 群维度,网络重推时复用同一条消息记录;超长时降级哈希兜底
const sourceExtId = String(extId || `sys:notice:${Date.now()}:${Math.random().toString(36).slice(2, 8)}`);
const uniqueExtId = `sys:notice:${sourceExtId}:${groupId}`;
let uniqueExtId = `sys:notice:${sourceExtId}:${groupId}`;
if (uniqueExtId.length > 128) {
const crypto = require('crypto');
const digest = crypto.createHash('md5')
.update(uniqueExtId)
.digest('hex')
.slice(0, 12);
uniqueExtId = `sys:notice:${sourceExtId.slice(0, 100)}:${digest}`;
}
const InboxMessage = ctx.model && ctx.model.InboxMessage;
const normalizedContent = String(content || '').trim() || '系统通知';
@ -283,7 +292,7 @@ class WarehouseNotifyService extends Service {
group_name: groupName,
user_name: null,
content: normalizedContent,
ext_data: null,
ext_data: extData || null,
flags: {},
push_status: 1,
push_started_at: new Date(),
@ -302,6 +311,7 @@ class WarehouseNotifyService extends Service {
type: 'system',
content: normalizedContent,
ext_id: sourceExtId,
ext_data: extData || null,
group_id: groupId,
group_name: groupName,
timestamp: Math.floor(Date.now() / 1000),

View File

@ -286,5 +286,80 @@
"item_code 反查不到时回退明细条码,仍无则显示未知编码"
],
"module": "receiving"
},
{
"version": "2026-08-28-warehouse-01",
"date": "2026-08-28",
"type": "fixed",
"summary": "审核明细 Excel 文件名去中文(审核明细_ → receiving_review_),通知正文修正为「请及时提交入库单入库,入库单务必备注Rxx」,不再额外拼接明细文件行",
"methods": [
"notify.reply"
],
"notes": [
"storage/receiving.js reviewReceiving:Excel 上传文件名改为 receiving_review_{单号}.xlsx,URL 不再含中文,无需转码",
"sendReviewNotice:messageType 固定 text、不再传 url/fileName/mimeType,避免 notice 层追加「明细文件:文件名 链接」行;下载链接直接内嵌正文「审核明细下载:url」",
"正文末尾改为「请及时提交入库单入库,入库单务必备注Rxx」,接收方只处理 content 字段,链接以文本形式可见"
],
"module": "receiving"
},
{
"version": "2026-08-28-warehouse-02",
"date": "2026-08-28",
"type": "fixed",
"summary": "审核明细商品编码反查增加兜底:无对应 wms_stock_store 时回退取 wms_stock_warehouse.item_code,避免部分商品无货主资料时编码缺失",
"methods": [
"notify.reply"
],
"notes": [
"storage/receiving.js resolveReviewDetailItemCodeMap:先按 stock_id 反查 wms_stock_store.item_code,未命中的 system_product_id 兜底查 wms_stock_warehouse(deleted_at 为空)取 item_code",
"两段反查均独立 try/catch,失败仅记日志不阻断审核通知主流程"
],
"module": "receiving"
},
{
"version": "2026-08-28-warehouse-03",
"date": "2026-08-28",
"type": "fixed",
"summary": "notice 群推送链路补齐 ext_data 透传:查群带回群扩展数据,pushSystemMessage 落库与推送均携带,对齐 pushSystemNotification 已有方式",
"methods": [
"notify.reply"
],
"notes": [
"systems/notice/index.js findSubscribedGroups 返回群对象新增 ext_data 字段(取 inbox_group.ext_data)",
"sendToWarehouseChannel 调 pushSystemMessage 时新增 extData=group.ext_data || null",
"systems/warehouseNotify.js pushSystemMessage 新增 extData 入参:wms_inbox_message outbound 行 ext_data 落库,notify.reply 推送体 data.ext_data 透传(与 processor.writeOutboundReply 一致)"
],
"module": "receiving"
},
{
"version": "2026-08-28-warehouse-04",
"date": "2026-08-28",
"type": "fixed",
"summary": "修复通知消息幂等键吞消息:ext_id 加入事件维度,同一业务单不同事件各落一条 outbound 消息",
"methods": [
"notify.reply"
],
"notes": [
"systems/notice/index.js sendToWarehouseChannel:extId 改为 businessId:event(同一收货单的创建/完成/审核事件各落一条 outbound 消息,不再被 sys:notice:{businessId}:{groupId} 幂等复用)",
"findSubscribedGroups 查询增加 ORDER BY id ASC,保证取群顺序稳定",
"systems/warehouseNotify.js:uniqueExtId 超过 VARCHAR(128) 时降级 md5 哈希兜底",
"线上案例:R20691023 审核消息因与「正在收货」共用 ext_id 被幂等吞掉,消息表无审核记录"
],
"module": "receiving"
},
{
"version": "2026-08-28-warehouse-05",
"date": "2026-08-28",
"type": "added",
"summary": "收货单创建/首次绑定货主通知(receiving_store_bound)新增收货人行:优先取 creator_snapshot 创建人姓名,回退当前操作人,无值显示无",
"methods": [
"notify.reply"
],
"notes": [
"storage/receiving.js 新增 resolveReceivingCreatorName:解析 creator_snapshot(字符串 JSON 或对象)取 name/employees_name/real_name,回退 ctx.user.employees_name",
"sendStoreBoundNotice 模板在车牌/快递行后增加「收货人:姓名/无」,修复线上显示「收货人:{}」的空对象问题",
"三个触发点(create/bindStore/updateReceivingStats)的 receiving 快照均补充 creator_snapshot 字段"
],
"module": "receiving"
}
]