mitao
4 天以前 67e7b5fc821a35f013e7a46a5957f4c6394d236d
ruoyi-system/src/main/java/com/ruoyi/system/service/impl/AssetInventoryTaskServiceImpl.java
@@ -1,6 +1,7 @@
package com.ruoyi.system.service.impl;
import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
@@ -12,7 +13,9 @@
import com.ruoyi.system.constants.AssetDeptConstant;
import com.ruoyi.system.dto.asset.AssetInventoryTaskDTO;
import com.ruoyi.system.dto.asset.AssetInventoryTaskItemDTO;
import com.ruoyi.system.dto.asset.AssetInventoryTaskItemUpdateDTO;
import com.ruoyi.system.dto.asset.AssetInventoryUserUpdateDTO;
import com.ruoyi.system.emums.AssetInventoryTaskStatusEnum;
import com.ruoyi.system.mapper.AssetInventoryTaskMapper;
import com.ruoyi.system.model.AssetInventoryRecord;
import com.ruoyi.system.model.AssetInventoryTask;
@@ -31,7 +34,6 @@
import com.ruoyi.system.vo.asset.InventoryTaskTabVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@@ -70,48 +72,35 @@
    @Override
    public IPage<AssetInventoryTaskVO> getInventoryTaskPage(AssertInventoryQuery query) {
        // 1. 构建Lambda查询条件
        LambdaQueryWrapper<AssetInventoryTask> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(StringUtils.isNotBlank(query.getTaskName()),
                     AssetInventoryTask::getTaskName, query.getTaskName())
               .eq(AssetInventoryTask::getDisabled, false)
               .orderByDesc(AssetInventoryTask::getCreateTime);
        // 数据权限:超级管理员/资产管理部查看所有数据,其他部门查看当前及下级部门的数据
        Long userId = SecurityUtils.getUserId();
        boolean isAdmin = SecurityUtils.isAdmin(userId);
        if (!isAdmin) {
            try {
                // 获取当前用户的部门名称
                String deptName = sysUserService.selectUserById(userId).getDeptName();
                // 非超级管理员且非资产管理部,设置部门权限
                if (!AssetDeptConstant.ASSET_INVENTORY_DEPT_NAMES.contains(deptName)) {
                    query.setDeptId(Integer.valueOf(SecurityUtils.getLoginUser().getDeptId()));
                }
            } catch (Exception e) {
                // 如果获取部门信息失败,默认设置部门权限
                try {
                    query.setDeptId(Integer.valueOf(SecurityUtils.getLoginUser().getDeptId()));
                } catch (Exception ex) {
                    // ignore parse, leave null if cannot parse
                }
            }
        }
        // 2. 构建分页对象
        Page<AssetInventoryTask> page = new Page<>(query.getPageNum(), query.getPageSize());
        // 3. 执行分页查询
        IPage<AssetInventoryTask> taskPage = this.page(page, wrapper);
        IPage<AssetInventoryTaskVO> taskPage = this.baseMapper.getPageList(page, query);
        // 4. 收集部门ID并去重
        List<Integer> deptIds = taskPage.getRecords().stream()
                .map(AssetInventoryTask::getDeptId)
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());
        // 5. 批量查询部门信息
        List<TDept> depts = deptIds.isEmpty() ?
                Collections.emptyList() :
                deptService.listByIds(deptIds);
        // 6. 构建部门ID->名称的映射Map
        Map<Integer, String> deptNameMap = depts.stream()
                .collect(Collectors.toMap(TDept::getId, TDept::getDeptName));
        // 7. 使用BeanUtil.copyToList转换VO并填充部门名称
        List<AssetInventoryTaskVO> voList = BeanUtil.copyToList(taskPage.getRecords(), AssetInventoryTaskVO.class);
        voList.forEach(vo -> {
            if (vo.getDeptId() != null) {
                vo.setDeptName(deptNameMap.get(vo.getDeptId()));
            }
        });
        // 8. 构建返回的分页结果
        IPage<AssetInventoryTaskVO> resultPage = new Page<>(taskPage.getCurrent(), taskPage.getSize(), taskPage.getTotal());
        resultPage.setRecords(voList);
        return resultPage;
        return taskPage;
    }
    @Override
