4 天以前 2a69f1a4365fb7daa8d00c07ac859a0d45780eb7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
package cn.iocoder.yudao.module.bi.service.decision;
 
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import cn.iocoder.yudao.module.bi.controller.admin.decision.vo.DecisionForecastHistorySaveReqVO;
import cn.iocoder.yudao.module.bi.controller.admin.decision.vo.DecisionForecastWorkOrderCreateReqVO;
import cn.iocoder.yudao.module.bi.dal.dataobject.decision.BiForecastDataDO;
import cn.iocoder.yudao.module.bi.dal.dataobject.decision.BiKpiDefinitionDO;
import cn.iocoder.yudao.module.bi.dal.dataobject.decision.BiKpiValueHistoryDO;
import cn.iocoder.yudao.module.bi.dal.mysql.decision.BiForecastDataMapper;
import cn.iocoder.yudao.module.bi.dal.mysql.decision.BiKpiDefinitionMapper;
import cn.iocoder.yudao.module.bi.dal.mysql.decision.BiKpiValueHistoryMapper;
import cn.iocoder.yudao.module.mes.api.workorder.MesProWorkOrderApi;
import cn.iocoder.yudao.module.mes.api.workorder.dto.MesProWorkOrderCreateReqDTO;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
 
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
 
import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.bi.enums.ErrorCodeConstants.BI_FORECAST_NO_HISTORY;
import static cn.iocoder.yudao.module.bi.enums.ErrorCodeConstants.BI_FORECAST_NOT_EXISTS;
 
/**
 * 负荷预测 Service 实现
 *
 * 本期使用简单移动平均占位,预留 ML 模型接口
 *
 * @author 超级管理员
 */
@Slf4j
@Service
public class BiForecastServiceImpl implements BiForecastService {
 
    /**
     * 工单来源类型:负荷预测(与字典 mes_pro_work_order_source_type 的 value=4 一致)
     */
    private static final Integer WORK_ORDER_SOURCE_TYPE_FORECAST = 4;
 
    @Resource
    private BiForecastDataMapper forecastDataMapper;
    @Resource
    private BiKpiDefinitionMapper kpiMapper;
    @Resource
    private BiKpiValueHistoryMapper kpiValueHistoryMapper;
    @Resource
    private MesProWorkOrderApi mesProWorkOrderApi;
 
    @Override
    public List<BiForecastDataDO> getForecastList(String forecastCode, LocalDateTime beginTime, LocalDateTime endTime) {
        return forecastDataMapper.selectListByCodeAndTimeRange(forecastCode, beginTime, endTime);
    }
 
    /**
     * 移动平均窗口大小
     */
    private static final int SMA_WINDOW = 12;
 
    @Override
    public Long createForecastHistory(DecisionForecastHistorySaveReqVO reqVO) {
        BiForecastDataDO data = BiForecastDataDO.builder()
                .forecastCode(reqVO.getForecastCode())
                .forecastName(reqVO.getForecastName())
                .pointTime(reqVO.getPointTime())
                .forecastValue(reqVO.getForecastValue())
                .actualValue(reqVO.getActualValue())
                .dimension(reqVO.getDimension())
                .dimensionValue(reqVO.getDimensionValue())
                .remark(reqVO.getRemark())
                .modelVersion("manual-history")
                .build();
        forecastDataMapper.insert(data);
        return data.getId();
    }
 
    @Override
    public void generateForecast(String forecastCode, LocalDateTime pointTime) {
        // 默认使用 SMA 模型
        generateForecast(forecastCode, "SMA", SMA_WINDOW, 7, pointTime);
    }
 
    @Override
    public void generateForecast(String forecastCode, String model, int window, int period,
                                 LocalDateTime pointTime) {
        // 基于同预测编码的历史预测数据做统计预测;无历史数据时不伪造零值
        List<BiForecastDataDO> history = forecastDataMapper.selectRecentByCode(forecastCode, SMA_WINDOW);
        if (CollUtil.isEmpty(history)) {
            throw exception(BI_FORECAST_NO_HISTORY);
        }
        List<BigDecimal> values = new ArrayList<>();
        for (BiForecastDataDO h : history) {
            if (h.getForecastValue() != null) {
                values.add(h.getForecastValue());
            }
        }
        BiForecastEngine.Forecast forecast = BiForecastEngine.forecast(model, values, window, period);
        if (forecast == null) {
            throw exception(BI_FORECAST_NO_HISTORY);
        }
        BiForecastDataDO data = BiForecastDataDO.builder()
                .forecastCode(forecastCode)
                .forecastName(history.get(0).getForecastName())
                .pointTime(pointTime)
                .forecastValue(forecast.value())
                .lowerBound(forecast.lowerBound())
                .upperBound(forecast.upperBound())
                .confidenceLevel(new BigDecimal("95.00"))
                .modelVersion("v2.0-" + model.toLowerCase())
                .build();
        forecastDataMapper.insert(data);
    }
 
