# ActualHourParseServiceByAdp.java

    package cloud.wconnect.workperformance.service.sva.actualschedulehour.actualhour;

    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.pojo.dto.internationalization.InternationalizationNumberDTO;
    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.pojo.bo.sva.actualschedulehour.SvaActualHoursBO;
    import cloud.wconnect.workperformance.service.AmazonS3Service;
    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.time.LocalDate;
    import java.time.LocalDateTime;
    import java.util.*;

    /**
     * 服务实现类：ADP 考勤平台 Actual Hour 报告处理
     *
     * @author zc
     * @date 2025/4/21
     */
    @Component
    @DS("work_performance")
    public class ActualHourParseServiceByAdp implements IActualHourParseService {
        @Resource
        private AttendancePropertyCodeInternalService attendancePropertyCodeInternalService;
        @Resource
        private ObjectMapper objectMapper;
        @Resource
        private AmazonS3Service amazonS3Service;
        @Resource
        @Qualifier("3pSender")
        private Sender snsSender;

        @Value("${aws-s3.third-party.key.schedule-vs-actual.actual-hours}")
        private String s3FilePath;
        @Value("${file-max-size.import-report.sva}")
        private long fileMaxSize;

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

        /**
         * 校验文件内容是否合法
         *
         * @param propertyDTOList 资产集合
         * @param file            文件
         * @author zc
         * @date 2024/8/19
         */
        @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 2024/8/19
         */
        @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.SVA_AV_HOURS.getBusiness());
                parameter.put(EventBodyParamEnum.SOURCE.getDesc(), SystemPlatformEnum.ADP.getDesc());
                parameter.put(EventBodyParamEnum.UID.getDesc(), operatorId);
                parameter.put(EventBodyParamEnum.ID.getDesc(), logIds);
                parameter.put(EventBodyParamEnum.START_DATE.getDesc(), dateRangeList.get(0));
                parameter.put(EventBodyParamEnum.END_DATE.getDesc(), dateRangeList.get(1));

                // 手动发送事件通知
                snsSender.publish(EventSubjectEnum.ATTENDANCE_AV_ACTUAL_HOURS.getSubject(),
                        JsonUtils.convertObjToString(objectMapper, new EventBodyDTO(key, parameter)));
            } catch (Exception e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle import Sva Actual Hour ADP report exception", e);
            }
        }

        /**
         * 解析报告
         *
         * @param propertyDTOList      资产集合
         * @param in                   报告文件
         * @param propertyId2DateRange 报告数据日期范围(yyyyMMdd)
         * @return SvaActualHoursBO 集合
         * @author zc
         * @date 2025/4/21
         */
        @Override
        public List<SvaActualHoursBO> parse(List<PropertyDTO> propertyDTOList, InputStream in,
                                            Map<Integer, List<Long>> propertyId2DateRange) throws ParseReportException {
            Map<String, PropertyDTO> code2PropertyDTO = attendancePropertyCodeInternalService.getCode2PropertyDTO(propertyDTOList);
            try (InputStreamReader inputStreamReader = new InputStreamReader(in)) {
                List<SvaActualHoursBO> actualHoursBOList = Lists.newArrayList();
                Iterable<CSVRecord> records = CSVFormat.EXCEL.parse(inputStreamReader);
                for (CSVRecord record : records) {
                    // 跳过第一行的标题
                    if (record.getRecordNumber() == 1) {
                        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;
                    }

                    // Pay Date 为空的不保存
                    String payDateStr = record.get(13);
                    if (StringUtils.isBlank(payDateStr)) {
                        continue;
                    }
                    // Time In 上班打卡时间为空的不保存
                    String timeInStr = record.get(9);
                    if (StringUtils.isBlank(timeInStr)) {
                        continue;
                    }
                    // Time Out 下班打卡时间为空的不保存
                    String timeOutStr = record.get(10);
                    if (StringUtils.isBlank(timeOutStr)) {
                        continue;
                    }
                    // 只提取指定日期范围的数据
                    LocalDate payDateLocalDate = DateTimeUtils.strToLocalDate(payDateStr, BaseConstant.DATE_FORMAT_MM_DD_YYYY_SLASH);
                    long targetDate = Long.parseLong(DateTimeUtils.localDateToStr(payDateLocalDate, BaseConstant.DATE_FORMAT_YYYYMMDD));
                    if (targetDate < dateRangeList.get(0) || targetDate > dateRangeList.get(1)) {
                        continue;
                    }

                    // Department Code 为空的不保存
                    String departmentCode = record.get(5);
                    if (StringUtils.isBlank(departmentCode)) {
                        continue;
                    }

                    actualHoursBOList.add(convert2HoursBo(propertyDTO, record));
                }
                return actualHoursBOList;
            } catch (IOException e) {
                throw new InternalServerErrorException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle parse Sva Actual Hour ADP report error.", e);
            }
        }

        /**
         * 将报告中的信息转换为实体类
         *
         * @param propertyDTO 资产
         * @param record      信息记录
         * @return SvaActualHoursBO 实例
         * @author zc
         * @date 2025/4/21
         */
        private SvaActualHoursBO convert2HoursBo(PropertyDTO propertyDTO, CSVRecord record) {
            // 获取国际化配置
            InternationalizationNumberDTO numberDTO = propertyDTO.getInternationalization().getNumber();
            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(numberDTO.getCalculationRule());

            SvaActualHoursBO actualHoursBO = new SvaActualHoursBO();
            actualHoursBO.setProperty(propertyDTO.getAbbr());
            // Position ID
            actualHoursBO.setPositionId(record.get(1));
            // Department Code
            actualHoursBO.setDepartmentCode(record.get(5));
            // Department Desc
            actualHoursBO.setDepartmentDesc(record.get(6));
            // Pay Code
            actualHoursBO.setPayCode(record.get(7));
            // Time In 上班打卡时间
            String timeInStr = record.get(9);
            LocalDateTime timeInLocalDateTime = DateTimeUtils.strToLocalDateTime(timeInStr, BaseConstant.DATE_FORMAT_MM_DD_YYYY_SLASH_HH_MM_A);
            actualHoursBO.setTimeInStr(DateTimeUtils.localDateTimeToStr(timeInLocalDateTime, BaseConstant.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MM));
            // Time Out 下班打卡时间
            String timeOutStr = record.get(10);
            LocalDateTime timeOutLocalDateTime = DateTimeUtils.strToLocalDateTime(timeOutStr, BaseConstant.DATE_FORMAT_MM_DD_YYYY_SLASH_HH_MM_A);
            actualHoursBO.setTimeOutStr(DateTimeUtils.localDateTimeToStr(timeOutLocalDateTime, BaseConstant.DATE_TIME_FORMAT_YYYY_MM_DD_HH_MM));
            // Pay Rate 时薪
            String payRateStr = record.get(11);
            BigDecimal payRate = StringUtils.isBlank(payRateStr) ?
                    null : new BigDecimal(payRateStr.split(" ")[1]).setScale(BaseConstant.DATA_PRECISION, roundingMode);
            actualHoursBO.setPayRate(payRate);
            // Hours
            String hoursStr = record.get(12);
            BigDecimal hours = StringUtils.isBlank(hoursStr) ?
                    BigDecimal.ZERO : new BigDecimal(hoursStr).setScale(BaseConstant.DATA_PRECISION, roundingMode);
            actualHoursBO.setHours(hours);
            // Payroll
            if (Objects.nonNull(payRate)) {
                actualHoursBO.setPayroll(payRate.multiply(hours).setScale(BaseConstant.DATA_PRECISION, roundingMode));
            }
            // Pay Date
            String payDateStr = record.get(13);
            LocalDate payDateLocalDate = DateTimeUtils.strToLocalDate(payDateStr, BaseConstant.DATE_FORMAT_MM_DD_YYYY_SLASH);
            actualHoursBO.setPayDateStr(DateTimeUtils.localDateToStr(payDateLocalDate, BaseConstant.DATE_FORMAT_YYYY_MM_DD));

            return actualHoursBO;
        }
    }