Commit 5ddfc559 by zhouhaibao

refactor(strategy): 优化策略执行和客户查询服务

- 修改 queryCandidateCustomers 方法返回类型为 List<Long>
- 使用 JdbcTemplate 替代 SqlSession 执行安全的 SQL 查询
- 将 executeCustomerQueryWithStoreFilter 方法返回类型改为 List<Long>
- 修复 SopStrategyMapper.xml 中的结果映射配置
- 更新 SopStrategyTriggerService 中的客户查询逻辑
- 修改 SopTriggerTypeEnum 枚举值类型为 String
- 移除 StrategySopQueryService 中未使用的方法
- 更新测试类中的方法调用和数据类型
- 修复执行记录查询接口的返回类型定义
1 parent 23efe54f
Showing 17 changed files with 122 additions and 59 deletions
......@@ -10,12 +10,12 @@ import java.util.Map;
@AllArgsConstructor
public enum SopTriggerTypeEnum {
DATE_TIME(2, "到达特定日期时间");
DATE_TIME("DATE_TIME", "到达特定日期时间");
private final Integer value;
private final String value;
private final String displayName;
private static final Map<Integer, SopTriggerTypeEnum> ENUM_MAP = new HashMap<>();
private static final Map<String, SopTriggerTypeEnum> ENUM_MAP = new HashMap<>();
static {
for (SopTriggerTypeEnum code : SopTriggerTypeEnum.values()) {
......@@ -23,7 +23,7 @@ public enum SopTriggerTypeEnum {
}
}
public static SopTriggerTypeEnum getEnum(Integer value) {
public static SopTriggerTypeEnum getEnum(String value) {
return ENUM_MAP.get(value);
}
}
\ No newline at end of file
......@@ -92,7 +92,7 @@ public class SopStrategy implements Serializable {
private Integer triggerMinute;
/**
* 动作确认类型:1-自动执行 2-需确认
* 动作确认类型:-1 自动执行 0 需确认
*/
@Column(name = "action_confirm_type", nullable = false)
private Integer actionConfirmType;
......
......@@ -2,7 +2,6 @@ package cn.com.glsx.dj.strategy.remote;
import cn.com.glsx.dj.strategy.dto.sop.*;
import cn.com.glsx.dj.strategy.model.sop.SopStrategy;
import cn.com.glsx.dj.strategy.model.sop.SopStrategyExecutionRecord;
import cn.com.glsx.framework.core.annotation.ApiMethod;
import cn.com.glsx.framework.core.annotation.ApiParam;
import cn.com.glsx.framework.core.annotation.ApiResponse;
......@@ -50,7 +49,7 @@ public interface SopStrategyRemote {
@ApiMethod("查询策略执行记录")
@ApiParam(name = "pagination", notes = "分页查询条件", dataType = ApiParam.DataTypeEnum.OBJECT, required = true)
@ApiResponse("查询策略执行记录")
RpcResponse<RpcPagination<SopStrategyExecutionRecord>> listSopStrategyRecords(RpcPagination<SopStrategyRecordReqDTO> pagination);
RpcResponse<RpcPagination<SopStrategyRecordDTO>> listSopStrategyRecords(RpcPagination<SopStrategyRecordReqDTO> pagination);
@ApiMethod("查询策略执行详情")
@ApiParam(name = "recordId", notes = "执行记录ID", dataType = ApiParam.DataTypeEnum.LONG, required = true)
......
......@@ -17,5 +17,5 @@ public interface SopStrategyExecutionRecordMapper extends OreMapper<SopStrategyE
List<SopStrategyExecutionRecord> selectByCustomerInstanceId(@Param("customerInstanceId") Long customerInstanceId);
List<SopStrategyExecutionRecord> selectPageByStrategyId( @Param("condition") SopStrategyRecordReqDTO sopStrategyRecordReqDTO);
List<SopStrategyExecutionRecord> selectPageByStrategyId(@Param("condition") SopStrategyRecordReqDTO condition);
}
\ No newline at end of file
......@@ -14,5 +14,5 @@ public interface SopStrategyMapper extends OreMapper<SopStrategy> {
SopStrategy selectByCode(@Param("strategyCode") String strategyCode);
List<SopStrategy> selectEnabledStrategies(@Param("triggerType") Integer triggerType);
List<SopStrategy> selectEnabledStrategies(@Param("triggerType") String triggerType);
}
\ No newline at end of file
......@@ -3,7 +3,6 @@ package cn.com.glsx.dj.strategy.remote;
import cn.com.glsx.dj.strategy.dto.sop.*;
import cn.com.glsx.dj.strategy.model.sop.SopStrategy;
import cn.com.glsx.dj.strategy.model.sop.SopStrategyExecutionRecord;
import cn.com.glsx.dj.strategy.remote.SopStrategyRemote;
import cn.com.glsx.dj.strategy.service.StrategySopQueryService;
import cn.com.glsx.dj.strategy.service.StrategySopService;
import cn.com.glsx.framework.core.beans.rpc.RpcPagination;
......@@ -11,8 +10,6 @@ import cn.com.glsx.framework.core.beans.rpc.RpcResponse;
import cn.com.glsx.framework.core.exception.RpcServiceException;
import cn.hutool.core.bean.BeanUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboService;
......@@ -138,7 +135,7 @@ public class SopStrategyRemoteImpl implements SopStrategyRemote {
}
@Override
public RpcResponse<RpcPagination<SopStrategyExecutionRecord>> listSopStrategyRecords(RpcPagination<SopStrategyRecordReqDTO> pagination) {
public RpcResponse<RpcPagination<SopStrategyRecordDTO>> listSopStrategyRecords(RpcPagination<SopStrategyRecordReqDTO> pagination) {
try {
log.info("营销SOP-策略执行记录查询:{}", pagination);
......
......@@ -46,12 +46,12 @@ public class SopCustomerQueryService {
@Autowired
private SopCustomerSnapshotService sopCustomerSnapshotService;
public List<CandidateCustomerDTO> queryCandidateCustomers(SopStrategy strategy) {
public List<Long> queryCandidateCustomers(SopStrategy strategy) {
log.info("查询满足条件的客户, strategyId:{}, strategyName:{}, bizType:{}, marketingStage:{}, triggerType:{}",
strategy.getId(), strategy.getStrategyName(), strategy.getBizType(),
strategy.getMarketingStage(), strategy.getTriggerType());
List<CandidateCustomerDTO> customers;
List<Long> customers;
String marketingStageCode = strategy.getMarketingStage();
Integer storeScopeType = strategy.getStoreScopeType();
......
......@@ -7,11 +7,16 @@ import cn.com.glsx.dj.strategy.model.sop.SopStrategyCondition;
import cn.com.glsx.dj.strategy.model.sop.SopStrategyConditionGroup;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.session.SqlSession;
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
......@@ -39,6 +44,9 @@ public class SopDynamicSqlService {
Pattern.CASE_INSENSITIVE
);
@Autowired
private JdbcTemplate jdbcTemplate;
public List<CandidateCustomerDTO> executeCustomerQuery(String sqlTemplate, Map<String, Object> params) {
if (StrUtil.isBlank(sqlTemplate)) {
log.warn("SQL模板为空");
......@@ -72,28 +80,27 @@ public class SopDynamicSqlService {
validateSql(sqlTemplate);
Map<String, Object> params = new HashMap<>();
params.put("customerInstanceId", customerInstanceId);
String executableSql = replacePlaceholders(sqlTemplate, params);
// 1. 使用预编译占位符,彻底杜绝 SQL 注入
// 假设 sqlTemplate 中的占位符是 ? 或者 :customerInstanceId
// 这里以 JdbcTemplate 支持的命名参数为例(更推荐)
String executableSql = sqlTemplate.replace(":customerInstanceId", "?");
log.info("执行单客户查询SQL: {}", executableSql);
log.info("执行单客户查询SQL: {}, 参数: {}", executableSql, customerInstanceId);
try {
SqlSession sqlSession = sqlSessionTemplate.getSqlSessionFactory().openSession();
try {
List<Map<String, Object>> result = sqlSession.selectList("", executableSql);
return CollUtil.isNotEmpty(result) ? result.get(0) : null;
} finally {
sqlSession.close();
}
// 2. 使用 JdbcTemplate 安全执行(自动管理连接,无需手动 openSession)
List<Map<String, Object>> resultList = jdbcTemplate.queryForList(executableSql, customerInstanceId);
// 3. 安全地返回第一条数据,避免空指针
return CollUtil.isNotEmpty(resultList) ? resultList.get(0) : null;
} catch (Exception e) {
log.error("执行单客户查询SQL失败: {}", e.getMessage(), e);
throw new SopStrategyException("执行单客户查询SQL失败: " + e.getMessage());
}
}
public List<CandidateCustomerDTO> executeCustomerQueryWithStoreFilter(String sqlTemplate, List<Long> storeIds) {
public List<Long> executeCustomerQueryWithStoreFilter(String sqlTemplate, List<Long> storeIds) {
if (StrUtil.isBlank(sqlTemplate)) {
log.warn("SQL模板为空");
return CollUtil.newArrayList();
......@@ -113,21 +120,31 @@ public class SopDynamicSqlService {
}
storeIdList.append(")");
executableSql = sqlTemplate + " AND ci.store_id IN " + storeIdList;
executableSql = sqlTemplate + " AND ci.merchant_id IN " + storeIdList;
}
log.info("执行动态SQL(带门店过滤): {}", executableSql);
SqlSession sqlSession = sqlSessionTemplate.getSqlSessionFactory().openSession();
try {
SqlSession sqlSession = sqlSessionTemplate.getSqlSessionFactory().openSession();
try {
return sqlSession.selectList("", executableSql);
} finally {
sqlSession.close();
// 使用 MyBatis 执行原生 SQL 的正确姿势:
// 获取底层 Connection 执行,或者使用 MyBatis 的 selectList 重载
// 实际上,可以直接使用 sqlSession.selectList 的 StatementHandler 重载,
// 但最简单的是使用底层 JDBC:
Connection conn = sqlSession.getConnection();
PreparedStatement ps = conn.prepareStatement(executableSql);
ResultSet rs = ps.executeQuery();
List<Long> result = new java.util.ArrayList<>();
while (rs.next()) {
result.add(rs.getLong("customer_instance_id"));
}
return result;
} catch (Exception e) {
log.error("执行动态SQL失败: {}", e.getMessage(), e);
throw new SopStrategyException("执行动态SQL失败: " + e.getMessage());
}finally {
sqlSession.close();
}
}
......
......@@ -279,7 +279,7 @@ public class SopStrategyExecutionService {
record.setExecuteTime(new Date());
record.setExecuteStatus(executeStatus);
record.setExecuteDesc(executeDesc);
record.setErrorMessage(getFullStackTrace(e));
record.setErrorMessage(e.getMessage());
SopStrategySnapshotCacheService.StrategyDetailCache cache = sopStrategySnapshotCacheService.loadStrategyDetail(task.getStrategyId());
record.setSnapshotInfo(sopStrategySnapshotCacheService.buildSnapshotJson(task, cache, contextVariables));
......
......@@ -126,14 +126,12 @@ public class SopStrategyTriggerService {
}
private List<Long> queryCandidateCustomers(SopStrategy strategy) {
List<CandidateCustomerDTO> customers =
List<Long> customers =
sopCustomerQueryService.queryCandidateCustomers(strategy);
if (CollUtil.isEmpty(customers)) {
return CollUtil.newArrayList();
}
return customers.stream()
.map(CandidateCustomerDTO::getCustomerInstanceId)
.collect(java.util.stream.Collectors.toList());
return customers;
}
private Date getCustomerBehaviorDate(Long customerInstanceId, SopStrategy strategy) {
......
......@@ -330,20 +330,6 @@ public class StrategySopQueryService {
.collect(Collectors.toList());
}
/**
* 构建所有操作符列表
*
* @return 操作符元数据项列表
*/
private List<SopStrategyMetaDTO.SopMetaItemDTO> buildOperators() {
List<SopStrategyMetaDTO.SopMetaItemDTO> items = new ArrayList<>();
for (SopOperatorTypeEnum op : SopOperatorTypeEnum.values()) {
items.add(createMetaItem(String.valueOf(op.getValue()), op.getDisplayName(), 4, op.getDisplayName()));
}
return items;
}
/**
* 根据变量类型构建可用操作符列表
......
......@@ -34,4 +34,10 @@
WHERE customer_instance_id = #{customerInstanceId} AND deleted_flag = 'N'
ORDER BY execute_time DESC
</select>
<select id="selectPageByStrategyId"
resultType="cn.com.glsx.dj.strategy.model.sop.SopStrategyExecutionRecord">
SELECT * FROM sop_strategy_execution_record
WHERE strategy_id = #{condition.strategyId} AND deleted_flag = 'N'
ORDER BY execute_time DESC
</select>
</mapper>
\ No newline at end of file
......@@ -6,6 +6,17 @@
<id column="id" property="id"/>
<result column="strategy_code" property="strategyCode"/>
<result column="strategy_name" property="strategyName"/>
<result column="biz_type" property="bizType"/>
<result column="store_scope_type" property="storeScopeType"/>
<result column="marketing_stage" property="marketingStage"/>
<result column="customer_behavior_type" property="customerBehaviorType"/>
<result column="date_variable_type" property="dateVariableType"/>
<result column="relative_date_type" property="relativeDateType"/>
<result column="relative_days" property="relativeDays"/>
<result column="trigger_hour" property="triggerHour"/>
<result column="trigger_minute" property="triggerMinute"/>
<result column="action_confirm_type" property="actionConfirmType"/>
<result column="version" property="version"/>
<result column="trigger_type" property="triggerType"/>
<result column="status" property="status"/>
<result column="created_by" property="createdBy"/>
......
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.com.glsx.dj.strategy.mapper.sop.SopStrategyMetaDateVariableMapper">
<resultMap id="BaseResultMap" type="cn.com.glsx.dj.strategy.model.sop.SopStrategyMetaDateVariable">
<id column="id" property="id"/>
<result column="date_code" property="dateCode"/>
<result column="date_name" property="dateName"/>
<result column="date_desc" property="dateDesc"/>
<result column="date_column" property="dateColumn"/>
<result column="sort_order" property="sortOrder"/>
<result column="status" property="status"/>
<result column="deleted_flag" property="deletedFlag"/>
<result column="created_by" property="createdBy"/>
<result column="created_date" property="createdDate"/>
<result column="updated_by" property="updatedBy"/>
<result column="updated_date" property="updatedDate"/>
</resultMap>
<select id="selectByStatus" resultMap="BaseResultMap">
SELECT * FROM sop_strategy_meta_date_variable
WHERE deleted_flag = 'N'
AND status = #{status}
ORDER BY sort_order ASC
</select>
<select id="selectByDateCode" resultMap="BaseResultMap">
SELECT * FROM sop_strategy_meta_date_variable
WHERE deleted_flag = 'N'
AND date_code = #{dateCode}
</select>
</mapper>
\ No newline at end of file
......@@ -30,7 +30,7 @@
<select id="selectTasksNeedExecute" resultMap="BaseResultMap">
SELECT * FROM sop_strategy_task
WHERE execute_status = 0
AND confirm_status IN (-1, 1)
AND confirm_status IN (-1)
AND trigger_time &lt; #{now}
AND deleted_flag = 'N'
ORDER BY trigger_time ASC
......
......@@ -9,6 +9,7 @@ import cn.com.glsx.dj.strategy.enums.StrategyDataSourceEnum;
import cn.com.glsx.dj.strategy.enums.StrategyPushFlagEnum;
import cn.com.glsx.dj.strategy.enums.StrategyPushType;
import cn.com.glsx.dj.strategy.enums.StrategyTypeEnum;
import cn.com.glsx.dj.strategy.job.SopStrategyTriggerJob;
import cn.com.glsx.scrm.equity.enums.DeleteFlagEnum;
import cn.com.glsx.dj.strategy.mapper.StrategyStaffRelMapper;
import cn.com.glsx.dj.strategy.model.*;
......@@ -39,6 +40,12 @@ public class StrategyInfoServiceTest extends BaseServiceTest {
@Autowired
private ProjectGroupService projectGroupService;
@Autowired
private SopStrategyTriggerJob sopStrategyTriggerJob;
@Autowired
private SopStrategyExecutionService sopStrategyExecutionService;
@Test
public void testQueryStrategyInfoList() {
......@@ -243,4 +250,13 @@ public class StrategyInfoServiceTest extends BaseServiceTest {
StrategyInfo strategyInfo = strategyInfoService.queryStrategyInfoById(146);
strategyInfoService.processWorktoolStrategy(strategyInfo);
}
@Test
public void sopStrategyTriggerJob() {
sopStrategyTriggerJob.execute(null);
}
@Test
public void executeTask() {
sopStrategyExecutionService.executeTask(3);
}
}
......@@ -340,7 +340,7 @@ public class StrategySopServiceTest {
@Test
public void testConfirmSopStrategyTask_SingleTask() {
SopStrategyConfirmReqDTO request = new SopStrategyConfirmReqDTO();
request.setTaskId(1L);
request.setTaskId(1);
request.setConfirmStatus(1);
SopStrategyTask task = new SopStrategyTask();
......@@ -362,7 +362,7 @@ public class StrategySopServiceTest {
@Test
public void testConfirmSopStrategyTask_BatchTasks() {
SopStrategyConfirmReqDTO request = new SopStrategyConfirmReqDTO();
request.setTaskIds(Arrays.asList(1L, 2L));
request.setTaskIds(Arrays.asList(1, 2));
request.setConfirmStatus(1);
SopStrategyTask task1 = new SopStrategyTask();
......@@ -390,7 +390,7 @@ public class StrategySopServiceTest {
@Test(expected = SopStrategyException.class)
public void testConfirmSopStrategyTask_NullConfirmStatus() {
SopStrategyConfirmReqDTO request = new SopStrategyConfirmReqDTO();
request.setTaskId(1L);
request.setTaskId(1);
strategySopService.confirmSopStrategyTask(request);
}
......@@ -406,7 +406,7 @@ public class StrategySopServiceTest {
@Test
public void testConfirmSopStrategyTask_TaskAlreadyConfirmed() {
SopStrategyConfirmReqDTO request = new SopStrategyConfirmReqDTO();
request.setTaskId(1L);
request.setTaskId(1);
request.setConfirmStatus(1);
SopStrategyTask task = new SopStrategyTask();
......@@ -426,7 +426,7 @@ public class StrategySopServiceTest {
@Test
public void testConfirmSopStrategyTask_TaskNotExist() {
SopStrategyConfirmReqDTO request = new SopStrategyConfirmReqDTO();
request.setTaskId(999L);
request.setTaskId(999);
request.setConfirmStatus(1);
when(sopStrategyTaskMapper.selectByPrimaryKey(999)).thenReturn(null);
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!