Commit ea83297a by zhouhaibao

refactor(strategy): 调整分支逻辑数据类型并添加策略快照功能

- 将 SopStrategyBranch 的 branchLogic 字段从 Boolean 改为 Integer 类型
- 修改条件验证逻辑以适配新的数据类型(1表示AND,0表示OR)
- 更新单元测试中的分支逻辑设置值
- 在 SopCustomerQueryService 中添加客户不存在时的异常处理
- 移除 SopDynamicSqlService 中的数据库条件验证相关方法
- 添加 SopStrategySnapshotCacheService 服务用于构建策略快照信息
- 在执行记录中添加快照信息存储功能
- 新增策略快照相关的DTO类和数据库字段映射
- 更新相对日期类型的注释说明
1 parent cdd1cc8d
Showing 16 changed files with 283 additions and 276 deletions
...@@ -61,6 +61,9 @@ public class SopStrategyDetailDTO { ...@@ -61,6 +61,9 @@ public class SopStrategyDetailDTO {
@ApiModelProperty(notes = "门店列表") @ApiModelProperty(notes = "门店列表")
private List<SopStrategyStoreDTO> stores; private List<SopStrategyStoreDTO> stores;
@ApiModelProperty(notes = "适用门店描述(如:已指定 3 个门店(北京朝阳旗舰店、上海浦东体验中心、广州天河展示店))")
private String storeDescription;
@ApiModelProperty(notes = "第二步条件规则列表(规则条件)") @ApiModelProperty(notes = "第二步条件规则列表(规则条件)")
private List<SopConditionGroupDTO> step2ConditionGroups; private List<SopConditionGroupDTO> step2ConditionGroups;
...@@ -81,4 +84,16 @@ public class SopStrategyDetailDTO { ...@@ -81,4 +84,16 @@ public class SopStrategyDetailDTO {
@ApiModelProperty(notes = "更新时间") @ApiModelProperty(notes = "更新时间")
private Date updatedTime; private Date updatedTime;
@ApiModelProperty(notes = "策略快照JSON(包含完整的触发条件和动作信息)")
private String snapshotJson;
@ApiModelProperty(notes = "基础信息快照")
private SopStrategySnapshotDTO.SnapshotBasicInfo basicInfo;
@ApiModelProperty(notes = "触发条件快照")
private SopStrategySnapshotDTO.SnapshotTriggerInfo triggerInfo;
@ApiModelProperty(notes = "动作快照")
private SopStrategySnapshotDTO.SnapshotActionInfo actionInfo;
} }
\ No newline at end of file \ No newline at end of file
...@@ -88,4 +88,16 @@ public class SopStrategyRecordDetailDTO { ...@@ -88,4 +88,16 @@ public class SopStrategyRecordDetailDTO {
@ApiModelProperty(notes = "客户快照-客户分类") @ApiModelProperty(notes = "客户快照-客户分类")
private String customerCategorySnapshot; private String customerCategorySnapshot;
@ApiModelProperty(notes = "基础信息快照")
private SopStrategySnapshotDTO.SnapshotBasicInfo basicInfo;
@ApiModelProperty(notes = "触发条件快照")
private SopStrategySnapshotDTO.SnapshotTriggerInfo triggerInfo;
@ApiModelProperty(notes = "动作快照")
private SopStrategySnapshotDTO.SnapshotActionInfo actionInfo;
@ApiModelProperty(notes = "消息变量快照")
private java.util.Map<String, Object> messageVariables;
} }
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.dj.strategy.dto.sop;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.List;
@Data
public class SopStrategySnapshotDTO {
@ApiModelProperty(notes = "基础信息")
private SnapshotBasicInfo basicInfo;
@ApiModelProperty(notes = "触发条件信息")
private SnapshotTriggerInfo triggerInfo;
@ApiModelProperty(notes = "动作信息")
private SnapshotActionInfo actionInfo;
@Data
public static class SnapshotBasicInfo {
@ApiModelProperty(notes = "策略名称")
private String strategyName;
@ApiModelProperty(notes = "业务类型")
private Integer bizType;
@ApiModelProperty(notes = "业务类型名称")
private String bizTypeName;
@ApiModelProperty(notes = "门店范围类型")
private Integer storeScopeType;
@ApiModelProperty(notes = "门店范围描述")
private String storeScopeDesc;
@ApiModelProperty(notes = "营销阶段")
private String marketingStage;
@ApiModelProperty(notes = "营销阶段名称")
private String marketingStageName;
@ApiModelProperty(notes = "适用门店描述")
private String storeDescription;
}
@Data
public static class SnapshotTriggerInfo {
@ApiModelProperty(notes = "触发类型")
private String triggerType;
@ApiModelProperty(notes = "触发类型名称")
private String triggerTypeName;
@ApiModelProperty(notes = "日期变量类型")
private String dateVariableType;
@ApiModelProperty(notes = "日期变量名称")
private String dateVariableName;
@ApiModelProperty(notes = "相对日期类型")
private Integer relativeDateType;
@ApiModelProperty(notes = "相对日期描述")
private String relativeDateDesc;
@ApiModelProperty(notes = "相对天数")
private Integer relativeDays;
@ApiModelProperty(notes = "触发小时")
private Integer triggerHour;
@ApiModelProperty(notes = "触发分钟")
private Integer triggerMinute;
@ApiModelProperty(notes = "实际触发时间描述")
private String triggerTimeDesc;
@ApiModelProperty(notes = "动作确认类型")
private Integer actionConfirmType;
@ApiModelProperty(notes = "动作确认描述")
private String actionConfirmDesc;
@ApiModelProperty(notes = "第二步条件组列表")
private List<SnapshotConditionGroup> step2ConditionGroups;
}
@Data
public static class SnapshotActionInfo {
@ApiModelProperty(notes = "分支列表")
private List<SnapshotBranch> branches;
}
@Data
public static class SnapshotConditionGroup {
@ApiModelProperty(notes = "条件组名称")
private String groupName;
@ApiModelProperty(notes = "条件组逻辑:1-AND 2-OR")
private Integer groupLogic;
@ApiModelProperty(notes = "条件组逻辑描述")
private String groupLogicDesc;
@ApiModelProperty(notes = "条件列表")
private List<SnapshotCondition> conditions;
}
@Data
public static class SnapshotCondition {
@ApiModelProperty(notes = "变量编码")
private String variableCode;
@ApiModelProperty(notes = "变量名称")
private String variableName;
@ApiModelProperty(notes = "值类型:1-文本 2-日期 3-数值 4-枚举")
private Integer valueType;
@ApiModelProperty(notes = "操作符:1-等于 2-不等于 3-大于 4-大于等于 5-小于 6-小于等于 7-包含 8-不包含")
private Integer operator;
@ApiModelProperty(notes = "操作符描述")
private String operatorDesc;
@ApiModelProperty(notes = "文本值")
private String textValue;
@ApiModelProperty(notes = "数值")
private String numberValue;
@ApiModelProperty(notes = "日期值")
private String dateValue;
@ApiModelProperty(notes = "枚举值")
private String enumValue;
@ApiModelProperty(notes = "条件表达式描述")
private String conditionDesc;
}
@Data
public static class SnapshotBranch {
@ApiModelProperty(notes = "分支编号")
private Integer branchNo;
@ApiModelProperty(notes = "分支名称")
private String branchName;
@ApiModelProperty(notes = "分支逻辑:1-AND 2-OR")
private Integer branchLogic;
@ApiModelProperty(notes = "分支逻辑描述")
private String branchLogicDesc;
@ApiModelProperty(notes = "条件组列表")
private List<SnapshotConditionGroup> conditionGroups;
@ApiModelProperty(notes = "动作列表")
private List<SnapshotAction> actions;
}
@Data
public static class SnapshotAction {
@ApiModelProperty(notes = "动作名称")
private String actionName;
@ApiModelProperty(notes = "动作类型")
private Integer actionType;
@ApiModelProperty(notes = "动作类型名称")
private String actionTypeName;
@ApiModelProperty(notes = "消息类型")
private Integer messageType;
@ApiModelProperty(notes = "消息类型名称")
private String messageTypeName;
@ApiModelProperty(notes = "消息内容")
private String content;
@ApiModelProperty(notes = "跳转URL")
private String jumpUrl;
@ApiModelProperty(notes = "网页背景色")
private String bgColor;
@ApiModelProperty(notes = "素材配置JSON")
private String materialJson;
@ApiModelProperty(notes = "素材间隔(像素)")
private Integer intervalPx;
}
}
...@@ -68,7 +68,7 @@ public class SopStrategy implements Serializable { ...@@ -68,7 +68,7 @@ public class SopStrategy implements Serializable {
private String dateVariableType; private String dateVariableType;
/** /**
* 相对日期类型:1-购车日 2-生日 3-保养日 * 相对日期类型(0提前/1当前/2推后)
*/ */
@Column(name = "relative_date_type") @Column(name = "relative_date_type")
private Integer relativeDateType; private Integer relativeDateType;
......
...@@ -45,10 +45,10 @@ public class SopStrategyBranch implements Serializable { ...@@ -45,10 +45,10 @@ public class SopStrategyBranch implements Serializable {
private Integer branchOrder; private Integer branchOrder;
/** /**
* 分支逻辑: true-并集(满足任一条件组) false-交集(需满足所有条件组) * 分支逻辑:1-并集(满足任一条件组) 0-交集(需满足所有条件组)
*/ */
@Column(name = "branch_logic") @Column(name = "branch_logic")
private Boolean branchLogic; private Integer branchLogic;
/** /**
* 步骤:2-第二步(规则条件) 3-第三步(动作条件) * 步骤:2-第二步(规则条件) 3-第三步(动作条件)
......
...@@ -80,6 +80,12 @@ public class SopStrategyExecutionRecord implements Serializable { ...@@ -80,6 +80,12 @@ public class SopStrategyExecutionRecord implements Serializable {
private String executeDesc; private String executeDesc;
/** /**
* 执行快照信息JSON(包含策略信息、客户信息、触发条件、执行动作、消息内容等)
*/
@Column(name = "snapshot_info", columnDefinition = "text")
private String snapshotInfo;
/**
* 删除标志:N-未删除 D-已删除 * 删除标志:N-未删除 D-已删除
*/ */
@Column(name = "deleted_flag") @Column(name = "deleted_flag")
......
...@@ -6,15 +6,16 @@ import com.dangdang.ddframe.job.api.simple.SimpleJob; ...@@ -6,15 +6,16 @@ import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.RequiredArgsConstructor; import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.oreframework.boot.autoconfigure.elasticjob.annotation.ElasticJobConf; import org.oreframework.boot.autoconfigure.elasticjob.annotation.ElasticJobConf;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
@Service @Service
@Slf4j @Slf4j
@ElasticJobConf(name = "SopStrategyTriggerJob", cron = "0 0 2 * * ?", description = "营销SOP每日客户筛选定时任务", overwrite = false) @ElasticJobConf(name = "SopStrategyTriggerJob", cron = "0 0 2 * * ?", description = "营销SOP每日客户筛选定时任务", overwrite = false)
@RequiredArgsConstructor
public class SopStrategyTriggerJob implements SimpleJob { public class SopStrategyTriggerJob implements SimpleJob {
private final SopStrategyTriggerService sopStrategyTriggerService; @Autowired
private SopStrategyTriggerService sopStrategyTriggerService;
@Override @Override
public void execute(ShardingContext shardingContext) { public void execute(ShardingContext shardingContext) {
......
...@@ -5,13 +5,12 @@ import cn.com.glsx.dj.strategy.model.sop.SopStrategyCondition; ...@@ -5,13 +5,12 @@ import cn.com.glsx.dj.strategy.model.sop.SopStrategyCondition;
import cn.com.glsx.dj.strategy.model.sop.SopStrategyConditionGroup; import cn.com.glsx.dj.strategy.model.sop.SopStrategyConditionGroup;
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.Date; import java.util.Date;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
@Slf4j @Slf4j
@Component @Component
...@@ -23,10 +22,10 @@ public class SopConditionEngine { ...@@ -23,10 +22,10 @@ public class SopConditionEngine {
return true; return true;
} }
Boolean branchLogic = branch.getBranchLogic(); Integer branchLogic = branch.getBranchLogic();
for (SopStrategyConditionGroup group : conditionGroups) { for (SopStrategyConditionGroup group : conditionGroups) {
boolean groupResult = evaluateConditionGroup(group, contextVariables); boolean groupResult = evaluateConditionGroup(group, contextVariables);
if (branchLogic != null && branchLogic) { if (branchLogic != null && branchLogic==1) {
if (!groupResult) { if (!groupResult) {
return false; return false;
} }
...@@ -37,7 +36,7 @@ public class SopConditionEngine { ...@@ -37,7 +36,7 @@ public class SopConditionEngine {
} }
} }
return branchLogic != null && branchLogic; return branchLogic != null && branchLogic == 1;
} }
public boolean evaluateConditionGroup(SopStrategyConditionGroup group, Map<String, Object> contextVariables) { public boolean evaluateConditionGroup(SopStrategyConditionGroup group, Map<String, Object> contextVariables) {
......
package cn.com.glsx.dj.strategy.service; package cn.com.glsx.dj.strategy.service;
import cn.com.glsx.dj.strategy.dto.sop.CandidateCustomerDTO; import cn.com.glsx.dj.strategy.dto.sop.CandidateCustomerDTO;
import cn.com.glsx.dj.strategy.exception.BusinessException;
import cn.com.glsx.dj.strategy.mapper.sop.SopStrategyBranchMapper; import cn.com.glsx.dj.strategy.mapper.sop.SopStrategyBranchMapper;
import cn.com.glsx.dj.strategy.mapper.sop.SopStrategyConditionGroupMapper; import cn.com.glsx.dj.strategy.mapper.sop.SopStrategyConditionGroupMapper;
import cn.com.glsx.dj.strategy.mapper.sop.SopStrategyConditionMapper; import cn.com.glsx.dj.strategy.mapper.sop.SopStrategyConditionMapper;
...@@ -169,19 +170,13 @@ public class SopCustomerQueryService { ...@@ -169,19 +170,13 @@ public class SopCustomerQueryService {
} }
boolean result; boolean result;
if (step != null) {
Map<String, Object> customer = getCustomerById(customerInstanceId, strategy); Map<String, Object> customer = getCustomerById(customerInstanceId, strategy);
if (customer != null) { if (customer != null) {
customer.put("triggerDate", new Date()); customer.put("triggerDate", new Date());
result = sopDynamicSqlService.executeConditionValidationFromSnapshot(customer, branches); result = sopDynamicSqlService.executeConditionValidationFromSnapshot(customer, branches);
log.info("使用快照数据条件验证结果: {}, strategyId:{}, customerInstanceId:{}, step:{}", result, strategy.getId(), customerInstanceId, step); log.info("使用快照数据条件验证结果: {}, strategyId:{}, customerInstanceId:{}, step:{}", result, strategy.getId(), customerInstanceId, step);
} else { } else {
result = sopDynamicSqlService.executeConditionValidation(customerInstanceId, branches); throw new BusinessException("客户不存在");
log.info("客户数据为空,使用数据库条件验证结果: {}, strategyId:{}, customerInstanceId:{}, step:{}", result, strategy.getId(), customerInstanceId, step);
}
} else {
result = sopDynamicSqlService.executeConditionValidation(customerInstanceId, branches);
log.info("条件验证结果: {}, strategyId:{}, customerInstanceId:{}, step:{}", result, strategy.getId(), customerInstanceId, step);
} }
return result; return result;
......
...@@ -247,185 +247,6 @@ public class SopDynamicSqlService { ...@@ -247,185 +247,6 @@ public class SopDynamicSqlService {
return condition.toString(); return condition.toString();
} }
public boolean executeConditionValidation(Long customerInstanceId, List<SopStrategyBranch> branches) {
if (CollUtil.isEmpty(branches)) {
return true;
}
String validationSql = buildConditionValidationSql(customerInstanceId, branches);
if (StrUtil.isBlank(validationSql)) {
return true;
}
log.info("执行条件验证SQL: {}", validationSql);
try {
SqlSession sqlSession = sqlSessionTemplate.getSqlSessionFactory().openSession();
try {
List<Map<String, Object>> result = sqlSession.selectList("", validationSql);
return CollUtil.isNotEmpty(result);
} finally {
sqlSession.close();
}
} catch (Exception e) {
log.error("执行条件验证SQL失败: {}", e.getMessage(), e);
throw new SopStrategyException("执行条件验证SQL失败: " + e.getMessage());
}
}
public String buildConditionValidationSql(Long customerInstanceId, List<SopStrategyBranch> branches) {
if (CollUtil.isEmpty(branches)) {
return "";
}
StringBuilder sql = new StringBuilder();
sql.append("SELECT 1 FROM scrm_customer_instance ci WHERE ci.customer_instance_id = ").append(customerInstanceId);
List<String> branchConditions = new ArrayList<>();
for (SopStrategyBranch branch : branches) {
String branchCondition = buildBranchCondition(branch);
if (StrUtil.isNotBlank(branchCondition)) {
branchConditions.add("(" + branchCondition + ")");
}
}
if (CollUtil.isNotEmpty(branchConditions)) {
Boolean branchLogic = branches.get(0).getBranchLogic();
String logicOperator = (branchLogic != null && branchLogic) ? " AND " : " OR ";
sql.append(" AND (").append(String.join(logicOperator, branchConditions)).append(")");
}
sql.append(" AND ci.deleted_flag = 'N' LIMIT 1");
return sql.toString();
}
private String buildBranchCondition(SopStrategyBranch branch) {
List<SopStrategyConditionGroup> conditionGroups = branch.getConditionGroups();
if (CollUtil.isEmpty(conditionGroups)) {
return "";
}
List<String> groupConditions = new ArrayList<>();
for (SopStrategyConditionGroup group : conditionGroups) {
String groupCondition = buildGroupCondition(group);
if (StrUtil.isNotBlank(groupCondition)) {
groupConditions.add("(" + groupCondition + ")");
}
}
if (CollUtil.isEmpty(groupConditions)) {
return "";
}
Integer groupLogic = conditionGroups.get(0).getGroupLogic();
String logicOperator = (groupLogic != null && groupLogic == 1) ? " AND " : " OR ";
return String.join(logicOperator, groupConditions);
}
private String buildGroupCondition(SopStrategyConditionGroup group) {
List<SopStrategyCondition> conditions = group.getConditions();
if (CollUtil.isEmpty(conditions)) {
return "";
}
List<String> conditionExpressions = new ArrayList<>();
for (SopStrategyCondition condition : conditions) {
String conditionExpr = buildConditionExpression(condition);
if (StrUtil.isNotBlank(conditionExpr)) {
conditionExpressions.add(conditionExpr);
}
}
if (CollUtil.isEmpty(conditionExpressions)) {
return "";
}
Integer groupLogic = group.getGroupLogic();
String logicOperator = (groupLogic != null && groupLogic == 1) ? " AND " : " OR ";
return String.join(logicOperator, conditionExpressions);
}
private String buildConditionExpression(SopStrategyCondition condition) {
String sqlFragment = condition.getVariableName();
Integer operator = condition.getOperator();
Integer valueType = condition.getValueType();
Integer valueSource = condition.getValueSource();
if (StrUtil.isBlank(sqlFragment)) {
log.warn("条件变量SQL片段为空, variableCode:{}, variableName:{}",
condition.getVariableCode(), condition.getVariableName());
return "";
}
String sqlOperator = convertOperator(operator);
if (StrUtil.isBlank(sqlOperator)) {
log.warn("未知运算符, operator:{}", operator);
return "";
}
if (valueSource != null && valueSource == 1) {
String variableRefCode = condition.getVariableRefCode();
if (StrUtil.isNotBlank(variableRefCode)) {
return buildVariableCompareSql(sqlFragment, sqlOperator, variableRefCode);
}
}
String value = getConditionValue(condition, valueType);
if (StrUtil.isBlank(value)) {
log.warn("条件值为空, variableCode:{}, valueType:{}",
condition.getVariableCode(), valueType);
return "";
}
return buildConditionSql(sqlFragment, sqlOperator, value);
}
private String buildVariableCompareSql(String leftFragment, String operator, String rightVariableCode) {
StringBuilder condition = new StringBuilder();
condition.append(leftFragment);
condition.append(" ").append(operator).append(" ");
condition.append("ci.").append(rightVariableCode.toLowerCase());
return condition.toString();
}
private String getConditionValue(SopStrategyCondition condition, Integer valueType) {
switch (valueType != null ? valueType : 1) {
case 1:
return condition.getTextValue();
case 2:
return condition.getNumberValue();
case 3:
return condition.getDateValue();
case 4:
return condition.getEnumValue();
default:
return condition.getTextValue();
}
}
private String convertOperator(Integer operator) {
switch (operator != null ? operator : 1) {
case 1:
return "=";
case 2:
return "!=";
case 3:
return ">";
case 4:
return ">=";
case 5:
return "<";
case 6:
return "<=";
case 7:
return "LIKE";
case 8:
return "NOT LIKE";
default:
return "=";
}
}
public boolean executeConditionValidationFromSnapshot(Map<String, Object> snapshotData, List<SopStrategyBranch> branches) { public boolean executeConditionValidationFromSnapshot(Map<String, Object> snapshotData, List<SopStrategyBranch> branches) {
if (CollUtil.isEmpty(branches)) { if (CollUtil.isEmpty(branches)) {
...@@ -435,10 +256,10 @@ public class SopDynamicSqlService { ...@@ -435,10 +256,10 @@ public class SopDynamicSqlService {
log.info("使用快照数据进行条件验证, branchCount:{}, snapshotDataKeys:{}", log.info("使用快照数据进行条件验证, branchCount:{}, snapshotDataKeys:{}",
branches.size(), snapshotData.keySet()); branches.size(), snapshotData.keySet());
Boolean branchLogic = branches.get(0).getBranchLogic(); Integer branchLogic = branches.get(0).getBranchLogic();
for (SopStrategyBranch branch : branches) { for (SopStrategyBranch branch : branches) {
boolean branchResult = conditionEngine.evaluateBranch(branch, snapshotData); boolean branchResult = conditionEngine.evaluateBranch(branch, snapshotData);
if (branchLogic != null && branchLogic) { if (branchLogic != null && branchLogic== 1) {
if (!branchResult) { if (!branchResult) {
return false; return false;
} }
...@@ -449,6 +270,6 @@ public class SopDynamicSqlService { ...@@ -449,6 +270,6 @@ public class SopDynamicSqlService {
} }
} }
return branchLogic != null && branchLogic; return branchLogic != null && branchLogic == 1;
} }
} }
\ No newline at end of file \ No newline at end of file
...@@ -7,11 +7,18 @@ import cn.com.glsx.dj.strategy.mapper.sop.SopStrategyConditionGroupMapper; ...@@ -7,11 +7,18 @@ import cn.com.glsx.dj.strategy.mapper.sop.SopStrategyConditionGroupMapper;
import cn.com.glsx.dj.strategy.mapper.sop.SopStrategyConditionMapper; import cn.com.glsx.dj.strategy.mapper.sop.SopStrategyConditionMapper;
import cn.com.glsx.dj.strategy.mapper.sop.SopStrategyExecutionRecordMapper; import cn.com.glsx.dj.strategy.mapper.sop.SopStrategyExecutionRecordMapper;
import cn.com.glsx.dj.strategy.mapper.sop.SopStrategyMapper; import cn.com.glsx.dj.strategy.mapper.sop.SopStrategyMapper;
import cn.com.glsx.dj.strategy.mapper.sop.SopStrategyMetaConditionVariableMapper;
import cn.com.glsx.dj.strategy.mapper.sop.SopStrategyMetaMarketingStageMapper;
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.mapper.sop.SopStrategyTaskMapper;
import cn.com.glsx.dj.strategy.model.sop.*; 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;
...@@ -50,6 +57,9 @@ public class SopStrategyExecutionService { ...@@ -50,6 +57,9 @@ public class SopStrategyExecutionService {
private SopStrategyExecutionRecordMapper sopStrategyExecutionRecordMapper; private SopStrategyExecutionRecordMapper sopStrategyExecutionRecordMapper;
@Autowired @Autowired
private SopStrategySnapshotCacheService sopStrategySnapshotCacheService;
@Autowired
private SopConditionEngine conditionEngine; private SopConditionEngine conditionEngine;
@Autowired @Autowired
...@@ -64,6 +74,18 @@ public class SopStrategyExecutionService { ...@@ -64,6 +74,18 @@ public class SopStrategyExecutionService {
@Autowired @Autowired
private SopMessageVariableResolverService sopMessageVariableResolverService; private SopMessageVariableResolverService sopMessageVariableResolverService;
@Autowired
private SopStrategyMetaMarketingStageMapper metaMarketingStageMapper;
@Autowired
private SopStrategyMetaTriggerMapper metaTriggerMapper;
@Autowired
private SopStrategyMetaConditionVariableMapper metaConditionVariableMapper;
@Autowired
private SopStrategyStoreRelMapper sopStrategyStoreRelMapper;
private static final Integer STEP_3 = 3; private static final Integer STEP_3 = 3;
private static final String DESC_SUCCESS = "执行成功"; private static final String DESC_SUCCESS = "执行成功";
private static final String DESC_TIMEOUT = "超时未确认"; private static final String DESC_TIMEOUT = "超时未确认";
...@@ -142,14 +164,14 @@ public class SopStrategyExecutionService { ...@@ -142,14 +164,14 @@ public class SopStrategyExecutionService {
try { try {
executeStrategy(task.getStrategyId(), task.getCustomerInstanceId(), contextVariables); executeStrategy(task.getStrategyId(), task.getCustomerInstanceId(), contextVariables);
updateTaskStatus(taskId, 2); updateTaskStatus(taskId, 2);
saveExecutionRecord(task, 1, DESC_SUCCESS, null); saveExecutionRecord(task, 1, DESC_SUCCESS, contextVariables, strategy, 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); updateTaskStatus(taskId, 3);
String executeDesc = resolveExecuteDesc(e); String executeDesc = resolveExecuteDesc(e);
saveExecutionRecord(task, 2, executeDesc, e); saveExecutionRecord(task, 2, executeDesc, contextVariables, strategy, e);
} }
} }
...@@ -247,7 +269,8 @@ public class SopStrategyExecutionService { ...@@ -247,7 +269,8 @@ public class SopStrategyExecutionService {
@GlsxDistributeLockable(name = "'SopStrategyExecutionService_saveExecutionRecord_' + #task.id", @GlsxDistributeLockable(name = "'SopStrategyExecutionService_saveExecutionRecord_' + #task.id",
time = 5, timeUnit = TimeUnit.MINUTES, timeoutException = Exception.class) time = 5, timeUnit = TimeUnit.MINUTES, timeoutException = Exception.class)
public void saveExecutionRecord(SopStrategyTask task, Integer executeStatus, String executeDesc, Exception e) { public void saveExecutionRecord(SopStrategyTask task, Integer executeStatus, String executeDesc,
Map<String, Object> contextVariables, SopStrategy strategy, Exception e) {
SopStrategyExecutionRecord record = new SopStrategyExecutionRecord(); SopStrategyExecutionRecord record = new SopStrategyExecutionRecord();
record.setStrategyId(task.getStrategyId()); record.setStrategyId(task.getStrategyId());
record.setTaskId(task.getId()); record.setTaskId(task.getId());
...@@ -257,6 +280,10 @@ public class SopStrategyExecutionService { ...@@ -257,6 +280,10 @@ public class SopStrategyExecutionService {
record.setExecuteStatus(executeStatus); record.setExecuteStatus(executeStatus);
record.setExecuteDesc(executeDesc); record.setExecuteDesc(executeDesc);
record.setErrorMessage(getFullStackTrace(e)); record.setErrorMessage(getFullStackTrace(e));
SopStrategySnapshotCacheService.StrategyDetailCache cache = sopStrategySnapshotCacheService.loadStrategyDetail(task.getStrategyId());
record.setSnapshotInfo(sopStrategySnapshotCacheService.buildSnapshotJson(task, cache, contextVariables));
record.setDeletedFlag("N"); record.setDeletedFlag("N");
record.setCreatedDate(new Date()); record.setCreatedDate(new Date());
sopStrategyExecutionRecordMapper.insertSelective(record); sopStrategyExecutionRecordMapper.insertSelective(record);
......
...@@ -44,6 +44,7 @@ public class StrategySopService { ...@@ -44,6 +44,7 @@ public class StrategySopService {
private final SopStrategyTaskMapper sopStrategyTaskMapper; private final SopStrategyTaskMapper sopStrategyTaskMapper;
private final SopStrategyExecutionService sopStrategyExecutionService; private final SopStrategyExecutionService sopStrategyExecutionService;
private final SopStrategyEventLogService sopStrategyEventLogService; private final SopStrategyEventLogService sopStrategyEventLogService;
private final SopStrategySnapshotCacheService sopStrategySnapshotCacheService;
private final ObjectMapper objectMapper; private final ObjectMapper objectMapper;
@Transactional @Transactional
...@@ -101,6 +102,7 @@ public class StrategySopService { ...@@ -101,6 +102,7 @@ public class StrategySopService {
saveStrategyBranches(request.getStrategyId(), request.getBranches(), updatedBy); saveStrategyBranches(request.getStrategyId(), request.getBranches(), updatedBy);
sopStrategyEventLogService.recordSubmitChangeEvent(request.getStrategyId(), null); sopStrategyEventLogService.recordSubmitChangeEvent(request.getStrategyId(), null);
sopStrategySnapshotCacheService.evictStrategyCache(request.getStrategyId());
log.info("更新策略成功, strategyId:{}, version:{}", request.getStrategyId(), strategy.getVersion()); log.info("更新策略成功, strategyId:{}, version:{}", request.getStrategyId(), strategy.getVersion());
return true; return true;
} }
...@@ -136,6 +138,7 @@ public class StrategySopService { ...@@ -136,6 +138,7 @@ public class StrategySopService {
sopStrategyStoreRelMapper.deleteByStrategyId(strategyId); sopStrategyStoreRelMapper.deleteByStrategyId(strategyId);
sopStrategyBranchMapper.deleteByStrategyId(strategyId); sopStrategyBranchMapper.deleteByStrategyId(strategyId);
sopStrategySnapshotCacheService.evictStrategyCache(strategyId);
log.info("删除策略成功, strategyId:{}", strategyId); log.info("删除策略成功, strategyId:{}", strategyId);
return true; return true;
} }
......
...@@ -37,7 +37,7 @@ public class SopConditionEngineTest { ...@@ -37,7 +37,7 @@ public class SopConditionEngineTest {
@Test @Test
public void testEvaluateBranch_BranchLogicAnd_AllGroupsMatch() { public void testEvaluateBranch_BranchLogicAnd_AllGroupsMatch() {
SopStrategyBranch branch = new SopStrategyBranch(); SopStrategyBranch branch = new SopStrategyBranch();
branch.setBranchLogic(true); branch.setBranchLogic(1);
List<SopStrategyConditionGroup> groups = new ArrayList<>(); List<SopStrategyConditionGroup> groups = new ArrayList<>();
groups.add(createConditionGroup(1, createCondition("name", "张三"))); groups.add(createConditionGroup(1, createCondition("name", "张三")));
...@@ -55,7 +55,7 @@ public class SopConditionEngineTest { ...@@ -55,7 +55,7 @@ public class SopConditionEngineTest {
@Test @Test
public void testEvaluateBranch_BranchLogicAnd_OneGroupNotMatch() { public void testEvaluateBranch_BranchLogicAnd_OneGroupNotMatch() {
SopStrategyBranch branch = new SopStrategyBranch(); SopStrategyBranch branch = new SopStrategyBranch();
branch.setBranchLogic(true); branch.setBranchLogic(1);
List<SopStrategyConditionGroup> groups = new ArrayList<>(); List<SopStrategyConditionGroup> groups = new ArrayList<>();
groups.add(createConditionGroup(1, createCondition("name", "张三"))); groups.add(createConditionGroup(1, createCondition("name", "张三")));
...@@ -73,7 +73,7 @@ public class SopConditionEngineTest { ...@@ -73,7 +73,7 @@ public class SopConditionEngineTest {
@Test @Test
public void testEvaluateBranch_BranchLogicOr_OneGroupMatch() { public void testEvaluateBranch_BranchLogicOr_OneGroupMatch() {
SopStrategyBranch branch = new SopStrategyBranch(); SopStrategyBranch branch = new SopStrategyBranch();
branch.setBranchLogic(false); branch.setBranchLogic(1);
List<SopStrategyConditionGroup> groups = new ArrayList<>(); List<SopStrategyConditionGroup> groups = new ArrayList<>();
groups.add(createConditionGroup(1, createCondition("name", "李四"))); groups.add(createConditionGroup(1, createCondition("name", "李四")));
...@@ -91,7 +91,7 @@ public class SopConditionEngineTest { ...@@ -91,7 +91,7 @@ public class SopConditionEngineTest {
@Test @Test
public void testEvaluateBranch_BranchLogicOr_NoGroupMatch() { public void testEvaluateBranch_BranchLogicOr_NoGroupMatch() {
SopStrategyBranch branch = new SopStrategyBranch(); SopStrategyBranch branch = new SopStrategyBranch();
branch.setBranchLogic(false); branch.setBranchLogic(1);
List<SopStrategyConditionGroup> groups = new ArrayList<>(); List<SopStrategyConditionGroup> groups = new ArrayList<>();
groups.add(createConditionGroup(1, createCondition("name", "李四"))); groups.add(createConditionGroup(1, createCondition("name", "李四")));
......
...@@ -300,17 +300,10 @@ public class StrategySopServiceTest { ...@@ -300,17 +300,10 @@ public class StrategySopServiceTest {
@Test @Test
public void testUpdateSopStrategyStatus_Success() { public void testUpdateSopStrategyStatus_Success() {
SopStrategy strategy = new SopStrategy();
strategy.setId(1);
strategy.setStatus(0);
when(sopStrategyMapper.selectByPrimaryKey(1)).thenReturn(strategy);
when(sopStrategyMapper.updateByPrimaryKeySelective(any(SopStrategy.class))).thenReturn(1);
Boolean result = strategySopService.updateSopStrategyStatus(1, 1, "admin"); Boolean result = strategySopService.updateSopStrategyStatus(4, 1, "admin");
assertTrue(result); assertTrue(result);
assertEquals(1, strategy.getStatus().intValue());
} }
@Test(expected = SopStrategyException.class) @Test(expected = SopStrategyException.class)
...@@ -464,65 +457,4 @@ public class StrategySopServiceTest { ...@@ -464,65 +457,4 @@ public class StrategySopServiceTest {
verify(sopStrategyEventLogService, times(1)).recordH5PageViewEvent( verify(sopStrategyEventLogService, times(1)).recordH5PageViewEvent(
eq(1), eq(100L), eq(200L), eq("门店A"), eq("张三"), eq("13800138000")); eq(1), eq(100L), eq(200L), eq("门店A"), eq("张三"), eq("13800138000"));
} }
@Test
public void testGetMarketingPageRenderData_Success() {
SopStrategyActionMapper actionMapper = mock(SopStrategyActionMapper.class);
SopStrategyActionMediaMapper mediaMapper = mock(SopStrategyActionMediaMapper.class);
ObjectMapper mapper = new ObjectMapper();
StrategySopService service = new StrategySopService(
mock(SopStrategyMapper.class),
mock(SopStrategyStoreRelMapper.class),
mock(SopStrategyBranchMapper.class),
mock(SopStrategyConditionGroupMapper.class),
mock(SopStrategyConditionMapper.class),
actionMapper,
mediaMapper,
mock(SopStrategyTaskMapper.class),
mock(SopStrategyExecutionService.class),
mock(SopStrategyEventLogService.class),
mapper
);
cn.com.glsx.dj.strategy.model.sop.SopStrategyAction action = new cn.com.glsx.dj.strategy.model.sop.SopStrategyAction();
action.setId(1);
action.setContent("测试页面");
action.setDeletedFlag("N");
when(actionMapper.selectByPrimaryKey(1)).thenReturn(action);
when(mediaMapper.selectByActionId(1)).thenReturn(Collections.emptyList());
java.util.Map<String, Object> result = service.getMarketingPageRenderData(1);
assertNotNull(result);
assertEquals("测试页面", result.get("pageTitle"));
assertEquals("#ffffff", result.get("bgColor"));
assertEquals(0, result.get("intervalPx"));
}
@Test
public void testGetMarketingPageRenderData_ActionNotExist() {
SopStrategyActionMapper actionMapper = mock(SopStrategyActionMapper.class);
StrategySopService service = new StrategySopService(
mock(SopStrategyMapper.class),
mock(SopStrategyStoreRelMapper.class),
mock(SopStrategyBranchMapper.class),
mock(SopStrategyConditionGroupMapper.class),
mock(SopStrategyConditionMapper.class),
actionMapper,
mock(SopStrategyActionMediaMapper.class),
mock(SopStrategyTaskMapper.class),
mock(SopStrategyExecutionService.class),
mock(SopStrategyEventLogService.class),
new ObjectMapper()
);
when(actionMapper.selectByPrimaryKey(999)).thenReturn(null);
java.util.Map<String, Object> result = service.getMarketingPageRenderData(999);
assertNull(result);
}
} }
\ No newline at end of file \ No newline at end of file
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!