|
|
@@ -1,9 +1,11 @@
|
|
|
package com.etotem.cfc.service;
|
|
|
|
|
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
|
|
+import com.etotem.cfc.entity.DimensionDailyLimit;
|
|
|
import com.etotem.cfc.entity.EnergyDimension;
|
|
|
import com.etotem.cfc.entity.EnergyLog;
|
|
|
import com.etotem.cfc.entity.EnergyRule;
|
|
|
+import com.etotem.cfc.mapper.DimensionDailyLimitMapper;
|
|
|
import com.etotem.cfc.mapper.EnergyDimensionMapper;
|
|
|
import com.etotem.cfc.mapper.EnergyRuleMapper;
|
|
|
import com.fasterxml.jackson.core.type.TypeReference;
|
|
|
@@ -13,8 +15,12 @@ import org.springframework.stereotype.Service;
|
|
|
import javax.annotation.Resource;
|
|
|
import java.util.ArrayList;
|
|
|
import java.util.Collections;
|
|
|
+import java.util.HashMap;
|
|
|
+import java.util.LinkedHashMap;
|
|
|
import java.util.List;
|
|
|
import java.util.Map;
|
|
|
+import java.util.Set;
|
|
|
+import java.util.concurrent.ConcurrentHashMap;
|
|
|
|
|
|
@Slf4j
|
|
|
@Service
|
|
|
@@ -25,8 +31,20 @@ public class EnergyRuleEngine {
|
|
|
private EnergyDimensionMapper energyDimensionMapper;
|
|
|
@Resource
|
|
|
private EnergyService energyService;
|
|
|
+ /**
|
|
|
+ * 单维度日上限配置(SC-P-90 前置:{@code energy_daily_limit} 按维度配 {@code dailyLimit=N})。
|
|
|
+ * 引擎写路径按该配置判定触顶(配置驱动,替代 EnergyService 侧硬编码 {@code DAILY_LIMIT_MAP})。
|
|
|
+ */
|
|
|
+ @Resource
|
|
|
+ private DimensionDailyLimitMapper dimensionDailyLimitMapper;
|
|
|
private final ObjectMapper objectMapper = new ObjectMapper();
|
|
|
|
|
|
+ /**
|
|
|
+ * 写路径幂等记录(同 member+dimension+sourceType+sourceId 重复触发仅写一次流水;
|
|
|
+ * DB 侧幂等唯一键由 {@code energy.ledger.guard}(S-cfc-225/390)覆盖,本集合为引擎内软去重)。
|
|
|
+ */
|
|
|
+ private final Set<String> appliedKeys = ConcurrentHashMap.newKeySet();
|
|
|
+
|
|
|
public List<EnergyRule> findActiveRules(String eventType) {
|
|
|
return energyRuleMapper.selectList(
|
|
|
new LambdaQueryWrapper<EnergyRule>()
|
|
|
@@ -36,29 +54,83 @@ public class EnergyRuleEngine {
|
|
|
);
|
|
|
}
|
|
|
|
|
|
- public void evaluate(String eventType, Long sourceId, Long memberId, Map<String, Object> context) {
|
|
|
+ /**
|
|
|
+ * 实时触发写入入口(能力键 {@code energy.ruleEngine.apply},SC-P-87/88/90/93):
|
|
|
+ * 事件 → 规则匹配 → 归因维度+数值 → 写 EnergyLog/EnergyBalance,返回可观测结果。
|
|
|
+ *
|
|
|
+ * <p>返回值(调用方可感知写入结果,SC-P-87/88/90):
|
|
|
+ * <ul>
|
|
|
+ * <li>{@code awarded}:{@code Map<dimensionCode, amount>} 本次实际归因发放;</li>
|
|
|
+ * <li>{@code capped}:boolean,日上限触顶(ED-4「已达今日上限」)拒发;</li>
|
|
|
+ * <li>{@code duplicated}:boolean,写路径幂等命中(同源重复触发)跳过。</li>
|
|
|
+ * </ul>
|
|
|
+ *
|
|
|
+ * <p>异常语义:规则 {@code amount} 缺失/非正 → {@link IllegalArgumentException};
|
|
|
+ * decrease 余额不足 → {@link IllegalStateException};写入层失败/归因无分配 → {@link RuntimeException}。
|
|
|
+ * 一律向调用方传播(可告警/回滚),不静默吞掉。</p>
|
|
|
+ */
|
|
|
+ public Map<String, Object> apply(String eventType, Long sourceId, Long memberId, Map<String, Object> context) {
|
|
|
+ Map<String, Object> result = new LinkedHashMap<>();
|
|
|
+ Map<String, Integer> awarded = new LinkedHashMap<>();
|
|
|
+ result.put("awarded", awarded);
|
|
|
+ result.put("capped", false);
|
|
|
+ result.put("duplicated", false);
|
|
|
+ if (eventType == null || memberId == null) {
|
|
|
+ return result;
|
|
|
+ }
|
|
|
List<EnergyRule> rules = findActiveRules(eventType);
|
|
|
- if (rules.isEmpty()) return;
|
|
|
+ if (rules == null || rules.isEmpty()) {
|
|
|
+ return result;
|
|
|
+ }
|
|
|
+ if (context == null) {
|
|
|
+ context = new HashMap<>();
|
|
|
+ }
|
|
|
for (EnergyRule rule : rules) {
|
|
|
- try {
|
|
|
- if (!matchesConditions(rule, context)) continue;
|
|
|
- int amount = calculateAmount(rule, context);
|
|
|
- if (amount == 0) continue;
|
|
|
- Long dimId = resolveDimensionId(rule);
|
|
|
- if ("increase".equals(rule.getAction())) {
|
|
|
- // SC-P-90:写入前经 daily limit 守卫校验(与 energy.ruleEngine.apply 同链)
|
|
|
- if (!guardDailyLimit(memberId, dimId, amount)) {
|
|
|
- log.info("每日上限已达,规则跳过发放: ruleId={}, memberId={}", rule.getId(), memberId);
|
|
|
- continue;
|
|
|
- }
|
|
|
- energyService.awardEnergy(memberId, eventType, sourceId, amount, rule.getDescription(), null);
|
|
|
- } else if ("decrease".equals(rule.getAction())) {
|
|
|
- energyService.deductEnergy(memberId, dimId, Math.abs(amount), rule.getDescription());
|
|
|
+ if (!matchesConditions(rule, context)) continue;
|
|
|
+ int amount = calculateAmount(rule, context);
|
|
|
+ if (amount == 0) continue;
|
|
|
+ String action = rule.getAction();
|
|
|
+ if (!"increase".equals(action) && !"decrease".equals(action)) continue;
|
|
|
+ Long dimId = resolveDimensionId(rule);
|
|
|
+ if (dimId == null) {
|
|
|
+ log.info("规则未解析到归因维度,跳过(不 500): ruleId={}", rule.getId());
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+ if ("increase".equals(action)) {
|
|
|
+ if (alreadyApplied(memberId, dimId, eventType, sourceId)) {
|
|
|
+ result.put("duplicated", true);
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+ if (isDailyLimitCapped(memberId, dimId, rule.getDimensionCode(), amount)) {
|
|
|
+ result.put("capped", true);
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+ Map<String, Integer> dimAllocations = new LinkedHashMap<>();
|
|
|
+ dimAllocations.put(rule.getDimensionCode(), amount);
|
|
|
+ Map<String, Integer> written = energyService.awardEnergyAtomic(
|
|
|
+ memberId, eventType, sourceId, amount,
|
|
|
+ rule.getDescription(), null, dimAllocations);
|
|
|
+ if (written == null || written.isEmpty()) {
|
|
|
+ throw new RuntimeException("能量写入失败(归因无分配): ruleId=" + rule.getId()
|
|
|
+ + ", memberId=" + memberId);
|
|
|
+ }
|
|
|
+ awarded.putAll(written);
|
|
|
+ } else {
|
|
|
+ int after = energyService.deductEnergy(memberId, dimId, Math.abs(amount), rule.getDescription());
|
|
|
+ if (after < 0) {
|
|
|
+ throw new IllegalStateException("能量不足,拒绝扣减: ruleId=" + rule.getId()
|
|
|
+ + ", memberId=" + memberId);
|
|
|
}
|
|
|
- } catch (Exception e) {
|
|
|
- log.error("规则执行失败: ruleId={}, error={}", rule.getId(), e.getMessage());
|
|
|
}
|
|
|
}
|
|
|
+ return result;
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 实时触发(保留旧入口,委托 {@link #apply},结果可观测性见 apply)。
|
|
|
+ */
|
|
|
+ public void evaluate(String eventType, Long sourceId, Long memberId, Map<String, Object> context) {
|
|
|
+ apply(eventType, sourceId, memberId, context);
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
@@ -83,6 +155,67 @@ public class EnergyRuleEngine {
|
|
|
}
|
|
|
}
|
|
|
|
|
|
+ /**
|
|
|
+ * 写路径日上限触顶判定(SC-P-90/ED-4,配置驱动)。
|
|
|
+ *
|
|
|
+ * <p>优先级:引擎注入的 {@code energy_daily_limit} 配置({@link #dimensionDailyLimitMapper})
|
|
|
+ * 判定单维度日上限;配置缺失回落 {@link EnergyService#isDailyLimitExceeded}(硬编码 DAILY_LIMIT_MAP
|
|
|
+ * 口径,与 Service 侧 guard 一致)。配置 0/负 按 0 处理不发放、不崩溃(TC-P-90-E-4)。
|
|
|
+ * 多来源共享同一日上限:累计按「服务端今日窗口」查询 energy_log(created_at between,次日重置)。</p>
|
|
|
+ *
|
|
|
+ * @return true=已达上限应拒发;false=可发放
|
|
|
+ */
|
|
|
+ boolean isDailyLimitCapped(Long memberId, Long dimId, String dimensionCode, Integer amount) {
|
|
|
+ Integer limit = resolveConfiguredDailyLimit(dimensionCode);
|
|
|
+ if (limit == null) {
|
|
|
+ return energyService.isDailyLimitExceeded(memberId, Collections.singleton(dimId), amount);
|
|
|
+ }
|
|
|
+ if (limit <= 0) {
|
|
|
+ log.info("日上限配置为 0/负,按 0 处理不再发放: dimensionCode={}", dimensionCode);
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+ int todayTotal = energyService.getTodayDimensionTotal(memberId, dimId);
|
|
|
+ return todayTotal + amount > limit;
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 读取某维度日上限配置(引擎注入的 DimensionDailyLimitMapper),未配置/读取失败返回 null。
|
|
|
+ */
|
|
|
+ private Integer resolveConfiguredDailyLimit(String dimensionCode) {
|
|
|
+ if (dimensionCode == null || dimensionDailyLimitMapper == null) {
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+ try {
|
|
|
+ List<DimensionDailyLimit> limits = dimensionDailyLimitMapper.selectList(
|
|
|
+ new LambdaQueryWrapper<DimensionDailyLimit>()
|
|
|
+ .eq(DimensionDailyLimit::getDimensionCode, dimensionCode));
|
|
|
+ if (limits != null && !limits.isEmpty() && limits.get(0) != null) {
|
|
|
+ return limits.get(0).getDailyLimit();
|
|
|
+ }
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.warn("读取日上限配置失败 dimensionCode={}: {}", dimensionCode, e.getMessage());
|
|
|
+ }
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 写路径幂等判定:同 (memberId, dimensionId, sourceType, sourceId) 已写入则跳过(ED-1 重复审批/网络重试)。
|
|
|
+ * 引擎内软去重 + DB 幂等入口({@link EnergyService#isAlreadyApplied})双保险。
|
|
|
+ */
|
|
|
+ private boolean alreadyApplied(Long memberId, Long dimId, String sourceType, Long sourceId) {
|
|
|
+ String key = memberId + ":" + dimId + ":" + sourceType + ":" + sourceId;
|
|
|
+ if (!appliedKeys.add(key)) {
|
|
|
+ log.info("写路径幂等命中,同源重复触发跳过: key={}", key);
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+ try {
|
|
|
+ return energyService.isAlreadyApplied(memberId, dimId, sourceType, sourceId);
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.warn("写路径幂等查询异常,按未写入处理: {}", e.getMessage());
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
private boolean matchesConditions(EnergyRule rule, Map<String, Object> context) {
|
|
|
if (rule.getConditions() == null || rule.getConditions().isEmpty()) return true;
|
|
|
try {
|
|
|
@@ -95,9 +228,15 @@ public class EnergyRuleEngine {
|
|
|
} catch (Exception e) { log.warn("条件解析失败: ruleId={}", rule.getId()); return false; }
|
|
|
}
|
|
|
|
|
|
+ /**
|
|
|
+ * 规则数值校验(SC-P-87-E-4):amount 缺失/非正属配置异常 → 拒绝并告警(抛异常),不静默跳过。
|
|
|
+ */
|
|
|
private int calculateAmount(EnergyRule rule, Map<String, Object> context) {
|
|
|
- if (rule.getAmount() != null && rule.getAmount() != 0) return rule.getAmount();
|
|
|
- return 0;
|
|
|
+ Integer amount = rule.getAmount();
|
|
|
+ if (amount == null || amount <= 0) {
|
|
|
+ throw new IllegalArgumentException("规则 amount 缺失/非正属配置异常: ruleId=" + rule.getId());
|
|
|
+ }
|
|
|
+ return amount;
|
|
|
}
|
|
|
|
|
|
private Long resolveDimensionId(EnergyRule rule) {
|