# YesterdayJournalByCashierAndTransactionCodeServiceListener.java

    package cloud.wconnect.frontoffice.messagelistener.adjustment;

    import cloud.wconnect.commonlib.cons.EventBodyParamEnum;
    import cloud.wconnect.commonlib.cons.FunctionIdConstant;
    import cloud.wconnect.commonlib.exception.ListenerException;
    import cloud.wconnect.commonlib.pojo.dto.EventBodyDTO;
    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.frontoffice.cons.BusinessEnum;
    import cloud.wconnect.frontoffice.cons.EventSubjectEnum;
    import cloud.wconnect.frontoffice.cons.S3BucketFunctionCons;
    import cloud.wconnect.frontoffice.cons.adjustment.AdjNotifyConfigTypeEnum;
    import cloud.wconnect.frontoffice.parsereport.adjustment.IParseJournalByCashierAndTransactionCodeService;
    import cloud.wconnect.frontoffice.pojo.dto.adjustment.JournalDTO;
    import cloud.wconnect.frontoffice.service.AmazonS3Service;
    import cloud.wconnect.frontoffice.service.adjustment.*;
    import cloud.wconnect.sns.http.entity.SnsHttpEvent;
    import com.fasterxml.jackson.databind.ObjectMapper;
    import com.google.common.collect.Lists;
    import com.google.common.collect.Maps;
    import lombok.extern.slf4j.Slf4j;
    import org.apache.commons.collections.MapUtils;
    import org.apache.commons.lang3.StringUtils;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.context.ApplicationContext;
    import org.springframework.context.event.EventListener;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.scheduling.annotation.Async;
    import org.springframework.stereotype.Service;

    import java.io.IOException;
    import java.io.InputStream;
    import java.text.MessageFormat;
    import java.util.Collection;
    import java.util.List;
    import java.util.Map;
    import java.util.Objects;
    import java.util.concurrent.TimeUnit;

    /**
     * @author lichen
     * @description Journal by Cashier and Transaction Code/service 报告处理
     * 同步前一日酒店的Journal报告中Debit为负值的数据，用于自动生成Adjustment Form
     * @date 2023/4/3 18:11
     */
    @Slf4j
    @Service
    public class YesterdayJournalByCashierAndTransactionCodeServiceListener {

        @Autowired
        private RedisTemplate<String, Object> redisTemplate;
        @Autowired
        private PropertyInternalService propertyInternalService;
        @Autowired
        private ObjectMapper objectMapper;
        @Autowired
        private ApplicationContext applicationContext;
        @Autowired
        private IAdRequestService adRequestService;
        @Autowired
        private AmazonS3Service amazonS3Service;
        @Value("${default.timezone}")
        private String defaultTimezone;
        @Autowired
        private MailInternalService mailInternalService;
        @Autowired
        private IAdJournalLogService adJournalLogService;
        @Autowired
        private ISchedulerService schedulerService;
        @Autowired
        private CommonService commonService;
        private final static String SUBJECT = EventSubjectEnum.YESTERDAY_JOURNAL_BY_CASHIER_AND_TRANSACTION_CODE_SERVICE.getSubject();
        private final static String BUSINESS = BusinessEnum.ADJUSTMENT_REQUESTS.getBusiness();
        private static final String KEY_PREFIX_FOR_MESSAGE = "wconnect:event:message:";
        private static final String KEY_PREFIX_FOR_PROCESSING = "wconnect:event:processing:";

        /**
         * 监听处理
         *
         * @param event 监听事件
         * @author lichen
         * @date 2025/12/4
         */
        @Async
        @EventListener
        public void handle(SnsHttpEvent event) {
            if (!StringUtils.equals(SUBJECT, event.getSubject())) {
                return;
            }

            log.info("YesterdayJournalByCashierAndTransactionCodeServiceListener.start");
            if (!preventConcurrency(event.getMessageId())) {
                return;
            }

            if (StringUtils.isBlank(event.getBody())) {
                return;
            }

            EventBodyDTO eventBodyDTO = JsonUtils.convertStringToObject(objectMapper, event.getBody(), EventBodyDTO.class);
            Map<String, Object> parameter = eventBodyDTO.getParameter();
            List<String> abbrNameList = (List<String>) parameter.get(EventBodyParamEnum.PROPERTY_ABBR.getDesc());
            String propertyAbbrName = abbrNameList.get(0);
            //获取租户标识
            String tenantAbbr = (String) parameter.get(EventBodyParamEnum.TENANT_SYMBOL.getDesc());
            //查询资产
            PropertyDTO propertyDTO = getEffectiveProperty(tenantAbbr, propertyAbbrName);
            if (Objects.isNull(propertyDTO)) {
                return;
            }

            String source = (String) parameter.get(EventBodyParamEnum.SOURCE.getDesc());
            if (!propertyDTO.getPmsType().equals(source)) {
                log.warn("YesterdayJournalByCashierAndTransactionCodeServiceListener.handle end... property not support this pms type, propertyId:{}, supportPmsType:{}, currentPmsType:{}",
                        propertyDTO.getId(), propertyDTO.getPmsType(), source);
                return;
            }

            boolean importResult = true;//处理结果
            /**
             * 操作人id
             * uid等于0表示自动导入报告
             * 不等于0表示用户手动导入报告
             */
            Integer uid = (Integer) parameter.get(EventBodyParamEnum.UID.getDesc());
            /**
             * 报告导入日志记录id
             * 当用户解决异常时，此id为报告导入异常的id。
             * 当用户非解决异常导入报告时，此id为null。
             */
            Long logId = Objects.isNull(parameter.get(EventBodyParamEnum.ID.getDesc())) ? null :
                    Long.parseLong(parameter.get(EventBodyParamEnum.ID.getDesc()).toString());
            //数据范围
            Map<String, Long> dateRange = getDateRange(propertyDTO, parameter, logId);
            if (MapUtils.isEmpty(dateRange)) {
                log.warn("YesterdayJournalByCashierAndTransactionCodeServiceListener.end The dateRange is empty; propertyAbbr:{}", propertyAbbrName);
                return;
            }
            String path = eventBodyDTO.getPath();
            try (InputStream fileInputStream = amazonS3Service.getFile(path)) {
                amazonS3Service.uploadFile(S3BucketFunctionCons.ADJUSTMENT_IMPORT_RECORD, fileInputStream, path);
                //解析报告
                List<JournalDTO> journalDTOS = parseReport(eventBodyDTO, propertyDTO, dateRange);
                //处理报告数据
                adRequestService.handleReportData(propertyDTO, journalDTOS, uid, dateRange);
                log.info("YesterdayJournalByCashierAndTransactionCodeServiceListener.end success");
            } catch (Exception e) {
                importResult = false;
                if (RateLimitUtils.tryAcquire(this, propertyAbbrName)) {
                    sendAlertEmail(propertyAbbrName, e.getMessage(), path);
                }
                log.error("handle import Yesterday Journal by Cashier and Transaction Code/service report error", e);
            } finally {
                if (uid == 0) {
                    //数据日期等于前一天时更新执行时间
                    updateLastTime(propertyAbbrName);
                }

                if (Objects.nonNull(logId)) {
                    String eventBusiness = (String) parameter.get(EventBodyParamEnum.ORIGINATE_FROM.getDesc());
                    if (BUSINESS.equals(eventBusiness)) {
                        //手动导入或解决异常，更新导入日志
                        adJournalLogService.updateLog(logId, uid, path, importResult);
                    } else {
                        adJournalLogService.save(propertyDTO, dateRange, path, importResult, uid);
                    }
                } else {
                    adJournalLogService.save(propertyDTO, dateRange, path, importResult, 0);
                }
            }
        }

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

        /**
         * 保存事件最近处理时刻
         *
         * @param abbrName 资产标识
         * @author lichen
         * @date 2023/5/20
         */
        private void updateLastTime(String abbrName) {
            //DateTimeUtils.nowTimestamp() 返回long 类型，存储进redis后，再获取是Integer类型。两边类型不一致，所以直接存储String类型
            redisTemplate.opsForValue().set(
                    KEY_PREFIX_FOR_PROCESSING + StringUtils.join(Lists.newArrayList(SUBJECT, BUSINESS, abbrName), "."),
                    String.valueOf(DateTimeUtils.dateTimeNowOfSecond(defaultTimezone)));
        }

        /**
         * 解析report报告
         *
         * @param eventBodyDTO 事件对象
         * @param propertyDTO  资产对象
         * @param dateRange    数据范围
         * @return java.util.List<cloud.wconnect.frontoffice.pojo.dto.adjustment.JournalDTO>
         * @author lichen
         * @date 2025/12/4
         */
        private List<JournalDTO> parseReport(EventBodyDTO eventBodyDTO, PropertyDTO propertyDTO, Map<String, Long> dateRange) {
            //获取source
            String source = (String) eventBodyDTO.getParameter().get(EventBodyParamEnum.SOURCE.getDesc());
            //解析报告
            try (InputStream fileInputStream = amazonS3Service.getFile(eventBodyDTO.getPath())) {
                Map<String, IParseJournalByCashierAndTransactionCodeService> parseServiceMap = applicationContext.getBeansOfType(IParseJournalByCashierAndTransactionCodeService.class);
                Collection<IParseJournalByCashierAndTransactionCodeService> parseServiceList = parseServiceMap.values();
                for (IParseJournalByCashierAndTransactionCodeService parser : parseServiceList) {
                    if (parser.supports(source)) {
                        return parser.parse(fileInputStream, propertyDTO, dateRange);
                    }
                }
            } catch (IOException e) {
                throw new ListenerException("File acquisition failure", e);
            }
            throw new ListenerException("not find report parser");
        }

        /**
         * 发送预警邮件
         *
         * @param propertyAbbr 资产简称
         * @param exceptionMsg 报错内容
         * @param s3Key        s3路径
         * @return void
         * @author lichen
         * @date 2024/2/22
         */
        private void sendAlertEmail(String propertyAbbr, String exceptionMsg, String s3Key) {
            //主题
            String subject = "[Warning] - Import Yesterday Journal Report error";
            //邮件内容
            String mailContent = MessageFormat.format("SNS Subject:{0}<br/>Business:{1}<br/>Property:{2}<br/>Content:{3}<br/>S3Key:{4}",
                    SUBJECT, BUSINESS, propertyAbbr, exceptionMsg, s3Key);
            //发送alert
            mailInternalService.sendAlertEmail(subject, mailContent);
        }

        /**
         * 获取有效的资产数据
         *
         * @param tenantSymbol 租户标识
         * @param propertyAbbr 资产标识
         * @return PropertyDTO
         * @author lichen
         * @date 2024/5/31
         */
        private PropertyDTO getEffectiveProperty(String tenantSymbol, String propertyAbbr) {
            PropertyDTO propertyDTO = propertyInternalService.getOne(propertyAbbr, tenantSymbol);
            if (Objects.isNull(propertyDTO)) {
                log.warn("YesterdayJournalByCashierAndTransactionCodeServiceListener.handle end... The property:{} is not exist", propertyAbbr);
                return null;
            }
            if (!propertyDTO.getStatus()) {
                log.warn("YesterdayJournalByCashierAndTransactionCodeServiceListener.handle end...  The property:{} is closed", propertyAbbr);
                return null;
            }

            //校验是否开通功能
            if (!commonService.checkOpenFunction(propertyDTO, FunctionIdConstant.ADJUSTMENT_REQUESTS)) {
                log.warn("YesterdayJournalByCashierAndTransactionCodeServiceListener.end... the property has not opened the adjustment function;property:{}", propertyAbbr);
                return null;
            }
            return propertyDTO;
        }

        /**
         * 获取报告数据日期范围
         *
         * @param propertyDTO 资产
         * @param parameter   事件体参数
         * @param logId       日志 id
         * @return 数据日期范围
         * @author lichen
         * @date 2024/5/31
         */
        private Map<String, Long> getDateRange(PropertyDTO propertyDTO, Map<String, Object> parameter, Long logId) {
            // 自动下发
            if (Objects.isNull(logId)) {
                return schedulerService.getDateRange(propertyDTO, AdjNotifyConfigTypeEnum.REPORT_MISSED.getType());
            }
            // 手动导入
            Map<String, Long> dateRange = Maps.newHashMap();
            Object startDateObj = parameter.get(EventBodyParamEnum.START_DATE.getDesc());
            Object endDateObj = parameter.get(EventBodyParamEnum.END_DATE.getDesc());
            if (Objects.nonNull(startDateObj) && Objects.nonNull(endDateObj)) {
                dateRange.put(EventBodyParamEnum.START_DATE.getDesc(), Long.parseLong(startDateObj.toString()));
                dateRange.put(EventBodyParamEnum.END_DATE.getDesc(), Long.parseLong(endDateObj.toString()));
            }
            return dateRange;
        }

    }