分布式XxlJob开发实战之员工、公司、部门接口表同步开发

 

一、 需求分析

       1. 根据客户要求,客户的hr系统会向我们公司的费控系统提供一个员工、公司、部门的接口的信息,然后我们根据信息来做插入信息和修改信息的操作。

       2. 不管是插入还是更新操作,对单笔记录都要进行记录操作,同时要给配置的人发送邮件提醒。

       3. 不管是新增或变更信息,最后的结果是成功还是失败,都要发送邮件。

       4. 每天5点的时候同步信息接口,自动执行。 

 

二、 表结构分析

       客户提供的接口信息如下:

        员工接口表:

数据库名 表名 表注释 字段名 字段注释  数据类型 是否允许为空 示例 测试数据 备注说明
fec_mdata sys_employee_interface 员工基本信息接口表 employee_code 工号 varchar(10) 01538 09998 HR系统的员工工号
full_name 姓名 varchar(50) 测试 ZK  
email 邮箱 varchar(100) [email protected] [email protected]  
direct_manager 直属领导工号 varchar(50) 06017 01538  
duty_code 职务code varchar(10) 01 01 普通员工=01、分公司总经理=02、董事长=03、
CEO=04、CFO=05
entry_date 入职日期 timestamp 2020/1/4 2020/1/4  
status 新增或变更 varchar(1) N N A-新增,U-更新、N-未插入
created_source 数据来源 varchar(50) MANUAL MANUAL HR,MANUAL
                   
fec_mdata sys_employee_position_interface 员工岗位信息接口表 employee_code 工号 varchar(10) 01538 09998 HR系统的员工工号
primary_flag 是否主岗位 varchar(1) Y Y Y 是,N 否
hr_company_name hr公司名称 varchar(100) 天津分公司 总部 该字段需要插入费控系统中的机构代码
hr_department_name hr部门名称 varchar(100) 银保-天津分公司 企业发展部-总公司 该字段需要插入费控系统中的部门代码

 

          公司接口表:  sys_company_interface

         

company_code 公司code varchar(100) NULL ZB JS009 该字段将被用于费控系统中的机构代码
company_name 公司名称 varchar(100) NULL 总部 江苏三级机构 该字段将被用于费控系统中的机构描述
company_level 公司级别 varchar(100) NULL First_level Third_level 总部=First_level、分公司=Second_level、
三级公司=Third_level、四级公司=Fourth_level
parent_company_code 上级公司代码 varchar(50) NULL null JS 该字段需插入费控系统中已有的机构代码
entry_date 生效日期 timestamp NULL 2020/1/4 2020/1/4  
created_source 数据来源 varchar(50) NULL MANUAL MANUAL HR,MANUAL

          部门接口表:  sys_department_interface

       

字段名 字段注释  数据类型 默认值 是否允许为空 示例 测试数据 备注说明
department_code 部门code varchar(100) NULL ZB020 JS020 该字段将被用于费控系统中的部门代码
department_name 部门名称 varchar(100) NULL Finance-总部 Finance-江苏三级机构 该字段将被用于费控系统中的部门描述
company_code 所属公司code varchar(100) NULL ZB JS009 该字段需插入费控系统中已有的机构代码
department_type 部门类型 varchar(50) NULL 01 01 后援=01;渠道=02;渠道(T4)=03
entry_date 生效日期 timestamp NULL 2020/1/4 2020/1/4  
created_source 数据来源 varchar(50) NULL MANUAL MANUAL HR,MANUAL

 

        hr公司名和费控公司映射表:  sys_company_inteface_mapping

    

