AutoCreateMealOrderTask.java
16.8 KB
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
package com.infoloop.tianting.logic.task;
import com.infoloop.tianting.clientinventoryservice.SingleClientRpcResponse;
import com.infoloop.tianting.context.LoginContextHolder;
import com.infoloop.tianting.enums.LoginSourceEnum;
import com.infoloop.tianting.mealorderservice.*;
import com.infoloop.tianting.service.client.ClientInventoryServiceRpcClient;
import com.infoloop.tianting.service.client.DeliveryRuleServiceRpcClient;
import com.infoloop.tianting.service.client.MealOrderServiceRpcClient;
import com.infoloop.tianting.service.SuspensionService;
import com.infoloop.tianting.store.WeeklyTaskStore;
import com.infoloop.tianting.utils.DateUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import java.time.DayOfWeek;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.ZonedDateTime;
import java.time.temporal.TemporalAdjusters;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.IntStream;
@Slf4j
@Component
@RequiredArgsConstructor
public class AutoCreateMealOrderTask {
private final MealOrderServiceRpcClient mealOrderServiceRpcClient;
private final ClientInventoryServiceRpcClient clientInventoryServiceRpcClient;
private final DeliveryRuleServiceRpcClient deliveryRuleServiceRpcClient;
private final WeeklyTaskStore weeklyTaskStore;
private final SuspensionService suspensionService;
@Scheduled(cron = "0 0/5 * * * ?")
public void executeTask() {
final int enterpriseId = 449;
final var now = LocalDateTime.now();
final var today = now.toLocalDate();
// 判断是否本周已执行
final var keyPrefix = "create-meal-order-task";
if (weeklyTaskStore.isExecutedThisWeek(keyPrefix, enterpriseId, today)) return;
final var rules = deliveryRuleServiceRpcClient.getDefaultDeliveryTemplateAndRule(enterpriseId).getRule();
if (rules.getConfigJson().getRulesList().isEmpty()) {
return;
}
final var rule = rules.getConfigJson().getRules(0);
final var endTime = LocalTime.parse(rule.getEndTime(), DateUtil.HH_MM_SS);
final var enabledDays = new ArrayList<DayOfWeek>();
if (Boolean.TRUE.equals(rule.getMonday())) enabledDays.add(DayOfWeek.MONDAY);
if (Boolean.TRUE.equals(rule.getTuesday())) enabledDays.add(DayOfWeek.TUESDAY);
if (Boolean.TRUE.equals(rule.getWednesday())) enabledDays.add(DayOfWeek.WEDNESDAY);
if (Boolean.TRUE.equals(rule.getThursday())) enabledDays.add(DayOfWeek.THURSDAY);
if (Boolean.TRUE.equals(rule.getFriday())) enabledDays.add(DayOfWeek.FRIDAY);
if (Boolean.TRUE.equals(rule.getSaturday())) enabledDays.add(DayOfWeek.SATURDAY);
if (Boolean.TRUE.equals(rule.getSunday())) enabledDays.add(DayOfWeek.SUNDAY);
if (enabledDays.isEmpty()) {
return;
}
final var maxDay = Collections.max(enabledDays);
final var endDateTime = getThisWeekDay(today, maxDay).atTime(endTime);
if (now.isBefore(endDateTime)) {
log.info("当前时间小于订餐结束时间:{},跳过自动订餐任务", endDateTime);
return;
}
try {
weeklyTaskStore.markExecuted(keyPrefix, enterpriseId, today);
final var thisWeekStart = today.with(DayOfWeek.MONDAY).atStartOfDay().atZone(DateUtil.CHINA_ZONE);
final var thisWeekEnd = today.with(DayOfWeek.SUNDAY).atTime(LocalTime.MAX).atZone(DateUtil.CHINA_ZONE);
final var nextWeekStart = today.with(TemporalAdjusters.next(DayOfWeek.MONDAY)).atStartOfDay().atZone(DateUtil.CHINA_ZONE);
// 获取下周每天的节假日信息
final var holidayMap = new HashMap<String, Integer>();
for (int i = 0; i < 7; i++) {
final var date = nextWeekStart.plusDays(i);
final var dateStr = date.format(DateUtil.YYYY_MM_DD);
try {
final var url = String.format("https://api.haoshenqi.top/holiday?date=%s", dateStr);
final var response = new java.net.URL(url).openConnection();
final var reader = new java.io.BufferedReader(new java.io.InputStreamReader(response.getInputStream()));
final var jsonResponse = reader.readLine();
final var jsonNode = new com.fasterxml.jackson.databind.ObjectMapper().readTree(jsonResponse);
final var status = jsonNode.get(0).get("status").asInt();
holidayMap.put(dateStr, status);
} catch (Exception e) {
log.error("检查节假日失败: {}", dateStr, e);
}
}
// 查询本周已订餐学生 ID
final var mealOrders = mealOrderServiceRpcClient.queryMealOrdersByCondition(enterpriseId, null, thisWeekStart.toInstant().toEpochMilli(), thisWeekEnd.toInstant().toEpochMilli());
final var dinerIds = mealOrders.stream().map(SingleMealOrderRpcResponse::getDinerId).sorted(Comparator.comparingInt(Integer::intValue)).collect(Collectors.toCollection(LinkedHashSet::new));
log.info("本周:{}, 已订餐学生 ID:{}", today, dinerIds);
// 所有学生 & 未订餐学生
final var allDiners = mealOrderServiceRpcClient.queryDinersByCondition(enterpriseId, null, null, null);
final var notReservedDiners = allDiners.stream().filter(diner -> !dinerIds.contains(diner.getId())).sorted(Comparator.comparingInt(SingleDinerRpcResponse::getId)).toList();
if (notReservedDiners.isEmpty()) {
return;
}
log.info("本周:{}, 未订餐学生 ID:{}", today, notReservedDiners.stream().map(SingleDinerRpcResponse::getId).toList());
// 所需关联数据查询
final var mpAccountDinerRefMap = mealOrderServiceRpcClient.queryMpAccountDinerRefsByCondition(enterpriseId, Collections.emptyList(), notReservedDiners.stream().map(SingleDinerRpcResponse::getId).toList()).stream().collect(Collectors.toMap(SingleMpAccountDinerRefRpcResponse::getDinerId, Function.identity(), (v1, v2) -> v1));
final var clientIds = notReservedDiners.stream().map(SingleDinerRpcResponse::getClientId).distinct().toList();
final var classIds = notReservedDiners.stream().map(SingleDinerRpcResponse::getClassId).distinct().toList();
final var clientMap = clientInventoryServiceRpcClient.getClientsByIds(enterpriseId, clientIds).getClientsList().stream().collect(Collectors.toMap(SingleClientRpcResponse::getId, Function.identity()));
final var gradeClassMap = mealOrderServiceRpcClient.getGradeClassesByIds(enterpriseId, classIds).stream().collect(Collectors.toMap(SingleGradeClassRpcResponse::getId, Function.identity()));
final var latestMealMenuRecordMap = mealOrderServiceRpcClient.queryLatestMealMenuRecordsByClientIds(enterpriseId, clientIds).stream().collect(Collectors.toMap(SingleMealMenuRecordRpcResponse::getClientId, Function.identity()));
// 批量查询学校级别的停餐信息
final var schoolSuspensionMap = new HashMap<Integer, SingleDinerMealSuspensionRecordRpcResponse>();
var schoolSuspensionRecords = mealOrderServiceRpcClient.queryDinerMealSuspensionRecordsByCondition(
enterpriseId,
clientIds, // 使用0表示查询所有
null,
List.of(0)
);
if (schoolSuspensionRecords != null) {
final var nextWeekStartTime = nextWeekStart.toInstant().toEpochMilli();
final var nextWeekEndTime = nextWeekStart.plusDays(6).with(LocalTime.MAX).toInstant().toEpochMilli();
schoolSuspensionRecords.stream()
.filter(record -> clientIds.contains(record.getClientId()))
.filter(record -> !(record.getEndAt() < nextWeekStartTime || record.getStartAt() > nextWeekEndTime))
.collect(Collectors.groupingBy(
SingleDinerMealSuspensionRecordRpcResponse::getClientId,
Collectors.collectingAndThen(
Collectors.maxBy((a, b) -> Long.compare(a.getCreatedAt(), b.getCreatedAt())),
opt -> opt.orElse(null)
)
))
.forEach((clientId, record) -> {
if (record != null) {
schoolSuspensionMap.put(clientId, record);
}
});
}
// 批量查询学生级别的停餐信息
final var studentSuspensionMap = new HashMap<Integer, SingleDinerMealSuspensionRecordRpcResponse>();
var studentSuspensionRecords = mealOrderServiceRpcClient.queryDinerMealSuspensionRecordsByCondition(
enterpriseId,
null, // 使用0表示查询所有
null,
notReservedDiners.stream().map(SingleDinerRpcResponse::getId).toList()
);
if (studentSuspensionRecords != null) {
final var nextWeekStartTime = nextWeekStart.toInstant().toEpochMilli();
final var nextWeekEndTime = nextWeekStart.plusDays(6).with(LocalTime.MAX).toInstant().toEpochMilli();
var dinerIdSet = notReservedDiners.stream()
.map(SingleDinerRpcResponse::getId)
.collect(Collectors.toSet());
studentSuspensionRecords.stream()
.filter(record -> dinerIdSet.contains(record.getDinerId()))
.filter(record -> !(record.getEndAt() < nextWeekStartTime || record.getStartAt() > nextWeekEndTime))
.collect(Collectors.groupingBy(
SingleDinerMealSuspensionRecordRpcResponse::getDinerId,
Collectors.collectingAndThen(
Collectors.maxBy((a, b) -> Long.compare(a.getCreatedAt(), b.getCreatedAt())),
opt -> opt.orElse(null)
)
))
.forEach((dinerId, record) -> {
if (record != null) {
studentSuspensionMap.put(dinerId, record);
}
});
}
// 构建创建请求
final var creations = notReservedDiners.stream()
.map(diner -> toMealOrderCreation(
enterpriseId,
diner,
clientMap,
gradeClassMap,
latestMealMenuRecordMap,
mpAccountDinerRefMap,
nextWeekStart,
schoolSuspensionMap,
studentSuspensionMap,
holidayMap
))
.filter(Objects::nonNull)
.toList();
if (creations.isEmpty()) {
return;
}
final var loginInfo = LoginContextHolder.LoginInfo.builder()
.id(0)
.enterpriseId(enterpriseId)
.loginSource(LoginSourceEnum.MINI_PROGRAM)
.build();
final var batchCreateMealOrdersRpcResponse = mealOrderServiceRpcClient.batchCreateMealOrders(loginInfo, creations);
log.info("本周:{}, 已自动补单 {} 条", today, batchCreateMealOrdersRpcResponse.getIdsList().size());
} catch (Exception e) {
log.error("自动订餐失败", e);
weeklyTaskStore.clearExecutedThisWeek(keyPrefix, enterpriseId, today);
}
}
private MealOrderCreation toMealOrderCreation(int enterpriseId,
SingleDinerRpcResponse diner,
Map<Integer, SingleClientRpcResponse> clientIdToClient,
Map<Integer, SingleGradeClassRpcResponse> classIdToClass,
Map<Integer, SingleMealMenuRecordRpcResponse> clientIdToLatestMenu,
Map<Integer, SingleMpAccountDinerRefRpcResponse> dinerIdToAccountRef,
ZonedDateTime startOfNextWeek,
Map<Integer, SingleDinerMealSuspensionRecordRpcResponse> schoolSuspensionMap,
Map<Integer, SingleDinerMealSuspensionRecordRpcResponse> studentSuspensionMap,
Map<String, Integer> dateStrToHolidayStatus) {
final SingleMealMenuRecordRpcResponse menu = clientIdToLatestMenu.get(diner.getClientId());
final SingleClientRpcResponse client = clientIdToClient.get(diner.getClientId());
final SingleGradeClassRpcResponse gradeClass = classIdToClass.get(diner.getClassId());
final SingleMpAccountDinerRefRpcResponse mpAccountDinerRef = dinerIdToAccountRef.get(diner.getId());
if (menu == null || client == null || gradeClass == null) return null;
// 计算多段停餐区间(学校/班级/学生维度最新记录的并集,保留间隙)
final var intervals = suspensionService.getSuspensionIntervalsForDiner(
enterpriseId,
diner.getClientId(),
diner.getClassId(),
diner.getId()
);
// 构建下周的餐食安排(基于多段停餐区间)
List<MenuSchedule> meals = buildNextWeekMeals(startOfNextWeek, intervals, dateStrToHolidayStatus);
if (meals.isEmpty()) {
return null;
}
return MealOrderCreation.newBuilder()
.setClientId(diner.getClientId())
.setMenuId(menu.getId())
.setAccountId(mpAccountDinerRef == null ? 0 : mpAccountDinerRef.getAccountId())
.setOrderMethod(MealOrderOrderMethodEnum.MEAL_ORDER_METHOD_SYSTEM)
.setDinerId(diner.getId())
.setDinerName(diner.getName())
.setClientName(client.getName())
.setGradeName(gradeClass.getGradeName())
.setClassName(gradeClass.getClassName())
.setStudentNo(diner.getStudentNo())
.setReserveDate(Instant.now().toEpochMilli())
.addAllMeals(meals)
.build();
}
// 已由并集窗口版本替代
private List<MenuSchedule> buildNextWeekMeals(ZonedDateTime nextWeekStart,
java.util.List<SuspensionService.SuspensionInterval> intervals,
Map<String, Integer> holidayMap) {
return IntStream.range(0, 7)
.mapToObj(i -> {
final var date = nextWeekStart.plusDays(i);
final var dateStr = date.format(DateUtil.YYYY_MM_DD);
// 检查是否为节假日
final var status = holidayMap.get(dateStr);
if (status != null && status != 0 && status != 2) {
return null;
}
if (intervals != null && !intervals.isEmpty()) {
final var dateStart = date.with(LocalTime.MIN).toInstant().toEpochMilli();
final var dateEnd = date.with(LocalTime.MAX).toInstant().toEpochMilli();
final boolean overlaps = intervals.stream()
.anyMatch(interval -> !(dateEnd < interval.startAt || dateStart > interval.endAt));
if (overlaps) return null;
}
return MenuSchedule.newBuilder()
.setDate(date.format(DateUtil.YYYY_MM_DD_LEFT_SYMBOL))
.setMenu("A")
.build();
})
.filter(Objects::nonNull)
.toList();
}
private LocalDate getThisWeekDay(LocalDate now, DayOfWeek target) {
LocalDate monday = now.with(DayOfWeek.MONDAY);
return monday.plusDays(target.getValue() - 1L);
}
}