Commit c9fe6bb7 by 张富康

feat(perfSalary): 新增企微打卡数据同步及基于清洗数据的考勤摘要优化

- 新增StaffQwClockClean实体及相关MyBatis映射和Mapper接口,支持企微打卡数据清洗存储
- 在AttendanceDataCleansingService中替换企微打卡数据来源为StaffQwClockClean,实现考勤摘要计算逻辑适配
- 添加ClockInCompleteAnalysisStaffService服务,调用企微接口同步打卡明细数据并持久化到StaffQwClockClean表
- 在PerfRuleRemote接口及实现类中新增clockInCompleteAnalysisStaff RPC方法,触发同步打卡数据功能
- 修正AttendanceSummary数据库映射中merchantAttendanceListId字段为merchantAttendanceListIds,支持多商户考勤记录
- 调整StaffQwClockInInfo实体表名至测试表,移除重复经纬度及打卡时间字段
- 新增依赖 rpc-scrm-wechat-api 用于调用企微接口获取打卡数据的功能
- 优化代码结构,使用Java 8 Stream和Optional提升数据处理安全性与可读性
1 parent 90588a35
package cn.com.glsx.dj.staff.dto.perfSalary;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import java.util.List;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class CheckInRecordDTO {
private String userId;
private String groupName;
private String checkinType;
private String exceptionType;
private long checkinTime;
private String locationTitle;
private String locationDetail;
private String wifiName;
private String notes;
private String wifiMac;
private List<String> mediaIds;
private Integer lat;
private Integer lng;
private String deviceId;
private Long schCheckInTime;
private Integer groupId;
private Integer scheduleId;
private Integer timelineId;
/**
* 打卡日期
*/
private String checkinDate;
}
\ No newline at end of file
package cn.com.glsx.dj.staff.model.perfSalary;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import javax.persistence.*;
import java.io.Serializable;
import java.util.Date;
/**
* 员工企微打卡信息
*/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
@Table(name = "dj_car_life_staff_qw_clock_clean")
public class StaffQwClockClean implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
/**
* 员工手机号
*/
@ApiModelProperty(notes = "员工手机号")
@Column(name = "staff_phone")
private String staffPhone;
/**
* 打卡日期
*/
@ApiModelProperty(notes = "打卡日期")
@Column(name = "clock_in_date")
private String clockInDate;
/**
* 上班打卡地址-经度
*/
@ApiModelProperty(notes = "上班打卡地址-经度")
@Column(name = "clock_in_addr_lng")
private String clockInAddrLng;
/**
* 上班打卡地址-纬度
*/
@ApiModelProperty(notes = "上班打卡地址-纬度")
@Column(name = "clock_in_addr_lat")
private String clockInAddrLat;
/**
* 上班打卡时间-有打卡照片的最早打卡时间 clock_in_time_start
*/
@ApiModelProperty(notes = "上班打卡时间-有打卡照片的最早打卡时间")
@Column(name = "clock_in_time_start")
private Date clockInTimeStart;
/**
* 上班打卡地址 clock_in_addr_info
*/
@ApiModelProperty(notes = "上班打卡地址")
@Column(name = "clock_in_addr_info")
private String clockInAddrInfo;
/**
* 下班打卡地址-经度
*/
@ApiModelProperty(notes = "下班打卡地址-经度")
@Column(name = "clock_out_addr_lng")
private String clockOutAddrLng;
/**
* 下班打卡地址-纬度
*/
@ApiModelProperty(notes = "下班打卡地址-纬度")
@Column(name = "clock_out_addr_lat")
private String clockOutAddrLat;
/**
* 下班打卡地址 clock_out_addr_info
*/
@ApiModelProperty(notes = "下班打卡地址")
@Column(name = "clock_out_addr_info")
private String clockOutAddrInfo;
/**
* 下班打卡时间-有打卡照片的最晚打卡时间 clock_out_time_end
*/
@ApiModelProperty(notes = "下班打卡时间-有打卡照片的最晚打卡时间")
@Column(name = "clock_out_time_end")
private Date clockOutTimeEnd;
/**
* 企微userId
*/
@ApiModelProperty(notes = "企微userId")
@Column(name = "user_id")
private String userId;
/**
* 创建人
*/
@ApiModelProperty(notes = "创建人")
@Column(name = "created_by")
private String createdBy;
/**
* 创建时间
*/
@ApiModelProperty(notes = "创建时间")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@Column(name = "created_date")
private Date createdDate;
/**
* 修改人
*/
@ApiModelProperty(notes = "修改人")
@Column(name = "updated_by")
private String updatedBy;
/**
*
*/
@ApiModelProperty(notes = "")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@Column(name = "updated_date")
private Date updatedDate;
/**
* 删除标识(D:已删除;N:未删除)
*/
@ApiModelProperty(notes = "删除标识(D:已删除;N:未删除)")
@Column(name = "deleted_flag")
private String deletedFlag;
}
......@@ -18,7 +18,8 @@ import java.util.Date;
@AllArgsConstructor
@NoArgsConstructor
@Accessors(chain = true)
@Table(name = "dj_car_life_staff_qw_clock_in_info")
// todz dj_car_life_staff_qw_clock_in_info_dev 修改
@Table(name = "dj_car_life_staff_qw_clock_in_info_dev")
public class StaffQwClockInInfo implements Serializable {
private static final long serialVersionUID = 1L;
......@@ -78,62 +79,6 @@ public class StaffQwClockInInfo implements Serializable {
private String clockOutPhotoUrl;
/**
* 上班打卡地址-经度
*/
@ApiModelProperty(notes = "上班打卡地址-经度")
@Column(name = "clock_in_addr_lng")
private String clockInAddrLng;
/**
* 上班打卡地址-纬度
*/
@ApiModelProperty(notes = "上班打卡地址-纬度")
@Column(name = "clock_in_addr_lat")
private String clockInAddrLat;
/**
* 上班打卡时间-有打卡照片的最早打卡时间 clock_in_time_start
*/
@ApiModelProperty(notes = "上班打卡时间-有打卡照片的最早打卡时间")
@Column(name = "clock_in_time_start")
private Date clockInTimeStart;
/**
* 上班打卡地址 clock_in_addr_info
*/
@ApiModelProperty(notes = "上班打卡地址")
@Column(name = "clock_in_addr_info")
private String clockInAddrInfo;
/**
* 下班打卡地址-经度
*/
@ApiModelProperty(notes = "下班打卡地址-经度")
@Column(name = "clock_out_addr_lng")
private String clockOutAddrLng;
/**
* 下班打卡地址-纬度
*/
@ApiModelProperty(notes = "下班打卡地址-纬度")
@Column(name = "clock_out_addr_lat")
private String clockOutAddrLat;
/**
* 下班打卡地址 clock_out_addr_info
*/
@ApiModelProperty(notes = "下班打卡地址")
@Column(name = "clock_out_addr_info")
private String clockOutAddrInfo;
/**
* 下班打卡时间-有打卡照片的最晚打卡时间 clock_out_time_end
*/
@ApiModelProperty(notes = "下班打卡时间-有打卡照片的最晚打卡时间")
@Column(name = "clock_out_time_end")
private Date clockOutTimeEnd;
/**
* 企微userId
*/
@ApiModelProperty(notes = "企微userId")
......
......@@ -58,4 +58,9 @@ public interface PerfRuleRemote {
* 考勤数据清洗
*/
RpcResponse<Boolean> attendanceDataCleansing();
/**
* 打卡数据
*/
RpcResponse<Boolean> clockInCompleteAnalysisStaff();
}
......@@ -50,6 +50,12 @@
</dependency>
<dependency>
<groupId>cn.com.glsx</groupId>
<artifactId>rpc-scrm-wechat-api</artifactId>
<version>4.54.0-SNAPSHOT</version>
</dependency>
<dependency>
<groupId>org.oreframework.boot</groupId>
<artifactId>ore-boot-starter-elasticjob</artifactId>
</dependency>
......
package cn.com.glsx.dj.staff.job;
import cn.com.glsx.dj.staff.service.perfSalary.ClockInCompleteAnalysisStaffService;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.extern.slf4j.Slf4j;
import org.oreframework.boot.autoconfigure.elasticjob.annotation.ElasticJobConf;
import org.springframework.beans.factory.annotation.Autowired;
@Slf4j
@ElasticJobConf(name = "SyncQwClockInDetailDataJob", cron = "0 0 4 1 * ? ", description = "定时打卡详情同步任务-每月1号4点执行", overwrite = false)
public class SyncQwClockInDetailDataJob implements SimpleJob {
@Autowired
private ClockInCompleteAnalysisStaffService clockInCompleteAnalysisStaffService;
@Override
public void execute(ShardingContext shardingContext) {
log.info("----------------定时打卡详情同步任务开始-----------------");
long l = System.currentTimeMillis();
try {
clockInCompleteAnalysisStaffService.syncQwClockInDetailData();
} catch (Exception e) {
log.error(e.getMessage(), e);
}
log.info("----------------定时打卡详情同步任务结束,耗时:{} ms-----------------", System.currentTimeMillis() - l);
}
}
package cn.com.glsx.dj.staff.mapper.perfSalary;
import cn.com.glsx.dj.staff.model.perfSalary.StaffQwClockClean;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.oreframework.datasource.mybatis.mapper.OreMapper;
import java.util.List;
@Mapper
public interface StaffQwClockCleanMapper extends OreMapper<StaffQwClockClean> {
void insertByDate(StaffQwClockClean staffQwClockClean);
void insertByDateBatch(@Param("list") List<StaffQwClockClean> list);
}
\ No newline at end of file
......@@ -2,9 +2,14 @@ package cn.com.glsx.dj.staff.mapper.perfSalary;
import cn.com.glsx.dj.staff.model.perfSalary.StaffQwClockInInfo;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.oreframework.datasource.mybatis.mapper.OreMapper;
import java.util.List;
@Mapper
public interface StaffQwClockInInfoMapper extends OreMapper<StaffQwClockInInfo> {
List<StaffQwClockInInfo> selectByDate(@Param("clockInDate") String clockInDate);
}
\ No newline at end of file
......@@ -2,6 +2,7 @@ package cn.com.glsx.dj.staff.remote.perfSalary;
import cn.com.glsx.dj.staff.dto.perfSalary.*;
import cn.com.glsx.dj.staff.service.perfSalary.AttendanceDataCleansingService;
import cn.com.glsx.dj.staff.service.perfSalary.ClockInCompleteAnalysisStaffService;
import cn.com.glsx.dj.staff.service.perfSalary.PerfRuleRemoteService;
import cn.com.glsx.framework.core.beans.rpc.RpcResponse;
import cn.com.glsx.framework.core.exception.RpcServiceException;
......@@ -19,6 +20,8 @@ public class PerfRuleRemoteImpl implements PerfRuleRemote {
private PerfRuleRemoteService perfRuleRemoteService;
@Resource
private AttendanceDataCleansingService attendanceDataCleansingService;
@Resource
private ClockInCompleteAnalysisStaffService clockInCompleteAnalysisStaffService;
......@@ -118,5 +121,14 @@ public class PerfRuleRemoteImpl implements PerfRuleRemote {
return RpcResponse.success(true);
}
/**
* 打卡数据
*/
@Override
public RpcResponse<Boolean> clockInCompleteAnalysisStaff() {
clockInCompleteAnalysisStaffService.syncQwClockInDetailData();
return RpcResponse.success(true);
}
}
......@@ -4,12 +4,10 @@ import cn.com.glsx.dj.staff.dto.perfSalary.ClockInResult;
import cn.com.glsx.dj.staff.mapper.StaffBeisenBaseInfoMapper;
import cn.com.glsx.dj.staff.mapper.perfSalary.AttendanceSummaryMapper;
import cn.com.glsx.dj.staff.mapper.perfSalary.MerchantAttendanceListMapper;
import cn.com.glsx.dj.staff.mapper.perfSalary.StaffQwClockCleanMapper;
import cn.com.glsx.dj.staff.mapper.perfSalary.StaffQwClockInInfoMapper;
import cn.com.glsx.dj.staff.model.StaffBeisenBaseInfo;
import cn.com.glsx.dj.staff.model.perfSalary.AttendanceFailureRecord;
import cn.com.glsx.dj.staff.model.perfSalary.AttendanceSummary;
import cn.com.glsx.dj.staff.model.perfSalary.MerchantAttendanceList;
import cn.com.glsx.dj.staff.model.perfSalary.StaffQwClockInInfo;
import cn.com.glsx.dj.staff.model.perfSalary.*;
import cn.com.glsx.dj.staff.util.DistanceTest;
import cn.com.glsx.dj.staff.util.JudgeResult;
import cn.com.glsx.dj.staff.util.TimeRangeChecker;
......@@ -57,6 +55,8 @@ public class AttendanceDataCleansingService {
@Resource
private StaffQwClockInInfoMapper staffQwClockInInfoMapper;
@Resource
private StaffQwClockCleanMapper staffQwClockCleanMapper;
@Resource
private MerchantAttendanceListMapper merchantAttendanceListMapper;
@Resource
private AttendanceSummaryMapper attendanceSummaryMapper;
......@@ -191,23 +191,23 @@ public class AttendanceDataCleansingService {
private void processEmployeeBatch(List<StaffBeisenBaseInfo> employeeList, DateTime lastMonthYMD) {
// 1. 根据手机号查询当月考勤数据
List<String> mobilePhones = employeeList.stream().map(StaffBeisenBaseInfo::getStaffPhone).collect(Collectors.toList());
Example staffQwClockInInfoExample = new Example(StaffQwClockInInfo.class);
Example staffQwClockInInfoExample = new Example(StaffQwClockClean.class);
String staffQwClockInInfoCondition = "(DATE_FORMAT(clock_in_date, '%Y-%m') = '{}')";
staffQwClockInInfoCondition = StrUtil.format(staffQwClockInInfoCondition, lastMonthYMD.toString("yyyy-MM"));
staffQwClockInInfoCondition = StrUtil.format(staffQwClockInInfoCondition, DateUtil.format(lastMonthYMD, DatePattern.NORM_MONTH_PATTERN));
staffQwClockInInfoExample.createCriteria().andIn("staffPhone", mobilePhones).andCondition(staffQwClockInInfoCondition).andEqualTo("deletedFlag", 'N');
List<StaffQwClockInInfo> staffQwClockInInfos = staffQwClockInInfoMapper.selectByExample(staffQwClockInInfoExample);
log.info("获取到 {} 条员工考勤数据", staffQwClockInInfos.size());
List<StaffQwClockClean> staffQwClockCleans = staffQwClockCleanMapper.selectByExample(staffQwClockInInfoExample);
log.info("获取到 {} 条员工考勤数据", staffQwClockCleans.size());
// 2. 将考勤数据按手机号分组
Map<String, List<StaffQwClockInInfo>> staffQwClockInInfoMap = staffQwClockInInfos.stream()
.collect(Collectors.groupingBy(StaffQwClockInInfo::getStaffPhone));
Map<String, List<StaffQwClockClean>> staffQwClockCleanMap = staffQwClockCleans.stream()
.collect(Collectors.groupingBy(StaffQwClockClean::getStaffPhone));
// 3. 处理每个员工的考勤数据
List<AttendanceSummary> attendanceSummariesInsert = new ArrayList<>();
for (StaffBeisenBaseInfo employee : employeeList) {
try {
// 4. 生成考勤摘要记录
AttendanceSummary attendanceSummary = createAttendanceSummary(employee, staffQwClockInInfoMap, lastMonthYMD);
AttendanceSummary attendanceSummary = createAttendanceSummary(employee, staffQwClockCleanMap, lastMonthYMD);
attendanceSummariesInsert.add(attendanceSummary);
} catch (Exception e) {
log.error("处理员工 {} ({}) 考勤数据失败", employee.getStaffName(), employee.getStaffPhone(), e);
......@@ -228,7 +228,7 @@ public class AttendanceDataCleansingService {
* 创建考勤记录
*/
private AttendanceSummary createAttendanceSummary(StaffBeisenBaseInfo employee,
Map<String, List<StaffQwClockInInfo>> staffQwClockInInfoMap,
Map<String, List<StaffQwClockClean>> staffQwClockCleanMap,
DateTime lastMonthYMD) {
AttendanceSummary attendanceSummary = new AttendanceSummary();
attendanceSummary.setMobilePhone(employee.getStaffPhone());
......@@ -242,8 +242,8 @@ public class AttendanceDataCleansingService {
attendanceSummary.setUpdatedDate(new Date());
attendanceSummary.setDeletedFlag("N");
List<StaffQwClockInInfo> staffQwClockInInfos = staffQwClockInInfoMap.get(employee.getStaffPhone());
if (CollUtil.isEmpty(staffQwClockInInfos)) {
List<StaffQwClockClean> staffQwClockCleans = staffQwClockCleanMap.get(employee.getStaffPhone());
if (CollUtil.isEmpty(staffQwClockCleans)) {
// 无考勤记录
attendanceSummary.setActualAttendanceDays(BigDecimal.ZERO);
attendanceSummary.setLateEarlyHours(BigDecimal.ZERO);
......@@ -254,7 +254,7 @@ public class AttendanceDataCleansingService {
}
// 计算考勤数据
calculateAttendanceData(attendanceSummary, staffQwClockInInfos, lastMonthYMD);
calculateAttendanceData(attendanceSummary, staffQwClockCleans, lastMonthYMD);
return attendanceSummary;
}
......@@ -262,7 +262,7 @@ public class AttendanceDataCleansingService {
* 计算考勤数据
*/
private void calculateAttendanceData(AttendanceSummary attendanceSummary,
List<StaffQwClockInInfo> staffQwClockInInfos,
List<StaffQwClockClean> staffQwClockCleans,
DateTime lastMonthYMD) {
BigDecimal totalWorkHours;
BigDecimal lateEarlyHours = BigDecimal.ZERO;
......@@ -273,7 +273,7 @@ public class AttendanceDataCleansingService {
List<Integer> merchantAttendanceListIds = new ArrayList<>();
// 1. 遍历每个考勤记录
for (StaffQwClockInInfo clockInfo : staffQwClockInInfos) {
for (StaffQwClockClean clockInfo : staffQwClockCleans) {
try {
// 2. 处理每条考勤记录
ClockInResult result = processClockIn(clockInfo, lastMonthYMD);
......@@ -309,7 +309,7 @@ public class AttendanceDataCleansingService {
* 处理单条打卡记录
* 使用策略模式处理不同类型的打卡场景
*/
private ClockInResult processClockIn(StaffQwClockInInfo clockInfo,
private ClockInResult processClockIn(StaffQwClockClean clockInfo,
DateTime lastMonthYMD) {
// 1. 策略模式:根据是否有经纬度选择处理策略
ClockInStrategy strategy = determineClockInStrategy(clockInfo);
......@@ -319,7 +319,7 @@ public class AttendanceDataCleansingService {
/**
* 确定打卡处理策略
*/
private ClockInStrategy determineClockInStrategy(StaffQwClockInInfo clockInfo) {
private ClockInStrategy determineClockInStrategy(StaffQwClockClean clockInfo) {
// 1. 上班打卡时间不为空 上班经纬度不为空 - 策略一
if (ObjectUtil.isNotEmpty(clockInfo.getClockInTimeStart())
&& StrUtil.isNotBlank(clockInfo.getClockInAddrLng())
......@@ -589,11 +589,11 @@ public class AttendanceDataCleansingService {
DateUtil.format(failure.getStatDate(), "yyyy-MM"));
staffQwClockInInfoExample.createCriteria().andEqualTo("staffPhone", employee.getStaffPhone())
.andCondition(staffQwClockInInfoCondition).andEqualTo("deletedFlag", 'N');
List<StaffQwClockInInfo> staffQwClockInInfos = staffQwClockInInfoMapper.selectByExample(staffQwClockInInfoExample);
List<StaffQwClockClean> staffQwClockCleans = staffQwClockCleanMapper.selectByExample(staffQwClockInInfoExample);
// 3. 生成考勤摘要
AttendanceSummary attendanceSummary = createAttendanceSummary(employee,
staffQwClockInInfos.stream().collect(Collectors.groupingBy(StaffQwClockInInfo::getStaffPhone)),
staffQwClockCleans.stream().collect(Collectors.groupingBy(StaffQwClockClean::getStaffPhone)),
new DateTime(failure.getStatDate().getTime()));
// 4. 保存数据
......@@ -690,7 +690,7 @@ public class AttendanceDataCleansingService {
* 打卡处理策略接口
*/
private interface ClockInStrategy {
ClockInResult process(StaffQwClockInInfo clockInfo, DateTime lastMonthYMD);
ClockInResult process(StaffQwClockClean clockInfo, DateTime lastMonthYMD);
}
/**
......@@ -698,7 +698,7 @@ public class AttendanceDataCleansingService {
*/
private class ClockInStrategyOne implements ClockInStrategy {
@Override
public ClockInResult process(StaffQwClockInInfo clockInfo, DateTime lastMonthYMD) {
public ClockInResult process(StaffQwClockClean clockInfo, DateTime lastMonthYMD) {
// 1. 获取最近的商户
MerchantAttendanceList merchant = findNearestMerchant(clockInfo.getClockInAddrLng(), clockInfo.getClockInAddrLat());
......@@ -711,7 +711,7 @@ public class AttendanceDataCleansingService {
return processWithMerchant(clockInfo, merchant);
}
private ClockInResult processWithMerchant(StaffQwClockInInfo clockInfo,
private ClockInResult processWithMerchant(StaffQwClockClean clockInfo,
MerchantAttendanceList merchant) {
BigDecimal totalWorkHours = BigDecimal.ZERO;
BigDecimal lateEarlyMinutes = BigDecimal.ZERO;
......@@ -817,7 +817,7 @@ public class AttendanceDataCleansingService {
*/
private class ClockInStrategyTwo implements ClockInStrategy {
@Override
public ClockInResult process(StaffQwClockInInfo clockInfo, DateTime lastMonthYMD) {
public ClockInResult process(StaffQwClockClean clockInfo, DateTime lastMonthYMD) {
// 1. 获取最近的商户
MerchantAttendanceList merchant = findNearestMerchant(clockInfo.getClockOutAddrLng(), clockInfo.getClockOutAddrLat());
......@@ -830,7 +830,7 @@ public class AttendanceDataCleansingService {
return processWithTwo(clockInfo, merchant);
}
private ClockInResult processWithTwo(StaffQwClockInInfo clockInfo, MerchantAttendanceList merchant) {
private ClockInResult processWithTwo(StaffQwClockClean clockInfo, MerchantAttendanceList merchant) {
BigDecimal totalWorkHours = BigDecimal.ZERO;
BigDecimal lateEarlyMinutes = BigDecimal.ZERO;
int normalClockCount = 0;
......@@ -858,7 +858,7 @@ public class AttendanceDataCleansingService {
*/
private class DefaultClockInStrategy implements ClockInStrategy {
@Override
public ClockInResult process(StaffQwClockInInfo clockInfo, DateTime lastMonthYMD) {
public ClockInResult process(StaffQwClockClean clockInfo, DateTime lastMonthYMD) {
BigDecimal totalWorkHours = BigDecimal.ZERO;
BigDecimal lateEarlyMinutes = BigDecimal.ZERO;
int normalClockCount = 0;
......
package cn.com.glsx.dj.staff.service.perfSalary;
import cn.com.glsx.dj.staff.dto.perfSalary.CheckInRecordDTO;
import cn.com.glsx.dj.staff.mapper.perfSalary.StaffQwClockCleanMapper;
import cn.com.glsx.dj.staff.mapper.perfSalary.StaffQwClockInInfoMapper;
import cn.com.glsx.dj.staff.model.perfSalary.StaffQwClockClean;
import cn.com.glsx.dj.staff.model.perfSalary.StaffQwClockInInfo;
import cn.com.glsx.dj.staff.util.HttpUtil;
import cn.com.glsx.scrm.wechat.dto.workwechat.checkin.request.GetWorkWechatUserCheckInDataRequestDTO;
import cn.com.glsx.scrm.wechat.dto.workwechat.checkin.response.WorkWechatUserCheckInDataResponseDTO;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.oreframework.boot.env.OrePropertyConfigurer;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.Executor;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
@Service
@Slf4j
public class ClockInCompleteAnalysisStaffService {
@Resource
private StaffQwClockInInfoMapper staffQwClockInInfoMapper;
@Resource
private Executor taskExecutor;
@Resource
private StaffQwClockCleanMapper staffQwClockCleanMapper;
public void syncQwClockInDetailData() {
Integer merchantId = OrePropertyConfigurer.getProperty("syncQwClockInData.build.merchantId", Integer.class, 44202977);
// 查询企微打卡表指定日期所有人员
DateTime lastMonthDate = DateUtil.offsetMonth(new Date(), -1);
String clockInDate = DateUtil.format(lastMonthDate, DatePattern.NORM_MONTH_PATTERN);
List<StaffQwClockInInfo> staffQwClockInInfos = staffQwClockInInfoMapper.selectByDate(clockInDate);
// 判断是否有数据
if (ObjectUtil.isEmpty(staffQwClockInInfos)) {
log.info("没有员工数据");
return;
}
// log.info("打卡数据员工:{}", JSONUtil.toJsonStr(staffQwClockInInfos));
// 调用企微接口
GetWorkWechatUserCheckInDataRequestDTO requestDTO = new GetWorkWechatUserCheckInDataRequestDTO();
requestDTO.setOpenCheckInDataType(1);
requestDTO.setMerchantId(merchantId);
// lastMonthDate 第一天00:00:00
requestDTO.setStartTime(DateUtil.beginOfMonth(lastMonthDate).getTime());
requestDTO.setEndTime(DateUtil.beginOfMonth(new Date()).getTime());
// 获取 userId staffPhone map 分组
Map<String, String> userIdStaffPhoneMap = staffQwClockInInfos.stream()
.filter(info -> info.getClockInDate() != null)
.sorted(Comparator.comparing(StaffQwClockInInfo::getClockInDate).reversed())
.collect(Collectors.toMap(
StaffQwClockInInfo::getUserId,
StaffQwClockInInfo::getStaffPhone,
(oldValue, newValue) -> oldValue // 保留首次出现的最新记录
));
// 清空 staffQwClockInInfos
staffQwClockInInfos.clear();
// 分批获取用户考勤数据并处理
Set<String> userIdSet = userIdStaffPhoneMap.keySet();
log.debug("开始同步企微打卡数据-Set:{}", userIdSet);
int totalUserCount = userIdSet.size();
int batchCount = (int) Math.ceil((double) totalUserCount / 100);
log.info("开始同步企微打卡数据:总用户数={},分{}个批次处理", totalUserCount, batchCount);
for (List<String> userIdList : partition(new ArrayList<>(userIdSet), 100)) {
handlerData(userIdList, requestDTO, userIdStaffPhoneMap);
}
}
private void handlerData(List<String> userIdList, GetWorkWechatUserCheckInDataRequestDTO requestDTO, Map<String, String> userIdStaffPhoneMap) {
requestDTO.setUserIdList(userIdList);
WorkWechatUserCheckInDataResponseDTO responseDTO = getUserCheckInData(requestDTO);
if (responseDTO == null || !Objects.equals(responseDTO.getErrCode(), 0)
|| CollectionUtils.isEmpty(responseDTO.getCheckindata())) {
return;
}
List<WorkWechatUserCheckInDataResponseDTO.CheckInRecord> checkInData = responseDTO.getCheckindata();
if (CollectionUtils.isEmpty(checkInData)) return;
List<CheckInRecordDTO> checkInRecordDTOS = new ArrayList<>();
for (WorkWechatUserCheckInDataResponseDTO.CheckInRecord checkInRecord : checkInData) {
if (CollUtil.isNotEmpty(checkInRecord.getMediaIds())) {
CheckInRecordDTO checkInRecordDTO = new CheckInRecordDTO();
checkInRecordDTO.setUserId(checkInRecord.getUserId());
checkInRecordDTO.setGroupName(checkInRecord.getGroupName());
checkInRecordDTO.setCheckinType(checkInRecord.getCheckinType());
checkInRecordDTO.setExceptionType(checkInRecord.getExceptionType());
checkInRecordDTO.setCheckinTime(checkInRecord.getCheckinTime());
checkInRecordDTO.setLocationTitle(checkInRecord.getLocationTitle());
checkInRecordDTO.setLocationDetail(checkInRecord.getLocationDetail());
checkInRecordDTO.setWifiName(checkInRecord.getWifiName());
checkInRecordDTO.setNotes(checkInRecord.getNotes());
checkInRecordDTO.setWifiMac(checkInRecord.getWifiMac());
checkInRecordDTO.setMediaIds(new ArrayList<>(checkInRecord.getMediaIds()));
checkInRecordDTO.setLat(checkInRecord.getLat());
checkInRecordDTO.setLng(checkInRecord.getLng());
checkInRecordDTO.setDeviceId(checkInRecord.getDeviceId());
checkInRecordDTO.setSchCheckInTime(checkInRecord.getSchCheckInTime());
checkInRecordDTO.setGroupId(checkInRecord.getGroupId());
checkInRecordDTO.setScheduleId(checkInRecord.getScheduleId());
checkInRecordDTO.setTimelineId(checkInRecord.getTimelineId());
checkInRecordDTO.setCheckinDate(DateUtil.format(new Date(checkInRecord.getCheckinTime() * 1000), DatePattern.NORM_DATE_PATTERN));
checkInRecordDTOS.add(checkInRecordDTO);
}
}
// 清空checkInData
checkInData.clear();
// 处理每个用户的该月每天的考勤数据
// checkInRecordDTOS按userId分组
Map<String, List<CheckInRecordDTO>> checkInRecordDTOSByUserId = checkInRecordDTOS.stream().collect(Collectors.groupingBy(CheckInRecordDTO::getUserId));
// 对每个用户处理每天的数据
for (Map.Entry<String, List<CheckInRecordDTO>> entry : checkInRecordDTOSByUserId.entrySet()) {
String userId = entry.getKey();
List<CheckInRecordDTO> checkInRecordDTOList = entry.getValue();
// 按天分组
List<StaffQwClockClean> staffQwClockCleanList = new ArrayList<>();
Map<String, List<CheckInRecordDTO>> checkInRecordDTOSByDay = checkInRecordDTOList.stream().collect(Collectors.groupingBy(CheckInRecordDTO::getCheckinDate));
// 处理每个用户的打卡数据
int processedUsers = 0;
for (Map.Entry<String, List<CheckInRecordDTO>> dayEntry : checkInRecordDTOSByDay.entrySet()) {
String clockInDateInsert = dayEntry.getKey();
List<CheckInRecordDTO> check = dayEntry.getValue();
StaffQwClockClean record = new StaffQwClockClean();
record.setStaffPhone(userIdStaffPhoneMap.get(userId));
// 检查是否有有效的打卡记录(地点不为空或打卡类型为上班/下班打卡)
// 如果所有记录的地点详情都为空,且打卡类型不是上班或下班,则跳过此用户
if (check.stream().noneMatch(s -> StringUtils.isEmpty(s.getLocationDetail())
|| Objects.equals("上班打卡", s.getCheckinType())
|| Objects.equals("下班打卡", s.getCheckinType()))) continue;
// 查找上班打卡记录(最早的一次,且有照片媒体文件)
// 条件:打卡类型为"上班打卡",异常类型不是"未打卡",且媒体ID列表不为空
Optional<CheckInRecordDTO> checkIn = check.stream()
.filter(s -> Objects.equals("上班打卡", s.getCheckinType())
&& !Objects.equals("未打卡", s.getExceptionType())
&& CollectionUtils.isNotEmpty(s.getMediaIds()))
.min(Comparator.comparingLong(CheckInRecordDTO::getCheckinTime));
// 如果当前记录中没有打卡照片或者打卡状态为0,且找到了上班打卡记录 保存经纬度信息
if (checkIn.isPresent()) {
Integer lng = checkIn.get().getLng();
Integer lat = checkIn.get().getLat();
record.setClockInAddrLng(ObjectUtil.isEmpty(lng) ? null : ((double) lng / 1000000) + "");
record.setClockInAddrLat(ObjectUtil.isEmpty(lat) ? null : ((double) lat / 1000000) + "");
record.setClockInAddrInfo(checkIn.get().getLocationDetail());
record.setClockInTimeStart(DateUtil.date(checkIn.get().getCheckinTime() * 1000));
}
// 查找下班打卡记录(最晚的一次,且有照片媒体文件)
// 条件:打卡类型为"下班打卡",异常类型不是"未打卡",且媒体ID列表不为空
Optional<CheckInRecordDTO> checkOut = check.stream()
.filter(s -> Objects.equals("下班打卡", s.getCheckinType())
&& !Objects.equals("未打卡", s.getExceptionType())
&& CollectionUtils.isNotEmpty(s.getMediaIds()))
.max(Comparator.comparingLong(CheckInRecordDTO::getCheckinTime));
// 如果当前记录中没有下班打卡照片,且找到了下班打卡记录 保存经纬度信息
if (checkOut.isPresent()) {
Integer lng = checkOut.get().getLng();
Integer lat = checkOut.get().getLat();
record.setClockOutAddrLng(ObjectUtil.isEmpty(lng) ? null : ((double) lng / 1000000) + "");
record.setClockOutAddrLat(ObjectUtil.isEmpty(lat) ? null : ((double) lat / 1000000) + "");
record.setClockOutAddrInfo(checkOut.get().getLocationDetail());
record.setClockOutTimeEnd(DateUtil.date(checkOut.get().getCheckinTime() * 1000));
}
record.setUserId(userId);
record.setClockInDate(clockInDateInsert);
log.debug("插入打卡数据:{}", record);
staffQwClockCleanList.add(record);
}
if (CollUtil.isNotEmpty(staffQwClockCleanList)) {
// 打印用户级进度
processedUsers++;
if (processedUsers == checkInRecordDTOSByUserId.size()) {
log.info("用户批次进度:已处理 {}/{} 个用户, 正在更新用户: {}",
processedUsers, checkInRecordDTOSByUserId.size(), userId);
}
// 线程异步更新
// taskExecutor.execute(() -> {
log.info("插入打卡数据-企微id:{}", userId);
staffQwClockCleanMapper.insertByDateBatch(staffQwClockCleanList);
// });
}
// 打印批次结束日志
log.info("用户批次处理完成:共处理 {} 个用户", processedUsers);
}
}
public static WorkWechatUserCheckInDataResponseDTO getUserCheckInData(GetWorkWechatUserCheckInDataRequestDTO requestDTO) {
WorkWechatUserCheckInDataResponseDTO responseDTO = null;
JSONObject jsonObject = new JSONObject();
jsonObject.put("merchantId", requestDTO.getMerchantId());
jsonObject.put("starttime", requestDTO.getStartTime() / 1000);
jsonObject.put("endtime", requestDTO.getEndTime() / 1000);
jsonObject.put("opencheckindatatype", requestDTO.getOpenCheckInDataType());
jsonObject.put("useridlist", requestDTO.getUserIdList().toArray());
// log.info("获取打卡记录数据 jsonObject:{}", requestDTO);
log.info("获取打卡记录数据 jsonObject:{}", jsonObject);
try {
String baseurl = OrePropertyConfigurer.getString("workwechat.clockin.getUserCheckInData.path",
"https://scrm.glsx.com.cn/wechat-build-server/wechat/getUserCheckInData");
// String baseurl = "https://scrm.beta.glsx.com.cn/wechat-build-server/wechat/getUserCheckInData";
responseDTO = HttpUtil.post(baseurl, jsonObject, WorkWechatUserCheckInDataResponseDTO.class);
log.info("获取打卡记录数据 ropResponse:{}", responseDTO);
log.info("获取打卡记录数据返回 errCode:{}, errMsg:{}", responseDTO.getErrCode(), responseDTO.getErrMsg());
} catch (Exception e) {
e.printStackTrace();
log.error("获取打卡记录数据异常 responseDTO:{}", responseDTO, e);
}
return responseDTO;
}
public static <T> List<List<T>> partition(List<T> list, int size) {
if (size <= 0) {
throw new IllegalArgumentException("Size must be greater than 0.");
}
return IntStream.range(0, (list.size() + size - 1) / size)
.mapToObj(i -> list.subList(i * size, Math.min(size * (i + 1), list.size()))).collect(Collectors.toList());
}
}
......@@ -25,7 +25,7 @@
)
VALUES (#{mobilePhone},
#{name},
#{merchantAttendanceListId},
#{merchantAttendanceListIds},
#{attendanceMonth},
#{expectedAttendanceDays},
#{actualAttendanceDays},
......@@ -40,7 +40,7 @@
#{updatedBy},
#{updatedDate},
#{deletedFlag}) ON DUPLICATE KEY UPDATE
merchant_attendance_list_id = VALUES(merchant_attendance_list_id),
merchant_attendance_list_ids = VALUES(merchant_attendance_list_ids),
expected_attendance_days = VALUES(expected_attendance_days),
actual_attendance_days = VALUES(actual_attendance_days),
appeal_attendance_days = VALUES(appeal_attendance_days),
......@@ -54,7 +54,7 @@
<!-- 批量插入(使用MyBatis foreach) -->
<insert id="insertOrUpdateBatch" parameterType="java.util.List">
INSERT INTO sal_attendance_summary (
mobile_phone, name, merchant_attendance_list_id, attendance_month,
mobile_phone, name, merchant_attendance_list_ids, attendance_month,
expected_attendance_days, actual_attendance_days, appeal_attendance_days,
total_work_hours, late_early_minutes, late_early_hours,
missing_punch_count, superior_leader_mobile_phone,
......@@ -63,7 +63,7 @@
VALUES
<foreach collection="list" item="item" separator=",">
(
#{item.mobilePhone}, #{item.name}, #{item.merchantAttendanceListId},
#{item.mobilePhone}, #{item.name}, #{item.merchantAttendanceListIds},
#{item.attendanceMonth}, #{item.expectedAttendanceDays},
#{item.actualAttendanceDays}, #{item.appealAttendanceDays},
#{item.totalWorkHours}, #{item.lateEarlyMinutes}, #{item.lateEarlyHours},
......@@ -73,7 +73,7 @@
)
</foreach>
ON DUPLICATE KEY UPDATE
merchant_attendance_list_id = VALUES(merchant_attendance_list_id),
merchant_attendance_list_ids = VALUES(merchant_attendance_list_ids),
expected_attendance_days = VALUES(expected_attendance_days),
actual_attendance_days = VALUES(actual_attendance_days),
appeal_attendance_days = VALUES(appeal_attendance_days),
......
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.glsx.dj.staff.mapper.perfSalary.StaffQwClockCleanMapper">
<insert id="insertByDate">
insert into dj_car_life_staff_qw_clock_clean (staff_phone,
clock_in_date,
clock_in_addr_lng,
clock_in_addr_lat,
clock_in_addr_info,
clock_in_time_start,
clock_out_addr_lng,
clock_out_addr_lat,
clock_out_addr_info,
clock_out_time_end,
user_id)
VALUES (#{staffPhone},
#{clockInDate},
#{clockInAddrLng},
#{clockInAddrLat},
#{clockInAddrInfo},
#{clockInTimeStart},
#{clockOutAddrLng},
#{clockOutAddrLat},
#{clockOutAddrInfo},
#{clockOutTimeEnd},
#{userId})
</insert>
<insert id="insertByDateBatch" parameterType="java.util.List">
insert into dj_car_life_staff_qw_clock_clean (staff_phone,
clock_in_date,
clock_in_addr_lng,
clock_in_addr_lat,
clock_in_addr_info,
clock_in_time_start,
clock_out_addr_lng,
clock_out_addr_lat,
clock_out_addr_info,
clock_out_time_end,
user_id)
VALUES
<foreach collection="list" item="item" separator=",">
(#{item.staffPhone},
#{item.clockInDate},
#{item.clockInAddrLng},
#{item.clockInAddrLat},
#{item.clockInAddrInfo},
#{item.clockInTimeStart},
#{item.clockOutAddrLng},
#{item.clockOutAddrLat},
#{item.clockOutAddrInfo},
#{item.clockOutTimeEnd},
#{item.userId})
</foreach>
ON DUPLICATE KEY UPDATE
clock_in_addr_lng = VALUES(clock_in_addr_lng),
clock_in_addr_lat = VALUES(clock_in_addr_lat),
clock_in_addr_info = VALUES(clock_in_addr_info),
clock_in_time_start = VALUES(clock_in_time_start),
clock_out_addr_lng = VALUES(clock_out_addr_lng),
clock_out_addr_lat = VALUES(clock_out_addr_lat),
clock_out_addr_info = VALUES(clock_out_addr_info),
clock_out_time_end = VALUES(clock_out_time_end),
user_id = VALUES(user_id)
</insert>
</mapper>
\ No newline at end of file
......@@ -4,5 +4,16 @@
<mapper namespace="cn.com.glsx.dj.staff.mapper.perfSalary.StaffQwClockInInfoMapper">
<!-- todz dj_car_life_staff_qw_clock_in_info_dev 修改-->
<select id="selectByDate" resultType="cn.com.glsx.dj.staff.model.perfSalary.StaffQwClockInInfo">
select user_id as userId,
staff_phone as staffPhone,
clock_in_date as clockInDate
from dj_car_life_staff_qw_clock_in_info_dev
where deleted_flag = 'N'
and (DATE_FORMAT(clock_in_date, '%Y-%m') = #{clockInDate})
order by user_id;
</select>
</mapper>
\ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!