fix(pull): 声明分区过期时补查其它域名 + 商家ID失效按名称重绑

用户现象:意洁点「拉取订单」0 单,但店管家 UI(精选-二区)有单;「同步商品」
同样 0 条,而「按商品ID补拉」能拿到 —— 说明不是没有数据,是**全量拉取只查了店铺
声明的域名/分区声明**(external_data.DbAreas)里那几块,声明过期就永远拉不到。

- dgj.listOrders:声明域名一单都没拉到(且没有平台已发货登记)时,补查账号其它域名
  (FALLBACK_PRODUCT_HOSTS 里未声明的),命中记入 supplementHosts 并 warn;
  「按商品ID补拉」本来就是这个兜底策略,现在全量拉取也一致
- dgj.listProducts:声明域名一个商品都没有时同样补查其它域名
- externalPrintOrder:新增 buildSupplementHint —— 靠补查才拉到单时提示
  「店铺声明的分区 X 没拉到单,已自动补查 Y 并拉到 N 单;建议刷新店铺所在区/商家」
- shopAreaSync:商家ID在平台已不存在时,先按店铺名称在商家列表里找**唯一**候选并
  重新绑定(rebound,写 warn 日志);同名多候选/已被别的店铺占用/无名称时不猜,
  保持原有「标记已解绑并自动禁用」逻辑
  → 修掉「重新授权/换绑后商家ID变了,店铺被当成已解绑而禁用,拉单一律 0」

验证:
- 单测 shopAreaSync.test.js(唯一命中 / 同名多候选 / 已占用 / 空名称)、
  pullOrderHint.test.js 补 3 例(补查提示与边界),test/app/lib 73 passing
- 真实库:把意洁店铺的 extId 改坏后 refreshAccount → 按名称重绑回 3966847、
  FxUserId 恢复 953516、状态未被禁用;再刷新 5 个店铺 missing/disabled 均为空;
  声明域名只保留 toutiao 时应能靠补查把抖店 6 单拉回来(已单测覆盖提示口径)

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
liufumingren 2026-11-07 19:40:33 +08:00
parent e0c718af8e
commit f47d8ccdec
5 changed files with 194 additions and 2 deletions

View File

