|
@@ -0,0 +1,219 @@
|
|
|
|
|
+package com.etotem.cfc.service;
|
|
|
|
|
+
|
|
|
|
|
+import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
|
|
|
|
+import com.etotem.cfc.entity.CfBalanceLog;
|
|
|
|
|
+import com.etotem.cfc.entity.CfDirectSalesTier;
|
|
|
|
|
+import com.etotem.cfc.entity.CfIndirectSalesTier;
|
|
|
|
|
+import com.etotem.cfc.entity.CfEarnRule;
|
|
|
|
|
+import com.etotem.cfc.mapper.CfBalanceLogMapper;
|
|
|
|
|
+import com.etotem.cfc.mapper.PpointConsumptionLogMapper;
|
|
|
|
|
+import com.fasterxml.jackson.databind.ObjectMapper;
|
|
|
|
|
+import org.springframework.stereotype.Service;
|
|
|
|
|
+
|
|
|
|
|
+import javax.annotation.Resource;
|
|
|
|
|
+import java.util.*;
|
|
|
|
|
+
|
|
|
|
|
+/**
|
|
|
|
|
+ * F03 存量重算(2026-11-29):按每笔订单时刻回放业绩,重算 F03a/F03b 差额并补发/扣回。
|
|
|
|
|
+ *
|
|
|
|
|
+ * <p>纯计算 computeDelta 可独立单测;execute 走 adjustWithType(新 ref_type,免三道闸)。</p>
|
|
|
|
|
+ */
|
|
|
|
|
+@Service
|
|
|
|
|
+public class CfCommissionRecalcService {
|
|
|
|
|
+
|
|
|
|
|
+ @Resource private CfReferralService referralService;
|
|
|
|
|
+ @Resource private PpointConsumptionLogMapper ppointMapper;
|
|
|
|
|
+ @Resource private CfBalanceLogMapper balanceLogMapper;
|
|
|
|
|
+ @Resource private CfEarnRuleService earnRuleService;
|
|
|
|
|
+ @Resource private CfBalanceService cfBalanceService;
|
|
|
|
|
+
|
|
|
|
|
+ private final ObjectMapper objectMapper = new ObjectMapper();
|
|
|
|
|
+
|
|
|
|
|
+ // setters for unit test injection
|
|
|
|
|
+ public void setReferralService(CfReferralService s) { this.referralService = s; }
|
|
|
|
|
+ public void setPpointMapper(PpointConsumptionLogMapper m) { this.ppointMapper = m; }
|
|
|
|
|
+ public void setBalanceLogMapper(CfBalanceLogMapper m) { this.balanceLogMapper = m; }
|
|
|
|
|
+ public void setEarnRuleService(CfEarnRuleService s) { this.earnRuleService = s; }
|
|
|
|
|
+ public void setCfBalanceService(CfBalanceService s) { this.cfBalanceService = s; }
|
|
|
|
|
+
|
|
|
|
|
+ /** 差额计算结果 */
|
|
|
|
|
+ public static class Delta {
|
|
|
|
|
+ public int oldAmount;
|
|
|
|
|
+ public int newAmount;
|
|
|
|
|
+ public int delta;
|
|
|
|
|
+ public Delta(int o, int n) { this.oldAmount = o; this.newAmount = n; this.delta = n - o; }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ /**
|
|
|
|
|
+ * 纯计算:按订单时刻 asOf 回放,算新/旧 amount 差额。
|
|
|
|
|
+ *
|
|
|
|
|
+ * @param orderId 订单ID
|
|
|
|
|
+ * @param asOf 订单时刻(滚动窗口右界 + referral_tree 层级回放)
|
|
|
|
|
+ * @param ruleCode F03a / F03b
|
|
|
|
|
+ * @param referrerId 推荐人用户ID(该笔订单的收益人)
|
|
|
|
|
+ */
|
|
|
|
|
+ public Delta computeDelta(Long orderId, Date asOf, String ruleCode, Long referrerId) {
|
|
|
|
|
+ // ① 订单 P 点基数:按 order_id 精确取(asOf 截止)
|
|
|
|
|
+ int base = ppointMapper.sumPpointsByOrderId(orderId, asOf);
|
|
|
|
|
+
|
|
|
|
|
+ // ② 新费率:F03a 用业绩(self+加权),F03b 用自身业绩;按订单时刻回放
|
|
|
|
|
+ int rate;
|
|
|
|
|
+ if ("F03a".equals(ruleCode)) {
|
|
|
|
|
+ int tierPp = referralService.getF03aTierPpoints(referrerId, asOf);
|
|
|
|
|
+ CfDirectSalesTier tier = referralService.matchDirectSalesTier(tierPp);
|
|
|
|
|
+ rate = tier == null || tier.getRatePercent() == null ? 0 : tier.getRatePercent();
|
|
|
|
|
+ } else {
|
|
|
|
|
+ int self = referralService.getSelfAnnualPpointsAt(referrerId, asOf);
|
|
|
|
|
+ CfIndirectSalesTier t2 = referralService.matchIndirectSalesTier(self);
|
|
|
|
|
+ rate = t2 == null || t2.getRatePercent() == null ? 0 : t2.getRatePercent();
|
|
|
|
|
+ }
|
|
|
|
|
+ int maxRate = maxRate(ruleCode);
|
|
|
|
|
+ if (maxRate > 0 && rate > maxRate) rate = maxRate;
|
|
|
|
|
+ int newAmount = (int) Math.floor(base * rate / 100.0);
|
|
|
|
|
+
|
|
|
|
|
+ // 旧金额:只取 type='earn' 的原发放流水(skip/补差流水不计)
|
|
|
|
|
+ List<CfBalanceLog> olds = balanceLogMapper.selectList(
|
|
|
|
|
+ new LambdaQueryWrapper<CfBalanceLog>()
|
|
|
|
|
+ .eq(CfBalanceLog::getRefType, ruleCode)
|
|
|
|
|
+ .eq(CfBalanceLog::getRefId, orderId)
|
|
|
|
|
+ .eq(CfBalanceLog::getType, "earn"));
|
|
|
|
|
+ int oldAmount = 0;
|
|
|
|
|
+ for (CfBalanceLog l : olds) if (l.getAmount() != null) oldAmount += l.getAmount();
|
|
|
|
|
+
|
|
|
|
|
+ return new Delta(oldAmount, newAmount);
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ private int maxRate(String ruleCode) {
|
|
|
|
|
+ try {
|
|
|
|
|
+ CfEarnRule rule = earnRuleService.getByCode(ruleCode);
|
|
|
|
|
+ if (rule == null || rule.getParamsJson() == null) return 0;
|
|
|
|
|
+ Map<?, ?> params = objectMapper.readValue(rule.getParamsJson(), Map.class);
|
|
|
|
|
+ Object max = params.get("max_rate_percent");
|
|
|
|
|
+ return max instanceof Number ? ((Number) max).intValue() : 0;
|
|
|
|
|
+ } catch (Exception e) { return 0; }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ // ==================== 批量 preview / execute / rollback ====================
|
|
|
|
|
+
|
|
|
|
|
+ @Resource private org.springframework.jdbc.core.JdbcTemplate jdbcTemplate;
|
|
|
|
|
+ public void setJdbcTemplate(org.springframework.jdbc.core.JdbcTemplate j) { this.jdbcTemplate = j; }
|
|
|
|
|
+
|
|
|
|
|
+ /** 重算汇总 */
|
|
|
|
|
+ public static class Summary {
|
|
|
|
|
+ public int total, applied, failed, sumDelta;
|
|
|
|
|
+ public Map<String, Object> toMap() {
|
|
|
|
|
+ Map<String, Object> m = new HashMap<>();
|
|
|
|
|
+ m.put("total", total); m.put("applied", applied); m.put("failed", failed); m.put("sumDelta", sumDelta);
|
|
|
|
|
+ return m;
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ /**
|
|
|
|
|
+ * 批量重算:扫 ppoint_consumption_log 全量(含旧规则下漏发订单),按订单时刻回放差额。
|
|
|
|
|
+ * preview 只写日志不写余额;execute 写 adjust 补差(新ref_type,免三道闸)。
|
|
|
|
|
+ */
|
|
|
|
|
+ public Summary recalc(String batchId, boolean execute) {
|
|
|
|
|
+ Summary s = new Summary();
|
|
|
|
|
+ Date now = new Date();
|
|
|
|
|
+ jdbcTemplate.update("INSERT IGNORE INTO cf_commission_recalc_batch "
|
|
|
|
|
+ + "(batch_id, scope, mode, started_at, status) VALUES (?, 'all', ?, NOW(), 'running')",
|
|
|
|
|
+ batchId, execute ? "execute" : "preview");
|
|
|
|
|
+ // 取所有有 P 点的订单(去重),含旧规则下无 F03 流水的漏发订单
|
|
|
|
|
+ List<Map<String, Object>> rows = jdbcTemplate.queryForList(
|
|
|
|
|
+ "SELECT order_id, user_id, created_at FROM ppoint_consumption_log ORDER BY order_id");
|
|
|
|
|
+ for (Map<String, Object> row : rows) {
|
|
|
|
|
+ long orderId = ((Number) row.get("order_id")).longValue();
|
|
|
|
|
+ java.sql.Timestamp ts = (java.sql.Timestamp) row.get("created_at");
|
|
|
|
|
+ Date asOf = ts != null ? new Date(ts.getTime()) : now;
|
|
|
|
|
+ Long buyerUserId = row.get("user_id") == null ? null : ((Number) row.get("user_id")).longValue();
|
|
|
|
|
+ // 订单买家链路上两级推荐人(跳过同家庭)→ F03a/F03b 受益人
|
|
|
|
|
+ List<Object[]> beneficiaries = resolveBeneficiaries(orderId, buyerUserId);
|
|
|
|
|
+ for (Object[] ben : beneficiaries) {
|
|
|
|
|
+ Long referrerUserId = (Long) ben[0];
|
|
|
|
|
+ String ruleCode = (String) ben[1];
|
|
|
|
|
+ Long memberId = resolveMemberId(referrerUserId);
|
|
|
|
|
+ if (memberId == null) continue;
|
|
|
|
|
+ try {
|
|
|
|
|
+ Delta d = computeDelta(orderId, asOf, ruleCode, referrerUserId);
|
|
|
|
|
+ s.total++;
|
|
|
|
|
+ s.sumDelta += d.delta;
|
|
|
|
|
+ // 幂等:uk_order_rule,重复执行跳过
|
|
|
|
|
+ int ins = jdbcTemplate.update("INSERT IGNORE INTO cf_commission_recalc_log "
|
|
|
|
|
+ + "(batch_id, order_id, rule_code, member_id, old_amount, new_amount, delta, status, as_of_order_time) "
|
|
|
|
|
+ + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
|
|
|
|
+ batchId, orderId, ruleCode, memberId, d.oldAmount, d.newAmount, d.delta,
|
|
|
|
|
+ execute ? "success" : "preview", new java.sql.Timestamp(asOf.getTime()));
|
|
|
|
|
+ if (ins == 0 || !execute || d.delta == 0) continue;
|
|
|
|
|
+ String refType = "F03a".equals(ruleCode) ? "F03a_recalc" : "F03b_recalc";
|
|
|
|
|
+ Long logId = jdbcTemplate.queryForObject(
|
|
|
|
|
+ "SELECT id FROM cf_commission_recalc_log WHERE order_id=? AND rule_code=?",
|
|
|
|
|
+ Long.class, orderId, ruleCode);
|
|
|
|
|
+ cfBalanceService.adjustWithType(memberId, d.delta, logId, refType,
|
|
|
|
|
+ "F03存量重算补差(" + ruleCode + ")", 1L);
|
|
|
|
|
+ s.applied++;
|
|
|
|
|
+ } catch (Exception e) {
|
|
|
|
|
+ s.failed++;
|
|
|
|
|
+ jdbcTemplate.update("UPDATE cf_commission_recalc_log SET status='failed' WHERE order_id=? AND rule_code=?",
|
|
|
|
|
+ orderId, ruleCode);
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ }
|
|
|
|
|
+ jdbcTemplate.update("UPDATE cf_commission_recalc_batch SET finished_at=NOW(), total=?, done=?, sum_delta=?, "
|
|
|
|
|
+ + "status=? WHERE batch_id=?", s.total, s.applied, s.sumDelta,
|
|
|
|
|
+ s.failed > 0 ? "partial" : "done", batchId);
|
|
|
|
|
+ return s;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ /** 回滚:按 batch_id 逆序,对 success 记录反向 adjust。 */
|
|
|
|
|
+ public Summary rollback(String batchId) {
|
|
|
|
|
+ Summary s = new Summary();
|
|
|
|
|
+ List<Map<String, Object>> logs = jdbcTemplate.queryForList(
|
|
|
|
|
+ "SELECT * FROM cf_commission_recalc_log WHERE batch_id=? AND status='success' ORDER BY id DESC", batchId);
|
|
|
|
|
+ for (Map<String, Object> l : logs) {
|
|
|
|
|
+ long logId = ((Number) l.get("id")).longValue();
|
|
|
|
|
+ String ruleCode = String.valueOf(l.get("rule_code"));
|
|
|
|
|
+ long memberId = ((Number) l.get("member_id")).longValue();
|
|
|
|
|
+ int delta = ((Number) l.get("delta")).intValue();
|
|
|
|
|
+ if (delta == 0) continue;
|
|
|
|
|
+ try {
|
|
|
|
|
+ String refType = ("F03a".equals(ruleCode) ? "F03a_recalc" : "F03b_recalc") + "_rollback";
|
|
|
|
|
+ cfBalanceService.adjustWithType(memberId, -delta, logId, refType, "F03存量重算回滚", 1L);
|
|
|
|
|
+ jdbcTemplate.update("UPDATE cf_commission_recalc_log SET status='rolled_back' WHERE id=?", logId);
|
|
|
|
|
+ s.applied++;
|
|
|
|
|
+ } catch (Exception e) { s.failed++; }
|
|
|
|
|
+ }
|
|
|
|
|
+ return s;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ /** 订单买家链路上两级推荐人(跳过同家庭),返回 {userId, ruleCode}[]。 */
|
|
|
|
|
+ private List<Object[]> resolveBeneficiaries(long orderId, Long buyerUserId) {
|
|
|
|
|
+ List<Object[]> result = new ArrayList<>();
|
|
|
|
|
+ if (buyerUserId == null) return result;
|
|
|
|
|
+ // 从 referral_tree 取 buyer 的祖先链(按 level 升序),跳过同家庭,取两级
|
|
|
|
|
+ // 通过注入的 referralService 提供的工具方法(此处用 JdbcTemplate 查 users/referral_tree 避免新增 mapper)
|
|
|
|
|
+ List<Map<String, Object>> refs = jdbcTemplate.queryForList(
|
|
|
|
|
+ "SELECT rt.parent_id, rt.level FROM referral_tree rt WHERE rt.member_id=? ORDER BY rt.level ASC", buyerUserId);
|
|
|
|
|
+ Long buyerFamily = jdbcTemplate.queryForObject("SELECT family_id FROM users WHERE id=?", Long.class, buyerUserId);
|
|
|
|
|
+ Set<Long> seen = new HashSet<>();
|
|
|
|
|
+ int awarded = 0;
|
|
|
|
|
+ for (Map<String, Object> r : refs) {
|
|
|
|
|
+ if (awarded >= 2) break;
|
|
|
|
|
+ long parent = ((Number) r.get("parent_id")).longValue();
|
|
|
|
|
+ if (seen.contains(parent)) continue;
|
|
|
|
|
+ seen.add(parent);
|
|
|
|
|
+ Long pf = jdbcTemplate.queryForObject("SELECT family_id FROM users WHERE id=?", Long.class, parent);
|
|
|
|
|
+ if (buyerFamily != null && buyerFamily.equals(pf)) continue;
|
|
|
|
|
+ result.add(new Object[]{parent, awarded == 0 ? "F03a" : "F03b"});
|
|
|
|
|
+ awarded++;
|
|
|
|
|
+ }
|
|
|
|
|
+ return result;
|
|
|
|
|
+ }
|
|
|
|
|
+
|
|
|
|
|
+ private Long resolveMemberId(Long userId) {
|
|
|
|
|
+ if (userId == null) return null;
|
|
|
|
|
+ try {
|
|
|
|
|
+ return jdbcTemplate.queryForObject(
|
|
|
|
|
+ "SELECT id FROM family_members WHERE user_id=? ORDER BY id LIMIT 1", Long.class, userId);
|
|
|
|
|
+ } catch (Exception e) { return null; }
|
|
|
|
|
+ }
|
|
|
|
|
+}
|