'use strict'; const { app, assert } = require('egg-mock/bootstrap'); describe('service/orderItemResolve 订单唯一赠品收敛(真实库 + 回滚)', () => { it('同一赠品的多条明细只落一行、数量 1', async () => { const ctx = app.mockContext({ state: { principalId: 3 } }); const t = await ctx.model.transaction(); try { const principalId = 3; const now = new Date(); const product = await ctx.model.Product.create({ principal_id: principalId, item_code: `TMP-GIFT-${Date.now()}`, item_name: 'TMP gift', retail_price: 0, is_order_unique_gift: 1, }, { transaction: t }); // 店铺商品绑定到该赠品:这样展开才会落到 product_id const shopProduct = await ctx.model.ShopProduct.create({ principal_id: principalId, shop_id: 18, outer_item_id: 'tmp-item', outer_sku_id: 'tmp-sku', title: 'TMP gift shop product', stock: 0, status: 1, bind_type: 1, product_id: product.id, }, { transaction: t }); const order = await ctx.model.Order.create({ principal_id: principalId, order_no: `TMP-${Date.now()}`, order_type: 1, total_amount: 0, pay_amount: 0, receiver: 'TMP', }, { transaction: t }); await ctx.model.OrderIndex.create({ id: order.id, principal_id: principalId, order_no: order.order_no, parent_order_no: order.order_no, current_status: 'pending', current_table: 'pending', created_at: now, updated_at: now, }, { transaction: t }); // 两条平台明细都命中同一赠品(模拟两份组合/多数量) for (const idx of [ 1, 2 ]) { await ctx.model.OrderStatusItem.create({ principal_id: principalId, order_id: order.id, shop_id: 18, order_line_no: String(idx), item_code: shopProduct.outer_item_id, item_name: 'TMP line', plan_qty: 3, quantity: 3, actual_price: 0, shop_product_id: shopProduct.id, product_id: product.id, item_type: 1, parse_status: 1, outer_item_id: 'tmp-item', outer_sku_id: 'tmp-sku', platform_snapshot: { line_no: String(idx), item_code: 'tmp-item', plan_qty: 3, actual_price: 0 }, }, { transaction: t }); } await ctx.service.orderItemResolve.rebuildOrderItems([ order.id ], { transaction: t }); const after = await ctx.model.OrderStatusItem.findAll({ where: { order_id: order.id }, attributes: [ 'product_id', 'quantity', 'plan_qty' ], raw: true, transaction: t, }); console.log('rows after rebuild:', JSON.stringify(after)); assert.strictEqual(after.length, 1, 'two sources of the same gift collapse into one row'); assert.strictEqual(Number(after[0].quantity), 1); assert.strictEqual(Number(after[0].plan_qty), 1); assert.strictEqual(Number(after[0].product_id), Number(product.id)); } finally { await t.rollback(); } }); });