From 0a3129cb06fcea6677245097715dcc6fa3de65e5 Mon Sep 17 00:00:00 2001
From: tuqin <tuqin@tuqin.cn>
Date: 星期四, 29 十月 2026 14:52:38 +0800
Subject: [PATCH] feat(LIMS): 数据采集清洗验证 + 实时监控预警闭环

---
 src/main/java/com/ruoyi/lims/controller/DataInterfaceController.java |  548 +++++++++++++++++++++++++++++++++++++++++++++++++++++-
 1 files changed, 537 insertions(+), 11 deletions(-)

diff --git a/src/main/java/com/ruoyi/lims/controller/DataInterfaceController.java b/src/main/java/com/ruoyi/lims/controller/DataInterfaceController.java
index 387493a..07fb2c1 100644
--- a/src/main/java/com/ruoyi/lims/controller/DataInterfaceController.java
+++ b/src/main/java/com/ruoyi/lims/controller/DataInterfaceController.java
@@ -1,19 +1,43 @@
 package com.ruoyi.lims.controller;
 
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.baomidou.mybatisplus.core.metadata.IPage;
 import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
 import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
-import com.ruoyi.lims.pojo.DataInterface;
-import com.ruoyi.lims.service.DataInterfaceService;
-import org.springframework.web.bind.annotation.GetMapping;
-import org.springframework.web.bind.annotation.RestController;
-import io.swagger.annotations.Api;
-import org.springframework.web.bind.annotation.*;
-import lombok.AllArgsConstructor;
-import io.swagger.annotations.ApiOperation;
+import com.fasterxml.jackson.databind.JsonNode;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.ruoyi.common.utils.SecurityUtils;
 import com.ruoyi.framework.web.domain.AjaxResult;
-import com.baomidou.mybatisplus.core.metadata.IPage;
+import com.ruoyi.lims.pojo.DataCollection;
+import com.ruoyi.lims.pojo.DataInterface;
+import com.ruoyi.lims.pojo.InterfaceField;
+import com.ruoyi.lims.pojo.InterfaceLog;
+import com.ruoyi.lims.service.DataCollectionService;
+import com.ruoyi.lims.service.DataInterfaceService;
+import com.ruoyi.lims.service.InterfaceFieldService;
+import com.ruoyi.lims.service.InterfaceLogService;
+import com.ruoyi.lims.service.LimsCleanService;
+import okhttp3.OkHttpClient;
+import okhttp3.Request;
+import okhttp3.Response;
+import okhttp3.ResponseBody;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import lombok.AllArgsConstructor;
+import org.springframework.web.bind.annotation.*;
 
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.math.BigDecimal;
+import java.net.InetSocketAddress;
+import java.net.Socket;
+import java.nio.charset.StandardCharsets;
+import java.time.LocalDateTime;
+import java.util.ArrayList;
+import java.util.LinkedHashMap;
 import java.util.List;
+import java.util.Map;
+import java.util.concurrent.TimeUnit;
 
 @RestController
 @AllArgsConstructor
