oms/backend/app/service/externalPrintOrder.js
liufumingren 61a9587851 feat(pull): 拉单 0 单时给出「商家对不上」的排查提示
抖音平台订单拉不到排查结论:平台侧数据本身能拉到(意洁的 1688→抖店分销单
11-07 16:27 已入库 6 单 DYXD),问题出在「店铺声明的商家 FxUserId 与平台不一致」时
只回 0 单、看不出原因。本次让这种情况自己说话:

- dgj.listOrders:全量兜底扫描时记录平台实际出现的商家(UpFxUserId → 单量/店铺名),
  返回 merchantSeen / otherMerchants
- externalPrintOrder:新增 buildZeroOrderHint —— 0 单且本店商家没出现过时,
  输出「近 N 天没有出现 FxUserId=xxx(分区…),实际出现的是 意洁(953516,450 单)…」,
  并提示刷新店铺所在区/商家
- 自动拉取的 last_order_sync_msg、手动拉取响应 hint / 前端提示都带上该说明
- 单测 pullOrderHint.test.js(2 例:有提示/无误报,含分区去重)

排查记录(本地账号 1 实测):
- 意洁(953516):15 天待处理 10 单 = DYXD 6 + TB 3 + PDD 1,抖音分销单正常
- 抖店分区(fxdd) 近 90 天 1099+154 单全部已发货/关闭,0 条待发货 → 平台侧确实没得拉
- 两家「奇迹商贸」店铺绑的商家 1921984 / 1844767 在全部分区 90 天内 0 单;
  平台上真正有单的奇迹商贸商家是 401499 → 需要在 OMS 重新同步店铺

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-07 18:44:02 +08:00

895 lines
40 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

