oms/backend/app/service/orderItemResolve.js
liufumingren a9cca6aa6f feat(log): 新增操作日志(店铺商品/系统商品/组合商品),并修正明细口径
操作日志:
- 新增 operation_logs 表与 model/service/controller,接口 GET /api/operation-logs
  (按 target_type + target_id 分页查询,主体隔离,按时间倒序)
- 店铺商品:采集进系统、平台已无此商品被移出/下架、绑定/解绑均留痕(含原绑定与受影响订单数)
- 系统商品:新增 / 修改(记录变更字段与前后值)/ 删除
- 组合商品:新增 / 修改(含子商品构成前后值)/ 删除
- 日志为旁路能力:写入失败只告警,不影响业务操作

明细口径修正:
- 已审核订单(待推送及之后)的明细在审核时已锁定,重算时按状态过滤,
  重新拉单与改绑定都不再波及(原先会覆盖老表 order_items 的解析结果)
- 组合商品构成/系统商品资料变更后,重建绑定方的待审核订单明细与商品摘要;
  并修正重建时读不到同事务内未提交构成的问题(loadBindings/loadComboItems 传事务)

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

224 lines
8.8 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
* @param {Object} [transaction] 事务(组合商品刚在同事务内改动时必须传,否则读不到未提交的构成)
* @return {Promise<Map<number, Array>>} comboId → 子商品数组
*/
async loadComboItems(comboIds, transaction) {
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' ]],
transaction,
});
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
* @param {Object} [transaction] 事务
* @return {Promise<Map<number, Object>>} shopProductId → { shopProduct, product, combo, comboItems }
*/
async loadBindings(shopProductIds, transaction) {
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,
transaction,
});
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, transaction })
: [];
const combos = comboIds.length
? await ctx.model.ComboProduct.findAll({ where: { id: { [Op.in]: comboIds } }, raw: true, transaction })
: [];
const comboItems = await this.loadComboItems(comboIds, transaction);
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>} shopProductIds 店铺商品ID
* @param {Object} [options] { transaction }
* @return {Promise<number>} 重建的明细行数
*/
async rebuildOrdersByShopProducts(shopProductIds, options = {}) {
const { ctx } = this;
const ids = [ ...new Set((shopProductIds || []).map(Number).filter(id => id > 0)) ];
if (!ids.length) return 0;
const Op = this.app.Sequelize.Op;
const items = await ctx.model.OrderStatusItem.findAll({
where: { shop_product_id: { [Op.in]: ids } },
attributes: [ 'order_id' ],
group: [ 'order_id' ],
raw: true,
transaction: options.transaction,
});
const orderIds = items.map(row => Number(row.order_id)).filter(id => id > 0);
if (!orderIds.length) return 0;
return this.rebuildOrderItems(orderIds, options);
}
/**
* 按当前绑定关系重建若干订单的明细(折叠为平台行 → 重新展开为最小单位)
*
* 默认只处理「待审核 / 异常」:这两类允许维护明细;
* 待推送及之后的订单明细已随审核锁定库存、甚至已下发仓库,改动会与仓内流程不一致。
* 不含平台溯源信息(手工录入)的订单整单跳过。
* @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), transaction);
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;