Commit 0fb9de9d by 杨卫

feat:策略中心联调问题修改以及预警引擎代码调整

1 parent 4fea436c
Showing 33 changed files with 1063 additions and 248 deletions
package cn.com.glsx.dj.strategy.consts;
/**
* 预警引擎常量类
*
* @author yangwei
* @version 1.0
* @since 2026/06/01 21:37
*/
public interface WarningEngineConsts {
String SYSTEM = "warning_engine";
}
...@@ -49,6 +49,9 @@ public class ProjectGroupWarningRecordQueryDTO implements Serializable { ...@@ -49,6 +49,9 @@ public class ProjectGroupWarningRecordQueryDTO implements Serializable {
@ApiModelProperty(notes = "员工ID") @ApiModelProperty(notes = "员工ID")
private String staffId; private String staffId;
@ApiModelProperty(notes = "员工ID")
private List<String> staffIds;
@ApiModelProperty(notes = "门店名称模糊搜索") @ApiModelProperty(notes = "门店名称模糊搜索")
private String storeName; private String storeName;
......
...@@ -8,9 +8,10 @@ import java.io.Serializable; ...@@ -8,9 +8,10 @@ import java.io.Serializable;
/** /**
* 规则条件——rule_json 数组中的单个条件元素。 * 规则条件——rule_json 数组中的单个条件元素。
* metricId/metricName 在顶层,运行时通过 metricId 反查 pg_warning_metric_dict 获取 BI 指标编码。
* *
* @author yangwei_by_claude * @author yangwei_by_claude
* @version 1.0 * @version 1.1
* @since 2026/05/28 14:00 * @since 2026/05/28 14:00
*/ */
@Data @Data
...@@ -22,8 +23,11 @@ public class ConditionDTO implements Serializable { ...@@ -22,8 +23,11 @@ public class ConditionDTO implements Serializable {
@ApiModelProperty(notes = "条件序号,从1开始递增") @ApiModelProperty(notes = "条件序号,从1开始递增")
private Integer seq; private Integer seq;
@ApiModelProperty(notes = "指标引用") @ApiModelProperty(notes = "指标字典主键ID")
private MetricRefDTO metric; private Integer metricId;
@ApiModelProperty(notes = "指标中文名(冗余,方便调试)")
private String metricName;
@ApiModelProperty(notes = "运算符: > < >= <= = >< >=<= >=< ><=") @ApiModelProperty(notes = "运算符: > < >= <= = >< >=<= >=< ><=")
private String operator; private String operator;
......
...@@ -8,9 +8,10 @@ import java.io.Serializable; ...@@ -8,9 +8,10 @@ import java.io.Serializable;
/** /**
* 指标引用——rule_json 中 condition.metric 部分。 * 指标引用——rule_json 中 condition.metric 部分。
* 存储 metricId(pg_warning_metric_dict 主键),运行时反查获取 BI 指标编码。
* *
* @author yangwei_by_claude * @author yangwei_by_claude
* @version 1.0 * @version 1.1
* @since 2026/05/28 14:00 * @since 2026/05/28 14:00
*/ */
@Data @Data
...@@ -19,12 +20,9 @@ public class MetricRefDTO implements Serializable { ...@@ -19,12 +20,9 @@ public class MetricRefDTO implements Serializable {
private static final long serialVersionUID = 754109325813660140L; private static final long serialVersionUID = 754109325813660140L;
@ApiModelProperty(notes = "指标中文名") @ApiModelProperty(notes = "指标字典主键ID")
private String name; private Integer metricId;
@ApiModelProperty(notes = "门店维度BI指标编码")
private String storeCode;
@ApiModelProperty(notes = "员工维度BI指标编码") @ApiModelProperty(notes = "指标中文名(冗余,方便调试)")
private String staffCode; private String name;
} }
...@@ -31,6 +31,9 @@ public class ThresholdDTO implements Serializable { ...@@ -31,6 +31,9 @@ public class ThresholdDTO implements Serializable {
@ApiModelProperty(notes = "区间上界") @ApiModelProperty(notes = "区间上界")
private String max; private String max;
@ApiModelProperty(notes = "type=2单值时,SQL结果集中值字段名")
private String valueField;
@ApiModelProperty(notes = "type=2区间时,SQL结果集中下界字段名") @ApiModelProperty(notes = "type=2区间时,SQL结果集中下界字段名")
private String minField; private String minField;
......
...@@ -73,4 +73,7 @@ public class WarningRecordQueryRequest implements Serializable { ...@@ -73,4 +73,7 @@ public class WarningRecordQueryRequest implements Serializable {
@ApiModelProperty(notes = "员工ID(查询指定员工预警明细时使用)") @ApiModelProperty(notes = "员工ID(查询指定员工预警明细时使用)")
private String staffId; private String staffId;
@ApiModelProperty(notes = "员工ID(查询指定员工预警明细时使用)")
private List<String> staffIds;
} }
package cn.com.glsx.dj.strategy.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* 指标数据类型枚举。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/06/02 16:00
*/
@Getter
@AllArgsConstructor
public enum MetricDataTypeEnum {
/** 比率 */
RATIO(1, "比率"),
/** 数值 */
NUMBER(2, "数值");
private final Integer code;
private final String desc;
/**
* 根据 code 获取枚举。
*/
public static MetricDataTypeEnum fromCode(Integer code) {
for (MetricDataTypeEnum t : values()) {
if (t.code.equals(code)) {
return t;
}
}
return null;
}
}
...@@ -12,6 +12,10 @@ import java.util.stream.Collectors; ...@@ -12,6 +12,10 @@ import java.util.stream.Collectors;
* *
* <p>说明:当前业务侧统一口径沿用 BI 业务类型: * <p>说明:当前业务侧统一口径沿用 BI 业务类型:
* 1-延保,2-轻改,3-权益。</p> * 1-延保,2-轻改,3-权益。</p>
* <pre>
* <strong>项目组业务类型枚举,不要新增或删除枚举,预警引擎依赖于该枚举类运行!!!!!!!!!!!!!!!!!!!!!!!!</strong>
* </pre>
*
*/ */
@Getter @Getter
@AllArgsConstructor @AllArgsConstructor
......
...@@ -25,24 +25,59 @@ public enum TimeDimensionEnum { ...@@ -25,24 +25,59 @@ public enum TimeDimensionEnum {
public PeriodRange calculate(Date date) { public PeriodRange calculate(Date date) {
return getWeekRange(date, true); return getWeekRange(date, true);
} }
@Override
public boolean shouldCompute(Date date) {
Calendar cal = toCalendar(date);
return cal.get(Calendar.DAY_OF_WEEK) == Calendar.SUNDAY;
}
@Override
public boolean isSnapshot() { return false; }
}, },
M("M", "月") { M("M", "月") {
@Override @Override
public PeriodRange calculate(Date date) { public PeriodRange calculate(Date date) {
return getMonthRange(date, true); return getMonthRange(date, true);
} }
@Override
public boolean shouldCompute(Date date) {
Calendar cal = toCalendar(date);
int lastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
return cal.get(Calendar.DAY_OF_MONTH) == lastDay;
}
@Override
public boolean isSnapshot() { return false; }
}, },
LDW("LDW", "截止周最新一天") { LDW("LDW", "截止周最新一天") {
@Override @Override
public PeriodRange calculate(Date date) { public PeriodRange calculate(Date date) {
return getWeekRange(date, false); return getWeekRange(date, false);
} }
@Override
public boolean shouldCompute(Date date) {
return true;
}
@Override
public boolean isSnapshot() { return true; }
}, },
LDM("LDM", "截止月最新一天") { LDM("LDM", "截止月最新一天") {
@Override @Override
public PeriodRange calculate(Date date) { public PeriodRange calculate(Date date) {
return getMonthRange(date, false); return getMonthRange(date, false);
} }
@Override
public boolean shouldCompute(Date date) {
return true;
}
@Override
public boolean isSnapshot() { return true; }
}; };
private final String code; private final String code;
...@@ -57,6 +92,22 @@ public enum TimeDimensionEnum { ...@@ -57,6 +92,22 @@ public enum TimeDimensionEnum {
public abstract PeriodRange calculate(Date date); public abstract PeriodRange calculate(Date date);
/** /**
* 判断该维度在给定日期是否应该执行计算。
* W 仅周日,M 仅月末最后一天,LDW/LDM 每天。
*
* @param date 参考日期
* @return true=应计算
*/
public abstract boolean shouldCompute(Date date);
/**
* 是否为快照维度(LDW/LDM每天覆盖,W/M为周期维度)。
*
* @return true=快照维度(删除时按维度级删),false=周期维度(按period级删)
*/
public abstract boolean isSnapshot();
/**
* 计算下一周期起止(endDate + 1 开始)。 * 计算下一周期起止(endDate + 1 开始)。
* *
* @param endDate 当前周期结束日期 * @param endDate 当前周期结束日期
......
...@@ -27,9 +27,10 @@ public enum WarningOperatorEnum { ...@@ -27,9 +27,10 @@ public enum WarningOperatorEnum {
} }
@Override @Override
public String buildWarningText(String metricName, BigDecimal metricDisplay, public String buildWarningText(String label, String unit,
BigDecimal thresholdDisplay, BigDecimal minDisplay, BigDecimal maxDisplay) { BigDecimal metricDisplay, BigDecimal thresholdDisplay,
return String.format("「%s」%.2f 高于 %.2f", metricName, metricDisplay, thresholdDisplay); BigDecimal minDisplay, BigDecimal maxDisplay) {
return String.format("%s%.2f%s高于目标值%.2f%s", label, metricDisplay, unit, thresholdDisplay, unit);
} }
}, },
LT("<", Category.SINGLE) { LT("<", Category.SINGLE) {
...@@ -39,9 +40,10 @@ public enum WarningOperatorEnum { ...@@ -39,9 +40,10 @@ public enum WarningOperatorEnum {
} }
@Override @Override
public String buildWarningText(String metricName, BigDecimal metricDisplay, public String buildWarningText(String label, String unit,
BigDecimal thresholdDisplay, BigDecimal minDisplay, BigDecimal maxDisplay) { BigDecimal metricDisplay, BigDecimal thresholdDisplay,
return String.format("「%s」%.2f 低于 %.2f", metricName, metricDisplay, thresholdDisplay); BigDecimal minDisplay, BigDecimal maxDisplay) {
return String.format("%s%.2f%s低于目标值%.2f%s", label, metricDisplay, unit, thresholdDisplay, unit);
} }
}, },
GE(">=", Category.SINGLE) { GE(">=", Category.SINGLE) {
...@@ -51,9 +53,10 @@ public enum WarningOperatorEnum { ...@@ -51,9 +53,10 @@ public enum WarningOperatorEnum {
} }
@Override @Override
public String buildWarningText(String metricName, BigDecimal metricDisplay, public String buildWarningText(String label, String unit,
BigDecimal thresholdDisplay, BigDecimal minDisplay, BigDecimal maxDisplay) { BigDecimal metricDisplay, BigDecimal thresholdDisplay,
return String.format("「%s」%.2f 高于或等于 %.2f", metricName, metricDisplay, thresholdDisplay); BigDecimal minDisplay, BigDecimal maxDisplay) {
return String.format("%s%.2f%s高于或等于目标值%.2f%s", label, metricDisplay, unit, thresholdDisplay, unit);
} }
}, },
LE("<=", Category.SINGLE) { LE("<=", Category.SINGLE) {
...@@ -63,9 +66,10 @@ public enum WarningOperatorEnum { ...@@ -63,9 +66,10 @@ public enum WarningOperatorEnum {
} }
@Override @Override
public String buildWarningText(String metricName, BigDecimal metricDisplay, public String buildWarningText(String label, String unit,
BigDecimal thresholdDisplay, BigDecimal minDisplay, BigDecimal maxDisplay) { BigDecimal metricDisplay, BigDecimal thresholdDisplay,
return String.format("「%s」%.2f 低于或等于 %.2f", metricName, metricDisplay, thresholdDisplay); BigDecimal minDisplay, BigDecimal maxDisplay) {
return String.format("%s%.2f%s低于或等于目标值%.2f%s", label, metricDisplay, unit, thresholdDisplay, unit);
} }
}, },
EQ("=", Category.SINGLE) { EQ("=", Category.SINGLE) {
...@@ -75,9 +79,10 @@ public enum WarningOperatorEnum { ...@@ -75,9 +79,10 @@ public enum WarningOperatorEnum {
} }
@Override @Override
public String buildWarningText(String metricName, BigDecimal metricDisplay, public String buildWarningText(String label, String unit,
BigDecimal thresholdDisplay, BigDecimal minDisplay, BigDecimal maxDisplay) { BigDecimal metricDisplay, BigDecimal thresholdDisplay,
return String.format("「%s」%.2f 等于 %.2f", metricName, metricDisplay, thresholdDisplay); BigDecimal minDisplay, BigDecimal maxDisplay) {
return String.format("%s%.2f%s等于目标值%.2f%s", label, metricDisplay, unit, thresholdDisplay, unit);
} }
}, },
...@@ -93,9 +98,10 @@ public enum WarningOperatorEnum { ...@@ -93,9 +98,10 @@ public enum WarningOperatorEnum {
} }
@Override @Override
public String buildWarningText(String metricName, BigDecimal metricDisplay, public String buildWarningText(String label, String unit,
BigDecimal thresholdDisplay, BigDecimal minDisplay, BigDecimal maxDisplay) { BigDecimal metricDisplay, BigDecimal thresholdDisplay,
return String.format("「%s」%.2f 低于 %.2f", metricName, metricDisplay, maxDisplay); BigDecimal minDisplay, BigDecimal maxDisplay) {
return String.format("%s%.2f%s低于目标值%.2f%s", label, metricDisplay, unit, maxDisplay, unit);
} }
}, },
/** /**
...@@ -109,9 +115,10 @@ public enum WarningOperatorEnum { ...@@ -109,9 +115,10 @@ public enum WarningOperatorEnum {
} }
@Override @Override
public String buildWarningText(String metricName, BigDecimal metricDisplay, public String buildWarningText(String label, String unit,
BigDecimal thresholdDisplay, BigDecimal minDisplay, BigDecimal maxDisplay) { BigDecimal metricDisplay, BigDecimal thresholdDisplay,
return String.format("「%s」%.2f 低于或等于 %.2f", metricName, metricDisplay, maxDisplay); BigDecimal minDisplay, BigDecimal maxDisplay) {
return String.format("%s%.2f%s低于或等于目标值%.2f%s", label, metricDisplay, unit, maxDisplay, unit);
} }
}, },
/** /**
...@@ -125,9 +132,10 @@ public enum WarningOperatorEnum { ...@@ -125,9 +132,10 @@ public enum WarningOperatorEnum {
} }
@Override @Override
public String buildWarningText(String metricName, BigDecimal metricDisplay, public String buildWarningText(String label, String unit,
BigDecimal thresholdDisplay, BigDecimal minDisplay, BigDecimal maxDisplay) { BigDecimal metricDisplay, BigDecimal thresholdDisplay,
return String.format("「%s」%.2f 低于 %.2f", metricName, metricDisplay, maxDisplay); BigDecimal minDisplay, BigDecimal maxDisplay) {
return String.format("%s%.2f%s低于目标值%.2f%s", label, metricDisplay, unit, maxDisplay, unit);
} }
}, },
/** /**
...@@ -141,9 +149,10 @@ public enum WarningOperatorEnum { ...@@ -141,9 +149,10 @@ public enum WarningOperatorEnum {
} }
@Override @Override
public String buildWarningText(String metricName, BigDecimal metricDisplay, public String buildWarningText(String label, String unit,
BigDecimal thresholdDisplay, BigDecimal minDisplay, BigDecimal maxDisplay) { BigDecimal metricDisplay, BigDecimal thresholdDisplay,
return String.format("「%s」%.2f 低于或等于 %.2f", metricName, metricDisplay, maxDisplay); BigDecimal minDisplay, BigDecimal maxDisplay) {
return String.format("%s%.2f%s低于或等于目标值%.2f%s", label, metricDisplay, unit, maxDisplay, unit);
} }
}; };
...@@ -172,16 +181,19 @@ public enum WarningOperatorEnum { ...@@ -172,16 +181,19 @@ public enum WarningOperatorEnum {
public abstract boolean evaluate(BigDecimal value, BigDecimal threshold, BigDecimal min, BigDecimal max); public abstract boolean evaluate(BigDecimal value, BigDecimal threshold, BigDecimal min, BigDecimal max);
/** /**
* 生成告警描述文本(统一入口)。 * 生成告警描述文本(统一入口)——label 由策略预先拼好,此处只拼正文。
* eg:品类扩展指标名称展示值(单位)逻辑语言目标值单位
* *
* @param metricName 指标名称 * @param label 指标标签(品类+指标名,由策略 buildWarningLabel 组装)
* @param metricDisplay 指标展示值 * @param unit 单位(生态预警传"",其余传实际单位)
* @param thresholdDisplay 阈值展示值(单值)或 null(区间) * @param metricDisplay 指标展示值
* @param minDisplay 区间下界展示值(区间)或 null(单值) * @param thresholdDisplay 阈值展示值(单值)或 null(区间)
* @param maxDisplay 区间上界展示值(区间)或 null(单值) * @param minDisplay 区间下界展示值(区间)或 null(单值)
* @param maxDisplay 区间上界展示值(区间)或 null(单值)
*/ */
public abstract String buildWarningText(String metricName, BigDecimal metricDisplay, public abstract String buildWarningText(String label, String unit,
BigDecimal thresholdDisplay, BigDecimal minDisplay, BigDecimal maxDisplay); BigDecimal metricDisplay, BigDecimal thresholdDisplay,
BigDecimal minDisplay, BigDecimal maxDisplay);
/** /**
* 根据 symbol 获取枚举。 * 根据 symbol 获取枚举。
......
package cn.com.glsx.dj.strategy.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* 预警类型枚举。
* <pre>
* <strong>项目组预警类型枚举,新增和删除该枚举请谨慎操作,预警引擎依赖于该枚举类
* {@link WarningTypeEnum#isFallback(Integer)}
* {@link WarningTypeEnum#isProjectGroup(Integer)}
* 运行!!!!!!!!!!!!!!!!!!!!!!!!
* </strong>
* <@link
* </pre>
* @author yangwei_by_claude
* @version 1.0
* @since 2026/06/01 14:00
*/
@Getter
@AllArgsConstructor
public enum WarningTypeEnum {
/** 兜底预警 */
FALLBACK(2, "兜底预警"),
/** 生态预警 */
ECO(3, "生态预警"),
/** 红色预警 */
RED(4, "红色预警"),
/** 黄色预警 */
YELLOW(5, "黄色预警");
private final Integer code;
private final String desc;
/**
* 是否为兜底预警类型。
*/
public static boolean isFallback(Integer warningType) {
return FALLBACK.getCode().equals(warningType);
}
/**
* 是否为组预警类型。
*/
public static boolean isProjectGroup(Integer warningType) {
return ECO.getCode().equals(warningType) || RED.getCode().equals(warningType) || YELLOW.getCode().equals(warningType);
}
/**
* 根据 code 获取枚举。
*/
public static WarningTypeEnum fromCode(Integer code) {
for (WarningTypeEnum t : values()) {
if (t.code.equals(code)) {
return t;
}
}
return null;
}
}
package cn.com.glsx.dj.strategy.job; package cn.com.glsx.dj.strategy.job;
import cn.com.glsx.dj.strategy.dto.warning.PeriodRange; import cn.com.glsx.dj.strategy.service.warning.executor.WarningComputeExecutor;
import cn.com.glsx.dj.strategy.enums.ProjectGroupBizEnum;
import cn.com.glsx.dj.strategy.enums.TimeDimensionEnum;
import cn.com.glsx.dj.strategy.mapper.PgGroupInfoMapper;
import cn.com.glsx.dj.strategy.mapper.PgGroupStoreRelMapper;
import cn.com.glsx.dj.strategy.model.projectgroup.PgGroupInfo;
import cn.com.glsx.dj.strategy.service.warning.StoreOutputService;
import cn.com.glsx.dj.strategy.service.warning.WarningEngineService;
import cn.hutool.core.date.DateUtil;
import com.dangdang.ddframe.job.api.ShardingContext; import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob; import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.oreframework.boot.autoconfigure.elasticjob.annotation.ElasticJobConf; import org.oreframework.boot.autoconfigure.elasticjob.annotation.ElasticJobConf;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/** /**
* 预警计算定时任务——每天执行,计算有产值门店和预警数据。 * 预警计算定时任务——每天凌晨2点,委托 WarningComputeExecutor 执行。
*
* <p>执行顺序:有产值门店 → 门店维度预警 → 员工维度预警。</p>
* *
* @author yangwei_by_claude * @author yangwei_by_claude
* @version 1.0 * @version 1.0
...@@ -40,80 +23,14 @@ import java.util.concurrent.TimeUnit; ...@@ -40,80 +23,14 @@ import java.util.concurrent.TimeUnit;
public class WarningComputeJob implements SimpleJob { public class WarningComputeJob implements SimpleJob {
@Resource @Resource
private StoreOutputService storeOutputService; private WarningComputeExecutor executor;
@Resource
private WarningEngineService warningEngineService;
@Resource
private PgGroupInfoMapper groupInfoMapper;
@Resource
private PgGroupStoreRelMapper storeRelMapper;
private final ExecutorService dataQueryExecutor = Executors.newFixedThreadPool(10); /** 手动指定计算日期(yyyy-MM-dd),为空则默认系统 T-1 */
@Value("${warning.compute.date:}")
private String computeDateStr;
@Override @Override
public void execute(ShardingContext shardingContext) { public void execute(ShardingContext shardingContext) {
log.info("预警计算定时任务开始执行"); executor.execute(computeDateStr);
Date today = new Date();
try {
// Step 1: 计算有产值门店(四种维度 × 三种业务)
storeOutputService.computeAll(today);
// Step 2: 加载所有启用项目组,并行计算预警
List<PgGroupInfo> groups = groupInfoMapper.selectAllEnabled();
if (CollectionUtils.isEmpty(groups)) {
log.info("无启用项目组,跳过预警计算");
return;
}
for (TimeDimensionEnum dim : TimeDimensionEnum.values()) {
PeriodRange range = dim.calculate(today);
for (ProjectGroupBizEnum biz : ProjectGroupBizEnum.values()) {
// 从 pg_store_output 获取有产值门店
List<Integer> outputStoreIds = storeOutputService.listStoreIdsWithOutput(
biz.getBiz(), dim.getCode(),
DateUtil.format(range.getStart(), "yyyy-MM-dd"),
DateUtil.format(range.getEnd(), "yyyy-MM-dd"));
if (CollectionUtils.isEmpty(outputStoreIds)) {
log.info("无有产值门店,跳过,biz={}, dim={}", biz.getBiz(), dim.getCode());
continue;
}
// 按项目组并行计算
List<CompletableFuture<Void>> futures = new ArrayList<>();
for (PgGroupInfo group : groups) {
futures.add(CompletableFuture.runAsync(() -> {
try {
// 项目组门店 ∩ 有产值门店
List<Integer> groupStoreIds = storeRelMapper.listMerchantIdsByGroupId(group.getId());
if (CollectionUtils.isEmpty(groupStoreIds)) {
return;
}
List<Integer> intersection = new ArrayList<>(groupStoreIds);
intersection.retainAll(outputStoreIds);
if (intersection.isEmpty()) {
return;
}
// 门店+员工维度预警(monitorTarget区分,引擎内自动处理)
warningEngineService.computeWarnings(dim.getCode(),
range.getStart(), range.getEnd(), biz.getBiz(), intersection);
} catch (Exception e) {
log.error("项目组预警计算失败,groupId={}, biz={}, dim={}",
group.getId(), biz.getBiz(), dim.getCode(), e);
}
}, dataQueryExecutor));
}
// 等待全部项目组计算完成
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
}
}
log.info("预警计算定时任务执行完成");
} catch (Exception e) {
log.error("预警计算定时任务执行异常", e);
}
} }
} }
package cn.com.glsx.dj.strategy.job; package cn.com.glsx.dj.strategy.job;
import cn.com.glsx.dj.strategy.dto.warning.PeriodRange; import cn.com.glsx.dj.strategy.service.warning.executor.WarningHistoryBackfillExecutor;
import cn.com.glsx.dj.strategy.enums.ProjectGroupBizEnum;
import cn.com.glsx.dj.strategy.enums.TimeDimensionEnum;
import cn.com.glsx.dj.strategy.mapper.PgGroupInfoMapper;
import cn.com.glsx.dj.strategy.service.warning.StoreOutputService;
import cn.com.glsx.dj.strategy.service.warning.WarningEngineService;
import com.dangdang.ddframe.job.api.ShardingContext; import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob; import com.dangdang.ddframe.job.api.simple.SimpleJob;
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.Value;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
/** /**
* 历史数据补跑定时任务——从 2026 年 1 月 1 日起逐周期回溯计算。 * 历史数据补跑定时任务——委托 WarningHistoryBackfillExecutor 执行。
*
* <p>按周/月/截止周最新一天/截止月最新一天逐周期回溯,写入 warning_record 和 pg_store_output。
* 一次性执行,跑完后通过持久化标记跳过重复执行。</p>
* *
* @author yangwei_by_claude * @author yangwei_by_claude
* @version 1.0 * @version 1.0
...@@ -32,73 +23,14 @@ import java.util.Date; ...@@ -32,73 +23,14 @@ import java.util.Date;
public class WarningHistoryBackfillJob implements SimpleJob { public class WarningHistoryBackfillJob implements SimpleJob {
@Resource @Resource
private StoreOutputService storeOutputService; private WarningHistoryBackfillExecutor executor;
@Resource
private WarningEngineService warningEngineService;
@Resource
private PgGroupInfoMapper groupInfoMapper;
/** 历史数据起始日期:2026-01-01 */
private static final Date BACKFILL_START = getBackfillStartDate();
/** Redis key 标记是否已完成 */ /** 起始日期(yyyy-MM-dd),默认 2026-01-01 */
private static final String BACKFILL_DONE_KEY = "warning:history:backfill:done"; @Value("${warning.history.backfill.start:2026-01-01}")
private String backfillStartStr;
@Override @Override
public void execute(ShardingContext shardingContext) { public void execute(ShardingContext shardingContext) {
log.info("历史数据补跑任务开始执行"); executor.execute(backfillStartStr);
try {
// TODO: 检查 Redis 标记,已执行过则跳过
// if (redisTemplate.hasKey(BACKFILL_DONE_KEY)) { skip }
Calendar startCal = Calendar.getInstance();
startCal.setTime(BACKFILL_START);
Calendar endCal = Calendar.getInstance();
endCal.setTime(new Date());
// 逐周回溯
Calendar weekCursor = (Calendar) startCal.clone();
while (weekCursor.before(endCal)) {
Date cursorDate = weekCursor.getTime();
PeriodRange weekRange = TimeDimensionEnum.W.calculate(cursorDate);
PeriodRange ldwRange = TimeDimensionEnum.LDW.calculate(cursorDate);
for (ProjectGroupBizEnum biz : ProjectGroupBizEnum.values()) {
storeOutputService.computeStoreOutputs(biz.getBiz(),
TimeDimensionEnum.W.getCode(), weekRange);
storeOutputService.computeStoreOutputs(biz.getBiz(),
TimeDimensionEnum.LDW.getCode(), ldwRange);
}
weekCursor.add(Calendar.WEEK_OF_YEAR, 1);
}
// 逐月回溯
Calendar monthCursor = (Calendar) startCal.clone();
while (monthCursor.before(endCal)) {
Date cursorDate = monthCursor.getTime();
PeriodRange monthRange = TimeDimensionEnum.M.calculate(cursorDate);
PeriodRange ldmRange = TimeDimensionEnum.LDM.calculate(cursorDate);
for (ProjectGroupBizEnum biz : ProjectGroupBizEnum.values()) {
storeOutputService.computeStoreOutputs(biz.getBiz(),
TimeDimensionEnum.M.getCode(), monthRange);
storeOutputService.computeStoreOutputs(biz.getBiz(),
TimeDimensionEnum.LDM.getCode(), ldmRange);
}
monthCursor.add(Calendar.MONTH, 1);
}
// TODO: 标记完成 Redis set(BACKFILL_DONE_KEY, "1")
log.info("历史数据补跑任务执行完成");
} catch (Exception e) {
log.error("历史数据补跑任务执行异常", e);
}
}
private static Date getBackfillStartDate() {
Calendar cal = Calendar.getInstance();
cal.set(2026, Calendar.JANUARY, 1, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
} }
} }
...@@ -32,7 +32,7 @@ public interface PgStoreOutputMapper extends OreMapper<PgStoreOutput> { ...@@ -32,7 +32,7 @@ public interface PgStoreOutputMapper extends OreMapper<PgStoreOutput> {
@Param("periodEnd") String periodEnd); @Param("periodEnd") String periodEnd);
/** /**
* 按条件删除(幂等重算用)。 * 按条件删除(幂等重算用,W/M 维度使用)。
* *
* @param businessType 业务类型 * @param businessType 业务类型
* @param timeDimension 时间维度 * @param timeDimension 时间维度
...@@ -46,6 +46,16 @@ public interface PgStoreOutputMapper extends OreMapper<PgStoreOutput> { ...@@ -46,6 +46,16 @@ public interface PgStoreOutputMapper extends OreMapper<PgStoreOutput> {
@Param("periodEnd") String periodEnd); @Param("periodEnd") String periodEnd);
/** /**
* 按业务线+维度删除所有记录(用于 LDW/LDM 快照维度,不论 period)。
*
* @param businessType 业务类型
* @param timeDimension 时间维度
* @return 删除条数
*/
int deleteByBizAndDimension(@Param("businessType") Integer businessType,
@Param("timeDimension") String timeDimension);
/**
* 批量插入有产值门店记录。 * 批量插入有产值门店记录。
* *
* @param list 记录列表 * @param list 记录列表
......
...@@ -36,7 +36,7 @@ public interface PgWarningRecordMapper extends OreMapper<PgWarningRecord> { ...@@ -36,7 +36,7 @@ public interface PgWarningRecordMapper extends OreMapper<PgWarningRecord> {
int batchInsert(@Param("records") List<PgWarningRecord> records); int batchInsert(@Param("records") List<PgWarningRecord> records);
/** /**
* 按条件删除预警记录(用于幂等重算)。 * 按条件删除预警记录(用于幂等重算,W/M 维度使用)。
* *
* @param configId 配置ID * @param configId 配置ID
* @param timeDimension 时间维度 * @param timeDimension 时间维度
...@@ -48,4 +48,14 @@ public interface PgWarningRecordMapper extends OreMapper<PgWarningRecord> { ...@@ -48,4 +48,14 @@ public interface PgWarningRecordMapper extends OreMapper<PgWarningRecord> {
@Param("timeDimension") String timeDimension, @Param("timeDimension") String timeDimension,
@Param("periodStart") String periodStart, @Param("periodStart") String periodStart,
@Param("periodEnd") String periodEnd); @Param("periodEnd") String periodEnd);
/**
* 按配置+维度删除所有预警记录(用于 LDW/LDM 快照维度,不论 period)。
*
* @param configId 配置ID
* @param timeDimension 时间维度
* @return 删除条数
*/
int deleteByConfigAndDimension(@Param("configId") Integer configId,
@Param("timeDimension") String timeDimension);
} }
...@@ -39,7 +39,6 @@ public class BiMetricQueryService { ...@@ -39,7 +39,6 @@ public class BiMetricQueryService {
private Environment environment; private Environment environment;
public static final String DATE_METHOD = "data/"; public static final String DATE_METHOD = "data/";
private static final String DETAIL_METHOD = "detail/";
private String getBaseUrl() { private String getBaseUrl() {
return environment.getProperty("tianqi.query.base.url", "http://192.168.3.211:8021/"); return environment.getProperty("tianqi.query.base.url", "http://192.168.3.211:8021/");
......
package cn.com.glsx.dj.strategy.service.warning; package cn.com.glsx.dj.strategy.service.warning;
import cn.com.glsx.dj.strategy.consts.WarningEngineConsts;
import cn.com.glsx.dj.strategy.dto.warning.PeriodRange; import cn.com.glsx.dj.strategy.dto.warning.PeriodRange;
import cn.com.glsx.dj.strategy.enums.BiAggregationTypeEnum; import cn.com.glsx.dj.strategy.enums.BiAggregationTypeEnum;
import cn.com.glsx.dj.strategy.enums.BiDateTypeEnum; import cn.com.glsx.dj.strategy.enums.BiDateTypeEnum;
...@@ -8,10 +9,12 @@ import cn.com.glsx.dj.strategy.enums.ProjectGroupBizEnum; ...@@ -8,10 +9,12 @@ import cn.com.glsx.dj.strategy.enums.ProjectGroupBizEnum;
import cn.com.glsx.dj.strategy.enums.TimeDimensionEnum; import cn.com.glsx.dj.strategy.enums.TimeDimensionEnum;
import cn.com.glsx.dj.strategy.mapper.PgStoreOutputMapper; import cn.com.glsx.dj.strategy.mapper.PgStoreOutputMapper;
import cn.com.glsx.dj.strategy.model.projectgroup.PgStoreOutput; import cn.com.glsx.dj.strategy.model.projectgroup.PgStoreOutput;
import cn.com.glsx.framework.core.beans.BaseModel;
import cn.hutool.core.date.DateUtil; import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j; import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import javax.annotation.Resource; import javax.annotation.Resource;
import java.math.BigDecimal; import java.math.BigDecimal;
...@@ -44,6 +47,7 @@ public class StoreOutputService { ...@@ -44,6 +47,7 @@ public class StoreOutputService {
* @param timeDimension 时间维度 * @param timeDimension 时间维度
* @param range 周期起止 * @param range 周期起止
*/ */
@Transactional(rollbackFor = Exception.class)
public void computeStoreOutputs(Integer biz, String timeDimension, PeriodRange range) { public void computeStoreOutputs(Integer biz, String timeDimension, PeriodRange range) {
String periodStart = DateUtil.format(range.getStart(), "yyyy-MM-dd"); String periodStart = DateUtil.format(range.getStart(), "yyyy-MM-dd");
String periodEnd = DateUtil.format(range.getEnd(), "yyyy-MM-dd"); String periodEnd = DateUtil.format(range.getEnd(), "yyyy-MM-dd");
...@@ -59,7 +63,7 @@ public class StoreOutputService { ...@@ -59,7 +63,7 @@ public class StoreOutputService {
List<BiMetricQueryService.ItemDetail> items; List<BiMetricQueryService.ItemDetail> items;
try { try {
items = biMetricQueryService.getItemDetail(params, "data/"); items = biMetricQueryService.getItemDetail(params, BiMetricQueryService.DATE_METHOD);
} catch (Exception e) { } catch (Exception e) {
log.error("查询有产值门店失败,biz={}, timeDimension={}", biz, timeDimension, e); log.error("查询有产值门店失败,biz={}, timeDimension={}", biz, timeDimension, e);
return; return;
...@@ -69,8 +73,12 @@ public class StoreOutputService { ...@@ -69,8 +73,12 @@ public class StoreOutputService {
return; return;
} }
// 幂等删除旧记录 // 幂等删除旧记录:快照维度按维度级删除,周期维度按period级删除
storeOutputMapper.deleteByCondition(biz, timeDimension, periodStart, periodEnd); if (TimeDimensionEnum.fromCode(timeDimension).isSnapshot()) {
storeOutputMapper.deleteByBizAndDimension(biz, timeDimension);
} else {
storeOutputMapper.deleteByCondition(biz, timeDimension, periodStart, periodEnd);
}
// 构造 PgStoreOutput 列表 // 构造 PgStoreOutput 列表
List<PgStoreOutput> outputs = new ArrayList<>(); List<PgStoreOutput> outputs = new ArrayList<>();
...@@ -78,6 +86,8 @@ public class StoreOutputService { ...@@ -78,6 +86,8 @@ public class StoreOutputService {
if (item.getMerchantId() == null) { if (item.getMerchantId() == null) {
continue; continue;
} }
Date now = new Date();
PgStoreOutput output = new PgStoreOutput(); PgStoreOutput output = new PgStoreOutput();
output.setBusinessType(biz); output.setBusinessType(biz);
output.setStoreId(Integer.valueOf(item.getMerchantId())); output.setStoreId(Integer.valueOf(item.getMerchantId()));
...@@ -85,9 +95,11 @@ public class StoreOutputService { ...@@ -85,9 +95,11 @@ public class StoreOutputService {
output.setTimeDimension(timeDimension); output.setTimeDimension(timeDimension);
output.setPeriodStart(range.getStart()); output.setPeriodStart(range.getStart());
output.setPeriodEnd(range.getEnd()); output.setPeriodEnd(range.getEnd());
output.setDeletedFlag("N"); output.setDeletedFlag(BaseModel.DeletedFlagEnum.N.name());
output.setCreatedDate(new Date()); output.setCreatedDate(now);
output.setUpdatedDate(new Date()); output.setUpdatedDate(now);
output.setCreatedBy(WarningEngineConsts.SYSTEM);
output.setUpdatedBy(WarningEngineConsts.SYSTEM);
outputs.add(output); outputs.add(output);
} }
......
...@@ -151,6 +151,7 @@ public class WarningRecordService { ...@@ -151,6 +151,7 @@ public class WarningRecordService {
dto.setStaffId(request.getStaffId()); dto.setStaffId(request.getStaffId());
dto.setStoreName(request.getStoreName()); dto.setStoreName(request.getStoreName());
dto.setIsStrategySent(request.getIsStrategySent()); dto.setIsStrategySent(request.getIsStrategySent());
dto.setStaffIds(request.getStaffIds());
return dto; return dto;
} }
} }
package cn.com.glsx.dj.strategy.service.warning.config;
import cn.com.glsx.dj.strategy.enums.WarningTypeEnum;
import cn.com.glsx.dj.strategy.mapper.PgGroupStoreRelMapper;
import cn.com.glsx.dj.strategy.model.projectgroup.PgWarningConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.List;
import java.util.stream.Collectors;
/**
* 兜底配置加载策略——warning_type = 2(兜底预警),直接使用全量有产值门店。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/06/01 14:00
*/
@Slf4j
@Component
public class FallbackConfigLoadStrategy implements WarningConfigLoadStrategy {
@Override
public List<PgWarningConfig> filter(List<PgWarningConfig> allConfigs, Integer biz) {
List<PgWarningConfig> filtered = allConfigs.stream()
.filter(c -> biz.equals(c.getBiz()) && WarningTypeEnum.isFallback(c.getWarningType()))
.collect(Collectors.toList());
log.info("兜底策略筛选,warningType={}, biz={}, configCount={}",
WarningTypeEnum.FALLBACK.getCode(), biz, filtered.size());
return filtered;
}
@Override
public List<Integer> resolveStoreIds(PgWarningConfig config, List<Integer> allOutputStoreIds,
PgGroupStoreRelMapper storeRelMapper) {
log.info("兜底策略,使用全量有产值门店,storeCount={}", allOutputStoreIds.size());
return allOutputStoreIds;
}
}
package cn.com.glsx.dj.strategy.service.warning.config;
import cn.com.glsx.dj.strategy.enums.WarningTypeEnum;
import cn.com.glsx.dj.strategy.mapper.PgGroupStoreRelMapper;
import cn.com.glsx.dj.strategy.model.projectgroup.PgWarningConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;
/**
* 项目组配置加载策略——非兜底预警类型(黄/红/生态),取项目组门店 ∩ 有产值门店。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/06/01 14:00
*/
@Slf4j
@Component
public class ProjectGroupConfigLoadStrategy implements WarningConfigLoadStrategy {
@Override
public List<PgWarningConfig> filter(List<PgWarningConfig> allConfigs, Integer biz) {
List<PgWarningConfig> filtered = allConfigs.stream()
.filter(c -> biz.equals(c.getBiz()) && WarningTypeEnum.isProjectGroup(c.getWarningType()))
.collect(Collectors.toList());
log.info("项目组策略筛选,biz={}, configCount={}", biz, filtered.size());
return filtered;
}
@Override
public List<Integer> resolveStoreIds(PgWarningConfig config, List<Integer> allOutputStoreIds,
PgGroupStoreRelMapper storeRelMapper) {
List<Integer> groupStoreIds = storeRelMapper.listMerchantIdsByGroupId(config.getGroupId());
if (CollectionUtils.isEmpty(groupStoreIds)) {
log.info("项目组无门店,跳过,groupId={}", config.getGroupId());
return new ArrayList<>();
}
List<Integer> intersection = new ArrayList<>(groupStoreIds);
intersection.retainAll(allOutputStoreIds);
if (intersection.isEmpty()) {
log.info("项目组门店与有产值门店无交集,跳过,groupId={}, groupStores={}, outputStores={}",
config.getGroupId(), groupStoreIds.size(), allOutputStoreIds.size());
}
return intersection;
}
}
package cn.com.glsx.dj.strategy.service.warning.config;
import cn.com.glsx.dj.strategy.dto.warning.ConditionDTO;
import cn.com.glsx.dj.strategy.mapper.PgGroupStoreRelMapper;
import cn.com.glsx.dj.strategy.mapper.PgWarningMetricDictMapper;
import cn.com.glsx.dj.strategy.model.projectgroup.PgWarningConfig;
import cn.com.glsx.dj.strategy.model.projectgroup.PgWarningMetricDict;
import cn.com.glsx.dj.strategy.service.warning.WarningEngineService;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* 配置加载上下文——由调用方传入全量配置,依次用所有 WarningConfigLoadStrategy 执行预警计算。
* 策略通过 Spring 自动注入 List,新增策略只需加 @Component 即可。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/06/01 14:00
*/
@Slf4j
@Component
public class WarningConfigLoadContext {
@Resource
private WarningEngineService warningEngineService;
@Resource
private PgWarningMetricDictMapper metricDictMapper;
@Resource
private PgGroupStoreRelMapper storeRelMapper;
/** Spring 自动注入所有 WarningConfigLoadStrategy 实现 */
@Resource
private List<WarningConfigLoadStrategy> strategies;
/**
* 按策略执行预警计算。
*
* @param allConfigs 全量启用配置(由调用方查一次传入)
* @param timeDimension 时间维度
* @param periodStart 周期开始
* @param periodEnd 周期结束
* @param biz 业务类型
* @param allOutputStoreIds 有产值门店列表
* @param batchSize 分批落库大小
*/
public void loadAndCompute(List<PgWarningConfig> allConfigs, String timeDimension,
Date periodStart, Date periodEnd,
Integer biz, List<Integer> allOutputStoreIds, int batchSize) {
if (CollectionUtils.isEmpty(allConfigs)) {
log.info("无启用配置,跳过,biz={}, dim={}", biz, timeDimension);
return;
}
// 收集所有 config 中的 metricIds,批量加载指标字典(外层循环只查一次)
List<Integer> allMetricIds = new ArrayList<>();
for (WarningConfigLoadStrategy strategy : strategies) {
for (PgWarningConfig config : strategy.filter(allConfigs, biz)) {
List<ConditionDTO> conditions = JSON.parseArray(config.getRuleJson(), ConditionDTO.class);
if (CollectionUtils.isNotEmpty(conditions)) {
for (ConditionDTO c : conditions) {
if (c.getMetricId() != null) {
allMetricIds.add(c.getMetricId());
}
}
}
}
}
Map<Integer, PgWarningMetricDict> metricDictMap = loadMetricDict(allMetricIds);
for (WarningConfigLoadStrategy strategy : strategies) {
List<PgWarningConfig> configs = strategy.filter(allConfigs, biz);
if (CollectionUtils.isEmpty(configs)) {
continue;
}
for (PgWarningConfig config : configs) {
try {
List<Integer> storeIds = strategy.resolveStoreIds(config, allOutputStoreIds, storeRelMapper);
if (CollectionUtils.isEmpty(storeIds)) {
continue;
}
warningEngineService.computeWarnings(config, timeDimension,
periodStart, periodEnd, storeIds, batchSize, metricDictMap);
} catch (Exception e) {
log.error("预警计算失败,configId={}, strategy={}",
config.getId(), strategy.getClass().getSimpleName(), e);
}
}
}
}
/**
* 批量加载指标字典。
*/
private Map<Integer, PgWarningMetricDict> loadMetricDict(List<Integer> metricIds) {
Map<Integer, PgWarningMetricDict> map = new LinkedHashMap<>();
if (CollectionUtils.isEmpty(metricIds)) {
return map;
}
List<PgWarningMetricDict> dicts = metricDictMapper.selectByIds(metricIds);
if (CollectionUtils.isNotEmpty(dicts)) {
for (PgWarningMetricDict dict : dicts) {
map.put(dict.getId(), dict);
}
}
log.info("预加载指标字典,metricIds={}, 命中数={}", metricIds, map.size());
return map;
}
}
package cn.com.glsx.dj.strategy.service.warning.config;
import cn.com.glsx.dj.strategy.mapper.PgGroupStoreRelMapper;
import cn.com.glsx.dj.strategy.model.projectgroup.PgWarningConfig;
import java.util.List;
/**
* 预警配置加载策略——分离兜底和项目组两种配置的加载+门店范围确定方式。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/06/01 14:00
*/
public interface WarningConfigLoadStrategy {
/**
* 从全量配置中筛选属于该策略的配置。
*
* @param allConfigs 全量启用配置
* @param biz 业务类型
* @return 筛选后的配置列表
*/
List<PgWarningConfig> filter(List<PgWarningConfig> allConfigs, Integer biz);
/**
* 确定该策略参与计算的门店范围。
*
* @param config 预警配置
* @param allOutputStoreIds 有产值门店列表
* @param storeRelMapper 项目组-门店关系Mapper
* @return 参与计算的门店ID列表
*/
List<Integer> resolveStoreIds(PgWarningConfig config, List<Integer> allOutputStoreIds,
PgGroupStoreRelMapper storeRelMapper);
}
package cn.com.glsx.dj.strategy.service.warning.executor;
import cn.com.glsx.dj.strategy.dto.warning.PeriodRange;
import cn.com.glsx.dj.strategy.enums.ProjectGroupBizEnum;
import cn.com.glsx.dj.strategy.enums.TimeDimensionEnum;
import cn.com.glsx.dj.strategy.mapper.PgWarningConfigMapper;
import cn.com.glsx.dj.strategy.model.projectgroup.PgWarningConfig;
import cn.com.glsx.dj.strategy.service.warning.StoreOutputService;
import cn.com.glsx.dj.strategy.service.warning.WarningEngineService;
import cn.com.glsx.dj.strategy.service.warning.config.WarningConfigLoadContext;
import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
/**
* 预警计算执行器——每天执行有产值门店+预警计算。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/06/02 14:00
*/
@Slf4j
@Component
public class WarningComputeExecutor {
@Resource
private StoreOutputService storeOutputService;
@Resource
private WarningConfigLoadContext configLoadContext;
@Resource
private PgWarningConfigMapper configMapper;
/**
* 执行预警计算。
*
* @param computeDateStr 手动指定计算日期(yyyy-MM-dd),为空则默认 T-1
*/
public void execute(String computeDateStr) {
long startTime = System.currentTimeMillis();
Date t1Date = getT1Date(computeDateStr);
log.info("预警计算开始执行,T-1日期={}", DateUtil.format(t1Date, "yyyy-MM-dd"));
try {
List<PgWarningConfig> allConfigs = configMapper.selectAllEnabled();
for (TimeDimensionEnum dim : TimeDimensionEnum.values()) {
if (!dim.shouldCompute(t1Date)) {
log.info("非计算日,跳过,dim={}, t1Date={}", dim.getCode(),
DateUtil.format(t1Date, "yyyy-MM-dd"));
continue;
}
PeriodRange range = dim.calculate(t1Date);
for (ProjectGroupBizEnum biz : ProjectGroupBizEnum.values()) {
try {
storeOutputService.computeStoreOutputs(biz.getBiz(), dim.getCode(), range);
String periodStart = DateUtil.format(range.getStart(), "yyyy-MM-dd");
String periodEnd = DateUtil.format(range.getEnd(), "yyyy-MM-dd");
List<Integer> outputStoreIds = storeOutputService.listStoreIdsWithOutput(
biz.getBiz(), dim.getCode(), periodStart, periodEnd);
if (CollectionUtils.isEmpty(outputStoreIds)) {
log.info("产值计算:无有产值门店,跳过,biz={}, dim={}", biz.getBiz(), dim.getCode());
continue;
}
configLoadContext.loadAndCompute(allConfigs, dim.getCode(),
range.getStart(), range.getEnd(),
biz.getBiz(), outputStoreIds,
WarningEngineService.DEFAULT_BATCH_SIZE);
} catch (Exception e) {
log.error("预警计算失败,biz={}, dim={}", biz.getBiz(), dim.getCode(), e);
}
}
}
long cost = System.currentTimeMillis() - startTime;
log.info("预警计算执行完成,总耗时={}ms", cost);
} catch (Exception e) {
log.error("预警计算执行异常", e);
}
}
/**
* 获取计算日期:优先手动指定,为空则默认系统 T-1。
*/
private Date getT1Date(String computeDateStr) {
if (computeDateStr != null && !computeDateStr.isEmpty()) {
try {
return new SimpleDateFormat("yyyy-MM-dd").parse(computeDateStr);
} catch (ParseException e) {
log.warn("配置日期解析失败,回退系统T-1,input={}", computeDateStr, e);
}
}
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DAY_OF_MONTH, -1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
}
package cn.com.glsx.dj.strategy.service.warning.executor;
import cn.com.glsx.dj.strategy.dto.warning.PeriodRange;
import cn.com.glsx.dj.strategy.enums.ProjectGroupBizEnum;
import cn.com.glsx.dj.strategy.enums.TimeDimensionEnum;
import cn.com.glsx.dj.strategy.mapper.PgWarningConfigMapper;
import cn.com.glsx.dj.strategy.model.projectgroup.PgWarningConfig;
import cn.com.glsx.dj.strategy.service.warning.StoreOutputService;
import cn.com.glsx.dj.strategy.service.warning.WarningEngineService;
import cn.com.glsx.dj.strategy.service.warning.config.WarningConfigLoadContext;
import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
/**
* 历史数据补跑执行器——从指定起始日起逐 W/M 周期回溯计算预警数据。
* 一次性任务,Redis 标记防止重复执行。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/06/02 14:00
*/
@Slf4j
@Component
public class WarningHistoryBackfillExecutor {
private static final String BACKFILL_DONE_KEY = "warning:history:backfill:done";
@Resource
private StoreOutputService storeOutputService;
@Resource
private WarningConfigLoadContext configLoadContext;
@Resource
private PgWarningConfigMapper configMapper;
@Resource
private StringRedisTemplate stringRedisTemplate;
/**
* 执行历史数据补跑。
*
* @param backfillStartStr 起始日期(yyyy-MM-dd),默认 2026-01-01
*/
public void execute(String backfillStartStr) {
if (isAlreadyDone()) {
log.info("历史数据补跑已完成,跳过");
return;
}
long startTime = System.currentTimeMillis();
Date backfillStart = parseDate(backfillStartStr);
log.info("历史数据补跑开始执行,起始日期={}", backfillStartStr);
try {
List<PgWarningConfig> allConfigs = configMapper.selectAllEnabled();
Date today = getTodayZero();
int weekCount = 0;
int monthCount = 0;
// 逐 W 周期回溯
Calendar weekCursor = Calendar.getInstance();
weekCursor.setTime(backfillStart);
while (weekCursor.getTime().before(today)) {
PeriodRange weekRange = TimeDimensionEnum.W.calculate(weekCursor.getTime());
for (ProjectGroupBizEnum biz : ProjectGroupBizEnum.values()) {
try {
backfillPeriod(allConfigs, biz.getBiz(), TimeDimensionEnum.W.getCode(), weekRange);
} catch (Exception e) {
log.error("历史回跑W周期失败,biz={}, date={}",
biz.getBiz(), DateUtil.format(weekCursor.getTime(), "yyyy-MM-dd"), e);
}
}
weekCount++;
weekCursor.add(Calendar.WEEK_OF_YEAR, 1);
}
// 逐 M 周期回溯
Calendar monthCursor = Calendar.getInstance();
monthCursor.setTime(backfillStart);
while (monthCursor.getTime().before(today)) {
PeriodRange monthRange = TimeDimensionEnum.M.calculate(monthCursor.getTime());
for (ProjectGroupBizEnum biz : ProjectGroupBizEnum.values()) {
try {
backfillPeriod(allConfigs, biz.getBiz(), TimeDimensionEnum.M.getCode(), monthRange);
} catch (Exception e) {
log.error("历史回跑M周期失败,biz={}, date={}",
biz.getBiz(), DateUtil.format(monthCursor.getTime(), "yyyy-MM-dd"), e);
}
}
monthCount++;
monthCursor.add(Calendar.MONTH, 1);
}
// LDW + LDM 只算最新周期
for (TimeDimensionEnum dim : new TimeDimensionEnum[]{TimeDimensionEnum.LDW, TimeDimensionEnum.LDM}) {
PeriodRange range = dim.calculate(today);
for (ProjectGroupBizEnum biz : ProjectGroupBizEnum.values()) {
try {
backfillPeriod(allConfigs, biz.getBiz(), dim.getCode(), range);
} catch (Exception e) {
log.error("快照维度计算失败,biz={}, dim={}", biz.getBiz(), dim.getCode(), e);
}
}
}
markDone();
long cost = System.currentTimeMillis() - startTime;
log.info("历史数据补跑执行完成,W周期={}, M周期={}, 总耗时={}ms", weekCount, monthCount, cost);
} catch (Exception e) {
log.error("历史数据补跑执行异常", e);
}
}
private void backfillPeriod(List<PgWarningConfig> allConfigs, Integer biz, String dim, PeriodRange range) {
storeOutputService.computeStoreOutputs(biz, dim, range);
String periodStart = DateUtil.format(range.getStart(), "yyyy-MM-dd");
String periodEnd = DateUtil.format(range.getEnd(), "yyyy-MM-dd");
List<Integer> outputStoreIds = storeOutputService.listStoreIdsWithOutput(biz, dim, periodStart, periodEnd);
if (CollectionUtils.isEmpty(outputStoreIds)) {
log.info("历史回跑无有产值门店,跳过,biz={}, dim={}", biz, dim);
return;
}
configLoadContext.loadAndCompute(allConfigs, dim, range.getStart(), range.getEnd(),
biz, outputStoreIds, WarningEngineService.DEFAULT_BATCH_SIZE);
}
private boolean isAlreadyDone() {
try {
if (stringRedisTemplate != null) {
return stringRedisTemplate.hasKey(BACKFILL_DONE_KEY);
}
} catch (Exception e) {
log.warn("Redis检查失败,默认未执行", e);
}
return false;
}
private void markDone() {
try {
if (stringRedisTemplate != null) {
stringRedisTemplate.opsForValue().set(BACKFILL_DONE_KEY, "1");
log.info("历史数据补跑标记完成");
}
} catch (Exception e) {
log.warn("Redis标记失败", e);
}
}
private Date parseDate(String dateStr) {
try {
return new SimpleDateFormat("yyyy-MM-dd").parse(dateStr);
} catch (ParseException e) {
log.warn("起始日期解析失败,使用默认 2026-01-01,input={}", dateStr, e);
Calendar cal = Calendar.getInstance();
cal.set(2026, Calendar.JANUARY, 1, 0, 0, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
}
private Date getTodayZero() {
Calendar cal = Calendar.getInstance();
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal.getTime();
}
}
...@@ -17,14 +17,19 @@ import java.util.Map; ...@@ -17,14 +17,19 @@ import java.util.Map;
/** /**
* 动态SQL阈值策略——批量执行SQL,按 merchantNo 分组返回阈值。 * 动态SQL阈值策略——批量执行SQL,按 merchantNo 分组返回阈值。
* *
* <p>SQL 结果集必须包含 merchant_id 列(或 store_id),用于区分不同门店的阈值。</p>
*
* @author yangwei_by_claude * @author yangwei_by_claude
* @version 1.0 * @version 1.1
* @since 2026/05/28 14:00 * @since 2026/05/28 14:00
*/ */
@Slf4j @Slf4j
@Component @Component
public class DynamicSqlThresholdStrategy implements ThresholdStrategy { public class DynamicSqlThresholdStrategy implements ThresholdStrategy {
/** SQL 结果集中标识商户的列名候选 */
private static final String[] MERCHANT_ID_KEYS = {"merchant_id", "store_id", "merchantId", "storeId", "merchant_id4s"};
@Resource @Resource
private JdbcTemplate jdbcTemplate; private JdbcTemplate jdbcTemplate;
...@@ -39,8 +44,8 @@ public class DynamicSqlThresholdStrategy implements ThresholdStrategy { ...@@ -39,8 +44,8 @@ public class DynamicSqlThresholdStrategy implements ThresholdStrategy {
} }
@Override @Override
public Map<Integer, ThresholdValue> batchResolve(List<ConditionDTO> conditions) { public Map<Integer, Map<String, ThresholdValue>> batchResolve(List<ConditionDTO> conditions) {
Map<Integer, ThresholdValue> result = new LinkedHashMap<>(); Map<Integer, Map<String, ThresholdValue>> result = new LinkedHashMap<>();
for (ConditionDTO cond : conditions) { for (ConditionDTO cond : conditions) {
ThresholdDTO t = cond.getThreshold(); ThresholdDTO t = cond.getThreshold();
if (t == null || t.getType() == null || t.getType() != ThresholdTypeEnum.DYNAMIC_SQL.getType()) { if (t == null || t.getType() == null || t.getType() != ThresholdTypeEnum.DYNAMIC_SQL.getType()) {
...@@ -51,16 +56,14 @@ public class DynamicSqlThresholdStrategy implements ThresholdStrategy { ...@@ -51,16 +56,14 @@ public class DynamicSqlThresholdStrategy implements ThresholdStrategy {
if (sql == null || sql.trim().isEmpty()) { if (sql == null || sql.trim().isEmpty()) {
continue; continue;
} }
// 动态SQL只允许SELECT
String upperSql = sql.trim().toUpperCase(); String upperSql = sql.trim().toUpperCase();
if (!upperSql.startsWith("SELECT")) { if (!upperSql.startsWith("SELECT")) {
log.warn("动态SQL不是SELECT语句,跳过: {}", sql); log.warn("动态SQL不是SELECT语句,跳过: {}", sql);
continue; continue;
} }
List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql); List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql);
// 按条件序号保存,后续使用时按 merchantNo 匹配 Map<String, ThresholdValue> byMerchant = buildMerchantThresholdMap(t, rows);
ThresholdValue tv = buildThresholdValue(t, rows); result.put(cond.getSeq(), byMerchant);
result.put(cond.getSeq(), tv);
} catch (Exception e) { } catch (Exception e) {
log.error("动态SQL阈值预加载失败,seq={}", cond.getSeq(), e); log.error("动态SQL阈值预加载失败,seq={}", cond.getSeq(), e);
} }
...@@ -68,26 +71,56 @@ public class DynamicSqlThresholdStrategy implements ThresholdStrategy { ...@@ -68,26 +71,56 @@ public class DynamicSqlThresholdStrategy implements ThresholdStrategy {
return result; return result;
} }
private ThresholdValue buildThresholdValue(ThresholdDTO t, List<Map<String, Object>> rows) { /**
* 按商户号构建阈值映射。
*/
private Map<String, ThresholdValue> buildMerchantThresholdMap(ThresholdDTO t,
List<Map<String, Object>> rows) {
Map<String, ThresholdValue> result = new LinkedHashMap<>();
if (rows.isEmpty()) { if (rows.isEmpty()) {
return ThresholdValue.single(null, null); return result;
} }
Map<String, Object> firstRow = rows.get(0);
String minField = t.getMinField(); String minField = t.getMinField();
String maxField = t.getMaxField(); String maxField = t.getMaxField();
if (minField != null || maxField != null) { String valueField = t.getValueField();
BigDecimal min = toBigDecimal(firstRow.get(minField));
BigDecimal max = toBigDecimal(firstRow.get(maxField)); for (Map<String, Object> row : rows) {
return ThresholdValue.range(min, max, min, max); String merchantNo = resolveMerchantId(row);
if (merchantNo == null) {
log.warn("SQL结果集无商户标识列,跳过该行");
continue;
}
// 区间型
if (minField != null || maxField != null) {
BigDecimal min = toBigDecimal(row.get(minField));
BigDecimal max = toBigDecimal(row.get(maxField));
result.put(merchantNo, ThresholdValue.range(min, max, min, max));
continue;
}
// 单值型
if (valueField != null) {
BigDecimal v = toBigDecimal(row.get(valueField));
result.put(merchantNo, ThresholdValue.single(v, v));
continue;
}
// 未指定任何取值字段,异常
log.warn("动态SQL阈值未指定 valueField/minField/maxField,跳过该行,merchantNo={}", merchantNo);
} }
// 取第一个数值字段作为单值阈值 return result;
for (Object val : firstRow.values()) { }
if (val instanceof Number) {
BigDecimal v = new BigDecimal(val.toString()); /**
return ThresholdValue.single(v, v); * 从 SQL 结果行中解析商户号。
*/
private String resolveMerchantId(Map<String, Object> row) {
for (String key : MERCHANT_ID_KEYS) {
Object val = row.get(key);
if (val != null) {
return String.valueOf(val);
} }
} }
return ThresholdValue.single(null, null); return null;
} }
private BigDecimal toBigDecimal(Object obj) { private BigDecimal toBigDecimal(Object obj) {
......
package cn.com.glsx.dj.strategy.service.warning.threshold;
import cn.com.glsx.dj.strategy.enums.MetricDataTypeEnum;
import cn.com.glsx.dj.strategy.enums.WarningTypeEnum;
import cn.com.glsx.dj.strategy.model.projectgroup.PgWarningMetricDict;
import cn.com.glsx.dj.strategy.service.warning.EcoCoefficientQueryService;
import cn.hutool.core.util.StrUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
/**
* 生态系数指标值转换策略——生态预警(warningType=3)时将 BI 原值替换为生态系数。
*
* <p>参照 NumericConditionStrategy:系数即指标值,直接用于和阈值比较,不对阈值做乘法。
* 比率%指标在引擎层已 ×100,此处需 /100 还原后再查系数。</p>
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/06/02 16:00
*/
@Slf4j
@Component
public class EcoMetricValueTransformStrategy implements MetricValueTransformStrategy {
private static final String UNIT_PERCENT = "%";
private static final BigDecimal PERCENT_SCALE = new BigDecimal("100");
@Resource
private EcoCoefficientQueryService ecoCoefficientQueryService;
@Override
public WarningTypeEnum supportedWarningType() {
return WarningTypeEnum.ECO;
}
@Override
public String buildWarningLabel(String metricName, String categoryExtension) {
return categoryExtension + metricName;
}
@Override
public String getWarningUnit(PgWarningMetricDict dict) {
// 生态系数无单位,返回空串
return StrUtil.EMPTY;
}
@Override
public BigDecimal transform(BigDecimal scaledValue, TransformContext ctx) {
if (scaledValue == null) {
return null;
}
PgWarningMetricDict dict = ctx.getMetricDict();
if (dict == null || dict.getIndexName() == null) {
return scaledValue;
}
try {
// 比率%指标在引擎层已 ×100,此处 /100 还原为 BI 原值再查系数
BigDecimal originalValue = scaledValue;
if (MetricDataTypeEnum.RATIO.getCode().equals(dict.getDataType())
&& UNIT_PERCENT.equals(dict.getUnit())) {
originalValue = scaledValue.divide(PERCENT_SCALE, 10, RoundingMode.HALF_UP);
}
BigDecimal coefficient = ecoCoefficientQueryService.getCoefficient(
dict.getIndexName(), originalValue);
if (coefficient == null) {
return scaledValue;
}
log.info("生态系数转换,metricCode={}, 原值={}, 系数={}",
dict.getIndexName(), originalValue, coefficient);
return coefficient;
} catch (Exception e) {
log.error("生态系数转换失败,使用原值", e);
return scaledValue;
}
}
}
package cn.com.glsx.dj.strategy.service.warning.threshold;
import cn.com.glsx.dj.strategy.enums.WarningTypeEnum;
import cn.com.glsx.dj.strategy.model.projectgroup.PgWarningMetricDict;
import cn.hutool.core.util.StrUtil;
import java.math.BigDecimal;
/**
* 指标值转换策略接口——根据预警类型对 BI 返回值做转换后再与阈值比较。
*
* <p>例如生态预警(warningType=3)将 BI 原值替换为生态系数,
* 其他类型原值返回。引擎通过遍历策略列表找到匹配 warningType 的策略执行转换,
* 无匹配策略时原值返回。</p>
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/06/02 16:00
*/
public interface MetricValueTransformStrategy {
/**
* 支持的预警类型。
*
* @return 预警类型枚举
*/
WarningTypeEnum supportedWarningType();
/**
* 转换指标值。
*
* @param rawValue BI 返回的原始值
* @param ctx 转换上下文(含指标值、指标字典)
* @return 转换后的值
*/
BigDecimal transform(BigDecimal rawValue, TransformContext ctx);
/**
* 构建告警标签——默认格式:指标名(品类)。单位由枚举模板拼接在值后面。
*
* @param metricName 指标名称
* @param categoryExtension 品类扩展
* @return 组装后的标签
*/
default String buildWarningLabel(String metricName, String categoryExtension) {
String label = metricName;
if (categoryExtension != null && !categoryExtension.isEmpty() && !"全部".equals(categoryExtension)) {
label = categoryExtension + metricName;
}
return label;
}
/**
* 告警文本中的单位——生态预警返回空串(系数无单位),其余返回实际单位。
*/
default String getWarningUnit(PgWarningMetricDict dict) {
return dict != null && dict.getUnit() != null ? dict.getUnit() : StrUtil.EMPTY;
}
}
...@@ -36,9 +36,9 @@ public interface ThresholdStrategy { ...@@ -36,9 +36,9 @@ public interface ThresholdStrategy {
* 批量预加载(用于动态SQL,避免逐条查库)。 * 批量预加载(用于动态SQL,避免逐条查库)。
* *
* @param conditions 条件列表 * @param conditions 条件列表
* @return condition.seq → ThresholdValue * @return condition.seq → merchantNo → ThresholdValue
*/ */
default Map<Integer, ThresholdValue> batchResolve(List<ConditionDTO> conditions) { default Map<Integer, Map<String, ThresholdValue>> batchResolve(List<ConditionDTO> conditions) {
return Collections.emptyMap(); return Collections.emptyMap();
} }
} }
...@@ -56,9 +56,9 @@ public class ThresholdStrategyFactory { ...@@ -56,9 +56,9 @@ public class ThresholdStrategyFactory {
* 对条件列表中 type=2(动态SQL)的条件批量预加载。 * 对条件列表中 type=2(动态SQL)的条件批量预加载。
* *
* @param conditions 条件列表 * @param conditions 条件列表
* @return seq → ThresholdValue * @return seq → merchantNo → ThresholdValue
*/ */
public Map<Integer, ThresholdValue> batchResolve(List<ConditionDTO> conditions) { public Map<Integer, Map<String, ThresholdValue>> batchResolve(List<ConditionDTO> conditions) {
ThresholdStrategy strategy = getStrategy(ThresholdTypeEnum.DYNAMIC_SQL); ThresholdStrategy strategy = getStrategy(ThresholdTypeEnum.DYNAMIC_SQL);
return strategy.batchResolve(conditions); return strategy.batchResolve(conditions);
} }
......
package cn.com.glsx.dj.strategy.service.warning.threshold;
import cn.com.glsx.dj.strategy.model.projectgroup.PgWarningMetricDict;
import lombok.Builder;
import lombok.Data;
import java.math.BigDecimal;
/**
* 阈值转换上下文——封装策略执行所需的指标值和字典信息。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/06/02 16:00
*/
@Data
@Builder
public class TransformContext {
/** 指标原始值(BI 返回) */
private BigDecimal metricValue;
/** 指标字典 */
private PgWarningMetricDict metricDict;
}
...@@ -25,17 +25,23 @@ ...@@ -25,17 +25,23 @@
AND period_end = #{periodEnd} AND period_end = #{periodEnd}
</delete> </delete>
<delete id="deleteByBizAndDimension">
DELETE FROM pg_store_output
WHERE business_type = #{businessType}
AND time_dimension = #{timeDimension}
</delete>
<insert id="batchInsert" parameterType="java.util.List"> <insert id="batchInsert" parameterType="java.util.List">
INSERT INTO pg_store_output ( INSERT INTO pg_store_output (
business_type, store_id, store_name, business_type, store_id, store_name,
time_dimension, period_start, period_end, time_dimension, period_start, period_end,
deleted_flag, created_by, created_date deleted_flag, created_by, created_date, updated_by, updated_date
) VALUES ) VALUES
<foreach collection="list" item="item" separator=","> <foreach collection="list" item="item" separator=",">
( (
#{item.businessType}, #{item.storeId}, #{item.storeName}, #{item.businessType}, #{item.storeId}, #{item.storeName},
#{item.timeDimension}, #{item.periodStart}, #{item.periodEnd}, #{item.timeDimension}, #{item.periodStart}, #{item.periodEnd},
'N', #{item.createdBy}, #{item.createdDate} 'N', #{item.createdBy}, #{item.createdDate}, #{item.updatedBy}, #{item.updatedDate}
) )
</foreach> </foreach>
</insert> </insert>
......
...@@ -83,6 +83,12 @@ ...@@ -83,6 +83,12 @@
<if test="staffId != null and staffId != ''"> <if test="staffId != null and staffId != ''">
AND r.staff_id = #{staffId} AND r.staff_id = #{staffId}
</if> </if>
<if test="staffIds != null and staffIds.size() > 0">
AND r.staff_id IN
<foreach collection="staffIds" item="staffId" open="(" separator="," close=")">
#{staffId}
</foreach>
</if>
<if test="storeName != null and storeName != ''"> <if test="storeName != null and storeName != ''">
AND r.store_name LIKE CONCAT('%', #{storeName}, '%') AND r.store_name LIKE CONCAT('%', #{storeName}, '%')
</if> </if>
...@@ -125,4 +131,10 @@ ...@@ -125,4 +131,10 @@
AND period_end = #{periodEnd} AND period_end = #{periodEnd}
</delete> </delete>
<delete id="deleteByConfigAndDimension">
DELETE FROM warning_record
WHERE config_id = #{configId}
AND time_dimension = #{timeDimension}
</delete>
</mapper> </mapper>
  • @wangxw1
    commented
    Master

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

    1. 严重风险:Dubbo 接口 DTO 已有字段被删除/修改,破坏向下兼容性

    • 问题描述:在 ConditionDTO 中删除了 MetricRefDTO metric 字段,并新增了 metricId 等字段;在 MetricRefDTO 中删除了 storeCode 和 staffCode 字段。
    • 影响分析:触发重要规则红线。若这些 DTO 被用作 Dubbo 提供者的 Remote 接口参数,直接删除或重命名已有字段会导致严重的向下兼容性问题。旧版本的消费者在调用时,会因 Hessian2 序列化找不到对应字段而报错(NoSuchFieldError 或 InvalidClassException),或者导致核心业务数据丢失,引发线上生产事故。
    • 优化建议:
      • 禁止删除已有字段:将需要废弃的字段标记为 @Deprecated,而不是直接删除。
      • 新增字段而非修改:保留原字段,新增 metricId 和 metricName,并在服务提供者内部做兼容性转换逻辑,确保新老客户端的请求均能被正确处理。

    2. 逻辑缺陷:定时任务使用 @Value 注入执行日期导致日期固化

    • 问题描述:在 WarningComputeJob 和 WarningHistoryBackfillJob 中,使用了 @Value("${warning.compute.date:}") 来接收计算日期。
    • 影响分析:Spring 的 @Value 注解在 Bean 实例化时只会解析一次。如果通过配置文件或环境变量指定了具体日期(例如 2026-06-01),该服务在不重启的情况下,每天凌晨 2 点触发定时任务时,传入 Executor 的日期将永远是这一天,导致重复计算同一天的数据,完全失去定时任务推进时间的意义。
    • 优化建议:对于 ElasticJob 等分布式调度框架,动态参数应通过任务的上下文传递。建议移除 @Value,改用 shardingContext.getJobParameter() 获取动态日期参数。若参数为空,则在业务逻辑中默认取 T-1。

    3. 稳定性风险:新增 List<String> staffIds 缺少 MyBatis 边界保护

    • 问题描述:在 ProjectGroupWarningRecordQueryDTO 和 WarningRecordQueryRequest 中新增了 List<String> staffIds 集合参数,通常用于 MyBatis 的 IN 查询。
    • 影响分析:
      • 若前端或上游传入的 staffIds 为空集合(empty list),MyBatis 的 <foreach> 标签若未做判空,会生成 IN () 这样的非法 SQL,导致数据库抛出语法错误。
      • 若传入的集合极大(如超过 1000 个 ID),会导致 SQL 语句过长,严重拖慢数据库性能,甚至超出数据库的 max_allowed_packet 限制。
    • 优化建议:
      • 在 Service 层或 DTO 校验层对 staffIds 增加 @Size(max = 500) 限制。
      • 在 MyBatis 的 XML 文件中,务必增加 <if test="staffIds != null and staffIds.size() > 0"> 的前置判断。

    二、评分明细

    • 功能实现的正确性与健壮性(28 / 40分) 扣分理由:定时任务使用 @Value 注入日期参数是严重的逻辑缺陷,会导致长期运行时的日期固化问题;集合参数未见明显的边界处理考量。但将复杂逻辑抽离到 Executor 并补充了 @Transactional 事务注解,方向正确。

    • 安全性与潜在风险(20 / 30分) 扣分理由:触碰重要规则红线。直接修改并删除了 DTO 中的已有字段(如 ConditionDTO),在 RPC (Dubbo) 调用场景下存在极大的反序列化失败和兼容性宕机风险。

    • 最佳实践与可维护性(16 / 20分) 扣分理由:常量类 WarningEngineConsts 使用了 public interface 声明,虽然在老项目中常见,但现代 Java 最佳实践推荐使用 public final class 配合私有构造器;枚举类增加了关键逻辑说明注释,提升了可读性,给予肯定。

    • 性能与资源利用(4 / 5分) 扣分理由:新增的 IN 查询集合参数存在潜在的慢 SQL 风险,当员工 ID 数量较多时可能成为性能瓶颈。

    • 提交信息质量(3 / 5分) 扣分理由:Commit 信息“feat:策略中心联调问题修改以及预警引擎代码调整”过于宽泛,包含了多个重构(如剥离 Executor、修改 DTO、修复事务),未能清晰追溯具体的变动原因和影响范围。

    总分:71分

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