Browse Source

feat(f03): Task2 业绩口径(getWeightedTeamAnnualPpoints逐层90→0+min(level)去重; getF03aTierPpoints=self+加权; legacy等权供F03c; asOf截止mapper重载) + TDD 5例(旧11例绿)

Xiaogang Liao 9 hours ago
parent
commit
5fa0d46586

+ 17 - 0
cfc-backend/src/main/java/com/etotem/cfc/mapper/PpointConsumptionLogMapper.java

@@ -27,4 +27,21 @@ public interface PpointConsumptionLogMapper extends BaseMapper<PpointConsumption
             "</script>"
     })
     int sumPpointsSince(@Param("userIds") Collection<Long> userIds, @Param("since") Date since);
+
+    /**
+     * 指定截止时刻的滚动窗口 P 点累计(F03 存量重算:按订单时刻回放 asOf)。
+     *
+     * @param userIds 用户ID集合
+     * @param since   窗口起点(含)
+     * @param until   窗口终点(含,通常为订单 created_at)
+     */
+    @Select({
+            "<script>",
+            "SELECT COALESCE(SUM(ppoints), 0) FROM ppoint_consumption_log",
+            "WHERE created_at &gt;= #{since} AND created_at &lt;= #{until}",
+            "AND user_id IN",
+            "<foreach collection='userIds' item='uid' open='(' separator=',' close=')'>#{uid}</foreach>",
+            "</script>"
+    })
+    int sumPpointsSince(@Param("userIds") Collection<Long> userIds, @Param("since") Date since, @Param("until") Date until);
 }

+ 76 - 3
cfc-backend/src/main/java/com/etotem/cfc/service/CfReferralService.java

@@ -20,8 +20,10 @@ import java.util.ArrayList;
 import java.util.Calendar;
 import java.util.Collections;
 import java.util.Date;
+import java.util.HashMap;
 import java.util.LinkedHashSet;
 import java.util.List;
+import java.util.Map;
 import java.util.Set;
 
 /**
@@ -39,9 +41,12 @@ import java.util.Set;
 @Service
 public class CfReferralService {
 
-    /** F03a 团队口径最大层级(§4.1.1:团队 8 层以内) */
+    /** F03a 团队口径最大层级(§4.1.1:团队 8 层以内;F03c 专用,保持不变) */
     public static final int DEFAULT_TEAM_DEPTH = 8;
 
+    /** F03a 业绩权重最大层级(新规则:第1层90%递减至第10层0%) */
+    public static final int F03A_WEIGHT_DEPTH = 10;
+
     /** 滚动一年窗口天数(§4.1/§4.4:按消费时间滚动一年) */
     private static final int ROLLING_YEAR_DAYS = 365;
 
@@ -182,6 +187,59 @@ public class CfReferralService {
         return sumAnnualPpoints(Collections.singletonList(referrerUserId));
     }
 