'use strict';
const Service = require('egg').Service;
const { createPrintPlatformService, hasPrintPlatformService } = require('../lib/printPlatform');
const { ORDER_STATUS } = require('../lib/orderStatus');
const { buildSnapshot } = require('../lib/orderItemExpand');
/**
* 截断字符串,避免超出表字段长度
* @param {*} value 原始值
* @param {number} max 最大长度
* @return {string} 截断后的字符串
*/
function truncateText(value, max) {
return String(value == null ? '' : value).slice(0, max);
}
/**
* 是否为平台登录态失效类错误(各分区接口统一返回「登录信息过期,请重新登录」或 token is invalid)
* @param {Error} err 异常
* @return {boolean} 是否需要重新登录
*/
function isSessionExpiredError(err) {
const message = String((err && err.message) || '');
return /登录信息过期|登录已失效|token is invalid|未登录|缺少 token/i.test(message);
}
/**
* 明细行转列表摘要快照(与订单页 product_info 口径一致)
* @param {Array} lines 明细
* @return {Array|null} 快照
*/
function buildProductInfo(lines) {
const list = Array.isArray(lines) ? lines : [];
if (!list.length) return null;
return list.map(line => ({
item_code: line.sku_code || line.outer_item_id || null,
item_name: line.name || null,
quantity: line.quantity,
price: line.price,
}));
}
/**
* 时间文本(用于自动作废备注,形如 2026-11-01 00:00)
* @param {Date} date 时间
* @return {string} 文本
*/
function formatTimeText(date) {
const value = new Date(date);
if (Number.isNaN(value.getTime())) return '-';
const pad = num => String(num).padStart(2, '0');
return `${value.getFullYear()}-${pad(value.getMonth() + 1)}-${pad(value.getDate())} ${pad(value.getHours())}:${pad(value.getMinutes())}`;
}
/**
* 明细行转平台原样快照:绑定系统商品/组合商品时明细字段会被覆盖或拆分,解绑时按此还原
* @param {Object} line 平台明细
* @param {String} lineNo 原行号
* @return {Object} 快照
*/
function buildPlatformSnapshot(line, lineNo) {
return buildSnapshot(line, lineNo);
}
/** 平台「查不到」的最大回看天数:平台对久远订单返回不可靠,避免把老单误判为消失 */
const MISSING_CHECK_MAX_DAYS = 45;
/** 单次核对的最大订单数(按 LogicOrderId 批量回读,防止一次核对把平台请求打满) */
const MAX_VERIFY_ORDERS = 300;
/** 每次回读携带的订单号个数(平台 Contract=in 支持逗号分隔多值) */
const VERIFY_CHUNK_SIZE = 50;
/**
* 外部打单平台订单拉取服务
*
* 同时服务手动拉取(控制器)与定时拉取(app/schedule/fetchExternalShopOrders.js),
* 保证两条链路的取数与入库规则完全一致:
* 1. 明细先按(店铺 + 平台商品ID + 平台规格ID)命中店铺商品,记录 shop_product_id;
* 2. 店铺商品已绑定系统商品/组合商品时写入 product_id / combo_product_id 并标记已解析;
* 3. 未采集或未绑定时保留平台原样快照,标记为待处理(parse_status=2)。
*/
class ExternalPrintOrderService extends Service {
/**
* 按账号所属平台创建服务实例;cookie/token 变更时写回账号表
* @param {Object} account 账号实例(需 include platform)
* @return {Object} 平台服务实例
*/
createPlatformService(account) {
const platform = account.platform;
if (!platform) throw new Error('打单账号未关联外部打单平台');
if (!hasPrintPlatformService(platform.code)) {
throw new Error(`外部打单平台 ${platform.name}(${platform.code})暂未接入`);
}
return createPrintPlatformService(platform.code, {
platform: platform.get({ plain: true }),
account: account.get({ plain: true }),
saveCookie: async cookie => {
await account.update({ cookie });
},
saveToken: async token => {
await account.update({ token });
},
saveLoginStatus: async status => {
if (Number(account.login_status) !== Number(status)) {
await account.update({ login_status: status });
}
},
});
}
/**
* 拉取并写入某个店铺的订单(含明细)
* @param {Object} shop 店铺实例(type=2 外部打单平台商家)
* @param {Object} account 账号实例(需 include platform)
* @param {Object} options 时间窗
* @param {Date} options.startTime 平台下单时间起
* @param {Date} options.endTime 平台下单时间止
* @return {Promise<Object>} 拉取与写入统计
*/
async syncOrders(shop, account, { startTime, endTime }) {
// 禁用的店铺不再拉单:拉回来的订单无法取号,只会在待审核列表里堆积报错
if (Number(shop.status) === 0) {
throw new Error('店铺已禁用,请先启用后再拉取订单');
}
const platformService = this.createPlatformService(account);
const shopPlain = shop.get ? shop.get({ plain: true }) : shop;
let result;
try {
result = await platformService.listOrders(shopPlain, { startTime, endTime });
} catch (err) {
// 店管家会话到期/被其它端顶掉时各分区接口会统一返回「登录信息过期」,
// 这里重新登录一次再重试,避免定时拉单因为会话过期整天失败
if (!isSessionExpiredError(err)) throw err;
this.ctx.logger.warn('[externalPrintOrder] 拉单时登录态失效,重新登录后重试:%s', err.message);
await platformService.loginByPassword();
result = await platformService.listOrders(shopPlain, { startTime, endTime });
}
const saved = await this.saveOrders(shop, account, result.list);
// 老分区不支持状态/商家过滤时会退化为全量拉取,留痕便于判断该店铺为何拉得多
if (Array.isArray(result.fallbackHosts) && result.fallbackHosts.length) {
this.ctx.logger.warn(
'[externalPrintOrder] 店铺 %s 有 %d 个老分区不支持状态过滤,已退化为按时间窗全量拉取:%s',
shop.id,
result.fallbackHosts.length,
result.fallbackHosts.join('、')
);
}
// 店铺只声明了新系统分区时,该平台的老分区属于迁移前遗留数据,直接跳过
if (Array.isArray(result.skippedLegacy) && result.skippedLegacy.length) {
this.ctx.logger.info(
'[externalPrintOrder] 店铺 %s 跳过 %d 个迁移前的老分区(商家分区声明中无老分区):%s',
shop.id,
result.skippedLegacy.length,
result.skippedLegacy.join('、')
);
}
// 旧系统分区不支持状态过滤,退化查询会带回已发货/已终结的单:这部分直接作废本地未处理副本
const shipped = await this.voidUnavailableOrders(shop, (result.finished || []).map(item => ({
external_order_id: item.external_order_id,
platform_status: item.platform_status || null,
reason_code: 'shipped',
reason: item.reason ? `店管家侧已发货或已终结(${item.reason})` : '店管家侧已发货或已终结',
})));
// 新系统分区只返回「待发货」,结果里没有的本地待审核单需要按单号精确回读后区分
// 「已发货/已终结」与「平台已查不到」,再决定是否作废
const verified = await this.verifyPendingOrders(shop, platformService, result, { startTime, endTime });
return {
startTime,
endTime,
orders: result.total,
skipped: result.skipped || 0,
voided: shipped.count + verified.shipped + verified.missing,
voidedShipped: shipped.count + verified.shipped,
voidedMissing: verified.missing,
created: saved.created,
updated: saved.updated,
items: saved.items,
itemsBound: saved.itemsBound,
itemsUnbound: saved.itemsUnbound,
hosts: result.hosts,
fallbackHosts: result.fallbackHosts || [],
hint: this.buildZeroOrderHint(shopPlain, result, { startTime, endTime }),
};
}
/**
* 一单都没拉到、且平台结果里根本没有本店铺声明的商家时给出排查提示
*
* 典型场景:商家重新授权 / 换绑后 `shops.external_data.FxUserId` 过期,
* 按老 FxUserId 过滤永远是 0 条,看起来就像「这个平台的订单拉不到」。
* @param {Object} shopPlain 店铺纯对象
* @param {Object} result listOrders 结果
* @param {Object} [range] 拉取时间窗
* @param {Date} [range.startTime] 下单时间起
* @param {Date} [range.endTime] 下单时间止
* @return {string} 提示(无需提示时为空字符串)
*/
buildZeroOrderHint(shopPlain, result, { startTime, endTime } = {}) {
if (!result || result.total > 0) return '';
if (result.merchantSeen !== false) return '';
const others = Array.isArray(result.otherMerchants) ? result.otherMerchants : [];
if (!others.length) return '';
const declared = String((shopPlain && shopPlain.external_data && shopPlain.external_data.FxUserId) || '') || '-';
const othersText = others
.map(item => `${item.shop_name || '未命名'}(${item.fx_user_id},${item.count} 单)`)
.join('、');
const areas = Array.from(new Set((result.hosts || []).concat(result.fallbackHosts || []))).join('、') || '-';
const days = startTime && endTime
? Math.max(1, Math.round((new Date(endTime).getTime() - new Date(startTime).getTime()) / 86400000))
: null;
const windowText = days ? `近 ${days} 天` : '本次窗口';
return `${windowText}平台结果里没有出现店铺声明的商家 FxUserId=${declared}(分区:${areas}),` +
`实际出现的是 ${othersText}。可能是该商家近段时间没有待发货订单,或商家重新授权/换绑导致 FxUserId 变化;` +
'请核对店铺「所在区/商家」是否需要刷新';
}
/**
* 核对「本次拉取窗口内本地仍是待审核、但平台待发货结果里没有」的订单
*
* 拉单已按 ErpState=waitsellersend + 商家过滤,结果里没有的本地待审核单只有三种可能:
* 已发货 / 已终结 / 平台已查不到。逐单按 LogicOrderId 精确回读(一次最多带 50 个单号)
* 来区分:
* - 回读到且已发货/已终结 → 作废,备注写清平台依据;
* - 回读到仍是待发货 → 保留(可能是分页/分区抖动);
* - 回读不到 → 按「查不到」作废(可用 AUTO_VOID_MISSING_ORDER=0 关闭)。
*
* 候选严格限定为「本店铺 + 待审核 + 下单时间落在本次窗口内」,且窗口最多回看
* MISSING_CHECK_MAX_DAYS 天;本次没有任何分区命中时不判定,避免平台异常导致整批误作废。
* @param {Object} shop 店铺实例
* @param {Object} platformService 平台服务实例
* @param {Object} result 平台返回(list / hosts / traceId)
* @param {Object} range 本次查询时间窗
* @param {Date} range.startTime 开始时间
* @param {Date} range.endTime 结束时间
* @return {Promise<{shipped: number, missing: number}>} 按原因统计的作废数量
*/
async verifyPendingOrders(shop, platformService, result, { startTime, endTime }) {
const { ctx } = this;
const summary = { shipped: 0, missing: 0 };
if (!Array.isArray(result.hosts) || !result.hosts.length) return summary;
const Op = this.app.Sequelize.Op;
const end = new Date(endTime);
const floor = new Date(end.getTime() - MISSING_CHECK_MAX_DAYS * 24 * 3600 * 1000);
const start = new Date(Math.max(new Date(startTime).getTime(), floor.getTime()));
const known = new Set();
for (const row of result.list || []) {
if (row && row.external_order_id) known.add(String(row.external_order_id));
}
// 退化分区会带回已发货单(已单独作废),这些订单无需再做精确核对
for (const row of result.finished || []) {
if (row && row.external_order_id) known.add(String(row.external_order_id));
}
const candidates = await ctx.model.OrderStatusPending.findAll({
where: {
principal_id: shop.principal_id,
shop_id: shop.id,
place_order_time: { [Op.between]: [ start, end ] },
},
attributes: [ 'id', 'order_no', 'parent_order_no', 'place_order_time', 'source_platform_code', 'extend_props' ],
raw: true,
});
const targets = candidates
.filter(row => row.parent_order_no && !known.has(String(row.parent_order_no)))
.slice(0, MAX_VERIFY_ORDERS);
if (!targets.length) return summary;
const platformRows = await this.fetchRowsForVerify(platformService, result, targets);
const describe = platformService.constructor.describeFinishedOrder;
const items = [];
for (const row of targets) {
const orderId = String(row.parent_order_no);
const platformRow = platformRows.get(orderId);
if (platformRow) {
const detail = typeof describe === 'function' ? describe(platformRow) : { finished: false, reason: '' };
// 仍是待发货:可能只是本次分页/分区抖动,保留不动
if (!detail.finished) continue;
items.push({
external_order_id: orderId,
platform_status: platformRow.ErpState || null,
reason_code: 'shipped',
reason: `店管家侧已发货或已终结(${detail.reason || `ErpState=${platformRow.ErpState || '-'}`})`,
});
summary.shipped += 1;
continue;
}
if (String(process.env.AUTO_VOID_MISSING_ORDER || '1') === '0') continue;
items.push({
external_order_id: orderId,
platform_status: null,
reason_code: 'missing',
reason: `店管家侧已查不到该订单(${formatTimeText(start)} 至 ${formatTimeText(end)} 的待发货结果中没有该单,且按系统编号回读也查不到,可能已删除、合并或转出本店铺)`,
});
summary.missing += 1;
}
if (items.length) await this.voidUnavailableOrders(shop, items);
return summary;
}
/**
* 按系统编号批量回读平台订单行(按平台域名 + 分区逐个命中,命中即停)
* @param {Object} platformService 平台服务实例
* @param {Object} result 平台返回(traceId)
* @param {Array} targets 待核对的本地订单(parent_order_no / source_platform_code)
* @return {Promise<Map<string, Object>>} 系统编号 → 平台订单行
*/
async fetchRowsForVerify(platformService, result, targets) {
const found = new Map();
if (typeof platformService.fetchOrdersByIds !== 'function') return found;
const resolveHost = platformService.constructor && platformService.constructor.resolveOrderHost;
if (typeof resolveHost !== 'function') return found;
const byHost = new Map();
for (const row of targets) {
// 域名必须按「订单实际所在平台」算:1688 分销单在 OMS 里被换算成抖音小店/淘宝(为了选对模板),
// 但订单行仍在 Alibaba 分区(fxali),用换算后的编码回读会查错域名 → 被误判「平台已查不到」而作废
const raw = row.extend_props && typeof row.extend_props === 'object' ? row.extend_props : {};
const originalCode = String(raw.original_platform_code || '').trim();
const host = resolveHost(originalCode || String(row.source_platform_code || ''));
if (!host) continue;
if (!byHost.has(host)) byHost.set(host, []);
byHost.get(host).push(String(row.parent_order_no));
}
for (const [ host, ids ] of byHost) {
let areas = [];
try {
areas = await platformService.listProductAreas(host);
} catch {
areas = [{ dbname: '', name: '' }];
}
if (!areas.length) areas = [{ dbname: '', name: '' }];
for (let start = 0; start < ids.length; start += VERIFY_CHUNK_SIZE) {
const chunk = ids.slice(start, start + VERIFY_CHUNK_SIZE);
const pending = new Set(chunk);
for (const area of areas) {
if (!pending.size) break;
let rows = [];
try {
rows = await platformService.fetchOrdersByIds(host, {
traceId: result.traceId || '',
dbname: area.dbname,
ids: Array.from(pending),
});
} catch (err) {
this.ctx.logger.warn('[externalPrintOrder] 订单核对失败 host=%s dbname=%s:%s', host, area.dbname, err.message);
continue;
}
for (const row of rows) {
const id = String(row.LogicOrderId || '');
if (!id || !pending.has(id)) continue;
found.set(id, row);
pending.delete(id);
}
}
}
}
return found;
}
/**
* 审核/推送前校验:平台侧是否已发货或已终结(只读)
*
* 场景:订单昨天已在店管家发货,OMS 今天才审核 → 不该再推仓库。
* 平台查询失败按「放行」处理(只告警),避免平台抖动把审核全卡住。
* @param {Object} order 订单明细(状态表行,需 shop_id / source_platform_code / extend_props)
* @param {Object} index 订单索引行(order_no / parent_order_no)
* @param {number} principalId 主体ID
* @return {Promise<{applicable: boolean, finished: boolean, status: string, reason: string, row: Object|null}>} 校验结果
*/
async checkPlatformFinished(order, index, principalId) {
const { ctx } = this;
const result = { applicable: false, finished: false, status: '', reason: '', row: null };
if (!order || !order.shop_id) return result;
const shop = await ctx.model.Shop.findByPk(order.shop_id, {
attributes: [ 'id', 'type', 'external_print_account_id' ],
});
if (!shop || Number(shop.type) !== 2 || !shop.external_print_account_id) return result;
const platformCode = String(order.source_platform_code || '').trim();
if (!platformCode) return result;
const account = await ctx.model.ExternalPrintAccount.findByPk(shop.external_print_account_id, {
include: [{ model: ctx.model.ExternalPrintPlatform, as: 'platform' }],
});
if (!account || !account.platform) return result;
const service = this.createPlatformService(account);
const resolvePlatformType = service.constructor && service.constructor.resolvePlatformType;
if (typeof resolvePlatformType !== 'function' || typeof service.fetchPlatformOrder !== 'function') return result;
// 平台类型 / 分区库优先取已同步的快递接口记录(无需额外接口)
const template = await ctx.model.ExternalPrintExpressInterface.findOne({
where: { principal_id: principalId, account_id: account.id, platform_code: platformCode, status: 1 },
attributes: [ 'id', 'platform_type', 'dbname' ],
order: [[ 'id', 'ASC' ]],
});
// 平台类型只用于选「订单域名」:1688 分销单被换算成抖音小店/淘宝后,订单行仍在 Alibaba 分区,
// 必须按原始平台算,否则回读会查错域名 → 查不到订单 → 校验形同失效
const raw = order.extend_props && typeof order.extend_props === 'object' ? order.extend_props : {};
const originalCode = String(raw.original_platform_code || '').trim();
const originalPlatformType = originalCode ? resolvePlatformType(originalCode) : '';
const platformType = originalPlatformType || (template ? template.platform_type : resolvePlatformType(platformCode));
if (!platformType) return result;
result.applicable = true;
const row = await service.fetchPlatformOrder({
platformType,
dbname: template ? template.dbname : '',
logicalOrderId: String((index && (index.parent_order_no || index.order_no)) || order.parent_order_no || order.order_no || ''),
platformOrderId: String((order.extend_props && order.extend_props.platform_order_no) || order.oaid_order_source_code || ''),
placeOrderTime: order.place_order_time || order.pay_time || order.created_at,
});
if (!row) return result;
const describe = service.constructor.describeFinishedOrder;
const detail = typeof describe === 'function' ? describe(row) : { finished: false, reason: '' };
result.row = row;
result.status = String(row.ErpState || '');
result.finished = detail.finished;
result.reason = detail.finished
? `店管家侧已发货或已终结(${detail.reason || `ErpState=${result.status || '-'}`})`
: '';
return result;
}
/**
* 作废「本地仍是待审核、但平台侧不应再处理」的订单(已发货/已终结,或平台已查不到)。
*
* 已审核(待推送/委外中/…)的订单不受影响:那些订单的库存与仓库动作已经发生,交由人工处理。
* **作废备注按每个订单的真实原因写入**(已发货的具体依据 / 平台查不到),便于事后区分。
* @param {Object} shop 店铺实例
* @param {Array<{external_order_id: string, platform_status: string, reason: string, reason_code: string}>} items 待作废项
* @return {Promise<{count: number, orders: Array}>} 作废数量与明细
*/
async voidUnavailableOrders(shop, items) {
const { ctx } = this;
const Op = this.app.Sequelize.Op;
const list = (items || []).filter(item => item && item.external_order_id);
if (!list.length) return { count: 0, orders: [] };
const reasonMap = new Map();
const statusMap = new Map();
for (const item of list) {
const key = String(item.external_order_id);
reasonMap.set(key, item.reason || '平台侧已不可处理');
statusMap.set(key, item.platform_status || null);
}
const indexRows = await ctx.model.OrderIndex.findAll({
where: {
principal_id: shop.principal_id,
parent_order_no: { [Op.in]: Array.from(reasonMap.keys()) },
current_status: ORDER_STATUS.PENDING,
},
attributes: [ 'id', 'order_no', 'parent_order_no' ],
raw: true,
});
if (!indexRows.length) return { count: 0, orders: [] };
// 先刷新订单头里的平台状态,作废后仍能看到平台侧最终状态
for (const row of indexRows) {
await ctx.model.Order.update(
{ platform_status: statusMap.get(String(row.parent_order_no)) || null, synced_at: new Date() },
{ where: { principal_id: shop.principal_id, order_no: row.order_no } }
);
}
// 按原因分组作废:voidOrder 一次只接受一个原因,分组后每单的备注才是准确的
const groups = new Map();
for (const row of indexRows) {
const reason = reasonMap.get(String(row.parent_order_no)) || '平台侧已不可处理';
if (!groups.has(reason)) groups.set(reason, []);
groups.get(reason).push(row);
}
let count = 0;
const voidedOrders = [];
for (const [ reason, rows ] of groups) {
try {
const result = await ctx.service.orderStatus.voidOrder({
ids: rows.map(row => Number(row.id)),
void_reason: `${reason},系统自动作废`,
principalId: shop.principal_id,
});
count += result.count || rows.length;
} catch (err) {
ctx.logger.warn('[externalPrintOrder] 自动作废失败(%s):%s', reason, err.message);
continue;
}
for (const row of rows) {
voidedOrders.push({ id: Number(row.id), order_no: row.order_no, reason, platform_status: statusMap.get(String(row.parent_order_no)) || null });
}
}
if (voidedOrders.length) {
await ctx.service.operationLog.recordMany(
voidedOrders.map(row => ({
principalId: shop.principal_id,
targetType: 'order',
targetId: row.id,
action: 'void',
title: `拉单自动作废:${row.order_no}`,
detail: {
reason: `${row.reason},系统自动作废`,
platform_status: row.platform_status,
shop_id: shop.id,
},
})),
{ source: 'sync' }
);
}
return { count, orders: voidedOrders };
}
/**
* 作废本地仍处于「待审核」、但平台侧已发货/已终结的订单(保留旧方法名,内部走统一实现)
* @param {Object} shop 店铺实例
* @param {Array<{external_order_id: string, platform_status: string, reason: string}>} finished 平台侧已处理的订单
* @return {Promise<number>} 作废数量
*/
async voidFinishedOrders(shop, finished) {
const result = await this.voidUnavailableOrders(shop, (finished || []).map(item => ({
external_order_id: item.external_order_id,
platform_status: item.platform_status || null,
reason_code: 'shipped',
reason: item.reason ? `店管家侧已发货或已终结(${item.reason})` : '店管家侧已发货或已终结',
})));
return result.count;
}
/**
* 写入平台订单与明细(按 order_no 去重,明细按 external_item_id 去重)
* @param {Object} shop 店铺实例
* @param {Object} account 账号实例
* @param {Array} list 平台订单列表
* @return {Promise<Object>} 写入统计
*/
async saveOrders(shop, account, list) {
const { ctx } = this;
const now = new Date();
// 店铺配置了默认发货仓库时,新拉进来的待审核订单直接落到该仓库
const defaultWarehouse = await ctx.service.shopWarehouse.resolveDefault(shop);
let created = 0;
let updated = 0;
let items = 0;
let itemsBound = 0;
let itemsUnbound = 0;
const transaction = await ctx.model.transaction();
try {
for (const item of list) {
const externalOrderId = String(item.external_order_id || '').trim();
if (!externalOrderId) continue;
const orderNo = truncateText(`${account.platform.code}-${externalOrderId}`, 50);
const fields = {
principal_id: shop.principal_id,
shop_id: shop.id,
order_no: orderNo,
order_type: 1,
total_amount: item.total_amount,
pay_amount: item.pay_amount,
receiver: item.receiver,
remark: item.remark || null,
external_print_account_id: account.id,
external_order_id: externalOrderId,
// 统一落系统预设平台编码(PDD / DYXD / SPH…),原始平台标识见 external_data
platform_type: item.platform_code || item.platform_type || null,
platform_status: item.platform_status || null,
external_shop_id: item.external_shop_id || null,
external_shop_name: item.external_shop_name || null,
external_created_at: item.external_created_at,
external_updated_at: item.external_updated_at,
synced_at: now,
external_data: item.raw,
};
let order = await ctx.model.Order.findOne({
where: { principal_id: shop.principal_id, order_no: orderNo },
transaction,
});
if (order) {
await order.update(fields, { transaction });
updated++;
} else {
order = await ctx.model.Order.create(fields, { transaction });
created++;
}
// 已审核(离开待审核)的订单明细在审核时已锁定库存、甚至已下发仓库,
// 重新拉单只刷新平台侧状态,不重算明细(解绑/改绑也不会波及这些订单)
const indexRow = await ctx.model.OrderIndex.findOne({
where: { principal_id: shop.principal_id, parent_order_no: externalOrderId },
attributes: [ 'id', 'current_status' ],
raw: true,
transaction,
});
if (indexRow && indexRow.current_status !== ORDER_STATUS.PENDING) continue;
const existingItems = await ctx.model.OrderItem.findAll({
where: { order_id: order.id },
attributes: [ 'id', 'external_item_id' ],
raw: true,
transaction,
});
const itemIdMap = new Map(existingItems.map(row => [ String(row.external_item_id || ''), row.id ]));
const resolvedLines = [];
for (const [ lineIndex, line ] of (item.items || []).entries()) {
const externalItemId = String(line.external_item_id || '').trim();
const matched = await this.matchShopProduct(shop, line);
const bound = this.resolveBoundProduct(matched);
resolvedLines.push({ line, externalItemId, matched, bound });
const lineFields = {
principal_id: shop.principal_id,
order_id: order.id,
shop_id: shop.id,
shop_product_id: matched ? matched.id : null,
product_id: bound.product_id,
combo_product_id: bound.combo_product_id,
item_type: bound.item_type,
parse_status: bound.parse_status,
parse_msg: bound.parse_msg,
outer_item_id: line.outer_item_id || null,
outer_sku_id: line.outer_sku_id || null,
sku_code: line.sku_code || null,
// 未绑定系统商品时保留平台原样快照
name: line.name || null,
spec: line.spec || null,
image: line.image || null,
quantity: line.quantity,
price: line.price,
total_amount: line.total_amount,
external_item_id: externalItemId || null,
raw: line.raw,
platform_snapshot: buildPlatformSnapshot(line, lineIndex + 1),
};
const existId = externalItemId ? itemIdMap.get(externalItemId) : null;
if (existId) {
await ctx.model.OrderItem.update(lineFields, { where: { id: existId }, transaction });
} else {
await ctx.model.OrderItem.create(lineFields, { transaction });
}
items++;
if (bound.parse_status === 1) itemsBound++;
else itemsUnbound++;
}
// 同步写入「待审核」状态表:订单页(待审核/待推送…)读取的是状态分表,不写这里列表看不到
await this.saveOrderToPending(shop, account, item, resolvedLines, transaction, defaultWarehouse);
}
await transaction.commit();
} catch (err) {
await transaction.rollback();
throw err;
}
return { created, updated, items, itemsBound, itemsUnbound };
}
/**
* 写入「待审核」状态表(order_index + order_status_pending + order_status_items)。
* 订单页的待审核/待推送等视图都基于状态分表,平台订单必须落到这里才可见。
* 已流转到其它状态(待推送/异常/委外中…)的订单不覆盖,避免打乱仓内流程。
* @param {Object} shop 店铺实例
* @param {Object} account 账号实例
* @param {Object} item 平台订单
* @param {Array} resolvedLines 已解析的明细(line / externalItemId / matched / bound)
* @param {Object} transaction 事务
* @param {Object|null} [defaultWarehouse] 店铺默认发货仓库(id / code),未配置为 null
* @return {Promise<void>} 无返回值
*/
async saveOrderToPending(shop, account, item, resolvedLines, transaction, defaultWarehouse = null) {
const { ctx } = this;
const externalOrderId = String(item.external_order_id || '').trim();
const lines = resolvedLines || [];
const receiver = item.receiver || {};
const phone = String(receiver.phone || '').trim();
const itemTotal = lines.reduce((sum, row) => sum + (Number(row.line.quantity) || 0), 0);
const itemAmount = lines.reduce((sum, row) => sum + (Number(row.line.total_amount) || 0), 0);
const fields = {
shop_id: shop.id,
// 订单货主跟随店铺(货主权限按此过滤)
subsidiary_id: shop.subsidiary_id == null ? null : Number(shop.subsidiary_id),
// 外部打单平台订单:平台配置要求回打单平台取号时,推送 WMS 需在根节点下发 need_oms_waybill=1
need_oms_waybill: Number(account.platform && account.platform.fetch_waybill_no) === 1 ? 1 : 0,
// 订单页「店铺」列展示 OMS 店铺名(平台店铺名带手机号,写入 extend_props 备用)
shop_nick: truncateText(shop.name, 200),
product_info: buildProductInfo(lines.map(row => row.line)),
receiver: truncateText(receiver.name, 50),
mobile: truncateText(phone, 50),
tel: truncateText(phone, 50),
province: truncateText(receiver.province, 100),
city: truncateText(receiver.city, 100),
area: truncateText(receiver.area, 100),
town: truncateText(receiver.town, 100),
detail_address: truncateText(receiver.address, 500),
address: truncateText(receiver.full_address || receiver.address, 255),
total_amount: item.total_amount,
pay_amount: item.pay_amount,
item_amount: Number(itemAmount.toFixed(2)),
item_total: Number(itemTotal.toFixed(3)),
item_kind: lines.length,
// 系统预设平台编码/名称(推 WMS 的 sourcePlatformCode/sourcePlatformName 同源)
source_platform_code: truncateText(item.platform_code || item.platform_type, 50),
source_platform_name: truncateText(item.platform_name || item.platform_type, 200),
// 来源订单号用的是平台「系统编号」,平台自己的「订单编号」落在这里随单推给 WMS
oaid_order_source_code: item.platform_order_no ? truncateText(item.platform_order_no, 50) : null,
buyer_message: truncateText(item.remark, 500),
place_order_time: item.external_created_at,
pay_time: item.external_updated_at,
remark: truncateText(item.remark, 255),
order_type: 'JYCK',
extend_props: {
source: 'external_print',
platform: account.platform.code,
// 1688 分销单会按下游渠道换算平台(douyin→抖音小店),原始平台与渠道留痕便于追溯
original_platform_code: item.original_platform_code || null,
distribute_channel: item.distribute_channel || null,
platform_shop_id: item.external_shop_id || null,
platform_shop_name: item.external_shop_name || null,
// 平台单号(店管家「订单编号」)与来源订单号(「系统编号」)分开保存,便于对账
platform_order_no: item.platform_order_no || null,
receiver_masked: !!receiver.masked,
},
};
// 店铺配置了默认发货仓库时带入(已有仓库的订单不覆盖,避免打乱用户手工设置)
const defaultWarehouseFields = defaultWarehouse
? { warehouse_id: defaultWarehouse.id, warehouse_code: defaultWarehouse.code }
: {};
let index = await ctx.model.OrderIndex.findOne({
where: { principal_id: shop.principal_id, parent_order_no: externalOrderId },
transaction,
});
let orderId;
if (index) {
const pending = await ctx.model.OrderStatusPending.findByPk(index.id, { transaction });
// 已流转出待审核(待推送/异常/委外中/配送…)时保持现状
if (!pending) return;
orderId = index.id;
const keepWarehouse = pending.warehouse_id != null && Number(pending.warehouse_id) > 0;
await pending.update({ ...fields, ...(keepWarehouse ? {} : defaultWarehouseFields) }, { transaction });
} else {
const orderNo = truncateText(`${account.platform.code}-${externalOrderId}`, 50);
index = await ctx.model.OrderIndex.create({
order_no: orderNo,
parent_order_no: externalOrderId,
principal_id: shop.principal_id,
subsidiary_id: shop.subsidiary_id == null ? null : Number(shop.subsidiary_id),
current_table: ORDER_STATUS.PENDING,
current_status: ORDER_STATUS.PENDING,
}, { transaction });
orderId = index.id;
await ctx.model.OrderStatusPending.create({
...fields,
...defaultWarehouseFields,
id: orderId,
order_no: orderNo,
parent_order_no: externalOrderId,
principal_id: shop.principal_id,
subsidiary_id: shop.subsidiary_id == null ? null : Number(shop.subsidiary_id),
status: ORDER_STATUS.PENDING,
}, { transaction });
}
// 明细整体替换:平台侧可能调整规格/数量
// 先按平台原样落库(保留原行号/原数量/原单价),再由统一解析器按店铺商品绑定关系展开为最小单位
await ctx.model.OrderStatusItem.destroy({ where: { order_id: orderId }, transaction });
const rows = lines.map(({ line, externalItemId, matched, bound }, idx) => ({
principal_id: shop.principal_id,
order_id: orderId,
shop_id: shop.id,
order_line_no: String(idx + 1),
item_code: truncateText(line.sku_code || line.outer_item_id, 100),
item_name: truncateText(line.name, 255),
plan_qty: line.quantity,
actual_price: line.price,
retail_price: line.price,
ext_code: truncateText(line.outer_item_id, 100),
inventory_type: 'ZP',
source_order_code: truncateText(externalOrderId, 50),
sub_source_order_code: truncateText(externalItemId, 50),
shop_product_id: matched ? matched.id : null,
product_id: bound.product_id,
combo_product_id: bound.combo_product_id,
item_type: bound.item_type,
parse_status: bound.parse_status,
parse_msg: bound.parse_msg,
outer_item_id: line.outer_item_id || null,
outer_sku_id: line.outer_sku_id || null,
sku_code: truncateText(line.sku_code, 100),
spec: truncateText(line.spec, 255),
image: truncateText(line.image, 255),
quantity: line.quantity,
price: line.price,
total_amount: line.total_amount,
raw: line.raw,
platform_snapshot: buildPlatformSnapshot(line, idx + 1),
}));
if (rows.length) await ctx.model.OrderStatusItem.bulkCreate(rows, { transaction });
// 按绑定关系重新展开(组合商品拆成子商品行),并刷新订单头摘要与明细统计
await ctx.service.orderItemResolve.rebuildOrderItems([ orderId ], { transaction });
}
/**
* 按平台商品ID/规格ID命中店铺商品(规格ID为空时按商品ID匹配任意规格)
* @param {Object} shop 店铺实例
* @param {Object} line 平台明细
* @return {Promise<Object|null>} 店铺商品
*/
async matchShopProduct(shop, line) {
const { ctx } = this;
const outerItemId = String(line.outer_item_id || '').trim();
if (!outerItemId) return null;
const where = { shop_id: shop.id, outer_item_id: outerItemId };
const outerSkuId = String(line.outer_sku_id || '').trim();
if (outerSkuId) where.outer_sku_id = outerSkuId;
return ctx.model.ShopProduct.findOne({ where });
}
/**
* 由店铺商品绑定关系推导订单明细的关联结果;未绑定时保持未解析(保留平台快照)
* @param {Object|null} shopProduct 店铺商品
* @return {{product_id: number|null, combo_product_id: number|null, item_type: number, parse_status: number, parse_msg: string|null}} 关联结果
*/
resolveBoundProduct(shopProduct) {
if (!shopProduct) {
return {
product_id: null,
combo_product_id: null,
item_type: 0,
parse_status: 2,
parse_msg: '未采集到该店铺商品,已保留平台原样数据',
};
}
if (Number(shopProduct.bind_type) === 1 && shopProduct.product_id) {
return { product_id: shopProduct.product_id, combo_product_id: null, item_type: 1, parse_status: 1, parse_msg: null };
}
if (Number(shopProduct.bind_type) === 2 && shopProduct.combo_product_id) {
return { product_id: null, combo_product_id: shopProduct.combo_product_id, item_type: 2, parse_status: 1, parse_msg: null };
}
return {
product_id: null,
combo_product_id: null,
item_type: 0,
parse_status: 2,
parse_msg: '店铺商品未绑定系统商品,已保留平台原样数据',
};
}
/**
* 记录店铺最近一次拉单结果(定时任务据此判断是否到期)
* @param {Object} shop 店铺实例
* @param {Date} syncedAt 本次拉单时间
* @param {string} message 结果说明
* @return {Promise<void>} 无返回值
*/
async markShopSynced(shop, syncedAt, message) {
await shop.update({
last_order_sync_at: syncedAt,
last_order_sync_msg: truncateText(message, 255),
});
}
}
module.exports = ExternalPrintOrderService;