'use strict'; const Service = require('egg').Service; const { foldPlatformLines, normalizeSnapshot, expandPlatformLine } = require('../lib/orderItemExpand'); const { createShopProductMatcher } = require('../lib/shopProductMatch'); 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; } /** * 商品同步/补拉后,把「未采集到店铺商品」的订单明细按最新店铺商品重新匹配一次 * * 拉单早于商品入库是新店铺/新平台的常态:明细会停在 shop_product_id=null(未采集), * 之后商品补齐也不会自动变化,订单页就一直显示未绑定、还被「仅已绑定」过滤掉。 * 这里在商品写入后按与拉单相同的口径(店铺 + 平台商品ID + 平台规格ID)补一次匹配, * 并重建命中订单的明细(有绑定关系的直接变成已解析)。 * @param {number} shopId 店铺ID * @param {Object} [options] { transaction } * @return {Promise<{matched: number, rebuilt: number}>} 补上的明细行数与重建后的明细行数 */ async rematchUnboundItems(shopId, options = {}) { const { ctx } = this; const Op = this.app.Sequelize.Op; const shopKey = Number(shopId); if (!shopKey) return { matched: 0, rebuilt: 0 }; // 以库内为准(不用平台快照的中间态),按 id 升序保证「无规格时取第一条」稳定 const products = await ctx.model.ShopProduct.findAll({ where: { shop_id: shopKey }, attributes: [ 'id', 'outer_item_id', 'outer_sku_id' ], order: [[ 'id', 'ASC' ]], raw: true, transaction: options.transaction, }); if (!products.length) return { matched: 0, rebuilt: 0 }; const pick = createShopProductMatcher(products); const items = await ctx.model.OrderStatusItem.findAll({ where: { shop_id: shopKey, shop_product_id: { [Op.is]: null } }, attributes: [ 'id', 'order_id', 'outer_item_id', 'outer_sku_id' ], raw: true, transaction: options.transaction, }); if (!items.length) return { matched: 0, rebuilt: 0 }; // 只补「待审核 / 异常」的订单:其余状态明细已随审核锁定(甚至已下发仓库),不跟着商品数据变化 const indexRows = await ctx.model.OrderIndex.findAll({ where: { id: { [Op.in]: [ ...new Set(items.map(item => Number(item.order_id)).filter(id => id > 0)) ] }, current_status: { [Op.in]: [ ORDER_STATUS.PENDING, ORDER_STATUS.EXCEPTION ] }, }, attributes: [ 'id' ], raw: true, transaction: options.transaction, }); const editableIds = new Set(indexRows.map(row => Number(row.id))); if (!editableIds.size) return { matched: 0, rebuilt: 0 }; const orderIds = new Set(); let matched = 0; for (const item of items) { if (!editableIds.has(Number(item.order_id))) continue; const shopProductId = pick(item); if (!shopProductId) continue; await ctx.model.OrderStatusItem.update( { shop_product_id: shopProductId }, { where: { id: item.id }, transaction: options.transaction } ); orderIds.add(Number(item.order_id)); matched++; } if (!matched) return { matched: 0, rebuilt: 0 }; const rebuilt = await this.rebuildOrderItems(Array.from(orderIds), { transaction: options.transaction }); return { matched, rebuilt }; } /** * 按店铺商品批量重建其订单明细(绑定关系或商品资料变化后调用) * @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;