    @Override
    public int generateKpiForecast(String kpiCode, String model, int window, int period,
                                   int periods, int intervalMinutes) {
        // 1. 校验 KPI 定义
        BiKpiDefinitionDO kpi = kpiMapper.selectOne(BiKpiDefinitionDO::getCode, kpiCode);
        if (kpi == null) {
            throw exception(BI_FORECAST_NOT_EXISTS);
        }
        // 2. 取 KPI 历史快照(升序),无数据不预测
        List<BiKpiValueHistoryDO> historyList = kpiValueHistoryMapper.selectByKpiCodeAndTimeRange(
                kpiCode, LocalDateTime.now().minusMonths(6), LocalDateTime.now());
        if (CollUtil.isEmpty(historyList)) {
            throw exception(BI_FORECAST_NO_HISTORY);
        }
        List<BigDecimal> history = new ArrayList<>();
        LocalDateTime lastSnapshotTime = null;
        for (BiKpiValueHistoryDO h : historyList) {
            if (h.getKpiValue() != null) {
                history.add(h.getKpiValue());
                lastSnapshotTime = h.getSnapshotTime();
            }
        }
        if (history.isEmpty()) {
            throw exception(BI_FORECAST_NO_HISTORY);
        }
        // 3. 逐期滚动预测
        int targetPeriods = periods > 0 ? Math.min(periods, 90) : 30;
        int stepMinutes = intervalMinutes > 0 ? intervalMinutes : 360;
        int count = 0;
        LocalDateTime nextTime = lastSnapshotTime;
        for (int i = 0; i < targetPeriods; i++) {
            BiForecastEngine.Forecast f = BiForecastEngine.forecast(model, history, window, period);
            if (f == null) {
                break;
            }
            nextTime = nextTime.plusMinutes(stepMinutes);
            BiForecastDataDO data = BiForecastDataDO.builder()
                    .forecastCode(kpiCode)
                    .forecastName(kpi.getName() + " 预测")
                    .pointTime(nextTime)
                    .forecastValue(f.value())
                    .lowerBound(f.lowerBound())
                    .upperBound(f.upperBound())
                    .confidenceLevel(new BigDecimal("95.00"))
                    .modelVersion("v2.0-" + (model == null ? "sma" : model.toLowerCase()))
                    .dimension("kpi")
                    .dimensionValue(kpiCode)
                    .build();
            forecastDataMapper.insert(data);
            count++;
            // 将预测值追加进历史,供下一期滚动
            history.add(f.value());
            if (history.size() > 200) {
                history.remove(0);
            }
        }
        return count;
    }
 
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Long createWorkOrderFromForecast(DecisionForecastWorkOrderCreateReqVO reqVO) {
        // 1. 校验预测数据存在
        BiForecastDataDO forecast = forecastDataMapper.selectById(reqVO.getForecastId());
        if (forecast == null) {
            throw exception(BI_FORECAST_NOT_EXISTS);
        }
        // 2. 组装工单 DTO 并调用 MES API 创建(无产品工单,跳 BOM)
        MesProWorkOrderCreateReqDTO dto = new MesProWorkOrderCreateReqDTO();
        dto.setCode(generateWorkOrderCode());
        dto.setName(reqVO.getWorkOrderName() != null
                ? reqVO.getWorkOrderName()
                : ("负荷预测-" + forecast.getForecastName()));
        dto.setType(reqVO.getWorkOrderType());
        dto.setOrderSourceType(WORK_ORDER_SOURCE_TYPE_FORECAST);
        dto.setOrderSourceCode(forecast.getForecastCode());
        dto.setRequestDate(reqVO.getRequestDate());
        dto.setQuantity(reqVO.getQuantity());
        dto.setRemark(reqVO.getRemark());
        return mesProWorkOrderApi.createWorkOrder(dto);
    }
 
    private String generateWorkOrderCode() {
        return "GZ" + DateUtil.format(LocalDateTime.now(), "yyyyMMddHHmmss")
                + String.format("%03d", (int) (Math.random() * 1000));
    }
 
}