Commit cf17f50a by 杨卫

feat:预警引擎功能策略中心列表,策略分析等接口

1 parent 96f5f43b
Showing 65 changed files with 4462 additions and 5 deletions
package cn.com.glsx.dj.strategy.dto.projectgroup;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
/**
* 项目组下拉选项 DTO。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/29 16:00
*/
@Data
@ToString
public class GroupOptionDTO implements Serializable {
private static final long serialVersionUID = -4879253148620973387L;
@ApiModelProperty(notes = "项目组id")
private Integer groupId;
@ApiModelProperty(notes = "项目组名称")
private String groupName;
}
...@@ -15,6 +15,9 @@ public class ProjectGroupMetricQueryDTO implements Serializable { ...@@ -15,6 +15,9 @@ public class ProjectGroupMetricQueryDTO implements Serializable {
private static final long serialVersionUID = -8450912935887202644L; private static final long serialVersionUID = -8450912935887202644L;
@ApiModelProperty(notes = "预警类型")
private Integer warningType;
@ApiModelProperty(notes = "应用业务") @ApiModelProperty(notes = "应用业务")
private Integer biz; private Integer biz;
......
...@@ -5,6 +5,8 @@ import lombok.Data; ...@@ -5,6 +5,8 @@ import lombok.Data;
import lombok.ToString; import lombok.ToString;
import java.io.Serializable; import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
/** /**
* 项目组预警结果DTO。 * 项目组预警结果DTO。
...@@ -15,15 +17,90 @@ public class ProjectGroupWarningRecordDTO implements Serializable { ...@@ -15,15 +17,90 @@ public class ProjectGroupWarningRecordDTO implements Serializable {
private static final long serialVersionUID = 3916133447622354984L; private static final long serialVersionUID = 3916133447622354984L;
@ApiModelProperty(notes = "记录ID")
private Integer id;
@ApiModelProperty(notes = "项目组ID")
private Integer groupId;
@ApiModelProperty(notes = "配置ID")
private Integer configId;
@ApiModelProperty(notes = "门店id") @ApiModelProperty(notes = "门店id")
private Integer merchantId; private Integer merchantId;
@ApiModelProperty(notes = "门店名称") @ApiModelProperty(notes = "门店名称")
private String merchantName; private String merchantName;
@ApiModelProperty(notes = "员工ID")
private String staffId;
@ApiModelProperty(notes = "员工名称")
private String staffName;
@ApiModelProperty(notes = "员工手机号")
private String staffPhone;
@ApiModelProperty(notes = "预警类型") @ApiModelProperty(notes = "预警类型")
private Integer warningType; private Integer warningType;
@ApiModelProperty(notes = "预警类型名称") @ApiModelProperty(notes = "预警类型名称")
private String warningTypeName; private String warningTypeName;
@ApiModelProperty(notes = "业务类型")
private Integer businessType;
@ApiModelProperty(notes = "监控对象")
private Integer monitorTarget;
@ApiModelProperty(notes = "时间维度")
private String timeDimension;
@ApiModelProperty(notes = "周期开始")
private Date periodStart;
@ApiModelProperty(notes = "周期结束")
private Date periodEnd;
@ApiModelProperty(notes = "指标编码")
private String metricCode;
@ApiModelProperty(notes = "指标名称")
private String metricName;
@ApiModelProperty(notes = "指标值")
private BigDecimal metricValue;
@ApiModelProperty(notes = "指标展示值")
private BigDecimal metricDisplay;
@ApiModelProperty(notes = "阈值类型")
private Integer thresholdType;
@ApiModelProperty(notes = "阈值展示值")
private BigDecimal thresholdDisplay;
@ApiModelProperty(notes = "阈值下界展示")
private BigDecimal thresholdMinDisplay;
@ApiModelProperty(notes = "阈值上界展示")
private BigDecimal thresholdMaxDisplay;
@ApiModelProperty(notes = "生态系数")
private BigDecimal ecoCoefficient;
@ApiModelProperty(notes = "运算符")
private String operator;
@ApiModelProperty(notes = "预警文本")
private String warningText;
@ApiModelProperty(notes = "是否已下发策略")
private Integer isStrategySent;
@ApiModelProperty(notes = "状态")
private Integer status;
@ApiModelProperty(notes = "创建时间")
private Date createdTime;
} }
...@@ -39,4 +39,16 @@ public class ProjectGroupWarningRecordQueryDTO implements Serializable { ...@@ -39,4 +39,16 @@ public class ProjectGroupWarningRecordQueryDTO implements Serializable {
@ApiModelProperty(notes = "结束时间") @ApiModelProperty(notes = "结束时间")
private String periodEnd; private String periodEnd;
@ApiModelProperty(notes = "门店ID")
private Integer storeId;
@ApiModelProperty(notes = "员工ID")
private String staffId;
@ApiModelProperty(notes = "门店名称模糊搜索")
private String storeName;
@ApiModelProperty(notes = "是否已下发策略: 0=否 1=是")
private Integer isStrategySent;
} }
package cn.com.glsx.dj.strategy.dto.warning;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
/**
* 规则条件——rule_json 数组中的单个条件元素。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/28 14:00
*/
@Data
@ToString
public class ConditionDTO implements Serializable {
private static final long serialVersionUID = -8086676469236141619L;
@ApiModelProperty(notes = "条件序号,从1开始递增")
private Integer seq;
@ApiModelProperty(notes = "指标引用")
private MetricRefDTO metric;
@ApiModelProperty(notes = "运算符: > < >= <= = >< >=<= >=< ><=")
private String operator;
@ApiModelProperty(notes = "阈值配置")
private ThresholdDTO threshold;
@ApiModelProperty(notes = "下一条逻辑: AND / OR / null(最后一条)")
private String nextLogic;
}
package cn.com.glsx.dj.strategy.dto.warning;
import cn.com.glsx.dj.strategy.dto.OperatorResponse;
import cn.com.glsx.dj.strategy.dto.StrategyTypeStatisticsRespDTO;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
import java.util.List;
/**
* 效果分析响应——按门店维度聚合,内含触发预警的各指标分析。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/28 14:00
*/
@Data
@ToString
public class EffectAnalysisDTO implements Serializable {
private static final long serialVersionUID = 7832506478100376535L;
@ApiModelProperty(notes = "商户号")
private String merchantNo;
@ApiModelProperty(notes = "门店名称")
private String storeName;
@ApiModelProperty(
name = "mainServiceMerchantName",
notes = "主服务商名称",
example = "1"
)
private String mainServiceMerchantName;
@ApiModelProperty(notes = "主营品牌(逗号分隔)")
private String mainBrandsStr;
@ApiModelProperty(notes = "线上运营")
private List<OperatorResponse> onlineOperator;
@ApiModelProperty(notes = "区域运营")
private List<OperatorResponse> areaOperator;
@ApiModelProperty(
name = "flightSupervision",
notes = "区域督导"
)
private List<OperatorResponse> flightSupervision;
@ApiModelProperty(notes = "执行策略总数")
private Integer strategyTotalCount;
@ApiModelProperty(notes = "策略类型统计详情")
private List<StrategyTypeStatisticsRespDTO> strategyTypeStatisticsResponse;
@ApiModelProperty(notes = "触发预警的指标分析列表")
private List<MetricAnalysisDTO> metrics;
}
package cn.com.glsx.dj.strategy.dto.warning;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
/**
* 效果分析请求入参。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/29 14:00
*/
@Data
@ToString
public class EffectAnalysisRequest implements Serializable {
private static final long serialVersionUID = 8179243105885129458L;
@ApiModelProperty(notes = "业务线: 1=延保 2=轻改 3=权益", required = true)
private Integer businessType;
@ApiModelProperty(notes = "预警类型: 5=黄色预警 4=红色预警 3=生态预警 2=兜底预警", required = true)
private Integer warningType;
@ApiModelProperty(notes = "时间维度: W/M/LDW/LDM", required = true)
private String timeDimension;
@ApiModelProperty(notes = "开始日期 yyyy-MM-dd", required = true)
private String startDate;
@ApiModelProperty(notes = "结束日期 yyyy-MM-dd", required = true)
private String endDate;
@ApiModelProperty(notes = "页码,默认1")
private Integer pageNum = 1;
@ApiModelProperty(notes = "每页数量,默认10")
private Integer pageSize = 10;
}
package cn.com.glsx.dj.strategy.dto.warning;
import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
import java.util.List;
/**
* 门店筛选条件 DTO——品牌/区域/运营/督导多维度筛选后取门店交集。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/28 14:00
*/
@Data
@ToString
public class MerchantFilterDTO implements Serializable {
private static final long serialVersionUID = -1071410850495914559L;
/** 业务类型: 1=延保 2=轻改 3=权益 */
private Integer businessType;
/** 区域ID(可选) */
private Integer regionId;
/** 一级品牌ID列表(可选) */
private List<Integer> firstbrandIds;
/** 二级品牌ID列表(可选) */
private List<Integer> twoBrandIds;
/** 线上运营人员ID(可选) */
private String onlineOperatorId;
/** 区域运营人员ID(可选) */
private String regionalOperatorId;
/** 飞行督导人员ID(可选) */
private String flyingSupervisorId;
/** 门店名称模糊搜索(可选) */
private String storeName;
/** 项目组ID(可选) */
private Integer groupId;
/** 是否已下发策略: 0=否 1=是(可选) */
private Integer isStrategySent;
/** 周期开始日期 yyyy-MM-dd(策略筛选时使用) */
private String startDate;
/** 周期结束日期 yyyy-MM-dd(策略筛选时使用) */
private String endDate;
}
package cn.com.glsx.dj.strategy.dto.warning;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
import java.math.BigDecimal;
/**
* 单指标效果分析——当前周期 vs 下一周期对比。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/29 14:00
*/
@Data
@ToString
public class MetricAnalysisDTO implements Serializable {
private static final long serialVersionUID = 4621029849577301294L;
@ApiModelProperty(notes = "指标编码")
private String metricCode;
@ApiModelProperty(notes = "指标名称")
private String metricName;
@ApiModelProperty(notes = "扩展品类")
private String categoryExtension;
@ApiModelProperty(notes = "当前周期指标值")
private BigDecimal currentValue;
@ApiModelProperty(notes = "下一周期指标值")
private BigDecimal nextValue;
@ApiModelProperty(notes = "指标单位")
private String unit;
@ApiModelProperty(notes = "变化率")
private BigDecimal changeRate;
@ApiModelProperty(notes = "是否提升")
private boolean improved;
}
package cn.com.glsx.dj.strategy.dto.warning;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
/**
* 指标引用——rule_json 中 condition.metric 部分。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/28 14:00
*/
@Data
@ToString
public class MetricRefDTO implements Serializable {
private static final long serialVersionUID = 754109325813660140L;
@ApiModelProperty(notes = "指标中文名")
private String name;
@ApiModelProperty(notes = "门店维度BI指标编码")
private String storeCode;
@ApiModelProperty(notes = "员工维度BI指标编码")
private String staffCode;
}
package cn.com.glsx.dj.strategy.dto.warning;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import java.io.Serializable;
import java.util.Date;
/**
* 统计周期起止日期。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/28 14:00
*/
@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class PeriodRange implements Serializable {
private static final long serialVersionUID = -2669050403430560292L;
/** 周期开始 */
private Date start;
/** 周期结束 */
private Date end;
}
package cn.com.glsx.dj.strategy.dto.warning;
import cn.com.glsx.dj.strategy.dto.OperatorResponse;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
import java.util.List;
/**
* 门店预警汇总响应。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/28 14:00
*/
@Data
@ToString
public class StoreWarningSummaryDTO implements Serializable {
private static final long serialVersionUID = 6874671301578247683L;
@ApiModelProperty(notes = "商户号")
private String merchantNo;
@ApiModelProperty(notes = "门店名称")
private String storeName;
@ApiModelProperty(notes = "主营品牌(逗号分隔)")
private String mainBrandsStr;
@ApiModelProperty(notes = "线上运营")
private List<OperatorResponse> onlineOperator;
@ApiModelProperty(notes = "区域运营")
private List<OperatorResponse> areaOperator;
@ApiModelProperty(notes = "区域督导")
private List<OperatorResponse> flightSupervision;
@ApiModelProperty(notes = "预警摘要(最多2条)")
private List<String> warningSummary;
@ApiModelProperty(notes = "预警总数")
private int warningTotalCount;
@ApiModelProperty(notes = "是否已下发策略")
private boolean strategySent;
}
package cn.com.glsx.dj.strategy.dto.warning;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
/**
* 阈值配置——rule_json 中 condition.threshold 部分。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/28 14:00
*/
@Data
@ToString
public class ThresholdDTO implements Serializable {
private static final long serialVersionUID = -5949072911915986709L;
@ApiModelProperty(notes = "阈值类型: 1=固定值 2=动态SQL兜底 3=引用指标")
private Integer type;
@ApiModelProperty(notes = "type=1时存数值,type=2时存SQL,type=3时存指标编码")
private String value;
@ApiModelProperty(notes = "区间下界")
private String min;
@ApiModelProperty(notes = "区间上界")
private String max;
@ApiModelProperty(notes = "type=2区间时,SQL结果集中下界字段名")
private String minField;
@ApiModelProperty(notes = "type=2区间时,SQL结果集中上界字段名")
private String maxField;
}
package cn.com.glsx.dj.strategy.dto.warning;
import io.swagger.annotations.ApiModelProperty;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;
import java.io.Serializable;
import java.math.BigDecimal;
/**
* 解析后的阈值——策略接口 resolve() 返回的统一结果。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/28 14:00
*/
@Data
@ToString
@NoArgsConstructor
@AllArgsConstructor
public class ThresholdValue implements Serializable {
private static final long serialVersionUID = -4724071098513030311L;
@ApiModelProperty(notes = "单值阈值(单值运算符使用)")
private BigDecimal value;
@ApiModelProperty(notes = "区间下界(区间运算符使用)")
private BigDecimal min;
@ApiModelProperty(notes = "区间上界(区间运算符使用)")
private BigDecimal max;
@ApiModelProperty(notes = "单值展示值")
private BigDecimal display;
@ApiModelProperty(notes = "区间下界展示值")
private BigDecimal minDisplay;
@ApiModelProperty(notes = "区间上界展示值")
private BigDecimal maxDisplay;
public static ThresholdValue single(BigDecimal value, BigDecimal display) {
ThresholdValue tv = new ThresholdValue();
tv.value = value;
tv.display = display;
return tv;
}
public static ThresholdValue range(BigDecimal min, BigDecimal max, BigDecimal minDisplay, BigDecimal maxDisplay) {
ThresholdValue tv = new ThresholdValue();
tv.min = min;
tv.max = max;
tv.minDisplay = minDisplay;
tv.maxDisplay = maxDisplay;
return tv;
}
}
package cn.com.glsx.dj.strategy.dto.warning;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
/**
* 预警配置创建/更新请求。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/28 14:00
*/
@Data
@ToString
public class WarningConfigCreateRequest implements Serializable {
private static final long serialVersionUID = 1774501266681146101L;
@ApiModelProperty(notes = "配置ID(更新时必填)")
private Integer id;
@ApiModelProperty(notes = "项目组ID")
private Integer groupId;
@ApiModelProperty(notes = "预警类型: 5=黄色预警 4=红色预警 3=生态预警 2=兜底预警")
private Integer warningType;
@ApiModelProperty(notes = "业务线: 1=延保 2=轻改 3=权益")
private Integer biz;
@ApiModelProperty(notes = "监控对象: 1=员工 2=门店")
private Integer monitorTarget;
@ApiModelProperty(notes = "规则JSON字符串")
private String ruleJson;
}
package cn.com.glsx.dj.strategy.dto.warning;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
import java.util.Date;
/**
* 预警配置响应。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/28 14:00
*/
@Data
@ToString
public class WarningConfigDTO implements Serializable {
private static final long serialVersionUID = 668237476790997177L;
@ApiModelProperty(notes = "配置ID")
private Integer id;
@ApiModelProperty(notes = "项目组ID")
private Integer groupId;
@ApiModelProperty(notes = "预警类型: 5=黄色预警 4=红色预警 3=生态预警 2=兜底预警")
private Integer warningType;
@ApiModelProperty(notes = "业务线: 1=延保 2=轻改 3=权益")
private Integer biz;
@ApiModelProperty(notes = "监控对象: 1=员工 2=门店")
private Integer monitorTarget;
@ApiModelProperty(notes = "规则JSON")
private String ruleJson;
@ApiModelProperty(notes = "是否启用: 1=启用 0=禁用")
private Integer isEnabled;
@ApiModelProperty(notes = "创建人")
private String createdBy;
@ApiModelProperty(notes = "创建时间")
private Date createdDate;
@ApiModelProperty(notes = "更新人")
private String updatedBy;
@ApiModelProperty(notes = "更新时间")
private Date updatedDate;
}
package cn.com.glsx.dj.strategy.dto.warning;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
/**
* 预警配置查询请求。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/28 14:00
*/
@Data
@ToString
public class WarningConfigQueryRequest implements Serializable {
private static final long serialVersionUID = -2248571333288266353L;
@ApiModelProperty(notes = "项目组ID")
private Integer groupId;
@ApiModelProperty(notes = "预警类型")
private Integer warningType;
@ApiModelProperty(notes = "业务线")
private Integer biz;
@ApiModelProperty(notes = "监控对象")
private Integer monitorTarget;
@ApiModelProperty(notes = "是否启用")
private Integer isEnabled;
}
package cn.com.glsx.dj.strategy.dto.warning;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
/**
* 预警配置启用/禁用请求。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/28 14:00
*/
@Data
@ToString
public class WarningConfigToggleRequest implements Serializable {
private static final long serialVersionUID = 398216842671868181L;
@ApiModelProperty(notes = "配置ID")
private Integer configId;
@ApiModelProperty(notes = "1=启用 0=禁用")
private Integer isEnabled;
}
package cn.com.glsx.dj.strategy.dto.warning;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.Date;
/**
* 预警记录响应。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/28 14:00
*/
@Data
@ToString
public class WarningRecordDTO implements Serializable {
private static final long serialVersionUID = -4536558612388635010L;
@ApiModelProperty(notes = "记录ID")
private Integer id;
@ApiModelProperty(notes = "项目组ID")
private Integer groupId;
@ApiModelProperty(notes = "配置ID")
private Integer configId;
@ApiModelProperty(notes = "预警类型")
private Integer warningType;
@ApiModelProperty(notes = "预警类型名称")
private String warningTypeName;
@ApiModelProperty(notes = "业务类型")
private Integer businessType;
@ApiModelProperty(notes = "监控对象: 1=员工 2=门店")
private Integer monitorTarget;
@ApiModelProperty(notes = "时间维度")
private String timeDimension;
@ApiModelProperty(notes = "周期开始")
private Date periodStart;
@ApiModelProperty(notes = "周期结束")
private Date periodEnd;
@ApiModelProperty(notes = "门店ID")
private Integer storeId;
@ApiModelProperty(notes = "门店名称")
private String storeName;
@ApiModelProperty(notes = "员工ID")
private String staffId;
@ApiModelProperty(notes = "员工姓名")
private String staffName;
@ApiModelProperty(notes = "员工手机号")
private String staffPhone;
@ApiModelProperty(notes = "指标编码")
private String metricCode;
@ApiModelProperty(notes = "指标名称")
private String metricName;
@ApiModelProperty(notes = "指标值")
private BigDecimal metricValue;
@ApiModelProperty(notes = "指标展示值")
private BigDecimal metricDisplay;
@ApiModelProperty(notes = "阈值类型")
private Integer thresholdType;
@ApiModelProperty(notes = "阈值展示值")
private BigDecimal thresholdDisplay;
@ApiModelProperty(notes = "区间下界展示值")
private BigDecimal thresholdMinDisplay;
@ApiModelProperty(notes = "区间上界展示值")
private BigDecimal thresholdMaxDisplay;
@ApiModelProperty(notes = "生态系数")
private BigDecimal ecoCoefficient;
@ApiModelProperty(notes = "运算符")
private String operator;
@ApiModelProperty(notes = "预警描述文本")
private String warningText;
@ApiModelProperty(notes = "是否已下发策略")
private Integer isStrategySent;
@ApiModelProperty(notes = "状态")
private Integer status;
@ApiModelProperty(notes = "创建时间")
private Date createdTime;
}
package cn.com.glsx.dj.strategy.dto.warning;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.ToString;
import java.io.Serializable;
import java.util.List;
/**
* 预警记录查询请求。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/28 14:00
*/
@Data
@ToString
public class WarningRecordQueryRequest implements Serializable {
private static final long serialVersionUID = 1652253646752099692L;
@ApiModelProperty(notes = "业务线: 1=延保 2=轻改 3=权益")
private Integer businessType;
@ApiModelProperty(notes = "预警类型: 5=黄色预警 4=红色预警 3=生态预警 2=兜底预警 (null=全部)")
private Integer warningType;
@ApiModelProperty(notes = "指标类型ID")
private Integer metricTypeId;
@ApiModelProperty(notes = "时间维度: W/M/LDW/LDM")
private String timeDimension;
@ApiModelProperty(notes = "开始日期 yyyy-MM-dd")
private String startDate;
@ApiModelProperty(notes = "结束日期 yyyy-MM-dd")
private String endDate;
@ApiModelProperty(notes = "项目组筛选")
private Integer groupId;
@ApiModelProperty(notes = "门店名称模糊搜索")
private String storeName;
@ApiModelProperty(notes = "是否已下发策略")
private Integer isStrategySent;
@ApiModelProperty(notes = "区域ID")
private Integer regionId;
@ApiModelProperty(notes = "监控对象 1=员工 2=门店")
private Integer monitorTarget;
@ApiModelProperty(notes = "一级品牌ID列表")
private List<Integer> firstbrandIds;
@ApiModelProperty(notes = "二级品牌ID列表")
private List<Integer> twoBrandIds;
@ApiModelProperty(notes = "区域运营人员ID")
private String regionalOperatorId;
@ApiModelProperty(notes = "线上运营人员ID")
private String onlineOperatorId;
@ApiModelProperty(notes = "区域督导人员ID")
private String flightSupervisionId;
@ApiModelProperty(notes = "门店ID(查询指定门店预警明细时使用)")
private Integer storeId;
@ApiModelProperty(notes = "员工ID(查询指定员工预警明细时使用)")
private String staffId;
}
package cn.com.glsx.dj.strategy.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* BI 聚合类型枚举——对应 BI 接口的 exts 参数,控制数据聚合维度。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/28 14:00
*/
@Getter
@AllArgsConstructor
public enum BiAggregationTypeEnum {
/** 按门店聚合返回 */
MERCHANT("merchantIds", "按门店聚合"),
/** 按员工staffUUID聚合返回 */
STAFF("staffIds", "按员工聚合"),
/** 按业务聚合返回 */
BIZ("bizs", "按业务聚合"),
/** 按品牌聚合返回 */
BRAND("brandIds", "按品牌聚合"),
/** 按门店+员工聚合返回 */
MERCHANT_STAFF("merchantIds,staffIds", "按门店+员工聚合");
/** exts 参数值 */
private final String value;
/** 描述 */
private final String desc;
}
package cn.com.glsx.dj.strategy.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* BI 日期类型枚举——对应 BI 接口的 dateType 参数。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/28 14:00
*/
@Getter
@AllArgsConstructor
public enum BiDateTypeEnum {
/** 按指定时段(由 startDate/endDate 决定) */
PERIOD(0, "按指定时段"),
/** 按周 */
WEEK(1, "按周"),
/** 按月 */
MONTH(2, "按月"),
/** 按年 */
YEAR(3, "按年"),
/** 全部(查询时间段汇总) */
ALL(4, "全部");
/** dateType 参数值 */
private final int value;
/** 描述 */
private final String desc;
}
package cn.com.glsx.dj.strategy.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* BI 指标代码枚举——维护 BI 系统的指标编码。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/28 14:00
*/
@Getter
@AllArgsConstructor
public enum BiMetricCodeEnum {
/** 产值 */
OUTPUT_VALUE("A036", "产值");
/** 指标编码 */
private final String code;
/** 指标名称 */
private final String name;
/**
* 根据编码获取枚举。
*/
public static BiMetricCodeEnum fromCode(String code) {
for (BiMetricCodeEnum e : values()) {
if (e.code.equals(code)) {
return e;
}
}
throw new IllegalArgumentException("不支持的BI指标编码: " + code);
}
}
package cn.com.glsx.dj.strategy.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
@Getter
@AllArgsConstructor
public enum MonitorTargetEnum {
EMPLOYEE(1, "员工"),
SHOP(2, "门店");
private final Integer code;
private final String desc;
}
...@@ -24,6 +24,14 @@ public enum ProjectGroupBizEnum { ...@@ -24,6 +24,14 @@ public enum ProjectGroupBizEnum {
private final Integer biz; private final Integer biz;
private final String bizName; private final String bizName;
public Integer getBiz() {
return biz;
}
public String getBizName() {
return bizName;
}
/** /**
* 返回全部业务枚举。 * 返回全部业务枚举。
* *
......
package cn.com.glsx.dj.strategy.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
/**
* 阈值类型枚举。
*
* <p>1=固定值 2=动态SQL兜底 3=引用指标。</p>
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/28 14:00
*/
@Getter
@AllArgsConstructor
public enum ThresholdTypeEnum {
FIXED(1, "固定值"),
DYNAMIC_SQL(2, "动态SQL兜底"),
REFERENCE_METRIC(3, "引用指标");
private final int type;
private final String desc;
/**
* 根据 type 值获取枚举。
*/
public static ThresholdTypeEnum fromType(int type) {
for (ThresholdTypeEnum t : values()) {
if (t.type == type) {
return t;
}
}
throw new IllegalArgumentException("不支持的阈值类型: " + type);
}
}
package cn.com.glsx.dj.strategy.enums;
import cn.com.glsx.dj.strategy.dto.warning.PeriodRange;
import lombok.AllArgsConstructor;
import lombok.Getter;
import java.util.Calendar;
import java.util.Date;
/**
* 时间维度枚举——封装周期计算逻辑。
*
* <p>W=自然周 M=自然月 LDW=截止周最新一天 LDM=截止月最新一天。</p>
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/28 14:00
*/
@Getter
@AllArgsConstructor
public enum TimeDimensionEnum {
W("W", "周") {
@Override
public PeriodRange calculate(Date date) {
return getWeekRange(date, true);
}
},
M("M", "月") {
@Override
public PeriodRange calculate(Date date) {
return getMonthRange(date, true);
}
},
LDW("LDW", "截止周最新一天") {
@Override
public PeriodRange calculate(Date date) {
return getWeekRange(date, false);
}
},
LDM("LDM", "截止月最新一天") {
@Override
public PeriodRange calculate(Date date) {
return getMonthRange(date, false);
}
};
private final String code;
private final String desc;
/**
* 计算指定日期对应的统计周期。
*
* @param date 参考日期
* @return 周期起止
*/
public abstract PeriodRange calculate(Date date);
/**
* 计算下一周期起止(endDate + 1 开始)。
*
* @param endDate 当前周期结束日期
* @return 下一周期起止
*/
public PeriodRange calcNextPeriod(Date endDate) {
Calendar cal = Calendar.getInstance();
cal.setTime(endDate);
cal.add(Calendar.DAY_OF_MONTH, 1);
Date nextStart = cal.getTime();
if (this == W || this == LDW) {
cal.add(Calendar.DAY_OF_MONTH, 6);
} else {
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
}
Date nextEnd = cal.getTime();
return new PeriodRange(nextStart, nextEnd);
}
/**
* 根据 code 获取枚举。
*/
public static TimeDimensionEnum fromCode(String code) {
for (TimeDimensionEnum t : values()) {
if (t.code.equals(code)) {
return t;
}
}
throw new IllegalArgumentException("不支持的时间维度: " + code);
}
/**
* 周范围:completeWeek=true 返回完整周(周一~周日),false 返回周一~date。
*/
private static PeriodRange getWeekRange(Date date, boolean completeWeek) {
Calendar cal = toCalendar(date);
// 周一
cal.set(Calendar.DAY_OF_WEEK, Calendar.MONDAY);
Date start = cal.getTime();
Date end;
if (completeWeek) {
cal.add(Calendar.DAY_OF_MONTH, 6);
end = cal.getTime();
} else {
end = date;
}
return new PeriodRange(start, end);
}
/**
* 月范围:completeMonth=true 返回完整月(1日~月末),false 返回1日~date。
*/
private static PeriodRange getMonthRange(Date date, boolean completeMonth) {
Calendar cal = toCalendar(date);
cal.set(Calendar.DAY_OF_MONTH, 1);
Date start = cal.getTime();
Date end;
if (completeMonth) {
cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH));
end = cal.getTime();
} else {
end = date;
}
return new PeriodRange(start, end);
}
private static Calendar toCalendar(Date date) {
Calendar cal = Calendar.getInstance();
cal.setTime(date);
// 归一化到当天0点
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
return cal;
}
}
package cn.com.glsx.dj.strategy.enums;
import lombok.AllArgsConstructor;
import lombok.Getter;
import java.math.BigDecimal;
import java.util.Arrays;
/**
* 预警运算符枚举——封装比对逻辑与告警文本模版。
*
* <p>单值运算符:{@code > < >= <= =};区间运算符:{@code >< >=<= >=< ><=}。</p>
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/28 14:00
*/
@Getter
@AllArgsConstructor
public enum WarningOperatorEnum {
// ==================== 单值运算符 ====================
GT(">", Category.SINGLE) {
@Override
public boolean evaluate(BigDecimal value, BigDecimal threshold, BigDecimal min, BigDecimal max) {
return value != null && threshold != null && value.compareTo(threshold) > 0;
}
@Override
public String buildWarningText(String metricName, BigDecimal metricDisplay,
BigDecimal thresholdDisplay, BigDecimal minDisplay, BigDecimal maxDisplay) {
return String.format("「%s」%.2f 高于 %.2f", metricName, metricDisplay, thresholdDisplay);
}
},
LT("<", Category.SINGLE) {
@Override
public boolean evaluate(BigDecimal value, BigDecimal threshold, BigDecimal min, BigDecimal max) {
return value != null && threshold != null && value.compareTo(threshold) < 0;
}
@Override
public String buildWarningText(String metricName, BigDecimal metricDisplay,
BigDecimal thresholdDisplay, BigDecimal minDisplay, BigDecimal maxDisplay) {
return String.format("「%s」%.2f 低于 %.2f", metricName, metricDisplay, thresholdDisplay);
}
},
GE(">=", Category.SINGLE) {
@Override
public boolean evaluate(BigDecimal value, BigDecimal threshold, BigDecimal min, BigDecimal max) {
return value != null && threshold != null && value.compareTo(threshold) >= 0;
}
@Override
public String buildWarningText(String metricName, BigDecimal metricDisplay,
BigDecimal thresholdDisplay, BigDecimal minDisplay, BigDecimal maxDisplay) {
return String.format("「%s」%.2f 高于或等于 %.2f", metricName, metricDisplay, thresholdDisplay);
}
},
LE("<=", Category.SINGLE) {
@Override
public boolean evaluate(BigDecimal value, BigDecimal threshold, BigDecimal min, BigDecimal max) {
return value != null && threshold != null && value.compareTo(threshold) <= 0;
}
@Override
public String buildWarningText(String metricName, BigDecimal metricDisplay,
BigDecimal thresholdDisplay, BigDecimal minDisplay, BigDecimal maxDisplay) {
return String.format("「%s」%.2f 低于或等于 %.2f", metricName, metricDisplay, thresholdDisplay);
}
},
EQ("=", Category.SINGLE) {
@Override
public boolean evaluate(BigDecimal value, BigDecimal threshold, BigDecimal min, BigDecimal max) {
return value != null && threshold != null && value.compareTo(threshold) == 0;
}
@Override
public String buildWarningText(String metricName, BigDecimal metricDisplay,
BigDecimal thresholdDisplay, BigDecimal minDisplay, BigDecimal maxDisplay) {
return String.format("「%s」%.2f 等于 %.2f", metricName, metricDisplay, thresholdDisplay);
}
},
// ==================== 区间运算符 ====================
OPEN_INTERVAL("><", Category.RANGE) {
@Override
public boolean evaluate(BigDecimal value, BigDecimal threshold, BigDecimal min, BigDecimal max) {
return value != null && min != null && max != null
&& value.compareTo(min) > 0 && value.compareTo(max) < 0;
}
@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);
}
},
CLOSE_INTERVAL(">=<=", Category.RANGE) {
@Override
public boolean evaluate(BigDecimal value, BigDecimal threshold, BigDecimal min, BigDecimal max) {
return value != null && min != null && max != null
&& value.compareTo(min) >= 0 && value.compareTo(max) <= 0;
}
@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);
}
},
LEFT_CLOSE_RIGHT_OPEN(">=<", Category.RANGE) {
@Override
public boolean evaluate(BigDecimal value, BigDecimal threshold, BigDecimal min, BigDecimal max) {
return value != null && min != null && max != null
&& value.compareTo(min) >= 0 && value.compareTo(max) < 0;
}
@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);
}
},
LEFT_OPEN_RIGHT_CLOSE("><=", Category.RANGE) {
@Override
public boolean evaluate(BigDecimal value, BigDecimal threshold, BigDecimal min, BigDecimal max) {
return value != null && min != null && max != null
&& value.compareTo(min) > 0 && value.compareTo(max) <= 0;
}
@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);
}
};
/** 运算符类别 */
@Getter
@AllArgsConstructor
public enum Category {
SINGLE("单值"),
RANGE("区间");
private final String desc;
}
private final String symbol;
private final Category category;
/**
* 评估条件是否成立。
*
* @param value 指标实际值
* @param threshold 阈值(单值运算符使用)
* @param min 区间下界(区间运算符使用)
* @param max 区间上界(区间运算符使用)
* @return true=条件成立
*/
public abstract boolean evaluate(BigDecimal value, BigDecimal threshold, BigDecimal min, BigDecimal max);
/**
* 生成告警描述文本(统一入口)。
*
* @param metricName 指标名称
* @param metricDisplay 指标展示值
* @param thresholdDisplay 阈值展示值(单值)或 null(区间)
* @param minDisplay 区间下界展示值(区间)或 null(单值)
* @param maxDisplay 区间上界展示值(区间)或 null(单值)
*/
public abstract String buildWarningText(String metricName, BigDecimal metricDisplay,
BigDecimal thresholdDisplay, BigDecimal minDisplay, BigDecimal maxDisplay);
/**
* 根据 symbol 获取枚举。
*/
public static WarningOperatorEnum fromSymbol(String symbol) {
return Arrays.stream(values())
.filter(op -> op.symbol.equals(symbol))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("不支持的运算符: " + symbol));
}
/**
* 判断是否为区间运算符。
*/
public boolean isRange() {
return category == Category.RANGE;
}
}
package cn.com.glsx.dj.strategy.model.projectgroup;
import lombok.Data;
import lombok.ToString;
import javax.persistence.Column;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import java.io.Serializable;
import java.util.Date;
/**
* 有产值门店记录模型。
*
* <p>定时任务预计算,记录各周期内有产值的门店。</p>
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/28 14:00
*/
@Data
@ToString
@Table(name = "pg_store_output")
public class PgStoreOutput implements Serializable {
private static final long serialVersionUID = -5540942633567676889L;
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@Column(name = "business_type")
private Integer businessType;
@Column(name = "store_id")
private Integer storeId;
@Column(name = "store_name")
private String storeName;
@Column(name = "time_dimension")
private String timeDimension;
@Column(name = "period_start")
private Date periodStart;
@Column(name = "period_end")
private Date periodEnd;
@Column(name = "deleted_flag")
private String deletedFlag;
@Column(name = "created_by")
private String createdBy;
@Column(name = "created_date")
private Date createdDate;
@Column(name = "updated_by")
private String updatedBy;
@Column(name = "updated_date")
private Date updatedDate;
}
package cn.com.glsx.dj.strategy.remote;
import cn.com.glsx.dj.strategy.dto.warning.WarningConfigCreateRequest;
import cn.com.glsx.dj.strategy.dto.warning.WarningConfigDTO;
import cn.com.glsx.dj.strategy.dto.warning.WarningConfigQueryRequest;
import cn.com.glsx.framework.core.annotation.ApiMethod;
import cn.com.glsx.framework.core.annotation.ApiParam;
import cn.com.glsx.framework.core.annotation.ApiResponse;
import cn.com.glsx.framework.core.beans.rpc.RpcResponse;
import java.util.List;
/**
* 预警配置管理远程接口。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/28 14:00
*/
public interface WarningConfigRemote {
/**
* 配置列表。
*
* @param request 查询参数
* @return 配置列表
*/
@ApiMethod("配置列表")
@ApiParam(name = "request", notes = "查询参数", dataType = ApiParam.DataTypeEnum.OBJECT, required = true)
@ApiResponse("配置列表")
RpcResponse<List<WarningConfigDTO>> listConfigs(WarningConfigQueryRequest request);
/**
* 创建配置。
*
* @param request 创建参数
* @return 是否成功
*/
@ApiMethod("创建配置")
@ApiParam(name = "request", notes = "创建参数", dataType = ApiParam.DataTypeEnum.OBJECT, required = true)
@ApiResponse("是否成功")
RpcResponse<Boolean> createConfig(WarningConfigCreateRequest request);
/**
* 更新配置。
*
* @param request 更新参数
* @return 是否成功
*/
@ApiMethod("更新配置")
@ApiParam(name = "request", notes = "更新参数", dataType = ApiParam.DataTypeEnum.OBJECT, required = true)
@ApiResponse("是否成功")
RpcResponse<Boolean> updateConfig(WarningConfigCreateRequest request);
/**
* 删除配置。
*
* @param configId 配置ID
* @return 是否成功
*/
@ApiMethod("删除配置")
@ApiParam(name = "configId", notes = "配置ID", dataType = ApiParam.DataTypeEnum.INT, required = true)
@ApiResponse("是否成功")
RpcResponse<Boolean> deleteConfig(Integer configId);
/**
* 启用/禁用配置。
*
* @param configId 配置ID
* @param isEnabled 1=启用 0=禁用
* @return 是否成功
*/
@ApiMethod("启用/禁用")
@ApiParam(name = "configId", notes = "配置ID", dataType = ApiParam.DataTypeEnum.INT, required = true)
@ApiResponse("是否成功")
RpcResponse<Boolean> toggleEnable(Integer configId, Integer isEnabled);
}
package cn.com.glsx.dj.strategy.remote;
import cn.com.glsx.dj.strategy.dto.projectgroup.GroupOptionDTO;
import cn.com.glsx.dj.strategy.dto.projectgroup.MetricOptionDTO;
import cn.com.glsx.dj.strategy.dto.projectgroup.ProjectGroupMetricQueryDTO;
import cn.com.glsx.dj.strategy.dto.projectgroup.WarningTypeOptionDTO;
import cn.com.glsx.dj.strategy.dto.warning.EffectAnalysisDTO;
import cn.com.glsx.dj.strategy.dto.warning.EffectAnalysisRequest;
import cn.com.glsx.dj.strategy.dto.warning.StoreWarningSummaryDTO;
import cn.com.glsx.framework.core.beans.rpc.RpcPagination;
import cn.com.glsx.dj.strategy.dto.warning.WarningRecordDTO;
import cn.com.glsx.dj.strategy.dto.warning.WarningRecordQueryRequest;
import cn.com.glsx.framework.core.annotation.ApiMethod;
import cn.com.glsx.framework.core.annotation.ApiParam;
import cn.com.glsx.framework.core.annotation.ApiResponse;
import cn.com.glsx.framework.core.beans.rpc.RpcResponse;
import java.util.List;
/**
* 预警引擎查询远程接口。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/28 14:00
*/
public interface WarningEngineRemote {
/**
* 门店预警汇总列表。
*
* @param request 查询参数
* @return 门店预警汇总列表
*/
@ApiMethod("门店预警汇总列表")
@ApiParam(name = "request", notes = "查询参数", dataType = ApiParam.DataTypeEnum.OBJECT, required = true)
@ApiResponse("门店预警汇总列表")
RpcResponse<List<StoreWarningSummaryDTO>> findWarningSummary(WarningRecordQueryRequest request);
/**
* 指定门店+员工预警明细。
*
* @param request 查询参数(含storeId/staffId)
* @return 预警明细列表
*/
@ApiMethod("指定门店员工预警明细")
@ApiParam(name = "request", notes = "查询参数", dataType = ApiParam.DataTypeEnum.OBJECT, required = true)
@ApiResponse("预警明细列表")
RpcResponse<List<WarningRecordDTO>> findWarningDetailByStoreAndStaff(WarningRecordQueryRequest request);
/**
* 预警类型下拉。
*
* @return 预警类型列表
*/
@ApiMethod("预警类型下拉")
@ApiResponse("预警类型列表")
RpcResponse<List<WarningTypeOptionDTO>> listWarningTypes();
/**
* 指标类型下拉。
*
* @param queryDTO 查询参数
* @return 指标列表
*/
@ApiMethod("指标类型下拉")
@ApiParam(name = "queryDTO", notes = "查询参数", dataType = ApiParam.DataTypeEnum.OBJECT, required = true)
@ApiResponse("指标列表")
RpcResponse<List<MetricOptionDTO>> listMetrics(ProjectGroupMetricQueryDTO queryDTO);
/**
* 效果分析——当前周期 vs 下一周期指标对比。
*
* @param request 查询参数
* @return 效果分析列表
*/
@ApiMethod("效果分析")
@ApiParam(name = "request", notes = "查询参数", dataType = ApiParam.DataTypeEnum.OBJECT, required = true)
@ApiResponse("效果分析列表")
RpcResponse<RpcPagination<EffectAnalysisDTO>> analysisEffect(EffectAnalysisRequest request);
/**
* 项目组下拉列表。
*
* @return 项目组列表
*/
@ApiMethod("项目组下拉列表")
@ApiResponse("项目组列表")
RpcResponse<List<GroupOptionDTO>> listGroups();
}
package cn.com.glsx.dj.strategy.job;
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.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.simple.SimpleJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.oreframework.boot.autoconfigure.elasticjob.annotation.ElasticJobConf;
import org.springframework.stereotype.Component;
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;
/**
* 预警计算定时任务——每天执行,计算有产值门店和预警数据。
*
* <p>执行顺序:有产值门店 → 门店维度预警 → 员工维度预警。</p>
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/28 14:00
*/
@Slf4j
@Component
@ElasticJobConf(name = "WarningComputeJob", cron = "0 0 2 * * ?", description = "预警计算定时任务", overwrite = false)
public class WarningComputeJob implements SimpleJob {
@Resource
private StoreOutputService storeOutputService;
@Resource
private WarningEngineService warningEngineService;
@Resource
private PgGroupInfoMapper groupInfoMapper;
@Resource
private PgGroupStoreRelMapper storeRelMapper;
private final ExecutorService dataQueryExecutor = Executors.newFixedThreadPool(10);
@Override
public void execute(ShardingContext shardingContext) {
log.info("预警计算定时任务开始执行");
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;
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.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.simple.SimpleJob;
import lombok.extern.slf4j.Slf4j;
import org.oreframework.boot.autoconfigure.elasticjob.annotation.ElasticJobConf;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.util.Calendar;
import java.util.Date;
/**
* 历史数据补跑定时任务——从 2026 年 1 月 1 日起逐周期回溯计算。
*
* <p>按周/月/截止周最新一天/截止月最新一天逐周期回溯,写入 warning_record 和 pg_store_output。
* 一次性执行,跑完后通过持久化标记跳过重复执行。</p>
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/28 14:00
*/
@Slf4j
@Component
@ElasticJobConf(name = "WarningHistoryBackfillJob", cron = "0 0 3 * * ?", description = "历史数据补跑定时任务", overwrite = false)
public class WarningHistoryBackfillJob implements SimpleJob {
@Resource
private StoreOutputService storeOutputService;
@Resource
private WarningEngineService warningEngineService;
@Resource
private PgGroupInfoMapper groupInfoMapper;
/** 历史数据起始日期:2026-01-01 */
private static final Date BACKFILL_START = getBackfillStartDate();
/** Redis key 标记是否已完成 */
private static final String BACKFILL_DONE_KEY = "warning:history:backfill:done";
@Override
public void execute(ShardingContext shardingContext) {
log.info("历史数据补跑任务开始执行");
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();
}
}
package cn.com.glsx.dj.strategy.mapper;
import cn.com.glsx.dj.mindworkplate.model.EcoCoefficientRule;
import org.apache.ibatis.annotations.Mapper;
import org.oreframework.datasource.mybatis.mapper.OreMapper;
import java.util.List;
/**
* 生态系数规则 Mapper(复用 eco_coefficient_rule 表)。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/28 14:00
*/
@Mapper
public interface EcoCoefficientRuleMapper extends OreMapper<EcoCoefficientRule> {
/**
* 查询所有启用的生态系数规则(按排序字段升序)。
*
* @return 规则列表
*/
List<EcoCoefficientRule> selectAllEnabled();
}
...@@ -11,6 +11,10 @@ import java.util.List; ...@@ -11,6 +11,10 @@ import java.util.List;
/** /**
* 项目组主表 Mapper。 * 项目组主表 Mapper。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/28 14:00
*/ */
@Mapper @Mapper
public interface PgGroupInfoMapper extends OreMapper<PgGroupInfo> { public interface PgGroupInfoMapper extends OreMapper<PgGroupInfo> {
...@@ -24,6 +28,13 @@ public interface PgGroupInfoMapper extends OreMapper<PgGroupInfo> { ...@@ -24,6 +28,13 @@ public interface PgGroupInfoMapper extends OreMapper<PgGroupInfo> {
List<ProjectGroupListDTO> selectProjectGroupPage(ProjectGroupQueryDTO queryDTO); List<ProjectGroupListDTO> selectProjectGroupPage(ProjectGroupQueryDTO queryDTO);
/** /**
* 查询所有启用的项目组(用于定时任务)。
*
* @return 项目组列表
*/
List<PgGroupInfo> selectAllEnabled();
/**
* 查询项目组下拉列表。 * 查询项目组下拉列表。
* *
* @param queryDTO 查询条件 * @param queryDTO 查询条件
......
...@@ -12,6 +12,10 @@ import java.util.Map; ...@@ -12,6 +12,10 @@ import java.util.Map;
/** /**
* 项目组门店关系 Mapper。 * 项目组门店关系 Mapper。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/28 14:00
*/ */
@Mapper @Mapper
public interface PgGroupStoreRelMapper extends OreMapper<PgGroupStoreRel> { public interface PgGroupStoreRelMapper extends OreMapper<PgGroupStoreRel> {
......
package cn.com.glsx.dj.strategy.mapper;
import cn.com.glsx.dj.strategy.model.projectgroup.PgStoreOutput;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.oreframework.datasource.mybatis.mapper.OreMapper;
import java.util.List;
/**
* 有产值门店记录 Mapper。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/28 14:00
*/
@Mapper
public interface PgStoreOutputMapper extends OreMapper<PgStoreOutput> {
/**
* 按条件查询有产值门店列表。
*
* @param businessType 业务类型
* @param timeDimension 时间维度
* @param periodStart 周期开始
* @param periodEnd 周期结束
* @return 有产值门店列表
*/
List<PgStoreOutput> selectByCondition(@Param("businessType") Integer businessType,
@Param("timeDimension") String timeDimension,
@Param("periodStart") String periodStart,
@Param("periodEnd") String periodEnd);
/**
* 按条件删除(幂等重算用)。
*
* @param businessType 业务类型
* @param timeDimension 时间维度
* @param periodStart 周期开始
* @param periodEnd 周期结束
* @return 删除条数
*/
int deleteByCondition(@Param("businessType") Integer businessType,
@Param("timeDimension") String timeDimension,
@Param("periodStart") String periodStart,
@Param("periodEnd") String periodEnd);
/**
* 批量插入有产值门店记录。
*
* @param list 记录列表
* @return 插入条数
*/
int batchInsert(@Param("list") List<PgStoreOutput> list);
}
...@@ -10,6 +10,10 @@ import java.util.Map; ...@@ -10,6 +10,10 @@ import java.util.Map;
/** /**
* 项目组预警配置 Mapper。 * 项目组预警配置 Mapper。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/28 14:00
*/ */
@Mapper @Mapper
public interface PgWarningConfigMapper extends OreMapper<PgWarningConfig> { public interface PgWarningConfigMapper extends OreMapper<PgWarningConfig> {
...@@ -21,4 +25,27 @@ public interface PgWarningConfigMapper extends OreMapper<PgWarningConfig> { ...@@ -21,4 +25,27 @@ public interface PgWarningConfigMapper extends OreMapper<PgWarningConfig> {
* @return 统计结果 * @return 统计结果
*/ */
List<Map<String, Object>> countActiveByGroupIds(@Param("groupIds") List<Integer> groupIds); List<Map<String, Object>> countActiveByGroupIds(@Param("groupIds") List<Integer> groupIds);
/**
* 查询项目组下所有启用的配置。
*
* @param groupId 项目组ID
* @return 配置列表
*/
List<PgWarningConfig> selectEnabledByGroupId(@Param("groupId") Integer groupId);
/**
* 查询所有启用的配置(用于定时任务)。
*
* @return 配置列表
*/
List<PgWarningConfig> selectAllEnabled();
/**
* 按预警类型查询所有启用的配置(用于效果分析获取全部指标)。
*
* @param warningType 预警类型: 5=黄色预警 4=红色预警 3=生态预警 2=兜底预警
* @return 配置列表
*/
List<PgWarningConfig> selectEnabledByWarningType(@Param("warningType") Integer warningType);
} }
...@@ -11,6 +11,10 @@ import java.util.List; ...@@ -11,6 +11,10 @@ import java.util.List;
/** /**
* 预警指标字典 Mapper。 * 预警指标字典 Mapper。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/28 14:00
*/ */
@Mapper @Mapper
public interface PgWarningMetricDictMapper extends OreMapper<PgWarningMetricDict> { public interface PgWarningMetricDictMapper extends OreMapper<PgWarningMetricDict> {
...@@ -22,4 +26,14 @@ public interface PgWarningMetricDictMapper extends OreMapper<PgWarningMetricDict ...@@ -22,4 +26,14 @@ public interface PgWarningMetricDictMapper extends OreMapper<PgWarningMetricDict
* @return 指标元数据列表 * @return 指标元数据列表
*/ */
List<MetricOptionDTO> listMetrics(@Param("queryDTO") ProjectGroupMetricQueryDTO queryDTO); List<MetricOptionDTO> listMetrics(@Param("queryDTO") ProjectGroupMetricQueryDTO queryDTO);
/**
* 按预警类型+业务线查询所有指标基础数据(用于效果分析批量获取 dataType/unit/categoryExtension)。
*
* @param warningType 预警类型
* @param biz 业务类型
* @return 指标字典列表
*/
List<PgWarningMetricDict> selectByWarningTypeAndBiz(@Param("warningType") Integer warningType,
@Param("biz") Integer biz);
} }
...@@ -4,12 +4,17 @@ import cn.com.glsx.dj.strategy.dto.projectgroup.ProjectGroupWarningRecordDTO; ...@@ -4,12 +4,17 @@ import cn.com.glsx.dj.strategy.dto.projectgroup.ProjectGroupWarningRecordDTO;
import cn.com.glsx.dj.strategy.dto.projectgroup.ProjectGroupWarningRecordQueryDTO; import cn.com.glsx.dj.strategy.dto.projectgroup.ProjectGroupWarningRecordQueryDTO;
import cn.com.glsx.dj.strategy.model.projectgroup.PgWarningRecord; import cn.com.glsx.dj.strategy.model.projectgroup.PgWarningRecord;
import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.oreframework.datasource.mybatis.mapper.OreMapper; import org.oreframework.datasource.mybatis.mapper.OreMapper;
import java.util.List; import java.util.List;
/** /**
* 预警结果 Mapper。 * 预警结果 Mapper。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/28 14:00
*/ */
@Mapper @Mapper
public interface PgWarningRecordMapper extends OreMapper<PgWarningRecord> { public interface PgWarningRecordMapper extends OreMapper<PgWarningRecord> {
...@@ -21,4 +26,26 @@ public interface PgWarningRecordMapper extends OreMapper<PgWarningRecord> { ...@@ -21,4 +26,26 @@ public interface PgWarningRecordMapper extends OreMapper<PgWarningRecord> {
* @return 预警结果列表 * @return 预警结果列表
*/ */
List<ProjectGroupWarningRecordDTO> listWarningRecordsByCondition(ProjectGroupWarningRecordQueryDTO queryDTO); List<ProjectGroupWarningRecordDTO> listWarningRecordsByCondition(ProjectGroupWarningRecordQueryDTO queryDTO);
/**
* 批量插入预警记录。
*
* @param records 预警记录列表
* @return 插入条数
*/
int batchInsert(@Param("records") List<PgWarningRecord> records);
/**
* 按条件删除预警记录(用于幂等重算)。
*
* @param configId 配置ID
* @param timeDimension 时间维度
* @param periodStart 周期开始
* @param periodEnd 周期结束
* @return 删除条数
*/
int deleteByCondition(@Param("configId") Integer configId,
@Param("timeDimension") String timeDimension,
@Param("periodStart") String periodStart,
@Param("periodEnd") String periodEnd);
} }
...@@ -5,7 +5,11 @@ import org.apache.ibatis.annotations.Mapper; ...@@ -5,7 +5,11 @@ import org.apache.ibatis.annotations.Mapper;
import org.oreframework.datasource.mybatis.mapper.OreMapper; import org.oreframework.datasource.mybatis.mapper.OreMapper;
/** /**
* 预警类型字典 Mapper。 * 预警类型字典 Mapper(基础 CRUD 由 OreMapper 提供)。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/28 14:00
*/ */
@Mapper @Mapper
public interface PgWarningTypeDictMapper extends OreMapper<PgWarningTypeDict> { public interface PgWarningTypeDictMapper extends OreMapper<PgWarningTypeDict> {
......
...@@ -29,4 +29,14 @@ public interface ShopMerchantDirectorConfigMapper extends OreMapper<ShopMerchant ...@@ -29,4 +29,14 @@ public interface ShopMerchantDirectorConfigMapper extends OreMapper<ShopMerchant
*/ */
List<ShopMerchantDirectorConfig> selectByMerchantIdAndType(@Param("merchantId") Integer merchantId, List<ShopMerchantDirectorConfig> selectByMerchantIdAndType(@Param("merchantId") Integer merchantId,
@Param("directorType") Integer directorType); @Param("directorType") Integer directorType);
/**
* 根据负责人用户ID和负责人类型查询关联的门店号列表。
*
* @param uuid 负责人用户ID
* @param typeValue 负责人类型(DirectorTypeEnum byte值)
* @return 门店号列表
*/
List<Integer> findMerchantIdsByUUidAndType(@Param("uuid") String uuid,
@Param("typeValue") byte typeValue);
} }
...@@ -95,4 +95,18 @@ public interface StrategyInfoMapper extends OreMapper<StrategyInfo> { ...@@ -95,4 +95,18 @@ public interface StrategyInfoMapper extends OreMapper<StrategyInfo> {
* @return * @return
*/ */
List<String> selectStaffTempSupport(@Param("merchantId") Integer merchantId, @Param("yearMonth") String yearMonth, @Param("userUuidList") List<String> userUuidList); List<String> selectStaffTempSupport(@Param("merchantId") Integer merchantId, @Param("yearMonth") String yearMonth, @Param("userUuidList") List<String> userUuidList);
/**
* 查询指定业务+周期内有策略记录的门店号列表。
*
* @param biz 业务类型
* @param merchantIds 门店号列表
* @param startDate 周期开始日期
* @param endDate 周期结束日期
* @return 有策略记录的门店号列表
*/
List<Integer> listMerchantIdsWithStrategy(@Param("biz") Integer biz,
@Param("merchantIds") List<Integer> merchantIds,
@Param("startDate") String startDate,
@Param("endDate") String endDate);
} }
\ No newline at end of file \ No newline at end of file
package cn.com.glsx.dj.strategy.remote;
import cn.com.glsx.dj.peanalysis.constants.SymbolConstants;
import cn.com.glsx.dj.strategy.dto.projectgroup.GroupOptionDTO;
import cn.com.glsx.dj.strategy.dto.projectgroup.MetricOptionDTO;
import cn.com.glsx.dj.strategy.dto.projectgroup.ProjectGroupMetricQueryDTO;
import cn.com.glsx.dj.strategy.dto.projectgroup.WarningTypeOptionDTO;
import cn.com.glsx.dj.strategy.dto.warning.EffectAnalysisDTO;
import cn.com.glsx.dj.strategy.dto.warning.EffectAnalysisRequest;
import cn.com.glsx.dj.strategy.dto.warning.MerchantFilterDTO;
import cn.com.glsx.dj.strategy.dto.warning.MetricAnalysisDTO;
import cn.com.glsx.dj.strategy.dto.warning.StoreWarningSummaryDTO;
import cn.com.glsx.dj.strategy.dto.warning.WarningRecordDTO;
import cn.com.glsx.dj.strategy.dto.warning.WarningRecordQueryRequest;
import cn.com.glsx.dj.strategy.enums.*;
import cn.com.glsx.dj.strategy.dto.warning.PeriodRange;
import cn.com.glsx.dj.strategy.mapper.PgGroupInfoMapper;
import cn.com.glsx.dj.strategy.mapper.PgWarningMetricDictMapper;
import cn.com.glsx.dj.strategy.model.projectgroup.PgGroupInfo;
import cn.com.glsx.dj.strategy.model.projectgroup.PgStoreOutput;
import cn.com.glsx.dj.strategy.model.projectgroup.PgWarningMetricDict;
import cn.com.glsx.dj.strategy.service.warning.BiMetricQueryService;
import cn.com.glsx.dj.strategy.service.warning.MerchantFilterUtil;
import cn.com.glsx.dj.strategy.service.warning.StoreOutputService;
import cn.com.glsx.dj.strategy.service.warning.WarningRecordService;
import cn.com.glsx.dj.strategy.util.MemoryPageUtil;
import cn.hutool.core.collection.CollUtil;
import cn.com.glsx.framework.core.beans.rpc.RpcPagination;
import cn.com.glsx.framework.core.beans.rpc.RpcResponse;
import cn.com.glsx.framework.core.enums.DefaultErrorEnum;
import cn.com.glsx.framework.core.exception.RpcServiceException;
import edu.umd.cs.findbugs.annotations.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.dubbo.config.annotation.DubboService;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
/**
* 预警引擎查询远程接口实现。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/28 14:00
*/
@Slf4j
@DubboService(version = "1.0.0", validation = "true")
public class WarningEngineRemoteImpl implements WarningEngineRemote {
@Resource
private WarningRecordService warningRecordService;
@Resource
private MerchantFilterUtil merchantFilterUtil;
@Resource
private BiMetricQueryService biMetricQueryService;
@Resource
private PgWarningMetricDictMapper pgWarningMetricDictMapper;
@Resource
private PgGroupInfoMapper pgGroupInfoMapper;
@Resource
private StoreOutputService storeOutputService;
@Override
public RpcResponse<List<StoreWarningSummaryDTO>> findWarningSummary(WarningRecordQueryRequest request) {
try {
// 自定义区间(无时间维度)→ 查BI获取有产值门店
if (request.getTimeDimension() == null || request.getTimeDimension().isEmpty()) {
return RpcResponse.success(buildSummaryFromBi(request));
}
List<Integer> filteredMerchantIds = resolveFilteredMerchantIds(request);
if (request.getWarningType() == null) {
// 未选预警类型 → 查 pg_store_output 获取有产值门店,left join 预警摘要
return RpcResponse.success(buildSummaryFromStoreOutput(request, filteredMerchantIds));
}
// 选了预警类型 → 查 warning_record 筛选触发该类型的门店
return RpcResponse.success(warningRecordService.queryStoreSummary(request, filteredMerchantIds));
} catch (RpcServiceException e) {
log.error("查询门店预警汇总列表失败", e);
return RpcResponse.error(e.getError(), e.getMessage());
} catch (Exception e) {
log.error("查询门店预警汇总列表异常", e);
return RpcResponse.error(DefaultErrorEnum.SERVICE_ERROR, e.getMessage());
}
}
/**
* 从 pg_store_output 查有产值门店,left join 预警摘要。
*/
private List<StoreWarningSummaryDTO> buildSummaryFromStoreOutput(WarningRecordQueryRequest request,
List<Integer> filteredMerchantIds) {
// 1. 查 pg_store_output 获取有产值门店
List<PgStoreOutput> outputs = storeOutputService.listStoreOutputs(
request.getBusinessType(), request.getTimeDimension(),
request.getStartDate(), request.getEndDate());
if (CollectionUtils.isEmpty(outputs)) {
return new ArrayList<>();
}
// 2. 提取门店ID→名称映射
Map<Integer, String> storeIdToName = new LinkedHashMap<>();
for (PgStoreOutput output : outputs) {
storeIdToName.putIfAbsent(output.getStoreId(), output.getStoreName());
}
// 3. 应用品牌/区域/运营/督导筛选
Set<Integer> targetStoreIds;
if (CollectionUtils.isNotEmpty(filteredMerchantIds)) {
targetStoreIds = new HashSet<>(filteredMerchantIds);
targetStoreIds.retainAll(storeIdToName.keySet());
} else {
targetStoreIds = new LinkedHashSet<>(storeIdToName.keySet());
}
if (targetStoreIds.isEmpty()) {
return new ArrayList<>();
}
// 4. 查 warning_record 获取预警摘要(不限预警类型)
WarningRecordQueryRequest warnReq = new WarningRecordQueryRequest();
warnReq.setBusinessType(request.getBusinessType());
warnReq.setTimeDimension(request.getTimeDimension());
warnReq.setStartDate(request.getStartDate());
warnReq.setEndDate(request.getEndDate());
warnReq.setMonitorTarget(MonitorTargetEnum.SHOP.getCode());
List<WarningRecordDTO> records = warningRecordService.queryRecords(warnReq, new ArrayList<>(targetStoreIds));
Map<Integer, List<WarningRecordDTO>> recordsByStore = new LinkedHashMap<>();
if (CollectionUtils.isNotEmpty(records)) {
for (WarningRecordDTO r : records) {
if (r.getStoreId() != null) {
recordsByStore.computeIfAbsent(r.getStoreId(), k -> new ArrayList<>()).add(r);
}
}
}
// 5. 按门店构建汇总
List<StoreWarningSummaryDTO> result = new ArrayList<>();
for (Integer storeId : targetStoreIds) {
StoreWarningSummaryDTO dto = new StoreWarningSummaryDTO();
dto.setMerchantNo(String.valueOf(storeId));
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);
result.add(dto);
}
return result;
}
@Override
public RpcResponse<List<WarningRecordDTO>> findWarningDetailByStoreAndStaff(WarningRecordQueryRequest request) {
try {
List<Integer> filteredMerchantIds = resolveFilteredMerchantIds(request);
return RpcResponse.success(warningRecordService.queryRecords(request, filteredMerchantIds));
} catch (RpcServiceException e) {
log.error("查询门店员工预警明细失败", e);
return RpcResponse.error(e.getError(), e.getMessage());
} catch (Exception e) {
log.error("查询门店员工预警明细异常", e);
return RpcResponse.error(DefaultErrorEnum.SERVICE_ERROR, e.getMessage());
}
}
/**
* 自定义区间查BI获取有产值门店。
*/
private List<StoreWarningSummaryDTO> buildSummaryFromBi(WarningRecordQueryRequest request) {
BiMetricQueryService.QueryParams params = new BiMetricQueryService.QueryParams();
params.setBizs(request.getBusinessType());
params.setItemCodes(BiMetricCodeEnum.OUTPUT_VALUE.getCode());
params.setDateType(BiDateTypeEnum.ALL.getValue());
params.setExts(BiAggregationTypeEnum.MERCHANT.getValue());
params.setStartDate(request.getStartDate());
params.setEndDate(request.getEndDate());
Optional.ofNullable(resolveFilteredMerchantIds(request))
.filter(CollUtil::isNotEmpty)
.ifPresent(filterMerchantIds -> params.setMerchantIds(CollUtil.join(filterMerchantIds, SymbolConstants.COMMA)));
List<BiMetricQueryService.ItemDetail> items = biMetricQueryService.getItemDetail(params, BiMetricQueryService.DATE_METHOD);
if (CollectionUtils.isEmpty(items)) {
return new ArrayList<>();
}
return items.stream().map(item -> {
StoreWarningSummaryDTO dto = new StoreWarningSummaryDTO();
dto.setMerchantNo(item.getMerchantId());
dto.setStoreName(item.getMerchantName());
return dto;
}).collect(Collectors.toList());
}
@Override
public RpcResponse<RpcPagination<EffectAnalysisDTO>> analysisEffect(EffectAnalysisRequest request) {
try {
// 1. 预警类型必传
if (request.getWarningType() == null) {
log.warn("效果分析缺少必传参数warningType");
return RpcResponse.success(new RpcPagination<>());
}
// 2. 从 warning_record 查询触发了该预警类型的门店记录
WarningRecordQueryRequest queryReq = toQueryRequest(request);
queryReq.setMonitorTarget(MonitorTargetEnum.SHOP.getCode());
List<WarningRecordDTO> warningRecords = warningRecordService.queryRecords(queryReq, null);
if (CollectionUtils.isEmpty(warningRecords)) {
return RpcResponse.success(new RpcPagination<>());
}
// 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<>();
for (WarningRecordDTO r : warningRecords) {
if (r.getStoreId() != 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());
storeCurrentValueMap.computeIfAbsent(r.getStoreId(), k -> new LinkedHashMap<>())
.putIfAbsent(r.getMetricCode(), r.getMetricValue());
allMetricCodeToName.putIfAbsent(r.getMetricCode(), r.getMetricName());
}
}
if (storeIdToName.isEmpty() || allMetricCodeToName.isEmpty()) {
return RpcResponse.success(new RpcPagination<>());
}
// 4. 先对门店列表内存分页,后续只查当前页门店的BI数据
int pageNum = request.getPageNum() != null ? request.getPageNum() : 1;
int pageSize = request.getPageSize() != null ? request.getPageSize() : 10;
List<Integer> allStoreIds = new ArrayList<>(storeIdToName.keySet());
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);
}
}
}
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
// 6. 计算下一周期(按时间维度:周→下周,月→下月)
TimeDimensionEnum dimension = TimeDimensionEnum.fromCode(request.getTimeDimension());
PeriodRange nextPeriod = dimension.calcNextPeriod(sdf.parse(request.getEndDate()));
String nextStart = sdf.format(nextPeriod.getStart());
String nextEnd = sdf.format(nextPeriod.getEnd());
String merchantIdStr = pageStoreIds.stream().map(String::valueOf)
.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();
PgWarningMetricDict metricDict = metricDictMap.get(metricCode);
boolean needPercentScale = metricDict != null
&& metricDict.getDataType() != null && metricDict.getDataType() == 1
&& "%".equals(metricDict.getUnit());
String categoryExtension = metricDict != null ? metricDict.getCategoryExtension() : null;
// 下一周期从BI查询;当前周期从 warning_record 直接取
Map<Integer, BigDecimal> nextByStore = queryBiForStores(
request.getBusinessType(), metricCode, merchantIdStr,
nextStart, nextEnd);
// 只对该指标触发了的门店生成 MetricAnalysisDTO
for (Integer storeId : pageStoreIds) {
if (!storeMetricMap.containsKey(storeId)
|| !storeMetricMap.get(storeId).containsKey(metricCode)) {
continue;
}
// 当前值:直接从 warning_record 获取
BigDecimal currentValue = storeCurrentValueMap
.getOrDefault(storeId, new LinkedHashMap<>()).get(metricCode);
if (currentValue != null && needPercentScale) {
currentValue = currentValue.multiply(new BigDecimal("100"));
}
MetricAnalysisDTO metricDto = new MetricAnalysisDTO();
metricDto.setMetricCode(metricCode);
metricDto.setMetricName(metricName);
metricDto.setCategoryExtension(categoryExtension);
metricDto.setCurrentValue(currentValue);
metricDto.setUnit(metricDict != null ? metricDict.getUnit() : null);
BigDecimal nextValue = nextByStore.get(storeId);
if (nextValue == null) {
nextValue = BigDecimal.ZERO;
} else if (needPercentScale) {
nextValue = nextValue.multiply(new BigDecimal("100"));
}
metricDto.setNextValue(nextValue);
if (currentValue != null && currentValue.compareTo(BigDecimal.ZERO) != 0) {
BigDecimal changeRate = nextValue.subtract(currentValue)
.divide(currentValue, 4, RoundingMode.HALF_UP);
metricDto.setChangeRate(changeRate);
metricDto.setImproved(changeRate.compareTo(BigDecimal.ZERO) > 0);
}
storeMetricsResult.get(storeId).add(metricDto);
}
}
// 8. 按门店构建 EffectAnalysisDTO 列表(仅当前页)
List<EffectAnalysisDTO> pageList = new ArrayList<>();
for (Integer storeId : pageStoreIds) {
EffectAnalysisDTO dto = new EffectAnalysisDTO();
dto.setMerchantNo(String.valueOf(storeId));
dto.setStoreName(storeIdToName.get(storeId));
dto.setMetrics(storeMetricsResult.getOrDefault(storeId, new ArrayList<>()));
pageList.add(dto);
}
// 9. 封装分页结果
RpcPagination<EffectAnalysisDTO> result = new RpcPagination<>();
result.setPageNum(pageNum);
result.setPageSize(pageSize);
result.setTotal(allStoreIds.size());
result.setPages(storePage.getPages());
result.setList(pageList);
return RpcResponse.success(result);
} catch (RpcServiceException e) {
log.error("效果分析失败", e);
return RpcResponse.error(e.getError(), e.getMessage());
} catch (Exception e) {
log.error("效果分析异常", e);
return RpcResponse.error(DefaultErrorEnum.SERVICE_ERROR, e.getMessage());
}
}
/**
* 将效果分析请求转为通用查询请求。
*/
private WarningRecordQueryRequest toQueryRequest(EffectAnalysisRequest request) {
WarningRecordQueryRequest req = new WarningRecordQueryRequest();
req.setBusinessType(request.getBusinessType());
req.setWarningType(request.getWarningType());
req.setTimeDimension(request.getTimeDimension());
req.setStartDate(request.getStartDate());
req.setEndDate(request.getEndDate());
return req;
}
/**
* 按门店维度查询BI指标值。
*
* @param biz 业务类型
* @param metricCode 指标编码
* @param merchantIds 门店号(逗号分隔)
* @param startDate 开始日期
* @param endDate 结束日期
* @return storeId → metricValue
*/
private Map<Integer, BigDecimal> queryBiForStores(Integer biz, String metricCode,
String merchantIds, String startDate, String endDate) {
Map<Integer, BigDecimal> result = new LinkedHashMap<>();
BiMetricQueryService.QueryParams params = new BiMetricQueryService.QueryParams();
params.setBizs(biz);
params.setItemCodes(metricCode);
params.setMerchantIds(merchantIds);
params.setStartDate(startDate);
params.setEndDate(endDate);
params.setDateType(BiDateTypeEnum.ALL.getValue());
params.setExts(BiAggregationTypeEnum.MERCHANT.getValue());
try {
List<BiMetricQueryService.ItemDetail> items = biMetricQueryService.getItemDetail(params, BiMetricQueryService.DATE_METHOD);
if (CollectionUtils.isNotEmpty(items)) {
for (BiMetricQueryService.ItemDetail item : items) {
if (item.getMerchantId() != null && item.getItemValue() != null) {
result.put(Integer.parseInt(item.getMerchantId()), item.getItemValue());
}
}
}
} catch (Exception e) {
log.error("BI查询失败,metricCode={}", metricCode, e);
}
return result;
}
@Override
public RpcResponse<List<WarningTypeOptionDTO>> listWarningTypes() {
try {
return RpcResponse.success(null);
} catch (RpcServiceException e) {
log.error("查询预警类型列表失败", e);
return RpcResponse.error(e.getError(), e.getMessage());
} catch (Exception e) {
log.error("查询预警类型列表异常", e);
return RpcResponse.error(DefaultErrorEnum.SERVICE_ERROR, e.getMessage());
}
}
@Override
public RpcResponse<List<MetricOptionDTO>> listMetrics(ProjectGroupMetricQueryDTO queryDTO) {
try {
if (queryDTO == null || queryDTO.getWarningType() == null || queryDTO.getBiz() == null) {
return RpcResponse.success(new ArrayList<>());
}
List<PgWarningMetricDict> dicts = pgWarningMetricDictMapper
.selectByWarningTypeAndBiz(queryDTO.getWarningType(), queryDTO.getBiz());
if (CollUtil.isEmpty(dicts)) {
return RpcResponse.success(new ArrayList<>());
}
List<MetricOptionDTO> result = new ArrayList<>();
for (PgWarningMetricDict dict : dicts) {
MetricOptionDTO dto = new MetricOptionDTO();
dto.setMetricId(dict.getId());
dto.setMetricName(dict.getIndexName());
dto.setIndexName(dict.getIndexName());
dto.setDataType(dict.getDataType());
dto.setUnit(dict.getUnit());
dto.setSortOrder(dict.getSortOrder());
dto.setCategoryExtension(dict.getCategoryExtension());
result.add(dto);
}
return RpcResponse.success(result);
} catch (RpcServiceException e) {
log.error("查询指标列表失败", e);
return RpcResponse.error(e.getError(), e.getMessage());
} catch (Exception e) {
log.error("查询指标列表异常", e);
return RpcResponse.error(DefaultErrorEnum.SERVICE_ERROR, e.getMessage());
}
}
@Override
public RpcResponse<List<GroupOptionDTO>> listGroups() {
try {
List<PgGroupInfo> groups = pgGroupInfoMapper.selectAllEnabled();
if (CollUtil.isEmpty(groups)) {
return RpcResponse.success(new ArrayList<GroupOptionDTO>());
}
List<GroupOptionDTO> result = new ArrayList<>();
for (PgGroupInfo group : groups) {
GroupOptionDTO dto = new GroupOptionDTO();
dto.setGroupId(group.getId());
dto.setGroupName(group.getGroupName());
result.add(dto);
}
return RpcResponse.success(result);
} catch (RpcServiceException e) {
log.error("查询项目组下拉列表失败", e);
return RpcResponse.error(e.getError(), e.getMessage());
} catch (Exception e) {
log.error("查询项目组下拉列表异常", e);
return RpcResponse.error(DefaultErrorEnum.SERVICE_ERROR, e.getMessage());
}
}
/**
* 根据请求中的品牌/区域/运营/门店名称/项目组/策略下发等筛选条件计算门店交集。
*/
private List<Integer> resolveFilteredMerchantIds(WarningRecordQueryRequest request) {
MerchantFilterDTO filterDto = new MerchantFilterDTO();
filterDto.setBusinessType(request.getBusinessType());
filterDto.setRegionId(request.getRegionId());
filterDto.setFirstbrandIds(request.getFirstbrandIds());
filterDto.setTwoBrandIds(request.getTwoBrandIds());
filterDto.setOnlineOperatorId(request.getOnlineOperatorId());
filterDto.setRegionalOperatorId(request.getRegionalOperatorId());
filterDto.setFlyingSupervisorId(request.getFlightSupervisionId());
filterDto.setStoreName(request.getStoreName());
filterDto.setGroupId(request.getGroupId());
filterDto.setIsStrategySent(request.getIsStrategySent());
filterDto.setStartDate(request.getStartDate());
filterDto.setEndDate(request.getEndDate());
return merchantFilterUtil.getIntersectionMerchantIds(filterDto);
}
}
...@@ -27,6 +27,9 @@ import cn.com.glsx.dj.strategy.dto.MentoringTaskDetailDTO; ...@@ -27,6 +27,9 @@ import cn.com.glsx.dj.strategy.dto.MentoringTaskDetailDTO;
import cn.com.glsx.dj.strategy.dto.MerchantInfo; import cn.com.glsx.dj.strategy.dto.MerchantInfo;
import cn.com.glsx.dj.strategy.dto.StaffHistoryRecordDTO; import cn.com.glsx.dj.strategy.dto.StaffHistoryRecordDTO;
import cn.com.glsx.dj.strategy.dto.StaffInfoDTO; import cn.com.glsx.dj.strategy.dto.StaffInfoDTO;
import cn.com.glsx.dj.strategy.enums.BiAggregationTypeEnum;
import cn.com.glsx.dj.strategy.enums.BiDateTypeEnum;
import cn.com.glsx.dj.strategy.enums.BiMetricCodeEnum;
import cn.com.glsx.dj.strategy.enums.StrategyErrorEnum; import cn.com.glsx.dj.strategy.enums.StrategyErrorEnum;
import cn.com.glsx.dj.strategy.enums.StrategyPushFlagEnum; import cn.com.glsx.dj.strategy.enums.StrategyPushFlagEnum;
import cn.com.glsx.dj.strategy.enums.StrategyPushType; import cn.com.glsx.dj.strategy.enums.StrategyPushType;
...@@ -766,9 +769,9 @@ public class StrategyInfoService { ...@@ -766,9 +769,9 @@ public class StrategyInfoService {
queryParams.setBrandIds(dataStatsConfig.defaultBrandId); queryParams.setBrandIds(dataStatsConfig.defaultBrandId);
queryParams.setBizs(bizs); queryParams.setBizs(bizs);
queryParams.setMerchantIds(String.valueOf(merchantId)); queryParams.setMerchantIds(String.valueOf(merchantId));
queryParams.setItemCodes("A036"); queryParams.setItemCodes(BiMetricCodeEnum.OUTPUT_VALUE.getCode());
queryParams.setDateType(2); queryParams.setDateType(BiDateTypeEnum.MONTH.getValue());
queryParams.setExts("staffIds"); queryParams.setExts(BiAggregationTypeEnum.STAFF.getValue());
queryParams.setStartDate(DateUtil.formatDate(strategyMerchantTimelineList.get(0).getNodeDate())); queryParams.setStartDate(DateUtil.formatDate(strategyMerchantTimelineList.get(0).getNodeDate()));
queryParams.setEndDate(DateUtil.formatDate(strategyMerchantTimelineList.get(strategyMerchantTimelineList.size() - 1).getNodeDate())); queryParams.setEndDate(DateUtil.formatDate(strategyMerchantTimelineList.get(strategyMerchantTimelineList.size() - 1).getNodeDate()));
List<DataBusinessDTO> totalOutputList = getTotalOutputGroupByMerchant(queryParams); List<DataBusinessDTO> totalOutputList = getTotalOutputGroupByMerchant(queryParams);
......
package cn.com.glsx.dj.strategy.service.warning;
import cn.com.glsx.framework.core.exception.RpcServiceException;
import cn.com.glsx.dj.strategy.util.DateUtil;
import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.annotation.JsonFormat;
import lombok.Data;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.client.RestTemplate;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
/**
* BI 指标查询服务——仿 DateService(rpc-mindworkplate),调用同一 BI HTTP API。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/28 14:00
*/
@Slf4j
@Service
public class BiMetricQueryService {
@Autowired
private Environment environment;
public static final String DATE_METHOD = "data/";
private static final String DETAIL_METHOD = "detail/";
private String getBaseUrl() {
return environment.getProperty("tianqi.query.base.url", "http://192.168.3.211:8021/");
}
/**
* 获取时间区间指标数据。
*
* @param queryParams 查询参数
* @param method 接口方法(data/ 或 detail/)
* @return 指标明细列表
*/
public List<ItemDetail> getItemDetail(QueryParams queryParams, String method) {
RestTemplate restTemplate = new RestTemplate();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
HttpEntity<QueryParams> entity = new HttpEntity<>(queryParams, headers);
log.info("BI请求参数:{}, 请求方法:{}", JSON.toJSONString(queryParams), method);
ResponseEntity<String> response = restTemplate.postForEntity(getBaseUrl() + method, entity, String.class);
log.info("BI返回结果:{}", response.getBody());
Response response1;
try {
response1 = JSON.parseObject(response.getBody(), Response.class);
} catch (Exception e) {
log.error("BI返回结果解析异常:{}", e.getMessage(), e);
throw new RpcServiceException(e.getMessage());
}
if (response1 == null) {
throw new RpcServiceException("调用BI获取数据异常!");
}
if (response1.getCode() != 200) {
throw new RpcServiceException(response1.getMsg());
}
if (StringUtils.isEmpty(response1.getContent())) {
return new ArrayList<>();
}
try {
return JSON.parseArray(JSON.toJSONString(response1.getContent()), ItemDetail.class);
} catch (Exception e) {
log.error("BI返回结果解析异常:{}", e.getMessage(), e);
throw new RpcServiceException(e.getMessage());
}
}
// ==================== 内部类 ====================
@ToString
@Data
public static class Response<T> implements Serializable {
private T content;
private String msg;
private int code;
}
@ToString
@Data
public static class QueryParams implements Serializable {
/** 业务: 1=延保 2=轻改 3=权益 */
private Integer bizs;
/** 指标代码 */
private String itemCodes;
/** 品牌ID */
private String brandIds;
/** 门店号列表 */
private String merchantIds;
/** 产品ID */
private String productIds;
/** 车系 */
private String series;
/** 扩展参数 */
private String exts;
private Integer year;
/** 员工ID列表 */
private String staffIds;
/** 员工手机号列表 */
private String staffPhones;
/** 开始日期 */
private String startDate;
/** 结束日期 */
private String endDate;
private Integer step;
/** 日期类型: 0=按日 1=按周 2=按月 3=按年 4=按查询时间段汇总 */
private Integer dateType;
}
@ToString
@Data
public static class ItemDetail implements Serializable {
private String biz;
private String rowkey;
private String itemCode;
@JsonFormat(pattern = DateUtil.PATTERN_YYYY_MM_DD, timezone = "GMT+8")
private Date date;
private String merchantId;
private String merchantName;
private String staffId;
private String staffName;
private String staffPhone;
private String productId;
private String brandId;
private String productName;
private String series;
/** 指标值 */
private BigDecimal itemValue;
/** 上一周期值(环比) */
private BigDecimal preValue;
/** 环比 */
private BigDecimal rate;
@JsonFormat(pattern = DateUtil.PATTERN_YYYY_MM_DD, timezone = "GMT+8")
private Date createTime;
private String remark;
@JsonFormat(pattern = DateUtil.PATTERN_YYYY_MM_DD, timezone = "GMT+8")
private Date startDate;
@JsonFormat(pattern = DateUtil.PATTERN_YYYY_MM_DD, timezone = "GMT+8")
private Date endDate;
}
}
package cn.com.glsx.dj.strategy.service.warning;
import cn.com.glsx.dj.mindworkplate.model.EcoCoefficientRule;
import cn.com.glsx.dj.strategy.mapper.EcoCoefficientRuleMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
/**
* 指标生态系数规则查询服务——仿 EcoCoefficientService(rpc-dj-pe-analysis)。
*
* <p>加载 eco_coefficient_rule 中已启用的规则到内存缓存,按指标编码和指标值匹配生态系数。</p>
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/28 14:00
*/
@Slf4j
@Service
public class EcoCoefficientQueryService implements ApplicationListener<ApplicationReadyEvent> {
@Resource
private EcoCoefficientRuleMapper ecoCoefficientRuleMapper;
private final Map<String, List<EcoCoefficientRule>> ruleCache = new ConcurrentHashMap<>();
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
reloadRules();
log.info("生态系数规则查询服务初始化完成");
}
/**
* 重新加载已启用的生态系数规则到内存缓存。
*/
public void reloadRules() {
List<EcoCoefficientRule> rules = ecoCoefficientRuleMapper.selectAllEnabled();
Map<String, List<EcoCoefficientRule>> groupedRules = (rules == null ? Collections.<EcoCoefficientRule>emptyList() : rules)
.stream()
.filter(rule -> StringUtils.isNotBlank(rule.getIndicatorCode()))
.filter(rule -> rule.getCoefficient() != null)
.collect(Collectors.groupingBy(
EcoCoefficientRule::getIndicatorCode,
Collectors.collectingAndThen(Collectors.toList(), this::sortRules)
));
ruleCache.clear();
ruleCache.putAll(groupedRules);
log.info("生态系数规则加载完成,规则数:{},指标数:{}",
rules == null ? 0 : rules.size(), groupedRules.size());
}
/**
* 根据指标编码和指标值获取生态系数。
*
* @param indicatorCode 指标编码
* @param metricValue 指标值
* @return 命中时返回生态系数,未命中返回 BigDecimal.ZERO
*/
public BigDecimal getCoefficient(String indicatorCode, BigDecimal metricValue) {
if (StringUtils.isBlank(indicatorCode) || metricValue == null) {
return null;
}
List<EcoCoefficientRule> rules = ruleCache.get(indicatorCode);
if (CollectionUtils.isEmpty(rules)) {
log.info("未找到生态系数规则,indicatorCode:{}", indicatorCode);
return null;
}
BigDecimal coefficient = matchRules(rules, metricValue);
if (coefficient != null) {
return coefficient;
}
log.warn("生态系数规则未命中,indicatorCode:{},metricValue:{}", indicatorCode, metricValue);
return BigDecimal.ZERO;
}
private BigDecimal matchRules(List<EcoCoefficientRule> rules, BigDecimal metricValue) {
for (EcoCoefficientRule rule : rules) {
BigDecimal minValue = rule.getMinPenetration() == null ? BigDecimal.ZERO : rule.getMinPenetration();
BigDecimal maxValue = rule.getMaxPenetration();
boolean match = metricValue.compareTo(minValue) >= 0
&& (maxValue == null || metricValue.compareTo(maxValue) < 0);
if (match) {
log.info("生态系数规则命中,indicatorCode:{},metricValue:{},range:[{}~{}],coefficient:{}",
rule.getIndicatorCode(), metricValue, minValue, maxValue, rule.getCoefficient());
return rule.getCoefficient();
}
}
return null;
}
private List<EcoCoefficientRule> sortRules(List<EcoCoefficientRule> rules) {
return rules.stream()
.sorted(Comparator
.comparing(EcoCoefficientRule::getSortOrder, Comparator.nullsLast(Integer::compareTo))
.thenComparing(EcoCoefficientRule::getMinPenetration, Comparator.nullsFirst(BigDecimal::compareTo)))
.collect(Collectors.toList());
}
}
package cn.com.glsx.dj.strategy.service.warning;
import cn.com.glsx.dj.strategy.dto.warning.MerchantFilterDTO;
import cn.com.glsx.dj.strategy.mapper.PgGroupStoreRelMapper;
import cn.com.glsx.dj.strategy.mapper.ShopMerchantDirectorConfigMapper;
import cn.com.glsx.dj.strategy.mapper.StrategyInfoMapper;
import cn.com.glsx.merchants.dto.merchant.CarBrandProvinceRequestDTO;
import cn.com.glsx.merchants.dto.merchant.CarBrandRequestDTO;
import cn.com.glsx.merchants.model.request.MerchantOpenRequest;
import cn.com.glsx.merchants.model.response.MerchantProvinceDTO;
import cn.com.glsx.merchants.model.response.MerchantResponse;
import cn.com.glsx.merchants.model.response.MerchantSimpleResponse;
import cn.com.glsx.merchants.remote.MerchantRemote;
import cn.com.glsx.framework.core.beans.rpc.RpcResponse;
import cn.com.glsx.framework.core.exception.RpcServiceException;
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.Arrays;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* 门店筛选工具——提取自 MonitoringService.getSearchMerchantIds() 的门店交集逻辑。
*
* <p>通过品牌/区域/运营人员/飞行督导筛选门店,并取交集。</p>
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/28 14:00
*/
@Slf4j
@Component
public class MerchantFilterUtil {
/** 线上运营:业务 1/3 → 2.1线上运营(type=7),业务 2 → 1.1线上运营(type=5) */
private static final byte ONLINE_TYPE_21 = (byte) 7;
private static final byte ONLINE_TYPE_11 = (byte) 5;
/** 区域运营:业务 1/3 → 2.1区域运营(type=9),业务 2 → 1.1区域运营(type=8) */
private static final byte REGIONAL_TYPE_21 = (byte) 9;
private static final byte REGIONAL_TYPE_11 = (byte) 8;
/** 飞行督导:业务 1/3 → 2.1飞行督导(type=13),业务 2 → 1.1飞行督导(type=6) */
private static final byte FLIGHT_TYPE_21 = (byte) 13;
private static final byte FLIGHT_TYPE_11 = (byte) 6;
@Resource
private MerchantRemote merchantRemote;
@Resource
private ShopMerchantDirectorConfigMapper shopMerchantDirectorConfigMapper;
@Resource
private PgGroupStoreRelMapper pgGroupStoreRelMapper;
@Resource
private StrategyInfoMapper strategyInfoMapper;
/**
* 根据筛选条件计算门店交集。
*
* @param dto 筛选条件
* @return 门店ID交集列表;所有筛选条件为空时返回空列表
*/
public List<Integer> getIntersectionMerchantIds(MerchantFilterDTO dto) {
// 无任何筛选条件,返回空列表
if (isEmptyFilter(dto)) {
return Collections.emptyList();
}
Set<Integer> brandMerchantIds = resolveBrandMerchantIds(dto);
Set<Integer> regMerchantIds = resolveRegionMerchantIds(dto);
Set<Integer> onlineMerchantIds = resolveOnlineOperatorMerchantIds(dto);
Set<Integer> regionalMerchantIds = resolveRegionalOperatorMerchantIds(dto);
Set<Integer> flyingSupervisorMerchantIds = resolveFlyingSupervisorMerchantIds(dto);
Set<Integer> storeNameMerchantIds = resolveStoreNameMerchantIds(dto);
Set<Integer> groupMerchantIds = resolveGroupMerchantIds(dto);
Set<Integer> strategySentMerchantIds = resolveStrategySentMerchantIds(dto);
// 取交集
log.info("门店筛选交集:brand={}, region={}, regionalOpr={}, onlineOpr={}, flyingSupervisor={}, storeName={}, group={}, strategySent={}",
brandMerchantIds.size(), regMerchantIds.size(),
regionalMerchantIds.size(), onlineMerchantIds.size(),
flyingSupervisorMerchantIds.size(), storeNameMerchantIds.size(),
groupMerchantIds.size(), strategySentMerchantIds.size());
List<Set<Integer>> collections = Stream.of(
brandMerchantIds, regMerchantIds, regionalMerchantIds,
onlineMerchantIds, flyingSupervisorMerchantIds,
storeNameMerchantIds, groupMerchantIds, strategySentMerchantIds)
.filter(Objects::nonNull)
.filter(s -> !s.isEmpty())
.collect(Collectors.toList());
if (collections.isEmpty()) {
return Collections.emptyList();
}
if (collections.size() == 1) {
return new ArrayList<>(collections.get(0));
}
Set<Integer> intersection = new LinkedHashSet<>(collections.get(0));
for (int i = 1; i < collections.size(); i++) {
intersection.retainAll(collections.get(i));
if (intersection.isEmpty()) {
return Arrays.asList(-9999);
}
}
return new ArrayList<>(intersection);
}
/**
* 判断是否没有任何筛选条件。
*/
private boolean isEmptyFilter(MerchantFilterDTO dto) {
return dto == null || (dto.getRegionId() == null
&& CollectionUtils.isEmpty(dto.getFirstbrandIds())
&& CollectionUtils.isEmpty(dto.getTwoBrandIds())
&& dto.getOnlineOperatorId() == null
&& dto.getRegionalOperatorId() == null
&& dto.getFlyingSupervisorId() == null
&& dto.getStoreName() == null
&& dto.getGroupId() == null
&& dto.getIsStrategySent() == null);
}
/**
* 品牌筛选 → 门店ID集合(已去重)。
*/
private Set<Integer> resolveBrandMerchantIds(MerchantFilterDTO dto) {
if (CollectionUtils.isEmpty(dto.getFirstbrandIds()) && CollectionUtils.isEmpty(dto.getTwoBrandIds())) {
return Collections.emptySet();
}
CarBrandRequestDTO brandDto = new CarBrandRequestDTO();
brandDto.setFirstBrandIdList(dto.getFirstbrandIds());
brandDto.setSecBrandIdList(dto.getTwoBrandIds());
RpcResponse<List<MerchantSimpleResponse>> rpcResult = merchantRemote.findMerchantListByBrandIds2(brandDto);
if (rpcResult.isSuccess()) {
List<MerchantSimpleResponse> result = rpcResult.getResult();
if (CollectionUtils.isNotEmpty(result)) {
return result.stream()
.map(MerchantSimpleResponse::getMerchantNo)
.collect(Collectors.toCollection(LinkedHashSet::new));
}
return new LinkedHashSet<>(Arrays.asList(-9999));
}
throw new RpcServiceException("查询品牌门店失败");
}
/**
* 区域筛选 → 门店ID集合(已去重)。
*/
private Set<Integer> resolveRegionMerchantIds(MerchantFilterDTO dto) {
if (dto.getRegionId() == null) {
return Collections.emptySet();
}
CarBrandProvinceRequestDTO provinceDto = new CarBrandProvinceRequestDTO();
provinceDto.setProvinceIds(Arrays.asList(dto.getRegionId()));
RpcResponse<List<MerchantProvinceDTO>> rpcResult = merchantRemote.findMerchantListByBrandIdsProvince(provinceDto);
if (rpcResult.isSuccess()) {
List<MerchantProvinceDTO> result = rpcResult.getResult();
if (CollectionUtils.isNotEmpty(result)) {
return result.stream()
.map(MerchantProvinceDTO::getMerchantId)
.collect(Collectors.toCollection(LinkedHashSet::new));
}
return new LinkedHashSet<>(Arrays.asList(-9999));
}
throw new RpcServiceException("查询区域门店失败");
}
/**
* 线上运营人员筛选 → 门店ID集合(已去重)。
*/
private Set<Integer> resolveOnlineOperatorMerchantIds(MerchantFilterDTO dto) {
if (dto.getOnlineOperatorId() == null) {
return Collections.emptySet();
}
byte typeValue = (dto.getBusinessType() != null && dto.getBusinessType() == 2)
? ONLINE_TYPE_11 : ONLINE_TYPE_21;
List<Integer> ids = shopMerchantDirectorConfigMapper.findMerchantIdsByUUidAndType(
dto.getOnlineOperatorId(), typeValue);
if (CollectionUtils.isEmpty(ids)) {
return new LinkedHashSet<>(Arrays.asList(-9999));
}
return new LinkedHashSet<>(ids);
}
/**
* 区域运营人员筛选 → 门店ID集合(已去重)。
*/
private Set<Integer> resolveRegionalOperatorMerchantIds(MerchantFilterDTO dto) {
if (dto.getRegionalOperatorId() == null) {
return Collections.emptySet();
}
byte typeValue = (dto.getBusinessType() != null && dto.getBusinessType() == 2)
? REGIONAL_TYPE_11 : REGIONAL_TYPE_21;
List<Integer> ids = shopMerchantDirectorConfigMapper.findMerchantIdsByUUidAndType(
dto.getRegionalOperatorId(), typeValue);
if (CollectionUtils.isEmpty(ids)) {
return new LinkedHashSet<>(Arrays.asList(-9999));
}
return new LinkedHashSet<>(ids);
}
/**
* 飞行督导人员筛选 → 门店ID集合(已去重)。
*/
private Set<Integer> resolveFlyingSupervisorMerchantIds(MerchantFilterDTO dto) {
if (dto.getFlyingSupervisorId() == null) {
return Collections.emptySet();
}
byte typeValue = (dto.getBusinessType() != null && dto.getBusinessType() == 2)
? FLIGHT_TYPE_11 : FLIGHT_TYPE_21;
List<Integer> ids = shopMerchantDirectorConfigMapper.findMerchantIdsByUUidAndType(
dto.getFlyingSupervisorId(), typeValue);
if (CollectionUtils.isEmpty(ids)) {
return new LinkedHashSet<>(Arrays.asList(-9999));
}
return new LinkedHashSet<>(ids);
}
/**
* 门店名称模糊搜索 → 门店ID集合(已去重)。
*/
private Set<Integer> resolveStoreNameMerchantIds(MerchantFilterDTO dto) {
if (dto.getStoreName() == null || dto.getStoreName().isEmpty()) {
return Collections.emptySet();
}
MerchantOpenRequest openReq = new MerchantOpenRequest();
openReq.setMerchantName(dto.getStoreName());
RpcResponse<List<MerchantResponse>> rpcResult = merchantRemote.findMerchantListRemote(openReq);
if (rpcResult.isSuccess()) {
List<MerchantResponse> result = rpcResult.getResult();
if (CollectionUtils.isNotEmpty(result)) {
return result.stream()
.map(MerchantResponse::getMerchantNo)
.collect(Collectors.toCollection(LinkedHashSet::new));
}
return new LinkedHashSet<>(Arrays.asList(-9999));
}
throw new RpcServiceException("查询门店名称门店失败");
}
/**
* 项目组筛选 → 门店ID集合(已去重)。
*/
private Set<Integer> resolveGroupMerchantIds(MerchantFilterDTO dto) {
if (dto.getGroupId() == null) {
return Collections.emptySet();
}
List<Integer> ids = pgGroupStoreRelMapper.listMerchantIdsByGroupId(dto.getGroupId());
if (CollectionUtils.isEmpty(ids)) {
return new LinkedHashSet<>(Arrays.asList(-9999));
}
return new LinkedHashSet<>(ids);
}
/**
* 策略下发筛选 → 门店ID集合(已去重)。
* isStrategySent=1 时返回有策略记录的门店,=0 时暂无需求直接返回空。
*/
private Set<Integer> resolveStrategySentMerchantIds(MerchantFilterDTO dto) {
if (dto.getIsStrategySent() == null || dto.getIsStrategySent() != 1) {
return Collections.emptySet();
}
List<Integer> ids = strategyInfoMapper.listMerchantIdsWithStrategy(
dto.getBusinessType(), null, dto.getStartDate(), dto.getEndDate());
if (CollectionUtils.isEmpty(ids)) {
return new LinkedHashSet<>(Arrays.asList(-9999));
}
return new LinkedHashSet<>(ids);
}
}
package cn.com.glsx.dj.strategy.service.warning;
import cn.com.glsx.dj.strategy.dto.warning.PeriodRange;
import cn.com.glsx.dj.strategy.enums.BiAggregationTypeEnum;
import cn.com.glsx.dj.strategy.enums.BiDateTypeEnum;
import cn.com.glsx.dj.strategy.enums.BiMetricCodeEnum;
import cn.com.glsx.dj.strategy.enums.ProjectGroupBizEnum;
import cn.com.glsx.dj.strategy.enums.TimeDimensionEnum;
import cn.com.glsx.dj.strategy.mapper.PgStoreOutputMapper;
import cn.com.glsx.dj.strategy.model.projectgroup.PgStoreOutput;
import cn.hutool.core.date.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;
/**
* 有产值门店服务——计算有产值门店 + 读写 pg_store_output。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/28 14:00
*/
@Slf4j
@Service
public class StoreOutputService {
@Resource
private PgStoreOutputMapper storeOutputMapper;
@Resource
private BiMetricQueryService biMetricQueryService;
/**
* 计算指定周期+业务的有产值门店,写入 pg_store_output(幂等:先删后插)。
*
* @param biz 业务类型
* @param timeDimension 时间维度
* @param range 周期起止
*/
public void computeStoreOutputs(Integer biz, String timeDimension, PeriodRange range) {
String periodStart = DateUtil.format(range.getStart(), "yyyy-MM-dd");
String periodEnd = DateUtil.format(range.getEnd(), "yyyy-MM-dd");
// 查询BI有产值门店
BiMetricQueryService.QueryParams params = new BiMetricQueryService.QueryParams();
params.setBizs(biz);
params.setItemCodes(BiMetricCodeEnum.OUTPUT_VALUE.getCode());
params.setDateType(BiDateTypeEnum.ALL.getValue());
params.setExts(BiAggregationTypeEnum.MERCHANT.getValue());
params.setStartDate(periodStart);
params.setEndDate(periodEnd);
List<BiMetricQueryService.ItemDetail> items;
try {
items = biMetricQueryService.getItemDetail(params, "data/");
} catch (Exception e) {
log.error("查询有产值门店失败,biz={}, timeDimension={}", biz, timeDimension, e);
return;
}
if (CollectionUtils.isEmpty(items)) {
log.info("无有产值门店,biz={}, timeDimension={}", biz, timeDimension);
return;
}
// 幂等删除旧记录
storeOutputMapper.deleteByCondition(biz, timeDimension, periodStart, periodEnd);
// 构造 PgStoreOutput 列表
List<PgStoreOutput> outputs = new ArrayList<>();
for (BiMetricQueryService.ItemDetail item : items) {
if (item.getMerchantId() == null) {
continue;
}
PgStoreOutput output = new PgStoreOutput();
output.setBusinessType(biz);
output.setStoreId(Integer.valueOf(item.getMerchantId()));
output.setStoreName(item.getMerchantName());
output.setTimeDimension(timeDimension);
output.setPeriodStart(range.getStart());
output.setPeriodEnd(range.getEnd());
output.setDeletedFlag("N");
output.setCreatedDate(new Date());
output.setUpdatedDate(new Date());
outputs.add(output);
}
if (CollectionUtils.isNotEmpty(outputs)) {
storeOutputMapper.batchInsert(outputs);
log.info("有产值门店写入完成,biz={}, timeDimension={}, 门店数={}", biz, timeDimension, outputs.size());
}
}
/**
* 查询当前周期+业务的有产值门店号列表。
*
* @param businessType 业务类型
* @param timeDimension 时间维度
* @param periodStart 周期开始
* @param periodEnd 周期结束
* @return 门店号列表
*/
public List<Integer> listStoreIdsWithOutput(Integer businessType, String timeDimension,
String periodStart, String periodEnd) {
List<PgStoreOutput> list = listStoreOutputs(businessType, timeDimension, periodStart, periodEnd);
if (CollectionUtils.isEmpty(list)) {
return new ArrayList<>();
}
return list.stream().map(PgStoreOutput::getStoreId).collect(Collectors.toList());
}
/**
* 查询当前周期+业务的有产值门店完整记录。
*
* @param businessType 业务类型
* @param timeDimension 时间维度
* @param periodStart 周期开始
* @param periodEnd 周期结束
* @return 有产值门店记录列表
*/
public List<PgStoreOutput> listStoreOutputs(Integer businessType, String timeDimension,
String periodStart, String periodEnd) {
return storeOutputMapper.selectByCondition(businessType, timeDimension, periodStart, periodEnd);
}
/**
* 对有产值门店批量执行(四种维度 × 三种业务)。
*
* @param date 参考日期
*/
public void computeAll(Date date) {
for (TimeDimensionEnum dim : TimeDimensionEnum.values()) {
PeriodRange range = dim.calculate(date);
for (ProjectGroupBizEnum biz : ProjectGroupBizEnum.values()) {
try {
computeStoreOutputs(biz.getBiz(), dim.getCode(), range);
} catch (Exception e) {
log.error("有产值门店计算失败,biz={}, dim={}", biz.getBiz(), dim.getCode(), e);
}
}
}
}
}
package cn.com.glsx.dj.strategy.service.warning;
import cn.com.glsx.dj.strategy.dto.warning.ConditionDTO;
import cn.com.glsx.dj.strategy.dto.warning.ThresholdValue;
import cn.com.glsx.dj.strategy.enums.BiAggregationTypeEnum;
import cn.com.glsx.dj.strategy.enums.BiDateTypeEnum;
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.PgWarningRecordMapper;
import cn.com.glsx.dj.strategy.model.projectgroup.PgWarningConfig;
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;
import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* 预警规则引擎核心服务。
*
* <p>负责 rule_json 解析、BI 批量取指标、逐门店/逐员工条件评估、AND/OR 组合、生成预警记录。</p>
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/28 14:00
*/
@Slf4j
@Service
public class WarningEngineService {
@Resource
private PgWarningConfigMapper configMapper;
@Resource
private PgWarningRecordMapper recordMapper;
@Resource
private PgGroupStoreRelMapper storeRelMapper;
@Resource
private BiMetricQueryService biMetricQueryService;
@Resource
private EcoCoefficientQueryService ecoCoefficientQueryService;
@Resource
private ThresholdStrategyFactory thresholdFactory;
/**
* 对指定周期的所有项目组执行预警计算。
*
* @param timeDimension 时间维度
* @param periodStart 周期开始
* @param periodEnd 周期结束
* @param biz 业务类型
* @param storeIds 有产值门店列表
*/
public void computeWarnings(String timeDimension, Date periodStart, Date periodEnd,
Integer biz, List<Integer> storeIds) {
List<PgWarningConfig> configs = configMapper.selectAllEnabled();
if (CollectionUtils.isEmpty(configs)) {
return;
}
for (PgWarningConfig config : configs) {
if (!biz.equals(config.getBiz())) {
continue;
}
try {
List<PgWarningRecord> records = evaluateConfig(config, storeIds,
periodStart, periodEnd, timeDimension);
if (CollectionUtils.isNotEmpty(records)) {
recordMapper.deleteByCondition(config.getId(), timeDimension,
DateUtil.format(periodStart, "yyyy-MM-dd"),
DateUtil.format(periodEnd, "yyyy-MM-dd"));
recordMapper.batchInsert(records);
log.info("预警计算完成,configId={}, 记录数={}", config.getId(), records.size());
}
} catch (Exception e) {
log.error("预警计算失败,configId={}", config.getId(), e);
}
}
}
/**
* 对一条配置评估所有门店/员工,返回触发的预警记录。
*/
public List<PgWarningRecord> evaluateConfig(PgWarningConfig config, List<Integer> storeIds,
Date periodStart, Date periodEnd, String timeDimension) {
List<ConditionDTO> conditions = parseRuleJson(config.getRuleJson());
if (CollectionUtils.isEmpty(conditions)) {
return new ArrayList<>();
}
boolean isStoreTarget = config.getMonitorTarget() != null && config.getMonitorTarget() == 2;
// 批量预加载动态SQL阈值
Map<Integer, ThresholdValue> preloadedThresholds = new LinkedHashMap<>();
for (ConditionDTO cond : conditions) {
if (cond.getThreshold() != null && cond.getThreshold().getType() != null
&& cond.getThreshold().getType() == ThresholdTypeEnum.DYNAMIC_SQL.getType()) {
preloadedThresholds.putAll(thresholdFactory.batchResolve(conditions));
break;
}
}
// 批量获取BI指标值
Map<String, BiMetricQueryService.ItemDetail> metricValues = fetchMetricValues(
conditions, storeIds, periodStart, periodEnd, isStoreTarget);
if (isStoreTarget) {
return evaluateStoreDimension(config, storeIds, periodStart, periodEnd,
timeDimension, conditions, metricValues, preloadedThresholds);
} else {
return evaluateStaffDimension(config, periodStart, periodEnd,
timeDimension, conditions, metricValues, preloadedThresholds);
}
}
/**
* 门店维度评估——逐门店判断条件。
*/
private List<PgWarningRecord> evaluateStoreDimension(PgWarningConfig config, List<Integer> storeIds,
Date periodStart, Date periodEnd, String timeDimension,
List<ConditionDTO> conditions,
Map<String, BiMetricQueryService.ItemDetail> metricValues,
Map<Integer, ThresholdValue> preloadedThresholds) {
List<PgWarningRecord> records = new ArrayList<>();
for (Integer storeId : storeIds) {
Map<Integer, Boolean> conditionResults = new LinkedHashMap<>();
for (ConditionDTO cond : conditions) {
BigDecimal value = getStoreValueFromResult(metricValues, storeId);
WarningOperatorEnum operator = WarningOperatorEnum.fromSymbol(cond.getOperator());
ThresholdValue threshold = resolveThresholdForCond(cond, preloadedThresholds);
boolean met = operator.evaluate(value,
threshold != null ? threshold.getValue() : null,
threshold != null ? threshold.getMin() : null,
threshold != null ? threshold.getMax() : null);
conditionResults.put(cond.getSeq(), met);
}
if (evaluateLogic(conditions, conditionResults)) {
PgWarningRecord record = buildStoreRecord(config, storeId, periodStart, periodEnd,
timeDimension, conditions, conditionResults, metricValues);
if (record != null) {
records.add(record);
}
}
}
return records;
}
/**
* 员工维度评估——从BI结果中提取员工列表,逐员工判断条件。
*/
private List<PgWarningRecord> evaluateStaffDimension(PgWarningConfig config,
Date periodStart, Date periodEnd, String timeDimension,
List<ConditionDTO> conditions,
Map<String, BiMetricQueryService.ItemDetail> metricValues,
Map<Integer, ThresholdValue> preloadedThresholds) {
// 从BI结果中提取员工-门店去重对
Set<String> staffStorePairs = new LinkedHashSet<>();
Map<String, BiMetricQueryService.ItemDetail> staffDetailMap = new LinkedHashMap<>();
for (BiMetricQueryService.ItemDetail item : metricValues.values()) {
if (item.getStaffId() == null) {
continue;
}
String key = item.getMerchantId() + "_" + item.getStaffId();
staffStorePairs.add(key);
staffDetailMap.putIfAbsent(key, item);
}
if (staffStorePairs.isEmpty()) {
return new ArrayList<>();
}
List<PgWarningRecord> records = new ArrayList<>();
for (String pairKey : staffStorePairs) {
BiMetricQueryService.ItemDetail staffItem = staffDetailMap.get(pairKey);
if (staffItem == null) {
continue;
}
String storeIdStr = staffItem.getMerchantId();
String staffId = staffItem.getStaffId();
Map<Integer, Boolean> conditionResults = new LinkedHashMap<>();
for (ConditionDTO cond : conditions) {
BigDecimal value = getStaffValueFromResult(metricValues, storeIdStr, staffId);
WarningOperatorEnum operator = WarningOperatorEnum.fromSymbol(cond.getOperator());
ThresholdValue threshold = resolveThresholdForCond(cond, preloadedThresholds);
boolean met = operator.evaluate(value,
threshold != null ? threshold.getValue() : null,
threshold != null ? threshold.getMin() : null,
threshold != null ? threshold.getMax() : null);
conditionResults.put(cond.getSeq(), met);
}
if (evaluateLogic(conditions, conditionResults)) {
PgWarningRecord record = buildStaffRecord(config, storeIdStr, staffId, staffItem,
periodStart, periodEnd, timeDimension, conditions, conditionResults, metricValues);
if (record != null) {
records.add(record);
}
}
}
return records;
}
/**
* 解析 ruleJson → List<ConditionDTO>。
*/
public List<ConditionDTO> parseRuleJson(String ruleJson) {
if (ruleJson == null || ruleJson.trim().isEmpty()) {
return new ArrayList<>();
}
return JSON.parseArray(ruleJson, ConditionDTO.class);
}
/**
* AND/OR 组合逻辑:遇到OR分割AND组,组内AND,组间OR。
*/
boolean evaluateLogic(List<ConditionDTO> conditions, Map<Integer, Boolean> results) {
List<List<ConditionDTO>> andGroups = new ArrayList<>();
List<ConditionDTO> current = new ArrayList<>();
for (ConditionDTO cond : conditions) {
current.add(cond);
if ("OR".equals(cond.getNextLogic())) {
andGroups.add(current);
current = new ArrayList<>();
}
}
if (!current.isEmpty()) {
andGroups.add(current);
}
return andGroups.stream()
.map(g -> g.stream().allMatch(c -> results.getOrDefault(c.getSeq(), false)))
.reduce(false, (a, b) -> a || b);
}
/**
* 批量获取BI指标值。
*/
private Map<String, BiMetricQueryService.ItemDetail> fetchMetricValues(
List<ConditionDTO> conditions, List<Integer> storeIds,
Date periodStart, Date periodEnd, boolean isStoreTarget) {
Map<String, BiMetricQueryService.ItemDetail> result = new LinkedHashMap<>();
String merchantIds = storeIds.stream().map(String::valueOf)
.reduce((a, b) -> a + "," + b).orElse("");
// 门店维度按merchantIds聚合,员工维度按staffIds聚合
String exts = isStoreTarget ? BiAggregationTypeEnum.MERCHANT.getValue() : BiAggregationTypeEnum.STAFF.getValue();
for (ConditionDTO cond : conditions) {
String itemCode = isStoreTarget
? cond.getMetric().getStoreCode()
: cond.getMetric().getStaffCode();
if (itemCode == null) {
continue;
}
try {
BiMetricQueryService.QueryParams params = new BiMetricQueryService.QueryParams();
params.setItemCodes(itemCode);
params.setMerchantIds(merchantIds);
params.setStartDate(DateUtil.format(periodStart, "yyyy-MM-dd"));
params.setEndDate(DateUtil.format(periodEnd, "yyyy-MM-dd"));
params.setDateType(BiDateTypeEnum.ALL.getValue());
params.setExts(exts);
List<BiMetricQueryService.ItemDetail> items = biMetricQueryService.getItemDetail(params, BiMetricQueryService.DATE_METHOD);
for (BiMetricQueryService.ItemDetail item : items) {
result.put(buildItemKey(item), item);
}
} catch (Exception e) {
log.error("BI指标查询失败,itemCode={}", itemCode, e);
}
}
return result;
}
/**
* 门店维度:按storeId从结果中取值。
*/
private BigDecimal getStoreValueFromResult(Map<String, BiMetricQueryService.ItemDetail> metricValues,
Integer storeId) {
for (BiMetricQueryService.ItemDetail item : metricValues.values()) {
if (item.getMerchantId() != null && item.getMerchantId().equals(String.valueOf(storeId))) {
return item.getItemValue();
}
}
return null;
}
/**
* 员工维度:按storeId + staffId从结果中取值。
*/
private BigDecimal getStaffValueFromResult(Map<String, BiMetricQueryService.ItemDetail> metricValues,
String storeIdStr, String staffId) {
for (BiMetricQueryService.ItemDetail item : metricValues.values()) {
if (item.getMerchantId() != null && item.getMerchantId().equals(storeIdStr)
&& item.getStaffId() != null && item.getStaffId().equals(staffId)) {
return item.getItemValue();
}
}
return null;
}
private String buildItemKey(BiMetricQueryService.ItemDetail item) {
return (item.getMerchantId() != null ? item.getMerchantId() : "")
+ "_" + (item.getStaffId() != null ? item.getStaffId() : "")
+ "_" + (item.getItemCode() != null ? item.getItemCode() : "");
}
/**
* 解析阈值(优先预加载,其次按策略解析)。
*/
private ThresholdValue resolveThresholdForCond(ConditionDTO cond,
Map<Integer, ThresholdValue> preloadedThresholds) {
if (cond.getThreshold() != null && cond.getThreshold().getType() != null
&& cond.getThreshold().getType() == ThresholdTypeEnum.DYNAMIC_SQL.getType()) {
return preloadedThresholds.get(cond.getSeq());
}
ThresholdTypeEnum type = cond.getThreshold() != null
? ThresholdTypeEnum.fromType(cond.getThreshold().getType())
: ThresholdTypeEnum.FIXED;
ThresholdStrategy strategy = thresholdFactory.getStrategy(type);
return strategy.resolve(cond);
}
// ==================== 门店维度记录构建 ====================
private PgWarningRecord buildStoreRecord(PgWarningConfig config, Integer storeId,
Date periodStart, Date periodEnd, String timeDimension,
List<ConditionDTO> conditions, Map<Integer, Boolean> results,
Map<String, BiMetricQueryService.ItemDetail> metricValues) {
ConditionDTO triggeredCond = findTriggeredCondition(conditions, results);
if (triggeredCond == null) {
return null;
}
BiMetricQueryService.ItemDetail triggeredItem = findStoreItem(metricValues, storeId);
BigDecimal triggeredValue = triggeredItem != null ? triggeredItem.getItemValue() : null;
PgWarningRecord record = buildBaseRecord(config, periodStart, periodEnd, timeDimension);
record.setMonitorTarget(2);
record.setStoreId(storeId);
if (triggeredItem != null) {
record.setStoreName(triggeredItem.getMerchantName());
}
fillMetricAndThreshold(record, triggeredCond, triggeredValue, true);
fillEcoAndText(record, triggeredCond, triggeredValue, true);
return record;
}
// ==================== 员工维度记录构建 ====================
private PgWarningRecord buildStaffRecord(PgWarningConfig config,
String storeIdStr, String staffId,
BiMetricQueryService.ItemDetail staffItem,
Date periodStart, Date periodEnd, String timeDimension,
List<ConditionDTO> conditions, Map<Integer, Boolean> results,
Map<String, BiMetricQueryService.ItemDetail> metricValues) {
ConditionDTO triggeredCond = findTriggeredCondition(conditions, results);
if (triggeredCond == null) {
return null;
}
BigDecimal triggeredValue = getStaffValueFromResult(metricValues, storeIdStr, staffId);
PgWarningRecord record = buildBaseRecord(config, periodStart, periodEnd, timeDimension);
record.setMonitorTarget(1);
record.setStoreId(Integer.valueOf(storeIdStr));
record.setStoreName(staffItem.getMerchantName());
record.setStaffId(staffId);
record.setStaffName(staffItem.getStaffName());
record.setStaffPhone(staffItem.getStaffPhone());
fillMetricAndThreshold(record, triggeredCond, triggeredValue, false);
fillEcoAndText(record, triggeredCond, triggeredValue, false);
return record;
}
// ==================== 共用构建方法 ====================
private PgWarningRecord buildBaseRecord(PgWarningConfig config,
Date periodStart, Date periodEnd, String timeDimension) {
PgWarningRecord record = new PgWarningRecord();
record.setGroupId(config.getGroupId());
record.setConfigId(config.getId());
record.setWarningType(config.getWarningType());
record.setBusinessType(config.getBiz());
record.setTimeDimension(timeDimension);
record.setPeriodStart(periodStart);
record.setPeriodEnd(periodEnd);
record.setIsStrategySent(0);
record.setStatus(1);
record.setCreatedTime(new Date());
record.setDeletedFlag("N");
return record;
}
private ConditionDTO findTriggeredCondition(List<ConditionDTO> conditions, Map<Integer, Boolean> results) {
for (ConditionDTO cond : conditions) {
if (Boolean.TRUE.equals(results.get(cond.getSeq()))) {
return cond;
}
}
return null;
}
private BiMetricQueryService.ItemDetail findStoreItem(
Map<String, BiMetricQueryService.ItemDetail> metricValues, Integer storeId) {
for (BiMetricQueryService.ItemDetail item : metricValues.values()) {
if (item.getMerchantId() != null && item.getMerchantId().equals(String.valueOf(storeId))) {
return item;
}
}
return null;
}
private void fillMetricAndThreshold(PgWarningRecord record, ConditionDTO triggeredCond,
BigDecimal triggeredValue, boolean isStoreTarget) {
if (triggeredCond.getMetric() != null) {
record.setMetricCode(isStoreTarget
? triggeredCond.getMetric().getStoreCode()
: triggeredCond.getMetric().getStaffCode());
record.setMetricName(triggeredCond.getMetric().getName());
}
record.setMetricValue(triggeredValue);
record.setMetricDisplay(triggeredValue);
record.setThresholdType(triggeredCond.getThreshold() != null ? triggeredCond.getThreshold().getType() : null);
ThresholdValue threshold = resolveThreshold(triggeredCond);
if (threshold != null) {
record.setThresholdDisplay(threshold.getDisplay());
record.setThresholdMinDisplay(threshold.getMinDisplay());
record.setThresholdMaxDisplay(threshold.getMaxDisplay());
}
}
private void fillEcoAndText(PgWarningRecord record, ConditionDTO triggeredCond,
BigDecimal triggeredValue, boolean isStoreTarget) {
if (triggeredCond.getMetric() != null && triggeredValue != null) {
String metricCode = isStoreTarget
? triggeredCond.getMetric().getStoreCode()
: triggeredCond.getMetric().getStaffCode();
BigDecimal eco = ecoCoefficientQueryService.getCoefficient(metricCode, triggeredValue);
record.setEcoCoefficient(eco);
}
record.setOperator(triggeredCond.getOperator());
WarningOperatorEnum operator = WarningOperatorEnum.fromSymbol(triggeredCond.getOperator());
ThresholdValue threshold = resolveThreshold(triggeredCond);
record.setWarningText(operator.buildWarningText(
triggeredCond.getMetric() != null ? triggeredCond.getMetric().getName() : "",
record.getMetricDisplay(),
threshold != null ? threshold.getDisplay() : null,
threshold != null ? threshold.getMinDisplay() : null,
threshold != null ? threshold.getMaxDisplay() : null));
}
private ThresholdValue resolveThreshold(ConditionDTO cond) {
if (cond.getThreshold() == null || cond.getThreshold().getType() == null) {
return null;
}
try {
ThresholdTypeEnum type = ThresholdTypeEnum.fromType(cond.getThreshold().getType());
ThresholdStrategy strategy = thresholdFactory.getStrategy(type);
return strategy.resolve(cond);
} catch (Exception e) {
log.warn("阈值解析失败", e);
return null;
}
}
}
package cn.com.glsx.dj.strategy.service.warning;
import cn.com.glsx.dj.strategy.dto.projectgroup.ProjectGroupWarningRecordDTO;
import cn.com.glsx.dj.strategy.dto.projectgroup.ProjectGroupWarningRecordQueryDTO;
import cn.com.glsx.dj.strategy.dto.warning.StoreWarningSummaryDTO;
import cn.com.glsx.dj.strategy.dto.warning.WarningRecordDTO;
import cn.com.glsx.dj.strategy.dto.warning.WarningRecordQueryRequest;
import cn.com.glsx.dj.strategy.mapper.PgWarningRecordMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
/**
* 预警记录查询服务——动态查询 + 门店汇总。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/28 14:00
*/
@Slf4j
@Service
public class WarningRecordService {
@Resource
private PgWarningRecordMapper recordMapper;
/**
* 按条件动态查询预警记录。
*
* @param request 查询条件
* @param merchantIds 门店交集筛选(可为空)
* @return 预警记录列表
*/
public List<WarningRecordDTO> queryRecords(WarningRecordQueryRequest request, List<Integer> merchantIds) {
ProjectGroupWarningRecordQueryDTO queryDTO = buildQueryDTO(request);
if (CollectionUtils.isNotEmpty(merchantIds)) {
queryDTO.setMerchantIds(merchantIds);
}
List<ProjectGroupWarningRecordDTO> list = recordMapper.listWarningRecordsByCondition(queryDTO);
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());
}
/**
* 按门店汇总预警——返回门店预警卡片列表。
*
* @param request 查询条件
* @param merchantIds 限定门店列表
* @return 门店预警汇总列表
*/
public List<StoreWarningSummaryDTO> queryStoreSummary(WarningRecordQueryRequest request,
List<Integer> merchantIds) {
ProjectGroupWarningRecordQueryDTO queryDTO = buildQueryDTO(request);
if (CollectionUtils.isNotEmpty(merchantIds)) {
queryDTO.setMerchantIds(merchantIds);
}
List<ProjectGroupWarningRecordDTO> records = recordMapper.listWarningRecordsByCondition(queryDTO);
if (records == null || records.isEmpty()) {
return new ArrayList<>();
}
// 按 merchantId 分组
Map<Integer, List<ProjectGroupWarningRecordDTO>> grouped = records.stream()
.filter(r -> r.getMerchantId() != null)
.collect(Collectors.groupingBy(ProjectGroupWarningRecordDTO::getMerchantId));
List<StoreWarningSummaryDTO> result = new ArrayList<>();
for (Map.Entry<Integer, List<ProjectGroupWarningRecordDTO>> entry : grouped.entrySet()) {
StoreWarningSummaryDTO summary = new StoreWarningSummaryDTO();
summary.setMerchantNo(String.valueOf(entry.getKey()));
List<ProjectGroupWarningRecordDTO> storeRecords = entry.getValue();
if (!storeRecords.isEmpty()) {
ProjectGroupWarningRecordDTO first = storeRecords.get(0);
summary.setStoreName(first.getMerchantName());
}
summary.setWarningTotalCount(storeRecords.size());
// 预警摘要:取前2条 warningTypeName
List<String> warnSummary = storeRecords.stream()
.limit(2)
.map(ProjectGroupWarningRecordDTO::getWarningTypeName)
.collect(Collectors.toList());
summary.setWarningSummary(warnSummary);
result.add(summary);
}
return result;
}
private ProjectGroupWarningRecordQueryDTO buildQueryDTO(WarningRecordQueryRequest request) {
ProjectGroupWarningRecordQueryDTO dto = new ProjectGroupWarningRecordQueryDTO();
dto.setProjectGroupId(request.getGroupId());
dto.setBusinessType(request.getBusinessType());
dto.setWarningType(request.getWarningType());
dto.setTimeDimension(request.getTimeDimension());
dto.setPeriodStart(request.getStartDate());
dto.setPeriodEnd(request.getEndDate());
dto.setMonitorTarget(request.getMonitorTarget());
dto.setStoreId(request.getStoreId());
dto.setStaffId(request.getStaffId());
dto.setStoreName(request.getStoreName());
dto.setIsStrategySent(request.getIsStrategySent());
return dto;
}
}
package cn.com.glsx.dj.strategy.service.warning.threshold;
import cn.com.glsx.dj.strategy.dto.warning.ConditionDTO;
import cn.com.glsx.dj.strategy.dto.warning.ThresholdDTO;
import cn.com.glsx.dj.strategy.dto.warning.ThresholdValue;
import cn.com.glsx.dj.strategy.enums.ThresholdTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
/**
* 动态SQL阈值策略——批量执行SQL,按 merchantNo 分组返回阈值。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/28 14:00
*/
@Slf4j
@Component
public class DynamicSqlThresholdStrategy implements ThresholdStrategy {
@Resource
private JdbcTemplate jdbcTemplate;
@Override
public ThresholdTypeEnum supportedType() {
return ThresholdTypeEnum.DYNAMIC_SQL;
}
@Override
public ThresholdValue resolve(ConditionDTO condition) {
throw new UnsupportedOperationException("动态SQL阈值请使用 batchResolve() 批量预加载");
}
@Override
public Map<Integer, ThresholdValue> batchResolve(List<ConditionDTO> conditions) {
Map<Integer, ThresholdValue> result = new LinkedHashMap<>();
for (ConditionDTO cond : conditions) {
ThresholdDTO t = cond.getThreshold();
if (t == null || t.getType() == null || t.getType() != ThresholdTypeEnum.DYNAMIC_SQL.getType()) {
continue;
}
try {
String sql = t.getValue();
if (sql == null || sql.trim().isEmpty()) {
continue;
}
// 动态SQL只允许SELECT
String upperSql = sql.trim().toUpperCase();
if (!upperSql.startsWith("SELECT")) {
log.warn("动态SQL不是SELECT语句,跳过: {}", sql);
continue;
}
List<Map<String, Object>> rows = jdbcTemplate.queryForList(sql);
// 按条件序号保存,后续使用时按 merchantNo 匹配
ThresholdValue tv = buildThresholdValue(t, rows);
result.put(cond.getSeq(), tv);
} catch (Exception e) {
log.error("动态SQL阈值预加载失败,seq={}", cond.getSeq(), e);
}
}
return result;
}
private ThresholdValue buildThresholdValue(ThresholdDTO t, List<Map<String, Object>> rows) {
if (rows.isEmpty()) {
return ThresholdValue.single(null, null);
}
Map<String, Object> firstRow = rows.get(0);
String minField = t.getMinField();
String maxField = t.getMaxField();
if (minField != null || maxField != null) {
BigDecimal min = toBigDecimal(firstRow.get(minField));
BigDecimal max = toBigDecimal(firstRow.get(maxField));
return ThresholdValue.range(min, max, min, max);
}
// 取第一个数值字段作为单值阈值
for (Object val : firstRow.values()) {
if (val instanceof Number) {
BigDecimal v = new BigDecimal(val.toString());
return ThresholdValue.single(v, v);
}
}
return ThresholdValue.single(null, null);
}
private BigDecimal toBigDecimal(Object obj) {
if (obj == null) {
return null;
}
return new BigDecimal(obj.toString());
}
}
package cn.com.glsx.dj.strategy.service.warning.threshold;
import cn.com.glsx.dj.strategy.dto.warning.ConditionDTO;
import cn.com.glsx.dj.strategy.dto.warning.ThresholdDTO;
import cn.com.glsx.dj.strategy.dto.warning.ThresholdValue;
import cn.com.glsx.dj.strategy.enums.ThresholdTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.math.BigDecimal;
/**
* 固定值阈值策略——直接读取 threshold.value / min / max。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/28 14:00
*/
@Slf4j
@Component
public class FixedThresholdStrategy implements ThresholdStrategy {
@Override
public ThresholdTypeEnum supportedType() {
return ThresholdTypeEnum.FIXED;
}
@Override
public ThresholdValue resolve(ConditionDTO condition) {
ThresholdDTO t = condition.getThreshold();
BigDecimal value = toBigDecimal(t.getValue());
BigDecimal min = toBigDecimal(t.getMin());
BigDecimal max = toBigDecimal(t.getMax());
if (min != null || max != null) {
return ThresholdValue.range(min, max, min, max);
}
return ThresholdValue.single(value, value);
}
private BigDecimal toBigDecimal(String str) {
if (str == null || str.trim().isEmpty()) {
return null;
}
return new BigDecimal(str.trim());
}
}
package cn.com.glsx.dj.strategy.service.warning.threshold;
import cn.com.glsx.dj.strategy.dto.warning.ConditionDTO;
import cn.com.glsx.dj.strategy.dto.warning.ThresholdDTO;
import cn.com.glsx.dj.strategy.dto.warning.ThresholdValue;
import cn.com.glsx.dj.strategy.enums.BiDateTypeEnum;
import cn.com.glsx.dj.strategy.enums.ThresholdTypeEnum;
import cn.com.glsx.dj.strategy.service.warning.BiMetricQueryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;
import java.math.BigDecimal;
/**
* 引用指标阈值策略——调用 BI 获取引用指标值作为阈值。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/28 14:00
*/
@Slf4j
@Component
public class ReferenceMetricThresholdStrategy implements ThresholdStrategy {
@Resource
private BiMetricQueryService biMetricQueryService;
@Override
public ThresholdTypeEnum supportedType() {
return ThresholdTypeEnum.REFERENCE_METRIC;
}
@Override
public ThresholdValue resolve(ConditionDTO condition) {
ThresholdDTO t = condition.getThreshold();
if (t == null || t.getValue() == null) {
return ThresholdValue.single(null, null);
}
// t.value 存的是引用指标的 itemCode
BiMetricQueryService.QueryParams params = new BiMetricQueryService.QueryParams();
params.setItemCodes(t.getValue());
params.setDateType(BiDateTypeEnum.ALL.getValue());
try {
java.util.List<BiMetricQueryService.ItemDetail> items =
biMetricQueryService.getItemDetail(params, BiMetricQueryService.DATE_METHOD);
if (items != null && !items.isEmpty()) {
BigDecimal refValue = items.get(0).getItemValue();
return ThresholdValue.single(refValue, refValue);
}
} catch (Exception e) {
log.error("引用指标查询失败,itemCode={}", t.getValue(), e);
}
return ThresholdValue.single(null, null);
}
}
package cn.com.glsx.dj.strategy.service.warning.threshold;
import cn.com.glsx.dj.strategy.dto.warning.ConditionDTO;
import cn.com.glsx.dj.strategy.dto.warning.ThresholdValue;
import cn.com.glsx.dj.strategy.enums.ThresholdTypeEnum;
import java.util.Collections;
import java.util.List;
import java.util.Map;
/**
* 阈值解析策略接口。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/28 14:00
*/
public interface ThresholdStrategy {
/**
* 支持的阈值类型。
*
* @return 阈值类型枚举
*/
ThresholdTypeEnum supportedType();
/**
* 单条条件解析(用于固定值/引用指标)。
*
* @param condition 条件DTO
* @return 解析后的阈值
*/
ThresholdValue resolve(ConditionDTO condition);
/**
* 批量预加载(用于动态SQL,避免逐条查库)。
*
* @param conditions 条件列表
* @return condition.seq → ThresholdValue
*/
default Map<Integer, ThresholdValue> batchResolve(List<ConditionDTO> conditions) {
return Collections.emptyMap();
}
}
package cn.com.glsx.dj.strategy.service.warning.threshold;
import cn.com.glsx.dj.strategy.dto.warning.ConditionDTO;
import cn.com.glsx.dj.strategy.dto.warning.ThresholdValue;
import cn.com.glsx.dj.strategy.enums.ThresholdTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.function.Function;
import java.util.stream.Collectors;
/**
* 阈值策略工厂——根据 threshold.type 路由到对应策略实现。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/28 14:00
*/
@Slf4j
@Component
public class ThresholdStrategyFactory {
@Autowired
private List<ThresholdStrategy> strategies;
private Map<ThresholdTypeEnum, ThresholdStrategy> strategyMap;
@PostConstruct
public void init() {
strategyMap = strategies.stream()
.collect(Collectors.toMap(ThresholdStrategy::supportedType, Function.identity(),
(a, b) -> a, LinkedHashMap::new));
log.info("阈值策略工厂初始化完成,已注册 {} 种策略", strategyMap.size());
}
/**
* 根据阈值类型获取对应策略。
*
* @param type 阈值类型
* @return 策略实现
*/
public ThresholdStrategy getStrategy(ThresholdTypeEnum type) {
ThresholdStrategy strategy = strategyMap.get(type);
if (strategy == null) {
throw new IllegalArgumentException("未找到阈值策略: " + type);
}
return strategy;
}
/**
* 对条件列表中 type=2(动态SQL)的条件批量预加载。
*
* @param conditions 条件列表
* @return seq → ThresholdValue
*/
public Map<Integer, ThresholdValue> batchResolve(List<ConditionDTO> conditions) {
ThresholdStrategy strategy = getStrategy(ThresholdTypeEnum.DYNAMIC_SQL);
return strategy.batchResolve(conditions);
}
}
package cn.com.glsx.dj.strategy.util;
import cn.com.glsx.framework.core.beans.rpc.RpcPagination;
import java.util.ArrayList;
import java.util.List;
/**
* 内存分页工具——对已加载的 List 进行内存分页,封装为 {@link RpcPagination} 返回。
*
* @author yangwei_by_claude
* @version 1.0
* @since 2026/05/29 14:00
*/
public final class MemoryPageUtil {
private MemoryPageUtil() {
throw new UnsupportedOperationException("Utility class");
}
/**
* 对全量列表进行内存分页。
*
* @param fullList 全量数据
* @param pageNum 页码(从1开始)
* @param pageSize 每页数量
* @param <T> 数据类型
* @return RpcPagination 分页结果
*/
public static <T> RpcPagination<T> page(List<T> fullList, int pageNum, int pageSize) {
RpcPagination<T> pagination = new RpcPagination<>();
if (fullList == null || fullList.isEmpty()) {
pagination.setPageNum(pageNum);
pagination.setPageSize(pageSize);
pagination.setTotal(0);
pagination.setPages(0);
pagination.setList(new ArrayList<>());
return pagination;
}
int total = fullList.size();
int pages = (total + pageSize - 1) / pageSize;
// 页码修正
if (pageNum < 1) {
pageNum = 1;
}
if (pageNum > pages) {
pageNum = pages;
}
int fromIndex = (pageNum - 1) * pageSize;
int toIndex = Math.min(fromIndex + pageSize, total);
List<T> pageList = fullList.subList(fromIndex, toIndex);
pagination.setPageNum(pageNum);
pagination.setPageSize(pageSize);
pagination.setTotal(total);
pagination.setPages(pages);
pagination.setList(pageList);
return pagination;
}
}
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="cn.com.glsx.dj.strategy.mapper.EcoCoefficientRuleMapper">
<select id="selectAllEnabled" resultType="cn.com.glsx.dj.mindworkplate.model.EcoCoefficientRule">
SELECT
id, indicator_code, min_penetration, max_penetration,
coefficient, sort_order, enabled, create_time, update_time
FROM eco_coefficient_rule
WHERE enabled = 1
ORDER BY indicator_code ASC, sort_order ASC
</select>
</mapper>
...@@ -33,4 +33,14 @@ ...@@ -33,4 +33,14 @@
ORDER BY g.created_date DESC, g.id DESC ORDER BY g.created_date DESC, g.id DESC
</select> </select>
<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
FROM pg_group_info
WHERE deleted_flag = 'N'
AND is_enabled = 1
ORDER BY id ASC
</select>
</mapper> </mapper>
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="cn.com.glsx.dj.strategy.mapper.PgStoreOutputMapper">
<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
FROM pg_store_output
WHERE deleted_flag = 'N'
AND business_type = #{businessType}
AND time_dimension = #{timeDimension}
AND period_start = #{periodStart}
AND period_end = #{periodEnd}
ORDER BY store_id ASC
</select>
<delete id="deleteByCondition">
DELETE FROM pg_store_output
WHERE business_type = #{businessType}
AND time_dimension = #{timeDimension}
AND period_start = #{periodStart}
AND period_end = #{periodEnd}
</delete>
<insert id="batchInsert" parameterType="java.util.List">
INSERT INTO pg_store_output (
business_type, store_id, store_name,
time_dimension, period_start, period_end,
deleted_flag, created_by, created_date
) VALUES
<foreach collection="list" item="item" separator=",">
(
#{item.businessType}, #{item.storeId}, #{item.storeName},
#{item.timeDimension}, #{item.periodStart}, #{item.periodEnd},
'N', #{item.createdBy}, #{item.createdDate}
)
</foreach>
</insert>
</mapper>
...@@ -15,4 +15,36 @@ ...@@ -15,4 +15,36 @@
GROUP BY group_id GROUP BY group_id
</select> </select>
<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
FROM pg_warning_config
WHERE deleted_flag = 'N'
AND is_enabled = 1
AND group_id = #{groupId}
ORDER BY id ASC
</select>
<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
FROM pg_warning_config
WHERE deleted_flag = 'N'
AND is_enabled = 1
ORDER BY group_id ASC, id ASC
</select>
<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
FROM pg_warning_config
WHERE deleted_flag = 'N'
AND is_enabled = 1
AND warning_type = #{warningType}
ORDER BY id ASC
</select>
</mapper> </mapper>
...@@ -40,4 +40,20 @@ ...@@ -40,4 +40,20 @@
</if> </if>
</select> </select>
<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
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}
ORDER BY m.sort_order ASC, m.id ASC
</select>
</mapper> </mapper>
...@@ -6,10 +6,35 @@ ...@@ -6,10 +6,35 @@
parameterType="cn.com.glsx.dj.strategy.dto.projectgroup.ProjectGroupWarningRecordQueryDTO" parameterType="cn.com.glsx.dj.strategy.dto.projectgroup.ProjectGroupWarningRecordQueryDTO"
resultType="cn.com.glsx.dj.strategy.dto.projectgroup.ProjectGroupWarningRecordDTO"> resultType="cn.com.glsx.dj.strategy.dto.projectgroup.ProjectGroupWarningRecordDTO">
SELECT DISTINCT SELECT DISTINCT
r.id AS id,
r.group_id AS groupId,
r.config_id AS configId,
r.store_id AS merchantId, r.store_id AS merchantId,
r.store_name AS merchantName, r.store_name AS merchantName,
r.staff_id AS staffId,
r.staff_name AS staffName,
r.staff_phone AS staffPhone,
r.warning_type AS warningType, r.warning_type AS warningType,
t.warning_type_name AS warningTypeName t.warning_type_name AS warningTypeName,
r.business_type AS businessType,
r.monitor_target AS monitorTarget,
r.time_dimension AS timeDimension,
r.period_start AS periodStart,
r.period_end AS periodEnd,
r.metric_code AS metricCode,
r.metric_name AS metricName,
r.metric_value AS metricValue,
r.metric_display AS metricDisplay,
r.threshold_type AS thresholdType,
r.threshold_display AS thresholdDisplay,
r.threshold_min_display AS thresholdMinDisplay,
r.threshold_max_display AS thresholdMaxDisplay,
r.eco_coefficient AS ecoCoefficient,
r.operator AS operator,
r.warning_text AS warningText,
r.is_strategy_sent AS isStrategySent,
r.status AS status,
r.created_time AS createdTime
FROM warning_record r FROM warning_record r
LEFT JOIN pg_warning_type_dict t LEFT JOIN pg_warning_type_dict t
ON r.warning_type = t.warning_type ON r.warning_type = t.warning_type
...@@ -42,7 +67,52 @@ ...@@ -42,7 +67,52 @@
#{merchantId} #{merchantId}
</foreach> </foreach>
</if> </if>
<if test="storeId != null">
AND r.store_id = #{storeId}
</if>
<if test="staffId != null and staffId != ''">
AND r.staff_id = #{staffId}
</if>
<if test="storeName != null and storeName != ''">
AND r.store_name LIKE CONCAT('%', #{storeName}, '%')
</if>
<if test="isStrategySent != null">
AND r.is_strategy_sent = #{isStrategySent}
</if>
ORDER BY merchantId ASC, warningType ASC ORDER BY merchantId ASC, warningType ASC
</select> </select>
<insert id="batchInsert" parameterType="java.util.List">
INSERT INTO warning_record (
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,
threshold_type, threshold_value, threshold_min, threshold_max,
threshold_display, threshold_min_display, threshold_max_display,
eco_coefficient, operator, warning_text,
is_strategy_sent, status, created_time, deleted_flag
) VALUES
<foreach collection="records" item="r" separator=",">
(
#{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.thresholdType}, #{r.thresholdValue}, #{r.thresholdMin}, #{r.thresholdMax},
#{r.thresholdDisplay}, #{r.thresholdMinDisplay}, #{r.thresholdMaxDisplay},
#{r.ecoCoefficient}, #{r.operator}, #{r.warningText},
#{r.isStrategySent}, #{r.status}, #{r.createdTime}, 'N'
)
</foreach>
</insert>
<delete id="deleteByCondition">
DELETE FROM warning_record
WHERE config_id = #{configId}
AND time_dimension = #{timeDimension}
AND period_start = #{periodStart}
AND period_end = #{periodEnd}
</delete>
</mapper> </mapper>
...@@ -39,4 +39,12 @@ ...@@ -39,4 +39,12 @@
AND director_type = #{directorType} AND director_type = #{directorType}
ORDER BY id DESC ORDER BY id DESC
</select> </select>
<select id="findMerchantIdsByUUidAndType" resultType="java.lang.Integer">
SELECT merchant_id
FROM dj_car_life_shop_merchant_director_config
WHERE deleted_flag = 'N'
AND director_user_id = #{uuid}
AND director_type = #{typeValue}
</select>
</mapper> </mapper>
...@@ -244,4 +244,19 @@ ...@@ -244,4 +244,19 @@
#{uuid} #{uuid}
</foreach> </foreach>
</select> </select>
<select id="listMerchantIdsWithStrategy" resultType="java.lang.Integer">
SELECT DISTINCT merchant_id
FROM dj_car_life_strategy_info
WHERE deleted_flag = 'N'
AND biz = #{biz}
<if test="merchantIds != null and merchantIds.size() > 0">
AND merchant_id IN
<foreach item="merchantId" collection="merchantIds" open="(" separator="," close=")">
#{merchantId}
</foreach>
</if>
AND start_date &lt;= #{endDate}
AND end_date &gt;= #{startDate}
</select>
</mapper> </mapper>
\ No newline at end of file \ No newline at end of file
  • @wangxw1
    commented
    Master

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

    1. 违反重要规则:Dubbo 接口请求参数变更存在严重兼容性风险

    • 问题描述:代码中对已有的 ProjectGroupMetricQueryDTO 和 ProjectGroupWarningRecordQueryDTO 进行了修改(新增了 warningType、storeId 等字段)。根据审查规则:“dubbo服务提供者Remote接口中的已有请求参数变更视为危险实现”。
    • 影响分析:在 Dubbo RPC 通信中,直接修改已被其他消费者依赖的 DTO 极易引发反序列化异常(如 UnrecognizedPropertyException),或者导致未同步更新 API jar 包的调用方出现兼容性阻断,引发线上故障。
    • 优化建议:
      • 方案 A:撤销对原 DTO 的修改。为新的预警引擎接口创建全新的请求 DTO(如 ProjectGroupMetricQueryV2DTO)。
      • 方案 B:若必须复用,请通过 Dubbo 的 @DubboService(version = "2.0.0") 进行接口版本隔离,确保平滑过渡。

    2. 严重的性能与稳定性风险:历史数据补跑定时任务缺乏幂等性控制

    • 问题描述:WarningHistoryBackfillJob 被配置为每天凌晨 3 点执行(cron = "0 0 3 * * ?"),但代码中的幂等性校验逻辑被注释掉了(// TODO: 检查 Redis 标记,已执行过则跳过),且未实现执行完成后的状态回写。
    • 影响分析:该任务包含从 2026-01-01 至今的嵌套 while 循环回溯。如果不加控制,系统每天凌晨都会全量重跑一次几年的历史数据。这将导致数据库 CPU/IO 飙升、内存溢出(OOM),并可能产生海量的重复脏数据,引发严重的生产事故。
    • 优化建议:
      • 上线前必须补全 Redis 的分布式锁或执行状态标记逻辑。
      • 建议将历史补跑任务的 Cron 表达式去掉或设为极远未来的时间,改为由运维接口或配置中心手动触发单次执行。

    3. 并发安全漏洞:内存缓存更新非原子操作导致脏读

    • 问题描述:在 EcoCoefficientQueryService.reloadRules() 方法中,更新内存缓存的代码为: java ruleCache.clear(); ruleCache.putAll(groupedRules);
    • 影响分析:ConcurrentHashMap 仅保证单个方法的线程安全。在 clear() 和 putAll() 之间的微小时间窗口内,如果有业务线程调用 getCoefficient(),将会读取到空的缓存,导致生态系数计算错误(错误地返回 BigDecimal.ZERO),进而引发大面积的预警误报或漏报。
    • 优化建议:将 ruleCache 声明为 volatile 并去掉 final 修饰符,通过直接替换引用的方式实现原子更新:

      // 声明处
      private volatile Map<String, List<EcoCoefficientRule>> ruleCache = Collections.emptyMap();
      
      // 更新处
      public void reloadRules() {
          // ... 前置处理逻辑
          this.ruleCache = new ConcurrentHashMap<>(groupedRules);
      }
      

    二、评分明细

    • 功能实现的正确性与健壮性(28/40分)
      • 理由:基础的预警逻辑、指标比对、时间维度计算(LDW/LDM)较为完整。但存在以下扣分项:
        1. 缓存更新存在并发漏洞(见 Top 3)。
        2. WarningEngineRemoteImpl.buildSummaryFromStoreOutput 中,将全量门店 ID 组装成 List 传入 warningRecordService.queryRecords,若门店数量超过 1000,极易触发 MyBatis/数据库的 IN 子句数量上限异常。
        3. 注:本次提交未包含 MyBatis XML 文件,无法直接检查“不允许使用子查询”的规则,请开发者务必在 SQL 实现中严格自查。
    • 安全性与潜在风险(18/30分)
      • 理由:修改了 Dubbo 既有 DTO,触发了高危操作红线,存在严重的向下兼容风险。此外,WarningEngineRemoteImpl 中使用逗号拼接 merchantIdStr 传递给下游 BI 接口,若分页过大可能导致 HTTP URL/Body 超长。
    • 最佳实践与可维护性(14/20分)
      • 理由:代码结构清晰,合理使用了枚举(如 WarningOperatorEnum 封装了计算逻辑,符合面向对象设计)。扣分点在于将 // TODO 直接提交到了生产环境的核心定时任务中,且未处理资源清理。
    • 性能与资源利用(2/5分)
      • 理由:WarningHistoryBackfillJob 的无限重跑逻辑是极其危险的性能炸弹。此外,WarningComputeJob 中使用了 CompletableFuture.runAsync 并在循环内并发调用数据库,若项目组数量多,容易打满数据库连接池。
    • 提交信息质量(4/5分)
      • 理由:Commit 信息(feat:预警引擎功能策略中心列表,策略分析等接口)基本描述了变更范围,但对于改动极大的底层定时任务和 DTO 变更未做重点说明,追溯性有待提升。

    总分:66分

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