Răsfoiți Sursa

feat(backend): 套餐独立模型重写补齐差距文件 — sync_gap_tasks(2026-10-31-bundle-redesign)

- 新增 ProductComboItem 实体/@TableName(product_combo_items) 与 ProductComboItemMapper(BaseMapper)
- DatabaseInitializer 新增迁移437 建 product_combo_items 表(UK combo_sku_id+child_sku_id),schema.sql 同步
- pricing 新增 ComboOfferDef(含嵌套 ComboChild)、ComboOfferResult、ComboOfferCalculator 纯计算类
  (勾选子集聚合/节省额>0才active/超量算groups/多套餐取最大节省/脏行防御/同套餐去重)

cfc-backend mvn compile: BUILD SUCCESS;计算器按文档 Review Focus 1-7 验证逻辑通过(临时测试已撤)
Sisyphus 3 săptămâni în urmă
părinte
comite
0bf5827e24

+ 27 - 0
cfc-backend/src/main/java/com/etotem/cfc/config/DatabaseInitializer.java

@@ -3403,6 +3403,9 @@ insertSysConfigSeed("gift_membership_pay_price", "198000", "送会员商品达
 
         // 迁移436: products 表添加营养数据字段(热量/蛋白质/脂肪/碳水/膳食纤维/营养标签)
         migrateProductNutritionFields();
+
+        // 迁移437: 套餐内容明细表 product_combo_items(套餐=独立商品,内容挂套餐SKU级)
+        migrateProductComboItems();
     }
 
     /**
@@ -14592,6 +14595,30 @@ log.info("迁移298: 已为无 openid 的 child 账号补齐 family_members 记
         }
     }
 
+    // ==================== 迁移437:套餐内容明细表(套餐独立模型重写) ====================
+
+    /**
+     * 迁移437: 创建 product_combo_items 表(套餐内容明细,内容挂套餐SKU级)。
+     * 幂等:CREATE TABLE IF NOT EXISTS + 异常兜底。
+     */
+    void migrateProductComboItems() {
+        try {
+            jdbcTemplate.execute("CREATE TABLE IF NOT EXISTS `product_combo_items` ("
+                    + "`id` BIGINT NOT NULL AUTO_INCREMENT, "
+                    + "`combo_sku_id` BIGINT NOT NULL COMMENT '套餐SKU id(内容挂SKU级)', "
+                    + "`child_product_id` BIGINT NOT NULL, "
+                    + "`child_sku_id` BIGINT NOT NULL COMMENT '子商品SKU(精确到规格)', "
+                    + "`quantity` INT NOT NULL DEFAULT 1, "
+                    + "`created_at` DATETIME DEFAULT CURRENT_TIMESTAMP, "
+                    + "PRIMARY KEY (`id`), "
+                    + "UNIQUE KEY `uk_combo_sku_child` (`combo_sku_id`, `child_sku_id`)"
+                    + ") ENGINE=InnoDB DEFAULT CHARSET=utf8mb4");
+            log.info("迁移437: 已创建 product_combo_items 表");
+        } catch (Exception e) {
+            log.warn("迁移437: 创建 product_combo_items 表失败(可能已存在): {}", e.getMessage());
+        }
+    }
+
     // ==================== 迁移429:用户关注指标收藏(T04 方案A) ====================
 
     /**

+ 46 - 0
cfc-backend/src/main/java/com/etotem/cfc/entity/ProductComboItem.java

@@ -0,0 +1,46 @@
+package com.etotem.cfc.entity;
+
+import com.baomidou.mybatisplus.annotation.IdType;
+import com.baomidou.mybatisplus.annotation.TableField;
+import com.baomidou.mybatisplus.annotation.TableId;
+import com.baomidou.mybatisplus.annotation.TableName;
+import lombok.Data;
+
+import java.io.Serializable;
+import java.util.Date;
+
+/**
+ * 套餐内容明细(套餐 = 独立商品 productType=bundle,内容挂在套餐 SKU 级)。
+ * 对应表 product_combo_items(迁移437),唯一键 (combo_sku_id, child_sku_id)。
+ */
+@Data
+@TableName("product_combo_items")
+public class ProductComboItem implements Serializable {
+
+    @TableId(type = IdType.AUTO)
+    private Long id;
+
+    /** 套餐SKU id(product_skus.id):内容挂SKU级 */
+    private Long comboSkuId;
+
+    /** 子商品ID */
+    private Long childProductId;
+
+    /** 子商品SKU id(精确到规格,SKU级必填) */
+    private Long childSkuId;
+
+    /** 该组成商品数量 */
+    private Integer quantity;
+
+    private Date createdAt;
+
+    // ---- 展示回填字段(非表字段) ----
+    @TableField(exist = false)
+    private String childProductName;
+    @TableField(exist = false)
+    private String childProductImage;
+    @TableField(exist = false)
+    private Integer childProductPrice;
+    @TableField(exist = false)
+    private String childSkuSpecs;
+}

