# JournalFileParseByOpera.java

    package cloud.wconnect.finance.service.parsereport.chargeback;

    import cloud.wconnect.commonlib.cons.BaseErrorCodeEnum;
    import cloud.wconnect.commonlib.cons.EventBodyParamEnum;
    import cloud.wconnect.commonlib.cons.ReportImportResultCons;
    import cloud.wconnect.commonlib.cons.SystemPlatformEnum;
    import cloud.wconnect.commonlib.exception.BadRequestException;
    import cloud.wconnect.commonlib.exception.ParseReportException;
    import cloud.wconnect.commonlib.pojo.dto.EventBodyDTO;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.util.FileCheckUtils;
    import cloud.wconnect.commonlib.util.JsonUtils;
    import cloud.wconnect.commonlib.util.UploadUtils;
    import cloud.wconnect.finance.cons.BusinessEnum;
    import cloud.wconnect.finance.cons.EventSubjectEnum;
    import cloud.wconnect.finance.cons.S3BucketFunctionCons;
    import cloud.wconnect.finance.entity.chargeback.CbJournalImportLog;
    import cloud.wconnect.finance.pojo.bo.chargeback.JournalListBO;
    import cloud.wconnect.finance.service.AmazonS3Service;
    import cloud.wconnect.finance.service.chargeback.ICbJournalImportLogService;
    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 jakarta.annotation.Resource;
    import org.apache.commons.lang3.StringUtils;
    import org.dom4j.Document;
    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.Service;
    import org.springframework.web.multipart.MultipartFile;

    import java.io.InputStream;
    import java.math.BigDecimal;
    import java.time.LocalDate;
    import java.time.ZoneId;
    import java.time.format.DateTimeFormatter;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    import java.util.Objects;

    /**
     * 解析 journal 报告
     *
     * @author yyt
     * 2023/9/8
     */
    @Service
    @DS("finance")
    public class JournalFileParseByOpera implements IJournalFileParse {

        @Resource
        private ICbJournalImportLogService cbJournalImportLogService;
        @Autowired
        private AmazonS3Service amazonS3Service;
        @Autowired
        private ObjectMapper objectMapper;

        @Value("${aws-s3.third-party.key.chargeback.journal}")
        private String journalS3key;

        @Value("${file-max-size.import-report.chargeback}")
        private Long importReportFileMaxSize;

        private final Sender snsSender;

        public JournalFileParseByOpera(@Qualifier("3pSender") Sender snsSender) {
            this.snsSender = snsSender;
        }

        private static final String SOURCE = SystemPlatformEnum.OPERA.getDesc();

        /**
         * 判断支持的平台
         *
         * @param source 平台数据源
         * @return boolean
         * @author yyt
         * @date 2023/9/8
         */
        @Override
        public boolean supports(String source) {
            return SOURCE.equals(source);
        }

        /**
         * 解析报告数据
         *
         * @param propertyDTO 资产
         * @param in          文件流
         * @param targetDate  指定日期
         * @return journal 数据
         * @author yyt
         * @date 2023/9/8
         */
        @Override
        public List<JournalListBO> parsReport(PropertyDTO propertyDTO, InputStream in, Long targetDate) {
            List<JournalListBO> result = new ArrayList<>();
            try {
                ZoneId zoneId = ZoneId.of(propertyDTO.getTimezone());
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("MM-dd-yy");
                DateTimeFormatter dateTimeFormatter2 = DateTimeFormatter.ofPattern("yyyy-MM-dd");
                Document document = new SAXReader().read(in);
                List<Node> nodes = document.selectNodes("//G_TRX_CHAR_DATE");
                for (Node node : nodes) {
                    Element element = (Element) node;
                    // 验证日期
                    String businessFormatDate = element.elementText("BUSINESS_FORMAT_DATE");
                    if (StringUtils.isEmpty(businessFormatDate)) {
                        continue;
                    }
                    long transactionDate = LocalDate.parse(businessFormatDate, dateTimeFormatter).atStartOfDay(zoneId).toEpochSecond();
                    if (transactionDate != targetDate) {
                        continue;
                    }

                    JournalListBO journal = new JournalListBO();
                    String creditCard = element.element("CREDIT_CARD_SUPPLEMENT").getTextTrim();
                    journal.setCardNumber(StringUtils.substring(creditCard, -4, creditCard.length()));
                    String credit = element.elementText("PRINT_CASHIER_CREDIT");
                    journal.setDebit(StringUtils.isEmpty(credit) ? BigDecimal.ZERO : new BigDecimal(credit));
                    journal.setDescription(element.elementText("TRX_DESC"));
                    journal.setGuestName(element.elementText("GUEST_FULL_NAME"));
                    journal.setRoomNumber(element.elementText("ROOM"));
                    journal.setTransactionDate(dateTimeFormatter2.format(LocalDate.parse(businessFormatDate, dateTimeFormatter)));
                    journal.setConfNumber("");
                    result.add(journal);
                }
            } catch (Exception e) {
                throw new ParseReportException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "parse journal report error", e);
            }
            return result;
        }

        /**
         * 检查文件
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @author yyt
         * @date 2024/8/9
         **/
        @Override
        public void checkFile(PropertyDTO propertyDTO, MultipartFile file) {
            // 限制文件大小
            FileCheckUtils.checkFileSize(file, importReportFileMaxSize);
            // 校验文件格式
            UploadUtils.checkFileFormat(file, Lists.newArrayList("xml"));

            try (InputStream in = file.getInputStream()) {
                FileCheckUtils.checkJournalFile(in);
            } catch (BadRequestException e) {
                throw e;
            } catch (Exception e) {
                throw new ParseReportException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "parsing file failed.", e);
            }
        }

        /**
         * 处理导入记录
         *
         * @param propertyDTO 资产
         * @param importLog   导入记录
         * @param theDate     指定日期
         * @param file        文件
         * @param userId      操作人
         * @return 导入记录
         * @author yyt
         * @date 2024/8/9
         **/
        @Override
        public CbJournalImportLog handleImportLog( PropertyDTO propertyDTO, CbJournalImportLog importLog,
                                                  Long theDate, MultipartFile file, int userId) {
            String key = toS3(propertyDTO.getTenantSymbol(), propertyDTO.getAbbr(), file);
            if (Objects.isNull(importLog)) {
                importLog = cbJournalImportLogService.saveRecord(propertyDTO.getId(), theDate,
                        ReportImportResultCons.IMPORT_IN_PROGRESS, key, userId);
            } else {
                // 更新异常为修复中
                CbJournalImportLog updateContent = new CbJournalImportLog();
                updateContent.setId(importLog.getId());
                updateContent.setStatus(ReportImportResultCons.IMPORT_RESULT_REPAIRING);
                updateContent.setUrl(key);
                cbJournalImportLogService.updateById(updateContent);
            }
            return importLog;
        }

        /**
         * 上传文件至 s3
         *
         * @param tenantSymbol   租户标识
         * @param propertySymbol 资产标识
         * @param file           文件
         * @return 文件路径
         * @author yyt
         * @date 2024/8/9
         **/
        private String toS3(String tenantSymbol, String propertySymbol, MultipartFile file) {
            String key = tenantSymbol + "/" + propertySymbol + "/" + journalS3key +
                    UploadUtils.getRandomFileName(file.getOriginalFilename());
            try {
                // 上传文件
                amazonS3Service.uploadFile(S3BucketFunctionCons.CHARGEBACK_IMPORT_RECORD, file, key);
            } catch (Exception e) {
                throw new BadRequestException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "Uploading to s3 failure", e);
            }
            return key;
        }

        /**
         * 处理文件
         *
         * @param propertyDTO 资产信息
         * @param file        文件
         * @param importLog   导入记录
         * @param userId      操作人
         * @author yyt
         * @date 2024/8/9
         **/
        @Override
        public void handleFile(PropertyDTO propertyDTO, MultipartFile file, CbJournalImportLog importLog, Integer userId) {
            try {
                // 设置事件体
                Map<String, Object> params = Maps.newHashMapWithExpectedSize(7);
                params.put(EventBodyParamEnum.TENANT_SYMBOL.getDesc(), propertyDTO.getTenantSymbol());
                params.put(EventBodyParamEnum.PROPERTY_ABBR.getDesc(), Lists.newArrayList(propertyDTO.getAbbr()));
                params.put(EventBodyParamEnum.SOURCE.getDesc(), SystemPlatformEnum.OPERA.getDesc());
                params.put(EventBodyParamEnum.UID.getDesc(), userId);
                params.put(EventBodyParamEnum.ID.getDesc(), importLog.getId());
                params.put(EventBodyParamEnum.DATE.getDesc(), importLog.getTheDate());
                params.put(EventBodyParamEnum.ORIGINATE_FROM.getDesc(), BusinessEnum.CHARGEBACK_JOURNAL.getBusiness());

                // 上传文件
                String key = propertyDTO.getTenantSymbol() + "/" + propertyDTO.getAbbr() + "/" + journalS3key +
                        UploadUtils.getRandomFileName(file.getOriginalFilename());
                amazonS3Service.uploadFile(file, key);

                snsSender.publish(EventSubjectEnum.JOURNAL_BY_CASHIER_AND_TRANSACTION_CODE_SERVICE.getSubject(),
                        JsonUtils.convertObjToString(objectMapper, new EventBodyDTO(key, params)));
            } catch (Exception e) {
                throw new ParseReportException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "Failed to send report event", e);
            }
        }

    }