# ParseJournalByTransactionCodePerDayServiceByShiji.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.cons.adjustment.AdjNotifyConfigTypeEnum;
    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.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.*;

    /**
     * 解析Shiji系统的Journal by Transaction Code per Day报告
     */
    @Slf4j
    @Component
    @DS("logbook")
    public class ParseJournalByTransactionCodePerDayServiceByShiji 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 2025/7/26
         */
        @Override
        public boolean supports(String source) {
            return SystemPlatformEnum.SHI_JI.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();
            //获取国际化的配置
            InternationalizationNumberDTO number = propertyDTO.getInternationalization().getNumber();
            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(number.getCalculationRule());

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

            long nowTimestamp = DateTimeUtils.nowTimestamp();

            try (InputStreamReader inputStreamReader = new InputStreamReader(in)) {
                ArrayList<JournalDTO> resultList = Lists.newArrayList();

                //获取CSV数据迭代器
                Iterable<CSVRecord> iterable = CSVFormat.EXCEL.parse(inputStreamReader);

                //转换成带下标的List
                List<CSVRecord> csvRecordList = Lists.newArrayList(iterable);

                for (int i = 1; i < csvRecordList.size(); i++) {
                    CSVRecord csvRecord = csvRecordList.get(i);
                    //日期格式mm/dd/yy
                    String dateStr = CsvFileUtils.get(csvRecord, "A");
                    if (StringUtils.isBlank(dateStr)) {
                        continue;
                    }
                    LocalDate businessLocalDate = DateTimeUtils.strToLocalDate(dateStr, BaseConstant.DATE_TIME_FORMAT_MM_DD_YY);
                    long date = DateTimeUtils.localDateToLong(businessLocalDate, timezone);

                    // 判断数据日期是否在开始日期 和 结束日期之间
                    if (date < startDate || date > endDate) {
                        continue;
                    }
                    String transactionCode = CsvFileUtils.get(csvRecord, "I");
                    if (StringUtils.isEmpty(transactionCode) || adjTrxCodeConfigService.isIgnore(adjTrxCodeConfigs, transactionCode)) {
                        continue;
                    }
                    String netDebitStr = CsvFileUtils.getAndFormatNumber(csvRecord, "O");
                    BigDecimal debit = StringUtils.isEmpty(netDebitStr) ? BigDecimal.ZERO :
                            new BigDecimal(netDebitStr).setScale(BaseConstant.DATA_PRECISION, roundingMode);
                    if (debit.compareTo(BigDecimal.ZERO) >= 0) {
                        continue;
                    }

                    // 获取下一条记录，若没有则无法判断indicator字段值是否Adjusted，跳过
                    int nextIndex = i + 1;
                    if (nextIndex >= csvRecordList.size()) {
                        // 没有下一条记录，则跳过
                        continue;
                    }

                    CSVRecord nextRecord = csvRecordList.get(nextIndex);
                    String nextDateStr = CsvFileUtils.get(nextRecord, "A");
                    if (StringUtils.isBlank(nextDateStr)) {
                        String indicator = CsvFileUtils.get(nextRecord, "C");
                        // 跳过不是"Adjusted"的数据
                        if (!"Adjusted".equals(indicator)) {
                            continue;
                        }
                    } else {
                        // 下一条记录有日期，则说明又是一条新的调账数据，
                        // 当前调账数据无法判断indicator字段值是否Adjusted，跳过
                        continue;
                    }

                    //Shiji平台的用户
                    String userLogin = CsvFileUtils.get(csvRecord, "N");
                    //房间号
                    String roomNumber = CsvFileUtils.get(csvRecord, "C");
                    if (StringUtils.isBlank(roomNumber)) {
                        roomNumber = "";
                    }
                    //客人姓名
                    String guestName = CsvFileUtils.get(csvRecord, "D");
                    guestName = GuestNameUtil.removeSpaces(guestName);
                    //描述
                    String description = CsvFileUtils.get(csvRecord, "J");
                    if (StringUtils.isBlank(description)) {
                        description = "";
                    }
                    //Account #
                    String accountNumber = CsvFileUtils.get(csvRecord, "F");
                    // Conf. #
                    String confNumber = CsvFileUtils.get(csvRecord, "G");
                    confNumber = StringUtils.isBlank(confNumber) ? "" : confNumber.trim();

                    JournalDTO journalDTO = new JournalDTO();
                    journalDTO.setCreateTime(nowTimestamp);
                    journalDTO.setGuestName(guestName);
                    journalDTO.setRoomNumber(roomNumber);
                    journalDTO.setAdjustedDollar(debit.abs());
                    journalDTO.setTrxDesc(description);
                    journalDTO.setBusinessDate(Integer.valueOf(DateTimeUtils.localDateToStr(businessLocalDate, BaseConstant.DATE_FORMAT_YYYYMMDD)));
                    journalDTO.setPmsAccount(userLogin);
                    journalDTO.setTrxCode(transactionCode);
                    journalDTO.setAccountNumber(accountNumber);
                    journalDTO.setConfNumber(confNumber);
                    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 shiji [Journal by Transaction Code per Day] report error", e);
            }
        }

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

        /**
         * 处理数据
         *
         * @param propertyDTO  资产DTO
         * @param file         文件
         * @param adJournalLog 导入日志
         * @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.SHI_JI.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);

                // 根据报告类型获取主题
                String subject = "";
                if (adJournalLog.getReportType() == AdjNotifyConfigTypeEnum.JOURNAL_REPORT_MISSED.getType()) {
                    subject = EventSubjectEnum.YESTERDAY_JOURNAL_BY_CASHIER_AND_TRANSACTION_CODE_SERVICE.getSubject();
                } else {
                    subject = EventSubjectEnum.YESTERDAY_JOURNAL_BY_CASHIER_AND_TRANSACTION_CODE_VOIDED_SERVICE.getSubject();
                }

                snsSender.publish(subject, JsonUtils.convertObjToString(objectMapper, new EventBodyDTO(key, params)));
            } catch (Exception e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "import shiji [Journal by Transaction Code per Day] report exception", e);
            }
        }
    }