فهرست منبع

提交地磅管理开发

zhangsan 2 ماه پیش
والد
کامیت
c4e84a4168
1فایلهای تغییر یافته به همراه393 افزوده شده و 0 حذف شده
  1. 393 0
      sckw-modules/sckw-system/src/main/java/com/sckw/system/service/KwsPrinterManageService.java

+ 393 - 0
sckw-modules/sckw-system/src/main/java/com/sckw/system/service/KwsPrinterManageService.java

@@ -0,0 +1,393 @@
+package com.sckw.system.service;
+
+import com.alibaba.fastjson2.JSON;
+import com.baomidou.mybatisplus.core.metadata.IPage;
+import com.sckw.core.exception.SystemException;
+import com.sckw.core.model.page.PageResult;
+import com.sckw.core.web.constant.HttpStatus;
+import com.sckw.core.web.context.LoginUserHolder;
+import com.sckw.system.model.KwsEnterprise;
+import com.sckw.system.model.KwsPrinter;
+import com.sckw.system.model.vo.req.PrinterPageReqVo;
+import com.sckw.system.model.vo.req.PrinterSaveReqVo;
+import com.sckw.system.model.vo.req.PrinterStatusReqVo;
+import com.sckw.system.model.vo.res.PlatformEnterpriseResVo;
+import com.sckw.system.model.vo.res.PrinterDetailResVo;
+import com.sckw.system.model.vo.res.PrinterOptionResVo;
+import com.sckw.system.model.vo.res.PrinterPageResVo;
+import com.sckw.system.repository.KwsEnterpriseRepository;
+import com.sckw.system.repository.KwsPrinterRepository;
+import lombok.RequiredArgsConstructor;
+import lombok.extern.slf4j.Slf4j;
+import org.apache.commons.lang3.StringUtils;
+import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
+
+import java.util.ArrayList;
+import java.util.Collection;
+import java.util.Collections;
+import java.util.Date;
+import java.util.LinkedHashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Objects;
+import java.util.Set;
+import java.util.stream.Collectors;
+
+/**
+ * 打印机管理服务类
+ * 负责打印机的增删改查、状态管理以及与企业信息的关联处理
+ */
+@Service
+@RequiredArgsConstructor
+@Slf4j
+public class KwsPrinterManageService {
+
+    private final KwsPrinterRepository kwsPrinterRepository;
+    private final KwsEnterpriseRepository kwsEnterpriseRepository;
+
+    /**
+     * 分页查询打印机列表
+     *
+     * @param reqVo 分页查询请求参数,包含页码、页大小、打印机名称模糊匹配、企业名称模糊匹配
+     * @return 分页结果集
+     */
+    public PageResult page(PrinterPageReqVo reqVo) {
+        log.info("分页查询打印机列表,参数:{}", JSON.toJSONString(reqVo));
+        // 根据企业名称解析出有权限查看的企业ID集合
+        Set<Long> entIds = resolveQueryEntIds(reqVo.getEnterpriseName());
+        if (entIds.isEmpty()) {
+            // 如果没有可查询的企业ID,直接返回空结果
+            return PageResult.build(reqVo.getPage(), reqVo.getPageSize(), 0L, Collections.emptyList());
+        }
+        // 执行数据库分页查询
+        IPage<KwsPrinter> page = kwsPrinterRepository.pageQuery(reqVo.getPage(), reqVo.getPageSize(),
+                reqVo.getPrinterName(), entIds);
+        // 构建返回结果,填充企业名称等额外信息
+        return PageResult.of(page, buildPageRes(page.getRecords()));
+    }
+
+    /**
+     * 获取打印机详情
+     *
+     * @param id 打印机ID
+     * @return 打印机详情响应对象
+     */
+    public PrinterDetailResVo detail(Long id) {
+        log.info("获取打印机详情,id:{}", id);
+        // 获取并校验打印机实体,同时检查权限
+        KwsPrinter printer = getAndCheck(id);
+        PrinterDetailResVo resVo = new PrinterDetailResVo();
+        // 填充基本信息及企业名称
+        fillBaseRes(printer, enterpriseNameMap(Collections.singleton(printer.getEntId())), resVo);
+        return resVo;
+    }
+
+    /**
+     * 新增打印机
+     *
+     * @param reqVo 新增请求参数
+     */
+    @Transactional(rollbackFor = Exception.class)
+    public void add(PrinterSaveReqVo reqVo) {
+        log.info("新增打印机,参数:{}", JSON.toJSONString(reqVo));
+        // 校验请求参数合法性(非空、重复性、企业有效性等)
+        validateSaveReq(reqVo, null);
+        Date now = new Date();
+        // 构建打印机实体对象
+        KwsPrinter printer = new KwsPrinter()
+                .setEntId(reqVo.getEntId())
+                .setPrinterName(reqVo.getPrinterName())
+                .setPrinterType(reqVo.getPrinterType())
+                .setUsefulLife(reqVo.getUsefulLife())
+                .setOnlineStatus(defaultOnlineStatus(reqVo.getOnlineStatus()))
+                .setStatus(0) // 默认启用
+                .setDelFlag(0) // 未删除
+                .setCreateBy(LoginUserHolder.getUserId())
+                .setCreateTime(now)
+                .setUpdateBy(LoginUserHolder.getUserId())
+                .setUpdateTime(now);
+        // 保存至数据库,失败则抛出异常
+        if (!kwsPrinterRepository.save(printer)) {
+            throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.INSERT_FAIL);
+        }
+    }
+
+    /**
+     * 更新打印机信息
+     *
+     * @param reqVo 更新请求参数
+     */
+    @Transactional(rollbackFor = Exception.class)
+    public void update(PrinterSaveReqVo reqVo) {
+        log.info("更新打印机信息,参数:{}", JSON.toJSONString(reqVo));
+        if (reqVo.getId() == null) {
+            throw new SystemException("打印机ID不能为空");
+        }
+        // 获取并校验原打印机数据及权限
+        KwsPrinter printer = getAndCheck(reqVo.getId());
+        // 校验更新参数的合法性
+        validateSaveReq(reqVo, printer.getId());
+        // 更新字段
+        printer.setEntId(reqVo.getEntId());
+        printer.setPrinterName(reqVo.getPrinterName());
+        printer.setPrinterType(reqVo.getPrinterType());
+        printer.setUsefulLife(reqVo.getUsefulLife());
+        printer.setOnlineStatus(defaultOnlineStatus(reqVo.getOnlineStatus()));
+        printer.setUpdateBy(LoginUserHolder.getUserId());
+        printer.setUpdateTime(new Date());
+        // 执行更新操作
+        if (!kwsPrinterRepository.updateById(printer)) {
+            throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.UPDATE_FAIL);
+        }
+    }
+
+    /**
+     * 更新打印机状态(启用/停用)
+     *
+     * @param reqVo 状态更新请求参数
+     */
+    @Transactional(rollbackFor = Exception.class)
+    public void updateStatus(PrinterStatusReqVo reqVo) {
+        log.info("更新打印机状态,参数:{}", JSON.toJSONString(reqVo));
+        if (reqVo.getId() == null) {
+            throw new SystemException("打印机ID不能为空");
+        }
+        // 校验状态值是否合法(0:启用, 1:停用)
+        if (!Objects.equals(reqVo.getStatus(), 0) && !Objects.equals(reqVo.getStatus(), 1)) {
+            throw new SystemException("打印机状态值非法");
+        }
+        // 获取并校验打印机及权限
+        KwsPrinter printer = getAndCheck(reqVo.getId());
+        printer.setStatus(reqVo.getStatus());
+        printer.setUpdateBy(LoginUserHolder.getUserId());
+        printer.setUpdateTime(new Date());
+        // 执行更新操作
+        if (!kwsPrinterRepository.updateById(printer)) {
+            throw new SystemException(HttpStatus.CRUD_FAIL_CODE, HttpStatus.UPDATE_FAIL);
+        }
+    }
+
+    /**
+     * 获取企业下拉选项列表
+     * 根据用户权限返回可见的企业列表,支持名称模糊搜索
+     *
+     * @param keyword 企业名称关键字
+     * @return 企业选项列表
+     */
+    public List<PlatformEnterpriseResVo> enterpriseOptions(String keyword) {
+        log.info("获取企业下拉选项列表,参数:{}", keyword);
+        // 获取当前用户有权限访问的企业ID集合
+        Set<Long> authEntIds = resolveAuthorizedEntIds();
+        List<KwsEnterprise> enterpriseList;
+        if (LoginUserHolder.isManager()) {
+            // 管理员可查看所有企业
+            enterpriseList = kwsEnterpriseRepository.queryByEntIdAndName(null, keyword);
+        } else if (authEntIds.isEmpty()) {
+            // 普通用户若无授权企业,返回空列表
+            return Collections.emptyList();
+        } else {
+            // 普通用户仅查看授权范围内的企业
+            enterpriseList = kwsEnterpriseRepository.queryByEntIds(authEntIds, keyword);
+        }
+        // 转换为响应VO
+        return enterpriseList.stream().map(item -> {
+            PlatformEnterpriseResVo resVo = new PlatformEnterpriseResVo();
+            resVo.setId(item.getId());
+            resVo.setFirmName(item.getFirmName());
+            return resVo;
+        }).toList();
+    }
+
+    /**
+     * 根据企业ID获取打印机下拉选项列表
+     *
+     * @param entId 企业ID
+     * @return 打印机选项列表
+     */
+    public List<PrinterOptionResVo> optionByEntId(Long entId) {
+        log.info("根据企业ID获取打印机下拉选项列表,参数:{}", entId);
+        // 校验企业是否存在及当前用户是否有该企业权限
+        checkEnterprise(entId);
+        // 查询该企业下的所有打印机并转换为VO
+        return kwsPrinterRepository.listByEntId(entId).stream().map(item -> {
+            PrinterOptionResVo resVo = new PrinterOptionResVo();
+            resVo.setId(item.getId());
+            resVo.setPrinterName(item.getPrinterName());
+            return resVo;
+        }).toList();
+    }
+
+    /**
+     * 构建分页响应数据列表
+     *
+     * @param records 数据库查询出的打印机实体列表
+     * @return 分页响应VO列表
+     */
+    private List<PrinterPageResVo> buildPageRes(List<KwsPrinter> records) {
+        if (records == null || records.isEmpty()) {
+            return Collections.emptyList();
+        }
+        // 批量获取企业名称映射,避免N+1查询问题
+        Map<Long, String> entNameMap = enterpriseNameMap(records.stream().map(KwsPrinter::getEntId).collect(Collectors.toSet()));
+        List<PrinterPageResVo> result = new ArrayList<>(records.size());
+        for (KwsPrinter record : records) {
+            PrinterPageResVo resVo = new PrinterPageResVo();
+            fillBaseRes(record, entNameMap, resVo);
+            result.add(resVo);
+        }
+        return result;
+    }
+
+    /**
+     * 填充打印机基础响应信息
+     *
+     * @param record     打印机实体
+     * @param entNameMap 企业ID到企业名称的映射
+     * @param resVo      待填充的响应VO
+     */
+    private void fillBaseRes(KwsPrinter record, Map<Long, String> entNameMap, PrinterPageResVo resVo) {
+        resVo.setId(record.getId());
+        resVo.setEntId(record.getEntId());
+        resVo.setEnterpriseName(entNameMap.getOrDefault(record.getEntId(), ""));
+        resVo.setPrinterName(record.getPrinterName());
+        resVo.setPrinterType(record.getPrinterType());
+        resVo.setUsefulLife(record.getUsefulLife());
+        resVo.setOnlineStatus(record.getOnlineStatus());
+        // 转换在线状态显示文本
+        resVo.setOnlineStatusName(Objects.equals(record.getOnlineStatus(), 1) ? "在线" : "离线");
+        resVo.setStatus(record.getStatus());
+        // 转换启用状态显示文本
+        resVo.setStatusName(Objects.equals(record.getStatus(), 0) ? "启用" : "停用");
+        resVo.setCreateTime(record.getCreateTime());
+        resVo.setUpdateTime(record.getUpdateTime());
+    }
+
+    /**
+     * 校验保存请求参数
+     *
+     * @param reqVo     请求参数
+     * @param excludeId 排除的ID(用于更新时排除自身)
+     */
+    private void validateSaveReq(PrinterSaveReqVo reqVo, Long excludeId) {
+        if (reqVo.getEntId() == null) {
+            throw new SystemException("所属企业不能为空");
+        }
+        if (StringUtils.isBlank(reqVo.getPrinterName())) {
+            throw new SystemException("打印机名称不能为空");
+        }
+        // 校验企业有效性及权限
+        checkEnterprise(reqVo.getEntId());
+        // 检查同一企业下打印机名称是否重复
+        KwsPrinter exists = kwsPrinterRepository.findByEntIdAndName(reqVo.getEntId(), reqVo.getPrinterName().trim());
+        if (exists != null && !Objects.equals(exists.getId(), excludeId)) {
+            throw new SystemException("同一企业下打印机名称不能重复");
+        }
+    }
+
+    /**
+     * 校验企业有效性及当前用户操作权限
+     *
+     * @param entId 企业ID
+     */
+    private void checkEnterprise(Long entId) {
+        // 判断是否有操作该企业的权限:管理员或授权企业列表中包含该企业
+        boolean allowed = LoginUserHolder.isManager() || resolveAuthorizedEntIds().contains(entId);
+        if (!allowed) {
+            throw new SystemException("没有当前企业的操作权限");
+        }
+        // 校验企业是否存在、未删除且状态正常
+        KwsEnterprise enterprise = kwsEnterpriseRepository.getById(entId);
+        if (enterprise == null || Objects.equals(enterprise.getDelFlag(), 1) || Objects.equals(enterprise.getStatus(), 1)) {
+            throw new SystemException(HttpStatus.ENT_NOT_EXISTS);
+        }
+    }
+
+    /**
+     * 获取打印机实体并校验权限
+     *
+     * @param id 打印机ID
+     * @return 打印机实体
+     */
+    private KwsPrinter getAndCheck(Long id) {
+        // 查询可用的打印机记录
+        KwsPrinter printer = kwsPrinterRepository.findAvailableById(id);
+        if (printer == null) {
+            throw new SystemException("打印机不存在");
+        }
+        // 非管理员需校验是否拥有该打印机所属企业的权限
+        if (!LoginUserHolder.isManager() && !resolveAuthorizedEntIds().contains(printer.getEntId())) {
+            throw new SystemException("没有当前打印机的操作权限");
+        }
+        return printer;
+    }
+
+    /**
+     * 获取企业ID到企业名称的映射
+     *
+     * @param entIds 企业ID集合
+     * @return 映射Map
+     */
+    private Map<Long, String> enterpriseNameMap(Collection<Long> entIds) {
+        if (entIds == null || entIds.isEmpty()) {
+            return Collections.emptyMap();
+        }
+        return kwsEnterpriseRepository.listByIds(entIds).stream()
+                .collect(Collectors.toMap(KwsEnterprise::getId, KwsEnterprise::getFirmName, (a, b) -> a));
+    }
+
+    /**
+     * 解析查询条件中的企业ID集合
+     * 根据用户权限和输入的企业名称关键字,筛选出符合条件的企业ID
+     *
+     * @param enterpriseName 企业名称关键字
+     * @return 企业ID集合
+     */
+    private Set<Long> resolveQueryEntIds(String enterpriseName) {
+        Set<Long> authEntIds = resolveAuthorizedEntIds();
+        List<KwsEnterprise> enterpriseList;
+        if (LoginUserHolder.isManager()) {
+            // 管理员可根据名称全局搜索
+            enterpriseList = kwsEnterpriseRepository.queryByEntIdAndName(null, enterpriseName);
+        } else if (authEntIds.isEmpty()) {
+            // 无授权企业则返回空集合
+            return Collections.emptySet();
+        } else {
+            // 普通用户在授权范围内根据名称搜索
+            enterpriseList = kwsEnterpriseRepository.queryByEntIds(authEntIds, enterpriseName);
+        }
+        // 提取ID并保持顺序
+        return enterpriseList.stream().map(KwsEnterprise::getId).collect(Collectors.toCollection(LinkedHashSet::new));
+    }
+
+    /**
+     * 解析当前用户有权限访问的企业ID集合
+     * 包括:用户所属企业、授权企业列表、子企业列表
+     * 如果是管理员,返回空集合表示无限制(具体逻辑视业务而定,此处空集合通常代表全选或特殊标记)
+     *
+     * @return 企业ID集合
+     */
+    private Set<Long> resolveAuthorizedEntIds() {
+        if (LoginUserHolder.isManager()) {
+            return Collections.emptySet();
+        }
+        Set<Long> result = new LinkedHashSet<>();
+        if (LoginUserHolder.getEntId() != null) {
+            result.add(LoginUserHolder.getEntId());
+        }
+        result.addAll(LoginUserHolder.getAuthEntIdList());
+        result.addAll(LoginUserHolder.getChildEntList());
+        return result;
+    }
+
+    /**
+     * 获取默认的在线状态
+     * 如果传入为1则在线,否则默认离线(0)
+     *
+     * @param onlineStatus 传入的在线状态
+     * @return 标准化后的在线状态
+     */
+    private Integer defaultOnlineStatus(Integer onlineStatus) {
+        return Objects.equals(onlineStatus, 1) ? 1 : 0;
+    }
+}