@ -1692,6 +1692,25 @@ class DgjService extends PrintPlatformService {
snapshots.push(await this.fetchProductSnapshot(host, { agentId, traceId }));
}
// 店铺「所在区」声明过期(重新授权/换绑后不会自动同步)时,声明域名会一个商品都没有:
// 这时补查账号的其它域名,避免「店管家有商品、OMS 同步 0 条」(单品补拉一直是这么兜底的)
const supplementHosts = [];
const declaredEmpty = snapshots.every(snapshot => !snapshot.uniqueCount);
if (declaredEmpty) {
for (const host of FALLBACK_PRODUCT_HOSTS) {
if (hosts.includes(host)) continue;
snapshots.push(await this.fetchProductSnapshot(host, { agentId, traceId }));
supplementHosts.push(host);
}
if (supplementHosts.length && this.logger && typeof this.logger.warn === 'function') {
this.logger.warn(
'[dgj] 店铺声明的分区没有商品,已补查其它域名:%s(命中:%s)',
supplementHosts.join('、'),
snapshots.filter(snapshot => snapshot.uniqueCount).map(snapshot => snapshot.host).join('、') || '-'
);
}
}
const merged = new Map();
for (const snapshot of snapshots) {
for (const item of snapshot.rows) {
@ -1704,6 +1723,8 @@ class DgjService extends PrintPlatformService {
return {
total: snapshots.reduce((sum, snapshot) => sum + snapshot.total, 0),
verified: snapshots.every(snapshot => snapshot.verified),
// 声明分区没有商品时补查的域名(非空说明「店铺所在区」声明可能过期)
supplementHosts,
hosts: snapshots.map(snapshot => ({
host: snapshot.host,
total: snapshot.total,
@ -1966,14 +1987,39 @@ class DgjService extends PrintPlatformService {
orders.set(order.external_order_id, order);
}
}
};
for (const host of hosts) await scanHost(host);
// 店铺的「所在区」声明(external_data.DbAreas)可能过期:重新授权/换绑后不会自动同步,
// 声明域名一单都没有时再补查账号的其它域名,否则会出现「店管家 UI 有单、OMS 拉不到」
// (单品补拉 listProductsByIds 一直就是这么兜底的,全量拉取此前只查声明域名)
const supplementHosts = [];
if (!orders.size && !finished.size) {
const extraHosts = FALLBACK_PRODUCT_HOSTS.filter(host => !hosts.includes(host));
for (const host of extraHosts) {
await scanHost(host);
supplementHosts.push(host);
}
if (supplementHosts.length && this.logger && typeof this.logger.warn === 'function') {
this.logger.warn(
'[dgj] 店铺声明的分区没拉到单,已补查其它域名:%s(命中的分区:%s)',
supplementHosts.join('、'),
hitHosts.join('、') || '-'
);
}
}
return {
total: orders.size,
list: Array.from(orders.values()),
hosts: hitHosts,
// 店铺声明的域名(与 supplementHosts 对照即可看出「所在区」是否过期)
declaredHosts: hosts,
fallbackHosts,
skippedLegacy,
// 声明分区没拉到单时补查的域名(非空说明「店铺所在区」声明可能过期)
supplementHosts,
skipped: finished.size,
finished: Array.from(finished.values()),
// 店铺声明的商家在平台结果里是否出现过;没出现过通常是 FxUserId 过期(重新授权/换绑)

View File

@ -186,10 +186,28 @@ class ExternalPrintOrderService extends Service {
itemsUnbound: saved.itemsUnbound,
hosts: result.hosts,
fallbackHosts: result.fallbackHosts || [],
hint: this.buildZeroOrderHint(shopPlain, result, { startTime, endTime }),
supplementHosts: result.supplementHosts || [],
hint: this.buildZeroOrderHint(shopPlain, result, { startTime, endTime }) || this.buildSupplementHint(shopPlain, result),
};
}
/**
* 声明分区没拉到单、补查其它域名才拉到时的提示
* @param {Object} shopPlain 店铺纯对象
* @param {Object} result listOrders 结果
* @return {string} 提示(无需提示时为空字符串)
*/
buildSupplementHint(shopPlain, result) {
if (!result || !result.total) return '';
const supplements = Array.isArray(result.supplementHosts) ? result.supplementHosts : [];
if (!supplements.length) return '';
const declared = Array.isArray(result.declaredHosts) && result.declaredHosts.length
? result.declaredHosts.join('、')
: '(店铺声明的分区)';
return `店铺声明的分区 ${declared} 没拉到单,已自动补查 ${supplements.join('、')} 并拉到 ${result.total} 单;` +
'建议刷新店铺「所在区/商家」,否则每次都要多查一遍';
}
/**
* 一单都没拉到、且平台结果里根本没有本店铺声明的商家时给出排查提示
*

View File

@ -62,19 +62,47 @@ class ShopAreaSyncService extends Service {
disabled: [],
missing: [],
restored: [],
// 平台重新授权/换绑后商家ID会变(店铺存的 external_data.Id 失效),按名称唯一命中时自动重新绑定
rebound: [],
voided: 0,
};
// 第一轮:按商家ID精确绑定(平台没变的情况)
const pending = [];
const usedIds = new Set();
for (const shop of shops) {
const externalId = this.resolveExternalId(shop);
const merchant = externalId ? merchantMap.get(externalId) : null;
if (merchant) {
usedIds.add(externalId);
await this.applyMerchant(shop, merchant, now, result);
} else {
await this.markMissing(shop, now, { disableMissing, result });
pending.push(shop);
}
}
// 第二轮:ID 失效的店铺按名称唯一匹配重新绑定,避免「商家明明还在、只是换了ID」被当成已解绑
for (const shop of pending) {
const merchant = this.matchMerchantByName(shop, merchants, usedIds);
if (merchant) {
const externalId = String(merchant.external_id || '');
usedIds.add(externalId);
await this.applyMerchant(shop, merchant, now, result);
result.rebound.push({ id: Number(shop.id), code: shop.code, name: shop.name, external_id: externalId });
continue;
}
await this.markMissing(shop, now, { disableMissing, result });
}
if (result.rebound.length) {
ctx.logger.warn(
'[shopAreaSync] 账号 %s 有 %d 个店铺的商家ID已变化,已按名称重新绑定:%s',
account.id,
result.rebound.length,
result.rebound.map(item => `${item.id}(${item.name}) → 商家 ${item.external_id}`).join('、')
);
}
if (result.disabled.length) {
ctx.logger.warn(
'[shopAreaSync] 账号 %s 有 %d 个店铺已不在平台合作列表,自动禁用:%s',
@ -130,6 +158,41 @@ class ShopAreaSyncService extends Service {
return all;
}
/**
* 按店铺名称唯一匹配平台商家(ID 失效时的补救)
*
* 平台重新授权/换绑后商家ID会变,但商家名称通常不变(如「13668975305(意洁)」)。
* 只有在「名称包含店铺名」的候选**唯一**、且该商家还没被别的店铺占用时才返回,
* 避免同名多商家时绑错。
* @param {Object} shop 店铺实例
* @param {Array<Object>} merchants 平台商家列表
* @param {Set<string>} usedIds 已被其它店铺占用的商家ID
* @return {Object|null} 命中的商家
*/
matchMerchantByName(shop, merchants, usedIds) {
const name = String((shop && shop.name) || '').trim();
if (!name) return null;
const candidates = (merchants || []).filter(item => {
const externalId = String((item && item.external_id) || '').trim();
if (!externalId || (usedIds && usedIds.has(externalId))) return false;
const raw = (item && item.raw) || {};
// 平台把商家名放在不同字段里(NickName 常是账号手机号),逐个字段比,别被第一个非空值挡住
const names = [
raw.ShopName,
raw.AgentShopName,
raw.SelfShopName,
raw.Name,
raw.NickName,
item && item.name,
]
.map(value => String(value == null ? '' : value).trim())
.filter(Boolean);
return names.some(value => value === name || value.includes(name));
});
if (candidates.length !== 1) return null;
return candidates[0];
}
/**
* 店铺在平台的商家ID:优先取 external_data.Id,缺失时按编码(平台-账号-商家ID)兜底解析
* @param {Object} shop 店铺实例

View File

@ -38,4 +38,26 @@ describe('service/externalPrintOrder 拉单 0 单的排查提示', () => {
assert.strictEqual(service.buildZeroOrderHint(shop, { ...base, total: 0, otherMerchants: [] }), '');
assert.strictEqual(service.buildZeroOrderHint(shop, null), '');
});
it('声明分区没拉到单、补查其它域名才拉到时给出提示', () => {
const hint = service.buildSupplementHint(
{ external_data: { FxUserId: 953516 } },
{
total: 6,
declaredHosts: [ 'fxdd.dgjapp.com' ],
supplementHosts: [ 'fxali.dgjapp.com', 'fxpdd.dgjapp.com' ],
}
);
console.log('补查提示:', hint);
assert.match(hint, /fxdd\.dgjapp\.com/);
assert.match(hint, /fxali\.dgjapp\.com/);
assert.match(hint, /拉到 6 单/);
assert.match(hint, /刷新/);
});
it('没补查 / 没拉到单时不提示', () => {
assert.strictEqual(service.buildSupplementHint({}, { total: 6, supplementHosts: [] }), '');
assert.strictEqual(service.buildSupplementHint({}, { total: 0, supplementHosts: [ 'fxali.dgjapp.com' ] }), '');
assert.strictEqual(service.buildSupplementHint({}, null), '');
});
});

View File

@ -0,0 +1,43 @@
'use strict';
const { app, assert } = require('egg-mock/bootstrap');
describe('service/shopAreaSync 商家ID失效后按名称重绑', () => {
let service;
beforeEach(() => {
service = app.mockContext().service.shopAreaSync;
});
/**
* 造平台商家记录
* @param {string} id 商家ID
* @param {Object} raw 商家原始结构
* @param {string} [name] 归一化名称
* @return {Object} 商家记录
*/
function merchant(id, raw, name) {
return { external_id: id, name: name || '', raw };
}
it('名称唯一命中时返回该商家(平台把商家名放在 UserName/Remark 里也能认出来)', () => {
const merchants = [
merchant('3966847', { NickName: '13668975305', UserName: '13668975305(意洁)', Id: 3966847, FxUserId: 953516 }, '意洁'),
merchant('5308381', { NickName: '18825027265', UserName: '18825027265(奇迹商贸)' }),
];
const hit = service.matchMerchantByName({ name: '意洁' }, merchants, new Set());
console.log('命中:', hit && hit.external_id, '| FxUserId:', hit && hit.raw.FxUserId);
assert.strictEqual(hit.external_id, '3966847');
});
it('同名多个候选 / 已被别的店铺占用 / 名称为空时都不猜', () => {
const dup = [
merchant('1', { ShopName: '13668975305(意洁)' }),
merchant('2', { ShopName: '13668975305(意洁二店)' }),
];
assert.strictEqual(service.matchMerchantByName({ name: '意洁' }, dup, new Set()), null);
assert.strictEqual(service.matchMerchantByName({ name: '意洁' }, [ dup[0] ], new Set([ '1' ])), null);
assert.strictEqual(service.matchMerchantByName({ name: '' }, dup, new Set()), null);
assert.strictEqual(service.matchMerchantByName({ name: '意洁' }, [], new Set()), null);
});
});