# BadGuestApproveController.java

    package cloud.wconnect.frontoffice.controller.badguest;

    import cloud.wconnect.commonlib.annotation.ApiId;
    import cloud.wconnect.commonlib.component.SessionContext;
    import cloud.wconnect.commonlib.cons.BaseConstant;
    import cloud.wconnect.commonlib.cons.BaseErrorCodeEnum;
    import cloud.wconnect.commonlib.cons.CommonErrorI18nConstant;
    import cloud.wconnect.commonlib.cons.EmailConfigCons;
    import cloud.wconnect.commonlib.exception.BadRequestException;
    import cloud.wconnect.commonlib.exception.ForbiddenException;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.pojo.dto.UserDTO;
    import cloud.wconnect.commonlib.pojo.dto.UsergroupDTO;
    import cloud.wconnect.commonlib.redis.PropertyI18nRedisService;
    import cloud.wconnect.commonlib.service.RoleInternalService;
    import cloud.wconnect.commonlib.service.UserInternalService;
    import cloud.wconnect.commonlib.service.UsergroupInternalService;
    import cloud.wconnect.commonlib.util.I18nMessageUtils;
    import cloud.wconnect.frontoffice.entity.badguest.BadGuestApproveLevel;
    import cloud.wconnect.frontoffice.pojo.dto.badguest.ApproveUser;
    import cloud.wconnect.frontoffice.pojo.dto.badguest.BadGuestApproveLevelDTO;
    import cloud.wconnect.frontoffice.pojo.dto.badguest.BgApproveCCDTO;
    import cloud.wconnect.frontoffice.service.badguest.IBadGuestApproveConfigService;
    import cloud.wconnect.frontoffice.service.badguest.IBadGuestApproveLevelService;
    import com.google.common.collect.Sets;
    import org.apache.commons.collections4.CollectionUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.*;

    import jakarta.validation.Valid;

    import java.text.MessageFormat;
    import java.util.*;
    import java.util.stream.Collectors;

    /**
     * @author lichen
     * @description Guests Blacklist 功能的审批配置 前端控制器
     * @date 2023/3/21 13:44
     */
    @RestController
    @RequestMapping("/guest-blacklist/approve-config")
    public class BadGuestApproveController {

        @Autowired
        private IBadGuestApproveLevelService badGuestApproveLevelService;
        @Autowired
        private IBadGuestApproveConfigService approveConfigService;
        @Autowired
        private RoleInternalService roleInternalService;
        @Autowired
        private SessionContext sessionContext;
        @Autowired
        private UserInternalService userInternalService;
        @Autowired
        private UsergroupInternalService usergroupInternalService;
        @Autowired
        private PropertyI18nRedisService propertyI18nRedisService;
        @Autowired
        private I18nMessageUtils i18nMessageUtils;

        /**
         * 查询某资产Guests Blacklist功能的审批配置
         *
         * @param property 资产标识
         * @return java.util.List<cloud.wconnect.frontoffice.pojo.dto.badguest.BadGuestApproveLevelDTO>
         * @author lichen
         * @date 2025/8/26
         */
        @ApiId(147)
        @GetMapping
        public List<BadGuestApproveLevelDTO> list(String property) {
            int propertyId = sessionContext.getPropertyId(property);
            Integer tenantId = sessionContext.getTenantSymbolBO().getId();
            return badGuestApproveLevelService.list(tenantId, propertyId);
        }

        /**
         * 保存审批配置
         *
         * @param property                资产标识
         * @param id                      审批层级id
         * @param badGuestApproveLevelDTO 审批级别dto
         * @return java.util.Map
         * @author lichen
         * @date 2025/8/26
         */
        @ApiId(148)
        @PostMapping
        public Map save(String property, @RequestParam(name = "id") Long id,
                        @Valid @RequestBody BadGuestApproveLevelDTO badGuestApproveLevelDTO) {
            Integer propertyId = sessionContext.getPropertyId(property);
            PropertyDTO propertyDTO = propertyI18nRedisService.get(propertyId);

            //获取当前保存的审核用户集合
            List<Integer> userIds = badGuestApproveLevelDTO.getUsers().stream().map(ApproveUser::getId).collect(Collectors.toList());

            //校验用户不能重复
            Set<Integer> userSet = Sets.newHashSetWithExpectedSize(userIds.size());
            userSet.addAll(userIds);
            if (userSet.size() != userIds.size()) {
                throw new BadRequestException(CommonErrorI18nConstant.DATA_CANNOT_REPEAT,
                        i18nMessageUtils.getErrorParamMapNotNeedTranslate("userIds"),
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                        "approve user cannot repeat");
            }

            //校验审批人和抄送对象
            checkApproverAndCC(propertyDTO, userIds, badGuestApproveLevelDTO.getCcList());

            if (id > BaseConstant.LONG_ZERO) {
                // 校验用户是否重复
                approveConfigService.checkUserRepeat(propertyId, userIds, id);

                BadGuestApproveLevel oriApprove = checkExistAndBelongProperty(id, propertyId);
                //index 不能修改
                badGuestApproveLevelDTO.setApproveIndex(oriApprove.getApproveIndex());
                badGuestApproveLevelDTO.setId(id);
                badGuestApproveLevelDTO.setPropertyId(propertyId);
                //修改
                badGuestApproveLevelService.update(oriApprove, badGuestApproveLevelDTO);
            } else {
                // 校验用户是否重复
                approveConfigService.checkUserRepeat(propertyId, userIds, null);
                //新增
                badGuestApproveLevelDTO.setPropertyId(propertyId);
                badGuestApproveLevelService.insert(badGuestApproveLevelDTO);
            }
            return Collections.emptyMap();
        }

        /**
         * 删除审批层级
         *
         * @param property 资产标识
         * @param id       审批层级id
         * @return java.util.Map
         * @author lichen
         * @date 2025/8/26
         */
        @ApiId(150)
        @DeleteMapping
        public Map remove(String property, @RequestParam(name = "id") Long id) {
            Integer propertyId = sessionContext.getPropertyId(property);
            BadGuestApproveLevel oriApprove = checkExistAndBelongProperty(id, propertyId);
            badGuestApproveLevelService.remove(oriApprove);
            return Collections.emptyMap();
        }

        /**
         * 查询审批角色用户
         *
         * @param property 资产标识
         * @return java.util.List<cloud.wconnect.commonlib.pojo.dto.UserDTO>
         * @author lichen
         * @date 2025/8/26
         */
        @ApiId(286)
        @GetMapping("/approveUser")
        public List<UserDTO> approveUser(String property) {
            int propertyId = sessionContext.getPropertyId(property);
            Integer tenantId = sessionContext.getTenantSymbolBO().getId();
            return roleInternalService.getUsers(tenantId, propertyId, BaseConstant.BLACK_LIST_APPROVE_ROLE);
        }

        /**
         * 校验是否存在；校验是否归属于资产
         *
         * @param id         主键id
         * @param propertyId 资产id
         * @return cloud.wconnect.frontoffice.entity.badguest.BadGuestApproveLevel
         * @author lichen
         * @date 2025/8/26
         */
        private BadGuestApproveLevel checkExistAndBelongProperty(Long id, Integer propertyId) {
            BadGuestApproveLevel byId = badGuestApproveLevelService.getById(id);
            if (Objects.isNull(byId)) {
                throw new BadRequestException(CommonErrorI18nConstant.DATA_NOT_FOUND,
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(), "id=" + id + " ,Guests Blacklist Approve Config not found");
            }
            if (byId.getPropertyId().compareTo(propertyId) != 0) {
                throw new ForbiddenException(BaseErrorCodeEnum.DATA_FORBIDDEN.getI18nCode(),
                        BaseErrorCodeEnum.DATA_FORBIDDEN.getCode(),
                        MessageFormat.format("BadGuest approve level not belong current property, badGuestId:{0}, badGuestBelongPropertyId:{1}, currentPropertyId:{2}",
                                id, byId.getPropertyId(), propertyId));
            }
            return byId;
        }

        /**
         * 校验审批人和抄送对象是否存在
         *
         * @param propertyDTO  资产DTO
         * @param approverList 审批人集合
         * @param ccList       抄送人集合
         * @return void
         * @author lichen
         * @date 2024/3/14
         */
        private void checkApproverAndCC(PropertyDTO propertyDTO, List<Integer> approverList, List<BgApproveCCDTO> ccList) {
            //按照用户来源分组
            Map<Integer, List<Integer>> source2IdentityIdList = ccList.stream()
                    .collect(Collectors.groupingBy(BgApproveCCDTO::getSource, Collectors.mapping(BgApproveCCDTO::getIdentityId, Collectors.toList())));
            List<Integer> userIdsByCC = source2IdentityIdList.getOrDefault(EmailConfigCons.SOURCE_USER, Collections.emptyList());
            List<Integer> usergroupIds = source2IdentityIdList.getOrDefault(EmailConfigCons.SOURCE_USERGROUP, Collections.emptyList());

            //校验是否重复
            if (userIdsByCC.size() != Sets.newHashSet(userIdsByCC).size()) {
                throw new BadRequestException(CommonErrorI18nConstant.DATA_CANNOT_REPEAT,
                        i18nMessageUtils.getErrorParamMapNotNeedTranslate("userIds"),
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(), "user cannot repeat");
            }
            if (usergroupIds.size() != Sets.newHashSet(usergroupIds).size()) {
                throw new BadRequestException(CommonErrorI18nConstant.DATA_CANNOT_REPEAT,
                        i18nMessageUtils.getErrorParamMapNotNeedTranslate("userGroupIds"),
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(), "usergroup cannot repeat");
            }
            List<String> manualEmails = ccList.stream().filter(cc -> cc.getSource() == EmailConfigCons.SOURCE_MANUAL)
                    .map(BgApproveCCDTO::getEmail).collect(Collectors.toList());
            if (manualEmails.size() != Sets.newHashSet(manualEmails).size()) {
                throw new BadRequestException(CommonErrorI18nConstant.DATA_CANNOT_REPEAT,
                        i18nMessageUtils.getErrorParamMapNotNeedTranslate("manualEmails"),
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(), "manual email cannot repeat");
            }

            //用户集合
            Set<Integer> allUserIds = new HashSet<>();
            allUserIds.addAll(approverList);
            allUserIds.addAll(userIdsByCC);
            List<UserDTO> allUsers = userInternalService.getUsers(propertyDTO.getTenantId(), allUserIds);
            //校验是否存在
            if (allUserIds.size() != allUsers.size()) {
                throw new BadRequestException(CommonErrorI18nConstant.DATA_NOT_EXIST,
                        i18nMessageUtils.getErrorParamMapNotNeedTranslate("userId"),
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                        "The user not exist");
            }

            //校验用户组是否存在
            if (CollectionUtils.isNotEmpty(usergroupIds)) {
                List<UsergroupDTO> usergroups = usergroupInternalService.getUsergroups(propertyDTO.getTenantId(), propertyDTO.getId(), usergroupIds);
                if (usergroupIds.size() != usergroups.size()) {
                    throw new BadRequestException(CommonErrorI18nConstant.DATA_NOT_EXIST,
                            i18nMessageUtils.getErrorParamMapNotNeedTranslate("userGroupId"),
                            BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                            "The user group not exist");
                }
            }
        }

    }