“mitao”
2026-01-27 4dd7eab60c500a58983a187a80b23dcf8a97116b
Merge remote-tracking branch 'origin/master'
6个文件已修改
194 ■■■■■ 已修改文件
ruoyi-admin/src/main/java/com/ruoyi/web/controller/api/ProjectController.java 68 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ruoyi-admin/src/main/resources/application-test.yml 2 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ruoyi-framework/src/main/java/com/ruoyi/framework/config/SecurityConfig.java 1 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ruoyi-system/src/main/java/com/ruoyi/system/query/EntrustListQuery.java 2 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ruoyi-system/src/main/java/com/ruoyi/system/service/impl/DeviceUsageServiceImpl.java 119 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ruoyi-system/src/main/resources/mapper/system/DeviceUsageMapper.xml 2 ●●●●● 补丁 | 查看 | 原始文档 | blame | 历史
ruoyi-admin/src/main/java/com/ruoyi/web/controller/api/ProjectController.java
@@ -16,16 +16,28 @@
import com.ruoyi.system.service.*;
import com.ruoyi.system.vo.*;
import io.swagger.annotations.*;
import lombok.SneakyThrows;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.parsing.Problem;
import org.springframework.core.io.InputStreamResource;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.validation.Valid;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;
import java.util.stream.Collectors;
@@ -440,4 +452,60 @@
        return R.ok(list);
    }
    @Resource
    UserFileService userFileService;
    @SneakyThrows
    @ApiOperation(value = "下载文件(名称)")
    @GetMapping("/download/{name}")
    public ResponseEntity<org.springframework.core.io.Resource> downloadFileByName(@PathVariable String name) {
        var userFile = userFileService.getOne(new LambdaQueryWrapper<UserFile>().eq(UserFile::getName, name));
        return downloadFile(userFile);
    }
    private ResponseEntity<org.springframework.core.io.Resource> downloadFile(UserFile userFile) throws IOException {
        InputStreamResource resource =resolveResource(userFile);
        var fileSize = userFile.getSize();
//        if(resource == null) {
//            resource = new InputStreamResource(getClass().getClassLoader().getResourceAsStream("images/wukong.png"));
//            fileSize = 6215360L;// resource.contentLength();
//        }
        String encodedFileName = URLEncoder.encode(userFile.getOriginFileName(), "UTF-8");
        String headerValue = String.format("attachment; filename=\"%s\"", encodedFileName);
        return ResponseEntity.ok()
                .contentType(MediaType.parseMediaType(userFile.getContentType()))
                .contentLength(fileSize)
                .header(HttpHeaders.CONTENT_DISPOSITION, headerValue)
                .body(resource);
    }
    public InputStreamResource resolveResource(UserFile userFile) throws IOException {
        var filePath = fileLocation.resolve(userFile.getName() + "." + userFile.getExtension()).normalize();
        if(!Files.exists(filePath)){
            return null;
        }
        return new InputStreamResource(Files.newInputStream(filePath));
    }
    private Path fileLocation;
    @Value("${file.upload.dir}/files")
    private String UPLOAD_DIR;
    @PostConstruct
    void init(){
        fileLocation  = Path.of(UPLOAD_DIR).toAbsolutePath().normalize();
        try {
            Files.createDirectories(this.fileLocation);
        } catch (Exception ex) {
            throw new RuntimeException("Could not create the directory where the uploaded files will be stored.", ex);
        }
    }
}
ruoyi-admin/src/main/resources/application-test.yml
@@ -176,6 +176,7 @@
  # 请求前缀
  pathMapping: /
# 防止XSS攻击
xss:
  # 过滤开关
@@ -187,6 +188,7 @@
# file upload
file:
  upload:
    dir: F:\file\estate
    location: /file/
    qrLocation: /file/qrCode/
    accessPath: /file/
ruoyi-framework/src/main/java/com/ruoyi/framework/config/SecurityConfig.java
@@ -119,6 +119,7 @@
                        "/index/**",
                        "/merchant/**",
                        "/openIdByJsCode","/wx/**","/html-config/*","/icbc-notify/**","/doc.html/**"
                        ,"/project/download/**"
                ).permitAll()
                // 静态资源,可匿名访问
                .antMatchers(HttpMethod.GET, "/", "/*.html", "/**/*.html", "/**/*.css", "/**/*.js", "/profile/**").permitAll()