+    /**
+     * F03 新口径(2026-11-29):团队业绩 = Σ(第N层下线的再销售P点 × 权重),
+     * 权重第1层90%、第2层80%…第9层10%、第10层0%;同一下线按 min(level) 取最高权重,不含本人。
+     *
+     * @param referrerUserId 推荐人用户ID
+     * @param asOf           业绩截止时刻(null=当前;存量重算传订单 created_at)
+     */
+    public int getWeightedTeamAnnualPpoints(Long referrerUserId, Date asOf) {
+        if (referrerUserId == null) return 0;
+        List<ReferralTree> rows = referralTreeMapper.selectList(
+                new LambdaQueryWrapper<ReferralTree>()
+                        .eq(ReferralTree::getParentId, referrerUserId)
+                        .le(ReferralTree::getLevel, F03A_WEIGHT_DEPTH));
+        if (rows == null || rows.isEmpty()) return 0;
+        Date end = asOf != null ? asOf : new Date();
+        Date since = rollingYearAgo(end);
+
+        // 按 memberId 去重取 min(level)
+        Map<Long, Integer> minLevel = new HashMap<>();
+        for (ReferralTree r : rows) {
+            Long mid = r.getMemberId();
+            if (mid == null || mid.equals(referrerUserId)) continue;
+            int lv = r.getLevel() == null ? 0 : r.getLevel();
+            Integer prev = minLevel.get(mid);
+            if (prev == null || lv < prev) minLevel.put(mid, lv);
+        }
+        int total = 0;
+        for (Map.Entry<Long, Integer> e : minLevel.entrySet()) {
+            int w = 10 - e.getValue(); // L1→9(90%), L9→1(10%), L10→0
+            if (w <= 0) continue;
+            long pp = sumAnnualPpointsAsOf(Collections.singletonList(e.getKey()), since, end);
+            total += (int) Math.round(pp * w / 10.0);
+        }
+        return total;
+    }
+
+    /** F03a 档位业绩 = 本人100% + 团队加权(self 只加一次,团队遍历不含本人)。 */
+    public int getF03aTierPpoints(Long referrerUserId, Date asOf) {
+        if (referrerUserId == null) return 0;
+        Date end = asOf != null ? asOf : new Date();
+        Date since = rollingYearAgo(end);
+        int self = sumAnnualPpointsAsOf(Collections.singletonList(referrerUserId), since, end);
+        return self + getWeightedTeamAnnualPpoints(referrerUserId, asOf);
+    }
+
+    /**
+     * F03c 专用旧口径:8层内成员等权求和(F03 重定义前的团队业绩,用于冻结快照匹配)。
+     * 与新 F03a 口径彻底解耦。
+     */
+    public int getTeamAnnualPpointsLegacy(Long referrerUserId, int depth) {
+        return sumAnnualPpoints(getTeamUserIds(referrerUserId, depth));
+    }
+
     /**
      * 团队用户ID集合:referrerUserId 向下 depth 层内所有成员(referral_tree.parent_id = 本人,
      * level <= depth 的 child_id 去重;不含本人)。空=无团队。
@@ -209,7 +267,13 @@ public class CfReferralService {
 
     /** 滚动一年起点(now - 365 天,含) */
     public Date rollingYearAgo() {
+        return rollingYearAgo(new Date());
+    }
+
+    /** 滚动一年起点(asOf - 365 天,含) */
+    public Date rollingYearAgo(Date asOf) {
         Calendar cal = Calendar.getInstance();
+        cal.setTime(asOf != null ? asOf : new Date());
         cal.add(Calendar.DAY_OF_YEAR, -ROLLING_YEAR_DAYS);
         return cal.getTime();
     }
@@ -219,11 +283,20 @@ public class CfReferralService {
         if (userIds == null || userIds.isEmpty()) {
             return 0;
         }
-        Date since = rollingYearAgo();
+        return sumAnnualPpointsAsOf(userIds, rollingYearAgo(), null);
+    }
+
+    /** 按用户集合分批求和 [since, until] 窗口 P 点(until=null 表示无上界) */
+    private int sumAnnualPpointsAsOf(List<Long> userIds, Date since, Date until) {
+        if (userIds == null || userIds.isEmpty()) {
+            return 0;
+        }
         int total = 0;
         for (int i = 0; i < userIds.size(); i += USER_ID_BATCH_SIZE) {
             List<Long> batch = userIds.subList(i, Math.min(i + USER_ID_BATCH_SIZE, userIds.size()));
-            total += ppointConsumptionLogMapper.sumPpointsSince(batch, since);
+            total += until == null
+                    ? ppointConsumptionLogMapper.sumPpointsSince(batch, since)
+                    : ppointConsumptionLogMapper.sumPpointsSince(batch, since, until);
         }
         return total;
     }

+ 109 - 0
cfc-backend/src/test/java/com/etotem/cfc/service/CfReferralWeightedPpointsTest.java

