# MorOvertimeParseServiceByAdp.java

    package cloud.wconnect.workperformance.service.mor.overtime;

    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.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.service.AttendancePropertyCodeInternalService;
    import cloud.wconnect.commonlib.util.*;
    import cloud.wconnect.sns.http.processor.Sender;
    import cloud.wconnect.workperformance.cons.BusinessEnum;
    import cloud.wconnect.workperformance.cons.EventSubjectEnum;
    import cloud.wconnect.workperformance.entity.mor.MorOvertimeReportFilterConfig;
    import cloud.wconnect.workperformance.pojo.bo.mor.overtime.OvertimeDailyBO;
    import cloud.wconnect.workperformance.service.AmazonS3Service;
    import cloud.wconnect.workperformance.service.mor.IMorOvertimeReportFilterConfigService;
    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 org.apache.commons.collections.CollectionUtils;
    import org.apache.commons.csv.CSVFormat;
    import org.apache.commons.csv.CSVRecord;
    import org.apache.commons.lang3.StringUtils;
    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.util.*;
    import java.util.stream.Collectors;

    /**
     * 服务实现类：ADP 加班时间报告处理
     *
     * @author zc
     * @date 2024/08/19
     */
    @Component
    @DS("work_performance")
    public class MorOvertimeParseServiceByAdp implements IMorOvertimeParseService {
        @Resource
        private AttendancePropertyCodeInternalService attendancePropertyCodeInternalService;
        @Resource
        private IMorOvertimeReportFilterConfigService filterConfigService;
        @Resource
        private ObjectMapper objectMapper;
        @Resource
        private AmazonS3Service amazonS3Service;
        @Resource
        @Qualifier("3pSender")
        private Sender snsSender;

        @Value("${aws-s3.third-party.key.monthly-ot-report.overtime-details.overtime}")
        private String s3FilePath;

        @Value("${file-max-size.import-report.overtime}")
        private long fileMaxSize;

        /**
         * 判断是否支持
         *
         * @param source 数据源
         * @return boolean
         * @author zc
         * @date 2024/8/16
         */
        @Override
        public boolean supports(String source) {
            return SystemPlatformEnum.ADP.getDesc().equals(source);
        }

        /**
         * 校验文件内容是否合法
         *
         * @param propertyDTOList 资产集合
         * @param file            文件
         * @author zc
         * @date 2024/8/16
         */
        @Override
        public void checkFile(List<PropertyDTO> propertyDTOList, MultipartFile file) {
            // 限制文件大小
            FileCheckUtils.checkFileSize(file, fileMaxSize);
            // 校验文件格式
            UploadUtils.checkFileFormat(file, Lists.newArrayList("csv"));
            // 校验文件内容
            try (InputStream in = file.getInputStream()) {
                AdpFileCheckUtils.checkHoursWorkedByDepartment(in);
            } catch (IOException e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle import [Hours worked by Department] ADP report error.", e);
            }
        }

        /**
         * 处理数据
         *
         * @param propertyDTOList      资产集合
         * @param file                 文件
         * @param propertyId2DateRange 报告数据日期范围(yyyyMMdd)
         * @param logIds               日志 id 集合
         * @param operatorId           操作人 id
         * @author zc
         * @date 2025/3/15
         */
        @Override
        public void handleData(List<PropertyDTO> propertyDTOList, MultipartFile file, Map<Integer, List<Long>> propertyId2DateRange, List<Long> logIds, int operatorId) {
            try {
                String tenantSymbol = propertyDTOList.get(0).getTenantSymbol();
                List<String> propertyAbbrList = propertyDTOList.stream().map(PropertyDTO::getAbbr).toList();

                String key = tenantSymbol + "/" + StringUtils.join(propertyAbbrList, "_") + "/" + s3FilePath
                        + UploadUtils.getRandomFileName(file.getOriginalFilename());
                // 上传文件到 S3 服务器，用于监听器监听并处理文件
                amazonS3Service.uploadFile(file, key);

                List<Long> dateRangeList = propertyId2DateRange.values().stream().toList().get(0);

                // 封装事件体
                HashMap<String, Object> parameter = Maps.newHashMap();
                parameter.put(EventBodyParamEnum.TENANT_SYMBOL.getDesc(), tenantSymbol);
                parameter.put(EventBodyParamEnum.PROPERTY_ABBR.getDesc(), propertyAbbrList);
                parameter.put(EventBodyParamEnum.ORIGINATE_FROM.getDesc(), BusinessEnum.MOR_OVERTIME.getBusiness());
                parameter.put(EventBodyParamEnum.SOURCE.getDesc(), SystemPlatformEnum.ADP.getDesc());
                parameter.put(EventBodyParamEnum.ID.getDesc(), logIds);
                parameter.put(EventBodyParamEnum.UID.getDesc(), operatorId);
                parameter.put(EventBodyParamEnum.START_DATE.getDesc(), dateRangeList.get(0));
                parameter.put(EventBodyParamEnum.END_DATE.getDesc(), dateRangeList.get(1));

                // 发布事件通知
                snsSender.publish(EventSubjectEnum.ATTENDANCE_WORK_HOUR_LAST_MONTH.getSubject(),
                        JsonUtils.convertObjToString(objectMapper, new EventBodyDTO(key, parameter)));
            } catch (Exception e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle Mor Overtime ADP Work Hour report send event exception", e);
            }
        }

        /**
         * 读取报告文件，转换生成加班时间信息集合
         *
         * @param propertyDTOList      资产集合
         * @param in                   文件流
         * @param propertyId2DateRange 数据日期范围
         * @return OvertimeListBO 集合
         * @author zc
         * @date 2024/8/17
         */
        @Override
        public List<OvertimeDailyBO> parse(List<PropertyDTO> propertyDTOList, InputStream in, Map<Integer, List<Long>> propertyId2DateRange) throws ParseReportException {
            // 获取资产 ADP Code
            Map<String, PropertyDTO> code2PropertyDTO = attendancePropertyCodeInternalService.getCode2PropertyDTO(propertyDTOList);
            List<Integer> propertyIds = propertyDTOList.stream().map(PropertyDTO::getId).toList();
            // 获取过滤的 Pay Code
            Map<Integer, List<String>> propertyId2PayCodeList = filterConfigService.listFilterPayCode(propertyIds).stream()
                    .collect(Collectors.groupingBy(MorOvertimeReportFilterConfig::getPropertyId,
                            Collectors.mapping(MorOvertimeReportFilterConfig::getPayCode, Collectors.toList())));
            try (InputStreamReader inputStreamReader = new InputStreamReader(in)) {
                List<OvertimeDailyBO> overtimes = Lists.newArrayList();
                Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(inputStreamReader);
                for (CSVRecord record : records) {
                    // 跳过第一行的标题行
                    if (record.getRecordNumber() == 1) {
                        continue;
                    }
                    String propertyNameStr = record.get(0);
                    if (StringUtils.isBlank(propertyNameStr)) {
                        continue;
                    }
                    PropertyDTO propertyDTO = code2PropertyDTO.get(record.get(0));
                    if (Objects.isNull(propertyDTO)) {
                        continue;
                    }
                    // 数据日期范围为空的不处理
                    List<Long> dateRangeList = propertyId2DateRange.getOrDefault(propertyDTO.getId(), Collections.emptyList());
                    if (CollectionUtils.isEmpty(dateRangeList)) {
                        continue;
                    }
                    // 跳过没有日期的数据
                    if (StringUtils.isBlank(record.get(13))) {
                        continue;
                    }
                    // 只处理指定日期范围的数据
                    long theDate = Long.parseLong(DateTimeUtils.localDateToStr(DateTimeUtils.strToLocalDate(record.get(13),
                            BaseConstant.DATE_FORMAT_MM_DD_YYYY_SLASH), BaseConstant.DATE_FORMAT_YYYYMMDD));
                    if (theDate < dateRangeList.get(0) || theDate > dateRangeList.get(1)) {
                        continue;
                    }
                    // 跳过过滤配置未包含的数据
                    List<String> payCodeList = propertyId2PayCodeList.getOrDefault(propertyDTO.getId(), Lists.newArrayList());
                    if (!payCodeList.contains(record.get(7))) {
                        continue;
                    }
                    // 跳过没有工作部门 Code 的数据
                    if (StringUtils.isEmpty(record.get(5))) {
                        continue;
                    }
                    // 跳过没有加班时薪的数据
                    if (StringUtils.isBlank(record.get(11))) {
                        continue;
                    }
                    overtimes.add(convert2Overtime(propertyDTO, record));
                }
                return overtimes;
            } catch (IOException e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle parse Mor Overtime ADP Work Hour report error.", e);
            }
        }

        /**
         * 将文件数据转成加班信息
         *
         * @param propertyDTO 资产
         * @param record      CSVRecord
         * @return OvertimeListBO
         * @author zc
         * @date 2024/8/17
         */
        private OvertimeDailyBO convert2Overtime(PropertyDTO propertyDTO, CSVRecord record) {
            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(propertyDTO
                    .getInternationalization().getNumber().getCalculationRule());

            OvertimeDailyBO overtime = new OvertimeDailyBO();
            overtime.setProperty(propertyDTO.getAbbr());
            overtime.setPositionId(record.get(1));
            overtime.setLastName(record.get(2));
            overtime.setFirstName(record.get(3));
            overtime.setWorkDepartmentCode(record.get(5));
            overtime.setWorkDepartmentDesc(record.get(6));

            String timeIn = DateTimeUtils.localDateTimeToStr(DateTimeUtils.strToLocalDateTime(record.get(9),
                    BaseConstant.DATE_FORMAT_MM_DD_YYYY_SLASH_HH_MM_A), BaseConstant.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MM);
            overtime.setTimeInStr(timeIn);
            String timeOut = DateTimeUtils.localDateTimeToStr(DateTimeUtils.strToLocalDateTime(record.get(10),
                    BaseConstant.DATE_FORMAT_MM_DD_YYYY_SLASH_HH_MM_A), BaseConstant.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MM);
            overtime.setTimeOutStr(timeOut);

            String payRateStr = record.get(11).substring(1).replaceAll(",", "").trim();
            BigDecimal payRate = StringUtils.isBlank(payRateStr) ? BigDecimal.ZERO
                    : new BigDecimal(payRateStr).setScale(BaseConstant.DATA_PRECISION, roundingMode);
            overtime.setPayRate(payRate);

            String hoursStr = record.get(12).replaceAll(",", "").trim();
            BigDecimal hours = StringUtils.isBlank(hoursStr) ? BigDecimal.ZERO
                    : new BigDecimal(hoursStr).setScale(BaseConstant.DATA_PRECISION, roundingMode);
            overtime.setHours(hours);

            overtime.setAmount(payRate.multiply(hours).setScale(BaseConstant.DATA_PRECISION, roundingMode));

            String theDateStr = DateTimeUtils.localDateToStr(DateTimeUtils.strToLocalDate(record.get(13),
                    BaseConstant.DATE_FORMAT_MM_DD_YYYY_SLASH), BaseConstant.DATE_FORMAT_YYYY_MM_DD);
            overtime.setTheDateStr(theDateStr);
            return overtime;
        }
    }