# JournalFileParseByOther.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.PropertyDTO;
    import cloud.wconnect.commonlib.util.*;
    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.finance.service.chargeback.ICbJournalService;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.google.common.collect.Lists;
    import jakarta.annotation.Resource;
    import org.apache.commons.lang3.StringUtils;
    import org.apache.poi.ss.usermodel.*;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.beans.factory.annotation.Value;
    import org.springframework.stereotype.Service;
    import org.springframework.transaction.annotation.Transactional;
    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.Objects;

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

        @Resource
        private ICbJournalImportLogService cbJournalImportLogService;
        @Resource
        private ICbJournalService cbJournalService;
        @Autowired
        private AmazonS3Service amazonS3Service;
        @Autowired
        private I18nMessageUtils i18nMessageUtils;

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

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

        private static final String SOURCE = SystemPlatformEnum.OTHER.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<>();
            String timeZone = propertyDTO.getTimezone();
            try(Workbook workbook = WorkbookFactory.create(in)) {
                Sheet sheet = workbook.getSheetAt(0);
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(BaseConstant.DATE_FORMAT_YYYY_MM_DD);

                for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                    Row row = sheet.getRow(i);
                    if (Objects.isNull(row)) {
                        continue;
                    }

                    String transactionDateStr = CellUtils.convertCellStr(row.getCell(2), BaseConstant.DATE_FORMAT_YYYY_MM_DD);
                    long transactionDate = DateTimeUtils.toTimestamp(LocalDate.parse(transactionDateStr, dateTimeFormatter)
                            .atStartOfDay(ZoneId.of(timeZone)));
                    if (transactionDate != targetDate) {
                        continue;
                    }

                    JournalListBO journal = new JournalListBO();
                    journal.setGuestName(CellUtils.convertCellStr(row.getCell(0)));
                    journal.setRoomNumber(CellUtils.convertCellStr(row.getCell(1)));
                    journal.setDebit(new BigDecimal(CellUtils.convertCellStr(row.getCell(3))));

                    String creditCard = CellUtils.convertCellStr(row.getCell(4));
                    journal.setCardNumber(StringUtils.substring(creditCard, -4, creditCard.length()));

                    journal.setDescription(CellUtils.convertCellStr(row.getCell(5)));
                    journal.setTransactionDate(transactionDateStr);

                    String confNumber = CellUtils.convertCellStr(row.getCell(6));
                    journal.setConfNumber(StringUtils.isBlank(confNumber) ? "" : confNumber);
                    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("xls", "xlsx"));

            try (InputStream in = file.getInputStream();
                 Workbook workbook = WorkbookFactory.create(in)) {
                Sheet sheet = workbook.getSheetAt(0);
                Row titleRow = sheet.getRow(0);
                if (Objects.isNull(titleRow)) {
                    throw new BadRequestException(CommonErrorI18nConstant.IMPORT_REPORT_NOT_REQUIRED,
                            BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                            "The imported report is not the one required for the current functionality");
                }

                String nameTitle = CellUtils.convertCellStr(titleRow.getCell(0));
                String roomNumberTitle = CellUtils.convertCellStr(titleRow.getCell(1));
                String transactionDateTitle = CellUtils.convertCellStr(titleRow.getCell(2));
                String transactionAmountTitle = CellUtils.convertCellStr(titleRow.getCell(3));
                String cardNumberTitle = CellUtils.convertCellStr(titleRow.getCell(4));
                String confNumberTitle = CellUtils.convertCellStr(titleRow.getCell(6));
                DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern(BaseConstant.DATE_FORMAT_YYYY_MM_DD);

                for (int i = 1; i <= sheet.getLastRowNum(); i++) {
                    Row row = sheet.getRow(i);
                    if (Objects.isNull(row)) {
                        continue;
                    }

                    Cell nameCell = row.getCell(0);
                    if (Objects.isNull(nameCell) || StringUtils.isBlank(nameCell.toString())) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(nameTitle),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The name cannot be empty");
                    } else {
                        // 最多 60 个字
                        if (CellUtils.convertCellStr(nameCell).length() > 60) {
                            throw new BadRequestException(CommonErrorI18nConstant.OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(nameTitle, 60),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The name cannot be more than 60 characters");
                        }
                    }

                    Cell roomNumberCell = row.getCell(1);
                    if (Objects.isNull(roomNumberCell) || StringUtils.isBlank(roomNumberCell.toString())) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(roomNumberTitle),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The room number cannot be empty");
                    } else {
                        if (CellUtils.convertCellStr(roomNumberCell).length() > 10) {
                            throw new BadRequestException(CommonErrorI18nConstant.OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(roomNumberTitle, 10),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The room number cannot be more than 10 characters");
                        }
                    }

                    Cell transactionDateCell = row.getCell(2);
                    if (Objects.isNull(transactionDateCell) || StringUtils.isBlank(transactionDateCell.toString())) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(transactionDateTitle),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The transaction date cannot be empty");
                    } else {
                        // 格式必须 yyyy-MM-dd
                        try {
                            LocalDate.parse(CellUtils.convertCellStr(transactionDateCell, BaseConstant.DATE_FORMAT_YYYY_MM_DD), dateTimeFormatter);
                        } catch (Exception e) {
                            throw new BadRequestException(CommonErrorI18nConstant.FORMAT_INCORRECT,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(transactionDateTitle, BaseConstant.DATE_FORMAT_YYYY_MM_DD),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The transaction date format error");
                        }
                    }

                    Cell transactionAmountCell = row.getCell(3);
                    if (Objects.isNull(transactionAmountCell) || StringUtils.isBlank(transactionAmountCell.toString())) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(transactionAmountTitle),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The transaction amount cannot be empty");
                    } else {
                        BigDecimal transactionAmount;
                        try {
                            transactionAmount = new BigDecimal(CellUtils.convertCellStr(transactionAmountCell));
                        } catch (Exception e) {
                            throw new BadRequestException(CommonErrorI18nConstant.MUST_NUMBER,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(transactionAmountTitle),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The transaction amount must be a number");
                        }
                        // 整数 8 位
                        if (transactionAmount.toBigInteger().toString().length() > 8) {
                            throw new BadRequestException(CommonErrorI18nConstant.NUMBER_INTEGER_OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(transactionAmountTitle, 8),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The transaction amount exceed the limit");
                        }
                    }

                    Cell cardNumberCell = row.getCell(4);
                    if (Objects.isNull(cardNumberCell) || StringUtils.isBlank(cardNumberCell.toString())) {
                        throw new BadRequestException(CommonErrorI18nConstant.CANNOT_EMPTY,
                                i18nMessageUtils.getErrorParamMapNotNeedTranslate(cardNumberTitle),
                                BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                "The card number cannot be empty");
                    } else {
                        // 最多 20 个字
                        if (CellUtils.convertCellStr(cardNumberCell).length() > 20) {
                            throw new BadRequestException(CommonErrorI18nConstant.OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(cardNumberTitle, 20),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The card number cannot be more than 20 characters");
                        }
                    }

                    Cell confNumberCell = row.getCell(6);
                    if (Objects.nonNull(confNumberCell)) {
                        // 最多 30 个字
                        if (CellUtils.convertCellStr(confNumberCell).length() > 30) {
                            throw new BadRequestException(CommonErrorI18nConstant.OVERLENGTH,
                                    i18nMessageUtils.getErrorParamMapNotNeedTranslate(confNumberTitle, 30),
                                    BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                                    "The confNumber cannot be more than 30 characters");
                        }
                    }
                }
            } 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);
                importLog.setStatus(ReportImportResultCons.IMPORT_RESULT_REPAIRING);
            }
            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
        @Transactional(rollbackFor = Exception.class)
        public void handleFile(PropertyDTO propertyDTO, MultipartFile file,
                               CbJournalImportLog importLog, Integer userId) {
            boolean importSuccess = true;
            try (InputStream inputStream = file.getInputStream()) {
                List<JournalListBO> journals = parsReport(propertyDTO, inputStream, importLog.getTheDate());
                String dateStr = DateTimeUtils.toZonedDateTime(importLog.getTheDate(), propertyDTO.getTimezone())
                        .format(DateTimeFormatter.ofPattern(BaseConstant.DATE_FORMAT_YYYY_MM_DD));
                cbJournalService.handleJournalData(propertyDTO, userId, dateStr, journals);
            } catch (Exception e) {
                importSuccess = false;
                throw new ParseReportException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(), "parse journal report error", e);
            } finally {
                if (importSuccess) {
                    importSuccess(importLog, userId);
                } else {
                    importFail(importLog);
                }
            }
        }

        /**
         * 导入成功
         *
         * @param importLog 导入记录
         * @param userId    操作人
         * @author yyt
         * @date 2024/8/9
         **/
        private void importSuccess(CbJournalImportLog importLog, int userId) {
            TransactionUtils.afterCommitSyncExecute(() -> {
                // 更新导入记录
                CbJournalImportLog updateLog = new CbJournalImportLog();
                updateLog.setId(importLog.getId());
                updateLog.setStatus(ReportImportResultCons.IMPORT_RESULT_SUCCESS);
                if (importLog.getStatus() == ReportImportResultCons.IMPORT_RESULT_REPAIRING) {
                    updateLog.setResolvedBy(userId).setResolvedTime(DateTimeUtils.nowTimestamp());
                }
                cbJournalImportLogService.updateById(updateLog);
            });
        }

        /**
         * 导入失败
         *
         * @param importLog 导入记录
         * @author yyt
         * @date 2024/8/9
         **/
        private void importFail(CbJournalImportLog importLog) {
            TransactionUtils.afterCompletionRollbackSyncExecute(() -> {
                // 更新导入记录
                CbJournalImportLog updateLog = new CbJournalImportLog();
                updateLog.setId(importLog.getId());
                updateLog.setStatus(ReportImportResultCons.IMPORT_RESULT_FAIL);
                cbJournalImportLogService.updateById(updateLog);
            });
        }

    }