فهرست منبع

Merge remote-tracking branch 'origin/20210223' into 20210223

wangyangyang 4 سال پیش
والد
کامیت
43328cf294
20فایلهای تغییر یافته به همراه658 افزوده شده و 222 حذف شده
  1. 22 0
      operation_manager/src/main/java/com/huaxu/annotation/Dict.java
  2. 193 0
      operation_manager/src/main/java/com/huaxu/aspect/DictAspect.java
  3. 50 45
      operation_manager/src/main/java/com/huaxu/evaluation/job/EvaluationResultJob.java
  4. 6 51
      operation_manager/src/main/java/com/huaxu/evaluation/service/impl/EvaluationResultServiceImpl.java
  5. 6 0
      operation_manager/src/main/java/com/huaxu/evaluation/vo/EvaluationReportRankingVo.java
  6. 1 0
      operation_manager/src/main/java/com/huaxu/evaluation/vo/EvaluationResultVo.java
  7. 45 8
      operation_manager/src/main/java/com/huaxu/order/controller/WorkOrderStatisticsController.java
  8. 2 2
      operation_manager/src/main/java/com/huaxu/order/dao/WorkOrderManageMapper.java
  9. 3 3
      operation_manager/src/main/java/com/huaxu/order/service/WorkOrderManageService.java
  10. 40 7
      operation_manager/src/main/java/com/huaxu/order/service/impl/WorkOrderManageServiceImpl.java
  11. 71 46
      operation_manager/src/main/java/com/huaxu/utils/EvaluationUtil.java
  12. 1 1
      operation_manager/src/main/resources/mapper/evaluation/EvaluationResultMapper.xml
  13. 18 2
      operation_manager/src/main/resources/mapper/order/WorkOrderManageMapper.xml
  14. 32 5
      sms_water/src/main/java/com/huaxu/controller/SceneController.java
  15. 1 0
      sms_water/src/main/java/com/huaxu/rabbitmq/AlarmDataHandler.java
  16. 1 0
      sms_water/src/main/java/com/huaxu/rabbitmq/ReceiveClearData.java
  17. 2 2
      sms_water/src/main/java/com/huaxu/rabbitmq/ReportWaterPumpStateHandler.java
  18. 36 2
      sms_water/src/main/java/com/huaxu/service/SceneService.java
  19. 17 6
      sms_water/src/main/java/com/huaxu/util/ReportExcelUtil.java
  20. 111 42
      sms_water/src/main/resources/mapper/SceneMapper.xml

+ 22 - 0
operation_manager/src/main/java/com/huaxu/annotation/Dict.java

@@ -0,0 +1,22 @@
+package com.huaxu.annotation;
+
+import java.lang.annotation.ElementType;
+import java.lang.annotation.Retention;
+import java.lang.annotation.RetentionPolicy;
+import java.lang.annotation.Target;
+
+/***
+ * 字典注解
+ * @author lihui
+ * @date 10:38 2021/5/24
+ **/
+@Target(ElementType.FIELD)
+@Retention(RetentionPolicy.RUNTIME)
+public @interface Dict {
+
+    String dicCode();
+
+    String dicText() default "";
+
+    String dictTable() default "";
+}

+ 193 - 0
operation_manager/src/main/java/com/huaxu/aspect/DictAspect.java

@@ -0,0 +1,193 @@
+package com.huaxu.aspect;
+
+import com.alibaba.fastjson.JSONObject;
+import com.fasterxml.jackson.annotation.JsonFormat;
+import com.fasterxml.jackson.core.JsonProcessingException;
+import com.fasterxml.jackson.databind.ObjectMapper;
+import com.huaxu.annotation.Dict;
+import com.huaxu.dict.DictUtil;
+import com.huaxu.model.AjaxMessage;
+import com.huaxu.model.Pagination;
+import lombok.extern.slf4j.Slf4j;
+import org.aspectj.lang.ProceedingJoinPoint;
+import org.aspectj.lang.annotation.Around;
+import org.aspectj.lang.annotation.Aspect;
+import org.aspectj.lang.annotation.Pointcut;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+
+import java.lang.reflect.Field;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Arrays;
+import java.util.Date;
+import java.util.List;
+
+/**
+ * @Description: 字典aop类
+ * @Author: lihui
+ * @Date: 2021-5-24
+ * @Version: 1.0
+ */
+@Aspect
+@Component
+@Slf4j
+public class  DictAspect {
+
+    private static final String DICT_TEXT_SUFFIX  = "_dict";
+
+    @Autowired
+    private DictUtil dictUtil;
+
+    /***
+     * 定义切点Pointcut
+     * @author lihui
+     * @date 11:26 2021/5/24
+     * @return void
+     **/
+    @Pointcut("execution(public * com.huaxu..*.*Controller.*(..))")
+    public void excudeService() {
+    }
+
+    @Around("excudeService()")
+    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
+        long time1 = System.currentTimeMillis();
+        Object result = pjp.proceed();
+        long time2 = System.currentTimeMillis();
+        log.debug("获取JSON数据 耗时:" + (time2 - time1) + "ms");
+        long start = System.currentTimeMillis();
+        this.parseDictText(result);
+        long end = System.currentTimeMillis();
+        log.debug("解析注入JSON数据  耗时" + (end - start) + "ms");
+        return result;
+    }
+
+    /**
+     * 本方法针对返回对象为Result 的IPage的分页列表数据进行动态字典注入
+     * 字典注入实现 通过对实体类添加注解@dict 来标识需要的字典内容,字典分为单字典code即可 ,table字典 code table text配合使用与原来jeecg的用法相同
+     * 示例为SysUser   字段为sex 添加了注解@Dict(dicCode = "sex") 会在字典服务立马查出来对应的text 然后在请求list的时候将这个字典text,已字段名称加_dict形式返回到前端
+     * 例输入当前返回值的就会多出一个sex_dictText字段
+     * {
+     * sex:1,
+     * sex_dictText:"男"
+     * }
+     * 前端直接取值sext_dict在table里面无需再进行前端的字典转换了
+     * customRender:function (text) {
+     * if(text==1){
+     * return "男";
+     * }else if(text==2){
+     * return "女";
+     * }else{
+     * return text;
+     * }
+     * }
+     * 目前vue是这么进行字典渲染到table上的多了就很麻烦了 这个直接在服务端渲染完成前端可以直接用
+     * @param result
+     */
+    private void parseDictText(Object result) {
+        if (!(result instanceof AjaxMessage)) {
+            return;
+        }
+        if (!(((AjaxMessage) result).getData() instanceof Pagination)) {
+            return;
+        }
+        List<JSONObject> items = new ArrayList<>();
+        List dataList = ((Pagination) ((AjaxMessage) result).getData()).getList();
+        for (Object record : dataList) {
+            ObjectMapper mapper = new ObjectMapper();
+            String json = "{}";
+            try {
+                //解决@JsonFormat注解解析不了的问题详见SysAnnouncement类的@JsonFormat
+                json = mapper.writeValueAsString(record);
+            } catch (JsonProcessingException e) {
+                log.error("json解析失败" + e.getMessage(), e);
+            }
+            JSONObject item = JSONObject.parseObject(json);
+            for (Field field : getAllFields(record)) {
+                if (field.getAnnotation(Dict.class) != null) {
+                    String code = field.getAnnotation(Dict.class).dicCode();
+                    String text = field.getAnnotation(Dict.class).dicText();
+                    String table = field.getAnnotation(Dict.class).dictTable();
+                    String key = String.valueOf(item.get(field.getName()));
+
+                    //翻译字典值对应的txt
+                    String textValue = translateDictValue(code, text, table, key);
+
+                    log.debug(" 字典Val : " + textValue);
+                    log.debug(" __翻译字典字段__ " + field.getName() + DICT_TEXT_SUFFIX + ": " + textValue);
+                    item.put(field.getName() + DICT_TEXT_SUFFIX, textValue);
+                }
+                //date类型默认转换string格式化日期
+                if (field.getType().getName().equals("java.util.Date") && field.getAnnotation(JsonFormat.class) == null && item.get(field.getName()) != null) {
+                    SimpleDateFormat aDate = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
+                    //解决日期较小的情况下被解析为Integer,最后导致导致强转为Long的报错问题
+                    item.put(field.getName(), aDate.format(new Date(Long.valueOf(String.valueOf(item.get(field.getName()))))));
+                }
+            }
+            items.add(item);
+        }
+        ((Pagination) ((AjaxMessage) result).getData()).setList(items);
+
+    }
+
+    /**
+     * 翻译字典文本
+     *
+     * @param code
+     * @param text
+     * @param table
+     * @param key
+     * @return
+     */
+    private String translateDictValue(String code, String text, String table, String key) {
+        if (isEmpty(key)) {
+            return null;
+        }
+        StringBuffer textValue = new StringBuffer();
+        String[] keys = key.split(",");
+        for (String k : keys) {
+            String tmpValue = null;
+            log.debug(" 字典 key : " + k);
+            if (k.trim().length() == 0) {
+                continue;
+            }
+            tmpValue = dictUtil.getDictName(code, Integer.parseInt(k.trim()));
+            if (tmpValue != null) {
+                if (!"".equals(textValue.toString())) {
+                    textValue.append(",");
+                }
+                textValue.append(tmpValue);
+            }
+        }
+        return textValue.toString();
+
+    }
+
+    private static Field[] getAllFields(Object object) {
+        Class<?> clazz = object.getClass();
+        List<Field> fieldList = new ArrayList<>();
+        while (clazz != null) {
+            fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
+            clazz = clazz.getSuperclass();
+        }
+        Field[] fields = new Field[fieldList.size()];
+        fieldList.toArray(fields);
+        return fields;
+    }
+
+    public static boolean isEmpty(Object object) {
+        if (object == null) {
+            return (true);
+        }
+        if ("".equals(object)) {
+            return (true);
+        }
+        if ("null".equals(object)) {
+            return (true);
+        }
+        return (false);
+    }
+
+}
+
+

