# SalesKpiMonthlyByAdjAmountListener.java

    package cloud.wconnect.workperformance.messagelistener.saleskpi;

    import cloud.wconnect.commonlib.cons.BaseConstant;
    import cloud.wconnect.commonlib.cons.EventRedisKeyPrefixEnum;
    import cloud.wconnect.commonlib.cons.FunctionIdConstant;
    import cloud.wconnect.commonlib.cons.MoudleEventSubjectEnum;
    import cloud.wconnect.commonlib.pojo.ModuleEvent;
    import cloud.wconnect.commonlib.pojo.bo.adj.AdjBO;
    import cloud.wconnect.commonlib.pojo.bo.adj.BatchAdjBO;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.service.CommonService;
    import cloud.wconnect.commonlib.service.MailInternalService;
    import cloud.wconnect.commonlib.service.PropertyInternalService;
    import cloud.wconnect.commonlib.util.DateTimeUtils;
    import cloud.wconnect.commonlib.util.JsonUtils;
    import cloud.wconnect.commonlib.util.RateLimitUtils;
    import cloud.wconnect.workperformance.cons.BusinessEnum;
    import cloud.wconnect.workperformance.service.saleskpi.ISalesKpiWconnectAdjustmentService;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.google.common.collect.Lists;
    import jakarta.annotation.Resource;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.lang3.StringUtils;
    import org.springframework.context.event.EventListener;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.scheduling.annotation.Async;
    import org.springframework.stereotype.Component;

    import java.text.MessageFormat;
    import java.time.LocalDate;
    import java.util.List;
    import java.util.concurrent.TimeUnit;

    /**
     * 事件处理：Sales KPI Monthly By Adjustment Amount
     *
     * @author zc
     * @date 2023/09/13
     */
    @Slf4j
    @Component
    public class SalesKpiMonthlyByAdjAmountListener {
        @Resource
        private ISalesKpiWconnectAdjustmentService wconnectAdjustmentService;
        @Resource
        private MailInternalService mailInternalService;
        @Resource
        private PropertyInternalService propertyInternalService;
        @Resource
        private RedisTemplate<String, Object> jsonRedisTemplate;
        @Resource
        private ObjectMapper objectMapper;
        @Resource
        private CommonService commonService;

        private static final String SUBJECT = MoudleEventSubjectEnum.ADJUSTMENT_AMOUNT.getSubject();
        private static final String BUSINESS = BusinessEnum.SALES_KPI.getBusiness();

        /**
         * 异步监听事件处理
         *
         * @param event 事件体
         * @author zc
         * @date 2024/8/27
         */
        @Async
        @EventListener
        public void handle(ModuleEvent event) {
            if (!StringUtils.equals(SUBJECT, event.getSubject())) {
                return;
            }
            log.info("SalesKpiMonthlyByAdjAmountListener.handle start...");
            if (!preventConcurrency(event.getMessageId())) {
                log.warn("SalesKpiMonthlyByAdjAmountListener.handle end... a machine has been executed.");
                return;
            }
            if (StringUtils.isBlank(event.getBody())) {
                log.warn("SalesKpiMonthlyByAdjAmountListener.handle end... event body is blank.");
                return;
            }

            // body 转换为对象
            BatchAdjBO batchAdjBO = JsonUtils.convertStringToObject(objectMapper,
                    event.getBody(), BatchAdjBO.class);
            PropertyDTO propertyDTO = propertyInternalService.getOne(batchAdjBO.getPropertyId());

            List<AdjBO> adjBOList = batchAdjBO.getData();

            // 保存 Adjustment 数据
            handleAdjustmentEvent(propertyDTO, batchAdjBO, adjBOList);

            // 判断资产是否有效
            if (!propertyDTO.getStatus()) {
                log.warn("SalesKpiMonthlyByAdjAmountListener.handle end... property is closed.");
                return;
            }
            if(!commonService.checkOpenFunction(propertyDTO, FunctionIdConstant.SALES_KPI)){
                log.warn("SalesKpiMonthlyByAdjAmountListener.handle end...property not open sales kpi function.");
                return;
            }

            try {
                // 提取需要更新数据的日期
                List<Long> dateList = adjBOList.stream().map(adjBO -> Long.valueOf(adjBO.getBusinessDate()))
                        .filter(date -> date > 0)
                        .distinct().toList();

                // 处理 Revenue Adj Lost
                wconnectAdjustmentService.handleRevenueAdjLostItem(propertyDTO, dateList);

                log.info("SalesKpiMonthlyByAdjAmountListener.handle end...");
            } catch (Exception e) {
                String propertyAbbr = propertyDTO.getAbbr();
                if (RateLimitUtils.tryAcquire(this, propertyAbbr)) {
                    sendAlertEmail(propertyAbbr, e.getMessage(), event.getBody());
                }

                log.error("SalesKpiMonthlyByAdjAmountListener.handle end... Process error.", e);
            }
        }

        /**
         * 处理 Adjustment 事件数据
         *
         * @param propertyDTO 资产
         * @param batchAdjBO  事件BO
         * @param adjBOList   数据
         * @author zc
         * @date 2024/8/27
         */
        private void handleAdjustmentEvent(PropertyDTO propertyDTO, BatchAdjBO batchAdjBO, List<AdjBO> adjBOList) {
            if (batchAdjBO.getActionType() == BatchAdjBO.ACTION_TYPE_SAVE) {
                // 保存数据
                wconnectAdjustmentService.save(propertyDTO.getId(), adjBOList, batchAdjBO.getUpdateTime());
            } else {
                // 删除数据
                wconnectAdjustmentService.delete(propertyDTO.getId(), adjBOList);
            }
        }

        /**
         * 发送预警邮件
         *
         * @param propertyAbbr     资产标识
         * @param exceptionMessage 异常信息
         * @param eventBody        事件体
         * @author zc
         * @date 2025/8/12
         */
        private void sendAlertEmail(String propertyAbbr, String exceptionMessage, String eventBody) {
            String subject = "[Warning] - Handle the [W-connect Adjustment] data error.";
            String content = "Process error: " + exceptionMessage;
            String mailContent = MessageFormat.format("Module SNS Subject:{0}<br/>Business:{1}<br/>Property:{2}<br/>Content:{3}<br/>EventBody:{4}",
                    SUBJECT, BUSINESS, propertyAbbr, content, eventBody);
            mailInternalService.sendAlertEmail(subject, mailContent);
        }

        /**
         * 防止并发操作
         *
         * @param messageId 消息事件 id
         * @return boolean true：未并发，当前线程可以执行；false：检测到并发，当前线程应放弃执行
         * @author zc
         * @date 2023/9/13
         */
        private Boolean preventConcurrency(String messageId) {
            String key = EventRedisKeyPrefixEnum.KEY_PREFIX_FOR_MESSAGE.getDesc() +
                    StringUtils.join(Lists.newArrayList(SUBJECT, BUSINESS, messageId), ".");
            return jsonRedisTemplate.opsForValue().setIfAbsent(key, 0L, 1, TimeUnit.DAYS);
        }
    }