Browse Source

ranking: A23 电气柜温度支持 + 报告下载补齐 + 逐机判据对齐本机结论

- A23 加入 FUNCTION_CODES / ALG_KEYS 白名单,修复机组详情无数据
- criteriaRow 实际情况/判断标准/说明 对齐「本机结论」(result.display + reason)
- downloadReport 报告生成链路优化
liujiejie 2 hours ago
parent
commit
076414e9ec

+ 25 - 3
energy-manage-service/src/main/java/com/energy/manage/service/controller/ranking/RankingController.java

@@ -10,6 +10,8 @@ import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.web.bind.annotation.*;
 
+import javax.servlet.http.HttpServletResponse;
+import java.net.URLEncoder;
 import java.util.Map;
 
 /**
@@ -70,9 +72,29 @@ public class RankingController extends BaseServiceController {
         return ResultResp.FAIL("报告生成服务未就绪");
     }
 
-    @ApiOperation(value = "同步下载报告(未就绪)")
+    @ApiOperation(value = "同步下载报告")
     @PostMapping("/reports/download")
-    public ResultResp reportDownload(@RequestBody Map<String, Object> data) {
-        return ResultResp.FAIL("报告生成服务未就绪");
+    public void reportDownload(@RequestBody Map<String, Object> data, HttpServletResponse response) {
+        try {
+            Map<String, Object> result = rankingService.downloadReport(data);
+            if (result.containsKey("error")) {
+                response.setContentType("application/json;charset=utf-8");
+                response.getWriter().write("{\"code\":500,\"msg\":\"" + result.get("error") + "\"}");
+                return;
+            }
+            byte[] bytes = (byte[]) result.get("bytes");
+            String fileName = String.valueOf(result.get("fileName"));
+            response.setContentType(String.valueOf(result.get("contentType")));
+            response.setHeader("Content-Disposition",
+                    "attachment; filename*=UTF-8''" + URLEncoder.encode(fileName, "UTF-8").replace("+", "%20"));
+            response.getOutputStream().write(bytes);
+        } catch (Exception e) {
+            log.error("reportDownload error", e);
+            try {
+                response.setContentType("application/json;charset=utf-8");
+                response.getWriter().write("{\"code\":500,\"msg\":\"报告生成失败\"}");
+            } catch (Exception ignored) {
+            }
+        }
     }
 }

+ 3 - 0
energy-manage-service/src/main/java/com/energy/manage/service/domain/vo/ranking/RankingUnitVo.java

@@ -19,6 +19,9 @@ public class RankingUnitVo {
     /** 风机编号(冗余,= id) */
     private String no;
 
+    /** 风机名称 engine_name */
+    private String engineName;
+
     /** 所属风电场编号 */
     private String farmId;
 

+ 6 - 0
energy-manage-service/src/main/java/com/energy/manage/service/service/ranking/RankingService.java

@@ -28,4 +28,10 @@ public interface RankingService {
      * 报告元信息预览
      */
     Map<String, Object> getReportMeta(Map<String, Object> query);
+
+    /**
+     * 生成诊断月报文件。返回 { fileName, bytes, contentType };失败返回 { error }。
+     * query 字段:year / number / projectId / projectName / format(html|docx)
+     */
+    Map<String, Object> downloadReport(Map<String, Object> query);
 }

+ 109 - 6
energy-manage-service/src/main/java/com/energy/manage/service/service/ranking/impl/DiagnosisServiceImpl.java