@@ -0,0 +1,109 @@
+package com.etotem.cfc.service;
+
+import com.etotem.cfc.entity.ReferralTree;
+import com.etotem.cfc.mapper.*;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
+
+import java.util.*;
+import static org.junit.jupiter.api.Assertions.*;
+import static org.mockito.ArgumentMatchers.*;
+import static org.mockito.Mockito.*;
+
+/**
+ * TDD 契约(Task2):F03a 业绩口径 = 个人100% + 团队逐层递减90%→0%(基于下线再销售P点),
+ * F03c legacy 等权口径不变,asOf 截止回放。
+ */
+class CfReferralWeightedPpointsTest {
+
+    @Mock private ReferralTreeMapper referralTreeMapper;
+    @Mock private UserMapper userMapper;
+    @Mock private CfRateTierMapper cfRateTierMapper;
+    @Mock private CfDirectSalesTierMapper cfDirectSalesTierMapper;
+    @Mock private CfIndirectSalesTierMapper cfIndirectSalesTierMapper;
+    @Mock private PpointConsumptionLogMapper ppointConsumptionLogMapper;
+
+    @InjectMocks private CfReferralService service;
+
+    private Date asOf;
+
+    @BeforeEach
+    void setUp() {
+        MockitoAnnotations.openMocks(this);
+        asOf = new Date();
+    }
+
+    private ReferralTree tree(long parent, long child, int level) {
+        ReferralTree r = new ReferralTree();
+        r.setParentId(parent); r.setMemberId(child); r.setLevel(level);
+        return r;
+    }
+
+    @Test
+    void weighted_team_applies_level_weights() {
+        // 下线:L1用户101(P点10000)、L2用户102(P点20000)、L10用户110(P点50000)
+        when(referralTreeMapper.selectList(any())).thenReturn(Arrays.asList(
+                tree(1L, 101L, 1), tree(1L, 102L, 2), tree(1L, 110L, 10)));
+        // 按用户集合返回P点:用 thenAnswer 区分
+        when(ppointConsumptionLogMapper.sumPpointsSince(anyCollection(), any(Date.class), any(Date.class)))
+                .thenAnswer(inv -> {
+                    Collection<Long> ids = inv.getArgument(0);
+                    int sum = 0;
+                    if (ids.contains(101L)) sum += 10000;
+                    if (ids.contains(102L)) sum += 20000;
+                    if (ids.contains(110L)) sum += 50000;
+                    return sum;
+                });
+        // 期望 = 10000*0.9 + 20000*0.8 + 50000*0.0 = 9000 + 16000 + 0 = 25000
+        assertEquals(25000, service.getWeightedTeamAnnualPpoints(1L, asOf));
+    }
+
+    @Test
+    void weighted_team_dedups_by_min_level_and_excludes_self() {
+        // 同一后代 103 既在 L1 又在 L2(脏数据)→ 取 min(level)=1 权重0.9;本人1混入 → 排除
+        when(referralTreeMapper.selectList(any())).thenReturn(Arrays.asList(
+                tree(1L, 103L, 1), tree(1L, 103L, 2), tree(1L, 1L, 1)));
+        when(ppointConsumptionLogMapper.sumPpointsSince(anyCollection(), any(Date.class), any(Date.class)))
+                .thenReturn(10000);
+        assertEquals(9000, service.getWeightedTeamAnnualPpoints(1L, asOf));
+    }
+
+    @Test
+    void f03a_tier_ppoints_is_self_plus_weighted_once() {
+        // self=10000(用户1本人),团队加权=9000(用户101 L1 ×0.9)
+        when(ppointConsumptionLogMapper.sumPpointsSince(anyCollection(), any(Date.class), any(Date.class)))
+                .thenAnswer(inv -> {
+                    Collection<Long> ids = inv.getArgument(0);
+                    if (ids.size() == 1 && ids.contains(1L)) return 10000; // self
+                    if (ids.contains(101L)) return 10000; // team L1
+                    return 0;
+                });
+        when(referralTreeMapper.selectList(any())).thenReturn(Collections.singletonList(tree(1L, 101L, 1)));
+        assertEquals(19000, service.getF03aTierPpoints(1L, asOf)); // self10000 + 9000,self只加一次
+    }
+
+    @Test
+    void legacy_team_is_equal_weight_unchanged() {
+        // legacy:8层等权求和,无权重递减
+        when(referralTreeMapper.selectList(any())).thenReturn(Arrays.asList(
+                tree(1L, 101L, 1), tree(1L, 102L, 2)));
+        when(ppointConsumptionLogMapper.sumPpointsSince(anyCollection(), any(Date.class)))
+                .thenReturn(30000); // 两个用户合计
+        assertEquals(30000, service.getTeamAnnualPpointsLegacy(1L, 8));
+    }
+
+    @Test
+    void asOf_filters_ppoints_by_created_at() {
+        // 验证 asOf 截止:mapper 应被调用时传入 asOf(滚动窗口右界=asOf)
+        when(referralTreeMapper.selectList(any())).thenReturn(Collections.singletonList(tree(1L, 101L, 1)));
+        when(ppointConsumptionLogMapper.sumPpointsSince(anyCollection(), any(Date.class), any(Date.class)))
+                .thenReturn(10000);
+        service.getWeightedTeamAnnualPpoints(1L, asOf);
+        org.mockito.ArgumentCaptor<Date> cap = org.mockito.ArgumentCaptor.forClass(Date.class);
+        verify(ppointConsumptionLogMapper, atLeastOnce()).sumPpointsSince(anyCollection(), any(Date.class), cap.capture());
+        assertTrue(cap.getAllValues().stream().anyMatch(d -> d.equals(asOf)), "应以订单时刻asOf为窗口右界");
+    }
+}