# SvaEmployeeParseServiceByAdp.java

    package cloud.wconnect.workperformance.service.sva.employees.employee;

    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.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.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.employees.EmployeesListBO;
    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.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.util.HashMap;
    import java.util.List;
    import java.util.Map;
    import java.util.Objects;

    /**
     * 服务实现类：ADP 员工报告处理
     *
     * @author zc
     * @date 2023/03/10
     */
    @Component
    @DS("work_performance")
    public class SvaEmployeeParseServiceByAdp implements ISvaEmployeeParseService {
        @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.employees}")
        private String s3FilePath;
        @Value("${file-max-size.import-report.sva}")
        private long fileMaxSize;

        /**
         * 判断是否支持
         *
         * @param source 数据源
         * @return boolean
         * @author zc
         * @date 2023/3/10
         */
        @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"));
        }

        /**
         * 处理数据
         *
         * @param propertyDTOList 资产集合
         * @param file            文件
         * @param logIds          日志 id 集合
         * @param operatorId      操作人 id
         * @author zc
         * @date 2024/8/16
         */
        @Override
        public void handleData(List<PropertyDTO> propertyDTOList, MultipartFile file, 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);

                // 封装事件体
                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_EMPLOYEES.getBusiness());
                parameter.put(EventBodyParamEnum.SOURCE.getDesc(), SystemPlatformEnum.ADP.getDesc());
                parameter.put(EventBodyParamEnum.ID.getDesc(), logIds);
                parameter.put(EventBodyParamEnum.UID.getDesc(), operatorId);

                // 发布事件通知
                snsSender.publish(EventSubjectEnum.ATTENDANCE_EMPLOYEE.getSubject(),
                        JsonUtils.convertObjToString(objectMapper, new EventBodyDTO(key, parameter)));
            } catch (Exception e) {
                throw new BadRequestException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle import Sva Employee ADP report send event exception", e);
            }
        }

        /**
         * 解析报告
         *
         * @param propertyDTOList 资产集合
         * @param in              文件流
         * @return EmployeesListBO 集合
         * @author zc
         * @date 2023/2/24
         */
        @Override
        public List<EmployeesListBO> parse(List<PropertyDTO> propertyDTOList, InputStream in) throws ParseReportException {
            Map<String, PropertyDTO> code2PropertyDTO = attendancePropertyCodeInternalService.getCode2PropertyDTO(propertyDTOList);
            try (InputStreamReader inputStreamReader = new InputStreamReader(in)) {
                List<EmployeesListBO> employeesListBOList = 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;
                    }

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

                    // 将 CSV 报告中的员工信息转换为实体类
                    EmployeesListBO employeesListBO = convert2AttendanceEmployee(propertyDTO, record);

                    employeesListBOList.add(employeesListBO);
                }
                return employeesListBOList;
            } catch (IOException e) {
                throw new BadRequestException(BaseErrorCodeEnum.SYSTEM_ERROR.getI18nCode(),
                        BaseErrorCodeEnum.SYSTEM_ERROR.getCode(),
                        "Handle parse Sva Employees ADP report error.", e);
            }
        }

        /**
         * 将 CSV 报告中的员工信息转换为实体类
         *
         * @param propertyDTO 资产
         * @param record      CSVRecord
         * @return EmployeesListBO
         * @author zc
         * @date 2023/2/24
         */
        private static EmployeesListBO convert2AttendanceEmployee(PropertyDTO propertyDTO, CSVRecord record) {
            RoundingMode roundingMode = InternationalizationUtils.getRoundingMode(propertyDTO
                    .getInternationalization().getNumber().getCalculationRule());

            EmployeesListBO employeesListBO = new EmployeesListBO();
            employeesListBO.setProperty(propertyDTO.getAbbr());

            // Position ID
            String positionId = record.get(1);
            employeesListBO.setPositionId(positionId);

            // Payroll Name
            String payrollName = record.get(2);
            employeesListBO.setEmpName(payrollName);

            // Department Code
            String departmentCode = record.get(3);
            employeesListBO.setDepartmentCode(departmentCode);

            // Department Desc.
            String departmentDesc = record.get(4);
            employeesListBO.setDepartmentDesc(departmentDesc);

            // Hire Date
            String hireDateStr = record.get(5);
            String hireDay = "";
            if (StringUtils.isNotBlank(hireDateStr)) {
                LocalDate localDate = DateTimeUtils.strToLocalDate(hireDateStr, BaseConstant.DATE_FORMAT_M_D_YYYY);
                hireDay = DateTimeUtils.localDateToStr(localDate, BaseConstant.DATE_FORMAT_YYYY_MM_DD);
            }
            employeesListBO.setHireDay(hireDay);

            // Rehire Date
            String reHireDateStr = record.get(6);
            String rehireDay = "";
            if (StringUtils.isNotBlank(reHireDateStr)) {
                LocalDate localDate = DateTimeUtils.strToLocalDate(hireDateStr, BaseConstant.DATE_FORMAT_M_D_YYYY);
                rehireDay = DateTimeUtils.localDateToStr(localDate, BaseConstant.DATE_FORMAT_YYYY_MM_DD);
            }
            employeesListBO.setRehireDay(rehireDay);

            // Pay Class
            String payClass = record.get(8);
            employeesListBO.setPayClass(payClass);

            // Worker Category Code
            String workerCategoryCode = record.get(9);
            employeesListBO.setWorkerCategoryCode(workerCategoryCode);

            // Hourly Rate
            String hourlyRate = record.get(10).trim();
            employeesListBO.setHourlyRate(StringUtils.isBlank(hourlyRate) ?
                    null : new BigDecimal(hourlyRate).setScale(BaseConstant.DATA_PRECISION, roundingMode));

            return employeesListBO;
        }
    }