@@ -191,36 +180,29 @@
        // 数据权限:超级管理员/资产管理部、董事长、总经理查看所有数据,其他部门查看当前及下级部门的数据
        Long userId = SecurityUtils.getUserId();
        boolean isAdmin = SecurityUtils.isAdmin(userId);
        boolean hasNoPermission = isAdmin;
        boolean hasNoPermission = false;
        if (!isAdmin) {
            try {
                // 获取当前用户的部门名称
                String deptName = sysUserService.selectUserById(userId).getDept().getDeptName();
                String deptName = sysUserService.selectUserById(userId).getDeptName();
                // 非超级管理员且非资产管理部,设置部门权限
                if (!AssetDeptConstant.ASSET_INVENTORY_DEPT_NAMES.contains(deptName)) {
                    hasNoPermission =  true;
                }
            } catch (Exception e) {
                log.error("获取当前登录用户部门信息异常", e);
                // 如果获取部门信息失败
            }
        }
        // 1. 查询所有有效的盘点任务,支持筛选条件
        LambdaQueryWrapper<AssetInventoryTask> taskWrapper = new LambdaQueryWrapper<>();
        taskWrapper.eq(AssetInventoryTask::getDisabled, false)
                   .orderByDesc(AssetInventoryTask::getCreateTime);
        taskWrapper.ne(AssetInventoryTask::getStatus, AssetInventoryTaskStatusEnum.CANCELED.getCode())
                .orderByDesc(AssetInventoryTask::getCreateTime);
        // 按部门筛选
        if (hasNoPermission) {
            //没有权限,根据盘点人查询任务列表
            taskWrapper.apply("EXISTS (SELECT 1 FROM asset_inventory_task_item item WHERE item.inventory_task_id = id AND item.user_id = {0})", Math.toIntExact(userId));
        }
        try {
            SysUser currentUser = SecurityUtils.getLoginUser().getUser();
            taskWrapper.eq(AssetInventoryTask::getUserId, Math.toIntExact(currentUser.getUserId()));
        } catch (Exception e) {
            // 如果获取用户信息失败,不应用筛选条件
            log.warn("获取当前用户信息失败,不应用'我的任务'筛选条件", e);
            taskWrapper.apply("EXISTS (SELECT 1 FROM asset_inventory_task_item item WHERE item.inventory_task_id = asset_inventory_task.id AND item.user_id = {0})", Math.toIntExact(userId));
        }
        List<AssetInventoryTask> tasks = this.list(taskWrapper);
@@ -345,6 +327,25 @@
    @Override
    public IPage<AssetMainInventoryVO> getListByTaskId(InventoryTaskQuery query) {
        // 数据权限:超级管理员/资产管理部、董事长、总经理查看所有数据,其他部门查看当前及下级部门的数据
        Long userId = SecurityUtils.getUserId();
        boolean isAdmin = SecurityUtils.isAdmin(userId);
        query.setHasNoPermission(Boolean.FALSE);
        query.setUserId(userId);
        if (!isAdmin) {
            try {
                // 获取当前用户的部门名称
                String deptName = sysUserService.selectUserById(userId).getDeptName();
                query.setDeptName(deptName);
                // 非超级管理员且非资产管理部,设置部门权限
                if (!AssetDeptConstant.ASSET_INVENTORY_DEPT_NAMES.contains(deptName)) {
                    query.setHasNoPermission(Boolean.TRUE);
                }
            } catch (Exception e) {
                log.error("获取当前登录用户部门信息异常", e);
                // 如果获取部门信息失败
            }
        }
        return baseMapper.getAssetMainInventoryPageList(new Page<>(query.getPageNum(), query.getPageSize()), query);
    }
