# WeeklyMonthlyRevenueImportLogServiceImpl.java

    package cloud.wconnect.rateshop.service.weeklymonthlyrevenue.impl;

    import cloud.wconnect.commonlib.component.BeanMapper;
    import cloud.wconnect.commonlib.cons.BaseConstant;
    import cloud.wconnect.commonlib.cons.BaseErrorCodeEnum;
    import cloud.wconnect.commonlib.cons.CommonErrorI18nConstant;
    import cloud.wconnect.commonlib.cons.ReportImportResultCons;
    import cloud.wconnect.commonlib.exception.BadRequestException;
    import cloud.wconnect.commonlib.exception.ForbiddenException;
    import cloud.wconnect.commonlib.pojo.dto.ListPagedDTO;
    import cloud.wconnect.commonlib.pojo.dto.PropertyDTO;
    import cloud.wconnect.commonlib.service.UserInternalService;
    import cloud.wconnect.commonlib.util.DateTimeUtils;
    import cloud.wconnect.rateshop.cons.weeklymonthlyrevenue.MonthlyRevenueImportCategoryCons;
    import cloud.wconnect.rateshop.entity.weeklymonthlyrevenue.WeeklyMonthlyRevenueImportLog;
    import cloud.wconnect.rateshop.mapper.weeklymonthlyrevenue.WeeklyMonthlyRevenueImportLogMapper;
    import cloud.wconnect.rateshop.pojo.dto.weeklymonthlyrevenue.WeeklyMonthlyRevenueImportLogDTO;
    import cloud.wconnect.rateshop.pojo.query.weeklymonthlyrevenue.WeeklyMonthlyRevenueImportLogQuery;
    import cloud.wconnect.rateshop.service.weeklymonthlyrevenue.IWeeklyMonthlyRevenueImportLogService;
    import com.baomidou.dynamic.datasource.annotation.DS;
    import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
    import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
    import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
    import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
    import com.google.common.collect.Sets;
    import jakarta.annotation.Nullable;
    import jakarta.annotation.Resource;
    import org.apache.commons.collections.CollectionUtils;
    import org.springframework.stereotype.Service;

    import java.text.MessageFormat;
    import java.time.LocalDate;
    import java.time.ZoneId;
    import java.util.List;
    import java.util.Map;
    import java.util.Objects;
    import java.util.Set;

    /**
     * <p>
     * Weekly Monthly Revenue report import log 服务实现类
     * </p>
     *
     * @author zc
     * @since 2024-05-13
     */
    @Service
    @DS("rate_shop")
    public class WeeklyMonthlyRevenueImportLogServiceImpl extends ServiceImpl<WeeklyMonthlyRevenueImportLogMapper, WeeklyMonthlyRevenueImportLog> implements IWeeklyMonthlyRevenueImportLogService {

        @Resource
        private UserInternalService userInternalService;
        @Resource
        private BeanMapper beanMapper;

        /**
         * 保存导入记录
         *
         * @param propertyDTO  资产DTO
         * @param category     0:历史和未来 1:当前和历史 2:未来
         * @param versionDate  版本日期（yyyyMMdd）
         * @param dateRange    日期范围（yyyyMMdd）
         * @param key          S3 key
         * @param importResult 导入结果
         * @param reportType   报告类型
         * @param operatorId   操作人 id
         * @author zc
         * @date 2025/5/24
         */
        @Override
        public void save(PropertyDTO propertyDTO, int category, @Nullable Long versionDate, List<Long> dateRange, String key,
                         int importResult, int reportType, int operatorId) {
            WeeklyMonthlyRevenueImportLog importLog = new WeeklyMonthlyRevenueImportLog();
            importLog.setPropertyId(propertyDTO.getId());
            importLog.setCategory(category);
            importLog.setTheDate(Long.parseLong(DateTimeUtils.localDateToStr(LocalDate.now(ZoneId.of(propertyDTO.getTimezone())),
                    BaseConstant.DATE_FORMAT_YYYYMMDD)));
            importLog.setVersionDate(versionDate);
            importLog.setReportType(reportType);
            importLog.setStartDate(dateRange.get(0));
            importLog.setEndDate(dateRange.get(1));
            importLog.setUrl(key);
            importLog.setCreatedBy(operatorId);
            importLog.setCreatedTime(DateTimeUtils.nowTimestamp());
            importLog.setResolvedBy(0);
            importLog.setResolvedTime(0L);
            importLog.setImportResult(importResult);
            save(importLog);
        }

        /**
         * 获取报告导入记录
         *
         * @param propertyDTO    资产
         * @param importLogQuery 查询条件
         * @return WeeklyMonthlyRevenueImportLogDTO 集合
         * @author zc
         * @date 2024/5/17
         */
        @Override
        public ListPagedDTO<WeeklyMonthlyRevenueImportLogDTO> list(PropertyDTO propertyDTO, WeeklyMonthlyRevenueImportLogQuery importLogQuery) {
            LambdaQueryWrapper<WeeklyMonthlyRevenueImportLog> queryWrapper = new QueryWrapper<WeeklyMonthlyRevenueImportLog>().lambda()
                    .in(CollectionUtils.isNotEmpty(importLogQuery.getReportType()), WeeklyMonthlyRevenueImportLog::getReportType, importLogQuery.getReportType())
                    .eq(WeeklyMonthlyRevenueImportLog::getPropertyId, propertyDTO.getId())
                    .in(WeeklyMonthlyRevenueImportLog::getCategory,
                            Objects.isNull(importLogQuery.getCategory()) ? List.of(MonthlyRevenueImportCategoryCons.ALL,
                                    MonthlyRevenueImportCategoryCons.HISTORY, MonthlyRevenueImportCategoryCons.FORECAST) :
                                    (importLogQuery.getCategory() == MonthlyRevenueImportCategoryCons.HISTORY ?
                                            List.of(MonthlyRevenueImportCategoryCons.ALL, MonthlyRevenueImportCategoryCons.HISTORY) :
                                            List.of(MonthlyRevenueImportCategoryCons.ALL, MonthlyRevenueImportCategoryCons.FORECAST)))
                    .in(CollectionUtils.isNotEmpty(importLogQuery.getStatus()),
                            WeeklyMonthlyRevenueImportLog::getImportResult, importLogQuery.getStatus())
                    .and(Objects.nonNull(importLogQuery.getStartOperationDate()) && Objects.nonNull(importLogQuery.getEndOperationDate()),
                            wrapper -> wrapper.between(WeeklyMonthlyRevenueImportLog::getCreatedTime,
                                            importLogQuery.getStartOperationDate(), importLogQuery.getEndOperationDate())
                                    .or().between(WeeklyMonthlyRevenueImportLog::getResolvedTime,
                                            importLogQuery.getStartOperationDate(), importLogQuery.getEndOperationDate()))
                    .between(Objects.nonNull(importLogQuery.getStartVersionDate()) && Objects.nonNull(importLogQuery.getEndVersionDate()),
                            WeeklyMonthlyRevenueImportLog::getVersionDate, importLogQuery.getStartVersionDate(), importLogQuery.getEndVersionDate())
                    .between(Objects.nonNull(importLogQuery.getStartFromDataDate()) && Objects.nonNull(importLogQuery.getStartToDataDate()),
                            WeeklyMonthlyRevenueImportLog::getStartDate, importLogQuery.getStartFromDataDate(), importLogQuery.getStartToDataDate())
                    .between(Objects.nonNull(importLogQuery.getEndFromDataDate()) && Objects.nonNull(importLogQuery.getEndToDataDate()),
                            WeeklyMonthlyRevenueImportLog::getEndDate, importLogQuery.getEndFromDataDate(), importLogQuery.getEndToDataDate());

            List<WeeklyMonthlyRevenueImportLog> importLogList;
            long total;
            if (Objects.nonNull(importLogQuery.getPage()) && Objects.nonNull(importLogQuery.getSize())) {
                Page<WeeklyMonthlyRevenueImportLog> page = page(new Page<>(importLogQuery.getPage(), importLogQuery.getSize()),
                        queryWrapper.orderByDesc(WeeklyMonthlyRevenueImportLog::getId));
                importLogList = page.getRecords();
                total = page.getTotal();
            } else {
                importLogList = list(queryWrapper);
                total = importLogList.size();
            }
            if (CollectionUtils.isEmpty(importLogList)) {
                return new ListPagedDTO<>();
            }

            Set<Integer> userIds = Sets.newHashSet();
            importLogList.forEach(item -> {
                userIds.add(item.getCreatedBy());
                userIds.add(item.getResolvedBy());
            });
            Map<Integer, String> userId2UserName = userInternalService.getNameMapByIds(propertyDTO.getTenantId(), userIds);
            return new ListPagedDTO<>(total, beanMapper.mapList(importLogList, WeeklyMonthlyRevenueImportLogDTO.class, (item, dto) -> {
                dto.setCreatedByName(userId2UserName.get(item.getCreatedBy()));
                dto.setResolvedByName(userId2UserName.get(item.getResolvedBy()));
            }));
        }

        /**
         * 校验是否存在并返回对象
         *
         * @param id 记录 id
         * @return WeeklyMonthlyRevenueImportLog
         * @author zc
         * @date 2024/5/17
         */
        @Override
        public WeeklyMonthlyRevenueImportLog checkExist(long id) {
            WeeklyMonthlyRevenueImportLog importLog = getById(id);
            if (Objects.isNull(importLog)) {
                throw new BadRequestException(CommonErrorI18nConstant.DATA_NOT_FOUND,
                        BaseErrorCodeEnum.DATA_VALIDATION_ERROR.getCode(),
                        "The import log is not found, id = " + id);
            }
            return importLog;
        }

        /**
         * 校验数据归属
         *
         * @param propertyId 资产 id
         * @param importLog  记录
         * @author zc
         * @date 2024/5/17
         */
        @Override
        public void checkBelong(int propertyId, WeeklyMonthlyRevenueImportLog importLog) {
            if (importLog.getPropertyId().compareTo(propertyId) != 0) {
                throw new ForbiddenException(BaseErrorCodeEnum.DATA_FORBIDDEN.getI18nCode(),
                        BaseErrorCodeEnum.DATA_FORBIDDEN.getCode(),
                        MessageFormat.format("The import log is not belong to current property, logId:{0}, " +
                                "currentPropertyId:{1}", importLog.getId(), propertyId));
            }
        }

        /**
         * 手动解决成功
         *
         * @param logId        记录 id
         * @param operatorId   操作人 id
         * @param importLogUrl 导入记录 url
         * @author zc
         * @date 2024/5/17
         */
        @Override
        public void manualSolveSuccess(long logId, int operatorId, String importLogUrl) {
            WeeklyMonthlyRevenueImportLog importLog = new WeeklyMonthlyRevenueImportLog();
            importLog.setId(logId);
            importLog.setResolvedBy(operatorId);
            importLog.setResolvedTime(DateTimeUtils.nowTimestamp());
            importLog.setUrl(importLogUrl);
            importLog.setImportResult(ReportImportResultCons.IMPORT_RESULT_SUCCESS);
            updateById(importLog);
        }

        /**
         * 忽略异常的记录
         *
         * @param importLog   记录
         * @param loginUserId 操作人 id
         * @author lichen
         * @date 2025/10/31
         */
        @Override
        public void ignore(WeeklyMonthlyRevenueImportLog importLog, int loginUserId) {
            updateById(new WeeklyMonthlyRevenueImportLog().setId(importLog.getId())
                    .setImportResult(ReportImportResultCons.IMPORT_RESULT_IGNORE)
                    .setResolvedBy(loginUserId)
                    .setResolvedTime(DateTimeUtils.nowTimestamp()));
        }

        /**
         * 自动解决
         *
         * @param logId        记录 id
         * @param handleResult 处理结果
         * @param operatorId   操作人 id
         * @author lichen
         * @date 2025/10/31
         */
        @Override
        public void autoSolve(Long logId, boolean handleResult, int operatorId) {
            updateById(new WeeklyMonthlyRevenueImportLog().setId(logId)
                    .setImportResult(handleResult ? ReportImportResultCons.IMPORT_RESULT_SUCCESS : ReportImportResultCons.IMPORT_RESULT_FAIL)
                    .setResolvedBy(operatorId)
                    .setResolvedTime(DateTimeUtils.nowTimestamp()));
        }
    }