From 4b4e1b54cae72088fa60978e0192fe57f986e6f3 Mon Sep 17 00:00:00 2001
From: churf <123456>
Date: Mon, 18 Sep 2023 01:25:13 +0000
Subject: [PATCH] 首页绩效图例距离修正

---
 eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/task/service/impl/TaskDaliyServiceImpl.java |  555 ++++++++++++++++++++++++++++++++++++++-----------------
 1 files changed, 384 insertions(+), 171 deletions(-)

diff --git a/eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/task/service/impl/TaskDaliyServiceImpl.java b/eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/task/service/impl/TaskDaliyServiceImpl.java
index 1e81526..d1dc6db 100644
--- a/eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/task/service/impl/TaskDaliyServiceImpl.java
+++ b/eladmin-master/eladmin-system/src/main/java/me/zhengjie/modules/task/service/impl/TaskDaliyServiceImpl.java
@@ -1,53 +1,49 @@
 /*
-*  Copyright 2019-2020 Zheng Jie
-*
-*  Licensed under the Apache License, Version 2.0 (the "License");
-*  you may not use this file except in compliance with the License.
-*  You may obtain a copy of the License at
-*
-*  http://www.apache.org/licenses/LICENSE-2.0
-*
-*  Unless required by applicable law or agreed to in writing, software
-*  distributed under the License is distributed on an "AS IS" BASIS,
-*  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-*  See the License for the specific language governing permissions and
-*  limitations under the License.
-*/
+ *  Copyright 2019-2020 Zheng Jie
+ *
+ *  Licensed under the Apache License, Version 2.0 (the "License");
+ *  you may not use this file except in compliance with the License.
+ *  You may obtain a copy of the License at
+ *
+ *  http://www.apache.org/licenses/LICENSE-2.0
+ *
+ *  Unless required by applicable law or agreed to in writing, software
+ *  distributed under the License is distributed on an "AS IS" BASIS,
+ *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ *  See the License for the specific language governing permissions and
+ *  limitations under the License.
+ */
 package me.zhengjie.modules.task.service.impl;
 
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.Calendar;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.function.Function;
+import java.text.DateFormat;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.*;
+import java.util.regex.Pattern;
 import java.util.stream.Collectors;
-import java.util.stream.Stream;
 
-import javax.servlet.http.HttpServletResponse;
-
-import org.springframework.data.domain.Page;
+import cn.hutool.core.date.DateTime;
+import me.zhengjie.modules.task.domain.*;
+import me.zhengjie.modules.task.service.dto.TaskDaliyMongoDto;
+import org.springframework.cache.annotation.CacheEvict;
 import org.springframework.data.domain.Pageable;
+import org.springframework.data.mongodb.core.MongoTemplate;
+import org.springframework.data.mongodb.core.query.Criteria;
+import org.springframework.data.mongodb.core.query.Query;
 import org.springframework.stereotype.Service;
 import org.springframework.transaction.annotation.Transactional;
 
 import lombok.RequiredArgsConstructor;
 import me.zhengjie.exception.BadRequestException;
+import me.zhengjie.modules.attendance.domain.AttendanceLeave;
+import me.zhengjie.modules.attendance.repository.AttendanceLeaveRepository;
+import me.zhengjie.modules.attendance.service.dto.AttendanceLeaveQueryCriteria;
 import me.zhengjie.modules.constant.Constant;
-import me.zhengjie.modules.project.domain.Project;
 import me.zhengjie.modules.project.repository.ProjectRepository;
-import me.zhengjie.modules.system.domain.User;
 import me.zhengjie.modules.system.repository.DictDetailRepository;
 import me.zhengjie.modules.system.repository.UserRepository;
 import me.zhengjie.modules.system.service.RoleService;
 import me.zhengjie.modules.system.service.dto.RoleSmallDto;
-import me.zhengjie.modules.task.domain.Task;
-import me.zhengjie.modules.task.domain.TaskDailyInterface;
-import me.zhengjie.modules.task.domain.TaskDaliy;
-import me.zhengjie.modules.task.domain.TaskUser;
 import me.zhengjie.modules.task.repository.TaskDaliyRepository;
 import me.zhengjie.modules.task.repository.TaskRepository;
 import me.zhengjie.modules.task.repository.TaskUserRepository;
@@ -56,18 +52,17 @@
 import me.zhengjie.modules.task.service.dto.TaskDaliyQueryCriteria;
 import me.zhengjie.modules.task.service.mapstruct.TaskDaliyMapper;
 import me.zhengjie.utils.DateUtil;