DROP TABLE IF EXISTS `sys_company_interface_mapping`;
CREATE TABLE `sys_company_interface_mapping`  (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `company_code` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT '费控公司代码',
  `company_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT '费控公司名称',
  `hr_company_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT 'hr公司名称',
  `version_number` int(11) NOT NULL COMMENT '版本号',
  `created_date` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建日期',
  `created_by` bigint(20) NOT NULL COMMENT '创建用户ID',
  `last_updated_date` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '最后更新日期',
  `last_updated_by` bigint(20) NOT NULL COMMENT '最后更新用户ID',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1265563134299119668 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;

 

        hr部门名和费控部门映射表:  sys_department_interface_mapping

DROP TABLE IF EXISTS `sys_department_interface_mapping`;
CREATE TABLE `sys_department_interface_mapping`  (
  `id` bigint(20) NOT NULL AUTO_INCREMENT,
  `department_code` varchar(20) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT '费控部门的代码',
  `department_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT '费控部门的名称',
  `hr_department_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT 'hr部门的名称',
  `company_code` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT '费控公司代码',
  `company_name` varchar(50) CHARACTER SET utf8mb4 COLLATE utf8mb4_bin NULL DEFAULT NULL COMMENT '费控公司名称',
  `version_number` int(11) NOT NULL COMMENT '版本号',
  `created_date` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建日期',
  `created_by` bigint(20) NOT NULL COMMENT '创建用户ID',
  `last_updated_date` timestamp(0) NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '-',
  `last_updated_by` bigint(20) NOT NULL COMMENT '最后更新用户ID',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1265566237231874260 CHARACTER SET = utf8mb4 COLLATE = utf8mb4_bin ROW_FORMAT = Dynamic;

SET FOREIGN_KEY_CHECKS = 1;

 

 

三、代码实现

         1.  继承IJobHandler用于自定义的处理器:
         

package com.hand.hcf.app.mdata.job;

import com.hand.hcf.app.mdata.contact.service.EmployeeInterfaceService;
import com.sun.net.httpserver.Authenticator;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.IJobHandler;
import com.xxl.job.core.handler.annotation.JobHandler;
import com.xxl.job.core.log.XxlJobLogger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.xxl.job.core.biz.model.ReturnT.SUCCESS;

/**
 * EmployeeHandler
 *
 * @Auther: zhengbing.zhang
 * @Date:2020/5/11
 * @remark
 */
@JobHandler(value="EmployeeInterfaceHandler")
@Component
public class EmployeeHandler  extends IJobHandler {



    @Autowired
    EmployeeInterfaceService employeeInterfaceService;


    @Override
    public ReturnT<String> execute(String... strings) throws Exception {
        XxlJobLogger.log("开始获取员工信息...");
        ResultDTO resultDTO= employeeInterfaceService.insertOrUpdateEmploee();
        XxlJobLogger.log("获取员工信息结束!总共获取员工信息"+resultDTO.getTotalNum()+"条!"+"成功:"+resultDTO.getSuccessNum()+"条"+",失败:"+resultDTO.getFailNum()+"条");
        return SUCCESS;
    }
}

 

 

具体实现:

       1) 只查询出,员工表和岗位表status为"N"的记录进行处理。  sql如下:

SELECT e.*,o.primary_flag,o.hr_company_name,o.hr_department_name 
from sys_employee_interface e  
join sys_employee_position_interface o on  e.employee_code=o.employee_code  
where e.status="N" and o.status="N"
   

       2)期间需要进行一些校验,如果不满足校验,那么就失败,状态为N的时候将其更新为F。 如果成功了,那么将status更新为"Y"

       3) 使用LinkedHashMap来固定邮件信息的顺序。

    

     4) 邮件工具类:

       另外在邮件里使用表格的形式,需要指定一下xml的配置:

     

String  header="<![CDATA[<html><head></head><body><h2>费控系统员工信息新增或变更(失败)!您好,费控系统接收新员工信息数据失败,请系统管理员通知相关用户进行后续信息处理,新增或变更员工信息数据如下:</h2>";

             然后拼接上表格里的内容,就能实现在邮件里出来表格信息了,效果如上!  

package com.hand.hcf.app.mdata.contact.utils;

import com.hand.hcf.app.client.org.SysCodeValueCO;
import com.hand.hcf.app.mdata.client.com.CompanyCO;
import com.hand.hcf.app.mdata.contact.domain.Contact;
import com.hand.hcf.app.mdata.department.domain.Department;
import com.hand.hcf.app.mdata.externalApi.FecPeripheralInterface;
import com.xxl.job.core.log.XxlJobLogger;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Map;
import java.util.Set;

