Commit 0fd48b95 by 杨卫

feat:策略中心,策略分析等接口自测

1 parent b3ef17f0
......@@ -62,6 +62,9 @@ public class ProjectGroupWarningRecordDTO implements Serializable {
@ApiModelProperty(notes = "周期结束")
private Date periodEnd;
@ApiModelProperty(notes = "指标字典ID")
private Integer metricId;
@ApiModelProperty(notes = "指标编码")
private String metricCode;
......@@ -103,4 +106,13 @@ public class ProjectGroupWarningRecordDTO implements Serializable {
@ApiModelProperty(notes = "创建时间")
private Date createdTime;
@ApiModelProperty(notes = "指标数据类型: 1=比率 2=数值")
private Integer metricDataType;
@ApiModelProperty(notes = "指标单位")
private String metricUnit;
@ApiModelProperty(notes = "指标扩展品类")
private String metricCategoryExtension;
}
......@@ -25,6 +25,9 @@ public class ProjectGroupWarningRecordQueryDTO implements Serializable {
@ApiModelProperty(notes = "预警类型")
private Integer warningType;
@ApiModelProperty(notes = "指标id")
private Integer metricId;
@ApiModelProperty(notes = "业务类型")
private Integer businessType;
......
......@@ -42,6 +42,9 @@ public class StoreWarningSummaryDTO implements Serializable {
@ApiModelProperty(notes = "预警摘要(最多2条)")
private List<String> warningSummary;
@ApiModelProperty(notes = "预警记录(最多2条)")
private List<WarningRecordDTO> warningRecords;
@ApiModelProperty(notes = "预警总数")
private int warningTotalCount;
......
......@@ -66,6 +66,9 @@ public class WarningRecordDTO implements Serializable {
@ApiModelProperty(notes = "员工手机号")
private String staffPhone;
@ApiModelProperty(notes = "指标字典ID")
private Integer metricId;
@ApiModelProperty(notes = "指标编码")
private String metricCode;
......@@ -107,4 +110,13 @@ public class WarningRecordDTO implements Serializable {
@ApiModelProperty(notes = "创建时间")
private Date createdTime;
@ApiModelProperty(notes = "指标数据类型: 1=比率 2=数值")
private Integer dataType;
@ApiModelProperty(notes = "指标单位")
private String unit;
@ApiModelProperty(notes = "指标扩展品类")
private String categoryExtension;
}
......@@ -82,6 +82,9 @@ public enum WarningOperatorEnum {
},
// ==================== 区间运算符 ====================
/**
* 区间右开:实际值 &lt; max → "低于"
*/
OPEN_INTERVAL("><", Category.RANGE) {
@Override
public boolean evaluate(BigDecimal value, BigDecimal threshold, BigDecimal min, BigDecimal max) {
......@@ -92,9 +95,12 @@ public enum WarningOperatorEnum {
@Override
public String buildWarningText(String metricName, BigDecimal metricDisplay,
BigDecimal thresholdDisplay, BigDecimal minDisplay, BigDecimal maxDisplay) {
return String.format("「%s」%.2f 在区间(%.2f, %.2f)内", metricName, metricDisplay, minDisplay, maxDisplay);
return String.format("「%s」%.2f 低于 %.2f", metricName, metricDisplay, maxDisplay);
}
},
/**
* 区间双闭:实际值 &le; max → "低于或等于"
*/
CLOSE_INTERVAL(">=<=", Category.RANGE) {
@Override
public boolean evaluate(BigDecimal value, BigDecimal threshold, BigDecimal min, BigDecimal max) {
......@@ -105,9 +111,12 @@ public enum WarningOperatorEnum {
@Override
public String buildWarningText(String metricName, BigDecimal metricDisplay,
BigDecimal thresholdDisplay, BigDecimal minDisplay, BigDecimal maxDisplay) {
return String.format("「%s」%.2f 在区间[%.2f, %.2f]内", metricName, metricDisplay, minDisplay, maxDisplay);
return String.format("「%s」%.2f 低于或等于 %.2f", metricName, metricDisplay, maxDisplay);
}
},
/**
* 区间左闭右开:实际值 &lt; max → "低于"
*/
LEFT_CLOSE_RIGHT_OPEN(">=<", Category.RANGE) {
@Override
public boolean evaluate(BigDecimal value, BigDecimal threshold, BigDecimal min, BigDecimal max) {
......@@ -118,9 +127,12 @@ public enum WarningOperatorEnum {
@Override
public String buildWarningText(String metricName, BigDecimal metricDisplay,
BigDecimal thresholdDisplay, BigDecimal minDisplay, BigDecimal maxDisplay) {
return String.format("「%s」%.2f 在区间[%.2f, %.2f)内", metricName, metricDisplay, minDisplay, maxDisplay);
return String.format("「%s」%.2f 低于 %.2f", metricName, metricDisplay, maxDisplay);
}
},
/**
* 区间左开右闭:实际值 &le; max → "低于或等于"
*/
LEFT_OPEN_RIGHT_CLOSE("><=", Category.RANGE) {
@Override
public boolean evaluate(BigDecimal value, BigDecimal threshold, BigDecimal min, BigDecimal max) {
......@@ -131,7 +143,7 @@ public enum WarningOperatorEnum {
@Override
public String buildWarningText(String metricName, BigDecimal metricDisplay,
BigDecimal thresholdDisplay, BigDecimal minDisplay, BigDecimal maxDisplay) {
return String.format("「%s」%.2f 在区间(%.2f, %.2f]内", metricName, metricDisplay, minDisplay, maxDisplay);
return String.format("「%s」%.2f 低于或等于 %.2f", metricName, metricDisplay, maxDisplay);
}
};
......
......@@ -65,6 +65,9 @@ public class PgWarningRecord implements Serializable {
@Column(name = "staff_phone")
private String staffPhone;
@Column(name = "metric_id")
private Integer metricId;
@Column(name = "metric_code")
private String metricCode;
......
......@@ -36,4 +36,24 @@ public interface PgWarningMetricDictMapper extends OreMapper<PgWarningMetricDict
*/
List<PgWarningMetricDict> selectByWarningTypeAndBiz(@Param("warningType") Integer warningType,
@Param("biz") Integer biz);
/**
* 按预警类型+业务线+指标编码查单个指标字典(用于计算时获取metric_id)。
*
* @param warningType 预警类型
* @param biz 业务类型
* @param indexName 指标编码
* @return 指标字典
*/
PgWarningMetricDict selectByWarningTypeBizAndIndexName(@Param("warningType") Integer warningType,
@Param("biz") Integer biz,
@Param("indexName") String indexName);
/**
* 按ID列表批量查询指标字典。
*
* @param ids 指标字典ID列表
* @return 指标字典列表
*/
List<PgWarningMetricDict> selectByIds(@Param("ids") List<Integer> ids);
}
......@@ -151,11 +151,12 @@ public class WarningEngineRemoteImpl implements WarningEngineRemote {
dto.setStoreName(storeIdToName.get(storeId));
List<WarningRecordDTO> storeRecords = recordsByStore.getOrDefault(storeId, new ArrayList<>());
dto.setWarningTotalCount(storeRecords.size());
List<String> warnSummary = storeRecords.stream()
.limit(2)
.map(WarningRecordDTO::getWarningText)
.collect(Collectors.toList());
dto.setWarningSummary(warnSummary);
List<WarningRecordDTO> warningRecordDTOList = storeRecords.stream().limit(2).collect(Collectors.toList());
if (CollUtil.isNotEmpty(warningRecordDTOList)) {
dto.setWarningSummary(warningRecordDTOList.stream().map(WarningRecordDTO::getWarningText)
.collect(Collectors.toList()));
dto.setWarningRecords(warningRecordDTOList);
}
result.add(dto);
}
return result;
......@@ -221,22 +222,27 @@ public class WarningEngineRemoteImpl implements WarningEngineRemote {
// 3. 提取门店→名称映射 + 门店→触发指标映射 + 当前周期指标值
Map<Integer, String> storeIdToName = new LinkedHashMap<>();
Map<Integer, Map<String, String>> storeMetricMap = new LinkedHashMap<>();
// storeId → metricCode → 当前周期指标值(来自 warning_record)
Map<Integer, Map<String, BigDecimal>> storeCurrentValueMap = new LinkedHashMap<>();
// 全局去重的指标编码→名称(用于批量查询指标字典)
Map<String, String> allMetricCodeToName = new LinkedHashMap<>();
// storeId → metricId → metricName
Map<Integer, Map<Integer, String>> storeMetricMap = new LinkedHashMap<>();
// storeId → metricId → 当前周期指标值(来自 warning_record)
Map<Integer, Map<Integer, BigDecimal>> storeCurrentValueMap = new LinkedHashMap<>();
// 全局去重: metricId → {metricCode, metricName}
Map<Integer, String> allMetricIdToCode = new LinkedHashMap<>();
Map<Integer, String> allMetricIdToName = new LinkedHashMap<>();
Set<Integer> allMetricIds = new LinkedHashSet<>();
for (WarningRecordDTO r : warningRecords) {
if (r.getStoreId() != null && r.getMetricCode() != null && r.getMetricName() != null) {
if (r.getStoreId() != null && r.getMetricId() != null && r.getMetricCode() != null && r.getMetricName() != null) {
storeIdToName.putIfAbsent(r.getStoreId(), r.getStoreName());
storeMetricMap.computeIfAbsent(r.getStoreId(), k -> new LinkedHashMap<>())
.putIfAbsent(r.getMetricCode(), r.getMetricName());
.putIfAbsent(r.getMetricId(), r.getMetricName());
storeCurrentValueMap.computeIfAbsent(r.getStoreId(), k -> new LinkedHashMap<>())
.putIfAbsent(r.getMetricCode(), r.getMetricValue());
allMetricCodeToName.putIfAbsent(r.getMetricCode(), r.getMetricName());
.putIfAbsent(r.getMetricId(), r.getMetricValue());
allMetricIdToCode.putIfAbsent(r.getMetricId(), r.getMetricCode());
allMetricIdToName.putIfAbsent(r.getMetricId(), r.getMetricName());
allMetricIds.add(r.getMetricId());
}
}
if (storeIdToName.isEmpty() || allMetricCodeToName.isEmpty()) {
if (storeIdToName.isEmpty() || allMetricIds.isEmpty()) {
return RpcResponse.success(new RpcPagination<>());
}
......@@ -247,17 +253,13 @@ public class WarningEngineRemoteImpl implements WarningEngineRemote {
RpcPagination<Integer> storePage = MemoryPageUtil.page(allStoreIds, pageNum, pageSize);
List<Integer> pageStoreIds = storePage.getList();
// 5. 批量查询指标字典,获取 dataType/unit/categoryExtension
Map<String, PgWarningMetricDict> metricDictMap = new LinkedHashMap<>();
if (request.getBusinessType() != null && request.getWarningType() != null) {
List<PgWarningMetricDict> metricDicts = pgWarningMetricDictMapper
.selectByWarningTypeAndBiz(request.getWarningType(), request.getBusinessType());
if (CollUtil.isNotEmpty(metricDicts)) {
for (PgWarningMetricDict dict : metricDicts) {
if (dict.getIndexName() != null) {
metricDictMap.put(dict.getIndexName(), dict);
}
}
// 5. 通过 metricId 批量查询指标字典,获取 dataType/unit/categoryExtension
Map<Integer, PgWarningMetricDict> metricDictMap = new LinkedHashMap<>();
List<PgWarningMetricDict> metricDicts = pgWarningMetricDictMapper
.selectByIds(new ArrayList<>(allMetricIds));
if (CollUtil.isNotEmpty(metricDicts)) {
for (PgWarningMetricDict dict : metricDicts) {
metricDictMap.put(dict.getId(), dict);
}
}
......@@ -273,17 +275,17 @@ public class WarningEngineRemoteImpl implements WarningEngineRemote {
.reduce((a, b) -> a + "," + b).orElse("");
// 7. 逐指标查询BI(当前周期 + 下一周期),仅查当前页门店
// 每个门店只计算它实际触发的指标
Map<Integer, List<MetricAnalysisDTO>> storeMetricsResult = new LinkedHashMap<>();
for (Integer storeId : pageStoreIds) {
storeMetricsResult.put(storeId, new ArrayList<>());
}
for (Map.Entry<String, String> metricEntry : allMetricCodeToName.entrySet()) {
String metricCode = metricEntry.getKey();
String metricName = metricEntry.getValue();
for (Map.Entry<Integer, String> metricEntry : allMetricIdToCode.entrySet()) {
Integer metricId = metricEntry.getKey();
String metricCode = metricEntry.getValue();
String metricName = allMetricIdToName.get(metricId);
PgWarningMetricDict metricDict = metricDictMap.get(metricCode);
PgWarningMetricDict metricDict = metricDictMap.get(metricId);
boolean needPercentScale = metricDict != null
&& metricDict.getDataType() != null && metricDict.getDataType() == 1
&& "%".equals(metricDict.getUnit());
......@@ -297,12 +299,12 @@ public class WarningEngineRemoteImpl implements WarningEngineRemote {
// 只对该指标触发了的门店生成 MetricAnalysisDTO
for (Integer storeId : pageStoreIds) {
if (!storeMetricMap.containsKey(storeId)
|| !storeMetricMap.get(storeId).containsKey(metricCode)) {
|| !storeMetricMap.get(storeId).containsKey(metricId)) {
continue;
}
// 当前值:直接从 warning_record 获取
BigDecimal currentValue = storeCurrentValueMap
.getOrDefault(storeId, new LinkedHashMap<>()).get(metricCode);
.getOrDefault(storeId, new LinkedHashMap<>()).get(metricId);
if (currentValue != null && needPercentScale) {
currentValue = currentValue.multiply(new BigDecimal("100"));
}
......@@ -324,7 +326,7 @@ public class WarningEngineRemoteImpl implements WarningEngineRemote {
if (currentValue != null && currentValue.compareTo(BigDecimal.ZERO) != 0) {
BigDecimal changeRate = nextValue.subtract(currentValue)
.divide(currentValue, 4, RoundingMode.HALF_UP);
.divide(currentValue, 2, RoundingMode.HALF_UP);
metricDto.setChangeRate(changeRate);
metricDto.setImproved(changeRate.compareTo(BigDecimal.ZERO) > 0);
}
......
......@@ -8,8 +8,10 @@ import cn.com.glsx.dj.strategy.enums.ThresholdTypeEnum;
import cn.com.glsx.dj.strategy.enums.WarningOperatorEnum;
import cn.com.glsx.dj.strategy.mapper.PgGroupStoreRelMapper;
import cn.com.glsx.dj.strategy.mapper.PgWarningConfigMapper;
import cn.com.glsx.dj.strategy.mapper.PgWarningMetricDictMapper;
import cn.com.glsx.dj.strategy.mapper.PgWarningRecordMapper;
import cn.com.glsx.dj.strategy.model.projectgroup.PgWarningConfig;
import cn.com.glsx.dj.strategy.model.projectgroup.PgWarningMetricDict;
import cn.com.glsx.dj.strategy.model.projectgroup.PgWarningRecord;
import cn.com.glsx.dj.strategy.service.warning.threshold.ThresholdStrategy;
import cn.com.glsx.dj.strategy.service.warning.threshold.ThresholdStrategyFactory;
......@@ -58,6 +60,9 @@ public class WarningEngineService {
private EcoCoefficientQueryService ecoCoefficientQueryService;
@Resource
private PgWarningMetricDictMapper metricDictMapper;
@Resource
private ThresholdStrategyFactory thresholdFactory;
/**
......@@ -353,7 +358,7 @@ public class WarningEngineService {
if (triggeredItem != null) {
record.setStoreName(triggeredItem.getMerchantName());
}
fillMetricAndThreshold(record, triggeredCond, triggeredValue, true);
fillMetricAndThreshold(record, config, triggeredCond, triggeredValue, true);
fillEcoAndText(record, triggeredCond, triggeredValue, true);
return record;
}
......@@ -380,7 +385,7 @@ public class WarningEngineService {
record.setStaffId(staffId);
record.setStaffName(staffItem.getStaffName());
record.setStaffPhone(staffItem.getStaffPhone());
fillMetricAndThreshold(record, triggeredCond, triggeredValue, false);
fillMetricAndThreshold(record, config, triggeredCond, triggeredValue, false);
fillEcoAndText(record, triggeredCond, triggeredValue, false);
return record;
}
......@@ -423,13 +428,25 @@ public class WarningEngineService {
return null;
}
private void fillMetricAndThreshold(PgWarningRecord record, ConditionDTO triggeredCond,
private void fillMetricAndThreshold(PgWarningRecord record, PgWarningConfig config,
ConditionDTO triggeredCond,
BigDecimal triggeredValue, boolean isStoreTarget) {
if (triggeredCond.getMetric() != null) {
record.setMetricCode(isStoreTarget
String metricCode = isStoreTarget
? triggeredCond.getMetric().getStoreCode()
: triggeredCond.getMetric().getStaffCode());
: triggeredCond.getMetric().getStaffCode();
record.setMetricCode(metricCode);
record.setMetricName(triggeredCond.getMetric().getName());
// 通过 metric_code + warning_type + biz 查找 metric_dict 的 id
try {
PgWarningMetricDict dict = metricDictMapper.selectByWarningTypeBizAndIndexName(
config.getWarningType(), config.getBiz(), metricCode);
if (dict != null) {
record.setMetricId(dict.getId());
}
} catch (Exception e) {
log.warn("查找指标字典metric_id失败,code={}", metricCode, e);
}
}
record.setMetricValue(triggeredValue);
record.setMetricDisplay(triggeredValue);
......
......@@ -46,39 +46,7 @@ public class WarningRecordService {
if (list == null) {
return new ArrayList<>();
}
return list.stream().map(dto -> {
WarningRecordDTO record = new WarningRecordDTO();
record.setId(dto.getId());
record.setGroupId(dto.getGroupId());
record.setConfigId(dto.getConfigId());
record.setWarningType(dto.getWarningType());
record.setWarningTypeName(dto.getWarningTypeName());
record.setBusinessType(dto.getBusinessType());
record.setMonitorTarget(dto.getMonitorTarget());
record.setTimeDimension(dto.getTimeDimension());
record.setPeriodStart(dto.getPeriodStart());
record.setPeriodEnd(dto.getPeriodEnd());
record.setStoreId(dto.getMerchantId());
record.setStoreName(dto.getMerchantName());
record.setStaffId(dto.getStaffId());
record.setStaffName(dto.getStaffName());
record.setStaffPhone(dto.getStaffPhone());
record.setMetricCode(dto.getMetricCode());
record.setMetricName(dto.getMetricName());
record.setMetricValue(dto.getMetricValue());
record.setMetricDisplay(dto.getMetricDisplay());
record.setThresholdType(dto.getThresholdType());
record.setThresholdDisplay(dto.getThresholdDisplay());
record.setThresholdMinDisplay(dto.getThresholdMinDisplay());
record.setThresholdMaxDisplay(dto.getThresholdMaxDisplay());
record.setEcoCoefficient(dto.getEcoCoefficient());
record.setOperator(dto.getOperator());
record.setWarningText(dto.getWarningText());
record.setIsStrategySent(dto.getIsStrategySent());
record.setStatus(dto.getStatus());
record.setCreatedTime(dto.getCreatedTime());
return record;
}).collect(Collectors.toList());
return list.stream().map(this::convertToWarningRecordDTO).collect(Collectors.toList());
}
/**
......@@ -114,22 +82,67 @@ public class WarningRecordService {
summary.setStoreName(first.getMerchantName());
}
summary.setWarningTotalCount(storeRecords.size());
List<ProjectGroupWarningRecordDTO> warningRecordDTOList = storeRecords.stream().limit(2).collect(Collectors.toList());
// 预警摘要:取前2条 warningTypeName
List<String> warnSummary = storeRecords.stream()
.limit(2)
.map(ProjectGroupWarningRecordDTO::getWarningTypeName)
List<String> warnSummary = warningRecordDTOList.stream().map(ProjectGroupWarningRecordDTO::getWarningTypeName)
.collect(Collectors.toList());
summary.setWarningSummary(warnSummary);
// 预警记录:取前2条
List<WarningRecordDTO> warnRecords = warningRecordDTOList.stream()
.map(this::convertToWarningRecordDTO)
.collect(Collectors.toList());
summary.setWarningRecords(warnRecords);
result.add(summary);
}
return result;
}
private WarningRecordDTO convertToWarningRecordDTO(ProjectGroupWarningRecordDTO dto) {
WarningRecordDTO record = new WarningRecordDTO();
record.setId(dto.getId());
record.setGroupId(dto.getGroupId());
record.setConfigId(dto.getConfigId());
record.setWarningType(dto.getWarningType());
record.setWarningTypeName(dto.getWarningTypeName());
record.setBusinessType(dto.getBusinessType());
record.setMonitorTarget(dto.getMonitorTarget());
record.setTimeDimension(dto.getTimeDimension());
record.setPeriodStart(dto.getPeriodStart());
record.setPeriodEnd(dto.getPeriodEnd());
record.setStoreId(dto.getMerchantId());
record.setStoreName(dto.getMerchantName());
record.setStaffId(dto.getStaffId());
record.setStaffName(dto.getStaffName());
record.setStaffPhone(dto.getStaffPhone());
record.setMetricId(dto.getMetricId());
record.setMetricCode(dto.getMetricCode());
record.setMetricName(dto.getMetricName());
record.setMetricValue(dto.getMetricValue());
record.setMetricDisplay(dto.getMetricDisplay());
record.setThresholdType(dto.getThresholdType());
record.setThresholdDisplay(dto.getThresholdDisplay());
record.setThresholdMinDisplay(dto.getThresholdMinDisplay());
record.setThresholdMaxDisplay(dto.getThresholdMaxDisplay());
record.setEcoCoefficient(dto.getEcoCoefficient());
record.setOperator(dto.getOperator());
record.setWarningText(dto.getWarningText());
record.setIsStrategySent(dto.getIsStrategySent());
record.setStatus(dto.getStatus());
record.setCreatedTime(dto.getCreatedTime());
record.setDataType(dto.getMetricDataType());
record.setUnit(dto.getMetricUnit());
record.setCategoryExtension(dto.getMetricCategoryExtension());
return record;
}
private ProjectGroupWarningRecordQueryDTO buildQueryDTO(WarningRecordQueryRequest request) {
ProjectGroupWarningRecordQueryDTO dto = new ProjectGroupWarningRecordQueryDTO();
dto.setProjectGroupId(request.getGroupId());
dto.setBusinessType(request.getBusinessType());
dto.setWarningType(request.getWarningType());
dto.setMetricId(request.getMetricTypeId());
dto.setTimeDimension(request.getTimeDimension());
dto.setPeriodStart(request.getStartDate());
dto.setPeriodEnd(request.getEndDate());
......
......@@ -35,11 +35,11 @@
<select id="selectAllEnabled" resultType="cn.com.glsx.dj.strategy.model.projectgroup.PgGroupInfo">
SELECT
id, group_name, remark, is_enabled,
created_by, created_date, updated_by, updated_date, deleted_flag
id, group_name AS groupName, remark,
created_by AS createdBy, created_date AS createdDate,
updated_by AS updatedBy, updated_date AS updatedDate, deleted_flag AS deletedFlag
FROM pg_group_info
WHERE deleted_flag = 'N'
AND is_enabled = 1
ORDER BY id ASC
</select>
......
......@@ -4,9 +4,10 @@
<select id="selectByCondition" resultType="cn.com.glsx.dj.strategy.model.projectgroup.PgStoreOutput">
SELECT
id, business_type, store_id, store_name,
time_dimension, period_start, period_end,
deleted_flag, created_by, created_date, updated_by, updated_date
id, business_type AS businessType, store_id AS storeId, store_name AS storeName,
time_dimension AS timeDimension, period_start AS periodStart, period_end AS periodEnd,
deleted_flag AS deletedFlag, created_by AS createdBy, created_date AS createdDate,
updated_by AS updatedBy, updated_date AS updatedDate
FROM pg_store_output
WHERE deleted_flag = 'N'
AND business_type = #{businessType}
......
......@@ -17,8 +17,10 @@
<select id="selectEnabledByGroupId" resultType="cn.com.glsx.dj.strategy.model.projectgroup.PgWarningConfig">
SELECT
id, group_id, warning_type, biz, monitor_target, rule_json, is_enabled,
created_by, created_date, updated_by, updated_date, deleted_flag
id, group_id AS groupId, warning_type AS warningType, biz, monitor_target AS monitorTarget,
rule_json AS ruleJson, is_enabled AS isEnabled,
created_by AS createdBy, created_date AS createdDate,
updated_by AS updatedBy, updated_date AS updatedDate, deleted_flag AS deletedFlag
FROM pg_warning_config
WHERE deleted_flag = 'N'
AND is_enabled = 1
......@@ -28,8 +30,10 @@
<select id="selectAllEnabled" resultType="cn.com.glsx.dj.strategy.model.projectgroup.PgWarningConfig">
SELECT
id, group_id, warning_type, biz, monitor_target, rule_json, is_enabled,
created_by, created_date, updated_by, updated_date, deleted_flag
id, group_id AS groupId, warning_type AS warningType, biz, monitor_target AS monitorTarget,
rule_json AS ruleJson, is_enabled AS isEnabled,
created_by AS createdBy, created_date AS createdDate,
updated_by AS updatedBy, updated_date AS updatedDate, deleted_flag AS deletedFlag
FROM pg_warning_config
WHERE deleted_flag = 'N'
AND is_enabled = 1
......@@ -38,8 +42,10 @@
<select id="selectEnabledByWarningType" resultType="cn.com.glsx.dj.strategy.model.projectgroup.PgWarningConfig">
SELECT
id, group_id, warning_type, biz, monitor_target, rule_json, is_enabled,
created_by, created_date, updated_by, updated_date, deleted_flag
id, group_id AS groupId, warning_type AS warningType, biz, monitor_target AS monitorTarget,
rule_json AS ruleJson, is_enabled AS isEnabled,
created_by AS createdBy, created_date AS createdDate,
updated_by AS updatedBy, updated_date AS updatedDate, deleted_flag AS deletedFlag
FROM pg_warning_config
WHERE deleted_flag = 'N'
AND is_enabled = 1
......
......@@ -43,10 +43,12 @@
<select id="selectByWarningTypeAndBiz"
resultType="cn.com.glsx.dj.strategy.model.projectgroup.PgWarningMetricDict">
SELECT
m.id, m.index_name, m.business_type, m.category_extension,
m.store_index_code, m.staff_index_code,
m.data_type, m.unit, m.sort_order,
m.created_by, m.created_date, m.updated_by, m.updated_date, m.deleted_flag
m.id, m.index_name AS indexName, m.business_type AS businessType,
m.category_extension AS categoryExtension,
m.store_index_code AS storeIndexCode, m.staff_index_code AS staffIndexCode,
m.data_type AS dataType, m.unit, m.sort_order AS sortOrder,
m.created_by AS createdBy, m.created_date AS createdDate,
m.updated_by AS updatedBy, m.updated_date AS updatedDate, m.deleted_flag AS deletedFlag
FROM pg_warning_metric_dict m
INNER JOIN pg_warning_type_metric_rel tm
ON tm.metric_id = m.id AND tm.deleted_flag = 'N'
......@@ -56,4 +58,39 @@
ORDER BY m.sort_order ASC, m.id ASC
</select>
<select id="selectByIds" resultType="cn.com.glsx.dj.strategy.model.projectgroup.PgWarningMetricDict">
SELECT
m.id, m.index_name AS indexName, m.business_type AS businessType,
m.category_extension AS categoryExtension,
m.store_index_code AS storeIndexCode, m.staff_index_code AS staffIndexCode,
m.data_type AS dataType, m.unit, m.sort_order AS sortOrder,
m.created_by AS createdBy, m.created_date AS createdDate,
m.updated_by AS updatedBy, m.updated_date AS updatedDate, m.deleted_flag AS deletedFlag
FROM pg_warning_metric_dict m
WHERE m.deleted_flag = 'N'
AND m.id IN
<foreach collection="ids" item="id" open="(" separator="," close=")">
#{id}
</foreach>
</select>
<select id="selectByWarningTypeBizAndIndexName"
resultType="cn.com.glsx.dj.strategy.model.projectgroup.PgWarningMetricDict">
SELECT
m.id, m.index_name AS indexName, m.business_type AS businessType,
m.category_extension AS categoryExtension,
m.store_index_code AS storeIndexCode, m.staff_index_code AS staffIndexCode,
m.data_type AS dataType, m.unit, m.sort_order AS sortOrder,
m.created_by AS createdBy, m.created_date AS createdDate,
m.updated_by AS updatedBy, m.updated_date AS updatedDate, m.deleted_flag AS deletedFlag
FROM pg_warning_metric_dict m
INNER JOIN pg_warning_type_metric_rel tm
ON tm.metric_id = m.id AND tm.deleted_flag = 'N'
WHERE m.deleted_flag = 'N'
AND tm.warning_type = #{warningType}
AND m.business_type = #{biz}
AND m.index_name = #{indexName}
LIMIT 1
</select>
</mapper>
......@@ -21,6 +21,7 @@
r.time_dimension AS timeDimension,
r.period_start AS periodStart,
r.period_end AS periodEnd,
r.metric_id AS metricId,
r.metric_code AS metricCode,
r.metric_name AS metricName,
r.metric_value AS metricValue,
......@@ -34,11 +35,17 @@
r.warning_text AS warningText,
r.is_strategy_sent AS isStrategySent,
r.status AS status,
r.created_time AS createdTime
r.created_time AS createdTime,
m.data_type AS metricDataType,
m.unit AS metricUnit,
m.category_extension AS metricCategoryExtension
FROM warning_record r
LEFT JOIN pg_warning_type_dict t
ON r.warning_type = t.warning_type
AND t.deleted_flag = 'N'
LEFT JOIN pg_warning_metric_dict m
ON r.metric_id = m.id
AND m.deleted_flag = 'N'
WHERE r.deleted_flag = 'N'
<if test="projectGroupId != null">
AND r.group_id = #{projectGroupId}
......@@ -56,10 +63,10 @@
AND r.time_dimension = #{timeDimension}
</if>
<if test="periodStart != null and periodStart != ''">
AND r.period_start = #{periodStart}
AND DATE_FORMAT(r.period_start, '%Y-%m-%d') = #{periodStart}
</if>
<if test="periodEnd != null and periodEnd != ''">
AND r.period_end = #{periodEnd}
AND DATE_FORMAT(r.period_end, '%Y-%m-%d') = #{periodEnd}
</if>
<if test="merchantIds != null and merchantIds.size() > 0">
AND r.store_id IN
......@@ -70,6 +77,9 @@
<if test="storeId != null">
AND r.store_id = #{storeId}
</if>
<if test="metricId != null">
AND r.metric_id = #{metricId}
</if>
<if test="staffId != null and staffId != ''">
AND r.staff_id = #{staffId}
</if>
......@@ -87,7 +97,7 @@
group_id, config_id, warning_type, business_type, monitor_target,
time_dimension, period_start, period_end,
store_id, store_name, staff_id, staff_name, staff_phone,
metric_code, metric_name, metric_value, metric_display,
metric_id, metric_code, metric_name, metric_value, metric_display,
threshold_type, threshold_value, threshold_min, threshold_max,
threshold_display, threshold_min_display, threshold_max_display,
eco_coefficient, operator, warning_text,
......@@ -98,7 +108,7 @@
#{r.groupId}, #{r.configId}, #{r.warningType}, #{r.businessType}, #{r.monitorTarget},
#{r.timeDimension}, #{r.periodStart}, #{r.periodEnd},
#{r.storeId}, #{r.storeName}, #{r.staffId}, #{r.staffName}, #{r.staffPhone},
#{r.metricCode}, #{r.metricName}, #{r.metricValue}, #{r.metricDisplay},
#{r.metricId}, #{r.metricCode}, #{r.metricName}, #{r.metricValue}, #{r.metricDisplay},
#{r.thresholdType}, #{r.thresholdValue}, #{r.thresholdMin}, #{r.thresholdMax},
#{r.thresholdDisplay}, #{r.thresholdMinDisplay}, #{r.thresholdMaxDisplay},
#{r.ecoCoefficient}, #{r.operator}, #{r.warningText},
......
  • @wangxw1
    commented
    Master

    你好!很高兴为你进行代码审查。本次提交的代码整体结构清晰,较好地运用了 Java 8 的 Stream API 进行数据处理。但在数据库查询性能和SQL索引命中方面存在几个较为严重的问题,需要在生产环境上线前进行优化。

    以下是本次审查的 Top 3 关键问题及优化建议:

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

    1. 严重的 SQL 性能隐患:索引失效(重要性:高)

    • 问题描述:在 PgWarningRecordMapper.xml 中,对 period_start 和 period_end 字段使用了 DATE_FORMAT 函数进行条件过滤(AND DATE_FORMAT(r.period_start, '%Y-%m-%d') = #{periodStart})。
    • 影响分析:在 SQL 的 WHERE 子句中对数据库字段使用函数,会导致该字段上的索引完全失效,从而引发全表扫描(Full Table Scan)。随着预警记录表数据量的增长,该查询将成为严重的性能瓶颈。
    • 优化建议:避免在左侧列上使用函数,应将传入的参数转换为时间范围进行比较。 xml <!-- 建议修改为范围查询,确保索引正常工作 --> <if test="periodStart != null and periodStart != ''"> AND r.period_start >= CONCAT(#{periodStart}, ' 00:00:00') AND r.period_start &lt;= CONCAT(#{periodStart}, ' 23:59:59') </if>

    2. 循环中执行数据库查询引发的 N+1 性能问题(重要性:高)

    • 问题描述:在 WarningEngineService.java 的 fillMetricAndThreshold 方法中,调用了 metricDictMapper.selectByWarningTypeBizAndIndexName。该方法通常在构建预警记录的循环中被调用。
    • 影响分析:这会导致典型的 N+1 查询问题。如果一次规则计算触发了 1000 条预警记录,就会向数据库发起 1000 次单条查询,极大消耗数据库连接资源并增加接口整体 RT(响应时间)。
    • 优化建议:应当在循环外部批量查询出所需的 PgWarningMetricDict 数据,并将其缓存在内存 Map 中,然后在循环中直接从内存获取。 java // 优化思路示例(在调用 fillMetricAndThreshold 的上层方法中): // 1. 收集所有需要的 metricCode // 2. 批量查询:List<PgWarningMetricDict> dicts = metricDictMapper.selectByCodes(codes, warningType, biz); // 3. 转换为 Map<String, Integer> metricCodeToIdMap; // 4. 将 Map 传入 fillMetricAndThreshold 或在循环中直接设值。

    3. 预警文案逻辑变更可能导致业务歧义(重要性:中)

    • 问题描述:在 WarningOperatorEnum.java 中,区间运算符(如 OPEN_INTERVAL 等)的 buildWarningText 方法,将文案从 在区间(min, max)内 修改为了 低于 max 或 低于或等于 max。
    • 影响分析:区间运算符的底层逻辑 evaluate 仍然是校验实际值是否处于 min 和 max 之间。如果文案只提示“低于 max”,丢失了“高于 min”的上下文,用户在看到预警时可能会产生困惑(例如:为什么某个极低的值没有触发“低于 max”的预警,因为实际上它低于了 min 从而未命中规则)。
    • 优化建议:建议与产品/业务方确认此文案变更是否符合预期。如果业务确实只需要展示上限,建议在注释中明确说明;如果属于误改,建议恢复双边界的文案展示,或改为 在 %s 与 %s 之间 的友好表述。

    二、评分明细

    • 功能实现的正确性与健壮性(36/40分):
      • 代码逻辑基本正确,未发现 MyBatis 子查询,未修改 Dubbo 接口已有参数(仅做新增,向下兼容)。
      • 扣分项:枚举类中文案的截断(丢失 min 值)可能引发业务逻辑表达上的歧义。
    • 安全性与潜在风险(30/30分):
      • MyBatis 均使用 #{} 占位符,无 SQL 注入风险。
      • 未发现越权、敏感信息明文打印等安全漏洞。
    • 最佳实践与可维护性(15/20分):
      • 较好地使用了 Stream API 简化集合操作,DTO 拆分合理。
      • 扣分项:在业务循环中直接调用 Mapper 查询数据库严重违反了工程最佳实践。
    • 性能与资源利用(1/5分):
      • 扣分项:DATE_FORMAT 导致索引失效,以及 N+1 查询问题,这两项在数据量上升后会对系统性能造成显著的负面影响,需重点整改。
    • 提交信息质量(3/5分):
      • 扣分项:Commit 信息为 feat:策略中心,策略分析等接口自测,描述过于宽泛。建议简要说明具体改动点(如:feat: 预警记录新增指标ID关联,优化预警文案及查询逻辑),以便于后续追溯。

    总分:85分

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