# JournalFileParseByPep.java

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

    import cloud.wconnect.commonlib.cons.*;
    import cloud.wconnect.commonlib.cons.pep.PepAllTransactionsCons;
    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.util.*;
    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 lombok.extern.slf4j.Slf4j;
    import org.apache.commons.csv.CSVFormat;
    import org.apache.commons.csv.CSVRecord;
    import org.apache.commons.lang3.StringUtils;
    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.IOException;
    import java.io.InputStream;
    import java.io.InputStreamReader;
    import java.math.BigDecimal;
    import java.math.RoundingMode;
    import java.time.LocalDate;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Map;
    import java.util.Objects;

    /**
     * 解析 PEP All Transactions 报告
     *
     * @author lichen
     * 2026/1/15
     */
    @Service
    @DS("finance")
    @Slf4j
    public class JournalFileParseByPep 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;
        @Autowired
        @Qualifier("3pSender")
        private Sender snsSender;

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

        /**
         * 判断支持的平台
         *
         * @param source 平台数据源
         * @return boolean
         * @author lichen
         * @date 2026/1/15
         */
        @Override
        public boolean supports(String source) {
            return SOURCE.equals(source);
        }

        /**
         * 解析报告
         *
         * @param in          文件流
         * @param propertyDTO 资产
         * @param targetDate  目标日期
         * @return java.util.List<cloud.wconnect.finance.pojo.bo.chargeback.JournalListBO>
         * @author lichen
         * @date 2026/1/15
         */
        @Override
        public List<JournalListBO> parsReport(PropertyDTO propertyDTO, InputStream in, Long targetDate) throws ParseReportException {
            try (InputStreamReader inputStreamReader = new InputStreamReader(in)) {
                ArrayList<JournalListBO> resultList = Lists.newArrayList();

                // 客人类型Reservations、Groups、House Accounts
                String guestType = "";

                //获取CSV数据迭代器
                Iterable<CSVRecord> iterable = CSVFormat.EXCEL.parse(inputStreamReader);
                for (CSVRecord csvRecord : iterable) {
                    // 第一列
                    String firstColumn = CsvFileUtils.get(csvRecord, "A");
                    // 跳过空行
                    if (StringUtils.isBlank(firstColumn)) {
                        continue;
                    }

                    // firstColumn == "Date"表示标题行
                    if ("Date".equals(firstColumn)) {
                        // 判断客人类型
                        guestType = PepFileCheckUtils.getAllTransactionsGuestType(csvRecord);
                        // 跳过标题行
                        continue;
                    }

                    if (StringUtils.isBlank(guestType)) {
                        continue;
                    }

                    // 根据客人类型进行解析
                    JournalListBO journalListBO = parseByGuestType(propertyDTO, guestType, csvRecord, targetDate);
                    if (Objects.nonNull(journalListBO)) {
                        resultList.add(journalListBO);
                    }
                }
                return resultList;
            } catch (IOException e) {
                log.error(e.getMessage(), e);
                throw new ParseReportException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "do parse pep [all-transactions] report error", e);
            }
        }

        /**
         * 根据客人类型解析报告
         *
         * @param propertyDTO 资产DTO
         * @param guestType   客人类型
         * @param csvRecord   当前数据行
         * @param targetDate  目标日期
         * @return JournalDTO
         * @author lichen
         * @date 2026/1/15
         */
        private JournalListBO parseByGuestType(PropertyDTO propertyDTO, String guestType, CSVRecord csvRecord, Long targetDate) {
            //获取资产时区
            String timezone = propertyDTO.getTimezone();
            //获取国际化的配置
            InternationalizationNumberDTO number = propertyDTO.getInternationalization().getNumber();
            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(number.getCalculationRule());

            //日期格式dd-MMM-yy
            String dateStr = CsvFileUtils.get(csvRecord, "A");
            //排除掉交易日为空的数据
            if (StringUtils.isBlank(dateStr)) {
                return null;
            }
            LocalDate businessLocalDate = DateTimeUtils.strToLocalDate(dateStr, BaseConstant.DATE_FORMAT_USA);
            long date = DateTimeUtils.localDateToLong(businessLocalDate, timezone);
            // 判断业务日期是否等于目标日期
            if (date != targetDate) {
                return null;
            }

            // 卡号后四位
            String last4Digits = CsvFileUtils.get(csvRecord, "I");
            if(StringUtils.isBlank(last4Digits)){
                return null;
            }

            //金额
            String amountStr = CsvFileUtils.get(csvRecord, "N");
            BigDecimal amount = StringUtils.isBlank(amountStr) ? BigDecimal.ZERO :
                    NumberUtil.parseCurrency(amountStr).setScale(BaseConstant.DATA_PRECISION, roundingMode);

            //房间号
            String roomNumber = getRoomNumberByGuestType(guestType, csvRecord);
            if (StringUtils.isBlank(roomNumber)) {
                roomNumber = "";
            }
            //客人姓名
            String guestName = getGuestNameByGuestType(guestType, csvRecord);
            if (StringUtils.isBlank(guestName)) {
                guestName = "";
            }
            //描述
            String description = CsvFileUtils.get(csvRecord, "H");
            if (StringUtils.isBlank(description)) {
                description = "";
            }
            // Conf. #
            String confNumber = CsvFileUtils.get(csvRecord, "C");
            confNumber = StringUtils.isBlank(confNumber) ? "" : confNumber.trim();

            JournalListBO journalListBO = new JournalListBO();
            journalListBO.setRoomNumber(roomNumber);
            journalListBO.setGuestName(guestName);
            journalListBO.setCardNumber(last4Digits);
            journalListBO.setDebit(amount);
            journalListBO.setTransactionDate(DateTimeUtils.localDateToStr(businessLocalDate, BaseConstant.DATE_FORMAT_YYYY_MM_DD));
            journalListBO.setDescription(description);
            journalListBO.setConfNumber(confNumber);
            return journalListBO;
        }

        /**
         * 根据客人类型获取客人姓名
         *
         * @param guestType 客人类型
         * @param csvRecord 当前数据行
         * @return java.lang.String
         * @author lichen
         * @date 2026/1/10
         */
        private String getGuestNameByGuestType(String guestType, CSVRecord csvRecord) {
            if (PepAllTransactionsCons.GUEST_TYPE_RESERVATIONS.equals(guestType)) {
                return CsvFileUtils.get(csvRecord, "D");
            } else if (PepAllTransactionsCons.GUEST_TYPE_GROUPS.equals(guestType)) {
                return CsvFileUtils.get(csvRecord, "E");
            } else {
                return CsvFileUtils.get(csvRecord, "D");
            }
        }

        /**
         * 根据客人类型获取房间号
         *
         * @param guestType 客人类型
         * @param csvRecord 当前数据行
         * @return java.lang.String
         * @author lichen
         * @date 2026/1/10
         */
        private String getRoomNumberByGuestType(String guestType, CSVRecord csvRecord) {
            if (PepAllTransactionsCons.GUEST_TYPE_RESERVATIONS.equals(guestType)) {
                return CsvFileUtils.get(csvRecord, "E");
            } else {
                return "";
            }
        }

        /**
         * 检查文件
         *
         * @param propertyDTO 资产
         * @param file        文件
         * @author lichen
         * @date 2026/1/15
         */
        @Override
        public void checkFile(PropertyDTO propertyDTO, MultipartFile file) {
            // 限制文件大小
            FileCheckUtils.checkFileSize(file, importReportFileMaxSize);
            // 校验文件格式
            UploadUtils.checkFileFormat(file, Lists.newArrayList("csv"));
            try (InputStream in = file.getInputStream()) {
                // 校验文件内容
                PepFileCheckUtils.checkAllTransactions(in);
            } catch (BadRequestException e) {
                throw e;
            } catch (Exception e2) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "parse pep [all-transactions] report error", e2);
            }
        }

        /**
         * 处理导入记录
         *
         * @param propertyDTO 资产
         * @param importLog   导入记录
         * @param theDate     指定日期
         * @param file        文件
         * @param userId      操作人
         * @return cloud.wconnect.finance.entity.chargeback.CbJournalImportLog
         * @author lichen
         * @date 2026/1/15
         */
        @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 java.lang.String
         * @author lichen
         * @date 2026/1/15
         */
        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 lichen
         * @date 2026/1/15
         */
        @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.PEP.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);
            }
        }

    }