/**
 * EmailUtil
 *
 * @Auther: zhengbing.zhang
 * @Date:2020/5/15
 * @remark
 */


@Component
public class EmailUtil {

    @Autowired
    private FecPeripheralInterface fecPeripheralInterface;

    public  void sendEmail(String subject,String header ,Map<String,String> map, String emailTo,String fail) {

        /**
         * 获取邮件的收件人值列表
         */
        Set<String> lines = map.keySet();

        StringBuilder content = new StringBuilder();
        content.append(header);
        if (!StringUtils.isEmpty(fail)){
            content.append("<h2>失败原因:"+fail+"</h2>");
        }
        content.append("<table border=\"1\" style=\"border-collapse: collapse;border: 1px solid #ccc;\">");
        for(String key:lines){
            content.append("<tr>");
            content.append("<td>" + key + "</td>"); //第一列
            content.append("<td>" + map.get(key) + "</td>"); //第二列
            content.append("</tr>");
        }
        content.append("]]>");

        if (StringUtils.isEmpty(emailTo)){
            XxlJobLogger.log(content+"没有配置收件人!");
        }else{
            fecPeripheralInterface.sendEmailToEft(subject,content.toString(),emailTo);
            XxlJobLogger.log("邮件发送成功!");
        }
    }

    /**
     * 给财务复审人员发邮件
     */
    public void sendCheckMail(List<Contact> contacts,Department department, CompanyCO companyCO) {
        //包含Finance给发财务复审发邮件。
        String subject="部门Code包含Finance";
        String   content="部门代码为:"+department.getDepartmentCode()+"部门名称为;"+department.getName();
        String   emailTo="";
        //获取到该公司下的所有财务审核岗
        if (CollectionUtils.isNotEmpty(contacts)){
            for (Contact c:contacts){
                emailTo=c.getEmail()+",";
            }
            XxlJobLogger.log("给财务复审的员工发邮件");
            fecPeripheralInterface.sendEmailToEft(subject,content,emailTo);
            XxlJobLogger.log("邮件发送成功!");
        }else{
            XxlJobLogger.log(companyCO.getName()+"没有财务复核岗!");
        }
    }

}

             5) 鉴于每次都要给处理的每天信息发送邮件,那么可以使用共有的变量FailCheck和fail, 分别用来判断是否处理失败和拼接失败原因的。  每次for循环后,需要将共有的变量恢复至默认和将字符串清空,要不然下次循环会继续使用,会发生掩盖上次处理结果的情况。 

  

  //发邮件
                senEmail(failCheck, map, toEmails, fail.toString(), e);
                //清空失败原因
                fail.setLength(0);
                baseMapper.updateStatusById(e.getId(), e.getStatus());
                //更新岗位表的状态
                baseMapper.updatePositionStatusByEmoloyeeCode(e.getEmployeeCode(), e.getStatus());
                //恢复
                failCheck=false;

        6) 核心实现如下:  

