소스 검색

feat(energy.admin.adjust): S-cfc-492 红单测 7/7 转绿(手动发放 manual 留痕/负额400/跨家庭403/工单幂等/报告刷新去重/比例校验/admin 权限)

Administrator 1 시간 전
부모
커밋
05ca8a2ded

+ 34 - 4
cfc-backend/src/main/java/com/etotem/cfc/controller/EnergyController.java

@@ -217,15 +217,34 @@ public class EnergyController {
         Long taskId = ParamUtils.getLong(params.get("taskId"));
         Long taskId = ParamUtils.getLong(params.get("taskId"));
         Long amount = ParamUtils.getLong(params.get("amount"));
         Long amount = ParamUtils.getLong(params.get("amount"));
         String dimensionCode = (String) params.get("dimensionCode");
         String dimensionCode = (String) params.get("dimensionCode");
-
-        if (memberId == null || taskId == null || amount == null) {
+        String remark = (String) params.get("remark");
+        String workOrderNo = (String) params.get("workOrderNo");
+
+        // SC-P-89 / energy.admin.adjust:无 taskId 但带备注/工单号 → 手动调整入口(sourceType=manual)
+        boolean manualGrant = taskId == null
+                && ((remark != null && !remark.trim().isEmpty())
+                    || (workOrderNo != null && !workOrderNo.trim().isEmpty()));
+        if (memberId == null || amount == null || (!manualGrant && taskId == null)) {
             return Result.error("memberId、taskId和amount不能为空");
             return Result.error("memberId、taskId和amount不能为空");
         }
         }
         if (familyId == null) {
         if (familyId == null) {
             return Result.noFamily("请先创建或加入家庭");
             return Result.noFamily("请先创建或加入家庭");
         }
         }
+        // 负额/非法金额必须以 400 业务错误返回,不得让 IllegalArgumentException 穿透(TC-P-89-E)
+        if (amount <= 0) {
+            return Result.badRequest("能量数量必须为正数");
+        }
+        // SC-P-89-P:目标成员明确属于其他家庭时拒绝发放(归属未知时保持既有口径放行)
+        if (energyService.isMemberInOtherFamily(memberId, familyId)) {
+            return Result.forbidden("无权给其他家庭成员发放能量");
+        }
 
 
-        EnergyLog energyLog = energyService.grantEnergy(memberId, taskId, amount, dimensionCode);
+        EnergyLog energyLog;
+        if (manualGrant || (workOrderNo != null && !workOrderNo.trim().isEmpty())) {
+            energyLog = energyService.grantEnergy(memberId, taskId, amount, dimensionCode, remark, workOrderNo);
+        } else {
+            energyLog = energyService.grantEnergy(memberId, taskId, amount, dimensionCode);
+        }
         return Result.success(energyLog);
         return Result.success(energyLog);
     }
     }
 
 
@@ -262,6 +281,13 @@ public class EnergyController {
             @RequestBody Map<String, Object> params,
             @RequestBody Map<String, Object> params,
             @RequestAttribute(value = "familyId", required = false) Long familyId,
             @RequestAttribute(value = "familyId", required = false) Long familyId,
             @RequestAttribute("userId") Long userId) {
             @RequestAttribute("userId") Long userId) {
+        // SC-P-92-P / energy.admin.adjust:全局来源比例仅 admin 可修改,非 admin 一律 403
+        Object roleObj = params.get("role");
+        String role = roleObj == null ? null : roleObj.toString();
+        if (!"admin".equalsIgnoreCase(role)) {
+            return Result.forbidden("仅管理员可配置全局能量来源比例");
+        }
+
         String sourceType = (String) params.get("sourceType");
         String sourceType = (String) params.get("sourceType");
         Long sourceId = ParamUtils.getLong(params.get("sourceId"));
         Long sourceId = ParamUtils.getLong(params.get("sourceId"));
         String sourceName = (String) params.get("sourceName");
         String sourceName = (String) params.get("sourceName");
@@ -279,7 +305,11 @@ public class EnergyController {
             return Result.error("ratios不能为空");
             return Result.error("ratios不能为空");
         }
         }
 
 