ruoyi-system/src/main/java/com/ruoyi/system/query/EntrustListQuery.java
@@ -14,6 +14,8 @@
    @ApiModelProperty("项目id")
    private Integer projectId;
    @ApiModelProperty("委托方id")
    private Integer clientId;
    @ApiModelProperty("项目类型:1-房建 2-市政 3-建筑工程等")
    private Integer type;
ruoyi-system/src/main/java/com/ruoyi/system/service/impl/DeviceUsageServiceImpl.java
@@ -1,23 +1,33 @@
package com.ruoyi.system.service.impl;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ruoyi.system.mapper.DeviceUsageMapper;
import com.ruoyi.system.mapper.EvalResultMapper;
import com.ruoyi.system.model.DeviceUsage;
import com.ruoyi.system.model.EvalResult;
import com.ruoyi.system.model.Record;
import com.ruoyi.system.query.*;
import com.ruoyi.system.service.DeviceUsageService;
import com.ruoyi.system.vo.*;
import com.ruoyi.system.vo.DeviceCountVo;
import com.ruoyi.system.vo.DeviceListVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.YearMonth;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
@@ -28,8 +38,12 @@
 * @author administrator
 * @since 2026-01-13
 */
@Slf4j
@Service
public class DeviceUsageServiceImpl extends ServiceImpl<DeviceUsageMapper, DeviceUsage> implements DeviceUsageService {
    @Autowired
    private EvalResultMapper evalResultMapper;
    @Override
    public List<String> getDeviceUsageList(Integer id) {
@@ -56,12 +70,49 @@
        return this.baseMapper.getProjectDeviceCount(id);
    }
    @Override
    public List<EntrustProjectVo> projectList( Page<EntrustProjectVo> page,EntrustListQuery query) {
        Integer pageNum = query.getPageNum();
        Integer pageSize = query.getPageSize();
        LocalDateTime startTime = LocalDateTime.of(LocalDate.now().withDayOfMonth(1), LocalDateTime.MIN.toLocalTime());
        Map<Integer, List<EvalResult>> resultMap = evalResultMapper.selectList(new LambdaQueryWrapper<EvalResult>()
                .ge(EvalResult::getCreateTime, startTime)
                .le(EvalResult::getCreateTime, LocalDateTime.now())
        ).stream().collect(Collectors.groupingBy(EvalResult::getProjectId));
        // 获取本月第一天凌晨
        List<EntrustProjectVo> deviceList = this.baseMapper.projectList(page,query);
        for (EntrustProjectVo deviceListVo : deviceList) {
            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;
                }
                // todo 查询项目所属委托人风险等级参数设置
                deviceListVo.setRisk("A类");
            }else{
                deviceListVo.setRisk("C类");
            }
            LocalDateTime checkTime = deviceListVo.getCheckTime();
            // 判断checkTime是否是本月的时间
            if (checkTime != null && YearMonth.from(checkTime).equals(YearMonth.now())) {
@@ -72,7 +123,75 @@
        }
        return deviceList;
    }
    private static Float calculateDeviceScore(String deviceResMapJson) {
        try {
            // 1. 解析 JSON 字符串
            JSONObject deviceMap = JSON.parseObject(deviceResMapJson);
            if (deviceMap == null || deviceMap.isEmpty()) {
                log.debug("设备评估结果映射为空");
                return null;
            }
            // 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;
                    }
                    // 获取 content 对象
                    JSONObject content = deviceData.getJSONObject("content");
                    if (content == null) {
                        log.debug("设备 content 为空,deviceId: {}", deviceId);
                        continue;
                    }
                    // 获取 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);
            return null;
        }
    }
    @Override
    public List<EntrustProjectReportVo> projectReport(Page<EntrustProjectReportVo> page, ProjectReportListQuery query) {
        List<EntrustProjectReportVo> entrustProjectReportVoList = this.baseMapper.projectReport(page,query);
ruoyi-system/src/main/resources/mapper/system/DeviceUsageMapper.xml
@@ -86,7 +86,7 @@
        group by project_id
        order by create_time desc
        ) result on t1.id = result.project_id
        where t1.deleted = 0 and t2.deleted = 0
        where t1.deleted = 0 and t1.status =1 and t1.type!=2 and t1.client_id =#{query.clientId}
        <if test="query.projectId != null">
            and t1.id = #{query.projectId}