From 8a38b7a1f3c7087bdc61ca2200964b69c2adcd0b Mon Sep 17 00:00:00 2001 From: liufumingren Date: Sat, 7 Nov 2026 09:13:58 +0800 Subject: [PATCH] =?UTF-8?q?fix(send):=20=E5=8F=91=E8=B4=A7=E6=A8=A1?= =?UTF-8?q?=E6=9D=BF=E6=8C=89=E8=BF=90=E5=8D=95=E5=AE=9E=E9=99=85=E5=BF=AB?= =?UTF-8?q?=E9=80=92=E5=AE=9A=E4=BD=8D=EF=BC=8C=E4=BF=AE=E6=8A=96=E9=9F=B3?= =?UTF-8?q?=E9=A3=8E=E6=8E=A7=E6=8B=A6=E6=88=AA?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 线上报 `10000280844951: 风控拦截#CONSIGN_RISK_CONTROL_BLOCK#NOT_MATCH_SEGMENT_CHANNEL# 此运单号非抖音的运单号`。 根因:发货模板取的是「账号 + 平台」下 id 最小的那条快递接口(抖音小店第一条是中通), 而运单是申通。店管家把 TemplateId / ExpressCompanyId / ExpressCompanyCode 透传给平台, 抖音按模板的电子面单渠道校验运单号,运单不在该渠道号池里就判风控。 - externalSendSync.resolveTarget:运单快递取最近一次成功取号记录的 express_code (兜底配送表 logistics_code;注意 express_code 列存的是运单号), 再用与取号同口径的 resolveByCode 定位模板;未绑定时按模板自带快递编码匹配, 仍无命中才退回第一条并打 warn - externalSendSync.resolveSendRow:取号记录只查一次,供模板与报文复用; WaybillCodes 为空时打 warn(平台校验渠道依赖该字段) - dgjSendRow.buildSendRow:面单 ExpressCpCode 优先取号记录的快递编码,模板编码只做兜底 - dgj.sendOrders:风控/渠道类失败追加处理提示(需用对应平台+该快递的电子面单模板重新取号) - 单测:新增 externalSendTemplate.test.js(4 例);dgjSendRow.test.js 补「快递编码不被模板覆盖」 本地库真实数据验证:快手单 dgj-10000267890142_1 运单 772085332374413 属申通, 旧逻辑命中模板 #17/YUNDA,修正后命中 #29/STO;抖音四张模板按快递分别命中 (STO→10776786、ZTO→13987231、YUNDA→12360764、POSTB→12712711)。 Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com> --- backend/app/lib/dgjSendRow.js | 4 +- backend/app/lib/printPlatform/dgj.js | 8 +- backend/app/service/externalSendSync.js | 138 +++++++++++++++--- backend/test/app/lib/dgjSendRow.test.js | 30 ++++ .../test/app/lib/externalSendTemplate.test.js | 116 +++++++++++++++ 店管家取号-旧系统提取.md | 25 ++++ 6 files changed, 298 insertions(+), 23 deletions(-) create mode 100644 backend/test/app/lib/externalSendTemplate.test.js diff --git a/backend/app/lib/dgjSendRow.js b/backend/app/lib/dgjSendRow.js index df25775..5090ec9 100644 --- a/backend/app/lib/dgjSendRow.js +++ b/backend/app/lib/dgjSendRow.js @@ -107,7 +107,9 @@ function buildSendRow({ order, snapshot, fetchRecord, template }) { if (!logicalOrderId) return null; const templateId = String((template && template.template_id) || ''); - const expressCode = String((template && template.express_company_code) || '').trim(); + // 快递编码优先取号记录(运单实际所属快递),模板编码只做兜底: + // 模板与运单快递不一致时,平台会按模板渠道校验运单号(抖音会报 NOT_MATCH_SEGMENT_CHANNEL) + const expressCode = String((fetchRecord && fetchRecord.express_code) || (template && template.express_company_code) || '').trim(); const expressName = String((template && template.express_company_name) || '').trim(); const subOrders = Array.isArray(snap.SubOrders) ? snap.SubOrders : []; diff --git a/backend/app/lib/printPlatform/dgj.js b/backend/app/lib/printPlatform/dgj.js index 6d3df12..b68fc2e 100644 --- a/backend/app/lib/printPlatform/dgj.js +++ b/backend/app/lib/printPlatform/dgj.js @@ -2973,8 +2973,14 @@ class DgjService extends PrintPlatformService { const failed = extractSendOrderFailures(res.json); const realFailures = failed.filter(item => !/不是待发货状态|已发货|已取消|已关闭/.test(item.message)); if (realFailures.length) { + // 风控/渠道不匹配:平台按「模板对应的电子面单渠道」校验运单号,模板与运单快递不一致就会拦截 + const riskBlocked = realFailures.some(item => + /CONSIGN_RISK_CONTROL_BLOCK|NOT_MATCH_SEGMENT_CHANNEL|风控拦截/.test(item.message)); + const hint = riskBlocked + ? '(运单号不是该平台渠道分配的面单:请确认发货模板与运单快递一致,并用「对应平台 + 该快递」的电子面单模板重新取号)' + : ''; throw buildPlatformError( - `店管家发货同步失败:${realFailures.map(item => `${item.logicOrderId}: ${item.message}`).join(';')}`, + `店管家发货同步失败:${realFailures.map(item => `${item.logicOrderId}: ${item.message}`).join(';')}${hint}`, res ); } diff --git a/backend/app/service/externalSendSync.js b/backend/app/service/externalSendSync.js index 220e142..24a9317 100644 --- a/backend/app/service/externalSendSync.js +++ b/backend/app/service/externalSendSync.js @@ -134,9 +134,9 @@ class ExternalSendSyncService extends Service { return { ok: true, skipped: true, message: '非外部打单订单,无需同步' }; } - const { service, platformType, dbname, platformCode, template } = target; + const { service, platformType, dbname, platformCode, template, fetchRecord } = target; const host = service.constructor.resolveOrderHost(platformType); - const row = await this.resolveSendRow(order, { service, host, dbname, platformCode, template }); + const row = await this.resolveSendRow(order, { service, host, dbname, platformCode, template, fetchRecord }); if (!row) { throw new Error(`外部打单平台未找到该订单(平台 ${platformCode},系统编号 ${order.parent_order_no || order.order_no})`); } @@ -172,6 +172,7 @@ class ExternalSendSyncService extends Service { dbname: target.dbname, platformCode: target.platformCode, template: target.template, + fetchRecord: target.fetchRecord, }); if (!row) throw new Error('外部打单平台未找到该订单'); await target.service.sendOrders(host, { @@ -207,9 +208,10 @@ class ExternalSendSyncService extends Service { * @param {string} ctxInfo.host 订单域名 * @param {string} ctxInfo.dbname 分区库名 * @param {Object} [ctxInfo.template] 快递接口记录 + * @param {Object} [ctxInfo.fetchRecord] 最近一次成功取号记录(已在 resolveTarget 查过就不再查) * @return {Promise} 订单行 */ - async resolveSendRow(order, { service, host, dbname, template }) { + async resolveSendRow(order, { service, host, dbname, template, fetchRecord }) { const { ctx } = this; const logicalOrderId = String(order.parent_order_no || order.order_no || ''); @@ -226,20 +228,22 @@ class ExternalSendSyncService extends Service { } // 2) 最近一次成功取号记录:拿最新面单信息(WaybillCodeId / Pid / 快递编码) - let fetchRecord = null; - if (order.express_code) { - fetchRecord = await ctx.model.WaybillFetchRecord.findOne({ - where: { - principal_id: order.principal_id, - delivery_order_code: { [ ctx.app.Sequelize.Op.like ]: `${order.order_no}%` }, - status: 1, - }, - order: [[ 'id', 'DESC' ]], - }); - } + if (!fetchRecord) fetchRecord = await this.findLatestFetchRecord(order); const localRow = buildSendRow({ order, snapshot, fetchRecord, template }); - if (localRow) return localRow; + if (localRow) { + // 报文里 WaybillCodes 是平台校验运单渠道的依据(WaybillCodeId / Pid / 快递编码),缺失时要能查到 + const waybills = Array.isArray(localRow.WaybillCodes) ? localRow.WaybillCodes : []; + if (!waybills.length) { + ctx.logger.warn( + '[external-send] %s 没有带平台面单标识(取号记录 %s),WaybillCodes 为空,运单号 %s', + order.order_no, + fetchRecord ? `#${fetchRecord.id}` : '缺失', + localRow.LastWaybillCode || order.express_code || '-' + ); + } + return localRow; + } // 3) 没有快照(历史单/非平台单):退回回读平台订单行 ctx.logger.info('[external-send] %s 没有本地快照,回读平台订单行', order.order_no); @@ -280,6 +284,92 @@ class ExternalSendSyncService extends Service { * @param {Object} order 配送表订单行 * @return {Promise} 目标信息;非外部打单订单返回 null */ + /** + * 最近一次成功取号记录(含运单号、快递编码、平台面单标识) + * @param {Object} order 配送状态行 + * @return {Promise} 取号记录 + */ + async findLatestFetchRecord(order) { + const { ctx } = this; + if (!order || !order.order_no) return null; + try { + return await ctx.model.WaybillFetchRecord.findOne({ + where: { + principal_id: order.principal_id, + delivery_order_code: { [ ctx.app.Sequelize.Op.like ]: `${order.order_no}%` }, + status: 1, + }, + order: [[ 'id', 'DESC' ]], + }); + } catch { + return null; + } + } + + /** + * 定位发货用的快递接口(模板) + * + * 必须按**运单实际所属的快递**取模板:店管家把 TemplateId / ExpressCompanyId 透传给平台, + * 抖音/快手等平台会按模板的电子面单渠道校验运单号,模板与运单快递不一致会被判 + * `风控拦截#NOT_MATCH_SEGMENT_CHANNEL#(此运单号非抖音的运单号)`。 + * 取号就是按「账号 + 平台 + 快递编码」定位模板(`resolveByCode`),发货沿用同一口径。 + * + * @param {Object} params 参数 + * @param {Object} params.account 打单账号 + * @param {string} params.platformCode OMS 平台编码 + * @param {string} params.expressCode 运单实际使用的快递编码(取号记录优先) + * @param {number} params.principalId 主体ID + * @return {Promise} 快递接口记录(纯对象) + */ + async resolveSendTemplate({ account, platformCode, expressCode, principalId }) { + const { ctx } = this; + const code = String(expressCode || '').trim(); + if (code && platformCode) { + // 1) 显式绑定关系(OMS 快递编码 → 模板) + const matched = await ctx.service.externalPrintExpressInterface.resolveByCode( + account.id, + { platformCode, expressCode: code }, + principalId + ); + if (matched) return matched; + // 2) 没绑 custom_code 的历史数据:按模板自带的快递公司编码兜底匹配(如 STO / YUNDA / POSTB) + const byCompany = await ctx.model.ExternalPrintExpressInterface.findOne({ + where: { + principal_id: principalId, + account_id: account.id, + platform_code: platformCode, + status: 1, + express_company_code: code.toUpperCase(), + }, + order: [[ 'id', 'ASC' ]], + }); + if (byCompany) return byCompany.get ? byCompany.get({ plain: true }) : byCompany; + } + // 3) 兜底(历史单没有取号记录 / 快递未绑定):退回该平台的第一条模板,保持原有行为 + const row = await ctx.model.ExternalPrintExpressInterface.findOne({ + where: { principal_id: principalId, account_id: account.id, platform_code: platformCode, status: 1 }, + order: [[ 'id', 'ASC' ]], + }); + if (!row) return null; + const fallback = row.get ? row.get({ plain: true }) : row; + if (code) { + // 运单快递没有对应模板时平台会按模板渠道校验运单号(风控/渠道不匹配),留痕便于排查 + ctx.logger.warn( + '[external-send] 平台 %s 快递 %s 未绑定模板,退回 #%s(模板快递 %s)', + platformCode, + code, + fallback.id, + fallback.express_company_code || '-' + ); + } + return fallback; + } + + /** + * 定位发货目标(打单账号 / 发货域名 / 分区库名 / 快递接口) + * @param {Object} order 配送表订单行 + * @return {Promise} 目标信息 + */ async resolveTarget(order) { const { ctx } = this; if (!order || !order.shop_id) return null; @@ -296,13 +386,19 @@ class ExternalSendSyncService extends Service { const platformCode = String(order.source_platform_code || '').trim(); const service = ctx.service.externalPrintOrder.createPlatformService(account); const resolvePlatformType = service.constructor && service.constructor.resolvePlatformType; - const template = await ctx.model.ExternalPrintExpressInterface.findOne({ - where: { principal_id: order.principal_id, account_id: account.id, platform_code: platformCode, status: 1 }, - attributes: [ 'id', 'platform_type', 'dbname', 'template_id', 'express_company_id', 'express_company_code' ], - order: [[ 'id', 'ASC' ]], + + // 运单实际用的快递:以最近一次成功取号记录为准(取号时按 WMS 传入的快递编码定位模板), + // 兜底用订单的物流公司编码;发货模板必须与之对齐,否则平台按模板渠道校验运单号会报风控 + const fetchRecord = await this.findLatestFetchRecord(order); + const waybillExpressCode = String((fetchRecord && fetchRecord.express_code) || order.logistics_code || '').trim(); + const template = await this.resolveSendTemplate({ + account, + platformCode, + expressCode: waybillExpressCode, + principalId: order.principal_id, }); // PlatformType(决定回传发货用哪个域名)优先按「订单原始平台」:1688 分销单在 OMS 里被换算成 - // 抖音小店/淘宝(为了选对模板),但订单行仍在 Alibaba 分区(fxali),按换算后的平台找会查错域名 + // 抖音小店/淘宝(为了选对模板),但订单行仍在 Alibaba 分区(fxali),按换算后的平台会查错域名 const raw = order.extend_props && typeof order.extend_props === 'object' ? order.extend_props : {}; const originalCode = String(raw.original_platform_code || '').trim(); let platformType = ''; @@ -313,7 +409,7 @@ class ExternalSendSyncService extends Service { platformType = template ? template.platform_type : (typeof resolvePlatformType === 'function' ? resolvePlatformType(platformCode) : ''); } if (!platformType) return null; - return { service, account, platformType, dbname: template ? template.dbname : '', platformCode, template }; + return { service, account, platformType, dbname: template ? template.dbname : '', platformCode, template, fetchRecord }; } /** diff --git a/backend/test/app/lib/dgjSendRow.test.js b/backend/test/app/lib/dgjSendRow.test.js index 8fc8fa1..ff71d7f 100644 --- a/backend/test/app/lib/dgjSendRow.test.js +++ b/backend/test/app/lib/dgjSendRow.test.js @@ -125,6 +125,36 @@ describe('lib/dgjSendRow 本地快照拼发货报文', () => { assert.strictEqual(noWaybill, null); }); + it('面单快递编码优先取号记录,不被模板编码覆盖(抖音会按模板渠道校验运单号)', () => { + // 平台响应里没有 CpCode/RealCpCode 时,旧实现会用模板快递(可能是别的快递)兜底 + const fetchRecord = { + express_code: 'STO', + waybill_code: '770357410089880', + created_at: new Date('2026-11-07T07:39:45Z'), + raw_response: JSON.stringify({ + Success: true, + Data: { + WaybillCode: [{ + WaybillCode: '770357410089880', + WaybillCodeId: 10000304201567, + WaybillCodePid: '8c51d72ab1f_2_1', + OrderId: '10000279877231', + }], + }, + }), + }; + const order = { + order_no: 'dgj-10000279877231', + parent_order_no: '10000279877231', + express_codes: JSON.stringify([ '770357410089880' ]), + extend_props: {}, + }; + const ztoTemplate = { template_id: '13987231', express_company_code: 'ZTO' }; + const row = buildSendRow({ order, snapshot: buildSnapshot(), fetchRecord, template: ztoTemplate }); + console.log('快递编码兜底:', row.WaybillCodes[0].ExpressCpCode, '| 模板:', ztoTemplate.express_company_code); + assert.strictEqual(row.WaybillCodes[0].ExpressCpCode, 'STO'); + }); + it('面单信息解析:优先 RealCpCode,缺字段不炸', () => { const waybill = pickWaybillFromFetchRecord(buildFetchRecord().raw_response); const entry = toWaybillEntry(waybill, { templateId: '10776786', expressCode: 'STO', subOrders: [{ OrderItemId: 1, OrderItemCode: 'A' }] }); diff --git a/backend/test/app/lib/externalSendTemplate.test.js b/backend/test/app/lib/externalSendTemplate.test.js new file mode 100644 index 0000000..d73800a --- /dev/null +++ b/backend/test/app/lib/externalSendTemplate.test.js @@ -0,0 +1,116 @@ +'use strict'; + +const { app, assert } = require('egg-mock/bootstrap'); +const mm = require('egg-mock'); + +/** + * 快递接口记录(纯对象形态,与 resolveByCode 返回一致) + * @param {Object} [overrides] 覆盖字段 + * @return {Object} 快递接口记录 + */ +function buildInterface(overrides = {}) { + return { + id: 25, + platform_type: 'TouTiao', + platform_code: 'DYXD', + template_id: '10776786', + express_company_id: 8, + express_company_code: 'STO', + express_company_name: '申通', + custom_code: null, + dbname: 'y/2wUDWCZOk=', + ...overrides, + }; +} + +/** + * 包一层 Sequelize 实例的最小替身(服务里用了 .get({ plain: true })) + * @param {Object} row 纯对象记录 + * @return {Object|null} 带 get() 的替身 + */ +function asModel(row) { + return row ? { get: () => row, ...row } : null; +} + +describe('service/externalSendSync 发货模板按运单快递定位', () => { + let ctx; + let service; + + beforeEach(() => { + ctx = app.mockContext(); + service = ctx.service.externalSendSync; + }); + + it('有绑定关系时用绑定模板(与取号同口径)', async () => { + const bound = buildInterface({ id: 29, template_id: '10824270', express_company_code: 'STO', custom_code: 'STO' }); + ctx.service.externalPrintExpressInterface.resolveByCode = async () => bound; + ctx.model.ExternalPrintExpressInterface.findOne = async () => { throw new Error('不应走到兜底查询'); }; + + const template = await service.resolveSendTemplate({ + account: { id: 1 }, + platformCode: 'SPH', + expressCode: 'STO', + principalId: 5, + }); + console.log('绑定命中:', template.id, template.template_id, template.express_company_code); + assert.strictEqual(template.id, 29); + }); + + it('没绑定 custom_code 时按模板快递公司编码兜底匹配', async () => { + ctx.service.externalPrintExpressInterface.resolveByCode = async () => null; + const queries = []; + ctx.model.ExternalPrintExpressInterface.findOne = async options => { + queries.push(options); + return asModel(buildInterface({ id: 25, express_company_code: 'STO' })); + }; + + const template = await service.resolveSendTemplate({ + account: { id: 1 }, + platformCode: 'DYXD', + expressCode: 'STO', + principalId: 5, + }); + console.log('兜底命中:', template.id, template.express_company_code, '| 查询条件:', JSON.stringify(queries[0].where)); + assert.strictEqual(template.id, 25); + assert.strictEqual(queries[0].where.express_company_code, 'STO'); + }); + + it('都对不上时退回该平台第一条模板(保持历史行为)', async () => { + ctx.service.externalPrintExpressInterface.resolveByCode = async () => null; + let call = 0; + ctx.model.ExternalPrintExpressInterface.findOne = async () => { + call += 1; + // 第一次按快递公司编码查(无命中),第二次退回第一条 + return call === 1 ? null : asModel(buildInterface({ id: 4, express_company_code: 'ZTO', template_id: '13987231' })); + }; + const warnings = []; + mm(ctx, 'logger', { warn: (...args) => warnings.push(args), info() {}, error() {} }); + + const template = await service.resolveSendTemplate({ + account: { id: 1 }, + platformCode: 'DYXD', + expressCode: 'STO', + principalId: 5, + }); + console.log('退回第一条:', template.id, template.express_company_code, '| 告警条数:', warnings.length); + assert.strictEqual(template.id, 4); + assert.ok(warnings.length > 0, '未绑定时应记一条告警便于排查'); + mm.restore(); + }); + + it('没有快递编码(历史单)时直接退回第一条,不告警', async () => { + ctx.service.externalPrintExpressInterface.resolveByCode = async () => null; + ctx.model.ExternalPrintExpressInterface.findOne = async () => asModel(buildInterface({ id: 4, express_company_code: 'ZTO' })); + const warnings = []; + mm(ctx, 'logger', { warn: (...args) => warnings.push(args), info() {}, error() {} }); + + const template = await service.resolveSendTemplate({ + account: { id: 1 }, + platformCode: 'DYXD', + expressCode: '', + principalId: 5, + }); + assert.strictEqual(template.id, 4); + assert.strictEqual(warnings.length, 0); + }); +}); diff --git a/店管家取号-旧系统提取.md b/店管家取号-旧系统提取.md index 03b8bd8..456d577 100644 --- a/店管家取号-旧系统提取.md +++ b/店管家取号-旧系统提取.md @@ -85,6 +85,31 @@ OMS 实现: | `dgj.sendOrders(host, { traceId, dbname, rows, templateId, expressCompanyId, expressCode })` | 按上面口径组装并提交;整包或逐单失败抛「店管家发货同步失败:…」 | | `service/externalSendSync.js` | 配送后同步的状态机(待同步 → 已同步 / 待重试 → 3 次转异常);快照缺失时才回读平台订单行兜底 | +**发货模板必须按运单实际快递定位(2026-11-07 生产故障)**: + +线上报过 `店管家发货同步失败:10000280844951: 风控拦截#CONSIGN_RISK_CONTROL_BLOCK#风控拦截# +NOT_MATCH_SEGMENT_CHANNEL#…此运单号非抖音的运单号…`。 + +原因是**发货模板取错**:旧实现按「账号 + 平台」取第一条快递接口(`order by id ASC`), +抖音小店的第一条恰好是中通模板,而运单是申通(77035741…)。店管家把 +`TemplateId` / `ExpressCompanyId` / `ExpressCompanyCode` 透传给平台, +抖音按模板的电子面单渠道去校验运单号 → 运单不在该渠道的号池里,直接风控拦截。 + +修正口径(与取号完全一致): + +| 步骤 | 取值 | +|---|---| +| 运单快递 | `waybill_fetch_records.express_code`(最近一次成功取号记录)→ 兜底 `order_status_delivery.logistics_code` | +| 模板定位 | `externalPrintExpressInterface.resolveByCode(账号, {平台编码, 快递编码})`(显式绑定)→ 模板自带 `express_company_code` 匹配 → 该平台第一条(保留历史行为并 `warn`) | +| 面单快照 | `WaybillCodes[].ExpressCpCode` 优先用**取号记录的快递编码**,模板编码只做兜底 | + +注意 `order_status_delivery.express_code` 存的是**运单号**(不是快递编码),快递编码在 `logistics_code`。 + +验证(本地库真实数据):快手单 `dgj-10000267890142_1` 的运单 `772085332374413` 是申通, +旧逻辑命中模板 `#17 / YUNDA(圆通)`,修正后命中 `#29 / STO(申通)`, +拼出的报文 `ExpressCompanyCode=STO`、`WaybillCodes[0].ExpressCpCode=STO`; +抖音四张模板也能按快递分别命中(STO→10776786 / ZTO→13987231 / YUNDA→12360764 / POSTB→12712711)。 + **请求量控制(避免被平台判成刷单/攻击)**: | 手段 | 说明 |