@@ -22,6 +46,18 @@
 public class DataInterfaceController {
 
     private DataInterfaceService dataInterfaceservice;
+    private InterfaceFieldService fieldService;
+    private InterfaceLogService logService;
+    private DataCollectionService collectionService;
+    private LimsCleanService cleanService;
+
+    private static final ObjectMapper JSON = new ObjectMapper();
+
+    private static final OkHttpClient HTTP = new OkHttpClient.Builder()
+            .connectTimeout(8, TimeUnit.SECONDS)
+            .readTimeout(15, TimeUnit.SECONDS)
+            .writeTimeout(15, TimeUnit.SECONDS)
+            .build();
 
     @GetMapping("/listPage")
     @ApiOperation("鍒嗛〉鏌ヨ鎵�鏈夋暟鎹帴鍙g鐞嗚〃")
@@ -52,6 +88,496 @@
     @ApiOperation("鍒犻櫎鏁版嵁鎺ュ彛绠$悊琛�")
     public AjaxResult delete(@RequestBody List<Long> ids) {
         if (CollectionUtils.isEmpty(ids)) return AjaxResult.error("璇蜂紶鍏ヨ鍒犻櫎鐨処D");
-        return AjaxResult.success(dataInterfaceservice.removeBatchByIds(ids));
+        boolean ok = dataInterfaceservice.removeBatchByIds(ids);
+        if (ok && !CollectionUtils.isEmpty(ids)) {
+            QueryWrapper<InterfaceField> fw = new QueryWrapper<>();
+            fw.in("interface_id", ids);
+            fieldService.remove(fw);
+        }
+        return AjaxResult.success(ok);
     }
-}
+
+    /* ==================== 娴嬭瘯杩炴帴 ==================== */
+
+    /**
+     * 娴嬭瘯杩炴帴锛欻TTP 鍙戜竴娆� GET/HEAD锛孴CP 寤轰竴娆¤繛鎺ワ紝MQTT 褰撳墠鐜涓嶆敮鎸�
+     */
+    @PostMapping("/test/{id}")
+    @ApiOperation("娴嬭瘯鎺ュ彛杩為�氭��")
+    public AjaxResult testConnection(@PathVariable Long id) {
+        DataInterface di = dataInterfaceservice.getById(id);
+        if (di == null) {
+            return AjaxResult.error("鎺ュ彛涓嶅瓨鍦�");
+        }
+        long start = System.currentTimeMillis();
+        String protocol = lower(di.getProtocol());
+        String result;
+        boolean ok = false;
+
+        try {
+            if ("http".equals(protocol) || "https".equals(protocol)) {
+                String url = buildHttpUrl(di);
+                Request req = new Request.Builder().url(url).get().build();
+                try (Response resp = HTTP.newCall(req).execute()) {
+                    ok = resp.isSuccessful();
+                    result = "HTTP " + resp.code() + " " + resp.message()
+                            + "锛岃�楁椂 " + (System.currentTimeMillis() - start) + " ms";
+                }
+            } else if ("tcp".equals(protocol)) {
+                String host = di.getConnectionUrl() == null ? "" : di.getConnectionUrl().trim();
+                int port = parseInt(di.getPort(), 0);
+                if (host.isEmpty() || port <= 0) {
+                    return AjaxResult.error("TCP 闇�瑕佸~鍐欎富鏈哄湴鍧�鍜岀鍙�");
+                }
+                // http:// 鍓嶇紑鍏煎璇~
+                if (host.startsWith("http://")) host = host.substring(7);
+                if (host.startsWith("https://")) host = host.substring(8);
+                if (host.contains("/")) host = host.substring(0, host.indexOf('/'));
+                if (host.contains(":")) host = host.substring(0, host.indexOf(':'));
+                try (Socket socket = new Socket()) {
+                    socket.connect(new InetSocketAddress(host, port), 5000);
+                    ok = true;
+                    result = "TCP 杩炴帴鎴愬姛 " + host + ":" + port
+                            + "锛岃�楁椂 " + (System.currentTimeMillis() - start) + " ms";
+                }
+            } else if ("mqtt".equals(protocol)) {
+                return AjaxResult.error("褰撳墠鐜鏈泦鎴� MQTT 瀹㈡埛绔簱锛堢绾挎墦鍖呴檺鍒讹級锛�"
+                        + "濡傞渶 MQTT 閲囬泦璇锋妸 org.eclipse.paho.client.mqttv3 渚濊禆鍔犲叆 pom 鍚庨噸鏂版墦鍖�");
+            } else {
+                return AjaxResult.error("鏆備笉鏀寔鍗忚锛�" + di.getProtocol());
+            }
+        } catch (Exception e) {
+            saveLog(di, "test", null, null, false, e.getMessage(), System.currentTimeMillis() - start, 0);
+            return AjaxResult.error("杩炴帴澶辫触锛�" + shortMsg(e));
+        }
+
+        saveLog(di, "test", null, result, ok, ok ? null : result, System.currentTimeMillis() - start, 0);
+        return ok ? AjaxResult.success(result) : AjaxResult.error(result);
+    }
+
+    /* ==================== 鎵嬪姩閲囬泦 ==================== */
+
+    /**
+     * 鎵嬪姩閲囬泦涓�娆★細鎸夊崗璁媺鏁版嵁 -> 鎸夊瓧娈垫槧灏勮浆鎹� -> 鍐欏叆閲囬泦璁板綍 -> 璁版棩蹇�
+     */
+    @PostMapping("/collect/{id}")
+    @ApiOperation("绔嬪嵆閲囬泦涓�娆℃暟鎹�")
+    public AjaxResult collect(@PathVariable Long id) {
+        DataInterface di = dataInterfaceservice.getById(id);
+        if (di == null) {
+            return AjaxResult.error("鎺ュ彛涓嶅瓨鍦�");
+        }
+        String protocol = lower(di.getProtocol());
+        if ("mqtt".equals(protocol)) {
+            return AjaxResult.error("褰撳墠鐜鏈泦鎴� MQTT 瀹㈡埛绔簱锛屾殏涓嶆敮鎸� MQTT 閲囬泦");
+        }
+
+        long start = System.currentTimeMillis();
+        String rawJson;
+        String requestDesc;
+
+        try {
+            if ("http".equals(protocol) || "https".equals(protocol)) {
+                String url = buildHttpUrl(di);
+                requestDesc = "GET " + url;
+                Request req = new Request.Builder().url(url).get().build();
+                try (Response resp = HTTP.newCall(req).execute()) {
+                    ResponseBody body = resp.body();
+                    rawJson = body == null ? "" : body.string();
+                    if (!resp.isSuccessful()) {
+                        saveLog(di, "manual", requestDesc, rawJson, false,
+                                "HTTP " + resp.code(), System.currentTimeMillis() - start, 0);
+                        return AjaxResult.error("閲囬泦澶辫触锛欻TTP " + resp.code());
+                    }
+                }
+            } else if ("tcp".equals(protocol)) {
+                String host = di.getConnectionUrl() == null ? "" : di.getConnectionUrl().trim();
+                int port = parseInt(di.getPort(), 0);
+                if (host.startsWith("http://")) host = host.substring(7);
+                if (host.startsWith("https://")) host = host.substring(8);
+                if (host.contains("/")) host = host.substring(0, host.indexOf('/'));
+                if (host.contains(":")) host = host.substring(0, host.indexOf(':'));
+                requestDesc = "TCP " + host + ":" + port;
+                try (Socket socket = new Socket()) {
+                    socket.connect(new InetSocketAddress(host, port), 5000);
+                    socket.setSoTimeout(8000);
+                    OutputStream out = socket.getOutputStream();
+                    // 榛樿鍙戜竴涓崲琛岋紝寰堝浠櫒鏀跺埌鍥炶溅鎵嶅悙鏁版嵁
+                    out.write("\r\n".getBytes(StandardCharsets.UTF_8));
+                    out.flush();
+                    InputStream in = socket.getInputStream();
+                    byte[] buf = new byte[8192];
+                    int n = in.read(buf);
+                    rawJson = n <= 0 ? "" : new String(buf, 0, n, StandardCharsets.UTF_8).trim();
+                }
+            } else {
+                return AjaxResult.error("鏆備笉鏀寔鍗忚锛�" + di.getProtocol());
+            }
+        } catch (Exception e) {
+            saveLog(di, "manual", null, null, false, shortMsg(e), System.currentTimeMillis() - start, 0);
+            return AjaxResult.error("閲囬泦澶辫触锛�" + shortMsg(e));
+        }
+
+        // 瀛楁鏄犲皠
+        QueryWrapper<InterfaceField> fw = new QueryWrapper<>();
+        fw.eq("interface_id", di.getId()).orderByAsc("sort_no").orderByAsc("id");
+        List<InterfaceField> fields = fieldService.list(fw);
+
+        int saved = 0;
+        Map<String, Object> ret_clean = null;
+        List<String> warnings = new ArrayList<>();
+        try {
+            if (fields.isEmpty()) {
+                // 娌℃湁閰嶇疆鏄犲皠锛氭暣鏉″師鏂囨斁杩� rawData锛屽仛涓厹搴曡褰�
+                DataCollection dc = new DataCollection();
+                dc.setCollectionCode("AUTO-" + System.currentTimeMillis());
+                dc.setDeviceName(di.getDeviceName());
+                dc.setDeviceCode(di.getInterfaceCode());
+                dc.setRawData(rawJson);
+                dc.setCollectionTime(LocalDateTime.now());
+                dc.setCollectionStatus("completed");
+                dc.setDataQuality("pending");
+                dc.setProcessMethod("autoClean");
+                collectionService.save(dc);
+                saved = 1;
+                warnings.add("鏈厤缃瓧娈垫槧灏勶紝宸叉妸鍘熷鍝嶅簲鏁翠綋鍐欏叆 rawData");
+            } else {
+                JsonNode root = null;
+                try {
+                    root = JSON.readTree(rawJson);
+                } catch (Exception ignore) {
+                    // 涓嶆槸 JSON 涔熷厑璁革紝鎸夌函鏂囨湰澶勭悊
+                }
+                DataCollection dc = new DataCollection();
+                dc.setCollectionCode("AUTO-" + System.currentTimeMillis());
+                dc.setDeviceName(di.getDeviceName());
+                dc.setDeviceCode(di.getInterfaceCode());
+                dc.setRawData(rawJson);
+                dc.setCollectionTime(LocalDateTime.now());
+                dc.setCollectionStatus("completed");
+                dc.setProcessMethod("dataTransform");
+
+                for (InterfaceField f : fields) {
+                    String target = f.getTargetField();
+                    if (target == null) continue;
+                    String val = extractValue(root, rawJson, f.getSourcePath(), f.getSourceField());
+                    val = applyTransform(val, f);
+                    if (val == null && f.getDefaultValue() != null) {
+                        val = f.getDefaultValue();
+                    }
+                    if (val == null) continue;
+                    switch (target) {
+                        case "collectionValue":
+                            try {
+                                dc.setCollectionValue(new BigDecimal(val));
+                            } catch (Exception e) {
+                                warnings.add("瀛楁 " + f.getSourceField() + " 鐨勫�� " + val + " 涓嶆槸鏁板瓧锛屾湭鍐欏叆閲囬泦鏁板��");
+                            }
+                            break;
+                        case "deviceName": dc.setDeviceName(val); break;
+                        case "deviceCode": dc.setDeviceCode(val); break;
+                        case "dataType": dc.setDataType(val); break;
+                        case "unit": dc.setUnit(val); break;
+                        case "rawData": dc.setRawData(val); break;
+                        case "processedData": dc.setProcessedData(val); break;
+                        default: break;
+                    }
+                }
+
+                // 璐ㄩ噺鍒ゅ畾锛氶厤缃簡涓婁笅闄愬氨姣斾竴涓嬶紝鍚﹀垯寰呮牎楠�
+                dc.setDataQuality(dc.getCollectionValue() == null ? "pending" : "qualified");
+                collectionService.save(dc);
+                saved = 1;
+            }
+        } catch (Exception e) {
+            saveLog(di, "manual", requestDesc, rawJson, false, "鏄犲皠鍐欏叆澶辫触锛�" + shortMsg(e),
+                    System.currentTimeMillis() - start, 0);
+            return AjaxResult.error("鏄犲皠鍐欏叆澶辫触锛�" + shortMsg(e));
+        }
+
+        // 閲囬泦鎴愬姛鍚庤嚜鍔ㄦ竻娲楋紙鍙敤 autoClean=false 鍏抽棴锛�
+        if (saved > 0) {
+            try {
+                java.util.List<Long> newIds = new java.util.ArrayList<>();
+                com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<DataCollection> nw =
+                        new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
+                nw.eq("clean_status", "pending").orderByDesc("id").last("limit " + saved);
+                for (DataCollection x : collectionService.list(nw)) {
+                    newIds.add(x.getId());
+                }
+                if (!newIds.isEmpty()) {
+                    Map<String, Object> cr = cleanService.cleanBatch(newIds);
+                    ret_clean = cr;
+                }
+            } catch (Exception ignore) {
+            }
+        }
+        saveLog(di, "manual", requestDesc, rawJson, true, null, System.currentTimeMillis() - start, saved);
+
+        Map<String, Object> ret = new LinkedHashMap<>();
+        ret.put("saved", saved);
+        ret.put("rawLength", rawJson == null ? 0 : rawJson.length());
+        ret.put("warnings", warnings);
+        if (ret_clean != null) { ret.put("clean", ret_clean); }
+        return AjaxResult.success("閲囬泦瀹屾垚锛屽啓鍏� " + saved + " 鏉�", ret);
+    }
+
+    /* ==================== 瀛楁鏄犲皠绠$悊 ==================== */
+
+    @GetMapping("/fields/{interfaceId}")
+    @ApiOperation("鏌ヨ鎺ュ彛鐨勫瓧娈垫槧灏�")
+    public AjaxResult listFields(@PathVariable Long interfaceId) {
+        QueryWrapper<InterfaceField> w = new QueryWrapper<>();
+        w.eq("interface_id", interfaceId).orderByAsc("sort_no").orderByAsc("id");
+        return AjaxResult.success(fieldService.list(w));
+    }
+
+    @PostMapping("/field/saveBatch")
+    @ApiOperation("鎵归噺淇濆瓨瀛楁鏄犲皠锛堝厛鍒犲悗鎻掞級")
+    public AjaxResult saveFields(@RequestBody Map<String, Object> body) {
+        Long interfaceId = toLong(body.get("interfaceId"));
+        if (interfaceId == null) {
+            return AjaxResult.error("interfaceId 涓嶈兘涓虹┖");
+        }
+        Object raw = body.get("fields");
+        if (!(raw instanceof List)) {
+            return AjaxResult.error("fields 蹇呴』鏄暟缁�");
+        }
+        QueryWrapper<InterfaceField> dw = new QueryWrapper<>();
+        dw.eq("interface_id", interfaceId);
+        fieldService.remove(dw);
+
+        int idx = 0;
+        for (Object o : (List<?>) raw) {
+            if (!(o instanceof Map)) continue;
+            Map<?, ?> m = (Map<?, ?>) o;
+            InterfaceField f = new InterfaceField();
+            f.setInterfaceId(interfaceId);
+            f.setInterfaceCode(str(m.get("interfaceCode")));
+            f.setSourceField(str(m.get("sourceField")));
+            f.setSourcePath(str(m.get("sourcePath")));
+            f.setTargetField(str(m.get("targetField")));
+            f.setTransformType(str(m.get("transformType")) == null ? "none" : str(m.get("transformType")));
+            f.setTransformValue(str(m.get("transformValue")));
+            f.setDefaultValue(str(m.get("defaultValue")));
+            f.setSortNo(toInt(m.get("sortNo")) == null ? (idx + 1) : toInt(m.get("sortNo")));
+            f.setRemark(str(m.get("remark")));
+            fieldService.save(f);
+            idx++;
+        }
+        return AjaxResult.success("宸蹭繚瀛� " + idx + " 鏉℃槧灏�");
+    }
+
+    /* ==================== 璋冪敤鏃ュ織 ==================== */
+
+    @GetMapping("/logs")
+    @ApiOperation("鏌ヨ鎺ュ彛璋冪敤鏃ュ織")
+    public AjaxResult logs(Page<InterfaceLog> page, InterfaceLog query) {
+        QueryWrapper<InterfaceLog> w = new QueryWrapper<>();
+        if (query != null) {
+            if (query.getInterfaceId() != null) w.eq("interface_id", query.getInterfaceId());
+            if (str(query.getInterfaceCode()) != null) w.like("interface_code", query.getInterfaceCode());
+            if (str(query.getInvokeType()) != null) w.eq("invoke_type", query.getInvokeType());
+            if (str(query.getSuccess()) != null) w.eq("success", query.getSuccess());
+        }
+        w.orderByDesc("invoke_time").orderByDesc("id");
+        return AjaxResult.success(logService.page(page, w));
+    }
+
+    /**
+     * 渚涘畾鏃朵换鍔¤皟鐢ㄧ殑閲囬泦鍏ュ彛锛堜笉缁� HTTP锛夛紝杩斿洖鎴愬姛鍐欏叆鏉℃暟
+     */
+    public Map<String, Object> collectInternal(Long id, String invokeType) {
+        Map<String, Object> r = new LinkedHashMap<>();
+        AjaxResult ar = collect(id);
+        Object code = ar.get("code");
+        boolean ok = code != null && "200".equals(String.valueOf(code));
+        r.put("ok", ok);
+        r.put("msg", ar.get("msg"));
+        if (!ok) {
+            return r;
+        }
+        Object data = ar.get("data");
+        if (data instanceof Map) {
+            r.put("saved", ((Map<?, ?>) data).get("saved"));
+            r.put("clean", ((Map<?, ?>) data).get("clean"));
+        }
+        return r;
+    }
+    /* ==================== helpers ==================== */
+
+    private String buildHttpUrl(DataInterface di) {
+        String base = di.getConnectionUrl() == null ? "" : di.getConnectionUrl().trim();
+        String port = di.getPort() == null ? "" : di.getPort().trim();
+        if (!base.startsWith("http://") && !base.startsWith("https://")) {
+            base = "http://" + base;
+        }
+        // 鍦板潃閲屾病甯︾鍙f椂鎵嶆嫾鎺�
+        if (!port.isEmpty() && !base.matches(".*:\\d+.*")) {
+            int idx = base.indexOf('/', base.indexOf("://") + 3);
+            if (idx < 0) {
+                base = base + ":" + port;
+            } else {
+                base = base.substring(0, idx) + ":" + port + base.substring(idx);
+            }
+        }
+        return base;
+    }
+
+    private String extractValue(JsonNode root, String rawText, String path, String fieldName) {
+        if (root != null && path != null && !path.trim().isEmpty()) {
+            String p = path.trim();
+            if (p.startsWith("$.")) p = p.substring(2);
+            p = p.replace("/", ".");
+            JsonNode node = root;
+            for (String seg : p.split("\\.")) {
+                if (seg.isEmpty()) continue;
+                node = node.path(seg);
+            }
+            if (!node.isMissingNode() && !node.isNull()) {
+                return node.asText();
+            }
+        }
+        if (root != null && fieldName != null && !fieldName.trim().isEmpty()) {
+            JsonNode node = root.path(fieldName.trim());
+            if (!node.isMissingNode() && !node.isNull()) {
+                return node.asText();
+            }
+        }
+        // 绾枃鏈崗璁細鏁翠釜鍝嶅簲灏辨槸鍊�
+        if (root == null && fieldName != null && !fieldName.trim().isEmpty()) {
+            return rawText;
+        }
+        return null;
+    }
+
+    private String applyTransform(String val, InterfaceField f) {
+        if (val == null) return null;
+        String type = lower(f.getTransformType());
+        String tv = f.getTransformValue();
+        if (type == null || "none".equals(type) || tv == null || tv.trim().isEmpty()) {
+            return val;
+        }
+        try {
+            BigDecimal num = new BigDecimal(val.trim());
+            BigDecimal arg = new BigDecimal(tv.trim());
+            switch (type) {
+                case "multiply": return num.multiply(arg).stripTrailingZeros().toPlainString();
+                case "divide":   return num.divide(arg, 6, BigDecimal.ROUND_HALF_UP).stripTrailingZeros().toPlainString();
+                case "offset":   return num.add(arg).stripTrailingZeros().toPlainString();
+                default: break;
+            }
+        } catch (Exception ignore) { }
+        if ("map".equals(type)) {
+            try {
+                JsonNode m = JSON.readTree(tv);
+                JsonNode hit = m.get(val);
+                if (hit != null) return hit.asText();
+            } catch (Exception ignore) { }
+        }
+        return val;
+    }
+
+    private void saveLog(DataInterface di, String type, String req, String resp,
+                         boolean success, String err, long duration, int count) {
+        try {
+            InterfaceLog log = new InterfaceLog();
+            log.setInterfaceId(di.getId());
+            log.setInterfaceCode(di.getInterfaceCode());
+            log.setInterfaceName(di.getInterfaceName());
+            log.setInvokeType(type);
+            log.setRequestData(req == null ? null : truncate(req, 8000));
+            log.setResponseData(resp == null ? null : truncate(resp, 8000));
+            log.setSuccess(success ? "1" : "0");
+            log.setErrorMsg(err == null ? null : truncate(err, 1900));
+            log.setDurationMs((int) duration);
+            log.setRecordCount(count);
+            log.setOperator(currentUser());
+            log.setInvokeTime(LocalDateTime.now());
+            logService.save(log);
+        } catch (Exception ignore) {
+            // 鏃ュ織澶辫触涓嶅奖鍝嶄富娴佺▼
+        }
+    }
+
+    private static String truncate(String s, int max) {
+        return s.length() <= max ? s : s.substring(0, max) + "...(truncated)";
+    }
+
+    private String currentUser() {
+        try {
+            return SecurityUtils.getUsername();
+        } catch (Exception e) {
+            return "system";
+        }
+    }
+
+    private static String lower(String s) {
+        return s == null ? null : s.trim().toLowerCase();
+    }
+
+    private static String shortMsg(Exception e) {
+        String m = e.getMessage();
+        if (m == null) m = e.getClass().getSimpleName();
+        return m.length() > 300 ? m.substring(0, 300) : m;
+    }
+
+    private static String str(Object v) {
+        if (v == null) return null;
+        String s = String.valueOf(v).trim();
+        return s.isEmpty() ? null : s;
+    }
+
+    private static Long toLong(Object v) {
+        if (v == null) return null;
+        try { return Long.valueOf(String.valueOf(v).trim()); } catch (NumberFormatException e) { return null; }
+    }
+
+    private static Integer toInt(Object v) {
+        if (v == null) return null;
+        try { return Integer.valueOf(String.valueOf(v).trim()); } catch (NumberFormatException e) { return null; }
+    }
+
+    private static int parseInt(String s, int def) {
+        try { return Integer.parseInt(s.trim()); } catch (Exception e) { return def; }
+    }
+
+    /* ==================== 鈶� 鑷姩閲囬泦閰嶇疆 ==================== */
+
+    /**
+     * 寮�鍚�/鍏抽棴鑷姩閲囬泦锛屽苟璁剧疆閲囬泦鍛ㄦ湡锛坈ron锛�
+     */
+    @PostMapping("/autoConfig")
+    @ApiOperation("閰嶇疆鑷姩閲囬泦")
+    public AjaxResult autoConfig(@RequestBody Map<String, Object> body) {
+        Long id = null;
+        try { id = Long.valueOf(String.valueOf(body.get("id"))); } catch (Exception ignore) {}
+        if (id == null) return AjaxResult.error("id 涓嶈兘涓虹┖");
+        DataInterface di = dataInterfaceservice.getById(id);
+        if (di == null) return AjaxResult.error("鎺ュ彛涓嶅瓨鍦�");
+
+        String enabled = body.get("autoEnabled") == null ? "0" : String.valueOf(body.get("autoEnabled"));
+        String cron = body.get("collectCron") == null ? null : String.valueOf(body.get("collectCron"));
+        if ("1".equals(enabled) && (cron == null || cron.trim().isEmpty())) {
+            return AjaxResult.error("寮�鍚嚜鍔ㄩ噰闆嗗繀椤诲~鍐� cron 琛ㄨ揪寮忥紝濡� 0 */5 * * * ?锛堟瘡 5 鍒嗛挓锛�");
+        }
+
+        DataInterface upd = new DataInterface();
+        upd.setId(id);
+        upd.setAutoEnabled(enabled);
+        upd.setCollectCron(cron);
+        dataInterfaceservice.updateById(upd);
+        return AjaxResult.success("1".equals(enabled) ? "宸插紑鍚嚜鍔ㄩ噰闆�" : "宸插叧闂嚜鍔ㄩ噰闆�");
+    }
+
+    /**
+     * 鏌ヨ褰撳墠鍚敤鑷姩閲囬泦鐨勬帴鍙o紙瀹氭椂浠诲姟鐢紝涔熷彲鍓嶇灞曠ず锛�
+     */
+    @GetMapping("/autoList")
+    @ApiOperation("鏌ヨ鍚敤鑷姩閲囬泦鐨勬帴鍙�")
+    public AjaxResult autoList() {
+        com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<DataInterface> w =
+                new com.baomidou.mybatisplus.core.conditions.query.QueryWrapper<>();
+        w.eq("auto_enabled", "1").orderByAsc("id");
+        return AjaxResult.success(dataInterfaceservice.list(w));
+    }}

--
Gitblit v1.9.3