Commit de63a639 by 谢海旭

区域运营小程序-事项:接口实现

1 parent f054dc8a
package cn.com.glsx.dj.staff.dto.taskcenter;
import com.fasterxml.jackson.annotation.JsonFormat;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
/**
* 任务信息 DTO(分页列表/详情通用)
*/
@Data
public class TaskInfoDTO implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(notes = "主键id")
private Long id;
@ApiModelProperty(notes = "外部任务中心关联id")
private Long taskCenterId;
@ApiModelProperty(notes = "任务类型,人员更换评估:staff-replace-access、商务政策更新评估:policy-update-access、多品类扩张:scene-expand、流量问题改善:traffic-optimize")
private String taskType;
@ApiModelProperty(notes = "任务类型名称")
private String taskTypeName;
@ApiModelProperty(notes = "状态:0-待完成,1-已完成")
private Integer status;
@ApiModelProperty(notes = "归属门店名称")
private String storeName;
@ApiModelProperty(notes = "归属门店id")
private String storeId;
@ApiModelProperty(notes = "归属业务:1.延保 2.轻改 3.权益")
private Integer businessType;
@ApiModelProperty(notes = "归属业务名称(多个用/隔开)")
private String businessTypeName;
@ApiModelProperty(notes = "创建人")
private String creator;
@ApiModelProperty(notes = "创建人手机号")
private String creatorPhone;
@ApiModelProperty(notes = "任务描述(完整)")
private String taskDescription;
@ApiModelProperty(notes = "专项任务回复")
private String replyContent;
@ApiModelProperty(notes = "回复时间")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date replyTime;
@ApiModelProperty(notes = "指派的区域运营id")
private String assignedToId;
@ApiModelProperty(notes = "指派的区域运营名称")
private String assignedToName;
@ApiModelProperty(notes = "创建时间")
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
private Date createdDate;
@ApiModelProperty(notes = "问题驻店人员列表")
private List<TaskStaffRelDTO> staffList;
}
package cn.com.glsx.dj.staff.dto.taskcenter;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
/**
* 任务分页查询条件 DTO
*/
@Data
public class TaskInfoQueryDTO implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(notes = "状态:0-待完成,1-已完成,null-全部")
private Integer status;
@ApiModelProperty(notes = "模糊搜索关键词(门店名称/业务名称/驻店销售/创建人/任务描述)")
private String keyword;
@ApiModelProperty(notes = "指派的区域运营id(当前登录人uuid,限制只能查看自己的任务)")
private String assignedToId;
}
package cn.com.glsx.dj.staff.dto.taskcenter;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
/**
* 专项任务回复提交 DTO
*/
@Data
public class TaskInfoSubmitDTO implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(notes = "任务主键id", required = true)
private Long id;
@ApiModelProperty(notes = "专项任务回复内容,1-800字符", required = true)
private String replyContent;
@ApiModelProperty(notes = "修改人")
private String updatedBy;
}
package cn.com.glsx.dj.staff.dto.taskcenter;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.io.Serializable;
/**
* 任务-问题驻店人员关联 DTO
*/
@Data
public class TaskStaffRelDTO implements Serializable {
private static final long serialVersionUID = 1L;
@ApiModelProperty(notes = "人员名称")
private String staffName;
@ApiModelProperty(notes = "人员手机号")
private String staffPhone;
@ApiModelProperty(notes = "人员uuid")
private String staffUuid;
@ApiModelProperty(notes = "岗位类型:0-驻店")
private Integer userPosition;
}
package cn.com.glsx.dj.staff.model;
import com.fasterxml.jackson.annotation.JsonFormat;
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_task_info")
public class TaskInfo implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
/** 外部任务中心关联id */
@Column(name = "task_center_id")
private Long taskCenterId;
/** 任务类型 */
@Column(name = "task_type")
private String taskType;
/** 任务类型名称 */
@Column(name = "task_type_name")
private String taskTypeName;
/** 状态:0-待完成,1-已完成 */
@Column(name = "status")
private Integer status;
/** 归属门店名称 */
@Column(name = "store_name")
private String storeName;
/** 归属门店id */
@Column(name = "store_id")
private String storeId;
/** 归属业务:1.延保 2.轻改 3.权益 */
@Column(name = "business_type")
private Integer businessType;
/** 归属业务名称 */
@Column(name = "business_type_name")
private String businessTypeName;
/** 创建人 */
@Column(name = "creator")
private String creator;
/** 创建人手机号 */
@Column(name = "creator_phone")
private String creatorPhone;
/** 任务描述(完整) */
@Column(name = "task_description")
private String taskDescription;
/** 专项任务回复 */
@Column(name = "reply_content")
private String replyContent;
/** 回复时间 */
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@Column(name = "reply_time")
private Date replyTime;
/** 指派的区域运营id */
@Column(name = "assigned_to_id")
private String assignedToId;
/** 指派的区域运营名称 */
@Column(name = "assigned_to_name")
private String assignedToName;
/** 创建人(系统字段) */
@Column(name = "created_by")
private String createdBy;
/** 创建时间 */
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@Column(name = "created_date")
private Date createdDate;
/** 修改人 */
@Column(name = "updated_by")
private String updatedBy;
/** 修改时间 */
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@Column(name = "updated_date")
private Date updatedDate;
/** 删除标识(D:已删除;N:未删除) */
@Column(name = "deleted_flag")
private String deletedFlag;
}
package cn.com.glsx.dj.staff.model;
import com.fasterxml.jackson.annotation.JsonFormat;
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_task_staff_rel")
public class TaskStaffRel implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
/** 任务id,关联dj_car_life_task_info.id */
@Column(name = "task_id")
private Long taskId;
/** 外部任务中心关联id(冗余字段) */
@Column(name = "task_center_id")
private Long taskCenterId;
/** 人员名称 */
@Column(name = "staff_name")
private String staffName;
/** 人员手机号 */
@Column(name = "staff_phone")
private String staffPhone;
/** 人员uuid */
@Column(name = "staff_uuid")
private String staffUuid;
/** 岗位类型:0-驻店 */
@Column(name = "user_position")
private Integer userPosition;
/** 创建人 */
@Column(name = "created_by")
private String createdBy;
/** 创建时间 */
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@Column(name = "created_date")
private Date createdDate;
/** 修改人 */
@Column(name = "updated_by")
private String updatedBy;
/** 修改时间 */
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8")
@Column(name = "updated_date")
private Date updatedDate;
/** 删除标识(D:已删除;N:未删除) */
@Column(name = "deleted_flag")
private String deletedFlag;
}
package cn.com.glsx.dj.staff.remote;
import cn.com.glsx.dj.staff.dto.taskcenter.TaskInfoDTO;
import cn.com.glsx.dj.staff.dto.taskcenter.TaskInfoQueryDTO;
import cn.com.glsx.dj.staff.dto.taskcenter.TaskInfoSubmitDTO;
import cn.com.glsx.framework.core.annotation.ApiMethod;
import cn.com.glsx.framework.core.annotation.ApiParam;
import cn.com.glsx.framework.core.annotation.ApiResponse;
import cn.com.glsx.framework.core.annotation.ApiService;
import cn.com.glsx.framework.core.beans.rpc.RpcPagination;
import cn.com.glsx.framework.core.beans.rpc.RpcResponse;
import javax.validation.constraints.NotNull;
@ApiService(value = "事项(专项任务)接口", owner = "staff", protocol = ApiService.ProtocolEnum.dubbo, version = "1.0.0")
public interface TaskInfoRemote {
@ApiMethod("分页查询事项列表")
@ApiParam(name = "pagination", notes = "分页查询条件", dataType = ApiParam.DataTypeEnum.OBJECT, required = true)
@ApiResponse("事项分页结果")
RpcResponse<RpcPagination<TaskInfoDTO>> pageTaskInfo(@NotNull RpcPagination<TaskInfoQueryDTO> pagination);
@ApiMethod("查询事项详情")
@ApiParam(name = "id", notes = "任务主键id", dataType = ApiParam.DataTypeEnum.LONG, required = true)
@ApiResponse("事项详情")
RpcResponse<TaskInfoDTO> getTaskInfoDetail(@NotNull Long id);
@ApiMethod("专项任务回复提交(去处理页面提交)")
@ApiParam(name = "dto", notes = "提交信息", dataType = ApiParam.DataTypeEnum.OBJECT, required = true)
@ApiResponse("提交结果")
RpcResponse<Boolean> submitTaskReply(@NotNull TaskInfoSubmitDTO dto);
}
...@@ -7,7 +7,7 @@ ...@@ -7,7 +7,7 @@
</parent> </parent>
<groupId>cn.com.glsx.dj</groupId> <groupId>cn.com.glsx.dj</groupId>
<artifactId>rpc-dj-staff</artifactId> <artifactId>rpc-dj-staff</artifactId>
<version>5.7.4-SNAPSHOT</version> <version>5.8.2-SNAPSHOT</version>
<name>rpc-dj-staff</name> <name>rpc-dj-staff</name>
<packaging>war</packaging> <packaging>war</packaging>
<dependencies> <dependencies>
...@@ -84,5 +84,10 @@ ...@@ -84,5 +84,10 @@
<artifactId>platform-merchants-api</artifactId> <artifactId>platform-merchants-api</artifactId>
<version>5.7.0-SNAPSHOT</version> <version>5.7.0-SNAPSHOT</version>
</dependency> </dependency>
<dependency>
<groupId>cn.com.glsx.dj</groupId>
<artifactId>rpc-dj-taskcenter-api</artifactId>
<version>1.0.0-SNAPSHOT</version>
</dependency>
</dependencies> </dependencies>
</project> </project>
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.dj.staff.job;
import cn.com.glsx.dj.staff.service.TaskInfoSyncService;
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;
/**
* 任务信息同步定时任务:每3秒从任务中心同步新增任务到本地
*/
@Slf4j
@ElasticJobConf(name = "TaskInfoSyncJob", cron = "0/3 * * * * ?", description = "从任务中心同步新增任务到本地", overwrite = false)
public class TaskInfoSyncJob implements SimpleJob {
@Autowired
private TaskInfoSyncService taskInfoSyncService;
@Override
public void execute(ShardingContext shardingContext) {
try {
taskInfoSyncService.syncTaskFromCenter();
} catch (Exception e) {
log.error("TaskInfoSyncJob__execute__error", e);
}
}
}
package cn.com.glsx.dj.staff.mapper;
import cn.com.glsx.dj.staff.dto.taskcenter.TaskInfoDTO;
import cn.com.glsx.dj.staff.dto.taskcenter.TaskInfoQueryDTO;
import cn.com.glsx.dj.staff.dto.taskcenter.TaskStaffRelDTO;
import cn.com.glsx.dj.staff.model.TaskInfo;
import cn.com.glsx.dj.staff.model.TaskStaffRel;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import java.util.Date;
import java.util.List;
@Mapper
public interface TaskInfoMapper {
/**
* 分页查询事项列表(支持状态和关键词过滤)
*/
List<TaskInfoDTO> pageTaskInfo(TaskInfoQueryDTO query);
/**
* 根据id查询事项详情
*/
TaskInfoDTO getTaskInfoById(@Param("id") Long id);
/**
* 根据任务id列表查询关联的人员
*/
List<TaskStaffRelDTO> listStaffByTaskId(@Param("taskId") Long taskId);
/**
* 提交回复(更新 reply_content、reply_time、status)
*/
int updateTaskReply(@Param("id") Long id,
@Param("replyContent") String replyContent,
@Param("updatedBy") String updatedBy);
/**
* 查询本地任务表最大创建时间
*/
Date getMaxCreatedDate();
/**
* 根据task_center_id判断本地是否已存在该任务
*/
int countByTaskCenterId(@Param("taskCenterId") Long taskCenterId);
/**
* 新增任务信息(同步用)
*/
int insertTaskInfo(TaskInfo taskInfo);
/**
* 批量新增任务关联人员(同步用)
*/
int batchInsertStaffRel(@Param("list") List<TaskStaffRel> list);
/**
* 根据task_center_id查询本地任务主键id
*/
Long getIdByTaskCenterId(@Param("taskCenterId") Long taskCenterId);
}
package cn.com.glsx.dj.staff.remote;
import cn.com.glsx.dj.staff.dto.taskcenter.TaskInfoDTO;
import cn.com.glsx.dj.staff.dto.taskcenter.TaskInfoQueryDTO;
import cn.com.glsx.dj.staff.dto.taskcenter.TaskInfoSubmitDTO;
import cn.com.glsx.dj.staff.service.TaskInfoService;
import cn.com.glsx.framework.core.beans.rpc.RpcPagination;
import cn.com.glsx.framework.core.beans.rpc.RpcResponse;
import cn.com.glsx.framework.core.exception.RpcServiceException;
import com.github.pagehelper.Page;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
@Slf4j
@DubboService(version = "1.0.0", validation = "true")
public class TaskInfoRemoteImpl implements TaskInfoRemote {
@Autowired
private TaskInfoService taskInfoService;
@Override
public RpcResponse<RpcPagination<TaskInfoDTO>> pageTaskInfo(RpcPagination<TaskInfoQueryDTO> pagination) {
try {
Page<TaskInfoDTO> page = taskInfoService.pageTaskInfo(pagination);
RpcPagination<TaskInfoDTO> result = RpcPagination.copyPage(page);
return RpcResponse.success(result);
} catch (RpcServiceException e) {
log.error("TaskInfoRemoteImpl__pageTaskInfo__bizException:{}", e.getMessage(), e);
return RpcResponse.error(e);
} catch (Exception e) {
log.error("TaskInfoRemoteImpl__pageTaskInfo__exception", e);
return RpcResponse.error(e);
}
}
@Override
public RpcResponse<TaskInfoDTO> getTaskInfoDetail(Long id) {
try {
TaskInfoDTO detail = taskInfoService.getTaskInfoDetail(id);
return RpcResponse.success(detail);
} catch (RpcServiceException e) {
log.error("TaskInfoRemoteImpl__getTaskInfoDetail__bizException:{}", e.getMessage(), e);
return RpcResponse.error(e);
} catch (Exception e) {
log.error("TaskInfoRemoteImpl__getTaskInfoDetail__exception", e);
return RpcResponse.error(e);
}
}
@Override
public RpcResponse<Boolean> submitTaskReply(TaskInfoSubmitDTO dto) {
try {
taskInfoService.submitTaskReply(dto);
return RpcResponse.success(true);
} catch (RpcServiceException e) {
log.error("TaskInfoRemoteImpl__submitTaskReply__bizException:{}", e.getMessage(), e);
return RpcResponse.error(e);
} catch (Exception e) {
log.error("TaskInfoRemoteImpl__submitTaskReply__exception", e);
return RpcResponse.error(e);
}
}
}
package cn.com.glsx.dj.staff.service;
import cn.com.glsx.dj.staff.dto.taskcenter.TaskInfoDTO;
import cn.com.glsx.dj.staff.dto.taskcenter.TaskInfoQueryDTO;
import cn.com.glsx.dj.staff.dto.taskcenter.TaskInfoSubmitDTO;
import cn.com.glsx.dj.staff.dto.taskcenter.TaskStaffRelDTO;
import cn.com.glsx.dj.staff.mapper.TaskInfoMapper;
import cn.com.glsx.dj.taskcenter.dto.taskcenter.TaskDTO;
import cn.com.glsx.dj.taskcenter.dto.taskcenter.request.FinishTaskAssigneeRequest;
import cn.com.glsx.dj.taskcenter.dto.taskcenter.request.GetTaskDetailRequest;
import cn.com.glsx.dj.taskcenter.remote.TaskCenterRemote;
import cn.com.glsx.framework.core.beans.rpc.RpcPagination;
import cn.com.glsx.framework.core.beans.rpc.RpcResponse;
import cn.com.glsx.framework.core.exception.RpcServiceException;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;
@Slf4j
@Service
public class TaskInfoService {
@Autowired
private TaskInfoMapper taskInfoMapper;
@DubboReference(version = "1.0.0", check = false)
private TaskCenterRemote taskCenterRemote;
/**
* 分页查询事项列表,列表中同时带出每条任务关联的人员
*/
public Page<TaskInfoDTO> pageTaskInfo(RpcPagination<TaskInfoQueryDTO> pagination) {
TaskInfoQueryDTO query = pagination.getCondition();
PageHelper.startPage(pagination.getPageNum(), pagination.getPageSize());
List<TaskInfoDTO> list = taskInfoMapper.pageTaskInfo(query);
// 填充人员列表
if (CollectionUtils.isNotEmpty(list)) {
for (TaskInfoDTO dto : list) {
dto.setStaffList(taskInfoMapper.listStaffByTaskId(dto.getId()));
}
}
return (Page<TaskInfoDTO>) list;
}
/**
* 查询事项详情(含人员列表)
*/
public TaskInfoDTO getTaskInfoDetail(Long id) {
TaskInfoDTO dto = taskInfoMapper.getTaskInfoById(id);
if (dto == null) {
throw new RpcServiceException("任务不存在或已删除");
}
List<TaskStaffRelDTO> staffList = taskInfoMapper.listStaffByTaskId(id);
dto.setStaffList(staffList);
return dto;
}
/**
* 专项任务回复提交:更新本地数据状态 + 回调任务中心同步
*/
@Transactional(rollbackFor = Exception.class)
public void submitTaskReply(TaskInfoSubmitDTO dto) {
if (dto.getId() == null) {
throw new RpcServiceException("任务id不能为空");
}
if (StringUtils.isBlank(dto.getReplyContent())) {
throw new RpcServiceException("专项任务回复不能为空");
}
if (dto.getReplyContent().length() > 800) {
throw new RpcServiceException("专项任务回复不能超过800字符");
}
// 1. 查询任务信息
TaskInfoDTO taskInfo = taskInfoMapper.getTaskInfoById(dto.getId());
if (taskInfo == null) {
throw new RpcServiceException("任务不存在或已删除");
}
// 2. 更新本地任务状态
int rows = taskInfoMapper.updateTaskReply(dto.getId(), dto.getReplyContent(), dto.getUpdatedBy());
if (rows == 0) {
throw new RpcServiceException("任务更新失败");
}
// 3. 回调任务中心-标记任务完成并同步业务上下文
Long taskCenterId = taskInfo.getTaskCenterId();
if (taskCenterId != null) {
// 3.1 查询任务中心任务详情,获取现有bizContext
GetTaskDetailRequest detailRequest = new GetTaskDetailRequest();
detailRequest.setTaskId(taskCenterId);
RpcResponse<TaskDTO> detailResp = taskCenterRemote.getTaskDetail(detailRequest);
String existingBizContext = null;
if (detailResp.isSuccess() && detailResp.getResult() != null) {
existingBizContext = detailResp.getResult().getBizContext();
}
// 3.2 组装回复内容信息,添加到任务中心任务上下文字段中
String updatedBizContext = buildUpdatedBizContext(existingBizContext, dto.getReplyContent());
// 3.3 调用finishTaskAssignee接口,标记任务完成
FinishTaskAssigneeRequest finishRequest = new FinishTaskAssigneeRequest();
finishRequest.setTaskId(taskCenterId);
finishRequest.setAssigneeId(taskInfo.getAssignedToId());
finishRequest.setUpdatedBy(dto.getUpdatedBy());
finishRequest.setBizContext(updatedBizContext);
RpcResponse<Boolean> finishResp = taskCenterRemote.finishTaskAssignee(finishRequest);
if (!finishResp.isSuccess()) {
log.error("submitTaskReply__finishTaskAssignee__fail:{}", JSONUtil.toJsonStr(finishResp));
throw new RpcServiceException("回调任务中心失败");
}
}
}
private JSONObject buildField(String fieldId, String fieldName, String fieldType, String fieldValue, String linkAlias) {
JSONObject field = new JSONObject();
field.set("fieldId", fieldId);
field.set("fieldName", fieldName);
field.set("fieldType", fieldType);
field.set("fieldValue", fieldValue == null ? "" : fieldValue);
field.set("linkAlias", linkAlias);
return field;
}
/**
* 构建更新后的业务上下文(bizContext)
* 在已有上下文基础上追加回复内容信息
* 格式:[{"fieldId":"xxx","fieldName":"xxx","fieldType":"text","fieldValue":"xxx","linkAlias":null}]
*/
private String buildUpdatedBizContext(String existingBizContext, String replyContent) {
JSONArray contextArray;
// 解析已有上下文,解析失败则新建
if (StringUtils.isNotBlank(existingBizContext)) {
try {
contextArray = JSONUtil.parseArray(existingBizContext);
} catch (Exception e) {
log.warn("submitTaskReply__parseBizContext__fail, build new", e);
contextArray = new JSONArray();
}
} else {
contextArray = new JSONArray();
}
// 将回复内容按标准字段格式追加到上下文中
contextArray.add(buildField("reply_content", "专项任务回复", "textarea", replyContent, null));
return contextArray.toString();
}
}
package cn.com.glsx.dj.staff.service;
import cn.com.glsx.dj.staff.mapper.TaskInfoMapper;
import cn.com.glsx.dj.staff.model.TaskInfo;
import cn.com.glsx.dj.staff.model.TaskStaffRel;
import cn.com.glsx.dj.taskcenter.dto.taskcenter.TaskAssigneeDTO;
import cn.com.glsx.dj.taskcenter.dto.taskcenter.TaskDTO;
import cn.com.glsx.dj.taskcenter.dto.taskcenter.TaskQueryConditionDTO;
import cn.com.glsx.dj.taskcenter.remote.TaskCenterRemote;
import cn.com.glsx.framework.core.beans.rpc.RpcPagination;
import cn.com.glsx.framework.core.beans.rpc.RpcResponse;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.*;
/**
* 任务信息同步服务:从任务中心同步新增任务到本地
*/
@Slf4j
@Service
public class TaskInfoSyncService {
/** 需要同步的业务类型列表 */
private static final List<String> SYNC_BIZ_TYPES = Arrays.asList(
"staff-replace-access",
"policy-update-access",
"scene-expand",
"traffic-optimize"
);
/** 每页查询大小 */
private static final int PAGE_SIZE = 50;
@Autowired
private TaskInfoMapper taskInfoMapper;
@DubboReference(version = "1.0.0", check = false)
private TaskCenterRemote taskCenterRemote;
/**
* 执行同步:从任务中心拉取新增任务写入本地
*/
public void syncTaskFromCenter() {
// 1. 查询本地最大创建时间作为增量起点
Date maxCreatedDate = taskInfoMapper.getMaxCreatedDate();
log.info("TaskInfoSync__start, localMaxCreatedDate={}", maxCreatedDate);
// 2. 构建分页查询条件
TaskQueryConditionDTO condition = new TaskQueryConditionDTO();
condition.setBizTypes(SYNC_BIZ_TYPES);
if (maxCreatedDate != null) {
condition.setCreatedDateStart(maxCreatedDate);
}
condition.setOrderBy("created_date asc");
RpcPagination<TaskQueryConditionDTO> pagination = new RpcPagination<>();
pagination.setCondition(condition);
pagination.setPageNum(1);
pagination.setPageSize(PAGE_SIZE);
pagination.setNeedCount(true);
// 3. 循环分页查询
int totalSynced = 0;
boolean hasMore = true;
while (hasMore) {
RpcResponse<RpcPagination<TaskDTO>> resp = taskCenterRemote.pageTask(pagination);
if (resp == null || !resp.isSuccess() || resp.getResult() == null) {
log.error("TaskInfoSync__pageTask__fail, pageNum={}, resp={}", pagination.getPageNum(), resp);
break;
}
RpcPagination<TaskDTO> pageResult = resp.getResult();
List<TaskDTO> taskList = pageResult.getList();
if (CollectionUtils.isEmpty(taskList)) {
break;
}
// 4. 逐条处理
for (TaskDTO task : taskList) {
try {
int synced = processSingleTask(task);
totalSynced += synced;
} catch (Exception e) {
log.error("TaskInfoSync__processSingleTask__error, taskId={}", task.getTaskId(), e);
}
}
// 5. 判断是否还有下一页
int pages = pageResult.getPages();
if (pagination.getPageNum() >= pages) {
hasMore = false;
} else {
pagination.setPageNum(pagination.getPageNum() + 1);
}
}
if (totalSynced > 0) {
log.info("TaskInfoSync__end, totalSynced={}", totalSynced);
}
}
/**
* 处理单条任务:判断是否已存在,不存在则插入
*
* @return 1-新增成功 0-已存在跳过
*/
@Transactional(rollbackFor = Exception.class)
public int processSingleTask(TaskDTO task) {
Long taskCenterId = task.getTaskId();
if (taskCenterId == null) {
return 0;
}
// 本地已存在则跳过
int count = taskInfoMapper.countByTaskCenterId(taskCenterId);
if (count > 0) {
return 0;
}
// 解析bizDisplayInfo中的业务字段
Map<String, String> fieldMap = parseBizDisplayInfo(task.getBizDisplayInfo());
// 获取执行人(区域运营)信息
String assignedToId = null;
String assignedToName = null;
if (CollectionUtils.isNotEmpty(task.getAssignees())) {
TaskAssigneeDTO assignee = task.getAssignees().get(0);
assignedToId = assignee.getAssigneeId();
assignedToName = assignee.getAssigneeName();
}
// 构建任务信息实体
TaskInfo taskInfo = new TaskInfo();
taskInfo.setTaskCenterId(taskCenterId);
taskInfo.setTaskType(task.getBizType());
taskInfo.setTaskTypeName(task.getBizTypeName());
taskInfo.setStatus(0);
taskInfo.setStoreName(fieldMap.getOrDefault("store_name", ""));
taskInfo.setStoreId(fieldMap.get("store_id"));
taskInfo.setBusinessType(parseIntOrNull(fieldMap.get("business_type")));
taskInfo.setBusinessTypeName(fieldMap.get("business_type_name"));
taskInfo.setCreator(task.getCreatedBy());
taskInfo.setCreatorPhone(fieldMap.get("creator_phone"));
taskInfo.setTaskDescription(task.getDescription());
taskInfo.setAssignedToId(assignedToId);
taskInfo.setAssignedToName(assignedToName);
taskInfo.setCreatedBy("system");
taskInfo.setCreatedDate(task.getCreatedDate());
taskInfo.setUpdatedBy("system");
taskInfoMapper.insertTaskInfo(taskInfo);
// 解析bizContext中的人员信息,写入关联表
List<TaskStaffRel> staffRelList = parseStaffFromBizContext(task.getBizContext());
if (CollectionUtils.isNotEmpty(staffRelList)) {
// 通过useGeneratedKeys获取到插入后的主键id
Long localTaskId = taskInfo.getId();
for (TaskStaffRel staffRel : staffRelList) {
staffRel.setTaskId(localTaskId);
staffRel.setTaskCenterId(taskCenterId);
staffRel.setCreatedBy("system");
staffRel.setUpdatedBy("system");
}
taskInfoMapper.batchInsertStaffRel(staffRelList);
}
log.info("TaskInfoSync__newTask, taskCenterId={}, bizType={}", taskCenterId, task.getBizType());
return 1;
}
/**
* 解析bizDisplayInfo中的字段,转为fieldId->fieldValue的Map
* 格式:[{"fieldId":"xxx","fieldName":"xxx","fieldType":"xxx","fieldValue":"xxx","linkAlias":null}]
*/
private Map<String, String> parseBizDisplayInfo(String bizDisplayInfo) {
Map<String, String> fieldMap = new HashMap<>();
if (StringUtils.isBlank(bizDisplayInfo)) {
return fieldMap;
}
try {
JSONArray array = JSONUtil.parseArray(bizDisplayInfo);
for (int i = 0; i < array.size(); i++) {
JSONObject obj = array.getJSONObject(i);
String fieldId = obj.getStr("fieldId");
String fieldValue = obj.getStr("fieldValue");
if (StringUtils.isNotBlank(fieldId)) {
fieldMap.put(fieldId, fieldValue);
}
}
} catch (Exception e) {
log.warn("TaskInfoSync__parseBizDisplayInfo__fail", e);
}
return fieldMap;
}
/**
* 从bizContext中解析人员列表
* 格式:[{"fieldId":"staff_list","fieldValue":"[{staffName,staffPhone,staffUuid,userPosition}]"}]
*/
private List<TaskStaffRel> parseStaffFromBizContext(String bizContext) {
List<TaskStaffRel> staffRelList = new ArrayList<>();
if (StringUtils.isBlank(bizContext)) {
return staffRelList;
}
try {
JSONArray contextArray = JSONUtil.parseArray(bizContext);
for (int i = 0; i < contextArray.size(); i++) {
JSONObject field = contextArray.getJSONObject(i);
String fieldId = field.getStr("fieldId");
if ("staff_list".equals(fieldId)) {
String staffJson = field.getStr("fieldValue");
if (StringUtils.isNotBlank(staffJson)) {
JSONArray staffArray = JSONUtil.parseArray(staffJson);
for (int j = 0; j < staffArray.size(); j++) {
JSONObject staffObj = staffArray.getJSONObject(j);
TaskStaffRel staffRel = new TaskStaffRel();
staffRel.setStaffName(staffObj.getStr("staffName"));
staffRel.setStaffPhone(staffObj.getStr("staffPhone"));
staffRel.setStaffUuid(staffObj.getStr("staffUuid"));
staffRel.setUserPosition(staffObj.getInt("userPosition"));
staffRelList.add(staffRel);
}
}
break;
}
}
} catch (Exception e) {
log.warn("TaskInfoSync__parseStaffFromBizContext__fail", e);
}
return staffRelList;
}
private Integer parseIntOrNull(String value) {
if (StringUtils.isBlank(value)) {
return null;
}
try {
return Integer.parseInt(value);
} catch (NumberFormatException e) {
return null;
}
}
}
<?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.TaskInfoMapper">
<resultMap id="TaskInfoDTOMap" type="cn.com.glsx.dj.staff.dto.taskcenter.TaskInfoDTO">
<id column="id" property="id" jdbcType="BIGINT"/>
<result column="task_center_id" property="taskCenterId" jdbcType="BIGINT"/>
<result column="task_type" property="taskType" jdbcType="VARCHAR"/>
<result column="task_type_name" property="taskTypeName" jdbcType="VARCHAR"/>
<result column="status" property="status" jdbcType="TINYINT"/>
<result column="store_name" property="storeName" jdbcType="VARCHAR"/>
<result column="store_id" property="storeId" jdbcType="VARCHAR"/>
<result column="business_type" property="businessType" jdbcType="TINYINT"/>
<result column="business_type_name" property="businessTypeName" jdbcType="VARCHAR"/>
<result column="creator" property="creator" jdbcType="VARCHAR"/>
<result column="creator_phone" property="creatorPhone" jdbcType="VARCHAR"/>
<result column="task_description" property="taskDescription" jdbcType="LONGVARCHAR"/>
<result column="reply_content" property="replyContent" jdbcType="LONGVARCHAR"/>
<result column="reply_time" property="replyTime" jdbcType="TIMESTAMP"/>
<result column="assigned_to_id" property="assignedToId" jdbcType="VARCHAR"/>
<result column="assigned_to_name" property="assignedToName" jdbcType="VARCHAR"/>
<result column="created_date" property="createdDate" jdbcType="TIMESTAMP"/>
</resultMap>
<resultMap id="TaskStaffRelDTOMap" type="cn.com.glsx.dj.staff.dto.taskcenter.TaskStaffRelDTO">
<result column="staff_name" property="staffName" jdbcType="VARCHAR"/>
<result column="staff_phone" property="staffPhone" jdbcType="VARCHAR"/>
<result column="staff_uuid" property="staffUuid" jdbcType="VARCHAR"/>
<result column="user_position" property="userPosition" jdbcType="INTEGER"/>
</resultMap>
<!-- 分页查询事项列表 -->
<select id="pageTaskInfo" parameterType="cn.com.glsx.dj.staff.dto.taskcenter.TaskInfoQueryDTO"
resultMap="TaskInfoDTOMap">
SELECT
t.id, t.task_center_id, t.task_type, t.task_type_name, t.status,
t.store_name, t.store_id, t.business_type, t.business_type_name,
t.creator, t.creator_phone, t.task_description, t.reply_content,
t.reply_time, t.assigned_to_id, t.assigned_to_name, t.created_date
FROM dj_car_life_task_info t
<where>
t.deleted_flag = 'N'
<if test="assignedToId != null and assignedToId != ''">
AND t.assigned_to_id = #{assignedToId}
</if>
<if test="status != null">
AND t.status = #{status}
</if>
<if test="keyword != null and keyword != ''">
AND (
t.store_name LIKE CONCAT('%', #{keyword}, '%')
OR t.business_type_name LIKE CONCAT('%', #{keyword}, '%')
OR t.creator LIKE CONCAT('%', #{keyword}, '%')
OR t.task_description LIKE CONCAT('%', #{keyword}, '%')
OR EXISTS (
SELECT 1 FROM dj_car_life_task_staff_rel s
WHERE s.task_id = t.id AND s.deleted_flag = 'N'
AND s.staff_name LIKE CONCAT('%', #{keyword}, '%')
)
)
</if>
</where>
ORDER BY t.created_date DESC
</select>
<!-- 根据id查询事项详情 -->
<select id="getTaskInfoById" resultMap="TaskInfoDTOMap">
SELECT
t.id, t.task_center_id, t.task_type, t.task_type_name, t.status,
t.store_name, t.store_id, t.business_type, t.business_type_name,
t.creator, t.creator_phone, t.task_description, t.reply_content,
t.reply_time, t.assigned_to_id, t.assigned_to_name, t.created_date
FROM dj_car_life_task_info t
WHERE t.id = #{id} AND t.deleted_flag = 'N'
</select>
<!-- 根据任务id查询关联人员 -->
<select id="listStaffByTaskId" resultMap="TaskStaffRelDTOMap">
SELECT staff_name, staff_phone, staff_uuid, user_position
FROM dj_car_life_task_staff_rel
WHERE task_id = #{taskId} AND deleted_flag = 'N'
</select>
<!-- 提交回复:更新reply_content、reply_time、status -->
<update id="updateTaskReply">
UPDATE dj_car_life_task_info
SET reply_content = #{replyContent},
reply_time = NOW(),
status = 1,
updated_by = #{updatedBy},
updated_date = NOW()
WHERE id = #{id} AND deleted_flag = 'N'
</update>
<!-- 查询本地任务表最大创建时间 -->
<select id="getMaxCreatedDate" resultType="java.util.Date">
SELECT MAX(created_date) FROM dj_car_life_task_info WHERE deleted_flag = 'N'
</select>
<!-- 根据task_center_id判断本地是否已存在该任务 -->
<select id="countByTaskCenterId" resultType="int">
SELECT COUNT(1) FROM dj_car_life_task_info
WHERE task_center_id = #{taskCenterId} AND deleted_flag = 'N'
</select>
<!-- 新增任务信息(同步用) -->
<insert id="insertTaskInfo" parameterType="cn.com.glsx.dj.staff.model.TaskInfo" useGeneratedKeys="true" keyProperty="id">
INSERT INTO dj_car_life_task_info
(task_center_id, task_type, task_type_name, status, store_name, store_id,
business_type, business_type_name, creator, creator_phone,
task_description, assigned_to_id, assigned_to_name,
created_by, created_date, updated_by, updated_date, deleted_flag)
VALUES
(#{taskCenterId}, #{taskType}, #{taskTypeName}, #{status}, #{storeName}, #{storeId},
#{businessType}, #{businessTypeName}, #{creator}, #{creatorPhone},
#{taskDescription}, #{assignedToId}, #{assignedToName},
#{createdBy}, #{createdDate}, #{updatedBy}, NOW(), 'N')
</insert>
<!-- 批量新增任务关联人员(同步用) -->
<insert id="batchInsertStaffRel">
INSERT INTO dj_car_life_task_staff_rel
(task_id, task_center_id, staff_name, staff_phone, staff_uuid, user_position,
created_by, created_date, updated_by, updated_date, deleted_flag)
VALUES
<foreach collection="list" item="item" separator=",">
(#{item.taskId}, #{item.taskCenterId}, #{item.staffName}, #{item.staffPhone},
#{item.staffUuid}, #{item.userPosition},
#{item.createdBy}, NOW(), #{item.updatedBy}, NOW(), 'N')
</foreach>
</insert>
<!-- 根据task_center_id查询本地任务主键id -->
<select id="getIdByTaskCenterId" resultType="java.lang.Long">
SELECT id FROM dj_car_life_task_info
WHERE task_center_id = #{taskCenterId} AND deleted_flag = 'N'
LIMIT 1
</select>
</mapper>
  • @wangxw1
    commented
    Master

    这是一份针对您提交代码的专业代码审查报告。审查过程严格遵守了您设定的目标权重与核心规则。

    一、关键问题与优化建议(Top 3)

    1. 违反核心规则:MyBatis SQL 中使用了子查询(功能正确性与规范)

    • 问题描述:在 TaskInfoMapper.xml 的 pageTaskInfo 方法中,针对 keyword 的模糊查询使用了 EXISTS 子查询(SELECT 1 FROM dj_car_life_task_staff_rel s WHERE ...)。这直接违反了“mybatis的sql语句不允许使用子查询”的强制规则。
    • 影响分析:违反团队底层工程架构规范。此外,在数据量较大的情况下,EXISTS 子查询可能会导致索引失效或产生严重的性能瓶颈(特别是与外层的 OR 条件混用时)。
    • 优化建议:由于涉及分页(PageHelper),直接使用 LEFT JOIN 可能会导致分页总数计算错误(一对多产生笛卡尔积)。建议在 Java 代码层面进行拆分:若存在 keyword,先从人员关联表查出匹配的 taskId 集合,再将其作为条件传入主查询(使用 IN 配合 Java List)。 xml <!-- 修改后的 XML 片段 --> <if test="keyword != null and keyword != ''"> AND ( t.store_name LIKE CONCAT('%', #{keyword}, '%') OR t.business_type_name LIKE CONCAT('%', #{keyword}, '%') OR t.creator LIKE CONCAT('%', #{keyword}, '%') OR t.task_description LIKE CONCAT('%', #{keyword}, '%') <if test="matchedTaskIds != null and matchedTaskIds.size() > 0"> OR t.id IN <foreach collection="matchedTaskIds" item="id" open="(" separator="," close=")"> #{id} </foreach> </if> ) </if>

    2. 严重的 N+1 查询性能问题(性能与资源利用)

    • 问题描述:在 TaskInfoService.pageTaskInfo 方法中,遍历分页查询的结果列表,并在 for 循环中逐条调用 taskInfoMapper.listStaffByTaskId(dto.getId()) 查询关联人员。
    • 影响分析:典型的 N+1 查询问题。如果一页有 50 条数据,该接口将执行 1 次主查询 + 50 次子查询。这会极大地消耗数据库连接资源,增加网络 IO 延迟,在高并发下会导致系统吞吐量断崖式下降。
    • 优化建议:提取所有任务的 ID,使用 IN 语句一次性查出所有关联人员,然后在内存中进行数据组装。

      // 优化代码示例
      List<TaskInfoDTO> list = taskInfoMapper.pageTaskInfo(query);
      if (CollectionUtils.isNotEmpty(list)) {
        List<Long> taskIds = list.stream().map(TaskInfoDTO::getId).collect(Collectors.toList());
        // 新增一个 mapper 方法:根据多个 taskId 查询关联人员
        List<TaskStaffRelDTO> allStaffList = taskInfoMapper.listStaffByTaskIds(taskIds);
        // 按 taskId 分组
        Map<Long, List<TaskStaffRelDTO>> staffMap = allStaffList.stream()
                .collect(Collectors.groupingBy(TaskStaffRelDTO::getTaskId)); // 需在DTO冗余taskId字段
      
        for (TaskInfoDTO dto : list) {
            dto.setStaffList(staffMap.getOrDefault(dto.getId(), new ArrayList<>()));
        }
      }
      

    3. 定时任务轮询频率过高,存在资源浪费(最佳实践与性能)

    • 问题描述:TaskInfoSyncJob 的 Cron 表达式配置为 0/3 * * * * ?(每 3 秒执行一次)。
    • 影响分析:每 3 秒发起一次 RPC 调用并查询本地数据库,极其消耗网络带宽、RPC 线程池以及数据库连接资源。如果任务中心接口响应稍慢,极易导致定时任务线程堆积。
    • 优化建议:
      1. 如果业务允许一定的延迟,建议将同步频率降低至 1~5 分钟(如 0 0/1 * * * ?)。
      2. 如果业务要求强实时性,应废弃定时拉取(Pull)模式,改为基于消息队列(MQ)的事件驱动推送(Push)模式。

    二、评分明细

    1. 功能实现的正确性与健壮性(32 / 40分)
      • 理由:基础业务逻辑完整,Dubbo 接口新增符合规范,未修改历史请求参数。但 XML 中违规使用了子查询,且 submitTaskReply 中本地事务与外部 RPC 强耦合,若 RPC 成功但超时,本地事务回滚会导致分布式数据不一致(建议后续引入重试或状态对账机制),扣除 8 分。
    2. 安全性与潜在风险(28 / 30分)
      • 理由:SQL 参数均使用 #{} 预编译,无明显 SQL 注入风险。权限方面,TaskInfoQueryDTO 中通过 assignedToId 限制只能查看自己的任务,有基本的越权防范。扣 2 分在于 submitTaskReply 缺少对 replyContent 的 JSR-303 注解校验(仅在 Service 层做了硬编码判断)。
    3. 最佳实践与可维护性(15 / 20分)
      • 理由:代码结构清晰,分层合理,使用了 DTO 进行数据传输,且有完善的 Swagger 注解。但代码中存在明显的 N+1 坏味道,且 JSON 解析强依赖 try-catch 掩盖潜在的解析异常,扣除 5 分。
    4. 性能与资源利用(2 / 5分)
      • 理由:N+1 查询缺陷以及每 3 秒一次的高频 RPC 轮询定时任务,是比较严重的性能隐患,扣除 3 分。
    5. 提交信息质量(4 / 5分)
      • 理由:“区域运营小程序-事项:接口实现” 描述了业务背景,但略显简略,未体现本次提交包含了定时同步 Job、Dubbo Provider 等核心技术实现,扣除 1 分。

    总分:81分

Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!