Commit d1fc07d0 by zhouhaibao

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

- 修改executeStrategy方法参数结构,改为传入SopStrategyTask对象
- 新增updateTaskSnapshot方法用于更新任务执行时的分支信息
- 重构buildSnapshotJson方法为buildTaskSnapshot,支持构建完整的任务快照
- 添加updateExecutionBranchInfo方法,支持在执行时更新分支匹配信息
- 优化任务执行流程,返回匹配的分支信息而非void
- 更新数据库表结构,添加执行描述、动作结果和快照信息字段
- 调整执行状态枚举值定义,修改状态码含义
- 修改策略记录查询接口,从任务表直接查询执行记录
- 移除原有的执行记录表相关代码,统一使用任务表存储执行信息
- 修复业务类型映射错误,将轻改类型对应到正确数值
- 修正日期和数值类型的字段映射关系
1 parent 2da489e7
package cn.com.glsx.dj.strategy.dto.sop; package cn.com.glsx.dj.strategy.dto.sop;
import io.swagger.annotations.ApiModelProperty; import io.swagger.annotations.ApiModelProperty;
import javax.persistence.Column;
import lombok.Data; import lombok.Data;
import java.util.Date; import java.util.Date;
...@@ -52,4 +53,10 @@ public class SopStrategyRecordDTO { ...@@ -52,4 +53,10 @@ public class SopStrategyRecordDTO {
@ApiModelProperty(notes = "执行结果描述:成功/失败") @ApiModelProperty(notes = "执行结果描述:成功/失败")
private String executeResultDesc; private String executeResultDesc;
/**
* 策略执行快照JSON(任务创建时保存,执行时更新分支信息)
*/
@ApiModelProperty(notes = "策略执行快照JSON(任务创建时保存,执行时更新分支信息)")
private String snapshotInfo;
} }
\ No newline at end of file \ No newline at end of file
...@@ -7,6 +7,6 @@ import lombok.Data; ...@@ -7,6 +7,6 @@ import lombok.Data;
public class SopStrategyRecordReqDTO { public class SopStrategyRecordReqDTO {
@ApiModelProperty(value = "策略ID") @ApiModelProperty(value = "策略ID")
private Long strategyId; private Integer strategyId;
} }
\ No newline at end of file \ No newline at end of file
...@@ -50,7 +50,7 @@ public class SopStrategyTask implements Serializable { ...@@ -50,7 +50,7 @@ public class SopStrategyTask implements Serializable {
private Date executeTime; private Date executeTime;
/** /**
* 执行状态:0-待执行 1-执行中 2-已完成 3-执行失败 * 执行状态:0-待执行 1-已完成 2-执行失败
*/ */
@Column(name = "execute_status", nullable = false) @Column(name = "execute_status", nullable = false)
private Integer executeStatus; private Integer executeStatus;
...@@ -80,6 +80,24 @@ public class SopStrategyTask implements Serializable { ...@@ -80,6 +80,24 @@ public class SopStrategyTask implements Serializable {
private String errorMessage; 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-已删除 * 删除标志:N-未删除 D-已删除
*/ */
@Column(name = "deleted_flag") @Column(name = "deleted_flag")
......
...@@ -18,4 +18,6 @@ public interface SopStrategyTaskMapper extends OreMapper<SopStrategyTask> { ...@@ -18,4 +18,6 @@ public interface SopStrategyTaskMapper extends OreMapper<SopStrategyTask> {
int deleteByStrategyId(@Param("strategyId") Integer strategyId); int deleteByStrategyId(@Param("strategyId") Integer strategyId);
List<SopStrategyTask> selectTasksNeedExecute(Date now); List<SopStrategyTask> selectTasksNeedExecute(Date now);
List<SopStrategyTask> selectPageByStrategyId(@Param("strategyId") Integer strategyId);
} }
\ No newline at end of file \ No newline at end of file
...@@ -139,9 +139,9 @@ public class SopStrategyRemoteImpl implements SopStrategyRemote { ...@@ -139,9 +139,9 @@ public class SopStrategyRemoteImpl implements SopStrategyRemote {
try { try {
log.info("营销SOP-策略执行记录查询:{}", pagination); 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) { } catch (RpcServiceException e) {
log.error("Controller__invoke__listSopStrategyRecords__bizException:{}", e.getMessage(), e); log.error("Controller__invoke__listSopStrategyRecords__bizException:{}", e.getMessage(), e);
return RpcResponse.error(e); return RpcResponse.error(e);
......
...@@ -16,9 +16,6 @@ import cn.com.glsx.dj.strategy.model.sop.*; ...@@ -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.SopActionExecutor;
import cn.com.glsx.dj.strategy.service.action.SopActionExecutorFactory; import cn.com.glsx.dj.strategy.service.action.SopActionExecutorFactory;
import cn.hutool.core.collection.CollUtil; 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 lombok.extern.slf4j.Slf4j;
import org.oreframework.distribute.lock.annotation.GlsxDistributeLockable; import org.oreframework.distribute.lock.annotation.GlsxDistributeLockable;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
...@@ -96,9 +93,10 @@ public class SopStrategyExecutionService { ...@@ -96,9 +93,10 @@ public class SopStrategyExecutionService {
private static final String DESC_SEND_FAILED = "发送消息失败"; private static final String DESC_SEND_FAILED = "发送消息失败";
@Transactional @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); log.info("执行策略, strategyId:{}, customerInstanceId:{}", strategyId, customerInstanceId);
SopStrategy strategy = sopStrategyMapper.selectByPrimaryKey(strategyId); SopStrategy strategy = sopStrategyMapper.selectByPrimaryKey(strategyId);
if (strategy == null) { if (strategy == null) {
log.warn("策略不存在, strategyId:{}", strategyId); log.warn("策略不存在, strategyId:{}", strategyId);
...@@ -119,21 +117,24 @@ public class SopStrategyExecutionService { ...@@ -119,21 +117,24 @@ public class SopStrategyExecutionService {
} }
} }
boolean branchMatched = false; SopStrategyBranch matchedBranch = null;
for (SopStrategyBranch branch : branches) { for (SopStrategyBranch branch : branches) {
loadBranchRelations(branch); loadBranchRelations(branch);
if (conditionEngine.evaluateBranch(branch, contextVariables)) { if (conditionEngine.evaluateBranch(branch, contextVariables)) {
log.info("分支条件匹配, strategyId:{}, branchId:{}", strategyId, branch.getId()); log.info("分支条件匹配, strategyId:{}, branchId:{}", strategyId, branch.getId());
matchedBranch = branch;
updateTaskSnapshot(task, matchedBranch, contextVariables);
executeBranchActions(branch, customerInstanceId, strategyId, contextVariables); executeBranchActions(branch, customerInstanceId, strategyId, contextVariables);
branchMatched = true;
break; break;
} }
} }
if (!branchMatched) { if (matchedBranch == null) {
log.warn("找不到可执行的动作, strategyId:{}, customerInstanceId:{}", strategyId, customerInstanceId); log.warn("找不到可执行的动作, strategyId:{}, customerInstanceId:{}", strategyId, customerInstanceId);
throw new RuntimeException("找不到可执行的动作"); throw new RuntimeException("找不到可执行的动作");
} }
return matchedBranch;
} }
@GlsxDistributeLockable(name = "'SopStrategyExecutionService_executeTask_' + #taskId", @GlsxDistributeLockable(name = "'SopStrategyExecutionService_executeTask_' + #taskId",
...@@ -160,19 +161,46 @@ public class SopStrategyExecutionService { ...@@ -160,19 +161,46 @@ public class SopStrategyExecutionService {
} }
Map<String, Object> contextVariables = buildContextVariables(task); Map<String, Object> contextVariables = buildContextVariables(task);
SopStrategyBranch matchedBranch = null;
try { try {
executeStrategy(task.getStrategyId(), task.getCustomerInstanceId(), contextVariables); matchedBranch = executeStrategy(task, contextVariables);
updateTaskStatus(taskId, 2);
saveExecutionRecord(task, 1, DESC_SUCCESS, contextVariables, strategy, null); updateTaskStatus(taskId, 1, DESC_SUCCESS, null);
log.info("任务执行成功, taskId:{}", taskId); log.info("任务执行成功, taskId:{}", taskId);
} catch (Exception e) { } catch (Exception e) {
log.error("任务执行失败, taskId:{}, error:{}", taskId, e.getMessage(), e); log.error("任务执行失败, taskId:{}, error:{}", taskId, e.getMessage(), e);
updateTaskStatus(taskId, 3);
String executeDesc = resolveExecuteDesc(e); 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) { private String resolveExecuteDesc(Exception e) {
...@@ -259,37 +287,17 @@ public class SopStrategyExecutionService { ...@@ -259,37 +287,17 @@ public class SopStrategyExecutionService {
@GlsxDistributeLockable(name = "'SopStrategyExecutionService_updateTaskStatus_' + #taskId", @GlsxDistributeLockable(name = "'SopStrategyExecutionService_updateTaskStatus_' + #taskId",
time = 5, timeUnit = TimeUnit.MINUTES, timeoutException = Exception.class) 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(); SopStrategyTask task = new SopStrategyTask();
task.setId(taskId); task.setId(taskId);
task.setExecuteStatus(status); task.setExecuteStatus(status);
task.setExecuteTime(new Date());
task.setExecuteDesc(executeDesc);
task.setErrorMessage(errorMessage);
task.setUpdatedDate(new Date()); task.setUpdatedDate(new Date());
sopStrategyTaskMapper.updateByPrimaryKeySelective(task); 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) { private String getFullStackTrace(Exception e) {
if (e == null) { if (e == null) {
return null; return null;
......
...@@ -125,12 +125,12 @@ public class SopStrategySnapshotCacheService { ...@@ -125,12 +125,12 @@ public class SopStrategySnapshotCacheService {
SopStrategyMetaConditionVariable::getVariableName)); SopStrategyMetaConditionVariable::getVariableName));
} }
public String buildSnapshotJson(SopStrategyTask task, StrategyDetailCache cache, Map<String, Object> contextVariables) { public String buildTaskSnapshot(SopStrategy strategy, Long customerInstanceId, Date triggerTime,
SopStrategy strategy = cache.getStrategy(); List<SopStrategyStoreRel> storeRels, List<SopStrategyBranch> branches,
if (strategy == null) { Map<Integer, List<SopStrategyConditionGroup>> groupMap,
return null; Map<Integer, List<SopStrategyCondition>> conditionMap,
} Map<Integer, List<SopStrategyAction>> actionMap,
List<SopStrategyConditionGroup> step2ConditionGroups) {
Map<String, Object> snapshot = new LinkedHashMap<>(); Map<String, Object> snapshot = new LinkedHashMap<>();
Map<String, Object> basicInfo = new LinkedHashMap<>(); Map<String, Object> basicInfo = new LinkedHashMap<>();
...@@ -141,15 +141,11 @@ public class SopStrategySnapshotCacheService { ...@@ -141,15 +141,11 @@ public class SopStrategySnapshotCacheService {
basicInfo.put("storeScopeDesc", strategy.getStoreScopeType() == 1 ? "指定门店" : "全部门店"); basicInfo.put("storeScopeDesc", strategy.getStoreScopeType() == 1 ? "指定门店" : "全部门店");
basicInfo.put("marketingStage", strategy.getMarketingStage()); basicInfo.put("marketingStage", strategy.getMarketingStage());
basicInfo.put("marketingStageName", getMarketingStageName(strategy.getMarketingStage())); basicInfo.put("marketingStageName", getMarketingStageName(strategy.getMarketingStage()));
basicInfo.put("storeDescription", buildStoreDescription(strategy.getStoreScopeType(), cache.getStoreRels())); basicInfo.put("storeDescription", buildStoreDescription(strategy.getStoreScopeType(), storeRels));
snapshot.put("basicInfo", basicInfo); snapshot.put("basicInfo", basicInfo);
Map<String, Object> customerInfo = new LinkedHashMap<>(); Map<String, Object> customerInfo = new LinkedHashMap<>();
customerInfo.put("customerInstanceId", task.getCustomerInstanceId()); customerInfo.put("customerInstanceId", customerInstanceId);
customerInfo.put("customerName", contextVariables.get("customerName"));
customerInfo.put("customerPhone", contextVariables.get("customerPhone"));
customerInfo.put("storeId", contextVariables.get("storeId"));
customerInfo.put("storeName", contextVariables.get("storeName"));
snapshot.put("customerInfo", customerInfo); snapshot.put("customerInfo", customerInfo);
Map<String, Object> triggerInfo = new LinkedHashMap<>(); Map<String, Object> triggerInfo = new LinkedHashMap<>();
...@@ -162,34 +158,170 @@ public class SopStrategySnapshotCacheService { ...@@ -162,34 +158,170 @@ public class SopStrategySnapshotCacheService {
triggerInfo.put("relativeDays", strategy.getRelativeDays()); triggerInfo.put("relativeDays", strategy.getRelativeDays());
triggerInfo.put("triggerHour", strategy.getTriggerHour()); triggerInfo.put("triggerHour", strategy.getTriggerHour());
triggerInfo.put("triggerMinute", strategy.getTriggerMinute()); triggerInfo.put("triggerMinute", strategy.getTriggerMinute());
triggerInfo.put("triggerTime", task.getTriggerTime()); triggerInfo.put("triggerTime", triggerTime);
triggerInfo.put("triggerTimeDesc", buildTriggerTimeDesc(strategy)); triggerInfo.put("triggerTimeDesc", buildTriggerTimeDesc(strategy));
triggerInfo.put("actionConfirmType", strategy.getActionConfirmType()); triggerInfo.put("actionConfirmType", strategy.getActionConfirmType());
triggerInfo.put("actionConfirmDesc", strategy.getActionConfirmType() == 1 ? "自动执行" : "需确认"); triggerInfo.put("actionConfirmDesc", strategy.getActionConfirmType() == 1 ? "自动执行" : "需驻店人员确认");
List<Map<String, Object>> step2ConditionGroups = buildStep2ConditionGroupsSnapshot(cache); List<Map<String, Object>> step2ConditionGroupsSnapshot = new ArrayList<>();
triggerInfo.put("step2ConditionGroups", step2ConditionGroups); for (SopStrategyConditionGroup group : step2ConditionGroups) {
Map<String, Object> groupMapItem = new LinkedHashMap<>();
groupMapItem.put("groupName", group.getGroupName());
groupMapItem.put("groupLogic", group.getGroupLogic());
groupMapItem.put("groupLogicDesc", group.getGroupLogic() == 1 ? "且" : "或");
List<Map<String, Object>> conditions = new ArrayList<>();
for (SopStrategyCondition condition : conditionMap.get(group.getId())) {
conditions.add(buildConditionSnapshot(condition));
}
groupMapItem.put("conditions", conditions);
step2ConditionGroupsSnapshot.add(groupMapItem);
}
triggerInfo.put("step2ConditionGroups", step2ConditionGroupsSnapshot);
snapshot.put("triggerInfo", triggerInfo); snapshot.put("triggerInfo", triggerInfo);
List<Map<String, Object>> branches = buildBranchesSnapshot(cache, contextVariables); List<Map<String, Object>> branchesSnapshot = new ArrayList<>();
snapshot.put("branches", branches); for (SopStrategyBranch branch : branches) {
Map<String, Object> branchMap = new LinkedHashMap<>();
branchMap.put("branchNo", branch.getBranchNo());
branchMap.put("branchName", branch.getBranchName());
branchMap.put("branchLogic", branch.getBranchLogic());
branchMap.put("branchLogicDesc", branch.getBranchLogic() == 0 ? "且" : "或");
List<Map<String, Object>> conditionGroups = new ArrayList<>();
for (SopStrategyConditionGroup group : groupMap.get(branch.getId())) {
Map<String, Object> groupMapItem = new LinkedHashMap<>();
groupMapItem.put("groupName", group.getGroupName());
groupMapItem.put("groupLogic", group.getGroupLogic());
groupMapItem.put("groupLogicDesc", group.getGroupLogic() == 1 ? "且" : "或");
List<Map<String, Object>> conditions = new ArrayList<>();
for (SopStrategyCondition condition : conditionMap.get(group.getId())) {
conditions.add(buildConditionSnapshot(condition));
}
groupMapItem.put("conditions", conditions);
conditionGroups.add(groupMapItem);
}
branchMap.put("conditionGroups", conditionGroups);
Map<String, Object> messageVariables = new LinkedHashMap<>(); List<Map<String, Object>> actions = new ArrayList<>();
for (Map.Entry<String, Object> entry : contextVariables.entrySet()) { for (SopStrategyAction action : actionMap.get(branch.getId())) {
if (entry.getKey().equals("customerInstanceId") || entry.getKey().equals("triggerTime") || Map<String, Object> actionMapItem = new LinkedHashMap<>();
entry.getKey().equals("taskId")) { actionMapItem.put("actionName", action.getActionName());
continue; actionMapItem.put("actionType", action.getActionType());
actionMapItem.put("actionTypeName", getActionTypeName(action.getActionType()));
actionMapItem.put("messageType", action.getMessageType());
actionMapItem.put("messageTypeName", getMessageTypeName(action.getMessageType()));
actionMapItem.put("content", action.getContent());
actionMapItem.put("jumpUrl", action.getJumpUrl());
actionMapItem.put("bgColor", action.getBgColor());
actionMapItem.put("materialJson", action.getMaterialJson());
actionMapItem.put("intervalPx", action.getIntervalPx());
actions.add(actionMapItem);
} }
messageVariables.put(entry.getKey(), entry.getValue()); branchMap.put("actions", actions);
branchesSnapshot.add(branchMap);
}
snapshot.put("branches", branchesSnapshot);
try {
return JSON.toJSONString(snapshot);
} catch (Exception e) {
log.error("构建任务快照JSON失败, strategyId:{}, customerInstanceId:{}", strategy.getId(), customerInstanceId, e);
return null;
} }
snapshot.put("messageVariables", messageVariables); }
public String updateExecutionBranchInfo(String existingSnapshotJson, SopStrategyBranch matchedBranch,
Map<String, Object> contextVariables,
Map<Integer, List<SopStrategyConditionGroup>> groupMap,
Map<Integer, List<SopStrategyCondition>> conditionMap,
Map<Integer, List<SopStrategyAction>> actionMap) {
try { try {
Map<String, Object> snapshot = JSON.parseObject(existingSnapshotJson, LinkedHashMap.class);
List<Map<String, Object>> matchedBranches = new ArrayList<>();
Map<String, Object> branchMap = new LinkedHashMap<>();
branchMap.put("branchNo", matchedBranch.getBranchNo());
branchMap.put("branchName", matchedBranch.getBranchName());
branchMap.put("branchLogic", matchedBranch.getBranchLogic());
branchMap.put("branchLogicDesc", matchedBranch.getBranchLogic() == 0 ? "且" : "或");
branchMap.put("matched", true);
List<Map<String, Object>> conditionGroups = new ArrayList<>();
for (SopStrategyConditionGroup group : groupMap.get(matchedBranch.getId())) {
Map<String, Object> groupMapItem = new LinkedHashMap<>();
groupMapItem.put("groupName", group.getGroupName());
groupMapItem.put("groupLogic", group.getGroupLogic());
groupMapItem.put("groupLogicDesc", group.getGroupLogic() == 1 ? "且" : "或");
List<Map<String, Object>> conditions = new ArrayList<>();
for (SopStrategyCondition condition : conditionMap.get(group.getId())) {
Map<String, Object> conditionMapItem = buildConditionSnapshot(condition);
conditions.add(conditionMapItem);
}
groupMapItem.put("conditions", conditions);
conditionGroups.add(groupMapItem);
}
branchMap.put("conditionGroups", conditionGroups);
List<Map<String, Object>> actions = new ArrayList<>();
for (SopStrategyAction action : actionMap.get(matchedBranch.getId())) {
Map<String, Object> actionMapItem = new LinkedHashMap<>();
actionMapItem.put("actionName", action.getActionName());
actionMapItem.put("actionType", action.getActionType());
actionMapItem.put("actionTypeName", getActionTypeName(action.getActionType()));
actionMapItem.put("messageType", action.getMessageType());
actionMapItem.put("messageTypeName", getMessageTypeName(action.getMessageType()));
String content = action.getContent();
if (content != null && !content.isEmpty()) {
content = replaceVariables(content, contextVariables);
}
actionMapItem.put("content", content);
actionMapItem.put("jumpUrl", action.getJumpUrl());
actionMapItem.put("bgColor", action.getBgColor());
actionMapItem.put("materialJson", action.getMaterialJson());
actionMapItem.put("intervalPx", action.getIntervalPx());
actions.add(actionMapItem);
}
branchMap.put("actions", actions);
matchedBranches.add(branchMap);
snapshot.put("branches", matchedBranches);
Map<String, Object> messageVariables = new LinkedHashMap<>();
if (contextVariables != null) {
for (Map.Entry<String, Object> entry : contextVariables.entrySet()) {
if (entry.getKey().equals("customerInstanceId") || entry.getKey().equals("triggerTime") ||
entry.getKey().equals("taskId")) {
continue;
}
messageVariables.put(entry.getKey(), entry.getValue());
}
}
snapshot.put("messageVariables", messageVariables);
return JSON.toJSONString(snapshot); return JSON.toJSONString(snapshot);
} catch (Exception e) { } catch (Exception e) {
log.error("构建快照JSON失败, taskId:{}", task.getId(), e); log.error("更新执行分支信息失败", e);
return existingSnapshotJson;
}
}
public String buildSnapshotJson(SopStrategyTask task, StrategyDetailCache cache, Map<String, Object> contextVariables) {
if (task.getSnapshotInfo() != null && !task.getSnapshotInfo().isEmpty()) {
return task.getSnapshotInfo();
}
SopStrategy strategy = cache.getStrategy();
if (strategy == null) {
return null; return null;
} }
return buildTaskSnapshot(strategy, task.getCustomerInstanceId(), task.getTriggerTime(),
cache.getStoreRels(), cache.getBranches(), cache.getGroupMap(),
cache.getConditionMap(), cache.getActionMap(), cache.getStep2ConditionGroups());
} }
private List<Map<String, Object>> buildStep2ConditionGroupsSnapshot(StrategyDetailCache cache) { private List<Map<String, Object>> buildStep2ConditionGroupsSnapshot(StrategyDetailCache cache) {
...@@ -279,10 +411,7 @@ public class SopStrategySnapshotCacheService { ...@@ -279,10 +411,7 @@ public class SopStrategySnapshotCacheService {
private String getBizTypeName(Integer bizType) { private String getBizTypeName(Integer bizType) {
if (bizType == null) return ""; if (bizType == null) return "";
switch (bizType) { switch (bizType) {
case 1: return "试驾"; case 1: return "轻改";
case 2: return "售后";
case 3: return "续保";
case 4: return "金融";
default: return ""; default: return "";
} }
} }
...@@ -380,8 +509,8 @@ public class SopStrategySnapshotCacheService { ...@@ -380,8 +509,8 @@ public class SopStrategySnapshotCacheService {
if (condition.getValueType() != null) { if (condition.getValueType() != null) {
switch (condition.getValueType()) { switch (condition.getValueType()) {
case 1: value = condition.getTextValue(); break; case 1: value = condition.getTextValue(); break;
case 2: value = condition.getDateValue(); break; case 2: value = condition.getNumberValue(); break;
case 3: value = condition.getNumberValue(); break; case 3: value = condition.getDateValue(); break;
case 4: value = condition.getEnumValue(); break; case 4: value = condition.getEnumValue(); break;
default: value = ""; default: value = "";
} }
......
...@@ -35,6 +35,8 @@ public class SopStrategyTriggerService { ...@@ -35,6 +35,8 @@ public class SopStrategyTriggerService {
private SopCustomerQueryService sopCustomerQueryService; private SopCustomerQueryService sopCustomerQueryService;
@Autowired @Autowired
private SopCustomerSnapshotService sopCustomerSnapshotService; private SopCustomerSnapshotService sopCustomerSnapshotService;
@Autowired
private SopStrategySnapshotCacheService sopStrategySnapshotCacheService;
private static final Integer STEP_2 = 2; private static final Integer STEP_2 = 2;
...@@ -106,18 +108,13 @@ public class SopStrategyTriggerService { ...@@ -106,18 +108,13 @@ public class SopStrategyTriggerService {
log.info("创建待执行任务, strategyId:{}, customerInstanceId:{}, triggerTime:{}", log.info("创建待执行任务, strategyId:{}, customerInstanceId:{}, triggerTime:{}",
strategy.getId(), customerInstanceId, triggerTime); strategy.getId(), customerInstanceId, triggerTime);
} else { } else {
if (checkConditionSatisfied(strategy, customerInstanceId)) { Integer taskId = createImmediateTask(strategy, customerInstanceId);
Integer taskId = createImmediateTask(strategy, customerInstanceId); if (taskId != null) {
if (taskId != null) { sopCustomerSnapshotService.saveCustomerSnapshotWithTaskId(strategy, taskId,
sopCustomerSnapshotService.saveCustomerSnapshotWithTaskId(strategy, taskId, customerInstanceId);
customerInstanceId);
}
log.info("条件满足,创建立即执行任务, strategyId:{}, customerInstanceId:{}",
strategy.getId(), customerInstanceId);
} else {
log.info("条件不满足,跳过, strategyId:{}, customerInstanceId:{}",
strategy.getId(), customerInstanceId);
} }
log.info("条件满足,创建立即执行任务, strategyId:{}, customerInstanceId:{}",
strategy.getId(), customerInstanceId);
} }
} catch (Exception e) { } catch (Exception e) {
log.error("处理客户ID {} 失败: {}", customerInstanceId, e.getMessage(), e); log.error("处理客户ID {} 失败: {}", customerInstanceId, e.getMessage(), e);
...@@ -158,6 +155,12 @@ public class SopStrategyTriggerService { ...@@ -158,6 +155,12 @@ public class SopStrategyTriggerService {
return null; 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(); SopStrategyTask task = new SopStrategyTask();
task.setStrategyId(strategy.getId()); task.setStrategyId(strategy.getId());
task.setCustomerInstanceId(customerInstanceId); task.setCustomerInstanceId(customerInstanceId);
...@@ -165,6 +168,7 @@ public class SopStrategyTriggerService { ...@@ -165,6 +168,7 @@ public class SopStrategyTriggerService {
task.setExecuteStatus(0); task.setExecuteStatus(0);
task.setConfirmStatus( task.setConfirmStatus(
strategy.getActionConfirmType() != null && strategy.getActionConfirmType() == 2 ? 0 : -1); strategy.getActionConfirmType() != null && strategy.getActionConfirmType() == 2 ? 0 : -1);
task.setSnapshotInfo(snapshotInfo);
task.setDeletedFlag("N"); task.setDeletedFlag("N");
task.setCreatedDate(new Date()); task.setCreatedDate(new Date());
task.setUpdatedDate(new Date()); task.setUpdatedDate(new Date());
...@@ -182,6 +186,12 @@ public class SopStrategyTriggerService { ...@@ -182,6 +186,12 @@ public class SopStrategyTriggerService {
return null; 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(); SopStrategyTask task = new SopStrategyTask();
task.setStrategyId(strategy.getId()); task.setStrategyId(strategy.getId());
task.setCustomerInstanceId(customerInstanceId); task.setCustomerInstanceId(customerInstanceId);
...@@ -189,6 +199,7 @@ public class SopStrategyTriggerService { ...@@ -189,6 +199,7 @@ public class SopStrategyTriggerService {
task.setExecuteStatus(0); task.setExecuteStatus(0);
task.setConfirmStatus( task.setConfirmStatus(
strategy.getActionConfirmType() != null && strategy.getActionConfirmType() == 2 ? 0 : -1); strategy.getActionConfirmType() != null && strategy.getActionConfirmType() == 2 ? 0 : -1);
task.setSnapshotInfo(snapshotInfo);
task.setDeletedFlag("N"); task.setDeletedFlag("N");
task.setCreatedDate(new Date()); task.setCreatedDate(new Date());
task.setUpdatedDate(new Date()); task.setUpdatedDate(new Date());
......
...@@ -17,6 +17,7 @@ import cn.com.glsx.dj.strategy.mapper.sop.SopStrategyMetaMarketingStageMapper; ...@@ -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.SopStrategyMetaMessageVariableMapper;
import cn.com.glsx.dj.strategy.mapper.sop.SopStrategyMetaTriggerMapper; 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.SopStrategyStoreRelMapper;
import cn.com.glsx.dj.strategy.mapper.sop.SopStrategyTaskMapper;
import cn.com.glsx.dj.strategy.model.sop.*; import cn.com.glsx.dj.strategy.model.sop.*;
import cn.com.glsx.framework.core.beans.rpc.RpcPagination; import cn.com.glsx.framework.core.beans.rpc.RpcPagination;
import cn.com.glsx.scrm.equity.enums.DeleteFlagEnum; import cn.com.glsx.scrm.equity.enums.DeleteFlagEnum;
...@@ -26,6 +27,7 @@ import com.github.pagehelper.Page; ...@@ -26,6 +27,7 @@ import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageHelper;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import cn.com.glsx.dj.strategy.dto.sop.SopStrategySnapshotDTO.*; import cn.com.glsx.dj.strategy.dto.sop.SopStrategySnapshotDTO.*;
...@@ -61,6 +63,9 @@ public class StrategySopQueryService { ...@@ -61,6 +63,9 @@ public class StrategySopQueryService {
private final SopStrategyMetaMessageVariableMapper metaMessageVariableMapper; private final SopStrategyMetaMessageVariableMapper metaMessageVariableMapper;
private final SopEnumDataSourceService sopEnumDataSourceService; private final SopEnumDataSourceService sopEnumDataSourceService;
@Autowired
private SopStrategyTaskMapper sopStrategyTaskMapper;
/** /**
* 分页查询SOP策略列表 * 分页查询SOP策略列表
* *
...@@ -839,41 +844,44 @@ public class StrategySopQueryService { ...@@ -839,41 +844,44 @@ public class StrategySopQueryService {
} }
/** /**
* 查询策略执行记录列表 * 查询策略执行记录列表(从任务表查询)
* *
* @param pagination 分页参数 * @param pagination 分页参数
* @return 执行记录列表 * @return 执行记录列表
*/ */
public Page<SopStrategyExecutionRecord> listSopStrategyRecords(RpcPagination<SopStrategyRecordReqDTO> pagination) { public Page<SopStrategyRecordDTO> listSopStrategyRecords(RpcPagination<SopStrategyRecordReqDTO> pagination) {
Page<SopStrategyExecutionRecord> page = PageHelper.startPage(pagination.getPageNum(), pagination.getPageSize()); Page<SopStrategyTask> page = PageHelper.startPage(pagination.getPageNum(), pagination.getPageSize());
sopStrategyExecutionRecordMapper.selectPageByStrategyId(pagination.getCondition()); sopStrategyTaskMapper.selectPageByStrategyId(pagination.getCondition().getStrategyId());
Page<SopStrategyRecordDTO> result = new Page<>(page.getPageNum(), page.getPageSize());
result.setTotal(page.getTotal());
for (SopStrategyExecutionRecord sopStrategyExecutionRecord : page) { for (SopStrategyTask task : page.getResult()) {
SopStrategyRecordDTO dto = convertToRecordDTO(sopStrategyExecutionRecord); result.add(convertToRecordDTO(task));
dto.setExecuteResultDesc(getExecuteResultDesc(sopStrategyExecutionRecord.getExecuteStatus()));
} }
return page; return result;
} }
/** /**
* 转换执行记录实体为DTO * 转换任务实体为执行记录DTO
*/ */
private SopStrategyRecordDTO convertToRecordDTO(SopStrategyExecutionRecord record) { private SopStrategyRecordDTO convertToRecordDTO(SopStrategyTask task) {
SopStrategyRecordDTO dto = new SopStrategyRecordDTO(); SopStrategyRecordDTO dto = new SopStrategyRecordDTO();
dto.setRecordId(record.getId() != null ? record.getId().longValue() : null); dto.setRecordId(task.getId() != null ? task.getId().longValue() : null);
dto.setTaskId(record.getTaskId() != null ? record.getTaskId().longValue() : null); dto.setTaskId(task.getId() != null ? task.getId().longValue() : null);
dto.setStrategyId(record.getStrategyId() != null ? record.getStrategyId().longValue() : null); dto.setStrategyId(task.getStrategyId() != null ? task.getStrategyId().longValue() : null);
dto.setCustomerInstanceId(record.getCustomerInstanceId()); dto.setCustomerInstanceId(task.getCustomerInstanceId());
dto.setTriggerTime(record.getTriggerTime()); dto.setTriggerTime(task.getTriggerTime());
dto.setExecuteTime(record.getExecuteTime()); dto.setExecuteTime(task.getExecuteTime());
dto.setExecuteResult(record.getExecuteStatus()); dto.setExecuteResult(task.getExecuteStatus());
dto.setExecuteResultDesc(getExecuteResultDesc(record.getExecuteStatus())); dto.setExecuteResultDesc(getExecuteResultDesc(task.getExecuteStatus()));
dto.setExecuteDesc(record.getExecuteDesc()); dto.setExecuteDesc(task.getExecuteDesc());
dto.setErrorMessage(record.getErrorMessage()); dto.setErrorMessage(task.getErrorMessage());
dto.setSnapshotInfo(task.getSnapshotInfo());
SopStrategyCustomerSnapshot snapshot = sopStrategyCustomerSnapshotMapper.selectByTaskIdAndCustomerInstanceId( SopStrategyCustomerSnapshot snapshot = sopStrategyCustomerSnapshotMapper.selectByTaskIdAndCustomerInstanceId(
record.getTaskId(), record.getCustomerInstanceId()); task.getId(), task.getCustomerInstanceId());
if (snapshot != null) { if (snapshot != null) {
dto.setCustomerName(snapshot.getCustomerName()); dto.setCustomerName(snapshot.getCustomerName());
dto.setCustomerPhone(snapshot.getCustomerPhone()); dto.setCustomerPhone(snapshot.getCustomerPhone());
......
...@@ -14,6 +14,9 @@ ...@@ -14,6 +14,9 @@
<result column="confirm_time" property="confirmTime"/> <result column="confirm_time" property="confirmTime"/>
<result column="confirm_by" property="confirmBy"/> <result column="confirm_by" property="confirmBy"/>
<result column="error_message" property="errorMessage"/> <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_by" property="createdBy"/>
<result column="created_date" property="createdDate"/> <result column="created_date" property="createdDate"/>
<result column="updated_by" property="updatedBy"/> <result column="updated_by" property="updatedBy"/>
...@@ -46,4 +49,10 @@ ...@@ -46,4 +49,10 @@
UPDATE sop_strategy_task SET deleted_flag = 'D', updated_date = NOW() UPDATE sop_strategy_task SET deleted_flag = 'D', updated_date = NOW()
WHERE strategy_id = #{strategyId} WHERE strategy_id = #{strategyId}
</delete> </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> </mapper>
\ No newline at end of file \ No newline at end of file
...@@ -257,6 +257,6 @@ public class StrategyInfoServiceTest extends BaseServiceTest { ...@@ -257,6 +257,6 @@ public class StrategyInfoServiceTest extends BaseServiceTest {
} }
@Test @Test
public void executeTask() { public void executeTask() {
sopStrategyExecutionService.executeTask(3); sopStrategyExecutionService.executeTask(21);
} }
} }
...@@ -5,6 +5,7 @@ import static org.junit.Assert.assertTrue; ...@@ -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.SopStrategyDetailDTO;
import cn.com.glsx.dj.strategy.dto.sop.SopStrategyMetaDTO; 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.SopStrategyRecordDetailDTO;
import cn.com.glsx.dj.strategy.dto.sop.SopStrategyRecordReqDTO; import cn.com.glsx.dj.strategy.dto.sop.SopStrategyRecordReqDTO;
import cn.com.glsx.dj.strategy.exception.SopStrategyException; import cn.com.glsx.dj.strategy.exception.SopStrategyException;
...@@ -93,9 +94,9 @@ public class StrategySopQueryServiceTest { ...@@ -93,9 +94,9 @@ public class StrategySopQueryServiceTest {
pagination.setPageNum(1); pagination.setPageNum(1);
pagination.setPageSize(10); pagination.setPageSize(10);
SopStrategyRecordReqDTO condition = new SopStrategyRecordReqDTO(); SopStrategyRecordReqDTO condition = new SopStrategyRecordReqDTO();
condition.setStrategyId(4L); condition.setStrategyId(4);
pagination.setCondition(condition); pagination.setCondition(condition);
Page<SopStrategyExecutionRecord> sopStrategyExecutionRecords = strategySopQueryService.listSopStrategyRecords( Page<SopStrategyRecordDTO> sopStrategyExecutionRecords = strategySopQueryService.listSopStrategyRecords(
pagination); pagination);
log.info("分页结果:{}",JSONObject.toJSONString( sopStrategyExecutionRecords)); 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!