|
|
@@ -0,0 +1,820 @@
|
|
|
+package com.etotem.cfc.service;
|
|
|
+
|
|
|
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
|
|
+import com.etotem.cfc.dto.RecommendationEngineContext;
|
|
|
+import com.etotem.cfc.dto.RecommendedProduct;
|
|
|
+import com.etotem.cfc.entity.Product;
|
|
|
+import com.etotem.cfc.entity.ProductDimensionMapping;
|
|
|
+import com.etotem.cfc.entity.ProductOrder;
|
|
|
+import com.etotem.cfc.entity.RecommendationRule;
|
|
|
+import com.etotem.cfc.mapper.ProductDimensionMappingMapper;
|
|
|
+import com.etotem.cfc.mapper.ProductMapper;
|
|
|
+import com.etotem.cfc.mapper.ProductOrderMapper;
|
|
|
+import lombok.extern.slf4j.Slf4j;
|
|
|
+import org.springframework.stereotype.Service;
|
|
|
+
|
|
|
+import javax.annotation.Resource;
|
|
|
+import java.util.ArrayList;
|
|
|
+import java.util.Arrays;
|
|
|
+import java.util.Calendar;
|
|
|
+import java.util.Collections;
|
|
|
+import java.util.Comparator;
|
|
|
+import java.util.Date;
|
|
|
+import java.util.HashMap;
|
|
|
+import java.util.HashSet;
|
|
|
+import java.util.LinkedHashSet;
|
|
|
+import java.util.List;
|
|
|
+import java.util.Map;
|
|
|
+import java.util.Set;
|
|
|
+import java.util.stream.Collectors;
|
|
|
+
|
|
|
+/**
|
|
|
+ * 商品推荐规则引擎。
|
|
|
+ *
|
|
|
+ * <p>实现设计文档 docs/superpowers/specs/2026-09-17-product-recommendation-rule-engine-design.md 第 4 节
|
|
|
+ * 中的统一计算逻辑:按配置表 recommendation_rules 与 priority 降序依次应用 5 种业务规则
|
|
|
+ *(已购不推 / 定时复购 / 购买A推B / 购买A不推B / 系列重点推),输出 {@link RecommendedProduct} 列表。
|
|
|
+ *
|
|
|
+ * <p>设计原则:
|
|
|
+ * <ul>
|
|
|
+ * <li>统一入口:推荐结果的计算只在此类完成,Controller/Service 不应重复写规则逻辑。</li>
|
|
|
+ * <li>降级兼容:规则表为空、规则加载失败或某条规则异常时,均不抛出异常,退化为基础候选。</li>
|
|
|
+ * <li>剔除优先:规则 1/4(排除类)在规则 2/3/5(注入类)之前应用,同优先级下按文档 4.1~4.5
|
|
|
+ * 顺序处理,更高优先级规则更先控制结果。</li>
|
|
|
+ * </ul>
|
|
|
+ */
|
|
|
+@Slf4j
|
|
|
+@Service
|
|
|
+public class RecommendationRuleEngine {
|
|
|
+
|
|
|
+ /** 场景代码:维度页 */
|
|
|
+ public static final String SCENE_DIMENSION_PAGE = "dimension_page";
|
|
|
+
|
|
|
+ /** 场景代码:商城首页 */
|
|
|
+ public static final String SCENE_MALL_HOME = "mall_home";
|
|
|
+
|
|
|
+ /** 场景代码:商品详情页(规则驱动) */
|
|
|
+ public static final String SCENE_PRODUCT_DETAIL = "product_detail";
|
|
|
+
|
|
|
+ /** 场景代码:下单成功页(规则驱动) */
|
|
|
+ public static final String SCENE_AFTER_ORDER = "after_order";
|
|
|
+
|
|
|
+ /** 场景代码:报告关联(弱维度商品) */
|
|
|
+ public static final String SCENE_REPORT_RELATED = "report_related";
|
|
|
+
|
|
|
+ /** 全局默认已购排除回溯窗口(天),90 天 */
|
|
|
+ public static final int DEFAULT_PURCHASED_EXCLUDE_DAYS = 90;
|
|
|
+
|
|
|
+ /** 默认复购延迟天数(规则 2),30 天 */
|
|
|
+ public static final int DEFAULT_DELAY_DAYS = 30;
|
|
|
+
|
|
|
+ /** 默认返回上限 */
|
|
|
+ public static final int DEFAULT_LIMIT = 6;
|
|
|
+
|
|
|
+ /** 规则 5(系列重点推)对目标商品的优先级加成 */
|
|
|
+ public static final int SERIES_PRIORITY_BOOST = 10;
|
|
|
+
|
|
|
+ /** 基础候选池商品的默认匹配分 */
|
|
|
+ private static final double BASE_MATCH_SCORE = 0.5;
|
|
|
+
|
|
|
+ /** 规则注入商品的默认匹配分 */
|
|
|
+ private static final double RULE_MATCH_SCORE = 0.8;
|
|
|
+
|
|
|
+ /** 已支付订单状态,与商城下单校验口径一致 */
|
|
|
+ private static final List<String> PAID_STATUSES = Collections.unmodifiableList(
|
|
|
+ Arrays.asList("paid", "pending_receipt", "shipped", "completed"));
|
|
|
+
|
|
|
+ /** 规则同优先级下的处理顺序:剔除类规则先于注入类规则(文档 4.1~4.5) */
|
|
|
+ private static final Comparator<RecommendationRule> RULE_PRIORITY_COMPARATOR = (a, b) -> {
|
|
|
+ int cmp = Integer.compare(priorityOf(b), priorityOf(a)); // priority DESC
|
|
|
+ if (cmp != 0) {
|
|
|
+ return cmp;
|
|
|
+ }
|
|
|
+ int orderA = ruleLoopOrder(a.getRuleType());
|
|
|
+ int orderB = ruleLoopOrder(b.getRuleType());
|
|
|
+ if (orderA != orderB) {
|
|
|
+ return Integer.compare(orderA, orderB);
|
|
|
+ }
|
|
|
+ return Long.compare(ruleIdOf(a), ruleIdOf(b));
|
|
|
+ };
|
|
|
+
|
|
|
+ @Resource
|
|
|
+ private RecommendationRuleService recommendationRuleService;
|
|
|
+
|
|
|
+ @Resource
|
|
|
+ private ProductMapper productMapper;
|
|
|
+
|
|
|
+ @Resource
|
|
|
+ private ProductDimensionMappingMapper dimensionMappingMapper;
|
|
|
+
|
|
|
+ @Resource
|
|
|
+ private ProductOrderMapper orderMapper;
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 计算推荐(引擎核心入口)。
|
|
|
+ *
|
|
|
+ * @param ctx 推荐上下文
|
|
|
+ * @param limit 若覆盖默认 limit,可传;否则用 ctx.limit
|
|
|
+ * @return 推荐列表(已按 priority DESC / matchScore DESC 排序并截断)
|
|
|
+ */
|
|
|
+ public List<RecommendedProduct> recommend(RecommendationEngineContext ctx, Integer limit) {
|
|
|
+ if (ctx == null) {
|
|
|
+ log.warn("推荐引擎上下文为空,返回空结果");
|
|
|
+ return Collections.emptyList();
|
|
|
+ }
|
|
|
+
|
|
|
+ int finalLimit = limit != null && limit > 0 ? limit
|
|
|
+ : (ctx.getLimit() != null && ctx.getLimit() > 0 ? ctx.getLimit() : DEFAULT_LIMIT);
|
|
|
+ String scene = ctx.getScene() == null || ctx.getScene().trim().isEmpty()
|
|
|
+ ? SCENE_MALL_HOME : ctx.getScene().trim();
|
|
|
+
|
|
|
+ // 1. 加载规则:enabled=1 且 scene_codes 命中指定场景,按 priority DESC 排序(文档 4.2 步骤1)
|
|
|
+ List<RecommendationRule> rules = loadRules(scene);
|
|
|
+
|
|
|
+ // 2. 查购买记录:family/individual 两个视角(文档 4.2 步骤2)
|
|
|
+ PurchaseView purchases = loadPurchases(ctx);
|
|
|
+ Map<Long, Date> globalPurchases = globalPurchasesView(ctx, purchases);
|
|
|
+
|
|
|
+ // 3. 构建场景基础候选(进入规则前已剔除默认窗口内已购商品 + 用户排除商品,文档 4.4)
|
|
|
+ List<RecommendedProduct> pool = buildBaseCandidates(ctx, scene, globalPurchases);
|
|
|
+
|
|
|
+ // 4. 按 priority 从高到低应用规则(文档 4.2 步骤4)
|
|
|
+ applyRules(rules, purchases, pool);
|
|
|
+
|
|
|
+ // 5. 结果排序(priority DESC, matchScore DESC)并截断 limit(文档 4.2 步骤5~6)
|
|
|
+ return sortAndTruncate(pool, finalLimit);
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 不传 limit 的便捷入口,使用 ctx.limit。
|
|
|
+ */
|
|
|
+ public List<RecommendedProduct> recommend(RecommendationEngineContext ctx) {
|
|
|
+ return recommend(ctx, null);
|
|
|
+ }
|
|
|
+
|
|
|
+ // -----------------------------------------------------------------------
|
|
|
+ // 步骤1:加载规则
|
|
|
+ // -----------------------------------------------------------------------
|
|
|
+
|
|
|
+ private List<RecommendationRule> loadRules(String scene) {
|
|
|
+ try {
|
|
|
+ List<RecommendationRule> all = recommendationRuleService.list(
|
|
|
+ new LambdaQueryWrapper<RecommendationRule>().eq(RecommendationRule::getEnabled, 1));
|
|
|
+ if (all == null || all.isEmpty()) {
|
|
|
+ log.info("推荐规则表为空,使用基础候选(降级,文档 7.1)");
|
|
|
+ return Collections.emptyList();
|
|
|
+ }
|
|
|
+ return all.stream()
|
|
|
+ .filter(r -> matchesScene(r, scene))
|
|
|
+ .sorted(RULE_PRIORITY_COMPARATOR)
|
|
|
+ .collect(Collectors.toList());
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.warn("加载推荐规则失败,降级为基础候选:{}", e.getMessage());
|
|
|
+ return Collections.emptyList();
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 场景匹配(文档 7.4):
|
|
|
+ * <ul>
|
|
|
+ * <li>scene_codes 为 null / 空字符串 / 空数组,视为“所有场景生效”;</li>
|
|
|
+ * <li>优先精确匹配 sceneCode;</li>
|
|
|
+ * <li>否则再尝试前缀匹配(如 sceneCode 为 dimension_page,scene_codes 包含 dimension 也视为命中);</li>
|
|
|
+ * </ul>
|
|
|
+ */
|
|
|
+ private boolean matchesScene(RecommendationRule rule, String scene) {
|
|
|
+ String sceneCodes = rule.getSceneCodes();
|
|
|
+ if (sceneCodes == null) {
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+ String trimmed = sceneCodes.trim();
|
|
|
+ if (trimmed.isEmpty() || "\"\"".equals(trimmed) || "[]".equals(trimmed)) {
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+ if (scene == null || scene.isEmpty()) {
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+ for (String code : parseStringArray(trimmed)) {
|
|
|
+ if (code.isEmpty()) {
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+ if (code.equals(scene)) {
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+ // 前缀匹配兜底(文档 7.4)
|
|
|
+ if (scene.startsWith(code)) {
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+
|
|
|
+ // -----------------------------------------------------------------------
|
|
|
+ // 步骤2:查购买记录
|
|
|
+ // -----------------------------------------------------------------------
|
|
|
+
|
|
|
+ private static class PurchaseView {
|
|
|
+ final Map<Long, Date> family = new HashMap<>();
|
|
|
+ final Map<Long, Date> individual = new HashMap<>();
|
|
|
+ }
|
|
|
+
|
|
|
+ private PurchaseView loadPurchases(RecommendationEngineContext ctx) {
|
|
|
+ PurchaseView view = new PurchaseView();
|
|
|
+
|
|
|
+ if (ctx.getFamilyId() != null) {
|
|
|
+ List<ProductOrder> orders = selectOrders(new LambdaQueryWrapper<ProductOrder>()
|
|
|
+ .eq(ProductOrder::getFamilyId, ctx.getFamilyId())
|
|
|
+ .in(ProductOrder::getStatus, PAID_STATUSES));
|
|
|
+ collect(view.family, orders);
|
|
|
+ }
|
|
|
+
|
|
|
+ // 个人购买:优先以登录用户 buyerId,为空时用成员ID(文档 4.2:scope=individual 查 buyerId(userId) 订单)
|
|
|
+ Long individualId = ctx.getUserId() != null ? ctx.getUserId() : ctx.getMemberId();
|
|
|
+ if (individualId != null) {
|
|
|
+ List<ProductOrder> orders = selectOrders(new LambdaQueryWrapper<ProductOrder>()
|
|
|
+ .eq(ProductOrder::getBuyerId, individualId)
|
|
|
+ .in(ProductOrder::getStatus, PAID_STATUSES));
|
|
|
+ collect(view.individual, orders);
|
|
|
+ }
|
|
|
+
|
|
|
+ return view;
|
|
|
+ }
|
|
|
+
|
|
|
+ private List<ProductOrder> selectOrders(LambdaQueryWrapper<ProductOrder> qw) {
|
|
|
+ try {
|
|
|
+ List<ProductOrder> orders = orderMapper.selectList(qw);
|
|
|
+ return orders == null ? Collections.emptyList() : orders;
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.warn("查询已购订单失败:{}", e.getMessage());
|
|
|
+ return Collections.emptyList();
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ private void collect(Map<Long, Date> into, List<ProductOrder> orders) {
|
|
|
+ for (ProductOrder o : orders) {
|
|
|
+ if (o.getProductId() == null) {
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+ Date at = o.getPaidAt() != null ? o.getPaidAt() : o.getCreatedAt();
|
|
|
+ if (at == null) {
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+ Date prev = into.get(o.getProductId());
|
|
|
+ if (prev == null || at.after(prev)) {
|
|
|
+ into.put(o.getProductId(), at);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 全局已购视图(文档 4.2 步骤2 / 4.4 兜底):
|
|
|
+ * 按上下文 scope 取主视图(family 查家庭订单,individual 查个人订单),主视图为空时回退到另一个。
|
|
|
+ */
|
|
|
+ private Map<Long, Date> globalPurchasesView(RecommendationEngineContext ctx, PurchaseView purchases) {
|
|
|
+ boolean individual = ctx.getScope() != null && "individual".equalsIgnoreCase(ctx.getScope().trim());
|
|
|
+ Map<Long, Date> primary = individual ? purchases.individual : purchases.family;
|
|
|
+ Map<Long, Date> fallback = individual ? purchases.family : purchases.individual;
|
|
|
+ return !primary.isEmpty() ? primary : fallback;
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 指定规则作用域的购买视图(文档 4.2 步骤2):rule.scope 为 individual 时取个人订单,
|
|
|
+ * 否则(含 family/非法/空)取家庭订单并回退。
|
|
|
+ */
|
|
|
+ private Map<Long, Date> purchasesForRule(RecommendationRule rule, PurchaseView purchases) {
|
|
|
+ boolean individual = rule.getScope() != null && "individual".equalsIgnoreCase(rule.getScope().trim());
|
|
|
+ Map<Long, Date> primary = individual ? purchases.individual : purchases.family;
|
|
|
+ Map<Long, Date> fallback = individual ? purchases.family : purchases.individual;
|
|
|
+ return !primary.isEmpty() ? primary : fallback;
|
|
|
+ }
|
|
|
+
|
|
|
+ // -----------------------------------------------------------------------
|
|
|
+ // 时间窗口工具
|
|
|
+ // -----------------------------------------------------------------------
|
|
|
+
|
|
|
+ /**
|
|
|
+ * days 回溯的截止时间点。days=0 表示“只计算今日购买”(文档 7.5);
|
|
|
+ * days<0 视为异常,取绝对值并已在日志提示。
|
|
|
+ */
|
|
|
+ private Date daysAgo(int days) {
|
|
|
+ Calendar cal = Calendar.getInstance();
|
|
|
+ if (days == 0) {
|
|
|
+ cal.set(Calendar.HOUR_OF_DAY, 0);
|
|
|
+ cal.set(Calendar.MINUTE, 0);
|
|
|
+ cal.set(Calendar.SECOND, 0);
|
|
|
+ cal.set(Calendar.MILLISECOND, 0);
|
|
|
+ } else if (days < 0) {
|
|
|
+ log.warn("规则回溯天数为负数,取绝对值处理:{}", days);
|
|
|
+ cal.add(Calendar.DAY_OF_YEAR, -Math.abs(days));
|
|
|
+ } else {
|
|
|
+ cal.add(Calendar.DAY_OF_YEAR, -days);
|
|
|
+ }
|
|
|
+ return cal.getTime();
|
|
|
+ }
|
|
|
+
|
|
|
+ /** 指定商品是否在回溯窗口内购买过(文档 4.4 time_window_days) */
|
|
|
+ private boolean purchasedWithin(Map<Long, Date> purchases, Long productId, int days) {
|
|
|
+ if (productId == null) {
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+ Date paidAt = purchases.get(productId);
|
|
|
+ return paidAt != null && !paidAt.before(daysAgo(days));
|
|
|
+ }
|
|
|
+
|
|
|
+ /** 指定商品的购买记录是否早于等于回溯窗口结束(即购买距今至少 days 天) */
|
|
|
+ private boolean purchasedAtLeastDaysAgo(Map<Long, Date> purchases, Long productId, int days) {
|
|
|
+ if (productId == null) {
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+ Date paidAt = purchases.get(productId);
|
|
|
+ return paidAt != null && !paidAt.after(daysAgo(days));
|
|
|
+ }
|
|
|
+
|
|
|
+ /** 回溯窗口内购买过的商品ID集合(文档 4.4 兜底) */
|
|
|
+ private Set<Long> productIdsWithin(Map<Long, Date> purchases, int days) {
|
|
|
+ Set<Long> ids = new HashSet<>();
|
|
|
+ Date cutoff = daysAgo(days);
|
|
|
+ for (Map.Entry<Long, Date> e : purchases.entrySet()) {
|
|
|
+ if (e.getValue() != null && !e.getValue().before(cutoff)) {
|
|
|
+ ids.add(e.getKey());
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return ids;
|
|
|
+ }
|
|
|
+
|
|
|
+ // -----------------------------------------------------------------------
|
|
|
+ // 步骤3:构建场景基础候选
|
|
|
+ // -----------------------------------------------------------------------
|
|
|
+
|
|
|
+ private List<RecommendedProduct> buildBaseCandidates(RecommendationEngineContext ctx, String scene,
|
|
|
+ Map<Long, Date> globalPurchases) {
|
|
|
+ // 全局兜底:剔除默认窗口内已购商品(文档 4.4)
|
|
|
+ Set<Long> excluded = productIdsWithin(globalPurchases, DEFAULT_PURCHASED_EXCLUDE_DAYS);
|
|
|
+ if (ctx.getExcludeProductIds() != null) {
|
|
|
+ excluded.addAll(ctx.getExcludeProductIds());
|
|
|
+ }
|
|
|
+
|
|
|
+ switch (scene) {
|
|
|
+ case SCENE_DIMENSION_PAGE:
|
|
|
+ return buildDimensionCandidates(ctx.getDimensionCode(), excluded);
|
|
|
+ case SCENE_REPORT_RELATED:
|
|
|
+ return buildReportRelatedCandidates(ctx.getAnalysis(), excluded);
|
|
|
+ case SCENE_MALL_HOME:
|
|
|
+ return buildMallHomeCandidates(excluded);
|
|
|
+ case SCENE_PRODUCT_DETAIL:
|
|
|
+ case SCENE_AFTER_ORDER:
|
|
|
+ // 基础候选为空,仅由规则 3/5 命中注入(文档 4.2 步骤3)
|
|
|
+ return new ArrayList<>();
|
|
|
+ default:
|
|
|
+ log.warn("未知推荐场景,按商城首页处理:{}", scene);
|
|
|
+ return buildMallHomeCandidates(excluded);
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ private List<RecommendedProduct> buildDimensionCandidates(String dimensionCode, Set<Long> excluded) {
|
|
|
+ List<RecommendedProduct> pool = new ArrayList<>();
|
|
|
+
|
|
|
+ LambdaQueryWrapper<ProductDimensionMapping> mappingQw = new LambdaQueryWrapper<ProductDimensionMapping>()
|
|
|
+ .eq(ProductDimensionMapping::getEnabled, 1);
|
|
|
+ if (dimensionCode != null && !dimensionCode.isEmpty()) {
|
|
|
+ mappingQw.eq(ProductDimensionMapping::getDimensionCode, dimensionCode);
|
|
|
+ }
|
|
|
+ List<ProductDimensionMapping> mappings = dimensionMappingMapper.selectList(mappingQw);
|
|
|
+ if (mappings == null || mappings.isEmpty()) {
|
|
|
+ return pool;
|
|
|
+ }
|
|
|
+
|
|
|
+ Map<Long, Integer> scores = new HashMap<>();
|
|
|
+ Map<Long, String> reasons = new HashMap<>();
|
|
|
+ List<Long> productIds = new ArrayList<>();
|
|
|
+ for (ProductDimensionMapping m : mappings) {
|
|
|
+ Long productId = m.getProductId();
|
|
|
+ if (productId == null) {
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+ scores.put(productId, m.getMatchScore() == null ? 100 : m.getMatchScore());
|
|
|
+ reasons.put(productId, m.getMatchReason());
|
|
|
+ productIds.add(productId);
|
|
|
+ }
|
|
|
+ if (productIds.isEmpty()) {
|
|
|
+ return pool;
|
|
|
+ }
|
|
|
+
|
|
|
+ List<Product> products = productMapper.selectList(new LambdaQueryWrapper<Product>()
|
|
|
+ .in(Product::getId, productIds)
|
|
|
+ .eq(Product::getStatus, "on_shelf")
|
|
|
+ .and(w -> w.ne(Product::getProductType, "physical").or().isNull(Product::getStock)
|
|
|
+ .or().gt(Product::getStock, 0)));
|
|
|
+ if (products == null) {
|
|
|
+ return pool;
|
|
|
+ }
|
|
|
+
|
|
|
+ for (Product p : products) {
|
|
|
+ if (excluded.contains(p.getId())) {
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+ RecommendedProduct rp = fromProduct(p);
|
|
|
+ String reason = reasons.get(p.getId());
|
|
|
+ rp.setReason(reason != null && !reason.isEmpty() ? reason : "根据您的维度匹配为您推荐");
|
|
|
+ rp.setMatchScore(scores.get(p.getId()) / 100.0);
|
|
|
+ rp.setPriority(0);
|
|
|
+ rp.setSource("engine");
|
|
|
+ pool.add(rp);
|
|
|
+ }
|
|
|
+ return pool;
|
|
|
+ }
|
|
|
+
|
|
|
+ private List<RecommendedProduct> buildMallHomeCandidates(Set<Long> excluded) {
|
|
|
+ List<RecommendedProduct> pool = new ArrayList<>();
|
|
|
+
|
|
|
+ List<Product> products = productMapper.selectList(new LambdaQueryWrapper<Product>()
|
|
|
+ .eq(Product::getStatus, "on_shelf")
|
|
|
+ .and(w -> w.ne(Product::getProductType, "physical").or().isNull(Product::getStock)
|
|
|
+ .or().gt(Product::getStock, 0))
|
|
|
+ .orderByAsc(Product::getSortOrder));
|
|
|
+ if (products == null) {
|
|
|
+ return pool;
|
|
|
+ }
|
|
|
+
|
|
|
+ for (Product p : products) {
|
|
|
+ if (excluded.contains(p.getId())) {
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+ RecommendedProduct rp = fromProduct(p);
|
|
|
+ rp.setReason("为您推荐的好物");
|
|
|
+ rp.setMatchScore(BASE_MATCH_SCORE);
|
|
|
+ rp.setPriority(0);
|
|
|
+ rp.setSource("engine");
|
|
|
+ pool.add(rp);
|
|
|
+ }
|
|
|
+ return pool;
|
|
|
+ }
|
|
|
+
|
|
|
+ private List<RecommendedProduct> buildReportRelatedCandidates(Object analysis, Set<Long> excluded) {
|
|
|
+ List<RecommendedProduct> pool = new ArrayList<>();
|
|
|
+ List<String> dims = extractWeakDimensions(analysis);
|
|
|
+ if (dims.isEmpty()) {
|
|
|
+ dims = Collections.singletonList("body");
|
|
|
+ }
|
|
|
+ Set<Long> seen = new HashSet<>();
|
|
|
+ for (String dim : dims) {
|
|
|
+ for (RecommendedProduct rp : buildDimensionCandidates(dim, excluded)) {
|
|
|
+ if (seen.add(rp.getProductId())) {
|
|
|
+ pool.add(rp);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return pool;
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 从健康/认知分析结果中提取弱维度(与现有 ProductRecommendationService 逻辑保持一致,
|
|
|
+ * 见文档 4.2 步骤3 report_related)。
|
|
|
+ */
|
|
|
+ @SuppressWarnings("unchecked")
|
|
|
+ private List<String> extractWeakDimensions(Object analysis) {
|
|
|
+ List<String> dims = new ArrayList<>();
|
|
|
+ if (analysis == null) {
|
|
|
+ return dims;
|
|
|
+ }
|
|
|
+ try {
|
|
|
+ if (analysis instanceof Map) {
|
|
|
+ Map<String, Object> map = (Map<String, Object>) analysis;
|
|
|
+ Number nutrition = asNumber(map.get("nutritionScore"));
|
|
|
+ Number gut = asNumber(map.get("gutHealthScore"));
|
|
|
+ Number overall = asNumber(map.get("overallScore"));
|
|
|
+ if (nutrition != null && nutrition.intValue() < 60) {
|
|
|
+ dims.add("body");
|
|
|
+ }
|
|
|
+ if (gut != null && gut.intValue() < 60) {
|
|
|
+ dims.add("body");
|
|
|
+ }
|
|
|
+ if (overall != null && overall.intValue() < 60) {
|
|
|
+ dims.add("body");
|
|
|
+ dims.add("mind");
|
|
|
+ }
|
|
|
+ } else if (analysis instanceof List) {
|
|
|
+ for (Object o : (List<Object>) analysis) {
|
|
|
+ String dim = String.valueOf(o);
|
|
|
+ if ("focusScore".equals(dim) || "processingSpeedScore".equals(dim)
|
|
|
+ || "memoryScore".equals(dim)) {
|
|
|
+ dims.add("wisdom");
|
|
|
+ } else if ("attentionScore".equals(dim)) {
|
|
|
+ dims.add("mind");
|
|
|
+ } else if (!"null".equals(dim)) {
|
|
|
+ dims.add(dim);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.warn("解析报告弱维度失败:{}", e.getMessage());
|
|
|
+ }
|
|
|
+ return dims.stream().distinct().collect(Collectors.toList());
|
|
|
+ }
|
|
|
+
|
|
|
+ private Number asNumber(Object o) {
|
|
|
+ return o instanceof Number ? (Number) o : null;
|
|
|
+ }
|
|
|
+
|
|
|
+ // -----------------------------------------------------------------------
|
|
|
+ // 步骤4:应用规则(按 priority 从高到低,剔除类规则先于注入类规则)
|
|
|
+ // -----------------------------------------------------------------------
|
|
|
+
|
|
|
+ private void applyRules(List<RecommendationRule> rules, PurchaseView purchases,
|
|
|
+ List<RecommendedProduct> pool) {
|
|
|
+ // removed 记录已被更高优先级排除规则剔除的商品,注入类规则不再注入(剔除优先)
|
|
|
+ Set<Long> removed = new HashSet<>();
|
|
|
+ for (RecommendationRule rule : rules) {
|
|
|
+ try {
|
|
|
+ int type = rule.getRuleType() == null ? 0 : rule.getRuleType();
|
|
|
+ Map<Long, Date> scopePurchases = purchasesForRule(rule, purchases);
|
|
|
+ switch (type) {
|
|
|
+ case 1:
|
|
|
+ applyRule1Exclude(rule, scopePurchases, pool, removed);
|
|
|
+ break;
|
|
|
+ case 2:
|
|
|
+ applyRule2Repurchase(rule, scopePurchases, pool, removed);
|
|
|
+ break;
|
|
|
+ case 3:
|
|
|
+ applyRule3CrossSell(rule, scopePurchases, pool, removed);
|
|
|
+ break;
|
|
|
+ case 4:
|
|
|
+ applyRule4Suppress(rule, scopePurchases, pool, removed);
|
|
|
+ break;
|
|
|
+ case 5:
|
|
|
+ applyRule5Series(rule, scopePurchases, pool, removed);
|
|
|
+ break;
|
|
|
+ default:
|
|
|
+ log.warn("推荐规则[{}]类型非法:{}", rule.getId(), rule.getRuleType());
|
|
|
+ }
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.warn("推荐规则[{}]应用异常,已跳过:{}", rule.getId(), e.getMessage());
|
|
|
+ }
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ // ---------- 规则 1:已购不推 ----------
|
|
|
+ private void applyRule1Exclude(RecommendationRule rule, Map<Long, Date> purchases,
|
|
|
+ List<RecommendedProduct> pool, Set<Long> removed) {
|
|
|
+ if (rule.getTargetProductId() == null) {
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ Long trigger = rule.getTriggerProductId();
|
|
|
+ if (trigger == null) {
|
|
|
+ // 未配置触发商品:全局已购兜底已在候选池构建阶段完成,规则 1 仅做特定商品覆盖(文档 4.4)
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ int window = rule.getTimeWindowDays() != null ? rule.getTimeWindowDays()
|
|
|
+ : DEFAULT_PURCHASED_EXCLUDE_DAYS;
|
|
|
+ if (!purchasedWithin(purchases, trigger, window)) {
|
|
|
+ return; // 未命中,跳过(文档 4.1)
|
|
|
+ }
|
|
|
+ removeFromPool(pool, removed, rule.getTargetProductId());
|
|
|
+ }
|
|
|
+
|
|
|
+ // ---------- 规则 2:定时复购 ----------
|
|
|
+ private void applyRule2Repurchase(RecommendationRule rule, Map<Long, Date> purchases,
|
|
|
+ List<RecommendedProduct> pool, Set<Long> removed) {
|
|
|
+ Long trigger = rule.getTriggerProductId();
|
|
|
+ Long target = rule.getTargetProductId();
|
|
|
+ if (trigger == null || target == null) {
|
|
|
+ log.warn("规则[{}]缺少触发/目标商品,已跳过", rule.getId());
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ int delay = rule.getDelayDays() != null ? rule.getDelayDays() : DEFAULT_DELAY_DAYS;
|
|
|
+ if (!purchasedAtLeastDaysAgo(purchases, trigger, delay)) {
|
|
|
+ return; // 未到复购时间
|
|
|
+ }
|
|
|
+ addToPool(pool, removed, target, "该商品您已购买,可考虑复购",
|
|
|
+ priorityOf(rule), rule.getId(), rule.getRuleType());
|
|
|
+ }
|
|
|
+
|
|
|
+ // ---------- 规则 3:购买A推B ----------
|
|
|
+ private void applyRule3CrossSell(RecommendationRule rule, Map<Long, Date> purchases,
|
|
|
+ List<RecommendedProduct> pool, Set<Long> removed) {
|
|
|
+ Long trigger = rule.getTriggerProductId();
|
|
|
+ Long target = rule.getTargetProductId();
|
|
|
+ if (trigger == null || target == null) {
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ if (!purchases.containsKey(trigger)) {
|
|
|
+ return; // 未命中,跳过(文档 4.3)
|
|
|
+ }
|
|
|
+ addToPool(pool, removed, target, "根据您的购买记录推荐",
|
|
|
+ priorityOf(rule), rule.getId(), rule.getRuleType());
|
|
|
+ }
|
|
|
+
|
|
|
+ // ---------- 规则 4:购买A不推B ----------
|
|
|
+ private void applyRule4Suppress(RecommendationRule rule, Map<Long, Date> purchases,
|
|
|
+ List<RecommendedProduct> pool, Set<Long> removed) {
|
|
|
+ Long trigger = rule.getTriggerProductId();
|
|
|
+ Long target = rule.getTargetProductId();
|
|
|
+ if (trigger == null || target == null) {
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ if (!purchases.containsKey(trigger)) {
|
|
|
+ return; // 未命中,跳过(文档 4.1)
|
|
|
+ }
|
|
|
+ removeFromPool(pool, removed, target);
|
|
|
+ }
|
|
|
+
|
|
|
+ // ---------- 规则 5:系列重点推 ----------
|
|
|
+ private void applyRule5Series(RecommendationRule rule, Map<Long, Date> purchases,
|
|
|
+ List<RecommendedProduct> pool, Set<Long> removed) {
|
|
|
+ Set<Long> triggers = parseLongArray(rule.getTriggerProductIds());
|
|
|
+ if (triggers.isEmpty()) {
|
|
|
+ log.warn("规则[{}] trigger_product_ids 为空或解析失败,已跳过", rule.getId());
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ // 触发商品需全部购买过(文档 4.4)
|
|
|
+ for (Long id : triggers) {
|
|
|
+ if (!purchases.containsKey(id)) {
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ addToPool(pool, removed, rule.getTargetProductId(), "系列商品重点推荐",
|
|
|
+ priorityOf(rule) + SERIES_PRIORITY_BOOST, rule.getId(), rule.getRuleType());
|
|
|
+ }
|
|
|
+
|
|
|
+ private void removeFromPool(List<RecommendedProduct> pool, Set<Long> removed, Long productId) {
|
|
|
+ if (productId == null) {
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ pool.removeIf(p -> productId.equals(p.getProductId()));
|
|
|
+ removed.add(productId);
|
|
|
+ }
|
|
|
+
|
|
|
+ private void addToPool(List<RecommendedProduct> pool, Set<Long> removed, Long productId,
|
|
|
+ String reason, int priority, Long ruleId, Integer ruleType) {
|
|
|
+ if (productId == null || removed.contains(productId)) {
|
|
|
+ return;
|
|
|
+ }
|
|
|
+
|
|
|
+ RecommendedProduct existing = null;
|
|
|
+ for (RecommendedProduct p : pool) {
|
|
|
+ if (productId.equals(p.getProductId())) {
|
|
|
+ existing = p;
|
|
|
+ break;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ if (existing != null) {
|
|
|
+ // 该商品已在候选池中:不重复添加,仅更新推荐理由(文档 4.3)。
|
|
|
+ // 若条目来自基础候选(ruleId 为空),则采用本规则的属性;若已由规则注入,则取更高优先级。
|
|
|
+ existing.setReason(reason);
|
|
|
+ if (existing.getRuleId() == null) {
|
|
|
+ existing.setRuleId(ruleId == null ? null : ruleId.intValue());
|
|
|
+ existing.setRuleType(ruleType);
|
|
|
+ existing.setPriority(priority);
|
|
|
+ existing.setMatchScore(Math.max(existing.getMatchScore() == null ? 0d : existing.getMatchScore(),
|
|
|
+ RULE_MATCH_SCORE));
|
|
|
+ } else if (priority > existing.getPriority()) {
|
|
|
+ existing.setPriority(priority);
|
|
|
+ }
|
|
|
+ return;
|
|
|
+ }
|
|
|
+
|
|
|
+ Product product = productMapper.selectById(productId);
|
|
|
+ if (!isRecommendable(product)) {
|
|
|
+ log.warn("规则目标商品不可推荐(productId={}, status={}): {}", productId,
|
|
|
+ product == null ? "null" : product.getStatus(), ruleId);
|
|
|
+ return;
|
|
|
+ }
|
|
|
+
|
|
|
+ RecommendedProduct rp = fromProduct(product);
|
|
|
+ rp.setReason(reason);
|
|
|
+ rp.setMatchScore(RULE_MATCH_SCORE);
|
|
|
+ rp.setRuleId(ruleId == null ? null : ruleId.intValue());
|
|
|
+ rp.setRuleType(ruleType);
|
|
|
+ rp.setPriority(priority);
|
|
|
+ rp.setSource("engine");
|
|
|
+ pool.add(rp);
|
|
|
+ }
|
|
|
+
|
|
|
+ private boolean isRecommendable(Product product) {
|
|
|
+ return product != null && "on_shelf".equals(product.getStatus()) && hasSellableStock(product);
|
|
|
+ }
|
|
|
+
|
|
|
+ private boolean hasSellableStock(Product product) {
|
|
|
+ if (!"physical".equals(product.getProductType())) {
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+ return product.getStock() == null || product.getStock() > 0;
|
|
|
+ }
|
|
|
+
|
|
|
+ // -----------------------------------------------------------------------
|
|
|
+ // 步骤5:排序与截断
|
|
|
+ // -----------------------------------------------------------------------
|
|
|
+
|
|
|
+ private List<RecommendedProduct> sortAndTruncate(List<RecommendedProduct> pool, int limit) {
|
|
|
+ if (pool == null || pool.isEmpty()) {
|
|
|
+ return Collections.emptyList();
|
|
|
+ }
|
|
|
+ pool.sort((a, b) -> {
|
|
|
+ int cmp = Integer.compare(priorityOfResult(b), priorityOfResult(a)); // priority DESC
|
|
|
+ if (cmp != 0) {
|
|
|
+ return cmp;
|
|
|
+ }
|
|
|
+ cmp = Double.compare(matchScoreOfResult(b), matchScoreOfResult(a)); // matchScore DESC
|
|
|
+ if (cmp != 0) {
|
|
|
+ return cmp;
|
|
|
+ }
|
|
|
+ return Long.compare(productIdOfResult(a), productIdOfResult(b));
|
|
|
+ });
|
|
|
+ if (pool.size() > limit) {
|
|
|
+ return new ArrayList<>(pool.subList(0, limit));
|
|
|
+ }
|
|
|
+ return new ArrayList<>(pool);
|
|
|
+ }
|
|
|
+
|
|
|
+ // -----------------------------------------------------------------------
|
|
|
+ // 工具方法
|
|
|
+ // -----------------------------------------------------------------------
|
|
|
+
|
|
|
+ private RecommendedProduct fromProduct(Product p) {
|
|
|
+ RecommendedProduct rp = new RecommendedProduct();
|
|
|
+ rp.setProductId(p.getId());
|
|
|
+ rp.setName(p.getName());
|
|
|
+ rp.setCoverImage(p.getCoverImage());
|
|
|
+ rp.setPrice(p.getPrice());
|
|
|
+ rp.setUrl("/pages/discover-detail/product-detail/product-detail?id=" + p.getId());
|
|
|
+ return rp;
|
|
|
+ }
|
|
|
+
|
|
|
+ /** JSON/逗号分隔的长整型数组解析(容错:忽略非数字项),用于 trigger_product_ids。 */
|
|
|
+ private Set<Long> parseLongArray(String raw) {
|
|
|
+ Set<Long> ids = new LinkedHashSet<>();
|
|
|
+ for (String s : parseStringArray(raw)) {
|
|
|
+ try {
|
|
|
+ ids.add(Long.parseLong(s));
|
|
|
+ } catch (NumberFormatException e) {
|
|
|
+ log.warn("规则配置包含无法解析的商品ID:{}", s);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return ids;
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 解析 JSON 数组字符串或纯逗号分隔字符串。
|
|
|
+ * 支持如 "[\"dimension_page\",\"mall_home\"]"、dimension_page,mall_home 等写法。
|
|
|
+ */
|
|
|
+ private List<String> parseStringArray(String raw) {
|
|
|
+ List<String> result = new ArrayList<>();
|
|
|
+ if (raw == null) {
|
|
|
+ return result;
|
|
|
+ }
|
|
|
+ String cleaned = raw.trim();
|
|
|
+ if (cleaned.startsWith("[")) {
|
|
|
+ cleaned = cleaned.substring(1);
|
|
|
+ }
|
|
|
+ if (cleaned.endsWith("]")) {
|
|
|
+ cleaned = cleaned.substring(0, cleaned.length() - 1);
|
|
|
+ }
|
|
|
+ for (String part : cleaned.split("[,,;]")) {
|
|
|
+ String s = part.trim().replace("\"", "").replace("'", "");
|
|
|
+ if (!s.isEmpty()) {
|
|
|
+ result.add(s);
|
|
|
+ }
|
|
|
+ }
|
|
|
+ return result;
|
|
|
+ }
|
|
|
+
|
|
|
+ private static int priorityOf(RecommendationRule r) {
|
|
|
+ return r.getPriority() == null ? 0 : r.getPriority();
|
|
|
+ }
|
|
|
+
|
|
|
+ private static long ruleIdOf(RecommendationRule r) {
|
|
|
+ return r.getId() == null ? 0L : r.getId();
|
|
|
+ }
|
|
|
+
|
|
|
+ /** 同优先级下,剔除类规则先于注入类规则(文档 4.1~4.5):4,1,3,5,2 */
|
|
|
+ private static int ruleLoopOrder(Integer ruleType) {
|
|
|
+ int t = ruleType == null ? 0 : ruleType;
|
|
|
+ switch (t) {
|
|
|
+ case 4:
|
|
|
+ return 0;
|
|
|
+ case 1:
|
|
|
+ return 1;
|
|
|
+ case 3:
|
|
|
+ return 2;
|
|
|
+ case 5:
|
|
|
+ return 3;
|
|
|
+ case 2:
|
|
|
+ return 4;
|
|
|
+ default:
|
|
|
+ return 5;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ private static int priorityOfResult(RecommendedProduct p) {
|
|
|
+ return p.getPriority() == null ? 0 : p.getPriority();
|
|
|
+ }
|
|
|
+
|
|
|
+ private static double matchScoreOfResult(RecommendedProduct p) {
|
|
|
+ return p.getMatchScore() == null ? 0d : p.getMatchScore();
|
|
|
+ }
|
|
|
+
|
|
|
+ private static long productIdOfResult(RecommendedProduct p) {
|
|
|
+ return p.getProductId() == null ? 0L : p.getProductId();
|
|
|
+ }
|
|
|
+}
|