@@ -54,7 +54,7 @@ public class DiagnosisServiceImpl implements DiagnosisService {
     /** 算法表路径列只允许这些功能编号,避免把请求参数拼进列名。 */
     private static final Set<String> FUNCTION_CODES = new HashSet<>(Arrays.asList(
             "A01", "A02", "A03", "A04", "A05", "A06", "A07", "A08", "A09", "A10", "A11", "A12",
-            "A13", "A14", "A15", "A16", "A17", "A18", "A19", "A20", "A21", "A22", "Y01", "Y02"));
+            "A13", "A14", "A15", "A16", "A17", "A18", "A19", "A20", "A21", "A22", "A23", "Y01", "Y02"));
 
     @Override
     public Map<String, Object> projectFunction(String fieldCode, String machineTypeCode,
@@ -112,15 +112,37 @@ public class DiagnosisServiceImpl implements DiagnosisService {
         }
         List<Map<String, Object>> criteria = new ArrayList<>();
         List<Map<String, Object>> turbines = new ArrayList<>();
-        resp.put("metrics", loadTurbineMetrics(fieldCode, machineTypeCode, month, functionCode, criteria, turbines));
+        List<Map<String, Object>> reviewClues = new ArrayList<>();
+        resp.put("metrics", loadTurbineMetrics(fieldCode, machineTypeCode, month, functionCode, criteria, turbines, reviewClues));
         Map<String, Object> table = new LinkedHashMap<>();
         table.put("id", "project_criteria_row");
+        table.put("columns", criteriaColumns());
         table.put("rows", criteria);
         resp.put("tables", Collections.singletonList(table));
         resp.put("turbines", turbines);
+        resp.put("reviewClues", reviewClues);
         return resp;
     }
 
