'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} comboIds 组合商品ID * @param {Object} [transaction] 事务(组合商品刚在同事务内改动时必须传,否则读不到未提交的构成) * @return {Promise>} 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} shopProductIds 店铺商品ID * @param {Object} [transaction] 事务 * @return {Promise>} 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} shopProductIds 店铺商品ID * @param {Object} [options] { transaction } * @return {Promise} 重建的明细行数 */ 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} orderIds 订单ID * @param {Object} [options] { transaction, statuses } * @return {Promise} 重建后的明细行数合计 */ 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 transaction = options.transaction || await ctx.model.transaction(); const ownedTransaction = !options.transaction; // 必须在事务内查索引行:首次拉单建单时 OrderIndex 与明细在同一事务里刚写入, // 事务外读不到 → 会误判「无需重建」而保留平台原值(表现为已绑定却显示平台商品名) const indexRows = await ctx.model.OrderIndex.findAll({ where: { id: { [Op.in]: ids }, current_status: { [Op.in]: statuses } }, attributes: [ 'id' ], raw: true, transaction, }); const targetIds = indexRows.map(row => Number(row.id)); if (!targetIds.length) { if (ownedTransaction) await transaction.rollback(); return 0; } 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;