# RateShopEmailConfigController.java

    package cloud.wconnect.rateshop.controller.rateshop;

    import cloud.wconnect.commonlib.annotation.ApiId;
    import cloud.wconnect.commonlib.component.SessionContext;
    import cloud.wconnect.commonlib.cons.BaseErrorCodeEnum;
    import cloud.wconnect.commonlib.cons.CommonErrorI18nConstant;
    import cloud.wconnect.commonlib.cons.EmailConfigCons;
    import cloud.wconnect.commonlib.cons.SystemPlatformEnum;
    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.UserInternalService;
    import cloud.wconnect.commonlib.service.UsergroupInternalService;
    import cloud.wconnect.commonlib.util.I18nMessageUtils;
    import cloud.wconnect.rateshop.cons.rateshop.RateShopCons;
    import cloud.wconnect.rateshop.entity.rateshop.RateShopEmailConfig;
    import cloud.wconnect.rateshop.pojo.dto.rateshop.emailconfig.RateShopEmailConfigDTO;
    import cloud.wconnect.rateshop.pojo.dto.rateshop.emailconfig.RateShopEmailTargetDTO;
    import cloud.wconnect.rateshop.service.rateshop.IRateShopEmailConfigService;
    import com.google.common.collect.ImmutableMap;
    import com.google.common.collect.Lists;
    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
     * @date 2023/6/16
     */
    @RestController
    @RequestMapping("/rate-shop/email-config")
    public class RateShopEmailConfigController {

        @Autowired
        private IRateShopEmailConfigService emailConfigService;
        @Autowired
        private SessionContext sessionContext;
        @Autowired
        private UserInternalService userInternalService;
        @Autowired
        private UsergroupInternalService usergroupInternalService;
        @Autowired
        private PropertyI18nRedisService propertyI18nRedisService;
        @Autowired
        private I18nMessageUtils i18nMessageUtils;

        /**
         * 保存邮件配置
         *
         * @param property       资产标识
         * @param emailConfigDTO 邮件配置dto
         * @return java.util.Map
         * @author lichen
         * @date 2023/6/16
         */
        @ApiId(364)
        @PostMapping
        public Map save(String property, @RequestBody @Valid RateShopEmailConfigDTO emailConfigDTO) {
            int propertyId = sessionContext.getPropertyId(property);
            PropertyDTO propertyDTO = propertyI18nRedisService.get(propertyId);
            //校验通知对象是否重复 是否存在
            checkEmailTarget(propertyDTO, emailConfigDTO);

            //校验通知类型是否符合预期
            checkNotifyType(propertyDTO, emailConfigDTO.getType());

            //id等于null时，设置为0
            if (Objects.isNull(emailConfigDTO.getId())) emailConfigDTO.setId(0);

            if (emailConfigDTO.getId() > 0) {
                //校验是否存在
                RateShopEmailConfig oriEmailConfig = emailConfigService.checkExist(emailConfigDTO.getId());
                //校验归属
                checkBelong(oriEmailConfig, propertyDTO.getId());
                //校验type不能修改
                if (!oriEmailConfig.getType().equals(emailConfigDTO.getType())) {
                    throw new BadRequestException(CommonErrorI18nConstant.CANNOT_MODIFIED,
                            i18nMessageUtils.getErrorParamMapNotNeedTranslate("emailConfitType"),
                            BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(), "The type cannot be modified");
                }
            } else {
                //校验资产是否已经配置邮件
                emailConfigService.checkSole(propertyDTO.getId(), emailConfigDTO.getType());
            }
            return ImmutableMap.of("id", emailConfigService.save(propertyDTO, emailConfigDTO));
        }

        /**
         * 查询邮件配置
         *
         * @param property 资产标识
         * @param type     邮件配置类型
         * @return cloud.wconnect.rateshop.pojo.dto.emailConfig.EmailConfigDTO
         * @author lichen
         * @date 2023/6/16
         */
        @ApiId(365)
        @GetMapping
        public RateShopEmailConfigDTO get(@RequestParam String property,
                                          @RequestParam(name = "type") Integer type) {
            int propertyId = sessionContext.getPropertyId(property);
            PropertyDTO propertyDTO = propertyI18nRedisService.get(propertyId);
            //校验通知类型是否符合预期
            checkNotifyType(propertyDTO, type);

            return emailConfigService.getByType(propertyDTO, type);
        }

        /**
         * 校验数据是否归属与当前资产
         *
         * @param emailConfig 邮件配置
         * @param propertyId  资产id
         * @return cloud.wconnect.rateshop.entity.rateshop.EmailConfig
         * @author lichen
         * @date 2023/6/16
         */
        private void checkBelong(RateShopEmailConfig emailConfig, Integer propertyId) {
            if (!emailConfig.getPropertyId().equals(propertyId)) {
                throw new ForbiddenException(BaseErrorCodeEnum.DATA_FORBIDDEN.getI18nCode(), BaseErrorCodeEnum.DATA_FORBIDDEN.getCode(),
                        MessageFormat.format("The rate shop email config not belong currentPropertyId, emailConfigId:{0}, belongPropertyId:{1}, currentPropertyId:{2}",
                                emailConfig.getId(), emailConfig.getPropertyId(), propertyId));
            }
        }

        /**
         * 校验通知对象是否合法
         *
         * @param propertyDTO    资产DTO
         * @param emailConfigDTO 邮件配置DTO
         * @return void
         * @author lichen
         * @date 2024/3/16
         */
        private void checkEmailTarget(PropertyDTO propertyDTO, RateShopEmailConfigDTO emailConfigDTO) {
            List<RateShopEmailTargetDTO> toList = emailConfigDTO.getToList();
            List<RateShopEmailTargetDTO> ccList = emailConfigDTO.getCcList();

            List<RateShopEmailTargetDTO> allNotifyList = Lists.newArrayList();
            if (CollectionUtils.isNotEmpty(toList)) {
                allNotifyList.addAll(toList);
            }
            if (CollectionUtils.isNotEmpty(ccList)) {
                allNotifyList.addAll(ccList);
            }
            if (CollectionUtils.isEmpty(allNotifyList)) return;

            //按照用户来源分组
            Map<Integer, List<Integer>> source2IdentityIdList = allNotifyList.stream()
                    .collect(Collectors.groupingBy(RateShopEmailTargetDTO::getSource, Collectors.mapping(RateShopEmailTargetDTO::getIdentityId, Collectors.toList())));
            List<Integer> userIds = source2IdentityIdList.getOrDefault(EmailConfigCons.SOURCE_USER, Collections.emptyList());
            List<Integer> usergroupIds = source2IdentityIdList.getOrDefault(EmailConfigCons.SOURCE_USERGROUP, Collections.emptyList());

            //校验是否重复
            if (userIds.size() != Sets.newHashSet(userIds).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 = allNotifyList.stream().filter(item -> item.getSource() == EmailConfigCons.SOURCE_MANUAL)
                    .map(RateShopEmailTargetDTO::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");
            }

            //用户集合
            if (CollectionUtils.isNotEmpty(userIds)) {
                List<UserDTO> allUsers = userInternalService.getUsers(propertyDTO.getTenantId(), userIds);
                //校验是否存在
                if (userIds.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");
                }
            }
        }

        /**
         * 校验通知类型是否符合预期
         *
         * @param propertyDTO 资产DTO
         * @param notifyType  通知类型
         * @return void
         * @author lichen
         * @date 2025/7/5
         */
        private void checkNotifyType(PropertyDTO propertyDTO, Integer notifyType) {
            String pmsType = propertyDTO.getPmsType();

            List<Integer> validNotifyTypes;
            if (SystemPlatformEnum.OPERA.getDesc().equals(pmsType)) {
                validNotifyTypes = RateShopCons.OPERA_PMS_TYPE_LIST;
            } else if (SystemPlatformEnum.SHI_JI.getDesc().equals(pmsType)){
                validNotifyTypes = RateShopCons.SHIJI_PMS_TYPE_LIST;
            } else {
                validNotifyTypes = RateShopCons.PEP_PMS_TYPE_LIST;
            }
            if (!validNotifyTypes.contains(notifyType)) {
                throw new BadRequestException(CommonErrorI18nConstant.NOTIFY_TYPE_NOT_SUPPORTED,
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                        "The notifyType must be in:" + validNotifyTypes);
            }
        }
    }