@@ -399,24 +400,24 @@
        // 3. 查询并更新对应的资产盘点项
        LambdaQueryWrapper<AssetInventoryTaskItem> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AssetInventoryTaskItem::getInventoryTaskId, dto.getTaskId())
               .eq(AssetInventoryTaskItem::getAssetMainId, dto.getAssetId());
               .in(AssetInventoryTaskItem::getAssetMainId, dto.getAssetIds());
        AssetInventoryTaskItem taskItem = assetInventoryTaskItemService.getOne(wrapper);
        if (taskItem == null) {
        List<AssetInventoryTaskItem> taskItems = assetInventoryTaskItemService.list(wrapper);
        if (CollUtil.isEmpty(taskItems)) {
            throw new ServiceException("未找到对应的盘点资产项");
        }
        // 4. 更新盘点人
        String currentUserName = SecurityUtils.getLoginUser().getUser().getNickName();
        taskItem.setUserId(dto.getUserId());
        boolean updated = assetInventoryTaskItemService.updateById(taskItem);
        taskItems.forEach(item->item.setUserId(dto.getUserId()));
        boolean updated = assetInventoryTaskItemService.updateBatchById(taskItems);
        if (!updated) {
            throw new ServiceException("修改盘点人失败");
        }
        log.info("成功修改盘点人,任务ID:{},资产ID:{},新盘点人ID:{},操作人:{}",
                dto.getTaskId(), dto.getAssetId(), dto.getUserId(), currentUserName);
                dto.getTaskId(), dto.getAssetIds(), dto.getUserId(), currentUserName);
    }
    /**
@@ -456,6 +457,7 @@
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void handleResult(List<AssetInventoryTaskItemDTO> dtoList) {
        Map<Integer, Integer> taskItemMap = dtoList.stream()
                .collect(Collectors.toMap(AssetInventoryTaskItemDTO::getAssetInventoryTaskItemId, AssetInventoryTaskItemDTO::getDeal));
@@ -471,5 +473,131 @@
            }
        }
        assetInventoryTaskItemService.updateBatchById(assetInventoryTaskItems);
        // 更新任务状态为已完成(盘点结果处理完成)
        if (CollUtil.isNotEmpty(dtoList) && CollUtil.isNotEmpty(assetInventoryTaskItems)) {
            // 获取任务ID(从第一个盘点项获取)
            Integer taskId = assetInventoryTaskItems.get(0).getInventoryTaskId();
            updateTaskStatusToCompleted(taskId);
        }
    }
    /**
     * 直接更新任务状态为已完成
     *
     * @param taskId 盘点任务ID
     */
    private void updateTaskStatusToCompleted(Integer taskId) {
        // 参数验证
        if (taskId == null) {
            log.warn("任务ID为空,无法更新任务状态");
            return;
        }
        // 检查任务是否存在
        AssetInventoryTask task = this.getById(taskId);
        if (task == null) {
            log.warn("任务不存在,任务ID:{}", taskId);
            return;
        }
        // 检查任务是否已经是已完成状态
        if (task.getStatus() != null && task.getStatus().equals(AssetInventoryTaskStatusEnum.COMPLETED.getCode())) {
            log.debug("任务已经是已完成状态,任务ID:{}", taskId);
            return;
        }
        // 更新任务状态为已完成
        task.setStatus(AssetInventoryTaskStatusEnum.COMPLETED.getCode());
        task.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName());
        this.updateById(task);
        log.info("盘点任务状态更新为已完成,任务ID:{},任务名称:{},操作人:{}",
                taskId, task.getTaskName(), task.getUpdateBy());
    }
    @Override
    public boolean cancel(Integer id) {
        AssetInventoryTask assetInventoryTask = this.getById(id);
        if (Objects.nonNull(assetInventoryTask) && !assetInventoryTask.getStatus() .equals(AssetInventoryTaskStatusEnum.COMPLETED.getCode())) {
            assetInventoryTask.setStatus(AssetInventoryTaskStatusEnum.CANCELED.getCode()); //已取消
            assetInventoryTask.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName());
            return this.updateById(assetInventoryTask);
        }
        return false;
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveInventory(List<AssetInventoryTaskItemUpdateDTO> dtoList) {
        Long userId = SecurityUtils.getUserId();
        Map<Integer, AssetInventoryTaskItemUpdateDTO> dtoMap = dtoList.stream()
                .collect(Collectors.toMap(AssetInventoryTaskItemUpdateDTO::getAssetInventoryTaskItemId, dto -> dto));
        List<AssetInventoryTaskItem> assetInventoryTaskItems = assetInventoryTaskItemService.listByIds(dtoMap.keySet());
        if (!Integer.valueOf(userId.intValue()).equals(assetInventoryTaskItems.get(0).getUserId())) {
            throw new ServiceException("保存失败,只有指定人员可以操作");
        }
        for (AssetInventoryTaskItem assetInventoryTaskItem : assetInventoryTaskItems) {
            AssetInventoryTaskItemUpdateDTO dto = dtoMap.get(assetInventoryTaskItem.getId());
            assetInventoryTaskItem.setResultStatus(dto.getResultStatus());
            assetInventoryTaskItem.setRealDeptName(dto.getRealDeptName());
            assetInventoryTaskItem.setRealUserName(dto.getRealUserName());
            assetInventoryTaskItem.setExceptionExplain(dto.getExceptionExplain());
        }
        assetInventoryTaskItemService.updateBatchById(assetInventoryTaskItems);
        // 检查并更新任务状态(保存盘点数据完成)
        if (CollUtil.isNotEmpty(dtoList) && CollUtil.isNotEmpty(assetInventoryTaskItems)) {
            // 获取任务ID(从第一个盘点项获取)
            Integer taskId = assetInventoryTaskItems.get(0).getInventoryTaskId();
            checkAndUpdateTaskCompletionStatus(taskId);
        }
    }
    /**
     * 检查并更新任务完成状态
     * 如果任务的所有盘点项都为正常状态,则将任务状态更新为已完成
     *
     * @param taskId                  盘点任务ID
     */
    private void checkAndUpdateTaskCompletionStatus(Integer taskId) {
        // 参数验证
        if (taskId == null) {
            log.warn("任务ID为空,无法检查任务完成状态");
            return;
        }
        // 1. 检查任务是否存在
        AssetInventoryTask task = this.getById(taskId);
        if (task == null) {
            log.warn("任务不存在,任务ID:{}", taskId);
            return;
        }
        // 2. 查询任务的所有盘点项
        LambdaQueryWrapper<AssetInventoryTaskItem> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AssetInventoryTaskItem::getInventoryTaskId, taskId);
        List<AssetInventoryTaskItem> allTaskItems = assetInventoryTaskItemService.list(wrapper);
        // 3. 检查是否所有项都已完成且为正常状态(resultStatus = 1)
        boolean allNormal = !allTaskItems.isEmpty() &&
                allTaskItems.stream()
                        .allMatch(item -> item.getResultStatus() != null && item.getResultStatus() == 1);
        // 4. 如果都正常,更新任务状态为已完成
        if (allNormal) {
            // 检查任务是否已经是已完成状态
            if (task.getStatus() != null && !task.getStatus().equals(AssetInventoryTaskStatusEnum.COMPLETED.getCode())) {
                task.setStatus(AssetInventoryTaskStatusEnum.COMPLETED.getCode());
                task.setUpdateBy(SecurityUtils.getLoginUser().getUser().getNickName());
                this.updateById(task);
                log.info("盘点任务已完成,任务ID:{},任务名称:{},操作人:{}",
                        taskId, task.getTaskName(), task.getUpdateBy());
            } else {
                log.debug("任务已经是已完成状态,任务ID:{}", taskId);
            }
        } else {
            log.debug("任务未完全完成,跳过状态更新,任务ID:{},盘点项总数:{}",
                    taskId, allTaskItems.size());
        }
    }
}