+ 50 - 45
operation_manager/src/main/java/com/huaxu/evaluation/job/EvaluationResultJob.java

@@ -10,15 +10,12 @@ import com.huaxu.evaluation.enums.EvaluationCycleEnums;
 import com.huaxu.evaluation.enums.EvaluationItemEnums;
 import com.huaxu.evaluation.vo.EvaluationItemValueVo;
 import com.huaxu.evaluation.vo.EvaluationItemVo;
-import com.huaxu.evaluation.vo.EvaluationResultTaskDetailsVo;
 import com.huaxu.exception.ServiceException;
-import com.huaxu.model.AjaxMessage;
 import com.huaxu.order.dao.WorkOrderManageMapper;
 import com.huaxu.order.dto.WorkOrderManageDto;
 import com.huaxu.task.entity.UserEntity;
 import com.huaxu.util.DatesUtil;
 import com.huaxu.utils.EvaluationUtil;
-import io.swagger.models.auth.In;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.scheduling.annotation.Async;
@@ -31,7 +28,6 @@ import java.math.BigDecimal;
 import java.math.RoundingMode;
 import java.time.LocalDate;
 import java.util.*;
-import java.util.stream.Collectors;
 
 /**
  * @ClassName EvaluationResultJob
@@ -86,13 +82,13 @@ public class EvaluationResultJob {
 
 
     /***
-     *  @Scheduled(cron = "0/5 * * * * ?")
-     *  异步启动定时任务
+     *
+     *  异步启动定时任务,每天凌晨4点
      * @Author lihui
      * @Date 18:26 2021/5/17
      * @return void
      **/