package com.hand.hcf.app.mdata.contact.service;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.hand.hcf.app.client.org.OrganizationClient;
import com.hand.hcf.app.client.org.OrganizationInterface;
import com.hand.hcf.app.client.org.SysCodeValueCO;
import com.hand.hcf.app.client.user.UserCO;
import com.hand.hcf.app.client.user.UserClient;
import com.hand.hcf.app.mdata.base.util.OrgInformationUtil;
import com.hand.hcf.app.mdata.client.com.CompanyCO;
import com.hand.hcf.app.mdata.client.contact.ContactCO;
import com.hand.hcf.app.mdata.company.domain.Company;
import com.hand.hcf.app.mdata.company.service.CompanyService;
import com.hand.hcf.app.mdata.contact.domain.Contact;
import com.hand.hcf.app.mdata.contact.domain.EmployeeInterface;
import com.hand.hcf.app.mdata.contact.domain.EmployeePositionInterface;
import com.hand.hcf.app.mdata.contact.domain.UserRole;
import com.hand.hcf.app.mdata.contact.dto.EmployeeInfoDTO;
import com.hand.hcf.app.mdata.contact.persistence.ContactMapper;
import com.hand.hcf.app.mdata.contact.persistence.EmployeeInterfaceMapper;
import com.hand.hcf.app.mdata.contact.persistence.EmployeePositionInterfaceMapper;
import com.hand.hcf.app.mdata.contact.utils.EmailUtil;
import com.hand.hcf.app.mdata.contact.utils.StringBuilderUtil;
import com.hand.hcf.app.mdata.department.domain.Department;
import com.hand.hcf.app.mdata.department.domain.DepartmentUser;
import com.hand.hcf.app.mdata.department.service.DepartmentService;
import com.hand.hcf.app.mdata.department.service.DepartmentUserService;
import com.hand.hcf.app.mdata.doubleposition.domin.DoublePosition;
import com.hand.hcf.app.mdata.doubleposition.service.DoublePositionService;
import com.hand.hcf.app.mdata.externalApi.FecBaseInterface;
import com.hand.hcf.app.mdata.externalApi.FecPeripheralInterface;
import com.hand.hcf.app.mdata.externalApi.HcfOrganizationInterface;
import com.hand.hcf.app.mdata.job.ResultDTO;
import com.hand.hcf.core.service.BaseService;
import com.xxl.job.core.log.XxlJobLogger;
import jdk.nashorn.internal.parser.JSONParser;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * EmployeeInterfaceService
 *
 * @Auther: zhengbing.zhang
 * @Date:2020/5/11
 * @remark
 */
@Service
public class EmployeeInterfaceService extends BaseService<EmployeeInterfaceMapper, EmployeeInterface> {


    @Autowired
    private ContactService contactService;

    @Autowired
    private EmployeePositionInterfaceMapper employeePositionInterfaceMapper;

    @Autowired
    private CompanyService companyService;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private DepartmentUserService departmentUserService;

    @Autowired
    private DoublePositionService doublePositionService;

    @Autowired
    private FecBaseInterface baseInterface;

    @Autowired
    private OrganizationInterface organizationInterface;


    @Autowired
    private HcfOrganizationInterface hcfOrganizationInterface;

    @Autowired
    private EmailUtil emailUtil;

    @Autowired
    private StringBuilderUtil stringBuilderUtil;

    @Autowired
    UserClient userClient;