+    /** 逐机判据表显示列(机组/机型/检测结果/实际情况/判断标准/说明) */
+    private List<Map<String, Object>> criteriaColumns() {
+        List<Map<String, Object>> cols = new ArrayList<>();
+        cols.add(col("engine_name", "机组"));
+        cols.add(col("machine_type_code", "机型"));
+        cols.add(col("status_label", "检测结果"));
+        cols.add(col("actual", "实际情况"));
+        cols.add(col("criterion", "判断标准"));
+        cols.add(col("explanation", "说明"));
+        return cols;
+    }
+
+    private Map<String, Object> col(String key, String label) {
+        Map<String, Object> c = new LinkedHashMap<>();
+        c.put("key", key);
+        c.put("label", label);
+        return c;
+    }
+
     @Override
     public Map<String, Object> turbineFunction(String fieldCode, String machineTypeCode,
                                                String month, String functionCode, String engineCode) {
@@ -379,7 +401,8 @@ public class DiagnosisServiceImpl implements DiagnosisService {
     private List<Map<String, Object>> loadTurbineMetrics(String fieldCode, String machineTypeCode,
                                                           String month, String functionCode,
                                                           List<Map<String, Object>> criteria,
-                                                          List<Map<String, Object>> turbines) {
+                                                          List<Map<String, Object>> turbines,
+                                                          List<Map<String, Object>> reviewClues) {
         List<Map<String, Object>> out = new ArrayList<>();
         String func = functionCode == null ? "" : functionCode.trim().toUpperCase();
         if (!FUNCTION_CODES.contains(func) || month == null || !month.matches("\\d{4}-\\d{2}")) {
@@ -388,20 +411,25 @@ public class DiagnosisServiceImpl implements DiagnosisService {
         String col = func.toLowerCase() + "_conclusion_txt_path";
         try {
             List<Map<String, Object>> rows = analyseJdbcTemplate.queryForList(
-                    "SELECT engine_code, " + col + " AS txt_path FROM turbine_monthly_result " +
+                    "SELECT engine_code, engine_name, " + col + " AS txt_path FROM turbine_monthly_result " +
                             "WHERE field_code = ? AND machine_type_code = ? AND period_start = ?",
                     fieldCode, machineTypeCode, month + "-01");
             for (Map<String, Object> row : rows) {
                 Object ec = row.get("engine_code");
+                Object en = row.get("engine_name");
                 Object path = row.get("txt_path");
                 if (ec == null || path == null) {
                     continue;
                 }
+                String engineName = en == null ? null : String.valueOf(en);
                 Map<String, Object> txt = GzlyTxtParser.parse(readByFullPath(String.valueOf(path)));
                 Map<String, Object> result = (Map<String, Object>) txt.get("result");
                 Map<String, Object> status = (Map<String, Object>) txt.get("status");
                 Map<String, Object> m = new LinkedHashMap<>();
                 m.put("engineCode", String.valueOf(ec));
+                if (engineName != null) {
+                    m.put("engineName", engineName);
+                }
                 m.put("value", result == null ? null : result.get("value"));
                 m.put("unit", result == null ? null : result.get("unit"));
                 m.put("status", status == null ? null : status.get("source_status"));
@@ -410,7 +438,7 @@ public class DiagnosisServiceImpl implements DiagnosisService {
                     m.put("metric", display.get("metric"));
                 }
                 out.add(m);
-                Map<String, Object> one = criteriaRow(txt, machineTypeCode, String.valueOf(ec));
+                Map<String, Object> one = criteriaRow(txt, machineTypeCode, String.valueOf(ec), engineName);
                 if (criteria != null && one != null) {
                     criteria.add(one);
                 }
@@ -419,11 +447,15 @@ public class DiagnosisServiceImpl implements DiagnosisService {
                     collectChannels(txt, channels, String.valueOf(ec));
                     Map<String, Object> turbine = new LinkedHashMap<>();
                     turbine.put("engineCode", String.valueOf(ec));
+                    if (engineName != null) {
+                        turbine.put("engineName", engineName);
+                    }
                     turbine.put("machineTypeCode", machineTypeCode);
                     turbine.put("criteria", one);
                     turbine.put("channels", channels);
                     turbines.add(turbine);
                 }
+                collectReviewClues(txt, String.valueOf(ec), engineName, reviewClues);
             }
         } catch (Exception e) {
             log.warn("loadTurbineMetrics failed for {} {} {}: {}",
@@ -432,6 +464,32 @@ public class DiagnosisServiceImpl implements DiagnosisService {
         return out;
     }
 
+    /** 从风机结论 TXT 的 result.review_clues 收集异常线索,并附上数据库 engine_code/engine_name。 */
+    @SuppressWarnings("unchecked")
+    private void collectReviewClues(Map<String, Object> txt, String engineCode, String engineName,
+                                    List<Map<String, Object>> out) {
+        if (txt == null || out == null) {
+            return;
+        }
+        Map<String, Object> result = (Map<String, Object>) txt.get("result");
+        if (result == null || !(result.get("review_clues") instanceof List)) {
+            return;
+        }
+        for (Object item : (List<?>) result.get("review_clues")) {
+            if (!(item instanceof Map)) {
+                continue;
+            }
+            Map<String, Object> clue = new LinkedHashMap<>((Map<String, Object>) item);
+            if (clue.get("engine_code") == null) {
+                clue.put("engine_code", engineCode);
+            }
+            if (clue.get("engine_name") == null) {
+                clue.put("engine_name", engineName);
+            }
+            out.add(clue);
+        }
+    }
+
     /** 从风机 TXT 收集温度矩阵单元格。行对象、按通道代码嵌套的对象、列式数组都收。 */
     private void collectChannels(Object node, List<Map<String, Object>> out, String engine) {
         if (node instanceof Map) {
@@ -592,7 +650,7 @@ public class DiagnosisServiceImpl implements DiagnosisService {
     }
 
     /** 一台风机的结论 TXT 收成逐机表的一行。没有检测结果和实际情况时不造行。 */
-    private Map<String, Object> criteriaRow(Map<String, Object> parsed, String machineTypeCode, String engineCode) {
+    private Map<String, Object> criteriaRow(Map<String, Object> parsed, String machineTypeCode, String engineCode, String engineName) {
         if (parsed == null || parsed.isEmpty()) {
             return null;
         }
@@ -604,12 +662,30 @@ public class DiagnosisServiceImpl implements DiagnosisService {
         String actualLabel = firstString(parsed, "actual_label");
         String criterion = firstString(parsed, "criterion");
         String explanation = firstString(parsed, "explanation");
+        // 对齐机组详情「本机结论」展示:实际情况取「名称:数值」,判断标准取 result.display.threshold,说明取 result.reason / conclusion.text
+        if (actual == null) {
+            actual = joinLabelValue(
+                    nestedString(parsed, "result", "display", "metric_label"),
+                    nestedString(parsed, "result", "display", "metric"));
+        }
+        if (criterion == null) {
+            criterion = nestedString(parsed, "result", "display", "threshold");
+        }
+        if (explanation == null) {
+            explanation = nestedString(parsed, "result", "reason");
+            if (explanation == null) {
+                explanation = nestedString(parsed, "conclusion", "text");
+            }
+        }
         if (status == null && actual == null && criterion == null && explanation == null) {
             return null;
         }
         Map<String, Object> row = new LinkedHashMap<>();
         String engine = firstString(parsed, "engine_code");
         row.put("engine_code", engine != null ? engine : engineCode);
+        if (engineName != null) {
+            row.put("engine_name", engineName);
+        }
         String model = firstString(parsed, "machine_type_code");
         row.put("machine_type_code", model != null ? model : machineTypeCode);
         row.put("status_label", status);
@@ -650,6 +726,33 @@ public class DiagnosisServiceImpl implements DiagnosisService {
         return null;
     }
 
+    /** 按固定路径读取嵌套字段(如 result -> display -> metric),返回字符串或 null。 */
+    private String nestedString(Object node, String... path) {
+        Object cur = node;
+        for (String key : path) {
+            if (!(cur instanceof Map)) {
+                return null;
+            }
+            cur = ((Map<String, Object>) cur).get(key);
+        }
+        if (cur instanceof String || cur instanceof Number || cur instanceof Boolean) {
+            String text = String.valueOf(cur).trim();
+            return text.isEmpty() ? null : text;
+        }
+        return null;
+    }
+
+    /** 把「名称」与「数值」拼成一行(如 需要复查的电气柜测点数:0测点)。 */
+    private String joinLabelValue(String label, String value) {
+        if (label == null || label.isEmpty()) {
+            return value;
+        }
+        if (value == null || value.isEmpty()) {
+            return label;
+        }
+        return label + ":" + value;
+    }
+
     /**
      * 拼出浏览器可直接读取的完整地址。
      * 本机和内网访问使用 http://192.168.50.233:6900,外网访问使用 http://106.120.102.238:26900。

+ 85 - 1
energy-manage-service/src/main/java/com/energy/manage/service/service/ranking/impl/RankingServiceImpl.java

@@ -8,15 +8,19 @@ import com.energy.manage.service.service.ranking.RankingService;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.beans.factory.annotation.Value;
 import org.springframework.jdbc.core.JdbcTemplate;
 import org.springframework.stereotype.Service;
 import org.springframework.util.StringUtils;
 
+import java.io.File;
+import java.nio.file.Files;
 import java.util.ArrayList;
 import java.util.Collections;
 import java.util.HashMap;
 import java.util.List;
 import java.util.Map;
+import java.util.concurrent.TimeUnit;
 
 /**
  * 排名看板服务实现。
@@ -38,10 +42,18 @@ public class RankingServiceImpl implements RankingService {
     @Qualifier("analyseJdbcTemplate")
     private JdbcTemplate analyseJdbcTemplate;
 
+    /** 报告生成器 Python 解释器路径 */
+    @Value("${gzly.report.python:/usr/bin/python3}")
+    private String reportPython;
+
+    /** 报告生成器脚本路径 */
+    @Value("${gzly.report.script:/data/app-gzly/report/generate_report.py}")
+    private String reportScript;
+
     /** 24 项功能编号(turbine_monthly_result 的 {小写}_is_anomaly 列) */
     private static final String[] ALG_KEYS = {
             "A01", "A02", "A03", "A04", "A05", "A06", "A07", "A08", "A09", "A10", "A11", "A12",
-            "A13", "A14", "A15", "A16", "A17", "A18", "A19", "A20", "A21", "A22", "Y01", "Y02"};
+            "A13", "A14", "A15", "A16", "A17", "A18", "A19", "A20", "A21", "A22", "A23", "Y01", "Y02"};
 
     @Override
     public RankingBoardVo getCockpitBoard(Integer year, Integer number) {
@@ -96,6 +108,78 @@ public class RankingServiceImpl implements RankingService {
         return meta;
     }
 
+    @Override
+    public Map<String, Object> downloadReport(Map<String, Object> query) {
+        String py = reportPython;
+        String script = reportScript;
+        int year = toInt(query.get("year"), 2026);
+        int number = toInt(query.get("number"), 8);
+        String fieldCode = str(query.get("projectId"), "");
+        String projectName = str(query.get("projectName"), "");
+        String format = "docx".equalsIgnoreCase(str(query.get("format"), "docx")) ? "docx" : "html";
+        String outDir = "/tmp/report/" + System.currentTimeMillis();
+        try {
+            List<String> cmd = new ArrayList<>();
+            cmd.add(py);
+            cmd.add(script);
+            cmd.add("--year"); cmd.add(String.valueOf(year));
+            cmd.add("--month"); cmd.add(String.valueOf(number));
+            cmd.add("--field-code"); cmd.add(fieldCode);
+            cmd.add("--project-name"); cmd.add(projectName);
+            cmd.add("--out"); cmd.add(outDir);
+            cmd.add("--format"); cmd.add(format);
+            Process p = new ProcessBuilder(cmd).redirectErrorStream(true).start();
+            boolean done = p.waitFor(120, TimeUnit.SECONDS);
+            if (!done) {
+                p.destroyForcibly();
+                return err("报告生成超时");
+            }
+            String fileName = format.equals("html") ? "诊断月报.html" : "诊断月报.docx";
+            File f = new File(outDir, fileName);
+            if (!f.exists()) {
+                return err("报告生成失败:" + readProcessOutput(p));
+            }
+            Map<String, Object> out = new HashMap<>();
+            out.put("fileName", projectName + "_" + year + "年" + number + "月_功能诊断月报." + (format.equals("html") ? "html" : "docx"));
+            out.put("contentType", format.equals("html") ? "text/html;charset=utf-8" : "application/vnd.openxmlformats-officedocument.wordprocessingml.document");
+            out.put("bytes", Files.readAllBytes(f.toPath()));
+            return out;
+        } catch (Exception e) {
+            log.warn("downloadReport failed: {}", e.getMessage());
+            return err("报告生成失败:" + e.getMessage());
+        }
+    }
+
+    private Map<String, Object> err(String message) {
+        Map<String, Object> out = new HashMap<>();
+        out.put("error", message);
+        return out;
+    }
+
+    private int toInt(Object v, int def) {
+        if (v == null) return def;
+        try {
+            return Integer.parseInt(String.valueOf(v));
+        } catch (NumberFormatException e) {
+            return def;
+        }
+    }
+
+    private String str(Object v, String def) {
+        return v == null || String.valueOf(v).isEmpty() ? def : String.valueOf(v);
+    }
+
+    private String readProcessOutput(Process p) {
+        try {
+            java.io.InputStream is = p.getInputStream();
+            byte[] buf = new byte[4096];
+            int n = is.read(buf);
+            return n > 0 ? new String(buf, 0, n, "UTF-8") : "";
+        } catch (Exception e) {
+            return "";
+        }
+    }
+
     /**
      * 组装风电场列表,补齐派生字段。
      */

+ 1 - 0
energy-manage-service/src/main/resources/mybatis/windrelation/WindRelationMapper.xml

@@ -164,6 +164,7 @@
         SELECT
             weg.engine_code        AS id,
             weg.engine_code        AS no,
+            weg.engine_name        AS engineName,
             wf.company_code        AS farmId,
             weg.field_code         AS projectId,
             wem.machine_type_code  AS modelId,