-import me.zhengjie.utils.FileUtil;
 import me.zhengjie.utils.PageUtil;
 import me.zhengjie.utils.QueryHelp;
 import me.zhengjie.utils.SecurityUtils;
 import me.zhengjie.utils.ValidationUtil;
 
 /**
-* @website https://eladmin.vip
-* @description 服务实现
-* @author 赵士淞
-* @date 2022-12-30
-**/
+ * @author 赵士淞
+ * @website https://eladmin.vip
+ * @description 服务实现
+ * @date 2022-12-30
+ **/
 @Service
 @RequiredArgsConstructor
 public class TaskDaliyServiceImpl implements TaskDaliyService {
@@ -76,101 +71,215 @@
     private final TaskDaliyMapper taskDaliyMapper;
     private final ProjectRepository projectRepository;
     private final TaskRepository taskRepository;
+    private final AttendanceLeaveRepository attendanceLeaveRepository;
     private final UserRepository userRepository;
+    //    private final UserServiceImpl userServiceImpl;
     private final DictDetailRepository dictDetailRepository;
     private final TaskUserRepository taskUserRepository;
     private final RoleService roleService;
+    private final MongoTemplate mongoTemplate;
+
 
     @Override
-    public Map<String,Object> queryAll(TaskDaliyQueryCriteria criteria, Pageable pageable){
-        // 获取登录用户角色等级
-        List<Integer> levels = roleService.findByUsersId(SecurityUtils.getCurrentUserId()).stream().map(RoleSmallDto::getLevel).collect(Collectors.toList());
-        // 登录用户最大角色等级
-        int min = Collections.min(levels);
-        // 判断角色等级
-        if (min == Constant.ROLE_LEVEL_MANAGER || min == Constant.ROLE_LEVEL_LEADER || min == Constant.ROLE_LEVEL_ORDINARY) {
-            // 根据用户ID查询参与的项目ID
-            List<Long> taskUserProjectIdList = taskUserRepository.findProjectIdByUserId(SecurityUtils.getCurrentUserId());
-            // 根据用户ID查询负责的项目ID
-            List<Long> projectIdList = projectRepository.findIdByLiableUserId(SecurityUtils.getCurrentUserId());
-            // 检索条件
-            List<Long> totalProjectIdList = Stream.of(taskUserProjectIdList, projectIdList).flatMap(Collection::stream).distinct().collect(Collectors.toList());
-            if (totalProjectIdList.size() == 0) {
-            	return PageUtil.toPage(Collections.emptyList(), 0);
+    public Map<String, Object> queryAll(TaskDaliyQueryCriteria criteria, Pageable pageable) {
+        Criteria criteriaMongo = new Criteria();
+        criteriaMongo.and("userId").is(SecurityUtils.getCurrentUserId());
+
+        if (criteria.getTaskId() != null || criteria.getProjectId() != null || criteria.getName() != null) {
+            Criteria criteriaTaskUserMongo = new Criteria();
+            if (criteria.getTaskMongoId() != null) {
+                criteriaTaskUserMongo.and("task").is(criteria.getTaskMongoId());
+            } else if (criteria.getProjectId() != null) {
+                List<TaskMongo> taskMongoList = mongoTemplate.find(Query.query(Criteria.where("projectId").is(criteria.getProjectId())), TaskMongo.class);
+                criteriaTaskUserMongo.and("task").in(taskMongoList);
             }
-            criteria.setProjectIdInList(totalProjectIdList);
+            if (criteria.getName() != null) {
+                Pattern pattern = Pattern.compile("^.*" + criteria.getName() + ".*$", Pattern.CASE_INSENSITIVE);
+                criteriaTaskUserMongo.and("name").is(pattern);
+            }
+            List<TaskUserMongo> taskUserMongoList = mongoTemplate.find(Query.query(criteriaTaskUserMongo), TaskUserMongo.class);
+            criteriaMongo.and("taskUserMongo").in(taskUserMongoList);
         }
-        Page<TaskDaliy> page = taskDaliyRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder),pageable);
-        // 将实体类转换为DTO(重写)
-        Function<TaskDaliy, TaskDaliyDto> func = new Function<TaskDaliy, TaskDaliyDto>(){
-            @Override
-            public TaskDaliyDto apply(TaskDaliy t) {
-                // 将实体类转换成DTO
-                TaskDaliyDto taskDaliyDto = taskDaliyMapper.toDto(t);
-                // 根据项目ID查询项目信息
-                Project project = projectRepository.findById(taskDaliyDto.getProjectId()).orElseGet(Project::new);
-                ValidationUtil.isNull(project.getId(),"Project","id",taskDaliyDto.getProjectId());
-                // 项目名称
-                taskDaliyDto.setProjectName(project.getName());
-                // 根据任务ID查询任务信息
-                Task task = taskRepository.findById(taskDaliyDto.getTaskId()).orElseGet(Task::new);
-                ValidationUtil.isNull(task.getId(),"Task","id",taskDaliyDto.getTaskId());
-                // 任务名称
-                taskDaliyDto.setTaskName(task.getName());
-                // 任务工作量单位
-                taskDaliyDto.setTaskWorkloadUnit(task.getPlanWorkloadUnit());
-                // 根据用户ID查询用户信息
-                User user = userRepository.findById(taskDaliyDto.getUserId()).orElseGet(User::new);
-                ValidationUtil.isNull(user.getId(),"User","id",taskDaliyDto.getUserId());
-                // 用户昵称
-                taskDaliyDto.setUserNickName(user.getNickName());
-                // 返回处理好的DTO
-                return taskDaliyDto;
-            }
-        };
-        return PageUtil.toPage(page.map(func));
+        if (criteria.getFillDates() != null) {
+            DateTime startTime = new DateTime(criteria.getFillDates().get(0));
+            DateTime endTime = new DateTime(criteria.getFillDates().get(1));
+            criteriaMongo.andOperator(Criteria.where("fillDate").gte(startTime), Criteria.where("fillDate").lte(endTime));
+        }
+
+        Query query = Query.query(criteriaMongo);
+        long count = mongoTemplate.count(query, TaskDaliyMongo.class);
+        //如果用户的日报为空
+        if (count == 0) {
+            return PageUtil.toPage(Collections.emptyList(), 0);
+        }
+
+        //如果这个用户的日报不为空
+        List<TaskDaliyMongo> daliyMongoList = mongoTemplate.find(query.with(pageable), TaskDaliyMongo.class);
+        List<TaskDaliyMongoDto> resultList = new ArrayList<>();
+        daliyMongoList.sort((o1, o2) -> o2.getFillDate().compareTo(o1.getFillDate()));
+        for (TaskDaliyMongo taskDaliyMongo : daliyMongoList) {
+            TaskDaliyMongoDto dto = new TaskDaliyMongoDto();
+            dto.setId(taskDaliyMongo.getId());
+            dto.setFillDate(taskDaliyMongo.getFillDate());
+            dto.setUserNickName(userRepository.findById(SecurityUtils.getCurrentUserId()).get().getNickName());
+            dto.setProjectId(taskDaliyMongo.getTaskUserMongo().getTask().getProjectId());
+            dto.setProjectName(projectRepository.findById(taskDaliyMongo.getTaskUserMongo().getTask().getProjectId()).get().getName());
+            dto.setTaskName(taskDaliyMongo.getTaskUserMongo().getTask().getName());
+            dto.setTaskId(taskDaliyMongo.getTaskUserMongo().getTask().getId());
+            //dto.setTaskMongoId(taskDaliyMongo.getTaskUserMongo().getTask().getId());
+            dto.setConsumedHours(taskDaliyMongo.getConsumedHours());
+            dto.setTaskProgress(taskDaliyMongo.getTaskProgress());
+            dto.setSettlementStatus(taskDaliyMongo.getSettlementStatus());
+            dto.setRemarks(taskDaliyMongo.getRemarks());
+            dto.setTaskUserMongo(taskDaliyMongo.getTaskUserMongo());
+            resultList.add(dto);
+        }
+        return PageUtil.toPage(resultList, count);
     }
 
+//    @Override
+//    public Map<String, Object> queryAllWithTaskUser(TaskDaliyQueryCriteria criteria, Pageable pageable) {
+//        Page<TaskDaliy> page = taskDaliyRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
+//        // 将实体类转换为DTO(重写)
+//        Function<TaskDaliy, TaskDaliyDto> func = new Function<TaskDaliy, TaskDaliyDto>() {
+//            @Override
+//            public TaskDaliyDto apply(TaskDaliy t) {
+//                // 将实体类转换成DTO
+//                TaskDaliyDto taskDaliyDto = taskDaliyMapper.toDto(t);
+//                // 根据任务ID查询任务信息
+//                Task task = taskRepository.findById(taskDaliyDto.getTaskId()).orElseGet(Task::new);
+//                ValidationUtil.isNull(task.getId(), "Task", "id", taskDaliyDto.getTaskId());
+//                // 任务名称
+//                taskDaliyDto.setTaskName(task.getName());
+//                // 根据任务ID,任务连番和用户ID查询任务分配
+//                //TaskUser taskUser = taskUserRepository.findByTaskIdAndTaskInnerIdAndUserId(t.getTaskId(), t.getTaskInnerId(), t.getUserId());
+//                // 计划工时
+//                //taskDaliyDto.setTaskHours(taskUser.getTaskHours());
+//                // 返回处理好的DTO
+//                return taskDaliyDto;
+//            }
+//        };
+//        return PageUtil.toPage(page.map(func));
+//    }
+
     @Override
-    public List<TaskDaliyDto> queryAll(TaskDaliyQueryCriteria criteria){
-        return taskDaliyMapper.toDto(taskDaliyRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder)));
+    public List<TaskDaliyDto> queryAll(TaskDaliyQueryCriteria criteria) {
+        return taskDaliyMapper.toDto(taskDaliyRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
     }
 
     @Override
     @Transactional
     public TaskDaliyDto findById(Long id) {
         TaskDaliy taskDaliy = taskDaliyRepository.findById(id).orElseGet(TaskDaliy::new);
-        ValidationUtil.isNull(taskDaliy.getId(),"TaskDaliy","id",id);
+        ValidationUtil.isNull(taskDaliy.getId(), "TaskDaliy", "id", id);
         return taskDaliyMapper.toDto(taskDaliy);
     }
 
     @Override
     @Transactional(rollbackFor = Exception.class)
-    public TaskDaliyDto create(TaskDaliy resources) {
-        // 新增修改删除验证
-        checkAddOrUpdateOrDelete(resources);
-        // 新增修改验证
-        checkAddOrUpdate(resources);
-        return taskDaliyMapper.toDto(taskDaliyRepository.save(resources));
+    public TaskDaliyDto create(TaskDaliyMongo resources) {
+
+        if (resources.getTaskUserMongo().getId() == null) {
+            TaskUserMongo taskUserMongo = new TaskUserMongo();
+            taskUserMongo.setUserId(SecurityUtils.getCurrentUserId());
+            taskUserMongo.setTaskHours(0D);
+            TaskMongo byId = mongoTemplate.findById(resources.getTaskId(), TaskMongo.class);
+            taskUserMongo.setTaskStartDate(byId.getPlanStartTime());
+            taskUserMongo.setTaskEndDate(byId.getPlanEndTime());
+            taskUserMongo.setTask(byId);
+            taskUserMongo.setPerformanceType(byId.getPerformanceType());
+            taskUserMongo.setName(resources.getTaskUserMongo().getName());
+            taskUserMongo.setTaskHours(0D);
+            taskUserMongo.setPerformanceHours(0D);
+            TaskUserMongo sailed = mongoTemplate.save(taskUserMongo);
+            resources.getTaskUserMongo().setId(sailed.getId());
+            create(resources);
+        }
+
+        Criteria criteria = new Criteria();
+        criteria.and("userId").is(SecurityUtils.getCurrentUserId());
+        criteria.and("taskUserMongo").is(resources.getTaskUserMongo());
+        /*
+        获取这个用户的这个任务的所有的日报
+
+        如果这个用户在这个任务中没有填写过日报 --直接新增即可
+        如果这个用户在这个任务中填写过日报
+        1.已用户填写的日报时间为基准,新添的日报需要大于前面所有的任务进度,反之报错
+        2.已用户填写的日报时间为基准,新增的日报需要小于前面所有的任务进度
+         */
+
+        List<TaskDaliyMongo> taskUserMongoList = mongoTemplate.find(new Query(new Criteria("userId").is(SecurityUtils.getCurrentUserId()).and("taskUserMongo").is(resources.getTaskUserMongo())), TaskDaliyMongo.class);
+
+        if (taskUserMongoList.size() == 0) {
+            mongoTemplate.save(resources);
+            TaskUserMongo byId = mongoTemplate.findById(resources.getTaskUserMongo().getId(), TaskUserMongo.class);
+            byId.setTaskStatus("task_status_in_hand");
+            mongoTemplate.save(byId);
+            return null;
+        } else {
+            List<TaskDaliyMongo> daliyMongoList = mongoTemplate.find(new Query(new Criteria("userId").is(SecurityUtils.getCurrentUserId()).and("taskUserMongo").is(resources.getTaskUserMongo()).and("fillDate").is(resources.getFillDate())), TaskDaliyMongo.class);
+            if (daliyMongoList.size() == 0) {
+                //这天没填写过日报
+                //check(resources, taskUserMongoList);
+                TaskUserMongo byId = mongoTemplate.findById(resources.getTaskUserMongo().getId(), TaskUserMongo.class);
+                byId.setTaskStatus("task_status_in_hand");
+                mongoTemplate.save(byId);
+                mongoTemplate.save(resources);
+                return null;
+            }
+
+            TaskDaliyMongo taskDaliyMongo = daliyMongoList.get(0);
+            //check(resources, taskUserMongoList);
+            taskDaliyMongo.setTaskProgress(resources.getTaskProgress());
+            taskDaliyMongo.setRemarks(resources.getRemarks());
+            taskDaliyMongo.setConsumedHours(resources.getConsumedHours());
+
+            TaskUserMongo byId = mongoTemplate.findById(resources.getTaskUserMongo().getId(), TaskUserMongo.class);
+            byId.setTaskStatus("task_status_in_hand");
+            mongoTemplate.save(byId);
+
+            mongoTemplate.save(taskDaliyMongo);
+        }
+
+
+        return null;
+    }
+
+    public static boolean check(TaskDaliyMongo resources, List<TaskDaliyMongo> taskDaliyMongoList) {
+        List<TaskDaliyMongo> beforeList = taskDaliyMongoList.stream().filter(item -> item.getFillDate().before(resources.getFillDate())).collect(Collectors.toList());
+        List<TaskDaliyMongo> afterList = taskDaliyMongoList.stream().filter(item -> item.getFillDate().after(resources.getFillDate())).collect(Collectors.toList());
+        for (TaskDaliyMongo beforeListMongo : beforeList) {
+            if (resources.getTaskProgress() <= beforeListMongo.getTaskProgress()) {
+                return false;
+            }
+        }
+
+        for (TaskDaliyMongo afterListMongo : afterList) {
+            if (resources.getTaskProgress() >= afterListMongo.getTaskProgress()) {
+                return false;
+
+            }
+        }
+        return true;
     }
 
     @Override
     @Transactional(rollbackFor = Exception.class)
-    public void update(TaskDaliy resources) {
-        TaskDaliy taskDaliy = taskDaliyRepository.findById(resources.getId()).orElseGet(TaskDaliy::new);
-        ValidationUtil.isNull( taskDaliy.getId(),"TaskDaliy","id",resources.getId());
-        // 新增修改删除验证
-        checkAddOrUpdateOrDelete(taskDaliy);
-        // 修改删除验证
-        checkUpdateOrDelete(taskDaliy);
-        // 新增修改验证
-        checkAddOrUpdate(resources);
-        taskDaliy.copy(resources);
-        taskDaliyRepository.save(taskDaliy);
+    @CacheEvict(cacheNames = "taskUser", allEntries = true)
+    public void update(TaskDaliyMongo resources) {
+//        List<TaskDaliyMongo> taskUserMongoList = mongoTemplate.find(new Query(new Criteria("userId").is(SecurityUtils.getCurrentUserId()).and("taskUserMongo").is(resources.getTaskUserMongo())), TaskDaliyMongo.class);
+//        check(resources,taskUserMongoList);
+        mongoTemplate.save(resources);
+
+        TaskUserMongo byId = mongoTemplate.findById(resources.getTaskUserMongo().getId(), TaskUserMongo.class);
+        byId.setTaskStatus("task_status_in_hand");
+        mongoTemplate.save(byId);
+        //更新的是日报~
     }
 
     /**
      * 新增修改验证
+     *
      * @param resources
      */
     private void checkAddOrUpdate(TaskDaliy resources) {
@@ -179,38 +288,52 @@
         criteria.setProjectId(resources.getProjectId());
         criteria.setTaskId(resources.getTaskId());
         criteria.setUserId(resources.getUserId());
-        criteria.setFillDate(resources.getFillDate());
+//        criteria.setFillDate(resources.getFillDate());// TODO
         // 根据项目ID、任务ID、用户ID、填报日期查询
-        List<TaskDaliy> taskDaliyList = taskDaliyRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder));
+        List<TaskDaliy> taskDaliyList = taskDaliyRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder));
         // 判断是否已有日报
         if (taskDaliyList.size() > 1 || (taskDaliyList.size() == 1 && taskDaliyList.get(0).getId() != resources.getId())) {
             throw new BadRequestException("每个任务每天只能填写一次日报!");
         }
+
+        // 当日任务分配
+        TaskUser currentTaskUser = taskUserRepository.findByTaskIdAndTaskInnerIdAndUserId(resources.getTaskId(), resources.getTaskInnerId(), resources.getUserId());
+
         // 根据项目ID、任务ID、用户ID查询填报日期前最近的任务日报信息
         TaskDaliy previousTaskDaliy = taskDaliyRepository.findPreviousByProjectIdAndTaskIdAndAndUserId(resources.getProjectId(), resources.getTaskId(), resources.getUserId(), resources.getFillDate());
+        if (previousTaskDaliy != null) {
+            TaskUser previousTaskUser = taskUserRepository.findByTaskIdAndTaskInnerIdAndUserId(previousTaskDaliy.getTaskId(), previousTaskDaliy.getTaskInnerId(), previousTaskDaliy.getUserId());
+            if (previousTaskUser != null && resources.getTaskProgress() * currentTaskUser.getTaskHours() < previousTaskDaliy.getTaskProgress() * previousTaskUser.getTaskHours()) {
+                throw new BadRequestException("任务进度必须比前一次多且比后一次少!");
+            }
+        }
+        // 前日任务分配
         // 根据项目ID、任务ID、用户ID查询填报日期后最近的任务日报信息
         TaskDaliy nextTaskDaliy = taskDaliyRepository.findNextByProjectIdAndTaskIdAndAndUserId(resources.getProjectId(), resources.getTaskId(), resources.getUserId(), resources.getFillDate());
-        // 判断任务进度是否比前一次多,比后一次少
-        if ((previousTaskDaliy != null && resources.getTaskProgress() <= previousTaskDaliy.getTaskProgress()) || (nextTaskDaliy != null && resources.getTaskProgress() >= nextTaskDaliy.getTaskProgress())) {
-            throw new BadRequestException("任务进度必须比前一次多且比后一次少!");
+        if (nextTaskDaliy != null) {
+            // 后日任务分配
+            TaskUser nextTaskUser = taskUserRepository.findByTaskIdAndTaskInnerIdAndUserId(nextTaskDaliy.getTaskId(), nextTaskDaliy.getTaskInnerId(), nextTaskDaliy.getUserId());
+            // 判断任务进度是否比前一次多,比后一次少
+            if (nextTaskUser != null && resources.getTaskProgress() * currentTaskUser.getTaskHours() > nextTaskDaliy.getTaskProgress() * nextTaskUser.getTaskHours()) {
+                throw new BadRequestException("任务进度必须比前一次多且比后一次少!");
+            }
         }
     }
 
     @Override
-    public void deleteAll(Long[] ids) {
-        for (Long id : ids) {
-            TaskDaliy taskDaliy = taskDaliyRepository.findById(id).orElseGet(TaskDaliy::new);
-            ValidationUtil.isNull( taskDaliy.getId(),"TaskDaliy","id",id);
-            // 新增修改删除验证
-            checkAddOrUpdateOrDelete(taskDaliy);
-            // 修改删除验证
-            checkUpdateOrDelete(taskDaliy);
-            taskDaliyRepository.deleteById(id);
+    @CacheEvict(cacheNames = "task", allEntries = true)
+    public void deleteAll(String[] ids) {
+        for (String id : ids) {
+            TaskDaliyMongo byId = mongoTemplate.findById(id, TaskDaliyMongo.class);
+            if (byId != null) {
+                mongoTemplate.remove(byId);
+            }
         }
     }
 
     /**
      * 修改删除验证
+     *
      * @param resources
      */
     private void checkUpdateOrDelete(TaskDaliy resources) {
@@ -222,6 +345,7 @@
 
     /**
      * 新增修改删除验证
+     *
      * @param resources
      */
     private void checkAddOrUpdateOrDelete(TaskDaliy resources) {
@@ -238,90 +362,93 @@
         }
     }
 
-    @Override
-    public void download(List<TaskDaliyDto> all, HttpServletResponse response) throws IOException {
-        List<Map<String, Object>> list = new ArrayList<>();
-        for (TaskDaliyDto taskDaliy : all) {
-            String projectName = taskDaliy.getProjectId() != null ? projectRepository.findById(taskDaliy.getProjectId()).orElseGet(Project::new).getName() : "";
-            String taskName = taskDaliy.getTaskId() != null ? taskRepository.findById(taskDaliy.getTaskId()).orElseGet(Task::new).getName() : "";
-            String userNickName = taskDaliy.getUserId() != null ? userRepository.findById(taskDaliy.getUserId()).orElseGet(User::new).getNickName() : "";
-            String settlementStatus = taskDaliy.getSettlementStatus() != null ? dictDetailRepository.findByDictNameAndValue(Constant.SETTLEMENT_STATUS, taskDaliy.getSettlementStatus()).getLabel() : "";
-            Map<String,Object> map = new LinkedHashMap<>();
-            map.put("填写日期", taskDaliy.getFillDate());
-            map.put("项目名称", projectName);
-            map.put("任务名称", taskName);
-            map.put("员工姓名", userNickName);
-            map.put("消耗工时", taskDaliy.getConsumedHours());
-            map.put("消耗工作量", taskDaliy.getConsumedWorkload());
-            map.put("任务进度", taskDaliy.getTaskProgress());
-            map.put("结算状态", settlementStatus);
-            map.put("备注", taskDaliy.getRemarks());
-            map.put("创建者", taskDaliy.getCreateBy());
-            map.put("创建时间", taskDaliy.getCreateTime());
-            map.put("更新者", taskDaliy.getUpdateBy());
-            map.put("更新时间", taskDaliy.getUpdateTime());
-            list.add(map);
-        }
-        FileUtil.downloadExcel(list, response);
-    }
+//    @Override
+//    public void download(List<TaskDaliyDto> all, HttpServletResponse response) throws IOException {
+//        List<Map<String, Object>> list = new ArrayList<>();
+//        for (TaskDaliyDto taskDaliy : all) {
+//            String projectName = taskDaliy.getProjectId() != null ? projectRepository.findById(taskDaliy.getProjectId()).orElseGet(Project::new).getName() : "";
+//            String taskName = taskDaliy.getTaskId() != null ? taskRepository.findById(taskDaliy.getTaskId()).orElseGet(Task::new).getName() : "";
+//            String userNickName = taskDaliy.getUserId() != null ? userRepository.findById(taskDaliy.getUserId()).orElseGet(User::new).getNickName() : "";
+//            String settlementStatus = taskDaliy.getSettlementStatus() != null ? dictDetailRepository.findByDictNameAndValue(Constant.SETTLEMENT_STATUS, taskDaliy.getSettlementStatus()).getLabel() : "";
+//            Map<String, Object> map = new LinkedHashMap<>();
+//            map.put("填写日期", taskDaliy.getFillDate());
+//            map.put("项目名称", projectName);
+//            map.put("任务名称", taskName);
+//            map.put("员工姓名", userNickName);
+//            map.put("消耗工时", taskDaliy.getConsumedHours());
+//            map.put("消耗工作量", taskDaliy.getConsumedWorkload());
+//            map.put("任务进度", taskDaliy.getTaskProgress());
+//            map.put("结算状态", settlementStatus);
+//            map.put("备注", taskDaliy.getRemarks());
+//            map.put("创建者", taskDaliy.getCreateBy());
+//            map.put("创建时间", taskDaliy.getCreateTime());
+//            map.put("更新者", taskDaliy.getUpdateBy());
+//            map.put("更新时间", taskDaliy.getUpdateTime());
+//            list.add(map);
+//        }
+//        FileUtil.downloadExcel(list, response);
+//    }
 
     @Override
-    public Double queryCompletedWork(TaskDaliyQueryCriteria criteria){
+    public Double queryOtherWage(TaskDaliyQueryCriteria criteria) {
         // 已完成工时
         Double completedWork = 0D;
         // 国际时间转中国时间
         String targetYearMonth = DateUtil.internationalTimeToChinaTime(criteria.getTargetYearMonth());
         // 任务日报检索类
-        criteria.setFillDateLike(targetYearMonth.substring(0,7));
+        criteria.setFillDateLike(targetYearMonth.substring(0, 7));
         // 获取本月任务日报列表
-        List<TaskDaliy> taskDaliyMonthList = taskDaliyRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root,criteria,criteriaBuilder));
+        List<TaskDaliy> taskDaliyMonthList = taskDaliyRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder));
         // 判断是否有本月任务日报
         if (taskDaliyMonthList.size() != 0) {
             // 获取本月任务日报中所有任务ID
-            List<Long> taskIds = taskDaliyMonthList.stream().map(item -> item.getTaskId()).distinct().collect(Collectors.toList());
+            //List<Long> taskIds = taskDaliyMonthList.stream().map(item -> item.getTaskId()).distinct().collect(Collectors.toList());
+            // 获取对应的任务
+            //Map<Long, Task> taskMap = taskRepository.findAllById(taskIds).stream().collect(Collectors.toMap(Task::getId, Function.identity()));
             // 获取本月任务分配列表
-            List<TaskUser> taskUserMonthList = taskUserRepository.findByUserIdAndTaskIdIn(criteria.getUserId(), taskIds);
+            //List<TaskUser> taskUserMonthList = taskUserRepository.findByUserIdAndTaskIdIn(criteria.getUserId(), taskIds);
             // 日历类
             Calendar cal = setUpCalendar(targetYearMonth);
             // 获取本月最大天数
             int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
             // 循环本月最大天数
-            for (int i = 1; i <= lastDay; i ++) {
+            for (int i = 1; i <= lastDay; i++) {
                 // 设置天数
                 cal.set(Calendar.DAY_OF_MONTH, i);
                 // 获取本日任务日报列表
                 List<TaskDaliy> taskDaliyDayList = taskDaliyMonthList.stream().filter(item -> item.getFillDate().getTime() == cal.getTime().getTime()).collect(Collectors.toList());
                 // 循环本日任务日报列表
-                for (int j = 0; j < taskDaliyDayList.size(); j ++) {
+                for (int j = 0; j < taskDaliyDayList.size(); j++) {
                     // 本日任务日报
                     TaskDaliy taskDaliyDay = taskDaliyDayList.get(j);
                     // 本日任务分配列表
-                    List<TaskUser> taskUserDayList = taskUserMonthList.stream().filter(item -> item.getTaskId() == taskDaliyDay.getTaskId()).collect(Collectors.toList());
-                    // 判断本日任务分配列表数量
-                    if (taskUserDayList.size() > 1) {
-                        throw new BadRequestException("任务存在多次分配同一人情况!");
-                    } else if (taskUserDayList.size() == 0) {
-                        throw new BadRequestException("未找到任务分配记录!");
-                    }
-                    // 本日任务分配
-                    TaskUser taskUserDay = taskUserDayList.get(0);
+                    //Optional<TaskUser> OptionalTaskUser = taskUserMonthList.stream().filter(item -> item.getTaskId().equals(taskDaliyDay.getTaskId()) && item.getTaskInnerId().equals(taskDaliyDay.getTaskInnerId())).findFirst();
+//                    if (!OptionalTaskUser.isPresent()) {
+//                        throw new BadRequestException("未找到任务分配记录!");
+//                    }
+                    //TaskUser taskUserDay = OptionalTaskUser.get();
+                    //Task task = taskMap.get(taskUserDay.getTaskId());
+                    //if (Constant.PERFORMANCE_TYPE_RATE.equals(task.getPerformanceType())) {
                     // 根据项目ID、任务ID、用户ID查询填报日期前最近的任务日报信息
                     TaskDaliy taskDaliyHistory = taskDaliyRepository.findPreviousByProjectIdAndTaskIdAndAndUserId(taskDaliyDay.getProjectId(), taskDaliyDay.getTaskId(), taskDaliyDay.getUserId(), taskDaliyDay.getFillDate());
-                    // 本日任务日报进度
-                    Double taskDaliyDayProgress = taskDaliyDay.getTaskProgress();
                     // 判断最近的任务日报是否为空
                     if (taskDaliyHistory != null) {
-                        // 本日任务日报相关历史进度
-                        Double taskDaliyHistoryProgress = taskDaliyHistory.getTaskProgress();
+                        TaskUser previousTaskUser = taskUserRepository.findByTaskIdAndTaskInnerIdAndUserId(taskDaliyHistory.getTaskId(), taskDaliyHistory.getTaskInnerId(), taskDaliyHistory.getUserId());
+                        if (previousTaskUser == null) {
+                            throw new BadRequestException("任务日报进度计算存在异常!");
+                        }
                         // 判断进度是否正常
-                        if (taskDaliyDayProgress - taskDaliyHistoryProgress <= 0) {
+                        if (taskDaliyDay.getConsumedWorkload() < taskDaliyHistory.getConsumedWorkload()) {
                             throw new BadRequestException("任务日报进度计算存在异常!");
                         }
                         // 本日任务日报进度
-                        taskDaliyDayProgress = taskDaliyDayProgress - taskDaliyHistoryProgress;
+                        //completedWork += task.getPieceRate() * (taskDaliyDay.getConsumedWorkload() - taskDaliyHistory.getConsumedWorkload());
+                    } else {
+                        // 已完成工时
+                        //completedWork += task.getPieceRate() * taskDaliyDay.getConsumedWorkload();
                     }
-                    // 已完成工时
-                    completedWork += taskUserDay.getTaskHours() * (taskDaliyDayProgress / 100);
+                    //}
+
                     // 本日任务日报
                     taskDaliyDay.setSettlementStatus(Constant.SETTLEMENT_STATUS_SETTLED);
                     // 保存本日任务日报
@@ -333,17 +460,49 @@
         return completedWork;
     }
 
+    @Override
+    public Double queryCompletedWork(TaskDaliyQueryCriteria criteria, Boolean readOnly) {
+        // 已完成工时
+        Double completedWork = 0D;
+        List<TaskDaliyMongo> daliyMongoList;
+        try {
+            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
+            Date dt = sdf.parse(criteria.getTargetYearMonth());
+            Calendar cal = Calendar.getInstance();
+            cal.setTime(dt);
+            cal.add(Calendar.MONTH,1);
+            Date nextMonth = cal.getTime();
+            daliyMongoList = mongoTemplate.find(Query.query(new Criteria("userId").is(criteria.getUserId()).and("fillDate").gte(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(criteria.getTargetYearMonth())).lte(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(nextMonth)))), TaskDaliyMongo.class);
+        } catch (ParseException e) {
+            throw new RuntimeException(e);
+        }
+        for (TaskDaliyMongo taskDaliyMongo : daliyMongoList) {
+            // 获取一下分配给这个人的绩效时长时长
+            TaskUserMongo taskUser = mongoTemplate.findById(taskDaliyMongo.getTaskUserMongo().getId(), TaskUserMongo.class);
+            assert taskUser != null;
+            // 如果绩效工时 - 消耗工时 > 0 说明当前的日报超出预计的绩效工时
+            if (taskUser.getPerformanceHours() - taskDaliyMongo.getConsumedHours() > 0) {
+                completedWork += taskDaliyMongo.getConsumedHours();
+            } else {
+                completedWork += taskUser.getPerformanceHours();
+            }
+        }
+        // 已完成工时
+        return completedWork;
+    }
+
     /**
      * 设置日历类
+     *
      * @return
      */
     private Calendar setUpCalendar(String targetYearMonth) {
         // 日历类
         Calendar cal = Calendar.getInstance();
         // 设置年份
-        cal.set(Calendar.YEAR, Integer.valueOf(targetYearMonth.substring(0,4)));
+        cal.set(Calendar.YEAR, Integer.valueOf(targetYearMonth.substring(0, 4)));
         // 设置月份
-        cal.set(Calendar.MONTH, Integer.valueOf(targetYearMonth.substring(5,7)) - 1);
+        cal.set(Calendar.MONTH, Integer.valueOf(targetYearMonth.substring(5, 7)) - 1);
         // 设置时数
         cal.set(Calendar.HOUR_OF_DAY, 0);
         // 设置分数
@@ -359,8 +518,62 @@
     @Override
     public Double queryTaskTotalConsumedHours(TaskDaliyQueryCriteria criteria) {
         // 根据项目ID、任务ID、用户ID查询总消耗工时、总消耗工作量、最大任务进度
-        TaskDailyInterface taskDailyInterface = taskDaliyRepository.findSumConsumedHoursAndSumConsumedWorkloadAndMaxTaskProgressByProjectIdAndTaskIdAndUserId(criteria.getProjectId(), criteria.getTaskId(), criteria.getUserId());
+        TaskDailyInterface taskDailyInterface = taskDaliyRepository.findSumConsumedHoursAndSumConsumedWorkloadByProjectIdAndTaskIdAndUserId(criteria.getProjectId(), criteria.getTaskId(), criteria.getUserId());
         // 返回
         return taskDailyInterface.getConsumedHours();
     }
+
+    @Override
+    public TaskDaliyMongo getDailyDetail(String taskUserId, String fillDate) {
+        try {
+            Criteria criteriaMongo = new Criteria();
+            //查询一下这个任务的这一天的日报
+            SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
+            Date date = ft.parse(fillDate);
+            Calendar instance = Calendar.getInstance();
+            instance.setTime(date);
+            instance.add(Calendar.DAY_OF_YEAR, 1);
+            date = instance.getTime();
+            criteriaMongo.and("taskUserMongo").is(taskUserId);
+            criteriaMongo.and("fillDate").is(date);
+            criteriaMongo.and("userId").is(SecurityUtils.getCurrentUserId());
+            List<TaskDaliyMongo> daliyMongoList = mongoTemplate.find(Query.query(criteriaMongo), TaskDaliyMongo.class);
+            if (daliyMongoList.size() == 0) {
+                //这一天还没填写过日报
+                return null;
+            } else {
+                //这一天填写了日报
+                return daliyMongoList.get(0);
+            }
+        } catch (ParseException e) {
+            throw new RuntimeException(e);
+        }
+    }
+
+    @Override
+    public boolean checkTask(Long taskProgress, String taskUserId, String fillDate) {
+        try {
+            //fillDate = fillDate.substring(0,22);
+            //fillDate = fillDate.length() > 34 ? fillDate.substring(0,24) : fillDate;
+            Date date = new Date();
+            if (fillDate.length() > 34) {
+                fillDate = fillDate.substring(0, 24);
+                System.out.println(fillDate);
+            } else {
+                SimpleDateFormat ft = new SimpleDateFormat("yyyy-MM-dd");
+                date = ft.parse(fillDate);
+            }
+            //获取当前用户,当前任务,所有的日报
+            List<TaskDaliyMongo> daliyMongoList = mongoTemplate.find(new Query(new Criteria("userId").is(SecurityUtils.getCurrentUserId()).and("taskUserMongo.id").is(taskUserId)), TaskDaliyMongo.class);
+            for (int i = 0; i < daliyMongoList.size(); i++) {
+                //如果有一个日报的任务进度要比这个大,就返回假
+                if (daliyMongoList.get(i).getTaskProgress() > taskProgress && date.after(daliyMongoList.get(i).getFillDate())) {
+                    return false;
+                }
+            }
+            return true;
+        } catch (ParseException e) {
+            throw new RuntimeException(e);
+        }
+    }
 }
\ No newline at end of file

--
Gitblit v1.9.3