oms/backend/app/service/externalPrintOrder.js
liufumingren e6d3f1ba8d fix(external-print): 来源订单号改用店管家系统编号(LogicOrderId)
问题:外部打单平台订单的来源订单号 / 去重键取的是 PlatformOrderId(平台单号),
但平台单号并不唯一(同一平台单可拆成多条逻辑单),唯一标识是店管家的「系统编号」LogicOrderId。
例如 订单编号 261023-105376715090914 的系统编号是 695351624597601813。

- normalizeOrder:external_order_id / order_no 改用 LogicOrderId(缺失时回落平台单号),
  平台单号以 platform_order_no 单独带出
- 订单表 extend_props 增加 platform_order_no,便于按店管家「订单编号」对账
- 订单详情抽屉新增「平台订单号」一行(有值才显示)
- 新增 scripts/migrate-logic-order-id.js(npm run orders:migrate-logic-id):
  把历史订单的来源订单号从平台单号迁移到系统编号,同时改写 orders / order_index /
  各状态表 / order_status_items / 配送单,并补写 extend_props.platform_order_no;默认 dry-run
- 修正 orders.external_order_id、order_index.parent_order_no、orderFields 的字段注释

已执行迁移 20 条(备份见会话 files/backup-before-logic-order-id-migration.json),
迁移后重新拉单 created=0 / updated=14,确认不会产生重复订单。

Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
2026-11-03 04:36:14 +08:00

519 lines
21 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,
}));
}
/**
* 明细行转平台原样快照:绑定系统商品/组合商品时明细字段会被覆盖或拆分,解绑时按此还原
* @param {Object} line 平台明细
* @param {String} lineNo 原行号
* @return {Object} 快照
*/
function buildPlatformSnapshot(line, lineNo) {
return buildSnapshot(line, lineNo);
}
/**
* 外部打单平台订单拉取服务
*
* 同时服务手动拉取(控制器)与定时拉取(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 }) {
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);
// 平台侧已发货/已终结、但本地仍停留在待审核的副本:自动作废,避免脏单积压在待审核
const voided = await this.voidFinishedOrders(shop, result.finished || []);
return {
startTime,
endTime,
orders: result.total,
skipped: result.skipped || 0,
voided,
created: saved.created,
updated: saved.updated,
items: saved.items,
itemsBound: saved.itemsBound,
itemsUnbound: saved.itemsUnbound,
hosts: result.hosts,
};
}
/**
* 作废本地仍处于「待审核」、但平台侧已发货/已终结的订单。
* 已审核(待推送/委外中/…)的订单不受影响:那些订单的库存与仓库动作已经发生,交由人工处理。
* @param {Object} shop 店铺实例
* @param {Array<{external_order_id: string, platform_status: string}>} finished 平台侧已处理的订单
* @return {Promise<number>} 作废数量
*/
async voidFinishedOrders(shop, finished) {
const { ctx } = this;
const Op = this.app.Sequelize.Op;
const list = (finished || []).filter(item => item && item.external_order_id);
if (!list.length) return 0;
const statusMap = new Map(list.map(item => [ String(item.external_order_id), item.platform_status || null ]));
const indexRows = await ctx.model.OrderIndex.findAll({
where: {
principal_id: shop.principal_id,
parent_order_no: { [Op.in]: Array.from(statusMap.keys()) },
current_status: ORDER_STATUS.PENDING,
},
attributes: [ 'id', 'order_no', 'parent_order_no' ],
raw: true,
});
if (!indexRows.length) return 0;
// 先刷新订单头里的平台状态,作废后仍能看到平台侧最终状态
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 } }
);
}
const reason = '平台侧已发货或已终结,系统自动作废';
let result;
try {
result = await ctx.service.orderStatus.voidOrder({
ids: indexRows.map(row => Number(row.id)),
void_reason: reason,
principalId: shop.principal_id,
});
} catch (err) {
this.ctx.logger.warn('[externalPrintOrder] 自动作废平台已发货订单失败:%s', err.message);
return 0;
}
await ctx.service.operationLog.recordMany(
indexRows.map(row => ({
principalId: shop.principal_id,
targetType: 'order',
targetId: Number(row.id),
action: 'void',
title: `平台已发货自动作废:${row.order_no}`,
detail: { reason, platform_status: statusMap.get(String(row.parent_order_no)) || null, shop_id: shop.id },
})),
{ source: 'sync' }
);
return result.count || indexRows.length;
}
/**
* 写入平台订单与明细(按 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();
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,
platform_type: 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);
}
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 事务
* @return {Promise<void>} 无返回值
*/
async saveOrderToPending(shop, account, item, resolvedLines, transaction) {
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,
// 订单页「店铺」列展示 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,
source_platform_code: truncateText(item.platform_type, 50),
source_platform_name: truncateText(item.platform_type, 200),
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,
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,
},
};
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;
await pending.update(fields, { 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,
current_table: ORDER_STATUS.PENDING,
current_status: ORDER_STATUS.PENDING,
}, { transaction });
orderId = index.id;
await ctx.model.OrderStatusPending.create({
...fields,
id: orderId,
order_no: orderNo,
parent_order_no: externalOrderId,
principal_id: shop.principal_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;