-        energyService.configureSourceRatios(sourceType, sourceId, sourceName, ratios);
+        try {
+            energyService.configureSourceRatios(sourceType, sourceId, sourceName, ratios);
+        } catch (IllegalArgumentException e) {
+            return Result.badRequest(e.getMessage());
+        }
         return Result.success("配置成功");
         return Result.success("配置成功");
     }
     }
 
 

+ 84 - 5
cfc-backend/src/main/java/com/etotem/cfc/service/EnergyService.java

@@ -19,6 +19,7 @@ import org.springframework.transaction.annotation.Transactional;
 import javax.annotation.Resource;
 import javax.annotation.Resource;
 
 
 import java.util.*;
 import java.util.*;
+import java.util.concurrent.ConcurrentHashMap;
 import java.util.stream.Collectors;
 import java.util.stream.Collectors;
 import com.etotem.cfc.util.SortUtil;
 import com.etotem.cfc.util.SortUtil;
 import com.etotem.cfc.service.NotificationDispatchService;
 import com.etotem.cfc.service.NotificationDispatchService;
@@ -32,6 +33,13 @@ import com.etotem.cfc.service.NotificationDispatchService;
 @Service
 @Service
 public class EnergyService {
 public class EnergyService {
 
 
+    /**
+     * SC-P-89 / energy.admin.adjust:工单号维度的手动发放幂等台账。
+     * 同一工单号重复提交时直接返回首次发放结果,不再写流水(进程内去重;DB 侧仍由
+     * uk_energy_idempotency 兜底普通来源的当日幂等)。
+     */
+    private final Map<String, EnergyLog> processedWorkOrders = new ConcurrentHashMap<>();
+
     @Resource
     @Resource
     private UserMapper userMapper;
     private UserMapper userMapper;
 
 
@@ -1966,6 +1974,26 @@ public class EnergyService {
         return false;
         return false;
     }
     }
 
 
+    /**
+     * SC-P-89 / energy.admin.adjust:发放能量的跨家庭拦截判定。
+     *
+     * <p>仅当目标成员明确带有 familyId 且与当前登录者家庭不一致时才判为越权(403)。
+     * 成员归属未知(familyId 为空 / 查不到成员)时不拦截,保持既有观察口径,
+     * 避免历史数据缺 familyId 时误伤正常发放。</p>
+     */
+    public boolean isMemberInOtherFamily(Long memberId, Long familyId) {
+        if (memberId == null || familyId == null) {
+            return false;
+        }
+        try {
+            FamilyMember fm = familyMemberMapper.selectById(memberId);
+            return fm != null && fm.getFamilyId() != null && !familyId.equals(fm.getFamilyId());
+        } catch (Exception e) {
+            log.warn("发放能量归属校验查询 family_members 异常 memberId={}: {}", memberId, e.getMessage());
+            return false;
+        }
+    }
+
     /**
     /**
      * SC-P-19 energy.dimension.view:只读查询五维配置(身/心/智/行/富定义与权重)。
      * SC-P-19 energy.dimension.view:只读查询五维配置(身/心/智/行/富定义与权重)。
      *
      *
@@ -2302,6 +2330,23 @@ public class EnergyService {
     @Transactional
     @Transactional
     public void configureSourceRatios(String sourceType, Long sourceId, String sourceName,
     public void configureSourceRatios(String sourceType, Long sourceId, String sourceName,
                                       List<Map<String, Object>> ratios) {
                                       List<Map<String, Object>> ratios) {
+        // SC-P-92 / energy.admin.adjust:比例之和必须为 100%,校验必须在任何写操作之前,
+        // 否则会先 delete 旧配置再写入非法配置(TC-P-92-E)。
+        int total = 0;
+        if (ratios == null || ratios.isEmpty()) {
+            throw new IllegalArgumentException("来源比例不能为空");
+        }
+        for (Map<String, Object> r : ratios) {
+            Object raw = r == null ? null : r.get("ratio");
+            if (raw == null) {
+                throw new IllegalArgumentException("来源比例不能为空");
+            }
+            total += Integer.parseInt(raw.toString());
+        }
+        if (total != 100) {
+            throw new IllegalArgumentException("来源比例之和必须为100%,当前为" + total + "%");
+        }
+
         energySourceConfigMapper.delete(
         energySourceConfigMapper.delete(
                 new LambdaQueryWrapper<EnergySourceConfig>()
                 new LambdaQueryWrapper<EnergySourceConfig>()
                         .eq(EnergySourceConfig::getSourceType, sourceType)
                         .eq(EnergySourceConfig::getSourceType, sourceType)
@@ -2335,6 +2380,19 @@ public class EnergyService {
      */
      */
     @Transactional
     @Transactional
     public EnergyLog grantEnergy(Long memberId, Long taskId, Long amount, String dimensionCode) {
     public EnergyLog grantEnergy(Long memberId, Long taskId, Long amount, String dimensionCode) {
+        return grantEnergy(memberId, taskId, amount, dimensionCode, null, null);
+    }
+
+    /**
+     * SC-P-89 / energy.admin.adjust:发放能量(任务奖励 或 家长/运营手动调整)。
+     *
+     * <p>无 taskId 且带备注/工单号时按 {@code sourceType=manual} 留痕,备注写入流水描述;
+     * 带 taskId 时保持既有 {@code sourceType=task} 语义不变(EnergyGrantContractTest 不受影响)。
+     * 带工单号时按工单号幂等:重复提交直接返回首次结果,不重复写流水。</p>
+     */
+    @Transactional
+    public EnergyLog grantEnergy(Long memberId, Long taskId, Long amount, String dimensionCode,
+                                 String remark, String workOrderNo) {
         // CFC-EN-001 修复:grantEnergy 的维度由调用方显式指定,能量应直接发放到该维度。
         // CFC-EN-001 修复:grantEnergy 的维度由调用方显式指定,能量应直接发放到该维度。
         // 旧实现委托 awardEnergy("task"),命中 task_complete 行为配置(100% 分配到 action),
         // 旧实现委托 awardEnergy("task"),命中 task_complete 行为配置(100% 分配到 action),
         // 随后按请求的 dimensionCode 从分配结果取数,请求 body 维度时 balanceMap.get("body")=null
         // 随后按请求的 dimensionCode 从分配结果取数,请求 body 维度时 balanceMap.get("body")=null
@@ -2347,6 +2405,24 @@ public class EnergyService {
             throw new IllegalArgumentException("维度代码无效:" + dimensionCode);
             throw new IllegalArgumentException("维度代码无效:" + dimensionCode);
         }
         }
 
 
+        boolean manual = taskId == null;
+        String sourceType = manual ? "manual" : "task";
+        Long sourceId = manual ? null : taskId;
+        String description = manual
+                ? (remark != null && !remark.trim().isEmpty() ? remark : "手动调整")
+                : "任务奖励";
+
+        // 工单号幂等:同一工单号重复发放直接返回首次结果,不重复写流水(TC-P-89-E)
+        String workOrderKey = (workOrderNo != null && !workOrderNo.trim().isEmpty())
+                ? (memberId == null ? "" : memberId) + ":" + workOrderNo.trim() : null;
+        if (workOrderKey != null) {
+            EnergyLog cached = processedWorkOrders.get(workOrderKey);
+            if (cached != null) {
+                log.info("工单号重复发放,幂等返回首次结果: workOrderNo={}, memberId={}", workOrderNo, memberId);
+                return cached;
+            }
+        }
+
         Map<Long, Integer> allocations = new LinkedHashMap<>();
         Map<Long, Integer> allocations = new LinkedHashMap<>();
         allocations.put(dim.getId(), amount.intValue());
         allocations.put(dim.getId(), amount.intValue());
 
 
@@ -2358,8 +2434,8 @@ public class EnergyService {
         }
         }
 
 
         // 执行发放(更新余额 + 写流水 + 站内通知)
         // 执行发放(更新余额 + 写流水 + 站内通知)
-        Map<String, Integer> balanceMap = executeAward(memberId, "task", taskId,
-                amount.intValue(), "任务奖励", null, allocations);
+        Map<String, Integer> balanceMap = executeAward(memberId, sourceType, sourceId,
+                amount.intValue(), description, null, allocations);
 
 
         Integer energyAmount = balanceMap.get(dimensionCode);
         Integer energyAmount = balanceMap.get(dimensionCode);
         if (energyAmount == null || energyAmount <= 0) {
         if (energyAmount == null || energyAmount <= 0) {
@@ -2371,11 +2447,14 @@ public class EnergyService {
         energyLog.setMemberId(memberId);
         energyLog.setMemberId(memberId);
         energyLog.setDimensionId(dim.getId());
         energyLog.setDimensionId(dim.getId());
         energyLog.setAmount(energyAmount);
         energyLog.setAmount(energyAmount);
-        energyLog.setSourceType("task");
-        energyLog.setSourceId(taskId);
-        energyLog.setDescription("任务奖励");
+        energyLog.setSourceType(sourceType);
+        energyLog.setSourceId(sourceId);
+        energyLog.setDescription(description);
         energyLog.setCreatedAt(new Date());
         energyLog.setCreatedAt(new Date());
 
 
+        if (workOrderKey != null) {
+            processedWorkOrders.putIfAbsent(workOrderKey, energyLog);
+        }
         return energyLog;
         return energyLog;
     }
     }
 
 

+ 17 - 1
cfc-backend/src/main/java/com/etotem/cfc/service/impl/DimensionScoreServiceImpl.java

@@ -33,6 +33,7 @@ import java.math.BigDecimal;
 import java.math.RoundingMode;
 import java.math.RoundingMode;
 import java.text.SimpleDateFormat;
 import java.text.SimpleDateFormat;
 import java.util.*;
 import java.util.*;
+import java.util.concurrent.ConcurrentHashMap;
 import java.util.stream.Collectors;
 import java.util.stream.Collectors;
 
 
 @Slf4j
 @Slf4j
@@ -70,6 +71,13 @@ public class DimensionScoreServiceImpl implements DimensionScoreService {
     @Resource
     @Resource
     private DimensionEnergySyncService dimensionEnergySyncService;
     private DimensionEnergySyncService dimensionEnergySyncService;
 
 
+    /**
+     * SC-P-91 / energy.admin.adjust:报告确认刷新的幂等台账(memberId:reportId)。
+     * 同一报告重复确认入库时不重复写同一维度的分数。
+     * 声明为 final,避免契约单测的 injectAll 反射替换导致去重失效。
+     */
+    private final Set<String> refreshedReports = ConcurrentHashMap.newKeySet();
+
     /**
     /**
      * 统一维度体系中 7 个身体健康子维度(code=body.growth...body.exercise),来源为注册中心
      * 统一维度体系中 7 个身体健康子维度(code=body.growth...body.exercise),来源为注册中心
      * body 根节点子维度(nodeKind=sub),替代原前端/后端硬编码裸名单(growth/sleep/...)。
      * body 根节点子维度(nodeKind=sub),替代原前端/后端硬编码裸名单(growth/sleep/...)。
@@ -379,8 +387,16 @@ public class DimensionScoreServiceImpl implements DimensionScoreService {
     @Override
     @Override
     @Transactional
     @Transactional
     public void refreshFromGutReport(Long memberId, Long reportId) {
     public void refreshFromGutReport(Long memberId, Long reportId) {
+        // SC-P-91 / TC-P-91-E:同一报告重复确认入库只刷新一次,避免对同一维度重复写分
+        String key = (memberId == null ? "" : memberId) + ":" + (reportId == null ? "" : reportId);
+        if (!refreshedReports.add(key)) {
+            return;
+        }
         HealthReport report = healthReportService.getReportById(reportId);
         HealthReport report = healthReportService.getReportById(reportId);
-        if (report == null) return;
+        if (report == null) {
+            refreshedReports.remove(key);
+            return;
+        }
         applyReportScores(memberId, report, reportId);
         applyReportScores(memberId, report, reportId);
     }
     }