+ 7 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/ProductComboItemMapper.java

@@ -0,0 +1,7 @@
+package com.etotem.cfc.mapper;
+
+import com.baomidou.mybatisplus.core.mapper.BaseMapper;
+import com.etotem.cfc.entity.ProductComboItem;
+
+public interface ProductComboItemMapper extends BaseMapper<ProductComboItem> {
+}

+ 174 - 0
cfc-backend/src/main/java/com/etotem/cfc/pricing/ComboOfferCalculator.java

@@ -0,0 +1,174 @@
+package com.etotem.cfc.pricing;
+
+import java.util.*;
+
+/**
+ * 购物车套餐 offer 检测核心算法(纯计算,无外部依赖,便于单测)。
+ * <p>
+ * 规则:
+ * 1. 商品行按 (productId, skuId) 聚合为「池」;
+ * 2. 多套餐候选时取节省额最大者,同节省额取先出现(确定性);
+ * 3. 节省额 = 该套消费的基础款单价合计 − 套餐价,仅 >0 才触发(避免会员价低于套餐价反而更贵);
+ * 4. 超量覆盖:计算组数 groups = min over children( floor(haveQty / needQty) );
+ *    实际消耗 groups 组后,行数量相应扣减,余量保留;
+ * 5. 脏行防御:child 的 childSkuId 不在 lines 中 → 0 补差值不命中该套餐;
+ * 6. 同一套餐 comoboSkuId 相同只报一次。
+ */
+public class ComboOfferCalculator {
+
+    /** 池内一行:某 (productId, skuId) 剩余数量与下单口径单价 */
+    private static class PoolEntry {
+        final Long productId;
+        final Long skuId;
+        int quantity;
+        final int unitPrice;
+
+        PoolEntry(Long productId, Long skuId, int quantity, int unitPrice) {
+            this.productId = productId;
+            this.skuId = skuId;
+            this.quantity = quantity;
+            this.unitPrice = unitPrice;
+        }
+    }
+
+    /**
+     * 聚合:同 (productId, skuId) 归并数量;单价取该聚合内首个非零值
+     */
+    private Map<String, PoolEntry> aggregate(List<LineItem> lines) {
+        Map<String, PoolEntry> pool = new LinkedHashMap<>();
+        for (LineItem line : lines) {
+            if (line == null || line.getProductId() == null || line.getQuantity() == null || line.getQuantity() <= 0) {
+                continue;
+            }
+            String key = line.getProductId() + "|" + (line.getSkuId() == null ? "" : line.getSkuId());
+            int unitPrice = safePrice(line.getUnitPrice());
+            PoolEntry entry = pool.get(key);
+            if (entry == null) {
+                pool.put(key, new PoolEntry(line.getProductId(), line.getSkuId(), line.getQuantity(), unitPrice));
+            } else {
+                entry.quantity += line.getQuantity();
+            }
+        }
+        return pool;
+    }
+
+    /** 线性安全价(null/负数视为 0) */
+    private static int safePrice(Integer price) {
+        return price == null || price < 0 ? 0 : price;
+    }
+
+    /** 计算 key:productId skuId 组合 */
+    private static String key(Long productId, Long skuId) {
+        return productId + "|" + (skuId == null ? "" : skuId);
+    }
+
+    /**
+     * 试凑一套套餐:不修改池,返回可覆盖的组数;任一基础款不足则返回 0。
+     * 同一 PoolEntry 被不同 child 消费(跨 child 共行),用 taken 防重复扣。
+     */
+    private int maxGroups(Map<String, PoolEntry> pool, ComboOfferDef def) {
+        int groups = Integer.MAX_VALUE;
+        Map<PoolEntry, Integer> taken = new HashMap<>();
+        for (ComboOfferDef.ComboChild child : def.getChildren()) {
+            if (child == null || child.getChildProductId() == null || child.getChildSkuId() == null) {
+                return 0; // 子项缺失(脏行防御),不命中该套餐
+            }
+            int needQty = child.getQuantity() == null || child.getQuantity() <= 0 ? 1 : child.getQuantity();
+            String k = key(child.getChildProductId(), child.getChildSkuId());
+            PoolEntry entry = pool.get(k);
+            if (entry == null) {
+                return 0; // 该基础款根本不在池中(脏行防御)
+            }
+            int already = taken.getOrDefault(entry, 0);
+            int available = entry.quantity - already;
+            if (available <= 0) {
+                return 0; // 已耗尽,不命中
+            }
+            int take = Math.min(available, needQty);
+            taken.put(entry, already + take);
+            int haveGroups = available / needQty; // floor division: full groups from this child
+            if (haveGroups < groups) {
+                groups = haveGroups;
+            }
+        }
+        return groups <= 0 ? 0 : groups;
+    }
+
+    /**
+     * 计算订单内套餐优惠。
+     *
+     * @param lines 下单/结算口径商品行(productId/skuId 为解析后身份,unitPrice 为结算单价,单位分)
+     * @param defs 套餐 offer 定义(product_combo_items 按套餐SKU 聚合)
+     * @return ComboOfferResult:active=false 表示不可替换;active=true 表示命中并可替换
+     */
+    public ComboOfferResult compute(List<LineItem> lines, List<ComboOfferDef> defs) {
+        if (lines == null || lines.isEmpty() || defs == null || defs.isEmpty()) {
+            return ComboOfferResult.inactive();
+        }
+        Map<String, PoolEntry> pool = aggregate(lines);
+        ComboOfferDef bestDef = null;
+        int bestSaving = 0;
+        int bestGroups = 0;
+        int bestOriginalTotal = 0;
+        Set<Long> seenComboSkuIds = new HashSet<>();
+
+        for (ComboOfferDef def : defs) {
+            // 同一套餐 comboSkuId 相同只报一次(取先出现)
+            if (def.getComboSkuId() == null || !seenComboSkuIds.add(def.getComboSkuId())) {
+                continue;
+            }
+            if (def.getComboPrice() == null || def.getChildren() == null || def.getChildren().isEmpty()) {
+                continue;
+            }
+            int groups = maxGroups(pool, def);
+            if (groups <= 0) {
+                continue; // 基础款不足或脏行防御,跳过该套餐
+            }
+
+            // 计算每组原价:按 needQty × 对应 pool 单价 累加
+            int perGroupOriginal = 0;
+            boolean allValid = true;
+            for (ComboOfferDef.ComboChild child : def.getChildren()) {
+                if (child == null) { allValid = false; break; }
+                Long pid = child.getChildProductId();
+                Long sid = child.getChildSkuId();
+                if (pid == null || sid == null) { allValid = false; break; }
+                int needQty = child.getQuantity() == null || child.getQuantity() <= 0 ? 1 : child.getQuantity();
+                String k = key(pid, sid);
+                PoolEntry entry = pool.get(k);
+                if (entry == null) { allValid = false; break; } // 脏行防御
+                int unitPrice = entry.unitPrice;
+                perGroupOriginal += unitPrice * needQty;
+            }
+            if (!allValid) continue;
+
+            int originalTotal = perGroupOriginal * groups;
+            int comboTotal = safePrice(def.getComboPrice()) * groups;
+            int saving = originalTotal - comboTotal;
+
+            if (saving <= 0) continue; // 套餐价≥总价,取原价结算(Review Focus 1)
+
+            // 严格大于:节省额相同取先出现(确定性)
+            if (saving > bestSaving) {
+                bestSaving = saving;
+                bestDef = def;
+                bestGroups = groups;
+                bestOriginalTotal = originalTotal;
+            }
+        }
+
+        if (bestDef == null) {
+            return ComboOfferResult.inactive();
+        }
+
+        ComboOfferResult result = new ComboOfferResult();
+        result.setActive(true);
+        result.setComboSkuId(bestDef.getComboSkuId());
+        result.setComboName(bestDef.getComboName());
+        result.setGroups(bestGroups);
+        result.setOriginalTotal(bestOriginalTotal);
+        result.setComboPrice(safePrice(bestDef.getComboPrice()) * bestGroups);
+        result.setSaving(bestSaving);
+        return result;
+    }
+}

