From 3728fa293e1faf4bf4f9bf41105b84ddb43dc82e Mon Sep 17 00:00:00 2001
From: liding <756868258@qq.com>
Date: 星期一, 02 十一月 2026 16:53:02 +0800
Subject: [PATCH] feat(order-rates): 新增筛选条件下全部订单费用汇总接口

---
 inspect-server/src/main/java/com/ruoyi/inspect/service/impl/InsOrderPlanServiceImpl.java |  166 +++++++++++++++++++++++++++++++++----------------------
 1 files changed, 100 insertions(+), 66 deletions(-)

diff --git a/inspect-server/src/main/java/com/ruoyi/inspect/service/impl/InsOrderPlanServiceImpl.java b/inspect-server/src/main/java/com/ruoyi/inspect/service/impl/InsOrderPlanServiceImpl.java
index 9e1e3c2..74f8661 100644
--- a/inspect-server/src/main/java/com/ruoyi/inspect/service/impl/InsOrderPlanServiceImpl.java
+++ b/inspect-server/src/main/java/com/ruoyi/inspect/service/impl/InsOrderPlanServiceImpl.java
@@ -45,6 +45,7 @@
 import com.ruoyi.inspect.pojo.*;
 import com.ruoyi.inspect.service.*;
 import com.ruoyi.inspect.util.HackLoopTableRenderPolicy;
+import com.ruoyi.inspect.util.ReportResultTableRenderPolicy;
 import com.ruoyi.inspect.util.PreserveReportPicturePlaceholderHandler;
 import com.ruoyi.inspect.util.ReportSignaturePictureUtils;
 import com.ruoyi.inspect.vo.InsOrderPlanTaskSwitchVo;
@@ -359,6 +360,9 @@
                         "妯℃澘ID " + snapshot.getTemplateId());
                 if (snapshot.getDetectionTime() == null) {
                     collect.add("璇烽�夋嫨鈥�" + templateName + "鈥濈殑妫�娴嬫椂闂�");
+                } else if (snapshot.getDetectionEndTime() != null
+                        && snapshot.getDetectionEndTime().isBefore(snapshot.getDetectionTime())) {
+                    collect.add("鈥�" + templateName + "鈥濈殑妫�娴嬬粨鏉熸棩鏈熶笉鑳芥棭浜庡紑濮嬫棩鏈�");
                 }
                 if (StringUtils.isBlank(snapshot.getDetectionPlace())) {
                     collect.add("璇峰~鍐欌��" + templateName + "鈥濈殑妫�娴嬪湴鐐�");
@@ -602,11 +606,9 @@
         }
 
 
