# JournalFileParseByShiji.java

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

    import cloud.wconnect.commonlib.cons.*;
    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.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;

    /**
     * 解析 journal 报告
     *
     * @author yyt
     * 2023/9/8
     */
    @Service
    @DS("finance")
    @Slf4j
    public class JournalFileParseByShiji 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;
        @Qualifier("3pSender")
        @Autowired
        private Sender snsSender;

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

        /**
         * 判断支持的平台
         *
         * @param source 平台数据源
         * @return boolean
         * @author lichen
         * @date 2025/7/28
         */
        @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) {
            InternationalizationNumberDTO number = propertyDTO.getInternationalization().getNumber();
            String calculationRule = number.getCalculationRule();
            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(calculationRule);

            List<JournalListBO> result = new ArrayList<>();

            String timezone = propertyDTO.getTimezone();
            try (InputStreamReader inputStreamReader = new InputStreamReader(in)) {
                //获取CSV数据迭代器
                Iterable<CSVRecord> iterable = CSVFormat.EXCEL.parse(inputStreamReader);

                ArrayList<CSVRecord> allRows = Lists.newArrayList();
                iterable.forEach(record -> {
                    if (record.getRecordNumber() == 1) {
                        return;
                    }
                    allRows.add(record);
                });

                for (int i = 0; i < allRows.size(); i++) {
                    CSVRecord csvRecord = allRows.get(i);
                    //日期格式mm/dd/yy
                    String dateStr = ShijiFileCheckUtils.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 != targetDate) {
                        continue;
                    }

                    JournalListBO journal = new JournalListBO();

                    //设置日期
                    journal.setTransactionDate(DateTimeUtils.localDateToStr(businessLocalDate, BaseConstant.DATE_FORMAT_YYYY_MM_DD));

                    String roomNumber = ShijiFileCheckUtils.get(csvRecord, "C");
                    journal.setRoomNumber(StringUtils.isEmpty(roomNumber) ? "" : roomNumber);

                    String guestName = ShijiFileCheckUtils.get(csvRecord, "D");
                    journal.setGuestName(guestName);

                    String description = ShijiFileCheckUtils.get(csvRecord, "J");
                    journal.setDescription(StringUtils.isEmpty(description) ? "" : description);

                    String netCreditStr = ShijiFileCheckUtils.getAndFormatNumber(csvRecord, "Q");
                    journal.setDebit(StringUtils.isEmpty(netCreditStr) ? BigDecimal.ZERO :
                            new BigDecimal(netCreditStr).setScale(BaseConstant.DATA_PRECISION, roundingMode));

                    //下一行的行号
                    int nextRowNumber = i + 1;
                    if (nextRowNumber <= allRows.size() - 1) {//防止数组越界
                        CSVRecord nextCsvRecord = allRows.get(nextRowNumber);

                        //下一行的日期字段为空时，表示还是当前这一条journal数据
                        String nextDateStr = ShijiFileCheckUtils.get(nextCsvRecord, "A");
                        if (StringUtils.isEmpty(nextDateStr)) {
                            //获取卡号后四位
                            String cardNumber = ShijiFileCheckUtils.get(nextCsvRecord, "E");
                            journal.setCardNumber(StringUtils.isEmpty(cardNumber) ? "" : cardNumber);
                        } else {
                            journal.setCardNumber("");
                        }
                    } else {
                        journal.setCardNumber("");
                    }
                    // 排除卡号后4位为空的数据
                    if (StringUtils.isBlank(journal.getCardNumber())) {
                        continue;
                    }

                    // Conf. #
                    String confNumber = ShijiFileCheckUtils.get(csvRecord, "G");
                    confNumber = StringUtils.isBlank(confNumber) ? "" : confNumber.trim();
                    journal.setConfNumber(confNumber);

                    result.add(journal);
                }
                return result;
            } 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 propertyDTO 资产
         * @param file        文件
         * @return void
         * @author lichen
         * @date 2025/7/28
         */
        @Override
        public void checkFile(PropertyDTO propertyDTO, MultipartFile file) {
            // 限制文件大小
            FileCheckUtils.checkFileSize(file, importReportFileMaxSize);
            // 校验文件格式
            UploadUtils.checkFileFormat(file, Lists.newArrayList("csv"));

            try (InputStream in = file.getInputStream()) {
                ShijiFileCheckUtils.checkJournalByTransactionCodePerDay(in);
            } catch (BadRequestException e) {
                throw e;
            } catch (Exception e) {
                throw new ParseReportException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "parsing shiji [Journal by Transaction Code per Day] file failed.", e);
            }
        }

        /**
         * 处理导入记录
         *
         * @param propertyDTO 资产
         * @param importLog   导入记录
         * @param theDate     指定日期
         * @param file        文件
         * @param userId      操作人
         * @return cloud.wconnect.finance.entity.chargeback.CbJournalImportLog
         * @author lichen
         * @date 2025/7/28
         */
        @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 2025/7/28
         */
        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      操作人
         * @return void
         * @author lichen
         * @date 2025/7/28
         */
        @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.SHI_JI.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 shiji [Journal by Transaction Code per Day] event", e);
            }
        }

    }