liujie
2026-04-02 6c3e93c94f74952a0cf1300822314caa21092de4
Merge branch 'master' of http://120.76.84.145:10101/gitblit/r/java/smart_screen
3个文件已修改
383 ■■■■■ 已修改文件
.gitignore 4 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ruoyi-system/src/main/java/com/ruoyi/system/service/impl/ClientServiceImpl.java 80 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ruoyi-system/src/main/java/com/ruoyi/system/service/impl/DeviceUsageServiceImpl.java 299 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
.gitignore
@@ -45,3 +45,7 @@
!*/build/*.java
!*/build/*.html
!*/build/*.xml
/.spec-workflow/
/.vscode/
/.claude/
/AGENTS.md
ruoyi-system/src/main/java/com/ruoyi/system/service/impl/ClientServiceImpl.java
@@ -98,11 +98,29 @@
        List<Project> projects = projectMapper.selectList(projectWrapper);
        // 1. 统计项目总数及分类
        vo.setProjectTotal(projects.size());
        long housingCount = projects.stream().filter(p -> p.getType() != null && p.getType() == 0).count();
        long municipalCount = projects.stream().filter(p -> p.getType() != null && p.getType() == 1).count();
        vo.setHousingProjectCount((int) housingCount);
        vo.setMunicipalProjectCount((int) municipalCount);
        ClientParam clientParam = null;
        if (clientId != null) {
            clientParam = clientParamMapper.selectOne(
                    new LambdaQueryWrapper<ClientParam>()
                            .eq(ClientParam::getClientId, clientId.intValue())
            );
        }
        int effectiveHousingCount = resolveDisplayProjectCount(
                clientParam != null ? clientParam.getHousingProjectNum() : null,
                housingCount
        );
        int effectiveMunicipalCount = resolveDisplayProjectCount(
                clientParam != null ? clientParam.getMunicipalProjectNum() : null,
                municipalCount
        );
        vo.setProjectTotal(effectiveHousingCount + effectiveMunicipalCount);
        vo.setHousingProjectCount(effectiveHousingCount);
        vo.setMunicipalProjectCount(effectiveMunicipalCount);
        // 计算检查覆盖率(仅当查询时间范围为当月时才计算)
        List<Integer> projectIds = projects.stream().map(Project::getId).collect(Collectors.toList());
@@ -139,15 +157,6 @@
                        .distinct()
                        .toList();
                // 查询配置的项目总数
                ClientParam clientParam = null;
                if (clientId != null) {
                    clientParam = clientParamMapper.selectOne(
                        new LambdaQueryWrapper<ClientParam>()
                            .eq(ClientParam::getClientId, clientId.intValue())
                    );
                }
                // 房建检查覆盖率
                List<Integer> housingProjectIds = projects.stream()
                        .filter(p -> p.getType() != null && p.getType() == 0)
@@ -157,12 +166,8 @@
                        .filter(housingProjectIds::contains)
                        .count();
                // 使用配置的房建项目总数,如果没有配置则使用实际数量
                int configuredHousingNum = (clientParam != null && clientParam.getHousingProjectNum() != null)
                        ? clientParam.getHousingProjectNum()
                        : (int) housingCount;
                vo.setHousingInspectionCoverage(
                        configuredHousingNum > 0 ? (int) Math.round(checkedHousingCount * 100.0 / configuredHousingNum) : 0
                        effectiveHousingCount > 0 ? (int) Math.round(checkedHousingCount * 100.0 / effectiveHousingCount) : 0
                );
                // 市政检查覆盖率
@@ -174,12 +179,8 @@
                        .filter(municipalProjectIds::contains)
                        .count();
                // 使用配置的市政项目总数,如果没有配置则使用实际数量
                int configuredMunicipalNum = (clientParam != null && clientParam.getMunicipalProjectNum() != null)
                        ? clientParam.getMunicipalProjectNum()
                        : (int) municipalCount;
                vo.setMunicipalInspectionCoverage(
                        configuredMunicipalNum > 0 ? (int) Math.round(checkedMunicipalCount * 100.0 / configuredMunicipalNum) : 0
                        effectiveMunicipalCount > 0 ? (int) Math.round(checkedMunicipalCount * 100.0 / effectiveMunicipalCount) : 0
                );
            } else {
                vo.setHousingInspectionCoverage(0);
@@ -269,9 +270,7 @@
            vo.setInspectedCount(0);
            vo.setInspectedHousingCount(0);
            vo.setInspectedMunicipalCount(0);
            vo.setUninspectedCount(projects.size());
            vo.setUninspectedHousingCount(vo.getHousingProjectCount());
            vo.setUninspectedMunicipalCount(vo.getMunicipalProjectCount());
            fillUninspectedProjectCounts(vo);
            return;
        }
@@ -287,9 +286,7 @@
            vo.setInspectedCount(0);
            vo.setInspectedHousingCount(0);
            vo.setInspectedMunicipalCount(0);
            vo.setUninspectedCount(projects.size());
            vo.setUninspectedHousingCount(vo.getHousingProjectCount());
            vo.setUninspectedMunicipalCount(vo.getMunicipalProjectCount());
            fillUninspectedProjectCounts(vo);
            return;
        }
@@ -327,16 +324,7 @@
        vo.setInspectedMunicipalCount((int) inspectedProjects.stream()
                .filter(p -> p.getType() != null && p.getType() == 1).count());
        // 未检查项目统计
        List<Project> uninspectedProjects = projects.stream()
                .filter(p -> !inspectedProjectIds.contains(p.getId()))
                .toList();
        vo.setUninspectedCount(uninspectedProjects.size());
        vo.setUninspectedHousingCount((int) uninspectedProjects.stream()
                .filter(p -> p.getType() != null && p.getType() == 0).count());
        vo.setUninspectedMunicipalCount((int) uninspectedProjects.stream()
                .filter(p -> p.getType() != null && p.getType() == 1).count());
        fillUninspectedProjectCounts(vo);
    }
    /**
@@ -732,6 +720,22 @@
        return DateUtil.endOfMonth(date);
    }
    private int resolveDisplayProjectCount(Integer configuredCount, long actualCount) {
        int actualProjectCount = (int) actualCount;
        if (configuredCount == null) {
            return actualProjectCount;
        }
        return Math.max(configuredCount, actualProjectCount);
    }
    private void fillUninspectedProjectCounts(OngoingProjectDashboardVO vo) {
        int uninspectedHousingCount = Math.max(vo.getHousingProjectCount() - vo.getInspectedHousingCount(), 0);
        int uninspectedMunicipalCount = Math.max(vo.getMunicipalProjectCount() - vo.getInspectedMunicipalCount(), 0);
        vo.setUninspectedHousingCount(uninspectedHousingCount);
        vo.setUninspectedMunicipalCount(uninspectedMunicipalCount);
        vo.setUninspectedCount(uninspectedHousingCount + uninspectedMunicipalCount);
    }
    /**
     * 判断给定的日期范围是否为当前月份
     *
ruoyi-system/src/main/java/com/ruoyi/system/service/impl/DeviceUsageServiceImpl.java
@@ -1,9 +1,7 @@
package com.ruoyi.system.service.impl;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
@@ -13,6 +11,7 @@
import com.ruoyi.system.query.*;
import com.ruoyi.system.service.ClientParamService;
import com.ruoyi.system.service.DeviceUsageService;
import com.ruoyi.system.service.ProjectCategoryCalculator;
import com.ruoyi.system.vo.*;
import com.ruoyi.system.vo.DeviceCountVo;
import com.ruoyi.system.vo.DeviceListVo;
@@ -23,7 +22,6 @@
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
@@ -52,6 +50,8 @@
    private TaskMapper taskMapper;
    @Autowired
    private RecordMapper recordMapper;
    @Autowired
    private ProjectCategoryCalculator projectCategoryCalculator;
    @Override
    public List<String> getDeviceUsageList(Integer id) {
@@ -81,9 +81,6 @@
    @Override
    public List<EntrustProjectVo> projectList(Page<EntrustProjectVo> page, EntrustListQuery query) {
        Integer pageNum = query.getPageNum();
        Integer pageSize = query.getPageSize();
        String startTime = query.getStartTime();
        String endTime = query.getEndTime();
@@ -128,160 +125,16 @@
            projectIds.add(-1);
        }
        query.setProjectIds(projectIds);
        Map<Integer, String> categoryMap = calculateProjectCategoryMap(projects, query);
        // 查询检查任务
        LambdaQueryWrapper<Task> taskWrapper = new LambdaQueryWrapper<>();
        taskWrapper.in(Task::getProjectId, projectIds)
                .eq(Task::getDeleted, false);
        List<Task> taskList = taskMapper.selectList(taskWrapper);
        List<Integer> checkTaskIds = taskList.stream().map(Task::getId).collect(Collectors.toList());
        if (checkTaskIds.isEmpty()) {
            checkTaskIds.add(-1);
        }
        // 查询重大隐患记录(level 表示隐患等级,0 表示重大隐患)
        LambdaQueryWrapper<Record> recordWrapper = new LambdaQueryWrapper<>();
        recordWrapper.eq(Record::getDeleted, false)
                .in(Record::getCheckTaskId, checkTaskIds)
                .eq(Record::getLevel, 0); // 重大隐患等级
        List<Integer> recordIds = new ArrayList<>(recordMapper.selectList(recordWrapper).stream().map(Record::getId).toList());
        if (recordIds.isEmpty()) {
            recordIds.add(-1);
        }
        Map<Integer, Integer> projectMap = projectMapper.selectList(new LambdaQueryWrapper<Project>()
                .eq(Project::getDeleted, false)).stream().collect(Collectors.toMap(Project::getId, Project::getClientId));
        Map<Integer, String> clientParamMap = clientParamMapper.selectList(new LambdaQueryWrapper<ClientParam>()
                        .isNotNull(ClientParam::getUnderConstructionProject))
                .stream().collect(Collectors.toMap(ClientParam::getClientId, ClientParam::getUnderConstructionProject));
        Map<Integer, String> assetParamMap = clientParamMapper.selectList(new LambdaQueryWrapper<ClientParam>()
                        .isNotNull(ClientParam::getAssetProject))
                .stream().collect(Collectors.toMap(ClientParam::getClientId, ClientParam::getAssetProject));
        Map<Integer, List<Task>> taskMap = taskMapper.selectList(new LambdaQueryWrapper<Task>()
                        .ge(Task::getCreateTime, startTime)
                        .le(Task::getCreateTime, LocalDateTime.now())
                        .in(Task::getId, checkTaskIds)
                        .isNotNull(Task::getProjectId))
                .stream().collect(Collectors.groupingBy(Task::getProjectId));
        Map<Integer, Task> taskRecordMap = taskMapper.selectList(new LambdaQueryWrapper<Task>()
                        .ge(Task::getCreateTime, startTime)
                        .le(Task::getCreateTime, LocalDateTime.now())
                        .in(Task::getId, checkTaskIds)
                        .isNotNull(Task::getProjectId))
                .stream().collect(Collectors.toMap(Task::getId, e -> e));
        Map<Integer, List<EvalResult>> resultMap = evalResultMapper.selectList(new LambdaQueryWrapper<EvalResult>()
                .in(EvalResult::getCheckTaskId, checkTaskIds)
        ).stream().collect(Collectors.groupingBy(EvalResult::getProjectId));
        List<Record> records = recordMapper.selectList(new LambdaQueryWrapper<Record>()
                .in(Record::getId, recordIds)
                .eq(Record::getDeleted, false));
        List<EntrustProjectVo> deviceList = this.baseMapper.projectList(page, query);
        for (EntrustProjectVo deviceListVo : deviceList) {
            if (query.getCategory() == 1) {
                // 在建
                List<EvalResult> evalResults = resultMap.get(deviceListVo.getId());
                if (evalResults != null) {
                    float temp = 0;
                    // 计算安全检查平均分
                    float avgSafetyScore = (float) evalResults.stream()
                            .filter(e -> e.getScore() != null)
                            .mapToDouble(EvalResult::getScore)
                            .average()
                            .orElse(0.0);
                    // 计算设备检查平均分(需要解析 device_res_map)
                    List<Float> deviceScores = evalResults.stream()
                            .filter(e -> StringUtils.hasText(e.getDeviceResMap()))
                            .map(e -> calculateDeviceScore(e.getDeviceResMap()))
                            .filter(score -> score != null && score > 0)
                            .toList();
                    if (!deviceScores.isEmpty()) {
                        float avgDeviceScore = (float) deviceScores.stream()
                                .mapToDouble(Float::doubleValue)
                                .average()
                                .orElse(0.0);
                        temp = (avgSafetyScore + avgDeviceScore) / 2;
                    }
                    Integer clientId = projectMap.get(deviceListVo.getId());
                    String s = clientParamMap.get(clientId);
                    JSONObject jsonObject = JSON.parseObject(s);
                    String a = jsonObject.getString("a");
                    String b = jsonObject.getString("b");
                    String c = jsonObject.getString("c");
                    if (temp >= Float.parseFloat(a)) {
                        deviceListVo.setRisk("A类");
                    } else if (temp >= Float.parseFloat(b)) {
                        deviceListVo.setRisk("B类");
                    } else if (temp >= Float.parseFloat(c)) {
                        deviceListVo.setRisk("C类");
                    }
                } else {
                    deviceListVo.setRisk(null);
                }
            } else {
                // 查询检查任务
                LambdaQueryWrapper<Task> taskWrapperPro = new LambdaQueryWrapper<>();
                taskWrapperPro.eq(Task::getProjectId, deviceListVo.getId())
                        .eq(Task::getDeleted, false);
                List<Task> tasks = taskMapper.selectList(taskWrapperPro);
                List<Integer> checkTaskIdsPro = tasks.stream().map(Task::getId).collect(Collectors.toList());
                // 查询重大隐患记录(level 表示隐患等级,0 表示重大隐患)
                LambdaQueryWrapper<Record> recordWrapperPro = new LambdaQueryWrapper<>();
                if(checkTaskIdsPro.size()>0){
                    recordWrapperPro.eq(Record::getDeleted, false)
                            .in(Record::getCheckTaskId, checkTaskIdsPro);
                }
                ; // 重大隐患等级
                List<Record> records1 = recordMapper.selectList(recordWrapperPro);
//                long c1 = records1.stream().filter(e -> e.getLevel() != null && e.getLevel() == 0).count();
//                long c2 = records1.stream().filter(e -> e.getLevel() != null && e.getLevel() == 0).count();
//                long c3 = records1.stream().filter(e -> e.getLevel() != null && e.getLevel() == 0).count();
//                long c4 = records1.stream().filter(e -> e.getLevel() != null && e.getLevel() == 0).count();
//                // 固定资产
//                String s = clientParamMap.get(query.getClientId());
//                JSONObject jsonObject = JSON.parseObject(s);
//                JSONArray a = jsonObject.getJSONArray("a");
//                for (Object o : a) {
//                    // 转化为jsonObject
//                    JSONObject jsonObject1 = (JSONObject) o;
//                }
//                JSONArray b = jsonObject.getJSONArray("b");
//                for (Object o : b) {
//                    // 转化为jsonObject
//                    JSONObject jsonObject1 = (JSONObject) o;
//                }
//                JSONArray c = jsonObject.getJSONArray("c");
//                for (Object o : c) {
//                    // 转化为jsonObject
//                    JSONObject jsonObject1 = (JSONObject) o;
//                }
                // 统计各等级隐患数量
                Map<Integer, Long> levelCountMap = records1.stream()
                        .filter(e -> e.getLevel() != null)
                        .collect(Collectors.groupingBy(Record::getLevel, Collectors.counting()));
// 获取客户参数配置
                String s = assetParamMap.get(query.getClientId());
                JSONObject jsonObject = JSON.parseObject(s);
// 初始化风险等级
                String riskLevel = null;
// 先判断 c 条件
                JSONArray cArray = jsonObject.getJSONArray("c");
                if (cArray != null && matchesCondition(cArray, levelCountMap)) {
                    riskLevel = "C类";
                }
// 再判断 b 条件
                else if (jsonObject.getJSONArray("b") != null && matchesCondition(jsonObject.getJSONArray("b"), levelCountMap)) {
                    riskLevel = "B类";
                }
// 最后判断 a 条件
                else if (jsonObject.getJSONArray("a") != null && matchesCondition(jsonObject.getJSONArray("a"), levelCountMap)) {
                    riskLevel = "A类";
                }
            }
            deviceListVo.setRisk(formatProjectCategory(categoryMap.get(deviceListVo.getId())));
            List<Task> tasks = taskList.stream().filter(e -> e.getProjectId().equals(deviceListVo.getId())).toList();
//            List<Task> tasks = taskMap.get(deviceListVo.getId());
            if (tasks != null && !tasks.isEmpty()) {
@@ -290,7 +143,8 @@
//                List<Record> recordList = records.stream().filter(e -> taskIds.contains(e.getCheckTaskId())).toList();
//                Record record = recordList.stream().max(Comparator.comparing(Record::getCreateTime)).orElse(null);
                if (task1 != null && (task1.getState() == 3 || Integer.valueOf(7).equals(task1.getState()))) {
                if (task1 != null && (task1.getState() == 3 || Integer.valueOf(5).equals(task1.getState()) ||
                        Integer.valueOf(6).equals(task1.getState()) || Integer.valueOf(7).equals(task1.getState()))) {
                    deviceListVo.setCheckTime(task1.getDate().atStartOfDay());
                    deviceListVo.setCheckResult("已检查");
                } else {
@@ -307,107 +161,56 @@
        return deviceList;
    }
    /**
     * 判断条件数组是否满足隐患统计结果
     *
     * @param conditionArray 条件数组,例如 [[{"4":"1"},{"4":"1"}], [{"4":"2"}]]
     * @param levelCountMap  隐患等级统计结果,key为隐患等级,value为数量
     * @return 是否满足条件
     */
    private boolean matchesCondition(JSONArray conditionArray, Map<Integer, Long> levelCountMap) {
        for (Object item : conditionArray) {
            if (item instanceof JSONArray) {
                JSONArray andConditions = (JSONArray) item;
                boolean allMatch = true;
                for (Object condition : andConditions) {
                    if (condition instanceof JSONObject) {
                        JSONObject conditionObj = (JSONObject) condition;
                        for (Map.Entry<String, Object> entry : conditionObj.entrySet()) {
                            int level = Integer.parseInt(entry.getKey()); // 隐患等级
                            int requiredCount = Integer.parseInt(entry.getValue().toString()); // 所需数量
                            Long actualCount = levelCountMap.getOrDefault(level, 0L);
                            if (actualCount < requiredCount) {
                                allMatch = false;
                                break;
                            }
                        }
                    }
                    if (!allMatch) break;
                }
                if (allMatch) return true; // 满足任意一个“或”条件即可返回 true
            }
    private Map<Integer, String> calculateProjectCategoryMap(List<Project> projects, EntrustListQuery query) {
        if (projects.isEmpty() || query.getClientId() == null || query.getCategory() == null) {
            return Collections.emptyMap();
        }
        return false;
        Date startDate = resolveProjectCategoryStartDate(query.getStartTime());
        Date endDate = resolveProjectCategoryEndDate(query.getEndTime());
        if (query.getCategory() == 1) {
            return projectCategoryCalculator.calculateOngoingProjectCategories(
                    projects, query.getClientId().longValue(), startDate, endDate
            );
        }
        if (query.getCategory() == 2) {
            return projectCategoryCalculator.calculateFixedAssetCategories(
                    projects, query.getClientId().longValue(), startDate, endDate
            );
        }
        return Collections.emptyMap();
    }
    private static Float calculateDeviceScore(String deviceResMapJson) {
        try {
            // 1. 解析 JSON 字符串
            JSONObject deviceMap = JSON.parseObject(deviceResMapJson);
            if (deviceMap == null || deviceMap.isEmpty()) {
                log.debug("设备评估结果映射为空");
                return null;
            }
    private Date resolveProjectCategoryStartDate(String startTime) {
        if (!StringUtils.hasLength(startTime)) {
            return DateUtil.beginOfMonth(new Date());
        }
        return DateUtil.beginOfDay(DateUtil.parse(normalizeDateText(startTime)));
    }
            // 2. 提取所有设备的分数
            List<Float> scores = new ArrayList<>();
            for (String deviceId : deviceMap.keySet()) {
                try {
                    // 获取设备数据对象
                    JSONObject deviceData = deviceMap.getJSONObject(deviceId);
                    if (deviceData == null) {
                        log.debug("设备数据为空,deviceId: {}", deviceId);
                        continue;
                    }
    private Date resolveProjectCategoryEndDate(String endTime) {
        if (!StringUtils.hasLength(endTime)) {
            return DateUtil.endOfMonth(new Date());
        }
        return DateUtil.endOfDay(DateUtil.parse(normalizeDateText(endTime)));
    }
                    // 获取 content 对象
                    JSONObject content = deviceData.getJSONObject("content");
                    if (content == null) {
                        log.debug("设备 content 为空,deviceId: {}", deviceId);
                        continue;
                    }
    private String normalizeDateText(String dateText) {
        return dateText.replace("年", "-")
                .replace("月", "-")
                .replace("日", "")
                .replace("/", "-")
                .trim();
    }
                    // 获取 data 对象
                    JSONObject data = content.getJSONObject("data");
                    if (data == null) {
                        log.debug("设备 data 为空,deviceId: {}", deviceId);
                        continue;
                    }
                    // 获取 score 字段
                    if (!data.containsKey("score")) {
                        log.debug("设备 data 中不包含 score 字段,deviceId: {}", deviceId);
                        continue;
                    }
                    Float score = data.getFloat("score");
                    if (score != null && score > 0) {
                        scores.add(score);
                        log.debug("成功提取设备得分,deviceId: {}, score: {}", deviceId, score);
                    }
                } catch (Exception e) {
                    log.warn("提取设备得分失败,deviceId: {}", deviceId, e);
                }
            }
            // 3. 计算平均分
            if (scores.isEmpty()) {
                log.debug("没有有效的设备得分数据");
                return null;
            }
            float avgScore = (float) scores.stream()
                    .mapToDouble(Float::doubleValue)
                    .average()
                    .orElse(0.0);
            log.debug("设备平均得分计算完成,设备数量: {}, 平均分: {}", scores.size(), avgScore);
            return avgScore;
        } catch (Exception e) {
            log.warn("解析设备得分失败,deviceResMapJson: {}", deviceResMapJson, e);
    private String formatProjectCategory(String category) {
        if (!StringUtils.hasLength(category)) {
            return null;
        }
        if (category.endsWith("类")) {
            return category;
        }
        return category + "类";
    }
    @Override