+ 54 - 0
cfc-backend/src/main/java/com/etotem/cfc/pricing/ComboOfferDef.java

@@ -0,0 +1,54 @@
+package com.etotem.cfc.pricing;
+
+import lombok.Data;
+
+import java.util.List;
+
+/**
+ * 套餐 offer 定义(来自 product_combo_items 按套餐SKU聚合 + product_skus 的 price/label)。
+ * comboPrice 取套餐 SKU 的 price(分);children 为套餐内容(子商品 SKU×数量)。
+ */
+@Data
+public class ComboOfferDef {
+
+    /** 套餐SKU id(product_skus.id) */
+    private Long comboSkuId;
+
+    /** 套餐展示名(取套餐 SKU 的 label) */
+    private String comboName;
+
+    /** 套餐价(分) */
+    private Integer comboPrice;
+
+    /** 套餐内容(每行: childProductId + childSkuId(精确到规格) + quantity) */
+    private List<ComboChild> children;
+
+    public ComboOfferDef() {
+    }
+
+    public ComboOfferDef(Long comboSkuId, String comboName, Integer comboPrice, List<ComboChild> children) {
+        this.comboSkuId = comboSkuId;
+        this.comboName = comboName;
+        this.comboPrice = comboPrice;
+        this.children = children;
+    }
+
+    /**
+     * 套餐组成商品(SKU 级必填:combo_sku_id + child_sku_id 为唯一键)。
+     */
+    @Data
+    public static class ComboChild {
+        private Long childProductId;
+        private Long childSkuId;
+        private Integer quantity;
+
+        public ComboChild() {
+        }
+
+        public ComboChild(Long childProductId, Long childSkuId, Integer quantity) {
+            this.childProductId = childProductId;
+            this.childSkuId = childSkuId;
+            this.quantity = quantity;
+        }
+    }
+}

