# ParseJournalByCashierAndTransactionCodeServiceByOpera.java

    package cloud.wconnect.frontoffice.parsereport.adjustment.impl;

    import cloud.wconnect.commonlib.cons.BaseConstant;
    import cloud.wconnect.commonlib.cons.BaseErrorCodeEnum;
    import cloud.wconnect.commonlib.cons.EventBodyParamEnum;
    import cloud.wconnect.commonlib.cons.SystemPlatformEnum;
    import cloud.wconnect.commonlib.exception.BadRequestException;
    import cloud.wconnect.commonlib.exception.InternalServerErrorException;
    import cloud.wconnect.commonlib.exception.ParseReportException;
    import cloud.wconnect.commonlib.pojo.dto.EventBodyDTO;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.pojo.dto.internationalization.InternationalizationNumberDTO;
    import cloud.wconnect.commonlib.pojo.dto.scheduler.JobParameterDTO;
    import cloud.wconnect.commonlib.util.*;
    import cloud.wconnect.frontoffice.cons.BusinessEnum;
    import cloud.wconnect.frontoffice.cons.EventSubjectEnum;
    import cloud.wconnect.frontoffice.entity.adjustment.AdJournalLog;
    import cloud.wconnect.frontoffice.entity.adjustment.AdjTrxCodeConfig;
    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.IAdjTrxCodeConfigService;
    import cloud.wconnect.sns.http.processor.Sender;
    import com.baomidou.dynamic.datasource.annotation.DS;
    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.lang3.StringUtils;
    import org.dom4j.Document;
    import org.dom4j.DocumentException;
    import org.dom4j.Element;
    import org.dom4j.Node;
    import org.dom4j.io.SAXReader;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Qualifier;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Component;
    import org.springframework.web.multipart.MultipartFile;

    import java.io.InputStream;
    import java.math.BigDecimal;
    import java.math.RoundingMode;
    import java.time.LocalDate;
    import java.time.format.DateTimeFormatter;
    import java.util.*;

    /**
     * @author lichen
     * @description 解析Opera系统的 Journal by Cashier and Transaction Code/service 报告
     * @date 2023/4/4 8:11
     */
    @Slf4j
    @Component
    @DS("logbook")
    public class ParseJournalByCashierAndTransactionCodeServiceByOpera implements IParseJournalByCashierAndTransactionCodeService {

        @Autowired
        private IAdjTrxCodeConfigService adjTrxCodeConfigService;
        @Autowired
        @Qualifier("3pSender")
        private Sender snsSender;
        @Autowired
        private AmazonS3Service amazonS3Service;
        @Autowired
        private ObjectMapper objectMapper;
        @Value("${aws-s3.third-party.key.adjustment.journal}")
        private String s3FilePath;

        @Override
        public boolean supports(String source) {
            return SystemPlatformEnum.OPERA.getDesc().equals(source);
        }

        /**
         * 解析报告
         *
         * @param in          文件流
         * @param propertyDTO 资产
         * @param dateRange   数据范围
         * @return java.util.List<cloud.wconnect.frontoffice.pojo.dto.adjustment.JournalDTO>
         * @author lichen
         * @date 2025/12/4
         */
        @Override
        public List<JournalDTO> parse(InputStream in, PropertyDTO propertyDTO, Map<String, Long> dateRange) throws ParseReportException {
            Long startDate = dateRange.get(JobParameterDTO.START_DATE);
            Long endDate = dateRange.get(JobParameterDTO.END_DATE);
            //获取资产时区
            String timezone = propertyDTO.getTimezone();
            Integer propertyId = propertyDTO.getId();

            //获取国际化的配置
            InternationalizationNumberDTO number = propertyDTO.getInternationalization().getNumber();
            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(number.getCalculationRule());

            try {
                Document document = new SAXReader().read(in);
                List<Node> nodes = document.selectNodes("//G_TRX_CHAR_DATE");
                if (nodes.isEmpty()) {
                    return null;
                }
                //创建adjustment容器
                List<JournalDTO> journalDTOS = Lists.newArrayListWithExpectedSize(nodes.size());

                //声明日期格式化对象
                DateTimeFormatter dateFormatter = DateTimeFormatter.ofPattern(BaseConstant.DATE_FORMAT_MM_DD_YY_STRIKE);

                //查询忽略的TrxCode
                List<AdjTrxCodeConfig> adjTrxCodeConfigs = adjTrxCodeConfigService.listByPropertyId(propertyId);

                long nowTimestamp = DateTimeUtils.nowTimestamp();

                for (Node node : nodes) {
                    Element element = (Element) node;
                    String businessFormatDate = element.elementTextTrim("BUSINESS_FORMAT_DATE");
                    //校验数据的日期
                    if (StringUtils.isEmpty(businessFormatDate)) {
                        continue;
                    }
                    LocalDate businessDateLocal = LocalDate.parse(businessFormatDate, dateFormatter);
                    long businessDate = DateTimeUtils.localDateToLong(businessDateLocal, timezone);
                    if (businessDate >= startDate && businessDate <= endDate) {
                        //校验trxCode
                        String trxCode = element.elementTextTrim("TRX_CODE");
                        if (StringUtils.isEmpty(trxCode) || adjTrxCodeConfigService.isIgnore(adjTrxCodeConfigs, trxCode)) {
                            continue;
                        }

                        //过滤掉非负数
                        String debitStr = element.elementTextTrim("CASHIER_DEBIT");
                        BigDecimal debit = StringUtils.isEmpty(debitStr) ? BigDecimal.ZERO :
                                new BigDecimal(debitStr).setScale(BaseConstant.DATA_PRECISION, roundingMode);
                        if (debit.compareTo(BigDecimal.ZERO) >= 0) {
                            continue;
                        }

                        String roomNumber = element.elementTextTrim("ROOM");
                        String guestName = element.elementTextTrim("GUEST_FULL_NAME");
                        guestName = GuestNameUtil.removeSpaces(guestName);
                        String trxDesc = element.elementTextTrim("TRX_DESC");
                        String pmsAccount = element.elementTextTrim("USER_NAME");

                        JournalDTO journalDTO = new JournalDTO();
                        journalDTO.setCreateTime(nowTimestamp);
                        journalDTO.setGuestName(guestName);
                        journalDTO.setRoomNumber(roomNumber);
                        journalDTO.setAdjustedDollar(debit.abs());
                        journalDTO.setTrxDesc(trxDesc);
                        journalDTO.setBusinessDate(Integer.valueOf(DateTimeUtils.localDateToStr(businessDateLocal, BaseConstant.DATE_FORMAT_YYYYMMDD)));
                        journalDTO.setPmsAccount(pmsAccount);
                        journalDTO.setTrxCode(trxCode);
                        journalDTOS.add(journalDTO);
                    }
                }
                return journalDTOS;
            } catch (DocumentException e) {
                log.error(e.getMessage(), e);
                throw new ParseReportException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "source=opera, parse [Journal by Cashier and Transaction Code/service] report error", e);
            }
        }

        /**
         * 校验文件内容是否合法
         *
         * @param file        文件
         * @param propertyDTO 资产DTO
         * @author lichen
         * @date 2024/7/26
         */
        @Override
        public void checkFile(MultipartFile file, PropertyDTO propertyDTO) {
            //校验文件格式
            UploadUtils.checkFileFormat(file, Lists.newArrayList("xml"));
            try (InputStream in = file.getInputStream()) {
                //校验文件内容
                FileCheckUtils.checkJournalFile(in);
            } catch (BadRequestException e) {
                throw e;
            } catch (Exception e2) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "parse [Journal by Cashier and Transaction Code/service] report error", e2);
            }
        }

        /**
         * 处理数据
         *
         * @param propertyDTO  资产DTO
         * @param file         文件
         * @param adJournalLog 导入log
         * @param userId       操作人ID
         * @author lichen
         * @date 2024/7/29
         */
        @Override
        public void handleData(PropertyDTO propertyDTO, MultipartFile file, AdJournalLog adJournalLog, int userId) {
            try {
                String tenantSymbol = propertyDTO.getTenantSymbol();
                String abbr = propertyDTO.getAbbr();
                // 设置事件体
                Map<String, Object> params = Maps.newHashMapWithExpectedSize(6);
                params.put(EventBodyParamEnum.TENANT_SYMBOL.getDesc(), tenantSymbol);
                params.put(EventBodyParamEnum.PROPERTY_ABBR.getDesc(), Lists.newArrayList(abbr));
                params.put(EventBodyParamEnum.SOURCE.getDesc(), SystemPlatformEnum.OPERA.getDesc());
                params.put(EventBodyParamEnum.UID.getDesc(), userId);
                params.put(EventBodyParamEnum.ID.getDesc(), adJournalLog.getId());
                params.put(EventBodyParamEnum.START_DATE.getDesc(), adJournalLog.getStartDate());
                params.put(EventBodyParamEnum.END_DATE.getDesc(), adJournalLog.getEndDate());
                params.put(EventBodyParamEnum.ORIGINATE_FROM.getDesc(), BusinessEnum.ADJUSTMENT_REQUESTS.getBusiness());

                // 上传文件
                String key = tenantSymbol + "/" + abbr + "/" + s3FilePath +
                        UploadUtils.getRandomFileName(file.getOriginalFilename());
                amazonS3Service.uploadFile(file, key);

                snsSender.publish(EventSubjectEnum.YESTERDAY_JOURNAL_BY_CASHIER_AND_TRANSACTION_CODE_SERVICE.getSubject(),
                        JsonUtils.convertObjToString(objectMapper, new EventBodyDTO(key, params)));
            } catch (Exception e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "Import opera journal-by-cashier-and-transaction-code/service report exception", e);
            }
        }

    }