    @Transactional(rollbackFor = Exception.class,propagation= Propagation.REQUIRED)
    public ResultDTO insertOrUpdateEmploee() {

        List<EmployeeInfoDTO> allEmployee= baseMapper.selectAllInfo();

        List<Contact> contactList=new ArrayList<>();
        int successNum=0;
        int failNum=0;
        //使用LinkedMap来固定顺序

        StringBuilder fail=new StringBuilder();
        //再次转换为信息map
        Boolean failCheck=false;
        //更新
        List<Contact> updateContacts=new ArrayList<>();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        if (CollectionUtils.isNotEmpty(allEmployee)){
            List<SysCodeValueCO> toEmails=organizationInterface.listSysValueByCodeConditionByEnabled("sys_employee_interface_email",true);
            for (EmployeeInfoDTO e:allEmployee){
                String employeeCode = e.getEmployeeCode();
                Map<String, String> map = new LinkedHashMap<>();
                /**
                 * 将员工信息加入到map中,在邮件中打印出来
                 */
                ZonedDateTime dateTime = e.getEntryDate();
                String entryDate = dateTime.format(formatter);
                map.put("工号", e.getEmployeeCode());
                map.put("姓名", e.getFullName());
                map.put("邮箱", e.getEmail());
                map.put("直属领导工号", e.getDirectManager());
                map.put("职务code", e.getDutyCode());
                map.put("入职日期", entryDate);
                map.put("数据来源", e.getCreatedSource());
                map.put("是否在职", e.getOnJob());
                map.put("状态", e.getStatus());
                map.put("hr公司名称",e.getHrCompanyName());
                map.put("hr部门名称",e.getHrDepartmentName());

                  map.put("是否主岗位", e.getPrimaryFlag());


                //先查是否存在映射关系,如果有的话,就执行插入操作,如果没有发送邮件
                List<EmployeeInfoDTO> dtos=baseMapper.selectEmployeeInfo(e.getEmployeeCode());
                if (dtos.size()==0){
                    failCheck=true;
                    fail.append("该员工不存在映射关系!工号:"+e.getEmployeeCode());
                }else {
                    /**
                     * 验证是否有主岗位信息
                     */
                    EmployeeInfoDTO e1=dtos.get(0);
                    map.put("公司代码", e1.getCompanyCode());
                    map.put("公司名称", companyService.getByCompanyCode(e1.getCompanyCode()).getName());
                    map.put("部门代码", e1.getDepartmentCode());
                    map.put("部门名称", departmentService.getDepartment(e1.getDepartmentCode()).getName());
                    Integer count = employeePositionInterfaceMapper.selectCount(new EntityWrapper<EmployeePositionInterface>()
                            .eq("employee_code", employeeCode)
                            .eq("primary_flag", e.getPrimaryFlag()));
                    if (count < 1) {
                        XxlJobLogger.log(e.getEmployeeCode() + "没有主岗位信息!");
                        //给管理员发邮件
                        fail.append(e.getEmployeeCode() + "没有主岗位信息!");
                        //从值列表中查出待发
                        failCheck = true;
                    }

                    Contact contact = contactService.selectOne(new EntityWrapper<Contact>().eq("employee_id", employeeCode));
                    if (contact == null) {
                        //员工
                        String directManager = e.getDirectManager();
                        CompanyCO company = companyService.getByCompanyCode(e1.getCompanyCode());
                        Contact contact1 = new Contact();
                        BeanUtils.copyProperties(e1, contact1);
                        Long companyId = null;
                        if (company != null) {
                            companyId = company.getId();
                            contact1.setCompanyId(companyId);
                        } else {
                            fail.append("员工" + e.getEmployeeCode() + "公司不存在!公司代码为:" + e1.getCompanyCode());
                            failCheck = true;
                        }
                        Department department = departmentService.selectOne(new EntityWrapper<Department>()
                                .eq("department_code", e1.getDepartmentCode()));
                        Long departmentId = null;
                        if (department != null) {
                            departmentId = department.getId();
                            if (department.getName().toLowerCase().contains("finance")) {
                                List<Contact> contacts = baseMapper.selectAllCheckByRole(companyId);
                                emailUtil.sendCheckMail(contacts, department, company);
                            }
                        } else {
                            fail.append("部门不存在!部门代码为:" + e1.getDepartmentCode());
                            failCheck = true;
                        }

                        UserCO user = new UserCO();
                        //保存至User表,以保证新增的用户可以登录进来
                        user.setLogin(e.getEmployeeCode());
                        user.setLanguage(OrgInformationUtil.getCurrentLanguage());
                        user.setTenantId(0L);
                        user.setPhoneNumber(null);
                        user.setEmail(e.getEmail());
                        user.setUserName(e.getFullName());
                        user.setRemark(null);
                        user.setTenantId(0L);
                        user.setLanguage("zh_cn");
                        try {
                            user = hcfOrganizationInterface.saveUser(user);
                            //设置一个默认角色,普通员工
                            UserRole userRole = new UserRole();
                            userRole.setRoleId(1169167757858390018L);
                            userRole.setUserId(user.getId());
                            userRole.setValidDateFrom(ZonedDateTime.now());
                            userRole.setDataAuthorityId(1169177142518685698L);
                            baseInterface.createUserRole(userRole);
                        } catch (Exception error) {
                            fail.append("插入用户信息失败!" + error.getMessage());
                            failCheck = true;
                            //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
                        }

                        contact1.setUserOid(user.getUserOid());
                        contact1.setId(null);
                        contact1.setUserId(user.getId());
                        contact1.setEmployeeId(e.getEmployeeCode());
                        contact1.setTenantId(0L);
                        contact1.setStatus("Y".equals(e.getOnJob()) ? 1001 : 1003);
                        if ("N".equals(e.getOnJob())) {
                            contact1.setEmployeeId(contact1.getEmployeeId() + "_LEAVED");
                            userClient.updateUserLeaveOffice(user.getId());
                        }
                        contact1.setEntryDate(dateTime);
                        Contact directManagerContact = contactService.selectOne(new EntityWrapper<Contact>().eq("employee_id", directManager));
                        if (directManagerContact != null) {
                            contact1.setDirectManager(directManagerContact == null ? null : directManagerContact.getUserOid());
                        } else {
                            fail.append("员工上级领导不存在!上级领导的工号为:" + directManager);
                            failCheck = true;
                        }
                        //插入员工
                        if (failCheck != true) {
                            contactService.insert(contact1);
                        }
                        contactList.add(contact1);
                        XxlJobLogger.log(contact1.toString());
                        //员工岗位兼岗
                        if ("N".equals(e.getPrimaryFlag().toUpperCase())) {
                            DoublePosition doublePosition = new DoublePosition();
                            doublePosition.setUserId(user.getId().toString());
                            doublePosition.setCompanyId(companyId.toString());
                            doublePosition.setDepartmentId(departmentId.toString());
                            doublePositionService.insert(doublePosition);
                        }
                        //员工部门
                        DepartmentUser departmentUser = new DepartmentUser();
                        departmentUser.setDepartmentId(departmentId);
                        departmentUser.setUserId(user.getId());
                        if (failCheck != true) {
                            departmentUserService.insert(departmentUser);
                        }

                    } else {
                        //存在就更新
                        int versionNumber = contact.getVersionNumber();
                        Long id = contact.getId();
                        BeanUtils.copyProperties(e1, contact);
                        //设置直属领导的工号
                       Contact directManager= contactService.selectOne(new EntityWrapper<Contact>().eq("employee_id", e1.getDirectManager()));
                       if (directManager!=null){
                           contact.setDirectManager(directManager.getUserOid());
                       }else{
                           fail.append("员工上级领导不存在!上级领导的工号为:" + e1.getDirectManager());
                           failCheck = true;
                       }

                        contact.setId(id);
                        contact.setVersionNumber(versionNumber);
                        contact.setStatus("Y".equals(e1.getOnJob()) ? 1001 : 1003);
                        if ("N".equals(e1.getOnJob())) {
                            contact.setEmployeeId(contact.getEmployeeId() + "_LEAVED");
                            userClient.updateUserLeaveOffice(contact.getUserId());
                        }
                        Company contactCompany = companyService.selectOne(new EntityWrapper<Company>().eq("company_code", e1.getCompanyCode()));
                        if (contactCompany != null) {
                            contact.setCompanyId(contactCompany.getId());
                        } else {
                            XxlJobLogger.log("员工的公司信息更新失败:" + e.getCompanyCode() + "对应的公司不存在!");
                        }
                        contactService.updateById(contact);
                        //更新base表里的数据
                        UserCO user = new UserCO();
                        //保存至User表,以保证新增的用户可以登录进来
                        user.setLogin(e1.getEmployeeCode());
                        user.setLanguage(OrgInformationUtil.getCurrentLanguage());
                        user.setTenantId(0L);
                        user.setPhoneNumber(null);
                        user.setEmail(e1.getEmail());
                        user.setUserName(e1.getFullName());
                        user.setRemark(null);
                        user.setTenantId(0L);
                        user.setLanguage("zh_cn");
                        user.setId(contact.getUserId());
                        try {
                            user = hcfOrganizationInterface.saveUser(user);
                            //更新完成
                        } catch (Exception error) {

                        }
                        //更新用户部门表里的部门
                        DepartmentUser departmentUser = departmentUserService.selectOne(new EntityWrapper<DepartmentUser>().eq("user_id", contact.getUserId()));
                        if (departmentUser != null) {
                            Department department = departmentService.selectOne(new EntityWrapper<Department>().eq("department_code", e1.getDepartmentCode()));
                            if (department != null) {
                                departmentUser.setDepartmentId(department.getId());
                            }
                            departmentUserService.updateByUserId(departmentUser);
                        }
                        updateContacts.add(contact);
                        XxlJobLogger.log("提示:员工" + e1.getEmployeeCode() + "已经存在!数据将会发生更新");
                        if (failCheck!=true){
                            e.setStatus("U");
                        }
                    }
                }
                if (failCheck == true) {
                    failNum++;
                } else {
                    successNum++;
                }
                //发邮件
                senEmail(failCheck, map, toEmails, fail.toString(), e);
                //清空失败原因
                fail.setLength(0);
                baseMapper.updateStatusById(e.getId(), e.getStatus());
                //更新岗位表的状态
                baseMapper.updatePositionStatusByEmoloyeeCode(e.getEmployeeCode(), e.getStatus());
                //恢复
                failCheck=false;
            }

        }
        ResultDTO resultDTO=new ResultDTO();
        resultDTO.setFailNum(failNum);
        resultDTO.setSuccessNum(successNum);
        resultDTO.setTotalNum(failNum+successNum);
        return resultDTO ;
    }