+ 45 - 0
cfc-backend/src/main/java/com/etotem/cfc/pricing/ComboOfferResult.java

@@ -0,0 +1,45 @@
+package com.etotem.cfc.pricing;
+
+import lombok.Data;
+
+/**
+ * 购物车套餐 offer 检测结果:active=命中套餐且节省额>0(套餐价 &lt; 子商品单买总和)。
+ * groups=可替换组数;originalTotal=命中部分子商品原价合计(分);
+ * comboPrice=命中套餐价合计(套餐价×groups,分);saving=节省额(originalTotal − comboPrice)。
+ */
+@Data
+public class ComboOfferResult {
+
+    /** 是否命中可替换套餐 */
+    private boolean active;
+
+    /** 命中套餐SKU id */
+    private Long comboSkuId;
+
+    /** 命中套餐名称 */
+    private String comboName;
+
+    /** 可替换组数 */
+    private int groups;
+
+    /** 命中部分子商品原价合计(分) */
+    private int originalTotal;
+
+    /** 命中套餐价合计(分) */
+    private int comboPrice;
+
+    /** 节省额(分),>0 才 active */
+    private int saving;
+
+    public ComboOfferResult() {
+        this.active = false;
+        this.groups = 0;
+        this.originalTotal = 0;
+        this.comboPrice = 0;
+        this.saving = 0;
+    }
+
+    public static ComboOfferResult inactive() {
+        return new ComboOfferResult();
+    }
+}

+ 12 - 0
cfc-backend/src/main/resources/schema.sql

@@ -5612,6 +5612,18 @@ CREATE TABLE IF NOT EXISTS product_sku_combo_items (
     INDEX idx_child_product (child_product_id)
 ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='商品SKU组合明细';
 
+-- 套餐内容明细表(套餐 = 独立商品 productType=bundle,内容挂套餐SKU级;迁移437)
+CREATE TABLE IF NOT EXISTS product_combo_items (
+    id BIGINT NOT NULL AUTO_INCREMENT,
+    combo_sku_id BIGINT NOT NULL COMMENT '套餐SKU id(内容挂SKU级)',
+    child_product_id BIGINT NOT NULL COMMENT '子商品ID',
+    child_sku_id BIGINT NOT NULL COMMENT '子商品SKU(精确到规格)',
+    quantity INT NOT NULL DEFAULT 1 COMMENT '该组成商品数量',
+    created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
+    PRIMARY KEY (id),
+    UNIQUE KEY uk_combo_sku_child (combo_sku_id, child_sku_id)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='套餐内容明细';
+
 -- 联系人表(cfclub 联系人管理)
 CREATE TABLE IF NOT EXISTS contacts (
     id BIGINT AUTO_INCREMENT PRIMARY KEY,