oms/backend/app/service/orderItemResolve.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

195 lines
7.6 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 { foldPlatformLines, normalizeSnapshot, expandPlatformLine } = require('../lib/orderItemExpand');
const { ORDER_STATUS } = require('../lib/orderStatus');
/**
* 订单明细解析服务
*
* 平台订单明细按「店铺商品 → 系统商品 / 组合商品」的绑定关系解析为最小单位:
* - 未采集到店铺商品 / 店铺商品未绑定系统商品:保留平台原样一行(parse_status=2)
* - 绑定系统商品:一行对一行
* - 绑定组合商品:拆成组合内每个子商品一行(数量 = 平台数量 × 组合内数量,单价取子商品零售价)
*
* 明细行始终在 platform_snapshot 里保留平台原样,因此绑定关系变化时可以折叠回平台行再重新展开,
* 行数变化(1 行 ↔ N 行)不会丢失原始数量与单价。
*/
class OrderItemResolveService extends Service {
/**
* 批量载入组合商品的子商品明细
* @param {Array<number>} comboIds 组合商品ID
* @return {Promise<Map<number, Array>>} comboId → 子商品数组
*/
async loadComboItems(comboIds) {
const { ctx } = this;
const map = new Map();
const ids = [ ...new Set((comboIds || []).map(Number).filter(id => id > 0)) ];
if (!ids.length) return map;
const Op = this.app.Sequelize.Op;
const rows = await ctx.model.ComboProductItem.findAll({
where: { combo_product_id: { [Op.in]: ids } },
include: [{
model: ctx.model.Product,
as: 'product',
attributes: [ 'id', 'item_code', 'item_name', 'sku_property', 'image', 'retail_price' ],
required: false,
}],
order: [[ 'id', 'ASC' ]],
});
for (const row of rows) {
const plain = row.get({ plain: true });
const product = plain.product || {};
const comboId = Number(plain.combo_product_id);
if (!map.has(comboId)) map.set(comboId, []);
map.get(comboId).push({
product_id: Number(plain.product_id),
quantity: Number(plain.quantity) || 1,
item_code: product.item_code || null,
item_name: product.item_name || null,
sku_property: product.sku_property || null,
image: product.image || null,
retail_price: product.retail_price,
});
}
return map;
}
/**
* 批量载入店铺商品的绑定上下文
* @param {Array<number>} shopProductIds 店铺商品ID
* @return {Promise<Map<number, Object>>} shopProductId → { shopProduct, product, combo, comboItems }
*/
async loadBindings(shopProductIds) {
const { ctx } = this;
const map = new Map();
const ids = [ ...new Set((shopProductIds || []).map(Number).filter(id => id > 0)) ];
if (!ids.length) return map;
const Op = this.app.Sequelize.Op;
const shopProducts = await ctx.model.ShopProduct.findAll({
where: { id: { [Op.in]: ids } },
raw: true,
});
if (!shopProducts.length) return map;
const productIds = shopProducts
.filter(row => Number(row.bind_type) === 1 && row.product_id)
.map(row => Number(row.product_id));
const comboIds = shopProducts
.filter(row => Number(row.bind_type) === 2 && row.combo_product_id)
.map(row => Number(row.combo_product_id));
const products = productIds.length
? await ctx.model.Product.findAll({ where: { id: { [Op.in]: productIds } }, raw: true })
: [];
const combos = comboIds.length
? await ctx.model.ComboProduct.findAll({ where: { id: { [Op.in]: comboIds } }, raw: true })
: [];
const comboItems = await this.loadComboItems(comboIds);
const productMap = new Map(products.map(row => [ Number(row.id), row ]));
const comboMap = new Map(combos.map(row => [ Number(row.id), row ]));
for (const shopProduct of shopProducts) {
const bindType = Number(shopProduct.bind_type);
const product = bindType === 1 ? productMap.get(Number(shopProduct.product_id)) : null;
const combo = bindType === 2 ? comboMap.get(Number(shopProduct.combo_product_id)) : null;
map.set(Number(shopProduct.id), {
shopProduct,
product: product || null,
combo: combo || null,
comboItems: combo ? comboItems.get(Number(combo.id)) || [] : [],
});
}
return map;
}
/**
* 按当前绑定关系重建若干订单的明细(折叠为平台行 → 重新展开为最小单位)
*
* 默认只处理「待审核 / 异常」:这两类允许维护明细;
* 待推送及之后的订单明细已随审核锁定库存、甚至已下发仓库,改动会与仓内流程不一致。
* 不含平台溯源信息(手工录入)的订单整单跳过。
* @param {Array<number>} orderIds 订单ID
* @param {Object} [options] { transaction, statuses }
* @return {Promise<number>} 重建后的明细行数合计
*/
async rebuildOrderItems(orderIds, options = {}) {
const { ctx } = this;
const ids = [ ...new Set((orderIds || []).map(Number).filter(id => id > 0)) ];
if (!ids.length) return 0;
const Op = this.app.Sequelize.Op;
const statuses = options.statuses || [ ORDER_STATUS.PENDING, ORDER_STATUS.EXCEPTION ];
const indexRows = await ctx.model.OrderIndex.findAll({
where: { id: { [Op.in]: ids }, current_status: { [Op.in]: statuses } },
attributes: [ 'id' ],
raw: true,
});
const targetIds = indexRows.map(row => Number(row.id));
if (!targetIds.length) return 0;
const transaction = options.transaction || await ctx.model.transaction();
const ownedTransaction = !options.transaction;
let affected = 0;
try {
for (const orderId of targetIds) {
const rows = await ctx.model.OrderStatusItem.findAll({
where: { order_id: orderId },
order: [[ 'order_line_no', 'ASC' ], [ 'id', 'ASC' ]],
raw: true,
transaction,
});
if (!rows.length) continue;
// 只重建「平台行」:手工录入的明细没有平台溯源信息(快照 / 平台商品ID / 店铺商品),
// 一旦按平台口径重排会被抹成未解析并丢掉已选商品,因此整单跳过,保持原样
const isPlatformOrder = rows.every(row => row.platform_snapshot
|| row.shop_product_id != null
|| String(row.outer_item_id || '').trim());
if (!isPlatformOrder) continue;
const lines = foldPlatformLines(rows);
const bindings = await this.loadBindings(lines.map(line => line.shop_product_id));
const payload = [];
for (const line of lines) {
const snapshot = normalizeSnapshot(line);
const binding = line.shop_product_id ? bindings.get(Number(line.shop_product_id)) : null;
const parts = expandPlatformLine({ ...line, platform_snapshot: snapshot }, binding || {});
for (const part of parts) payload.push(part);
}
await ctx.model.OrderStatusItem.destroy({ where: { order_id: orderId }, transaction });
if (payload.length) {
await ctx.model.OrderStatusItem.bulkCreate(
payload.map((row, idx) => ({
...row,
principal_id: rows[0].principal_id,
order_id: orderId,
order_line_no: String(idx + 1),
})),
{ transaction }
);
}
await ctx.service.orderStatus.refreshItemSummary(orderId, rows[0].principal_id, transaction);
affected += payload.length;
}
if (ownedTransaction) await transaction.commit();
} catch (err) {
if (ownedTransaction) await transaction.rollback();
throw err;
}
return affected;
}
}
module.exports = OrderItemResolveService;