-        // 娣诲姞璁惧璁板綍
-        threadPoolTaskExecutor.execute(() -> {
-            // 娣诲姞璁惧浣跨敤璁板綍
-            addDeviceRecord(insSample, userId);
-        });
+        // 鍘熷璁板綍淇濆瓨鍚庯紝鎸夊綋鍓嶆ā鏉块�夌敤鐨勮澶囩敓鎴愪娇鐢ㄨ褰�
+        syncDeviceRecordsFromTemplate(saveInsContextDto.getOrderId(), saveInsContextDto.getSampleId(),
+                saveInsContextDto.getCurrentTable(), userId);
     }
 
     /**
@@ -689,6 +691,9 @@
                 .and(w -> w.isNull(InsProduct::getLastValue).or().eq(InsProduct::getLastValue, "")));
         sample.setInsState(unfinished == 0 ? 2 : 1);
         insSampleMapper.updateById(sample);
+
+        // 鍘熷璁板綍淇濆瓨鍚庯紝鎸夊綋鍓嶆ā鏉块�夌敤鐨勮澶囩敓鎴愪娇鐢ㄨ褰�
+        syncDeviceRecordsFromTemplate(dto.getOrderId(), dto.getSampleId(), dto.getTemplateId(), userId);
     }
 
     /**
@@ -1028,60 +1033,52 @@
         }
     }
 
-    private synchronized void addDeviceRecord(InsSample insSample, Integer userId) {
-        InsOrder order = insOrderMapper.selectById(insSample.getInsOrderId());
+    /**
+     * 鍘熷璁板綍淇濆瓨鍚庯紝鎸夊綋鍓嶆ā鏉块�夌敤鐨勮澶囩敓鎴愬緟濉啓鐨勪娇鐢ㄨ褰曘��
+     * 鍚屼竴璁㈠崟銆佹牱鍝併�佽澶囧彧鐢熸垚涓�鏉★紱宸茬粡濉啓杩囩殑璁板綍涓嶄細琚鐩栥��
+     */
+    private synchronized void syncDeviceRecordsFromTemplate(Integer orderId, Integer sampleId,
+                                                            Integer templateId, Integer userId) {
+        if (orderId == null || sampleId == null || templateId == null) {
+            return;
+        }
+        InsOrder order = insOrderMapper.selectById(orderId);
+        InsSample sample = insSampleMapper.selectById(sampleId);
+        if (order == null || sample == null) {
+            return;
+        }
+        List<Integer> deviceIds = insOrderTemplateDeviceMapper
+                .selectDeviceIdsByOrderAndTemplate(orderId, templateId);
+        if (CollectionUtils.isEmpty(deviceIds)) {
+            return;
+        }
         User user = userMapper.selectById(userId);
-        // 鏌ヨ璁惧浣跨敤璁板綍鏌ヨ璇ヨ鍗曠殑浣跨敤璁板綍
-        List<InsOrderDeviceRecordDto> deviceRecordDtoList = insOrderDeviceRecordMapper.selectDeviceNumber(insSample.getInsOrderId());
-        Set<String> recordCodeset = deviceRecordDtoList.stream().map(InsOrderDeviceRecordDto::getManagementNumber).collect(Collectors.toSet());
-
-        // 鑾峰彇璁㈠崟璁惧缂栧彿
-        List<InsProductResult> resultList = insProductResultMapper.selectResultByOrderId(insSample.getInsOrderId());
-        Set<String> deviceCodeSet = new HashSet<>();
-        for (InsProductResult result : resultList) {
-            // 娣诲姞璁惧缂栧彿
-            List<JSONObject> jsonObjects = JSON.parseArray(result.getEquipValue(), JSONObject.class);
-            for (JSONObject jsonObject : jsonObjects) {
-                if (!"".equals(jsonObject.get("v") + "")) {
-                    List<String> v = StrUtil.split(jsonObject.get("v") + "", "锛�");
-                    deviceCodeSet.addAll(v);
-                }
+        String usePerson = user == null ? "" : user.getName();
+        String sampleCode = StringUtils.isNotBlank(sample.getSampleCode())
+                ? sample.getSampleCode() : order.getEntrustCode();
+        for (Integer deviceId : deviceIds) {
+            if (deviceId == null) {
+                continue;
             }
+            Long count = insOrderDeviceRecordMapper.selectCount(Wrappers.<InsOrderDeviceRecord>lambdaQuery()
+                    .eq(InsOrderDeviceRecord::getInsOrderId, orderId)
+                    .eq(InsOrderDeviceRecord::getDeviceId, deviceId)
+                    .eq(InsOrderDeviceRecord::getSampleCode, sampleCode));
+            if (count != null && count > 0) {
+                continue;
+            }
+            InsOrderDeviceRecord record = new InsOrderDeviceRecord();
+            record.setInsOrderId(orderId);
+            record.setDeviceId(deviceId);
+            record.setSampleCode(sampleCode);
+            record.setTemperature(order.getTemperature());
+            record.setHumidity(order.getHumidity());
+            record.setUseBefore(1);
+            record.setUseAfter(1);
+            record.setUsePersonId(userId);
+            record.setUsePerson(usePerson);
+            insOrderDeviceRecordMapper.insert(record);
         }
-        // 1.鍒ゆ柇鏄惁鏈夋病鏈夋坊鍔犵殑浣跨敤璁板綍
-        Set<String> orderDeviceNumbers = getDeviceDifference(deviceCodeSet, recordCodeset);
-        // 娣诲姞浣跨敤璁板綍, 鏍规嵁缂栧彿鏌ヨ璁惧id
-        if (CollectionUtils.isNotEmpty(orderDeviceNumbers)) {
-            List<Integer> orderDeviceIds = insOrderDeviceRecordMapper.selectDeviceIdsByNumbers(orderDeviceNumbers);
-            List<InsOrderDeviceRecord> collect = orderDeviceIds.stream().map(deviceId -> {
-                InsOrderDeviceRecord insOrderDeviceRecord = new InsOrderDeviceRecord();
-                insOrderDeviceRecord.setInsOrderId(insSample.getInsOrderId());
-                insOrderDeviceRecord.setDeviceId(deviceId);
-                insOrderDeviceRecord.setSampleCode(order.getEntrustCode());
-                insOrderDeviceRecord.setUseBefore(1);
-                insOrderDeviceRecord.setUseAfter(1);
-                insOrderDeviceRecord.setUsePerson(user.getName());
-                insOrderDeviceRecord.setUsePersonId(user.getId());
-                return insOrderDeviceRecord;
-            }).collect(Collectors.toList());
-
-            insOrderDeviceRecordService.saveBatch(collect);
-
-        }
-
-        // 2.鍒ゆ柇鏄惁鍙栨秷浜嗚澶囦娇鐢�
-        Set<String> repoprNumbers = getDeviceDifference(recordCodeset, deviceCodeSet);
-        if (CollectionUtils.isNotEmpty(repoprNumbers)) {
-            List<Integer> reportDeviceIds = insOrderDeviceRecordMapper.selectDeviceIdsByNumbers(repoprNumbers);
-            insOrderDeviceRecordMapper.delete(Wrappers.<InsOrderDeviceRecord>lambdaQuery()
-                    .in(InsOrderDeviceRecord::getDeviceId, reportDeviceIds)
-                    .eq(InsOrderDeviceRecord::getInsOrderId, insSample.getInsOrderId()));
-        }
-    }
-
-    private static Set<String> getDeviceDifference(Set<String> number1, Set<String> number2) {
-        return number1.stream().filter(s1 -> number2.stream().noneMatch(s2 -> s1.equals(s2)))
-                .collect(Collectors.toSet());
     }
 
 
@@ -1701,6 +1698,8 @@
             refreshed.setInsOrderId(orderId);
             refreshed.setTemplateId(templateId);
             refreshed.setNumber(standardTemplate == null ? oldSnapshot.getNumber() : standardTemplate.getNumber());
+            refreshed.setStandardRequirement(oldSnapshot == null
+                    ? standardTemplate.getStandardRequirement() : oldSnapshot.getStandardRequirement());
             refreshed.setName(standardTemplate == null ? oldSnapshot.getName() : standardTemplate.getName());
             refreshed.setRemark(standardTemplate == null ? oldSnapshot.getRemark() : standardTemplate.getRemark());
             refreshed.setThing(standardTemplate == null ? oldSnapshot.getThing() : standardTemplate.getThing());
@@ -1711,6 +1710,7 @@
             refreshed.setHumidity(templateHumidityMap.get(templateId));
             // 鍒锋柊妯℃澘缁撴瀯鏃跺繀椤讳繚鐣欐楠岄樁娈靛~鍐欑殑涓氬姟鏁版嵁锛岄伩鍏嶈繘鍏ュ鏍稿悗鍥炴樉涓虹┖銆�
             refreshed.setDetectionTime(oldSnapshot == null ? null : oldSnapshot.getDetectionTime());
+            refreshed.setDetectionEndTime(oldSnapshot == null ? null : oldSnapshot.getDetectionEndTime());
             refreshed.setDetectionPlace(oldSnapshot == null ? null : oldSnapshot.getDetectionPlace());
             refreshed.setInsResult(oldSnapshot == null ? null : oldSnapshot.getInsResult());
             Integer templateSort = templateSortMap.get(templateId);
@@ -1856,11 +1856,13 @@
             }
 
             // 妫�楠屼汉鍛樻彁浜ゅ鏍告椂涓嶇敓鎴愭姤鍛婏紱鍏ㄩ儴璇曢獙瀹ゅ鏍搁�氳繃鍚庣敓鎴愭姤鍛娿��
-            if (report == null || StringUtils.isBlank(report.getUrl())) {
+            boolean returnedFromReport = report != null && Objects.equals(report.getIsPass(), 0);
+            if (report == null || StringUtils.isBlank(report.getUrl()) || returnedFromReport) {
                 this.generateReport(orderId, DETECTION_REPORT, writeUserId);
             }
             // 鐩寸粦妯℃澘璁㈠崟鍚屾椂鐢熸垚妫�楠屾姤鍛婏紝涓や唤鏂囦欢鍏辩敤鍚屼竴鏉″鎵硅褰曘��
-            if (directTemplateOrder && (report == null || StringUtils.isBlank(report.getInspectionUrl()))) {
+            if (directTemplateOrder && (report == null || StringUtils.isBlank(report.getInspectionUrl())
+                    || returnedFromReport)) {
                 this.generateReport(orderId, INSPECTION_REPORT, writeUserId);
             }
             report = insReportMapper.selectOne(Wrappers.<InsReport>lambdaQuery()
@@ -2058,7 +2060,8 @@
         if (Objects.equals(report.getIsRatify(), 1)) {
             throw new ErrorException("宸叉壒鍑嗘姤鍛婁笉鑳介噸鏂扮敓鎴�");
         }
-        if (StringUtils.isNotBlank(report.getUrlS())) {
+        // urlS 鍚屾椂鐢ㄤ簬浜哄伐涓婁紶鍜屽鏍搁〉闈繚瀛樼殑 Word锛涘彧鏈変汉宸ヤ笂浼犻渶瑕佸厛鎵嬪姩鍒囧洖绯荤粺鎶ュ憡銆�
+        if (StringUtils.isNotBlank(report.getUrlS()) && !isBrowserEditedReportUrl(report.getUrlS())) {
             throw new ErrorException("褰撳墠鎶ュ憡宸叉墜鍔ㄤ笂浼狅紝璇峰厛杩樺師涓虹郴缁熸姤鍛婂悗鍐嶉噸鏂扮敓鎴�");
         }
         if (report.getInsOrderId() == null) {
@@ -2102,7 +2105,12 @@
                 .eq(InsReport::getId, reportId)
                 .set(InsReport::getWriteTime, report.getWriteTime())
                 .set(InsReport::getIsPass, report.getIsPass())
+                .set(InsReport::getUrlS, null)
                 .set(InsReport::getTempUrlPdf, "/word/" + tempPdfName));
+    }
+
+    private static boolean isBrowserEditedReportUrl(String url) {
+        return url != null && url.matches("(?i)^/word/(?:edited|reviewed)-[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\\.docx$");
     }
 
     private Map<String, Object> buildExistingReportMarks(InsReport report) {
@@ -3667,7 +3675,8 @@
                         .eq(InsOrderStandardTemplate::getInsOrderId, orderId)
                         .orderByAsc(InsOrderStandardTemplate::getSort, InsOrderStandardTemplate::getId));
         List<LocalDate> detectionDates = templateSnapshots.stream()
-                .map(InsOrderStandardTemplate::getDetectionTime)
+                .flatMap(snapshot -> java.util.stream.Stream.of(
+                        snapshot.getDetectionTime(), snapshot.getDetectionEndTime()))
                 .filter(Objects::nonNull)
                 .collect(Collectors.toList());
         String insTime = formatReportTestDate(detectionDates);
@@ -3683,7 +3692,7 @@
         List<Map<String, String>> finalDeviceList = deviceList;
         String finalModelStr = modelStr;
 
-        // 鐩寸粦妯℃澘璁㈠崟娌℃湁 ins_product锛屾娴嬮」鐩�佸崟浣嶅拰缁撴灉鍧囦粠璁㈠崟妯℃澘蹇収涓幏鍙栥��
+        // 鐩寸粦妯℃澘璁㈠崟娌℃湁 ins_product锛屾娴嬮」鐩�佹爣鍑嗚姹傚�煎拰缁撴灉鍧囦粠璁㈠崟妯℃澘蹇収涓幏鍙栥��
         List<Map<String, String>> detectionResultRows = directTemplateOrder
                 ? buildTemplateDetectionResultRows(orderId)
                 : buildDetectionResultRows(samples);
@@ -3741,7 +3750,7 @@
         }
         Configure configure = Configure.builder()
                 .bind("deviceList", new HackLoopTableRenderPolicy())
-                .bind("r", new HackLoopTableRenderPolicy(true))
+                .bind("r", new ReportResultTableRenderPolicy())
                 .setValidErrorHandler(new PreserveReportPicturePlaceholderHandler())
                 .useSpringEL(true)
                 .build();
@@ -3865,7 +3874,7 @@
     }
 
     /**
-     * 鏂扮増妫�娴嬫姤鍛婄殑缁撴灉琛ㄥ浐瀹氫负鍥涘垪锛氬簭鍙枫�佹娴嬮」鐩�佸崟浣嶃�佹娴嬬粨鏋溿��
+     * 鏂扮増妫�娴嬨�佹楠屾姤鍛婂叡鐢ㄧ粨鏋滄暟鎹紱鏍囧噯瑕佹眰鍊煎彇鑷師濮嬭褰曟ā鏉块厤缃��
      */
     private List<Map<String, String>> buildDetectionResultRows(List<SampleProductDto> samples) {
         List<Map<String, String>> rows = new ArrayList<>();
@@ -3874,6 +3883,7 @@
         }
 
         boolean multipleSamples = samples.size() > 1;
+        Map<Integer, String> requirementsByTemplate = new HashMap<>();
         int sequence = 1;
         for (SampleProductDto sample : samples) {
             if (CollectionUtils.isEmpty(sample.getInsProduct())) {
@@ -3894,8 +3904,15 @@
 
                 Map<String, String> row = new LinkedHashMap<>();
                 row.put("seq", String.valueOf(sequence++));
-                row.put("itemName", itemName);
+                row.put("itemName", formatReportItemWithUnit(itemName, product.getUnit()));
                 row.put("unit", defaultReportText(product.getUnit(), "/"));
+                String requirement = product.getTemplateId() == null ? null
+                        : requirementsByTemplate.computeIfAbsent(product.getTemplateId(), templateId -> {
+                            StandardTemplate sourceTemplate = standardTemplateService.getById(templateId);
+                            return defaultReportText(sourceTemplate == null ? null
+                                    : sourceTemplate.getStandardRequirement(), "/");
+                        });
+                row.put("standardRequirement", defaultReportText(requirement, "/"));
                 row.put("result", defaultReportText(product.getLastValue(), "/"));
                 row.put("inspectionConclusion", formatInspectionConclusion(product.getInsResult()));
                 rows.add(row);
@@ -3921,7 +3938,8 @@
                 Wrappers.<InsOrderStandardTemplate>lambdaQuery()
                         .eq(InsOrderStandardTemplate::getInsOrderId, orderId)
                         .orderByAsc(InsOrderStandardTemplate::getSort, InsOrderStandardTemplate::getId));
-        context.setDetectionDates(snapshots.stream().map(InsOrderStandardTemplate::getDetectionTime)
+        context.setDetectionDates(snapshots.stream().flatMap(snapshot -> java.util.stream.Stream.of(
+                        snapshot.getDetectionTime(), snapshot.getDetectionEndTime()))
                 .filter(Objects::nonNull).distinct().sorted().collect(Collectors.toList()));
         List<Integer> deviceIds = insOrderTemplateDeviceMapper.selectDeviceIdsByOrderId(orderId);
         if (CollectionUtils.isNotEmpty(deviceIds)) {
@@ -3949,6 +3967,12 @@
         List<Map<String, String>> rows = new ArrayList<>();
         int sequence = 1;
         for (InsOrderStandardTemplate snapshot : snapshots) {
+            String standardRequirement = snapshot.getStandardRequirement();
+            // 鍏煎鏂板璇ュ瓧娈靛墠涓嬪崟鐨勬棫璁板綍锛涙湁蹇収鏃跺缁堜互璁㈠崟淇濆瓨鐨勫�间负鍑嗐��
+            if (StringUtils.isBlank(standardRequirement) && snapshot.getTemplateId() != null) {
+                StandardTemplate sourceTemplate = standardTemplateService.getById(snapshot.getTemplateId());
+                standardRequirement = sourceTemplate == null ? null : sourceTemplate.getStandardRequirement();
+            }
             List<TemplateExportCell> exportCells = getTemplateExportCells(snapshot.getThing());
             JSONObject recordValues = StrUtil.isBlank(snapshot.getRecordValues())
                     ? new JSONObject() : JSON.parseObject(snapshot.getRecordValues());
@@ -3967,8 +3991,10 @@
                 row.put("seq", String.valueOf(sequence++));
                 String reportItemName = defaultReportText(itemName,
                         defaultReportText(snapshot.getName(), "妯℃澘ID " + snapshot.getTemplateId()));
-                row.put("itemName", formatExportItemName(reportItemName));
+                row.put("itemName", formatReportItemWithUnit(
+                        formatExportItemName(reportItemName), unit));
                 row.put("unit", defaultReportText(unit, "/"));
+                row.put("standardRequirement", defaultReportText(standardRequirement, "/"));
                 row.put("result", result);
                 row.put("inspectionConclusion", formatInspectionConclusion(snapshot.getInsResult()));
                 rows.add(row);
@@ -4144,6 +4170,14 @@
         return itemName.replaceAll("骞冲潎鍊糪\s*[锛�,]?\\s*", "");
     }
 
+    private static String formatReportItemWithUnit(String itemName, String unit) {
+        if (StringUtils.isBlank(unit) || "/".equals(unit.trim())
+                || itemName.contains(unit.trim())) {
+            return itemName;
+        }
+        return itemName + "锛�" + unit.trim();
+    }
+
     private static String getMapText(Map<String, String> map, String... keys) {
         if (map == null) {
             return null;

--
Gitblit v1.9.3