feat(退回对接): 退回通知复用既有 webhook(X-Signature)新增事件 preparations.returned——对方零新增凭据/端点,落售后+生成补送单
CI / server typecheck + tests (push) Canceled after 0s
CI / web typecheck + tests + miniprogram syntax (push) Canceled after 0s
CI / eslint (观察项,C7 骨架) (push) Canceled after 0s
CI / npm audit (critical 硬拦) (push) Canceled after 0s

This commit is contained in:
Ubuntu
2026-10-20 17:13:09 +08:00
parent c4b3a547cf
commit 54511665ed
@@ -557,6 +557,57 @@ router.post('/main-system/webhook', async (req: Request, res: Response) => {
* · 业务失败(如零价被拦)**返回 200** —— 事件已持久化,重试由我方对账负责,
* 返 5xx 只会让主系统重推,而重推解决不了"我方前置未满足"。
*/
/* ── 主系统「商品退回」(2026-10-20)────────────────────────────────────
* 通道与 `binding_changed` 完全一致:复用既有 webhook URL + `X-Signature` 验签,
* **对方无需新增端点/密钥/账号**;事件名 `preparations.returned`。
* 我方处理:落售后记录 + 立即生成补送单(幂等键 = main_return_code + sku)。
* 业务失败返回 200(事件已收,重试交给我方台账轮询兜底)。
*/
if (event === 'preparations.returned') {
const rawRows = Array.isArray(payload?.data) ? payload.data : [payload];
const results: Array<{ prepId: string; ok: boolean; duplicated?: boolean; resupplyOrderCode?: string | null; error?: string }> = [];
const { ingestMainSystemReturn, resolveOrderCodeByPrepId } = await import('../services/mainSystemReturnService');
for (const raw of rawRows) {
const row = (raw || {}) as Record<string, unknown>;
const prepId = String(row.id || row.preparation_id || row.prep_id || '').trim();
if (!prepId) continue;
const ourOrderCode =
String(row.our_order_code || '').trim() ||
(branchCode ? await resolveOrderCodeByPrepId({ branchCode, prepId }) : null) ||
'';
if (!ourOrderCode) {
results.push({ prepId, ok: false, error: 'order_not_found' });
continue;
}
const quantity = Number(row.return_qty ?? row.qty ?? row.quantity);
const skuCode = String(row.sku_code || '').trim();
if (!(quantity > 0) || !skuCode) {
results.push({ prepId, ok: false, error: 'invalid_payload' });
continue;
}
try {
const out = await ingestMainSystemReturn({
branchCode,
mainReturnCode: row.return_code ? String(row.return_code) : null,
mainOrderCode: row.order_code ? String(row.order_code) : String(payload?.order_code || ''),
ourOrderCode,
mainPrepId: prepId,
skuCode,
itemName: row.item_name ? String(row.item_name) : null,
quantity,
unit: row.unit ? String(row.unit) : null,
reason: row.reason ? String(row.reason) : null,
returnedAt: row.returned_at ? String(row.returned_at) : null,
});
results.push({ prepId, ok: true, duplicated: out.duplicated, resupplyOrderCode: out.resupplyOrderCode });
} catch (error) {
results.push({ prepId, ok: false, error: (error as Error)?.message || 'failed' });
}
}
console.log(`[main-system-webhook] ${branchCode} preparations.returned:处理 ${results.length} 行,成功 ${results.filter((r) => r.ok).length}`);
return res.json({ ok: true, results });
}
if (isFulfillmentEvent(event)) {
if (!isFulfillmentEventsEnabled()) {
// 开关关闭 ⇒ 与改造前逐字节一致:200 收下但忽略