-
+    @Scheduled(cron="0 0 4 * * ?")
     @Async
     public void run(){
         if (lock){
@@ -102,8 +98,9 @@ public class EvaluationResultJob {
         log.info("============绩效考评数据生成begin=====================");
         String startTime = null;
         String endTime   = null;
+        int today = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
         EvaluationCycleEntity queryEntity = new EvaluationCycleEntity();
-        queryEntity.setEvaluationDay(Calendar.getInstance().get(Calendar.DAY_OF_MONTH));
+        queryEntity.setEvaluationDay(today);
         // 首先查询当天哪些公司设置了绩效考评
         List<EvaluationCycleEntity> evaluationCycleEntities =  evaluationCycleMapper.findList(queryEntity);
         try {
@@ -114,8 +111,8 @@ public class EvaluationResultJob {
                     continue;
                 }
                 // 根据类型(0月度 1季度 2年度)得到当前的开始时间和结束时间,如果是按季度,当月必须是1,4,7,10
-                startTime = EvaluationUtil.getStartTime(evaluationCycleEntity.getType(), queryEntity.getEvaluationDay());
-                endTime   = EvaluationUtil.getEndTime(evaluationCycleEntity.getType(), queryEntity.getEvaluationDay());
+                startTime = EvaluationUtil.getStartTime(evaluationCycleEntity.getType(), today);
+                endTime   = EvaluationUtil.getEndTime(evaluationCycleEntity.getType(), today);
                 if (startTime == null || endTime == null) {
                     continue;
                 }
@@ -126,7 +123,8 @@ public class EvaluationResultJob {
         } finally {
             // 用完直接clear
             itemMap.clear();
-            //lock = false;
+            userInfoMap.clear();
+            lock = false;
         }
         log.info("============绩效考评数据生成end=====================");
     }
@@ -149,9 +147,9 @@ public class EvaluationResultJob {
             return;
         }
         for (UserEntity userEntity : userEntityList) {
-            itemEntityList = findItem(userEntity);
             // 1.获取部门考评项设置,如果未设置直接过滤
             // 2.判断部门考评项目设置里面有没有设置对应的考评周期,没有就直接过滤
+            itemEntityList = findItem(userEntity);
             if (CollectionUtil.isEmpty(itemEntityList) || !EvaluationUtil.containsType(itemEntityList, cycle)) {
                 continue;
             }
@@ -183,20 +181,28 @@ public class EvaluationResultJob {
     }
 
 
-    /**
-    * @Author lihui
-    * @Description  保存用户考评结果
-    * @Date 10:26 2021/5/11
-    * @Param [userEntity, itemEntityList, startTime, endTime, cycle]
-    * @return void
-    **/
+    /***
+     * 1.计算用户完成任务情况
+     * 2.组装考评结果数据
+     * 3.保存考评结果
+     * 4.计算得分范围,保存考评结果详情
+     * @author lihui
+     * @date 15:38 2021/5/21
+     * @param userEntity :
+     * @param itemEntityList :
+     * @param startTime :
+     * @param endTime :
+     * @param cycle :
+     * @return void
+     **/
     @Transactional(rollbackFor = Exception.class)
     public void saveEvaluationResultInfo(UserEntity userEntity, List<EvaluationItemVo> itemEntityList, String startTime, String endTime, Integer cycle){
+        // 条件值
+        BigDecimal evaluationValue = null;
         // 计算用户完成任务情况
-        EvaluationResultTaskEntity taskDetailsVo = calculationTaskInfo(userEntity.getId().intValue(), userEntity.getTenantId(), startTime, endTime, getValueCondition(itemEntityList));
-        // 组装考评结果数据
+        EvaluationResultTaskEntity taskDetailsVo = calculationTaskInfo(userEntity.getId().intValue(), userEntity.getTenantId(),
+                startTime, endTime, getValueCondition(itemEntityList));
         EvaluationResultEntity resultEntity = packagesEvaluationResultEntity(userEntity, cycle, startTime, endTime);
-        // 保存考评结果
         if (evaluationResultMapper.insertEvaluationResult(resultEntity) != 1) {
             throw new ServiceException(500, "保存考评结果出错,退出。");
         }
@@ -206,8 +212,9 @@ public class EvaluationResultJob {
         evaluationResultTaskMapper.insertEvaluationResultTask(taskDetailsVo);
         BigDecimal completeCount   = new BigDecimal(taskDetailsVo.getCompleteCount()) ;
         // 按时完成率
-        BigDecimal completionRate  = EvaluationUtil.divide(taskDetailsVo.getCompleteCount() - taskDetailsVo.getDelayCompleteCount(), taskDetailsVo.getTotalCount());
-        BigDecimal evaluationValue = null;
+        BigDecimal completionRate  = EvaluationUtil.onTimeCompletionRate(taskDetailsVo.getCompleteCount(),
+                taskDetailsVo.getDelayCompleteCount(), taskDetailsVo.getTotalCount());
+        // 保存考评分数
         for (EvaluationItemVo item : itemEntityList) {
             // 不是当前季度的,过滤
             if (item.getCycle().indexOf(cycle.toString()) == -1 || item.getType() == null) {
@@ -226,18 +233,23 @@ public class EvaluationResultJob {
         }
     }
 
-    /**
-    * @Author lihui
-    * @Description 计算用户完成任务情况
-    * @Date 17:38 2021/5/10
-    * @Param [userId, tenantId, startTime, endTime,valueCondition:延期时间多少分钟内算正常]
-    * @return void
-    **/
+    /***
+     * 计算用户完成任务情况
+     * @author lihui
+     * @date 15:51 2021/5/21
+     * @param userId :     用户ID
+     * @param tenantId :   租户ID
+     * @param startTime :  开始时间
+     * @param endTime :    结束时间
+     * @param valueCondition :  条件值
+     * @return com.huaxu.evaluation.entity.EvaluationResultTaskEntity
+     **/
     private EvaluationResultTaskEntity calculationTaskInfo(Integer userId, String tenantId, String startTime, String endTime, BigDecimal valueCondition) {
         int page = 1;
+        boolean completedBoolean = false;
         IPage<WorkOrderManageDto> iPage = null;
+        int conditionInt = valueCondition == null ? 0 : valueCondition.intValue();
         EvaluationResultTaskEntity taskEntity = new EvaluationResultTaskEntity();
-        boolean completedBoolean = false;
         while (true) {
             iPage = new Page<>(page, 200);
             // 查询该用户的工单和任务
@@ -251,15 +263,15 @@ public class EvaluationResultJob {
                 taskEntity.setCompleteCount(taskEntity.getCompleteCount() + (completedBoolean ? 1 : 0));
                 taskEntity.setNoCompleteCount(taskEntity.getNoCompleteCount() + (!completedBoolean ? 1 : 0));
                 // 计算完成的是否属于延期完成
-                if (completedBoolean && isDelay(dto, EvaluationUtil.minute(dto.getDateLimit())  + valueCondition.intValue())) {
+                if (completedBoolean && isDelay(dto, EvaluationUtil.minute(dto.getDateLimit())  + conditionInt)) {
                     taskEntity.setDelayCompleteCount(taskEntity.getDelayCompleteCount() + 1);
                 }
             }
             page ++;
         }
         // 计算完成率和延期率
-        taskEntity.setCompletionRate(EvaluationUtil.divide(taskEntity.getCompleteCount(),taskEntity.getTotalCount()));
-        taskEntity.setDelayRate(EvaluationUtil.divide(taskEntity.getDelayCompleteCount(),taskEntity.getTotalCount()));
+        taskEntity.setCompletionRate(EvaluationUtil.divide(taskEntity.getCompleteCount(),taskEntity.getTotalCount(), 4));
+        taskEntity.setDelayRate(EvaluationUtil.divide(taskEntity.getDelayCompleteCount(),taskEntity.getTotalCount(), 4));
         taskEntity.setTenantId(tenantId);
         taskEntity.setStatus(1);
         taskEntity.setDateCreate(new Date());
@@ -278,8 +290,8 @@ public class EvaluationResultJob {
      *    完成时间:finish_date
      * @author lihui
      * @date 10:56 2021/5/20
-     * @param dto :
-     * @param addMinute :
+     * @param dto : 请求参数
+     * @param addMinute : 增加的分钟数
      * @return boolean
      **/
     private boolean isDelay(WorkOrderManageDto dto, int addMinute){
@@ -348,14 +360,6 @@ public class EvaluationResultJob {
         return resultEntity;
     }
 
-    private Map<Long, UserEntity> toMap(List<Integer> userIds){
-        List<UserEntity> userEntities = userCenterClient.findUserIdsByUserIds(EvaluationUtil.toLong(userIds));
-        if (CollectionUtil.isEmpty(userEntities)){
-            return  null;
-        }
-        return userEntities.stream().collect(Collectors.toMap(UserEntity::getId, a -> a,(k1, k2)->k1));
-    }
-
     /***
      * 获取对应的分数
      * @Author lihui
@@ -410,4 +414,5 @@ public class EvaluationResultJob {
         return null;
     }
 
+
 }

+ 6 - 51
operation_manager/src/main/java/com/huaxu/evaluation/service/impl/EvaluationResultServiceImpl.java

@@ -18,7 +18,6 @@ import com.huaxu.model.LoginUser;
 import com.huaxu.org.OrgInfoUtil;
 import com.huaxu.util.UserUtil;
 import com.huaxu.utils.EvaluationUtil;
-import io.swagger.models.auth.In;
 import lombok.extern.slf4j.Slf4j;
 import org.apache.commons.lang3.StringUtils;
 import org.springframework.beans.BeanUtils;
@@ -26,7 +25,6 @@ import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
 
 import java.math.BigDecimal;
-import java.math.RoundingMode;
 import java.util.Arrays;
 import java.util.HashMap;
 import java.util.List;
@@ -76,6 +74,8 @@ public class EvaluationResultServiceImpl implements EvaluationResultService {
         Map<String,String> gradMap  = userCenterClient.selectListByPCodes("SC_EVALUATION_GRADE");
         for (EvaluationReportRankingVo evaluationReportRankingVo: list) {
             evaluationReportRankingVo.setEvaluationGrade(gradMap.get(evaluationReportRankingVo.getEvaluationGrade()));
+            evaluationReportRankingVo.setCompletionRate(EvaluationUtil.onTimeCompletionRate(evaluationReportRankingVo.getCompleteCount(),
+                    evaluationReportRankingVo.getDelayCompleteCount(), evaluationReportRankingVo.getTotalCount()).divide(new BigDecimal("100"),2));
         }
         return list;
     }
@@ -112,7 +112,7 @@ public class EvaluationResultServiceImpl implements EvaluationResultService {
             return null;
         }
         if (queryDto.getCycle() == EvaluationCycleEnums.QUARTER.getType()) {
-            queryDto.setMonths(formatList(queryDto.getCycle(), queryDto.getMonth()));
+            queryDto.setMonths(EvaluationUtil.formatList(queryDto.getMonth()));
         }
         queryDto.setCycle(0);
         return evaluationResultMapper.countQualifiedNumber(queryDto, qualifiedValue);
@@ -128,7 +128,7 @@ public class EvaluationResultServiceImpl implements EvaluationResultService {
             return null;
         }
         if (queryDto.getCycle() == EvaluationCycleEnums.QUARTER.getType()) {
-            queryDto.setMonths(formatList(queryDto.getCycle(), queryDto.getMonth()));
+            queryDto.setMonths(EvaluationUtil.formatList(queryDto.getMonth()));
         }
         queryDto.setCycle(0);
         return evaluationResultMapper.countPerformanceAvg(queryDto);
@@ -167,7 +167,7 @@ public class EvaluationResultServiceImpl implements EvaluationResultService {
         queryDto.setPermissonType(currentUser.getPermissonType());
         // 季度需要格式化月份
         if (queryDto.getCycle() != null && queryDto.getCycle() == EvaluationCycleEnums.QUARTER.getType()){
-            queryDto.setMonth(format(queryDto.getCycle(), queryDto.getMonth()));
+            queryDto.setMonth(EvaluationUtil.format(queryDto.getMonth()));
         }
         return queryDto;
     }
@@ -184,7 +184,7 @@ public class EvaluationResultServiceImpl implements EvaluationResultService {
         BeanUtils.copyProperties(dto, queryDto);
         // 季度需要格式化月份
         if (dto.getCycle() == EvaluationCycleEnums.QUARTER.getType()){
-            queryDto.setMonth(format(dto.getCycle(), dto.getMonth()));
+            queryDto.setMonth(EvaluationUtil.format(dto.getMonth()));
         }
         // 获取用户权限
         LoginUser currentUser = UserUtil.getCurrentUser();
@@ -243,49 +243,4 @@ public class EvaluationResultServiceImpl implements EvaluationResultService {
     }
 
 
-    private Integer format(Integer cycle, Integer month){
-        if (cycle == null) {
-            throw new ServiceException(EvaluationResultStatus.PARAM_ERROR.getStatus(), EvaluationResultStatus.PARAM_ERROR.getMessage());
-        }
-        // 季度需要格式化
-        if (month == null){
-            throw new ServiceException(EvaluationResultStatus.PARAM_ERROR.getStatus(), EvaluationResultStatus.PARAM_ERROR.getMessage());
-        }
-        if (month == 1) {
-            return 3;
-        } else if (month == 2 ){
-            return 6;
-        } else if (month == 3) {
-            return 9;
-        } else if (month == 4) {
-            return 12;
-        } else {
-            throw new ServiceException(EvaluationResultStatus.PARAM_ERROR.getStatus(), EvaluationResultStatus.PARAM_ERROR.getMessage());
-        }
-    }
-
-    private List<Integer> formatList(Integer cycle, Integer month){
-        if (cycle == null) {
-            throw new ServiceException(EvaluationResultStatus.PARAM_ERROR.getStatus(), EvaluationResultStatus.PARAM_ERROR.getMessage());
-        }
-        // 季度需要格式化
-        if (month == null){
-            throw new ServiceException(EvaluationResultStatus.PARAM_ERROR.getStatus(), EvaluationResultStatus.PARAM_ERROR.getMessage());
-        }
-        if (month == 3) {
-            return Arrays.asList(1,2,3);
-        } else if (month == 6 ){
-            return Arrays.asList(4,5,6);
-        } else if (month == 9) {
-            return Arrays.asList(7,8,9);
-        } else if (month == 12) {
-            return Arrays.asList(10,11,12);
-        } else {
-            throw new ServiceException(EvaluationResultStatus.PARAM_ERROR.getStatus(), EvaluationResultStatus.PARAM_ERROR.getMessage());
-        }
-    }
-
-    public static void main(String[] args) {
-        System.out.println(new BigDecimal(1).divide( new BigDecimal(1),4, BigDecimal.ROUND_HALF_DOWN).multiply(new BigDecimal("100")).setScale(2, BigDecimal.ROUND_HALF_DOWN));
-    }
 }

+ 6 - 0
operation_manager/src/main/java/com/huaxu/evaluation/vo/EvaluationReportRankingVo.java

@@ -30,6 +30,12 @@ public class EvaluationReportRankingVo {
     @ApiModelProperty(value = "已完成")
     private int completeCount;
 
+    @ApiModelProperty(value = "延期完成数")
+    private int delayCompleteCount;
+
+    @ApiModelProperty(value = "延期完成数")
+    private int totalCount;
+
     @ApiModelProperty(value = "完成率")
     private BigDecimal completionRate;
 

+ 1 - 0
operation_manager/src/main/java/com/huaxu/evaluation/vo/EvaluationResultVo.java

@@ -1,6 +1,7 @@
 package com.huaxu.evaluation.vo;
 
 import com.fasterxml.jackson.annotation.JsonIgnore;
+import com.huaxu.annotation.Dict;
 import io.swagger.annotations.ApiModel;
 import io.swagger.annotations.ApiModelProperty;
 import lombok.Data;

+ 45 - 8
operation_manager/src/main/java/com/huaxu/order/controller/WorkOrderStatisticsController.java

@@ -200,7 +200,12 @@ public class WorkOrderStatisticsController {
             case 1:
                 maintainerCount = userCenterClient.findMaintainerCount(String.format("%s-12",startDate));
                 startDate = String.format("%s-01-01", startDate);
-                endDate = subYear(startDate, 1);
+                if(isCurrentYear(startDate)==true){
+                    endDate = String.format("%s-%s-01", localDate.getYear(),localDate.getMonthValue()+1);
+                }
+                else {
+                    endDate = subYear(startDate, 1);
+                }
                 break;
             case 2:
                 maintainerCount = userCenterClient.findMaintainerCount(endDate);
@@ -290,15 +295,21 @@ public class WorkOrderStatisticsController {
     @RequestMapping(value = "dispatchTimesStatistics", method = RequestMethod.GET)
     @ApiOperation(value = "派单次数统计")
     public AjaxMessage<List<Map<String,Object>>> dispatchTimesStatistics(
-            @ApiParam(value = "场景ID", required = true) @RequestParam(required = true) int scenesId,
+            @ApiParam(value = "场景ID", required = true) @RequestParam(required = true) String scenesId,
             @ApiParam(value = "设备ID", required = true) @RequestParam(required = true) int id,
             @ApiParam(value = "设备或场景标识(1:设备;2:场景)", required = true) @RequestParam(required = true) int sort,
             @ApiParam(value = "统计类型:0-按月统计,1-按年统计,2-自定义统计", required = true) @RequestParam(required = true) int statsType,
             @ApiParam(value = "统计时间:月格式(yyyy-MM),年格式(yyyy),自定义统计时间开始日期", required = true) @RequestParam(required = true) String startDate,
             @ApiParam(value = "统计时间:年月统计不用传入此参数,自定义统计截至日期", required = false) @RequestParam(required = false) String endDate) throws ParseException {
         LocalDate localDate = LocalDate.now();
+        LoginUser loginUser = UserUtil.getCurrentUser();
         List<Map<String,Object>> statistics = new ArrayList<Map<String, Object>>();
         WorkOrderManageDto workOrderManageDto = new WorkOrderManageDto();
+        workOrderManageDto.setTenantId(loginUser.getTenantId());
+        workOrderManageDto.setProgramItems(loginUser.getProgramItemList());
+        workOrderManageDto.setUserType(loginUser.getType());
+        //1是公司,2是公司及以下,3部门,4部门及以下,5自定义
+        workOrderManageDto.setPermissonType(loginUser.getPermissonType());
         switch (statsType) {
             case 0:
                 startDate = String.format("%s-01", startDate);
@@ -311,7 +322,12 @@ public class WorkOrderStatisticsController {
                 break;
             case 1:
                 startDate = String.format("%s-01-01", startDate);
-                endDate = subYear(startDate, 1);
+                if(isCurrentYear(startDate)==true){
+                    endDate = String.format("%s-%s-01", localDate.getYear(),localDate.getMonthValue()+1);
+                }
+                else {
+                    endDate = subYear(startDate, 1);
+                }
                 break;
             case 2:
                 startDate = String.format("%s-01", startDate);
@@ -324,17 +340,22 @@ public class WorkOrderStatisticsController {
                 }
                 break;
         }
-        workOrderManageDto.setScenesId(scenesId);
+        List<String> idsList = null;
         workOrderManageDto.setStartDate(startDate);
         workOrderManageDto.setEndDate(endDate);
          if(sort==1){
            workOrderManageDto.setDeviceId(id);
-        }
-        if(statsType ==0 || statsType ==2){
-            statistics =  workOrderManageService.dispatchTimesMonthStatistics(workOrderManageDto);
+           idsList = new ArrayList<String>();
+           String [] ids = scenesId.split(",");
+           idsList = Arrays.asList(ids);
+        } else if (sort ==2){
+             workOrderManageDto.setScenesId(Integer.parseInt(scenesId));
+         }
+        if(statsType ==0 || statsType ==2) {
+            statistics = workOrderManageService.dispatchTimesMonthStatistics(workOrderManageDto, idsList);
         }
         else if(statsType == 1){
-            statistics =  workOrderManageService.dispatchTimesYearStatistics(workOrderManageDto);
+            statistics =  workOrderManageService.dispatchTimesYearStatistics(workOrderManageDto,idsList);
         }
         return new AjaxMessage<>(ResultStatus.OK, statistics);
     }
@@ -481,4 +502,20 @@ public class WorkOrderStatisticsController {
         }
         return false;
     }
+
+    /**
+     * 日期是否当前月份
+     */
+    public boolean isCurrentYear(String date) throws ParseException {
+        LocalDate localDate = LocalDate.now();
+        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
+        Date dt = sdf.parse(date);
+        Calendar rightNow = Calendar.getInstance();
+        rightNow.setTime(dt);
+        int y = rightNow.get(Calendar.YEAR);
+        if( y== localDate.getYear()){
+            return true;
+        }
+        return false;
+    }
 }

+ 2 - 2
operation_manager/src/main/java/com/huaxu/order/dao/WorkOrderManageMapper.java

@@ -97,12 +97,12 @@ public interface WorkOrderManageMapper {
     /**
      * 派单次数月统计
      */
-    List<Map<String,Object>> dispatchTimesMonthStatistics(@Param("order") WorkOrderManageDto workOrderManageDto);
+    List<Map<String,Object>> dispatchTimesMonthStatistics(@Param("order") WorkOrderManageDto workOrderManageDto, @Param("list") List<String> list);
 
     /**
      * 派单次数年统计
      */
-    List<Map<String,Object>> dispatchTimesYearStatistics(@Param("order") WorkOrderManageDto workOrderManageDto);
+    List<Map<String,Object>> dispatchTimesYearStatistics(@Param("order") WorkOrderManageDto workOrderManageDto, @Param("list") List<String> list);
 
     /**
      * 待处理权限

+ 3 - 3
operation_manager/src/main/java/com/huaxu/order/service/WorkOrderManageService.java

@@ -95,7 +95,7 @@ public interface WorkOrderManageService {
 
     List<Map<String,Object>> eventMonthStatistics(@Param("order") WorkOrderManageDto workOrderManageDto) throws ParseException;
 
-    List<Map<String,Object>> eventYearStatistics(@Param("order") WorkOrderManageDto workOrderManageDto);
+    List<Map<String,Object>> eventYearStatistics(@Param("order") WorkOrderManageDto workOrderManageDto) throws ParseException;
     /**
      * 待处理权限
      */
@@ -134,12 +134,12 @@ public interface WorkOrderManageService {
     /**
      * 判单次数月统计
      */
-    List<Map<String,Object>> dispatchTimesMonthStatistics(@Param("order") WorkOrderManageDto workOrderManageDto) throws ParseException;
+    List<Map<String,Object>> dispatchTimesMonthStatistics(WorkOrderManageDto workOrderManageDto,List<String> list) throws ParseException;
 
     /**
      * 判单次数年统计
      */
-    List<Map<String,Object>> dispatchTimesYearStatistics(@Param("order") WorkOrderManageDto workOrderManageDto);
+    List<Map<String,Object>> dispatchTimesYearStatistics( WorkOrderManageDto workOrderManageDto,List<String> list) throws ParseException;
 
 
     /**

+ 40 - 7
operation_manager/src/main/java/com/huaxu/order/service/impl/WorkOrderManageServiceImpl.java

@@ -183,10 +183,11 @@ public class WorkOrderManageServiceImpl implements WorkOrderManageService {
     }
 
     @Override
-    public List<Map<String, Object>> eventYearStatistics(WorkOrderManageDto workOrderManageDto) {
+    public List<Map<String, Object>> eventYearStatistics(WorkOrderManageDto workOrderManageDto) throws ParseException {
+        int months = differentMonths(workOrderManageDto.getStartDate(),workOrderManageDto.getEndDate());
         List<Map<String,Object>> list = workOrderManageMapper.eventYearStatistics(workOrderManageDto);
         List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
-        for(int i=0; i<12; i++) {
+        for(int i=0; i<months; i++) {
             String strDate = workOrderManageDto.getStartDate().substring(0, 4) + String.format("-%02d", i + 1);
             Map<String, Object> data = new HashMap<>();
             data.put("数量", 0);
@@ -253,10 +254,10 @@ public class WorkOrderManageServiceImpl implements WorkOrderManageService {
     }
 
     @Override
-    public List<Map<String, Object>> dispatchTimesMonthStatistics(WorkOrderManageDto workOrderManageDto) throws ParseException {
+    public List<Map<String, Object>> dispatchTimesMonthStatistics(WorkOrderManageDto workOrderManageDto,List<String> idsList) throws ParseException {
         int days = differentDaysByMillisecond(workOrderManageDto.getStartDate(),workOrderManageDto.getEndDate());
         List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
-        List<Map<String,Object>> list = workOrderManageMapper.dispatchTimesMonthStatistics(workOrderManageDto);
+        List<Map<String,Object>> list = workOrderManageMapper.dispatchTimesMonthStatistics(workOrderManageDto,idsList);
         for(int i=0; i<days; i++) {
             String strDate =  subDay(workOrderManageDto.getStartDate(),i);
             Map<String, Object> data = new HashMap<>();
@@ -274,10 +275,11 @@ public class WorkOrderManageServiceImpl implements WorkOrderManageService {
     }
 
     @Override
-    public List<Map<String, Object>> dispatchTimesYearStatistics(WorkOrderManageDto workOrderManageDto) {
-        List<Map<String,Object>> list = workOrderManageMapper.dispatchTimesYearStatistics(workOrderManageDto);
+    public List<Map<String, Object>> dispatchTimesYearStatistics(WorkOrderManageDto workOrderManageDto, List<String> idsList) throws ParseException {
+        int months = differentMonths(workOrderManageDto.getStartDate(),workOrderManageDto.getEndDate());
+        List<Map<String,Object>> list = workOrderManageMapper.dispatchTimesYearStatistics(workOrderManageDto,idsList);
         List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
-        for(int i=0; i<12; i++) {
+        for(int i=0; i<months; i++) {
             String strDate = workOrderManageDto.getStartDate().substring(0, 4) + String.format("-%02d", i + 1);
             Map<String, Object> data = new HashMap<>();
             data.put("数量", 0);
@@ -313,6 +315,37 @@ public class WorkOrderManageServiceImpl implements WorkOrderManageService {
     }
 
 
+    /**
+     * 计算2个日期之间相差的  以年、月、日为单位,各自计算结果是多少
+     * 比如:2011-02-02 到  2017-03-02
+     *                                以年为单位相差为:6年
+     *                                以月为单位相差为:73个月
+     *                                以日为单位相差为:2220天
+     * @param startDate
+     * @param endDate
+     * @return
+     */
+    public int differentMonths(String startDate,String endDate) throws ParseException {
+        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
+        Date fromDate = sdf.parse(startDate);
+        Date toDate = sdf.parse(endDate);
+        Calendar  from  =  Calendar.getInstance();
+        from.setTime(fromDate);
+        Calendar  to  =  Calendar.getInstance();
+        to.setTime(toDate);
+        //只要年月
+        int fromYear = from.get(Calendar.YEAR);
+        int fromMonth = from.get(Calendar.MONTH);
+
+        int toYear = to.get(Calendar.YEAR);
+        int toMonth = to.get(Calendar.MONTH);
+        // int year = toYear  -  fromYear;
+        int month = toYear *  12  + toMonth  -  (fromYear  *  12  +  fromMonth);
+        // int day = (int) ((to.getTimeInMillis()  -  from.getTimeInMillis())  /  (24  *  3600  *  1000));
+        return month;
+    }
+
+
     /**
      *日期加一天
      */

+ 71 - 46
operation_manager/src/main/java/com/huaxu/utils/EvaluationUtil.java

@@ -1,8 +1,10 @@
 package com.huaxu.utils;
 
 import com.huaxu.evaluation.enums.EvaluationCycleEnums;
+import com.huaxu.evaluation.enums.EvaluationResultStatus;
 import com.huaxu.evaluation.vo.EvaluationItemVo;
 import com.huaxu.evaluation.vo.EvaluationResultVo;
+import com.huaxu.exception.ServiceException;
 import com.huaxu.order.dto.WorkOrderManageDto;
 import com.huaxu.util.DatesUtil;
 import org.apache.commons.lang3.StringUtils;
@@ -71,16 +73,31 @@ public class EvaluationUtil {
     /**
      * 工单类型
      */
-    static List<Integer> workList = Arrays.asList(1,2,3,4,5,6);
+    static List<Integer> workList = Arrays.asList(1,2,3,4,5,6,10);
 
-    private static Calendar getCalendar(){
-        return Calendar.getInstance();
+    /**
+     * @Author lihui
+     * @Description 是否是同月
+     * @Date 18:14 2021/5/11
+     * @Param [month]
+     * @return boolean
+     **/
+    public static boolean sameMonth(int month){
+        return Calendar.getInstance().get(Calendar.MONTH) + 1  == month;
     }
 
-    public static Calendar getCalendar (String dateTime){
-        Calendar calendar = getCalendar();
-        calendar.setTime(DatesUtil.parseDate(dateTime, "yyyy-MM-dd HH:mm:ss"));
-        return calendar;
+    /***
+     * 计算按时完成率=(完成数-延期完成数)/任务总数
+     * @author lihui
+     * @date 15:35 2021/5/21
+     * @param completeCount :
+     * @param delayCompleteCount :
+     * @param totalCount :
+     * @return java.math.BigDecimal
+     **/
+    public static BigDecimal onTimeCompletionRate(int completeCount, int delayCompleteCount, int totalCount){
+        return divide(completeCount - delayCompleteCount,
+                totalCount, 4).multiply(new BigDecimal("100"));
     }
 
     /**
@@ -134,14 +151,14 @@ public class EvaluationUtil {
         return lon == null ? null : lon.intValue();
     }
 
-    public static BigDecimal divide(Integer completeCount, Integer total){
+    public static BigDecimal divide(Integer completeCount, Integer total, int scale){
         String defaultValue = "0";
         BigDecimal bigDecimalComplete =  new BigDecimal(completeCount.toString());
         BigDecimal bigDecimalTotal =  new BigDecimal(total.toString());
         if (bigDecimalTotal.compareTo(new BigDecimal(defaultValue)) == 0){
             return new BigDecimal(defaultValue);
         }
-        return bigDecimalComplete.divide(bigDecimalTotal,2, RoundingMode.HALF_UP);
+        return bigDecimalComplete.divide(bigDecimalTotal, scale, RoundingMode.HALF_UP);
     }
 
     /**
@@ -183,37 +200,6 @@ public class EvaluationUtil {
         return finishDate.after(DatesUtil.addMinuteOfDate(planFinishDate,addMinute));
     }
 
-    public static Long[] toLong (List<Integer> userIds){
-        Long [] longs = new Long[userIds.size()];
-        for (int i = 0 ; i < userIds.size(); i++) {
-            longs[i] =Long.parseLong(userIds.get(i).toString()) ;
-        }
-        return longs;
-    }
-
-    /**
-    * @Author lihui
-    * @Description 是否是当天
-    * @Date 17:08 2021/5/11
-    * @Param [evaluationDay]
-    * @return boolean
-    **/
-    public static boolean isToday(int evaluationDay){
-        return Calendar.getInstance().get(Calendar.DAY_OF_MONTH)  == evaluationDay;
-    }
-
-    /**
-    * @Author lihui
-    * @Description 是否是同月
-    * @Date 18:14 2021/5/11
-    * @Param [month]
-    * @return boolean
-    **/
-    public static boolean sameMonth(int month){
-        return Calendar.getInstance().get(Calendar.MONTH) + 1  == month;
-    }
-
-
     public static boolean containsType(List<EvaluationItemVo> itemEntityList, Integer type){
         List<String> list = itemEntityList.stream().map(EvaluationItemVo::getCycle).collect(Collectors.toList());
         for (String str: list) {
@@ -240,12 +226,6 @@ public class EvaluationUtil {
         return null;
     }
 
-
-    private static String toString (Integer var){
-        String result = var.toString();
-        return result.length() == 1 ?   "0" + result : result;
-    }
-
     public static String getStartTime(int cycle, int day) {
         LocalDate localDate = LocalDate.now();
         if (cycle == EvaluationCycleEnums.MONTH.getType()) {
@@ -415,6 +395,51 @@ public class EvaluationUtil {
         return "";
     }
 
+
+    /***
+     * 根据1-4季度,获取对应末尾的月份
+     * @author lihui
+     * @date 14:53 2021/5/21
+     * @param cycle : 季度
+     * @return java.lang.Integer
+     **/
+    public static Integer format(Integer cycle){
+        switch (cycle) {
+            case 1 :
+                return 3;
+            case 2 :
+                return 6;
+            case 3 :
+                return 9;
+            case 4:
+                return 12;
+            default:
+                throw new ServiceException(EvaluationResultStatus.PARAM_ERROR.getStatus(), EvaluationResultStatus.PARAM_ERROR.getMessage());
+        }
+    }
+
+    /**
+     * 根据1-4季度末尾月份,获取每个季度对应的月份
+     * @author lihui
+     * @date 14:54 2021/5/21
+     * @param month : 月份
+     * @return java.util.List<java.lang.Integer>
+     **/
+    public static List<Integer> formatList(Integer month){
+        switch (month) {
+            case 3 :
+                return Arrays.asList(1,2,3);
+            case 6 :
+                return Arrays.asList(4,5,6);
+            case 9 :
+                return Arrays.asList(7,8,9);
+            case 12:
+                return Arrays.asList(10,11,12);
+            default:
+                throw new ServiceException(EvaluationResultStatus.PARAM_ERROR.getStatus(), EvaluationResultStatus.PARAM_ERROR.getMessage());
+        }
+    }
+
     public static void main(String[] args) {
         System.out.println(EvaluationUtil.getStartTime(1, 15));
         System.out.println(EvaluationUtil.getEndTime(1, 15));

+ 1 - 1
operation_manager/src/main/resources/mapper/evaluation/EvaluationResultMapper.xml

@@ -110,7 +110,7 @@
     </update>
     
     <select id="findRanking" resultType="com.huaxu.evaluation.vo.EvaluationReportRankingVo">
-        select a.EVALUATION_BE,a.VALUE,a.EVALUATION_GRADE,t.COMPLETE_COUNT,t.COMPLETION_RATE
+        select a.EVALUATION_BE,a.VALUE,a.EVALUATION_GRADE,t.COMPLETE_COUNT,t.COMPLETION_RATE,t.DELAY_COMPLETE_COUNT,t.TOTAL_COUNT
         from sc_evaluation_result a
         inner join sc_evaluation_result_task t on a.id = t.EVALUATION_RESULT_ID
         <where>

+ 18 - 2
operation_manager/src/main/resources/mapper/order/WorkOrderManageMapper.xml

@@ -1203,7 +1203,15 @@
       from sc_work_order_manage t1
       where t1.send_time &gt;= date_format(#{order.startDate,jdbcType=VARCHAR},'%Y-%m-%d')
       and t1.send_time &lt; date_format(#{order.endDate,jdbcType=VARCHAR},'%Y-%m-%d')
-      and t1.scenes_id= #{order.scenesId,jdbcType=INTEGER}
+      <if test="list == null">
+        and t1.scenes_id= #{order.scenesId,jdbcType=INTEGER}
+      </if>
+      <if test="list != null">
+        and t1.scenes_id in
+        <foreach collection="list" item="item" open="(" close=")" separator=",">
+          #{item,jdbcType=INTEGER}
+        </foreach>
+      </if>
       <if test="order.deviceId != null">
         and device_id = #{order.deviceId,jdbcType=INTEGER}
       </if>
@@ -1215,7 +1223,15 @@
     from sc_work_order_manage t1
     where t1.send_time &gt;= date_format(#{order.startDate,jdbcType=VARCHAR},'%Y-%m-%d')
     and t1.send_time &lt; date_format(#{order.endDate,jdbcType=VARCHAR},'%Y-%m-%d')
-    and t1.scenes_id= #{order.scenesId,jdbcType=INTEGER}
+    <if test="list == null">
+      and t1.scenes_id= #{order.scenesId,jdbcType=INTEGER}
+    </if>
+    <if test="list != null">
+      and t1.scenes_id in
+      <foreach collection="list" item="item" open="(" close=")" separator=",">
+        #{item,jdbcType=INTEGER}
+      </foreach>
+    </if>
     <if test="order.deviceId != null">
       and device_id = #{order.deviceId,jdbcType=INTEGER}
     </if>

+ 32 - 5
sms_water/src/main/java/com/huaxu/controller/SceneController.java

@@ -226,9 +226,7 @@ public class SceneController {
             @ApiParam(value = "统计类型:0-按月统计,1-按年统计,2-自定义统计", required = true) @RequestParam(required = true) int statsType,
             @ApiParam(value = "统计时间:月格式(yyyy-MM),年格式(yyyy),自定义统计时间开始日期", required = true) @RequestParam(required = true) String startDate,
             @ApiParam(value = "统计时间:年月统计不用传入此参数,自定义统计截至日期", required = false) @RequestParam(required = false) String endDate) throws ParseException {
-
         LocalDate localDate = LocalDate.now();
-
         LoginUser loginUser = UserUtil.getCurrentUser();
         SceneEntity sceneEntity = new SceneEntity();
         sceneEntity.setTenantId(loginUser.getTenantId());
@@ -251,7 +249,7 @@ public class SceneController {
                 int year = Integer.parseInt(startDate);
                 if(year == localDate.getYear()){
                     days = differentDaysByMillisecond(String.format("%s-%s-%s",startDate,1,1),
-                            String.format("%s-%s-%s",localDate.getYear(),localDate.getMonthValue(),localDate.getDayOfMonth()));
+                            String.format("%s-%s-%s",localDate.getYear(),localDate.getMonthValue(),localDate.getDayOfMonth()+1));
                 }
                 else {
                     days = LocalDate.of(year, 1, 1).lengthOfYear();
@@ -313,7 +311,6 @@ public class SceneController {
         return new AjaxMessage<>(ResultStatus.OK, list);
     }
 
-
     @RequestMapping(value = "/alarmTimesStatistics", method = RequestMethod.GET)
     @ResponseBody
     @ApiOperation(value = "报警次数统计")
@@ -324,7 +321,13 @@ public class SceneController {
             @ApiParam(value = "统计时间:月格式(yyyy-MM),年格式(yyyy),自定义统计时间开始日期", required = true) @RequestParam(required = true) String startDate,
             @ApiParam(value = "统计时间:年月统计不用传入此参数,自定义统计截至日期", required = false) @RequestParam(required = false) String endDate) throws ParseException {
         LocalDate localDate = LocalDate.now();
+        LoginUser loginUser = UserUtil.getCurrentUser();
         SceneEntity sceneEntity = new SceneEntity();
+        sceneEntity.setTenantId(loginUser.getTenantId());
+        sceneEntity.setProgramItems(loginUser.getProgramItemList());
+        sceneEntity.setUserType(loginUser.getType());
+        //1是公司,2是公司及以下,3部门,4部门及以下,5自定义
+        sceneEntity.setPermissonType(loginUser.getPermissonType());
         sceneEntity.setId(Long.parseLong(String.valueOf(id)));
         switch (statsType) {
             case 0:
@@ -338,7 +341,12 @@ public class SceneController {
                 break;
             case 1:
                 startDate = String.format("%s-01-01", startDate);
-                endDate = subYear(startDate, 1);
+                if(isCurrentYear(startDate)==true){
+                    endDate = String.format("%s-%s-01", localDate.getYear(),localDate.getMonthValue()+1);
+                }
+                else {
+                    endDate = subYear(startDate, 1);
+                }
                 break;
             case 2:
                 startDate = String.format("%s-01", startDate);
@@ -422,6 +430,8 @@ public class SceneController {
     }
 
 
+
+
     public int differentDaysByMillisecond(String date1,String date2) throws ParseException {
         SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
         Date dt1 = sdf.parse(date1);
@@ -493,4 +503,21 @@ public class SceneController {
             return pattern.matcher(str).matches();
         }
     }
+
+
+    /**
+     * 日期是否当前月份
+     */
+    public boolean isCurrentYear(String date) throws ParseException {
+        LocalDate localDate = LocalDate.now();
+        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
+        Date dt = sdf.parse(date);
+        Calendar rightNow = Calendar.getInstance();
+        rightNow.setTime(dt);
+        int y = rightNow.get(Calendar.YEAR);
+        if( y== localDate.getYear()){
+            return true;
+        }
+        return false;
+    }
 }

+ 1 - 0
sms_water/src/main/java/com/huaxu/rabbitmq/AlarmDataHandler.java

@@ -56,6 +56,7 @@ public class AlarmDataHandler {
 
     @Async
     public void hanlder(MonitorDataEntity monitorDataEntity, JSONObject receiveData, Date receiveDateTime){
+        log.info("rabbitMq处理报警,code:{},上报时间:{}",monitorDataEntity.getDeviceCode(), receiveDateTime);
         // 校验各参数异常情况
         Double receivedValue            = null;
         List<AlarmDetailsEntity> insert = null;

+ 1 - 0
sms_water/src/main/java/com/huaxu/rabbitmq/ReceiveClearData.java

@@ -80,6 +80,7 @@ public class ReceiveClearData {
         JSONObject jsonObject = JSONObject.parseObject(new String(receivedData));
         String eventTime      = jsonObject.getString("eventTime");
         String deviceCode     = jsonObject.getString("unitIdentifier");
+        log.info("rabbitMq接收消息处理,code:{},上报时间:{}",deviceCode, eventTime);
         // 对象有时间、有设备编码、有数据则解析,任何一个位空直接退出
         if (!jsonObject.containsKey("eventTime") || !jsonObject.containsKey("unitIdentifier") ||
                 !jsonObject.containsKey("parsedData")) {

+ 2 - 2
sms_water/src/main/java/com/huaxu/rabbitmq/ReportWaterPumpStateHandler.java

@@ -50,7 +50,7 @@ public class ReportWaterPumpStateHandler {
     @Async
     public void handler(MonitorDataEntity monitorDataEntity, JSONObject receiveData, Date receiveDateTime){
 
-        log.info("【水泵运行状态报表:{}】开始处理", monitorDataEntity.getDeviceCode());
+        log.info("【rabbitMq处理报警水泵运行状态报表:{}】开始处理", monitorDataEntity.getDeviceCode());
         // 0 运行, 1停止
         int state = 0;
         // 执行批量插入操作
@@ -85,7 +85,7 @@ public class ReportWaterPumpStateHandler {
                 reportWaterPumpStateMapper.batchInsertReportWaterPumpState(insertList);
             }
         }
-        log.info("【水泵运行状态报表:{}】结束处理,新增:{}", monitorDataEntity.getDeviceCode(),insertList.size());
+        log.info("【rabbitMq处理报警水泵运行状态报表:{}】结束处理,新增:{}", monitorDataEntity.getDeviceCode(),insertList.size());
     }
 
     private List<String> toList(List<DeviceAttributeSpecsEntity> list){

+ 36 - 2
sms_water/src/main/java/com/huaxu/service/SceneService.java

@@ -481,10 +481,11 @@ public class SceneService extends ServiceImpl<SceneMapper, SceneEntity> {
         return result;
     }
 
-    public List<Map<String,Object>> selectYearAlarmTimes(@Param("scene") SceneEntity sceneEntity, @Param("startDate") String startDate, @Param("endDate") String endDate,@Param("sort") int sort){
+    public List<Map<String,Object>> selectYearAlarmTimes(@Param("scene") SceneEntity sceneEntity, @Param("startDate") String startDate, @Param("endDate") String endDate,@Param("sort") int sort) throws ParseException {
+        int months = differentMonths(startDate,endDate);
         List<Map<String,Object>> list = sceneMapper.selectYearAlarmTimes(sceneEntity,startDate,endDate,sort);
         List<Map<String,Object>> result = new ArrayList<Map<String,Object>>();
-        for(int i=0; i<12; i++) {
+        for(int i=0; i<months; i++) {
             String strDate = startDate.substring(0, 4) + String.format("-%02d", i + 1);
             Map<String, Object> data = new HashMap<>();
             data.put("数量", 0);
@@ -521,6 +522,39 @@ public class SceneService extends ServiceImpl<SceneMapper, SceneEntity> {
         return days;
     }
 
+
+
+    /**
+     * 计算2个日期之间相差的  以年、月、日为单位,各自计算结果是多少
+     * 比如:2011-02-02 到  2017-03-02
+     *                                以年为单位相差为:6年
+     *                                以月为单位相差为:73个月
+     *                                以日为单位相差为:2220天
+     * @param startDate
+     * @param endDate
+     * @return
+     */
+    public int differentMonths(String startDate,String endDate) throws ParseException {
+        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
+        Date fromDate = sdf.parse(startDate);
+        Date toDate = sdf.parse(endDate);
+        Calendar  from  =  Calendar.getInstance();
+        from.setTime(fromDate);
+        Calendar  to  =  Calendar.getInstance();
+        to.setTime(toDate);
+        //只要年月
+        int fromYear = from.get(Calendar.YEAR);
+        int fromMonth = from.get(Calendar.MONTH);
+
+        int toYear = to.get(Calendar.YEAR);
+        int toMonth = to.get(Calendar.MONTH);
+        // int year = toYear  -  fromYear;
+        int month = toYear *  12  + toMonth  -  (fromYear  *  12  +  fromMonth);
+        // int day = (int) ((to.getTimeInMillis()  -  from.getTimeInMillis())  /  (24  *  3600  *  1000));
+        return month;
+    }
+
+
     /**
      *日期加一天
      */

+ 17 - 6
sms_water/src/main/java/com/huaxu/util/ReportExcelUtil.java

@@ -34,16 +34,22 @@ public class ReportExcelUtil {
     public static List<List<String>> toReportExcelDto(List<ReportDto> list){
         int number = 1;
         List<List<String>> result = new ArrayList<>();
+        if (CollectionUtil.isEmpty(list)){
+            return result;
+        }
         for (ReportDto reportDto : list) {
             List<String>  dataList = new ArrayList<>();
             dataList.add((number++) +"");
             dataList.add(reportDto.getParentSceneName());
             dataList.add(reportDto.getCollectDate());
-            dataList.add(reportDto.getIntakeWaterUsage().toString());
-            dataList.add(reportDto.getYieldWaterUsage().toString());
-            dataList.add(reportDto.getPowerUsage().toString());
-            dataList.add(reportDto.getDrugUsage().toString());
+            dataList.add(doubleToString(reportDto.getIntakeWaterUsage()));
+            dataList.add(doubleToString(reportDto.getYieldWaterUsage()));
+            dataList.add(doubleToString(reportDto.getPowerUsage()));
+            dataList.add(doubleToString(reportDto.getDrugUsage()));
             List<Map<String,Object>> childList = reportDto.getDataMapValues();
+            if (CollectionUtil.isEmpty(childList)) {
+                continue;
+            }
             for (Map<String,Object> childMap: childList) {
                 int ok = 0;
                 for (Map.Entry<String,Object> entry : childMap.entrySet()) {
@@ -51,7 +57,7 @@ public class ReportExcelUtil {
                         ok++;
                         continue;
                     }
-                    dataList.add(entry.getValue().toString());
+                    dataList.add(entry.getValue() != null ? entry.getValue().toString() : "");
                 }
             }
             result.add(dataList);
@@ -60,6 +66,8 @@ public class ReportExcelUtil {
     }
 
 
+
+
     /**
     * @Author lihui
     * @Description 按顺序组装导出的标题
@@ -88,7 +96,6 @@ public class ReportExcelUtil {
         return result;
     }
 
-
     private static List<List<String>> toTitleList(List<ReportTitleDto> list){
         if (CollectionUtil.isEmpty(list)) {
             return null;
@@ -109,4 +116,8 @@ public class ReportExcelUtil {
         }
         return  result;
     }
+
+    private static String doubleToString(Double doubleValue){
+        return doubleValue == null ? "" : doubleValue.toString();
+    }
 }

+ 111 - 42
sms_water/src/main/resources/mapper/SceneMapper.xml

@@ -474,17 +474,120 @@
 
         union all
 
-        select count(1) amount, d.id,c.scene_id, d.device_name name,1 sort
-        from sms_alarm_details c
-        INNER JOIN sms_device d on c.DEVICE_ID=d.ID
-        INNER JOIN sms_scene a on  c.PARENT_SCENE_ID=a.ID
-        INNER JOIN sms_scene_type b on a.SCENE_TYPE_ID=b.ID
-        <where>
-            a.PARENT_SCENE_ID=0 and a.STATUS=1
+        select count(*) amount, id, GROUP_CONCAT(DISTINCT scene_id SEPARATOR ',') scene_id, name,1 sort from
+        (
+            select d.id,c.PARENT_SCENE_ID scene_id, d.device_name name
+            from sms_alarm_details c
+            INNER JOIN sms_device d on c.DEVICE_ID=d.ID
+            INNER JOIN sms_scene a on  c.PARENT_SCENE_ID=a.ID
+            INNER JOIN sms_scene_type b on a.SCENE_TYPE_ID=b.ID
+            <where>
+                a.PARENT_SCENE_ID=0 and a.STATUS=1
+                <if test="scene.tenantId != null  and scene.tenantId != ''">
+                    and a.tenant_id = #{scene.tenantId}
+                </if>
+                <if test="scene.userType!=null and scene.userType!=-999 and scene.userType!=-9999 and scene.programItems != null and scene.programItems.size() > 0">
+                    <if test="scene.permissonType == 5 or scene.permissonType == 2">
+                        and ( a.DEPT_ORG_ID in
+                        <foreach collection="scene.programItems" item="item" open="(" close=")" separator=",">
+                            #{item.orgId}
+                        </foreach>
+                        or
+                        a.COMPANY_ORG_ID in
+                        <foreach collection="scene.programItems" item="item" open="(" close=")" separator=",">
+                            #{item.orgId}
+                        </foreach>
+                        )
+                    </if>
+                    <if test="scene.permissonType == 4 or scene.permissonType == 3">
+                        and a.DEPT_ORG_ID in
+                        <foreach collection="scene.programItems" item="item" open="(" close=")" separator=",">
+                            #{item.orgId}
+                        </foreach>
+                    </if>
+                    <if test="scene.permissonType == 1">
+                        and a.COMPANY_ORG_ID in
+                        <foreach collection="scene.programItems" item="item" open="(" close=")" separator=",">
+                            #{item.orgId}
+                        </foreach>
+                        and (a.DEPT_ORG_ID is null or a.DEPT_ORG_ID =0)
+                    </if>
+                </if>
+                and c.alarm_start_time &gt;= date_format(#{startDate,jdbcType=VARCHAR},'%Y-%m-%d')
+                and c.alarm_start_time &lt; date_format(#{endDate,jdbcType=VARCHAR},'%Y-%m-%d')
+                and SCENE_TYPE_NAME='管网'
+            </where>
+            ) t1
+            group by name, id, scene_id, sort ) t
+            order by amount desc
+    </select>
+
+    <select id="selectMonthAlarmTimes" resultType="map">
+        select count(1) 数量, DATE_FORMAT(c.DATE_CREATE,'%Y-%m-%d') 日期
+            <if test="sort == 2">
+                from sms_scene a INNER JOIN sms_scene_type b on a.SCENE_TYPE_ID=b.ID
+                INNER JOIN sms_alarm_details c on c.PARENT_SCENE_ID=a.ID
+                where a.ID = #{scene.id}
+            </if>
+            <if test="sort == 1">
+                from sms_scene a inner join sms_scene_type b on a.SCENE_TYPE_ID=b.ID
+                INNER JOIN sms_alarm_details c on c.PARENT_SCENE_ID=a.ID
+                where a.PARENT_SCENE_ID=0 and a.STATUS=1
+                and c.device_id = #{scene.id}
+                and b.SCENE_TYPE_NAME='管网'
+                <if test="scene.tenantId != null  and scene.tenantId != ''">
+                    and a.tenant_id = #{scene.tenantId}
+                </if>
+                <if test="scene.userType!=null and scene.userType!=-999 and scene.userType!=-9999 and scene.programItems != null and scene.programItems.size() > 0">
+                    <if test="scene.permissonType == 5 or scene.permissonType == 2">
+                        and ( a.DEPT_ORG_ID in
+                        <foreach collection="scene.programItems" item="item" open="(" close=")" separator=",">
+                            #{item.orgId}
+                        </foreach>
+                        or
+                        a.COMPANY_ORG_ID in
+                        <foreach collection="scene.programItems" item="item" open="(" close=")" separator=",">
+                            #{item.orgId}
+                        </foreach>
+                        )
+                    </if>
+                    <if test="scene.permissonType == 4 or scene.permissonType == 3">
+                        and a.DEPT_ORG_ID in
+                        <foreach collection="scene.programItems" item="item" open="(" close=")" separator=",">
+                            #{item.orgId}
+                        </foreach>
+                    </if>
+                    <if test="scene.permissonType == 1">
+                        and a.COMPANY_ORG_ID in
+                        <foreach collection="scene.programItems" item="item" open="(" close=")" separator=",">
+                            #{item.orgId}
+                        </foreach>
+                        and (a.DEPT_ORG_ID is null or a.DEPT_ORG_ID =0)
+                    </if>
+                </if>
+            </if>
+            and c.alarm_start_time &gt;= date_format(#{startDate,jdbcType=VARCHAR},'%Y-%m-%d')
+            and c.alarm_start_time &lt; date_format(#{endDate,jdbcType=VARCHAR},'%Y-%m-%d')
+            group by DATE_FORMAT(c.DATE_CREATE,'%Y-%m-%d')
+    </select>
+
+    <select id="selectYearAlarmTimes" resultType="map">
+        select count(1) 数量, DATE_FORMAT(c.DATE_CREATE,'%Y-%m') 日期
+        <if test="sort == 2">
+            from sms_scene a INNER JOIN sms_scene_type b on a.SCENE_TYPE_ID=b.ID
+            INNER JOIN sms_alarm_details c on c.PARENT_SCENE_ID=a.ID
+            where a.ID = #{scene.id}
+        </if>
+        <if test="sort == 1">
+        from sms_scene a inner join  sms_scene_type b on a.SCENE_TYPE_ID=b.ID
+            INNER JOIN sms_alarm_details c on c.PARENT_SCENE_ID=a.ID
+            where a.PARENT_SCENE_ID=0 and a.STATUS=1
+            and c.device_id = #{scene.id}
+            and b.SCENE_TYPE_NAME='管网'
             <if test="scene.tenantId != null  and scene.tenantId != ''">
                 and a.tenant_id = #{scene.tenantId}
             </if>
-            <if test="scene.userType!=null and scene.userType!=-999 and scene.userType!=-9999 and  scene.programItems != null and scene.programItems.size() > 0">
+            <if test="scene.userType!=null and scene.userType!=-999 and scene.userType!=-9999 and scene.programItems != null and scene.programItems.size() > 0">
                 <if test="scene.permissonType == 5 or scene.permissonType == 2">
                     and ( a.DEPT_ORG_ID in
                     <foreach collection="scene.programItems" item="item" open="(" close=")" separator=",">
@@ -511,40 +614,6 @@
                     and (a.DEPT_ORG_ID is null or a.DEPT_ORG_ID =0)
                 </if>
             </if>
-            and c.alarm_start_time &gt;= date_format(#{startDate,jdbcType=VARCHAR},'%Y-%m-%d')
-            and c.alarm_start_time &lt; date_format(#{endDate,jdbcType=VARCHAR},'%Y-%m-%d')
-            and SCENE_TYPE_NAME='管网'
-        </where>
-        group by d.device_name, d.id, c.scene_id, sort) t
-        order by amount desc
-    </select>
-
-    <select id="selectMonthAlarmTimes" resultType="map">
-        select count(1) 数量, DATE_FORMAT(c.DATE_CREATE,'%Y-%m-%d') 日期
-            <if test="sort == 2">
-                from sms_scene a INNER JOIN sms_scene_type b on a.SCENE_TYPE_ID=b.ID
-                INNER JOIN sms_alarm_details c on c.PARENT_SCENE_ID=a.ID
-                where a.ID = #{scene.id}
-            </if>
-            <if test="sort == 1">
-                from sms_alarm_details c
-                where c.device_id = #{scene.id}
-            </if>
-            and c.alarm_start_time &gt;= date_format(#{startDate,jdbcType=VARCHAR},'%Y-%m-%d')
-            and c.alarm_start_time &lt; date_format(#{endDate,jdbcType=VARCHAR},'%Y-%m-%d')
-            group by DATE_FORMAT(c.DATE_CREATE,'%Y-%m-%d')
-    </select>
-
-    <select id="selectYearAlarmTimes" resultType="map">
-        select count(1) 数量, DATE_FORMAT(c.DATE_CREATE,'%Y-%m') 日期
-        <if test="sort == 2">
-            from sms_scene a INNER JOIN sms_scene_type b on a.SCENE_TYPE_ID=b.ID
-            INNER JOIN sms_alarm_details c on c.PARENT_SCENE_ID=a.ID
-            where a.ID = #{scene.id}
-        </if>
-        <if test="sort == 1">
-            from sms_alarm_details c
-            where c.device_id = #{scene.id}
         </if>
         and c.date_create &gt;= date_format(#{startDate,jdbcType=VARCHAR},'%Y-%m-%d')
         and c.date_create &lt; date_format(#{endDate,jdbcType=VARCHAR},'%Y-%m-%d')