|
|
@@ -1,20 +1,26 @@
|
|
|
package com.etotem.cfc.service;
|
|
|
|
|
|
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
|
|
|
+import com.etotem.cfc.dto.EnergyApplyResult;
|
|
|
+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;
|
|
|
import com.fasterxml.jackson.databind.ObjectMapper;
|
|
|
import lombok.extern.slf4j.Slf4j;
|
|
|
import org.springframework.stereotype.Service;
|
|
|
+
|
|
|
import javax.annotation.Resource;
|
|
|
import java.util.ArrayList;
|
|
|
import java.util.Collections;
|
|
|
+import java.util.HashSet;
|
|
|
import java.util.List;
|
|
|
import java.util.Map;
|
|
|
+import java.util.Set;
|
|
|
|
|
|
@Slf4j
|
|
|
@Service
|
|
|
@@ -25,8 +31,23 @@ public class EnergyRuleEngine {
|
|
|
private EnergyDimensionMapper energyDimensionMapper;
|
|
|
@Resource
|
|
|
private EnergyService energyService;
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 日上限配置驱动(SC-P-90 / TC-P-90 前置:{@code energy_daily_limit} 按维度 {@code dailyLimit=N},
|
|
|
+ * 配置驱动上限覆盖服务侧硬编码 {@code DAILY_LIMIT_MAP};多来源共享同一日上限,0/负按 0 处理不发放)。
|
|
|
+ */
|
|
|
+ @Resource
|
|
|
+ private DimensionDailyLimitMapper dimensionDailyLimitMapper;
|
|
|
+
|
|
|
private final ObjectMapper objectMapper = new ObjectMapper();
|
|
|
|
|
|
+ /**
|
|
|
+ * 本引擎实例内写路径幂等快查:同 (memberId, dimensionId, sourceType, sourceId) 不重复写
|
|
|
+ * (ED-1 重复审批/网络重试幂等;与 energy_log 幂等唯一键、{@link EnergyService#isAlreadyApplied}
|
|
|
+ * DB 层去重双保险)。
|
|
|
+ */
|
|
|
+ private final Set<String> appliedKeys = new HashSet<>();
|
|
|
+
|
|
|
public List<EnergyRule> findActiveRules(String eventType) {
|
|
|
return energyRuleMapper.selectList(
|
|
|
new LambdaQueryWrapper<EnergyRule>()
|
|
|
@@ -36,53 +57,179 @@ public class EnergyRuleEngine {
|
|
|
);
|
|
|
}
|
|
|
|
|
|
- public void evaluate(String eventType, Long sourceId, Long memberId, Map<String, Object> context) {
|
|
|
+ /**
|
|
|
+ * 五维能量规则引擎实时触发写入(能力键 {@code energy.ruleEngine.apply},S-cfc-391;SC-P-87/88/90/93 写路径)。
|
|
|
+ *
|
|
|
+ * <p>事件 → 规则匹配 → 归因维度+数值 → 写 {@code EnergyLog}/{@code EnergyBalance},返回可观测结果
|
|
|
+ * (归因维度→amount / 日上限触顶 / 拒绝原因)。与事后对账({@code energy.ledger.guard})、
|
|
|
+ * 服务侧日上限守卫入口({@code energy.dailyLimit.guard})互补。</p>
|
|
|
+ *
|
|
|
+ * <p>契约要点:</p>
|
|
|
+ * <ul>
|
|
|
+ * <li>规则归因生效(SC-P-87/93/ED-1/7):按规则 {@code dimensionCode} 写入对应维度,不回落配置默认 action;</li>
|
|
|
+ * <li>同源重复触发幂等(SC-P-87 边界/ED-1):同 (memberId, sourceType, sourceId) 只写一次;</li>
|
|
|
+ * <li>写入层/规则计算异常传播给调用方(SC-P-87-E-4),不静默吞掉;</li>
|
|
|
+ * <li>规则 amount 缺失/负值 → {@link IllegalArgumentException} 拒绝并告警(配置异常,不写脏流水);</li>
|
|
|
+ * <li>decrease 余额不足 → {@link IllegalStateException}『能量不足』拒绝(SC-P-88-E-1/ED-2);</li>
|
|
|
+ * <li>日上限配置驱动(SC-P-90/ED-4):按 {@code energy_daily_limit} 判定单维度日上限,
|
|
|
+ * 触顶不累加、多来源共享、0/负按 0 处理不崩溃。</li>
|
|
|
+ * </ul>
|
|
|
+ *
|
|
|
+ * @param eventType 事件类型(task/article/activity/wish/…)
|
|
|
+ * @param sourceId 来源实例ID(任务实例ID/文章ID/活动ID/心愿ID)
|
|
|
+ * @param memberId 家庭成员ID
|
|
|
+ * @param context 规则条件求值上下文(可为空 Map)
|
|
|
+ * @return 写入结果(归因维度→amount、触顶/拒绝标记),无匹配规则时为空结果不写流水
|
|
|
+ */
|
|
|
+ public EnergyApplyResult apply(String eventType, Long sourceId, Long memberId, Map<String, Object> context) {
|
|
|
+ EnergyApplyResult result = new EnergyApplyResult();
|
|
|
List<EnergyRule> rules = findActiveRules(eventType);
|
|
|
- if (rules.isEmpty()) return;
|
|
|
+ if (rules.isEmpty()) {
|
|
|
+ return result;
|
|
|
+ }
|
|
|
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());
|
|
|
- }
|
|
|
- } catch (Exception e) {
|
|
|
- log.error("规则执行失败: ruleId={}, error={}", rule.getId(), e.getMessage());
|
|
|
+ if (!matchesConditions(rule, context)) continue;
|
|
|
+
|
|
|
+ Integer amount = rule.getAmount();
|
|
|
+ if (amount == null || amount <= 0) {
|
|
|
+ // SC-P-87-E-4:规则 amount 缺失/负值属配置异常,拒绝执行并告警(不写脏流水)
|
|
|
+ log.error("规则 amount 缺失/负值属配置异常,拒绝执行并告警: ruleId={}, amount={}",
|
|
|
+ rule.getId(), amount);
|
|
|
+ throw new IllegalArgumentException("规则 amount 缺失/负值属配置异常: ruleId=" + rule.getId());
|
|
|
+ }
|
|
|
+
|
|
|
+ Long dimId = resolveDimensionId(rule);
|
|
|
+ if (dimId == null) {
|
|
|
+ log.warn("规则归因维度无法解析,跳过: ruleId={}, dimensionCode={}",
|
|
|
+ rule.getId(), rule.getDimensionCode());
|
|
|
+ continue;
|
|
|
+ }
|
|
|
+
|
|
|
+ if ("increase".equals(rule.getAction())) {
|
|
|
+ applyIncrease(result, rule, eventType, sourceId, memberId, amount, dimId);
|
|
|
+ } else if ("decrease".equals(rule.getAction())) {
|
|
|
+ applyDecrease(result, rule, memberId, amount, dimId);
|
|
|
}
|
|
|
}
|
|
|
+ return result;
|
|
|
+ }
|
|
|
+
|
|
|
+ /**
|
|
|
+ * 兼容入口(void):实时触发写入,结果可观测见 {@link #apply}。
|
|
|
+ * 既有调用方沿用;新调用方优先使用 {@link #apply} 拿归因/触顶/拒绝结果。
|
|
|
+ */
|
|
|
+ public void evaluate(String eventType, Long sourceId, Long memberId, Map<String, Object> context) {
|
|
|
+ apply(eventType, sourceId, memberId, context);
|
|
|
+ }
|
|
|
+
|
|
|
+ private void applyIncrease(EnergyApplyResult result, EnergyRule rule, String eventType,
|
|
|
+ Long sourceId, Long memberId, Integer amount, Long dimId) {
|
|
|
+ String dimCode = rule.getDimensionCode();
|
|
|
+ // ED-1 幂等:同 (memberId, dimId, sourceType, sourceId) 重复触发只写一次
|
|
|
+ if (isAlreadyApplied(memberId, dimId, eventType, sourceId)) {
|
|
|
+ log.info("同源重复触发已发放过,跳过: memberId={}, dimId={}, sourceType={}, sourceId={}",
|
|
|
+ memberId, dimId, eventType, sourceId);
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ // SC-P-90:写入前经日上限守卫校验(配置驱动,DimensionDailyLimit;无配置回落服务硬编码 map)
|
|
|
+ if (!guardDailyLimit(memberId, dimId, dimCode, amount)) {
|
|
|
+ result.setCapped(true);
|
|
|
+ result.setRejected(true);
|
|
|
+ result.setReason("已达今日上限");
|
|
|
+ log.info("每日上限已达,规则跳过发放: ruleId={}, memberId={}", rule.getId(), memberId);
|
|
|
+ return;
|
|
|
+ }
|
|
|
+ // 归因写入:按规则声明维度写 EnergyLog/EnergyBalance(SC-P-87/93 主流程)
|
|
|
+ EnergyService.setRuleDimensionHint(dimId);
|
|
|
+ try {
|
|
|
+ energyService.awardEnergy(memberId, eventType, sourceId, amount, rule.getDescription(), null);
|
|
|
+ } finally {
|
|
|
+ EnergyService.clearRuleDimensionHint();
|
|
|
+ }
|
|
|
+ markApplied(memberId, dimId, eventType, sourceId);
|
|
|
+ result.addAward(dimCode, amount);
|
|
|
+ }
|
|
|
+
|
|
|
+ private void applyDecrease(EnergyApplyResult result, EnergyRule rule, Long memberId,
|
|
|
+ Integer amount, Long dimId) {
|
|
|
+ int deducted = energyService.deductEnergy(memberId, dimId, Math.abs(amount), rule.getDescription());
|
|
|
+ if (deducted < 0) {
|
|
|
+ // SC-P-88-E-1/ED-2:余额不足 → 向调用方暴露『能量不足』拒绝(心愿保持待审批、不出现负余额)
|
|
|
+ result.setRejected(true);
|
|
|
+ result.setReason("能量不足");
|
|
|
+ log.warn("余额不足,扣除拒绝: memberId={}, dimId={}, amount={}, ruleId={}",
|
|
|
+ memberId, dimId, Math.abs(amount), rule.getId());
|
|
|
+ throw new IllegalStateException("能量不足: memberId=" + memberId
|
|
|
+ + ", dimension=" + rule.getDimensionCode());
|
|
|
+ }
|
|
|
+ result.addAward(rule.getDimensionCode(), -Math.abs(amount));
|
|
|
}
|
|
|
|
|
|
/**
|
|
|
- * 每日上限守卫钩子(SC-P-90:ruleEngine 写入前经守卫校验,S-cfc-304 同链)。
|
|
|
+ * 每日上限守卫钩子(SC-P-90:ruleEngine 写入前经守卫校验)。
|
|
|
*
|
|
|
- * <p>委托 {@link EnergyService#isDailyLimitExceeded}(公共守卫入口)判断该成员该维度当日
|
|
|
- * 累计是否已达上限;返回 true=允许发放,false=超限应跳过。</p>
|
|
|
+ * <p>配置驱动:本引擎注入的 {@link DimensionDailyLimitMapper} 按维度 code 读取
|
|
|
+ * {@code energy_daily_limit} 配置({@code dailyLimit=N})判定单维度日上限(SC-P-90 主流程 2;
|
|
|
+ * 多来源共享同一日上限);未配置/注入为 null 时回落
|
|
|
+ * {@link EnergyService#isDailyLimitExceeded}(服务侧硬编码 map)。配置 0/负按 0 处理
|
|
|
+ * (TC-P-90-E-4:不崩溃、不发放)。</p>
|
|
|
*
|
|
|
* @param memberId 家庭成员ID
|
|
|
* @param dimId 维度ID(null/解析失败按超限拦截,不发放)
|
|
|
+ * @param dimCode 维度 code(读取配置用)
|
|
|
* @param amount 拟发放能量
|
|
|
+ * @return true=允许发放;false=超限/触顶应跳过
|
|
|
*/
|
|
|
- public boolean guardDailyLimit(Long memberId, Long dimId, Integer amount) {
|
|
|
+ public boolean guardDailyLimit(Long memberId, Long dimId, String dimCode, Integer amount) {
|
|
|
if (dimId == null || amount == null || amount <= 0) {
|
|
|
return false;
|
|
|
}
|
|
|
+ Integer configuredLimit = resolveConfiguredDailyLimit(dimCode);
|
|
|
+ if (configuredLimit != null) {
|
|
|
+ // TC-P-90-E-4:配置 0/负 按 0 处理(不再累加),不崩溃
|
|
|
+ if (configuredLimit <= 0) {
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+ try {
|
|
|
+ int todayEarned = energyService.getTodayEarned(memberId, dimId);
|
|
|
+ return todayEarned + amount <= configuredLimit;
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.warn("日上限累计查询异常,按超限拦截: memberId={}, dimId={}: {}",
|
|
|
+ memberId, dimId, e.getMessage());
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+ }
|
|
|
+ // 回落服务侧公共守卫入口(硬编码 map)
|
|
|
try {
|
|
|
return !energyService.isDailyLimitExceeded(memberId, Collections.singleton(dimId), amount);
|
|
|
} catch (Exception e) {
|
|
|
- log.warn("daily limit 守卫校验异常,按超限拦截: memberId={}, dimId={}: {}", memberId, dimId, e.getMessage());
|
|
|
+ log.warn("daily limit 守卫校验异常,按超限拦截: memberId={}, dimId={}: {}",
|
|
|
+ memberId, dimId, e.getMessage());
|
|
|
return false;
|
|
|
}
|
|
|
}
|
|
|
|
|
|
+ /**
|
|
|
+ * 读取维度日上限配置:{@code energy_daily_limit} 按 dimensionCode 配置 {@code dailyLimit=N}
|
|
|
+ * (SC-P-90 前置)。未配置/读取失败返回 null(由调用方回落到服务侧硬编码 map)。
|
|
|
+ */
|
|
|
+ private Integer resolveConfiguredDailyLimit(String dimCode) {
|
|
|
+ if (dimCode == null || dimensionDailyLimitMapper == null) {
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+ try {
|
|
|
+ List<DimensionDailyLimit> limits = dimensionDailyLimitMapper.selectList(
|
|
|
+ new LambdaQueryWrapper<DimensionDailyLimit>()
|
|
|
+ .eq(DimensionDailyLimit::getDimensionCode, dimCode));
|
|
|
+ if (limits != null && !limits.isEmpty() && limits.get(0) != null) {
|
|
|
+ return limits.get(0).getDailyLimit();
|
|
|
+ }
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.warn("读取每日上限配置失败 dimensionCode={}: {}", dimCode, e.getMessage());
|
|
|
+ }
|
|
|
+ return null;
|
|
|
+ }
|
|
|
+
|
|
|
private boolean matchesConditions(EnergyRule rule, Map<String, Object> context) {
|
|
|
if (rule.getConditions() == null || rule.getConditions().isEmpty()) return true;
|
|
|
try {
|
|
|
@@ -95,11 +242,6 @@ public class EnergyRuleEngine {
|
|
|
} catch (Exception e) { log.warn("条件解析失败: ruleId={}", rule.getId()); return false; }
|
|
|
}
|
|
|
|
|
|
- private int calculateAmount(EnergyRule rule, Map<String, Object> context) {
|
|
|
- if (rule.getAmount() != null && rule.getAmount() != 0) return rule.getAmount();
|
|
|
- return 0;
|
|
|
- }
|
|
|
-
|
|
|
private Long resolveDimensionId(EnergyRule rule) {
|
|
|
if (rule.getDimensionCode() == null || rule.getDimensionCode().isEmpty()) return null;
|
|
|
EnergyDimension dim = energyDimensionMapper.selectOne(
|
|
|
@@ -112,6 +254,28 @@ public class EnergyRuleEngine {
|
|
|
new LambdaQueryWrapper<EnergyDimension>().eq(EnergyDimension::getStatus, 1).orderByAsc(EnergyDimension::getSortOrder));
|
|
|
}
|
|
|
|
|
|
+ /** 写路径幂等:内存快查 + DB {@code isAlreadyApplied}(energy_log 幂等唯一键兜底) */
|
|
|
+ private boolean isAlreadyApplied(Long memberId, Long dimId, String sourceType, Long sourceId) {
|
|
|
+ String key = appliedKey(memberId, dimId, sourceType, sourceId);
|
|
|
+ if (appliedKeys.contains(key)) {
|
|
|
+ return true;
|
|
|
+ }
|
|
|
+ try {
|
|
|
+ return energyService.isAlreadyApplied(memberId, dimId, sourceType, sourceId);
|
|
|
+ } catch (Exception e) {
|
|
|
+ log.warn("写路径幂等检查异常,按未发放处理: {}", e.getMessage());
|
|
|
+ return false;
|
|
|
+ }
|
|
|
+ }
|
|
|
+
|
|
|
+ private void markApplied(Long memberId, Long dimId, String sourceType, Long sourceId) {
|
|
|
+ appliedKeys.add(appliedKey(memberId, dimId, sourceType, sourceId));
|
|
|
+ }
|
|
|
+
|
|
|
+ private String appliedKey(Long memberId, Long dimId, String sourceType, Long sourceId) {
|
|
|
+ return memberId + ":" + dimId + ":" + sourceType + ":" + sourceId;
|
|
|
+ }
|
|
|
+
|
|
|
/**
|
|
|
* 对账/并发原子加守卫钩子(SC-X-20):写入后校验 balanceAfter 序列一致性(逐条 balanceAfter == prev + amount),
|
|
|
* 可被 evaluate() 在每次规则执行后调用,不一致即告警(不静默通过)。
|