    private void senEmail(Boolean failCheck, Map<String,String> info, List<SysCodeValueCO> maps,String fail,EmployeeInfoDTO e) {
        //发邮件

        StringBuilder emailTo=new StringBuilder();
        if (CollectionUtils.isNotEmpty(maps)){
            for (SysCodeValueCO co:maps){
                emailTo.append(co.getValue()+",");
            }
        }
        String header="";
        String subject="";
        if (!failCheck){
            //插入成功需要给系统管理员发邮件
            if ("N".equals(e.getStatus())){
                e.setStatus("Y");
            }
            subject="费控系统员工信息新增或变更(成功)";
            header="<![CDATA[<html><head></head><body><h2>费控系统员工信息新增或变更(成功)!您好,费控系统已接收新员工信息数据,请系统管理员通知相关用户进行后续信息新增,新增或变更员工信息数据如下:</h2>";
        }else{
            //插入失败
            subject="费控系统员工信息新增或变更(失败)";
            header="<![CDATA[<html><head></head><body><h2>费控系统员工信息新增或变更(失败)!您好,费控系统接收新员工信息数据失败,请系统管理员通知相关用户进行后续信息处理,新增或变更员工信息数据如下:</h2>";
            if ("N".equals(e.getStatus())){
                //同时回滚已经插入的数据记录,更新不回滚
                e.setStatus("F");
                deleteAllData(e.getEmployeeCode());
            }
        }
        emailUtil.sendEmail(subject,header,info,emailTo.toString(),fail);
    }

    private void deleteAllData(String employeeCode) {

        //根据用户id来删除base,contact,departmentUser表

       UserCO user= baseMapper.selectUserByCode(employeeCode);
       if (user!=null){
            Long userId=user.getId();
             baseMapper.deleleteUser(user.getLogin());
           //删除员工表数据
           Contact contact= contactService
                   .selectOne(new EntityWrapper<Contact>().eq("employee_id",employeeCode));
           if (contact!=null){
              contactService.delete(contact.getId());
           }
           //删除员工部门表
           DepartmentUser departmentUser=departmentUserService.selectOne(new EntityWrapper<DepartmentUser>().eq("user_id",userId));
           if (departmentUser == null) {
               departmentUserService.deleteById(departmentUser);
           }
           //删除双岗位表的数据
           DoublePosition doublePosition= doublePositionService.selectOne(new EntityWrapper<DoublePosition>().eq("user_id",userId));
           if (doublePosition!=null){
               doublePositionService.delete(doublePosition);
           }

       }

    }

}

 

 

四、配置Job

        根据客户要求,配置 每天5点,Cron表达式为:   0 0 5 * * ? *

 

   

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章