# ParseJournalByTransactionCodePerDayServiceByPep.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.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.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.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.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.Component;
    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报告
     */
    @Slf4j
    @Component
    @DS("logbook")
    public class ParseJournalByTransactionCodePerDayServiceByPep 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;

        /**
         * 判断是否支持
         *
         * @param source 来源
         * @return boolean
         * @author lichen
         * @date 2026/1/10
         */
        @Override
        public boolean supports(String source) {
            return SystemPlatformEnum.PEP.getDesc().equals(source);
        }

        /**
         * 解析报告
         *
         * @param in          文件流
         * @param propertyDTO 资产
         * @param dateRange   数据范围
         * @return java.util.List<cloud.wconnect.frontoffice.pojo.dto.adjustment.JournalDTO>
         * @author lichen
         * @date 2026/1/10
         */
        @Override
        public List<JournalDTO> parse(InputStream in, PropertyDTO propertyDTO, Map<String, Long> dateRange) throws ParseReportException {
            //查询忽略的TrxCode
            List<AdjTrxCodeConfig> adjTrxCodeConfigs = adjTrxCodeConfigService.listByPropertyId(propertyDTO.getId());

            long nowTimestamp = DateTimeUtils.nowTimestamp();

            try (InputStreamReader inputStreamReader = new InputStreamReader(in)) {
                ArrayList<JournalDTO> 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;
                    }

                    // 根据客人类型进行解析
                    JournalDTO journalDTO = parseByGuestType(propertyDTO, guestType, csvRecord, dateRange, adjTrxCodeConfigs);
                    if (Objects.nonNull(journalDTO)) {
                        journalDTO.setCreateTime(nowTimestamp);
                        resultList.add(journalDTO);
                    }
                }
                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 dateRange            数据范围
         * @param ignoreTrxCodeConfigs 忽略的TrxCode配置
         * @return cloud.wconnect.frontoffice.pojo.dto.adjustment.JournalDTO
         * @author lichen
         * @date 2026/1/10
         */
        private JournalDTO parseByGuestType(PropertyDTO propertyDTO, String guestType, CSVRecord csvRecord,
                                            Map<String, Long> dateRange, List<AdjTrxCodeConfig> ignoreTrxCodeConfigs) {
            Long startDate = dateRange.get(JobParameterDTO.START_DATE);
            Long endDate = dateRange.get(JobParameterDTO.END_DATE);
            //获取资产时区
            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 < startDate || date > endDate) {
                return null;
            }
            String transactionCode = CsvFileUtils.get(csvRecord, "G");
            if (StringUtils.isEmpty(transactionCode) || adjTrxCodeConfigService.isIgnore(ignoreTrxCodeConfigs, transactionCode)) {
                return null;
            }

            String amountStr = CsvFileUtils.get(csvRecord, "N");
            BigDecimal adjustedAmount = StringUtils.isEmpty(amountStr) ? BigDecimal.ZERO :
                    NumberUtil.parseCurrency(amountStr).setScale(BaseConstant.DATA_PRECISION, roundingMode);
            if (adjustedAmount.compareTo(BigDecimal.ZERO) >= 0) {
                return null;
            }

            //Pep平台的用户
            String userLogin = CsvFileUtils.get(csvRecord, "O");
            //房间号
            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();

            JournalDTO journalDTO = new JournalDTO();
            journalDTO.setGuestName(GuestNameUtil.removeSpaces(guestName));
            journalDTO.setRoomNumber(roomNumber);
            journalDTO.setAdjustedDollar(adjustedAmount.abs());
            journalDTO.setTrxDesc(description);
            journalDTO.setBusinessDate(Integer.valueOf(DateTimeUtils.localDateToStr(businessLocalDate, BaseConstant.DATE_FORMAT_YYYYMMDD)));
            journalDTO.setPmsAccount(userLogin);
            journalDTO.setTrxCode(transactionCode);
            journalDTO.setConfNumber(confNumber);
            return journalDTO;
        }

        /**
         * 根据客人类型获取客人姓名
         *
         * @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 file        文件
         * @param propertyDTO 资产DTO
         * @author lichen
         * @date 2026/1/10
         */
        @Override
        public void checkFile(MultipartFile file, PropertyDTO propertyDTO) {
            //校验文件格式
            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 资产DTO
         * @param file        文件
         * @param startDate   开始时间整点时刻时间戳
         * @param endDate     结束时间整点时刻时间戳
         * @param logId       日志ID
         * @param userId      操作人ID
         * @author lichen
         * @date 2026/1/10
         */
        @Override
        public void handleData(PropertyDTO propertyDTO, MultipartFile file,
                               Long startDate, Long endDate, Long logId, 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.PEP.getDesc());
                params.put(EventBodyParamEnum.UID.getDesc(), userId);
                params.put(EventBodyParamEnum.ID.getDesc(), logId);
                params.put(EventBodyParamEnum.START_DATE.getDesc(), startDate);
                params.put(EventBodyParamEnum.END_DATE.getDesc(), endDate);
                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 pep [all-transactions] report exception", e);
            }
        }
    }