Commit d1fc07d0 by zhouhaibao

refactor(strategy): 重构策略执行服务并优化任务快照功能

- 修改executeStrategy方法参数结构,改为传入SopStrategyTask对象
- 新增updateTaskSnapshot方法用于更新任务执行时的分支信息
- 重构buildSnapshotJson方法为buildTaskSnapshot,支持构建完整的任务快照
- 添加updateExecutionBranchInfo方法,支持在执行时更新分支匹配信息
- 优化任务执行流程,返回匹配的分支信息而非void
- 更新数据库表结构,添加执行描述、动作结果和快照信息字段
- 调整执行状态枚举值定义,修改状态码含义
- 修改策略记录查询接口,从任务表直接查询执行记录
- 移除原有的执行记录表相关代码,统一使用任务表存储执行信息
- 修复业务类型映射错误,将轻改类型对应到正确数值
- 修正日期和数值类型的字段映射关系
1 parent 2da489e7
package cn.com.glsx.dj.strategy.dto.sop;
import io.swagger.annotations.ApiModelProperty;
import javax.persistence.Column;
import lombok.Data;
import java.util.Date;
......@@ -52,4 +53,10 @@ public class SopStrategyRecordDTO {
@ApiModelProperty(notes = "执行结果描述:成功/失败")
private String executeResultDesc;
/**
* 策略执行快照JSON(任务创建时保存,执行时更新分支信息)
*/
@ApiModelProperty(notes = "策略执行快照JSON(任务创建时保存,执行时更新分支信息)")
private String snapshotInfo;
}
\ No newline at end of file
......@@ -7,6 +7,6 @@ import lombok.Data;
public class SopStrategyRecordReqDTO {
@ApiModelProperty(value = "策略ID")
private Long strategyId;
private Integer strategyId;
}
\ No newline at end of file
......@@ -50,7 +50,7 @@ public class SopStrategyTask implements Serializable {
private Date executeTime;
/**
* 执行状态:0-待执行 1-执行中 2-已完成 3-执行失败
* 执行状态:0-待执行 1-已完成 2-执行失败
*/
@Column(name = "execute_status", nullable = false)
private Integer executeStatus;
......@@ -80,6 +80,24 @@ public class SopStrategyTask implements Serializable {
private String errorMessage;
/**
* 执行描述:执行成功/超时未确认/找不到可执行的动作/消息内容文本变量异常/找不到目标客户所在群/指定微信群不存在/发送消息失败
*/
@Column(name = "execute_desc", length = 500)
private String executeDesc;
/**
* 动作执行结果JSON
*/
@Column(name = "action_results", length = 4000)
private String actionResults;
/**
* 策略执行快照JSON(任务创建时保存,执行时更新分支信息)
*/
@Column(name = "snapshot_info", columnDefinition = "TEXT")
private String snapshotInfo;
/**
* 删除标志:N-未删除 D-已删除
*/
@Column(name = "deleted_flag")
......
......@@ -18,4 +18,6 @@ public interface SopStrategyTaskMapper extends OreMapper<SopStrategyTask> {
int deleteByStrategyId(@Param("strategyId") Integer strategyId);
List<SopStrategyTask> selectTasksNeedExecute(Date now);
List<SopStrategyTask> selectPageByStrategyId(@Param("strategyId") Integer strategyId);
}
\ No newline at end of file
......@@ -139,9 +139,9 @@ public class SopStrategyRemoteImpl implements SopStrategyRemote {
try {
log.info("营销SOP-策略执行记录查询:{}", pagination);
Page<SopStrategyExecutionRecord> result = strategySopQueryService.listSopStrategyRecords(pagination);
Page<SopStrategyRecordDTO> result = strategySopQueryService.listSopStrategyRecords(pagination);
return RpcResponse.success(RpcPagination.copyPage( result));
return RpcResponse.success(RpcPagination.copyPage(result));
} catch (RpcServiceException e) {
log.error("Controller__invoke__listSopStrategyRecords__bizException:{}", e.getMessage(), e);
return RpcResponse.error(e);
......
......@@ -16,9 +16,6 @@ import cn.com.glsx.dj.strategy.model.sop.*;
import cn.com.glsx.dj.strategy.service.action.SopActionExecutor;
import cn.com.glsx.dj.strategy.service.action.SopActionExecutorFactory;
import cn.hutool.core.collection.CollUtil;
import com.alibaba.fastjson.JSON;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import lombok.extern.slf4j.Slf4j;
import org.oreframework.distribute.lock.annotation.GlsxDistributeLockable;
import org.springframework.beans.factory.annotation.Autowired;
......@@ -96,9 +93,10 @@ public class SopStrategyExecutionService {
private static final String DESC_SEND_FAILED = "发送消息失败";
@Transactional
public void executeStrategy(Integer strategyId, Long customerInstanceId, Map<String, Object> contextVariables) {
public SopStrategyBranch executeStrategy(SopStrategyTask task, Map<String, Object> contextVariables) {
Integer strategyId=task.getStrategyId();
Long customerInstanceId=task.getCustomerInstanceId();
log.info("执行策略, strategyId:{}, customerInstanceId:{}", strategyId, customerInstanceId);
SopStrategy strategy = sopStrategyMapper.selectByPrimaryKey(strategyId);
if (strategy == null) {
log.warn("策略不存在, strategyId:{}", strategyId);
......@@ -119,21 +117,24 @@ public class SopStrategyExecutionService {
}
}
boolean branchMatched = false;
SopStrategyBranch matchedBranch = null;
for (SopStrategyBranch branch : branches) {
loadBranchRelations(branch);
if (conditionEngine.evaluateBranch(branch, contextVariables)) {
log.info("分支条件匹配, strategyId:{}, branchId:{}", strategyId, branch.getId());
matchedBranch = branch;
updateTaskSnapshot(task, matchedBranch, contextVariables);
executeBranchActions(branch, customerInstanceId, strategyId, contextVariables);
branchMatched = true;
break;
}
}
if (!branchMatched) {
if (matchedBranch == null) {
log.warn("找不到可执行的动作, strategyId:{}, customerInstanceId:{}", strategyId, customerInstanceId);
throw new RuntimeException("找不到可执行的动作");
}
return matchedBranch;
}
@GlsxDistributeLockable(name = "'SopStrategyExecutionService_executeTask_' + #taskId",
......@@ -160,19 +161,46 @@ public class SopStrategyExecutionService {
}
Map<String, Object> contextVariables = buildContextVariables(task);
SopStrategyBranch matchedBranch = null;
try {
executeStrategy(task.getStrategyId(), task.getCustomerInstanceId(), contextVariables);
updateTaskStatus(taskId, 2);
saveExecutionRecord(task, 1, DESC_SUCCESS, contextVariables, strategy, null);
matchedBranch = executeStrategy(task, contextVariables);
updateTaskStatus(taskId, 1, DESC_SUCCESS, null);
log.info("任务执行成功, taskId:{}", taskId);
} catch (Exception e) {
log.error("任务执行失败, taskId:{}, error:{}", taskId, e.getMessage(), e);
updateTaskStatus(taskId, 3);
String executeDesc = resolveExecuteDesc(e);
saveExecutionRecord(task, 2, executeDesc, contextVariables, strategy, e);
updateTaskStatus(taskId, 2, executeDesc, e.getMessage());
}
}
private void updateTaskSnapshot(SopStrategyTask task, SopStrategyBranch matchedBranch, Map<String, Object> contextVariables) {
if (task.getSnapshotInfo() == null || task.getSnapshotInfo().isEmpty()) {
log.warn("任务快照为空, taskId:{}", task.getId());
return;
}
Map<Integer, List<SopStrategyConditionGroup>> groupMap = new HashMap<>();
Map<Integer, List<SopStrategyCondition>> conditionMap = new HashMap<>();
Map<Integer, List<SopStrategyAction>> actionMap = new HashMap<>();
List<SopStrategyConditionGroup> groups = sopStrategyConditionGroupMapper.selectByBranchId(matchedBranch.getId());
groupMap.put(matchedBranch.getId(), groups);
for (SopStrategyConditionGroup group : groups) {
conditionMap.put(group.getId(), sopStrategyConditionMapper.selectByGroupId(group.getId()));
}
actionMap.put(matchedBranch.getId(), sopStrategyActionMapper.selectByBranchId(matchedBranch.getId()));
String updatedSnapshot = sopStrategySnapshotCacheService.updateExecutionBranchInfo(
task.getSnapshotInfo(), matchedBranch, contextVariables, groupMap, conditionMap, actionMap);
task.setSnapshotInfo(updatedSnapshot);
task.setBranchId(matchedBranch.getId());
task.setUpdatedDate(new Date());
sopStrategyTaskMapper.updateByPrimaryKeySelective(task);
log.info("更新任务快照, taskId:{}, branchId:{}", task.getId(), matchedBranch.getId());
}
private String resolveExecuteDesc(Exception e) {
......@@ -259,37 +287,17 @@ public class SopStrategyExecutionService {
@GlsxDistributeLockable(name = "'SopStrategyExecutionService_updateTaskStatus_' + #taskId",
time = 5, timeUnit = TimeUnit.MINUTES, timeoutException = Exception.class)
public void updateTaskStatus(Integer taskId, Integer status) {
public void updateTaskStatus(Integer taskId, Integer status, String executeDesc, String errorMessage) {
SopStrategyTask task = new SopStrategyTask();
task.setId(taskId);
task.setExecuteStatus(status);
task.setExecuteTime(new Date());
task.setExecuteDesc(executeDesc);
task.setErrorMessage(errorMessage);
task.setUpdatedDate(new Date());
sopStrategyTaskMapper.updateByPrimaryKeySelective(task);
}
@GlsxDistributeLockable(name = "'SopStrategyExecutionService_saveExecutionRecord_' + #task.id",
time = 5, timeUnit = TimeUnit.MINUTES, timeoutException = Exception.class)
public void saveExecutionRecord(SopStrategyTask task, Integer executeStatus, String executeDesc,
Map<String, Object> contextVariables, SopStrategy strategy, Exception e) {
SopStrategyExecutionRecord record = new SopStrategyExecutionRecord();
record.setStrategyId(task.getStrategyId());
record.setTaskId(task.getId());
record.setCustomerInstanceId(task.getCustomerInstanceId());
record.setTriggerTime(task.getTriggerTime());
record.setExecuteTime(new Date());
record.setExecuteStatus(executeStatus);
record.setExecuteDesc(executeDesc);
record.setErrorMessage(e.getMessage());
SopStrategySnapshotCacheService.StrategyDetailCache cache = sopStrategySnapshotCacheService.loadStrategyDetail(task.getStrategyId());
record.setSnapshotInfo(sopStrategySnapshotCacheService.buildSnapshotJson(task, cache, contextVariables));
record.setDeletedFlag("N");
record.setCreatedDate(new Date());
sopStrategyExecutionRecordMapper.insertSelective(record);
log.info("保存执行记录, taskId:{}, executeStatus:{}, executeDesc:{}", task.getId(), executeStatus, executeDesc);
}
private String getFullStackTrace(Exception e) {
if (e == null) {
return null;
......
......@@ -35,6 +35,8 @@ public class SopStrategyTriggerService {
private SopCustomerQueryService sopCustomerQueryService;
@Autowired
private SopCustomerSnapshotService sopCustomerSnapshotService;
@Autowired
private SopStrategySnapshotCacheService sopStrategySnapshotCacheService;
private static final Integer STEP_2 = 2;
......@@ -106,18 +108,13 @@ public class SopStrategyTriggerService {
log.info("创建待执行任务, strategyId:{}, customerInstanceId:{}, triggerTime:{}",
strategy.getId(), customerInstanceId, triggerTime);
} else {
if (checkConditionSatisfied(strategy, customerInstanceId)) {
Integer taskId = createImmediateTask(strategy, customerInstanceId);
if (taskId != null) {
sopCustomerSnapshotService.saveCustomerSnapshotWithTaskId(strategy, taskId,
customerInstanceId);
}
log.info("条件满足,创建立即执行任务, strategyId:{}, customerInstanceId:{}",
strategy.getId(), customerInstanceId);
} else {
log.info("条件不满足,跳过, strategyId:{}, customerInstanceId:{}",
strategy.getId(), customerInstanceId);
Integer taskId = createImmediateTask(strategy, customerInstanceId);
if (taskId != null) {
sopCustomerSnapshotService.saveCustomerSnapshotWithTaskId(strategy, taskId,
customerInstanceId);
}
log.info("条件满足,创建立即执行任务, strategyId:{}, customerInstanceId:{}",
strategy.getId(), customerInstanceId);
}
} catch (Exception e) {
log.error("处理客户ID {} 失败: {}", customerInstanceId, e.getMessage(), e);
......@@ -158,6 +155,12 @@ public class SopStrategyTriggerService {
return null;
}
SopStrategySnapshotCacheService.StrategyDetailCache cache = sopStrategySnapshotCacheService.loadStrategyDetail(strategy.getId());
String snapshotInfo = sopStrategySnapshotCacheService.buildTaskSnapshot(
strategy, customerInstanceId, triggerTime,
cache.getStoreRels(), cache.getBranches(), cache.getGroupMap(),
cache.getConditionMap(), cache.getActionMap(), cache.getStep2ConditionGroups());
SopStrategyTask task = new SopStrategyTask();
task.setStrategyId(strategy.getId());
task.setCustomerInstanceId(customerInstanceId);
......@@ -165,6 +168,7 @@ public class SopStrategyTriggerService {
task.setExecuteStatus(0);
task.setConfirmStatus(
strategy.getActionConfirmType() != null && strategy.getActionConfirmType() == 2 ? 0 : -1);
task.setSnapshotInfo(snapshotInfo);
task.setDeletedFlag("N");
task.setCreatedDate(new Date());
task.setUpdatedDate(new Date());
......@@ -182,6 +186,12 @@ public class SopStrategyTriggerService {
return null;
}
SopStrategySnapshotCacheService.StrategyDetailCache cache = sopStrategySnapshotCacheService.loadStrategyDetail(strategy.getId());
String snapshotInfo = sopStrategySnapshotCacheService.buildTaskSnapshot(
strategy, customerInstanceId, triggerTime,
cache.getStoreRels(), cache.getBranches(), cache.getGroupMap(),
cache.getConditionMap(), cache.getActionMap(), cache.getStep2ConditionGroups());
SopStrategyTask task = new SopStrategyTask();
task.setStrategyId(strategy.getId());
task.setCustomerInstanceId(customerInstanceId);
......@@ -189,6 +199,7 @@ public class SopStrategyTriggerService {
task.setExecuteStatus(0);
task.setConfirmStatus(
strategy.getActionConfirmType() != null && strategy.getActionConfirmType() == 2 ? 0 : -1);
task.setSnapshotInfo(snapshotInfo);
task.setDeletedFlag("N");
task.setCreatedDate(new Date());
task.setUpdatedDate(new Date());
......
......@@ -17,6 +17,7 @@ import cn.com.glsx.dj.strategy.mapper.sop.SopStrategyMetaMarketingStageMapper;
import cn.com.glsx.dj.strategy.mapper.sop.SopStrategyMetaMessageVariableMapper;
import cn.com.glsx.dj.strategy.mapper.sop.SopStrategyMetaTriggerMapper;
import cn.com.glsx.dj.strategy.mapper.sop.SopStrategyStoreRelMapper;
import cn.com.glsx.dj.strategy.mapper.sop.SopStrategyTaskMapper;
import cn.com.glsx.dj.strategy.model.sop.*;
import cn.com.glsx.framework.core.beans.rpc.RpcPagination;
import cn.com.glsx.scrm.equity.enums.DeleteFlagEnum;
......@@ -26,6 +27,7 @@ import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cn.com.glsx.dj.strategy.dto.sop.SopStrategySnapshotDTO.*;
......@@ -61,6 +63,9 @@ public class StrategySopQueryService {
private final SopStrategyMetaMessageVariableMapper metaMessageVariableMapper;
private final SopEnumDataSourceService sopEnumDataSourceService;
@Autowired
private SopStrategyTaskMapper sopStrategyTaskMapper;
/**
* 分页查询SOP策略列表
*
......@@ -839,41 +844,44 @@ public class StrategySopQueryService {
}
/**
* 查询策略执行记录列表
* 查询策略执行记录列表(从任务表查询)
*
* @param pagination 分页参数
* @return 执行记录列表
*/
public Page<SopStrategyExecutionRecord> listSopStrategyRecords(RpcPagination<SopStrategyRecordReqDTO> pagination) {
Page<SopStrategyExecutionRecord> page = PageHelper.startPage(pagination.getPageNum(), pagination.getPageSize());
sopStrategyExecutionRecordMapper.selectPageByStrategyId(pagination.getCondition());
public Page<SopStrategyRecordDTO> listSopStrategyRecords(RpcPagination<SopStrategyRecordReqDTO> pagination) {
Page<SopStrategyTask> page = PageHelper.startPage(pagination.getPageNum(), pagination.getPageSize());
sopStrategyTaskMapper.selectPageByStrategyId(pagination.getCondition().getStrategyId());
Page<SopStrategyRecordDTO> result = new Page<>(page.getPageNum(), page.getPageSize());
result.setTotal(page.getTotal());
for (SopStrategyExecutionRecord sopStrategyExecutionRecord : page) {
SopStrategyRecordDTO dto = convertToRecordDTO(sopStrategyExecutionRecord);
dto.setExecuteResultDesc(getExecuteResultDesc(sopStrategyExecutionRecord.getExecuteStatus()));
for (SopStrategyTask task : page.getResult()) {
result.add(convertToRecordDTO(task));
}
return page;
return result;
}
/**
* 转换执行记录实体为DTO
* 转换任务实体为执行记录DTO
*/
private SopStrategyRecordDTO convertToRecordDTO(SopStrategyExecutionRecord record) {
private SopStrategyRecordDTO convertToRecordDTO(SopStrategyTask task) {
SopStrategyRecordDTO dto = new SopStrategyRecordDTO();
dto.setRecordId(record.getId() != null ? record.getId().longValue() : null);
dto.setTaskId(record.getTaskId() != null ? record.getTaskId().longValue() : null);
dto.setStrategyId(record.getStrategyId() != null ? record.getStrategyId().longValue() : null);
dto.setCustomerInstanceId(record.getCustomerInstanceId());
dto.setTriggerTime(record.getTriggerTime());
dto.setExecuteTime(record.getExecuteTime());
dto.setExecuteResult(record.getExecuteStatus());
dto.setExecuteResultDesc(getExecuteResultDesc(record.getExecuteStatus()));
dto.setExecuteDesc(record.getExecuteDesc());
dto.setErrorMessage(record.getErrorMessage());
dto.setRecordId(task.getId() != null ? task.getId().longValue() : null);
dto.setTaskId(task.getId() != null ? task.getId().longValue() : null);
dto.setStrategyId(task.getStrategyId() != null ? task.getStrategyId().longValue() : null);
dto.setCustomerInstanceId(task.getCustomerInstanceId());
dto.setTriggerTime(task.getTriggerTime());
dto.setExecuteTime(task.getExecuteTime());
dto.setExecuteResult(task.getExecuteStatus());
dto.setExecuteResultDesc(getExecuteResultDesc(task.getExecuteStatus()));
dto.setExecuteDesc(task.getExecuteDesc());
dto.setErrorMessage(task.getErrorMessage());
dto.setSnapshotInfo(task.getSnapshotInfo());
SopStrategyCustomerSnapshot snapshot = sopStrategyCustomerSnapshotMapper.selectByTaskIdAndCustomerInstanceId(
record.getTaskId(), record.getCustomerInstanceId());
task.getId(), task.getCustomerInstanceId());
if (snapshot != null) {
dto.setCustomerName(snapshot.getCustomerName());
dto.setCustomerPhone(snapshot.getCustomerPhone());
......
......@@ -14,6 +14,9 @@
<result column="confirm_time" property="confirmTime"/>
<result column="confirm_by" property="confirmBy"/>
<result column="error_message" property="errorMessage"/>
<result column="execute_desc" property="executeDesc"/>
<result column="action_results" property="actionResults"/>
<result column="snapshot_info" property="snapshotInfo"/>
<result column="created_by" property="createdBy"/>
<result column="created_date" property="createdDate"/>
<result column="updated_by" property="updatedBy"/>
......@@ -46,4 +49,10 @@
UPDATE sop_strategy_task SET deleted_flag = 'D', updated_date = NOW()
WHERE strategy_id = #{strategyId}
</delete>
<select id="selectPageByStrategyId" resultMap="BaseResultMap">
SELECT * FROM sop_strategy_task
WHERE strategy_id = #{strategyId} AND deleted_flag = 'N' and execute_status in (1,2)
ORDER BY trigger_time DESC
</select>
</mapper>
\ No newline at end of file
......@@ -257,6 +257,6 @@ public class StrategyInfoServiceTest extends BaseServiceTest {
}
@Test
public void executeTask() {
sopStrategyExecutionService.executeTask(3);
sopStrategyExecutionService.executeTask(21);
}
}
......@@ -5,6 +5,7 @@ import static org.junit.Assert.assertTrue;
import cn.com.glsx.dj.strategy.dto.sop.SopStrategyDetailDTO;
import cn.com.glsx.dj.strategy.dto.sop.SopStrategyMetaDTO;
import cn.com.glsx.dj.strategy.dto.sop.SopStrategyRecordDTO;
import cn.com.glsx.dj.strategy.dto.sop.SopStrategyRecordDetailDTO;
import cn.com.glsx.dj.strategy.dto.sop.SopStrategyRecordReqDTO;
import cn.com.glsx.dj.strategy.exception.SopStrategyException;
......@@ -93,9 +94,9 @@ public class StrategySopQueryServiceTest {
pagination.setPageNum(1);
pagination.setPageSize(10);
SopStrategyRecordReqDTO condition = new SopStrategyRecordReqDTO();
condition.setStrategyId(4L);
condition.setStrategyId(4);
pagination.setCondition(condition);
Page<SopStrategyExecutionRecord> sopStrategyExecutionRecords = strategySopQueryService.listSopStrategyRecords(
Page<SopStrategyRecordDTO> sopStrategyExecutionRecords = strategySopQueryService.listSopStrategyRecords(
pagination);
log.info("分页结果:{}",JSONObject.toJSONString( sopStrategyExecutionRecords));
}
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!