oms/backend/app/service/externalPrintOrder.js
liufumingren ab630e7c01 feat(external-print): 订单拉取与定时同步,组合商品拆分为最小单位
后端能力:
- 接入店管家订单接口(/NewOrder/List),明细归一化后按店铺商品匹配系统商品/组合商品
- 新增 service/externalPrintOrder:手动与定时拉单共用入库逻辑,同时写入待审核状态分表
- 新增 schedule/fetchExternalShopOrders:按店铺配置的间隔自动拉单(最小 3 分钟,起点重叠 10 分钟)
- 新增 lib/orderItemExpand + service/orderItemResolve:平台行与最小单位行互转;
  绑定组合商品时按「数量 = 平台数量 x 组合内数量、单价取子商品零售价」拆成子商品行,解绑可还原
- 明细新增 platform_snapshot,保留平台原样(编码/名称/规格/图片/原行号/原数量/原单价)
- 店铺商品列表支持 has_unbound_order 筛选,订单列表支持 exclude_unbound(均已同步导出定义)
- 店铺商品只读化:移除新增/编辑/删除动作,仅保留查询与绑定;
  同步商品时平台已不存在的商品自动清理(未绑定且未被订单引用直接删除,已绑定或被引用仅下架)
- 新增 scripts/rebuild-order-items 存量明细重建脚本,新增 orderItemExpand 单测(8 项)

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

424 lines
16 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);
}
/**
* 明细行转列表摘要快照(与订单页 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 result = await platformService.listOrders(shop.get ? shop.get({ plain: true }) : shop, {
startTime,
endTime,
});
const saved = await this.saveOrders(shop, account, result.list);
return {
startTime,
endTime,
orders: result.total,
created: saved.created,
updated: saved.updated,
items: saved.items,
itemsBound: saved.itemsBound,
itemsUnbound: saved.itemsUnbound,
hosts: result.hosts,
};
}
/**
* 写入平台订单与明细(按 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 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,
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;