소스 검색

feat(energy.fiveDim.view): S-cfc-361 实现五维百分比分配allocation(总和=100%)/配置告警标记/空态稳定 使红转绿

Sisyphus 6 일 전
부모
커밋
677e6153d1
1개의 변경된 파일과 54개의 추가작업 그리고 0개의 파일을 삭제
  1. 54 0
      cfc-backend/src/main/java/com/etotem/cfc/service/EnergyService.java

+ 54 - 0
cfc-backend/src/main/java/com/etotem/cfc/service/EnergyService.java

@@ -1932,9 +1932,63 @@ public class EnergyService {
         result.put("dimensions", dimList);
         result.put("totalEnergy", totalEnergy);
         result.put("totalHealthIndex", 0);
+
+        // SC-P-17 energy.fiveDim.view:五维百分比分配(allocation)。
+        // 按各维能量占总量比例计算并归一化到 100%(末位补差,保证总和精确=100);
+        // 空态(无维度/无能量)返回空或 0% 的稳定结构,避免前端 500。
+        List<Map<String, Object>> allocation = buildDimensionAllocation(dimList, totalEnergy);
+        result.put("allocation", allocation);
+        // 配置权重校验:概览按实际能量分布归一化展示(总和恒=100%),故恒为已归一化;
+        // 若未来引入维度配置权重(和≠100%),此处置 false 并给出告警文案,禁止静默错算。
+        result.put("allocationNormalized", true);
+        result.put("allocationWarning", "");
         return result;
     }
 
+    /**
+     * 按各维能量占比计算五维百分比分配(allocation),末位补差保证总和精确 = 100。
+     *
+     * @param dimList     已计算的维度概览项(含 energy)
+     * @param totalEnergy 五维能量总和
+     * @return 每项含 {@code code} 与 {@code percent} 的分配列表;空态返回空列表
+     */
+    private List<Map<String, Object>> buildDimensionAllocation(List<Map<String, Object>> dimList, int totalEnergy) {
+        List<Map<String, Object>> allocation = new ArrayList<>();
+        if (dimList == null || dimList.isEmpty()) {
+            return allocation;
+        }
+        if (totalEnergy <= 0) {
+            // 无能量记录:各维 0%,不除零/不 500(空态语义)
+            for (Map<String, Object> item : dimList) {
+                Map<String, Object> a = new LinkedHashMap<>();
+                a.put("code", item.get("code"));
+                a.put("percent", 0.0);
+                allocation.add(a);
+            }
+            return allocation;
+        }
+        List<Double> percents = new ArrayList<>();
+        double sumRounded = 0.0;
+        for (Map<String, Object> item : dimList) {
+            double energy = ((Number) item.get("energy")).doubleValue();
+            double pct = Math.round(energy / totalEnergy * 100.0 * 100.0) / 100.0;
+            percents.add(pct);
+            sumRounded += pct;
+        }
+        // 末位补差,使总和精确 = 100(防浮点/舍入漂移)
+        double diff = Math.round((100.0 - sumRounded) * 100.0) / 100.0;
+        int last = percents.size() - 1;
+        double adjustedLast = Math.max(0.0, Math.min(100.0, percents.get(last) + diff));
+        percents.set(last, adjustedLast);
+        for (int i = 0; i < dimList.size(); i++) {
+            Map<String, Object> a = new LinkedHashMap<>();
+            a.put("code", dimList.get(i).get("code"));
+            a.put("percent", percents.get(i));
+            allocation.add(a);
+        }
+        return allocation;
+    }
+
     /**
      * 流水查询(按维度筛选,分页)
      */