AutoCreateMealOrderTask.java
13.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
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.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;
@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);
// 查询本周已订餐学生 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,
null
);
if (schoolSuspensionRecords != null) {
var currentTime = System.currentTimeMillis();
schoolSuspensionRecords.stream()
.filter(record -> clientIds.contains(record.getClientId()))
.filter(record -> currentTime >= record.getStartAt() && currentTime <= record.getEndAt())
.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) {
var currentTime = System.currentTimeMillis();
var dinerIdSet = notReservedDiners.stream()
.map(SingleDinerRpcResponse::getId)
.collect(Collectors.toSet());
studentSuspensionRecords.stream()
.filter(record -> dinerIdSet.contains(record.getDinerId()))
.filter(record -> currentTime >= record.getStartAt() && currentTime <= record.getEndAt())
.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(
diner,
clientMap,
gradeClassMap,
latestMealMenuRecordMap,
mpAccountDinerRefMap,
nextWeekStart,
schoolSuspensionMap,
studentSuspensionMap
))
.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(SingleDinerRpcResponse diner,
Map<Integer, SingleClientRpcResponse> clientMap,
Map<Integer, SingleGradeClassRpcResponse> classMap,
Map<Integer, SingleMealMenuRecordRpcResponse> menuMap,
Map<Integer, SingleMpAccountDinerRefRpcResponse> mpAccountDinerRefMap,
ZonedDateTime startOfNextWeek,
Map<Integer, SingleDinerMealSuspensionRecordRpcResponse> schoolSuspensionMap,
Map<Integer, SingleDinerMealSuspensionRecordRpcResponse> studentSuspensionMap) {
final var menu = menuMap.get(diner.getClientId());
final var client = clientMap.get(diner.getClientId());
final var gradeClass = classMap.get(diner.getClassId());
final var mpAccountDinerRef = mpAccountDinerRefMap.get(diner.getId());
if (menu == null || client == null || gradeClass == null) return null;
// 检查学校级别的停餐信息
if (schoolSuspensionMap.containsKey(diner.getClientId())) {
log.info("学校 {} 当前处于停餐状态,跳过自动订餐", client.getName());
return null;
}
// 检查学生级别的停餐信息
if (studentSuspensionMap.containsKey(diner.getId())) {
log.info("学生 {} 当前处于停餐状态,跳过自动订餐", diner.getName());
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(buildNextWeekMeals(startOfNextWeek))
.build();
}
private LocalDate getThisWeekDay(LocalDate now, DayOfWeek target) {
LocalDate monday = now.with(DayOfWeek.MONDAY);
return monday.plusDays(target.getValue() - 1L);
}
private List<MenuSchedule> buildNextWeekMeals(ZonedDateTime nextWeekStart) {
return IntStream.range(0, 5)
.mapToObj(i -> {
final var date = nextWeekStart.plusDays(i);
return MenuSchedule.newBuilder()
.setDate(date.format(DateUtil.YYYY_MM_DD_LEFT_SYMBOL))
.setMenu("A")
.build();
})
.toList();
}
}