-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathProblemService.java
More file actions
409 lines (352 loc) · 17.1 KB
/
ProblemService.java
File metadata and controls
409 lines (352 loc) · 17.1 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
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
package com.gamzabat.algohub.feature.problem.service;
import static com.gamzabat.algohub.constants.ApiConstants.*;
import java.time.LocalDate;
import java.util.Comparator;
import java.util.List;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.gamzabat.algohub.constants.BOJResultConstants;
import com.gamzabat.algohub.exception.ProblemValidationException;
import com.gamzabat.algohub.exception.StudyGroupValidationException;
import com.gamzabat.algohub.feature.group.studygroup.domain.GroupMember;
import com.gamzabat.algohub.feature.group.studygroup.domain.StudyGroup;
import com.gamzabat.algohub.feature.group.studygroup.etc.RoleOfGroupMember;
import com.gamzabat.algohub.feature.group.studygroup.exception.CannotFoundProblemException;
import com.gamzabat.algohub.feature.group.studygroup.exception.GroupMemberValidationException;
import com.gamzabat.algohub.feature.group.studygroup.repository.GroupMemberRepository;
import com.gamzabat.algohub.feature.group.studygroup.repository.StudyGroupRepository;
import com.gamzabat.algohub.feature.notification.enums.NotificationCategory;
import com.gamzabat.algohub.feature.notification.repository.NotificationRepository;
import com.gamzabat.algohub.feature.notification.service.NotificationService;
import com.gamzabat.algohub.feature.problem.domain.Problem;
import com.gamzabat.algohub.feature.problem.dto.CreateProblemRequest;
import com.gamzabat.algohub.feature.problem.dto.EditProblemRequest;
import com.gamzabat.algohub.feature.problem.dto.GetProblemResponse;
import com.gamzabat.algohub.feature.problem.exception.NotBojLinkException;
import com.gamzabat.algohub.feature.problem.exception.SolvedAcApiErrorException;
import com.gamzabat.algohub.feature.problem.repository.ProblemRepository;
import com.gamzabat.algohub.feature.solution.repository.SolutionRepository;
import com.gamzabat.algohub.feature.user.domain.User;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
@Slf4j
@Service
@RequiredArgsConstructor
public class ProblemService {
private final SolutionRepository solutionRepository;
private final ProblemRepository problemRepository;
private final StudyGroupRepository studyGroupRepository;
private final GroupMemberRepository groupMemberRepository;
private final NotificationService notificationService;
private final RestTemplate restTemplate;
private final NotificationRepository notificationRepository;
@Transactional
public void createProblem(User user, Long groupId, CreateProblemRequest request) {
StudyGroup group = getGroup(groupId);
GroupMember groupMember = groupMemberRepository.findByUserAndStudyGroup(user, group)
.orElseThrow(
() -> new StudyGroupValidationException(HttpStatus.FORBIDDEN.value(), "참여하지 않은 그룹 입니다."));
if (RoleOfGroupMember.isParticipant(groupMember)) {
throw new StudyGroupValidationException(HttpStatus.FORBIDDEN.value(),
"문제 생성 권한이 없습니다. 방장, 부방장일 경우에만 생성이 가능합니다.");
}
String number = getProblemId(request);
JsonNode apiResult = fetchProblemDetails(number);
int level = getProblemLevel(apiResult);
String title = getProblemTitle(apiResult);
Problem problem = problemRepository.save(Problem.builder()
.studyGroup(group)
.link(request.link())
.number(Integer.parseInt(number))
.title(title)
.level(level)
.startDate(request.startDate())
.endDate(request.endDate())
.build());
if (request.startDate().equals(LocalDate.now()))
notificationService.sendNotificationToMembers(
group,
groupMemberRepository.findAllByStudyGroup(group),
problem,
null,
NotificationCategory.PROBLEM_STARTED,
NotificationCategory.PROBLEM_STARTED.getMessage(title)
);
log.info("success to create problem user_id={} , group_id = {}", user.getId(), groupId);
}
@Transactional
public void editProblem(User user, Long problemId, EditProblemRequest request) {
Problem problem = getProblem(problemId);
StudyGroup group = getGroup(problem.getStudyGroup().getId());
GroupMember groupMember = groupMemberRepository.findByUserAndStudyGroup(user, group)
.orElseThrow(
() -> new StudyGroupValidationException(HttpStatus.FORBIDDEN.value(), "참여하지 않은 그룹 입니다."));
if (RoleOfGroupMember.isParticipant(groupMember)) {
throw new StudyGroupValidationException(HttpStatus.FORBIDDEN.value(),
"문제 수정 권한이 없습니다. 방장, 부방장일 경우에만 수정이 가능합니다.");
}
checkProblemValidation(problem);
if (request.startDate() != null) {
checkProblemStartDate(request, problem);
problem.editProblemStartDate(request.startDate());
}
if (request.endDate() != null) {
checkProblemEndDate(request, problem);
problem.editProblemEndDate(request.endDate());
}
log.info("success to edit problem deadline user_id={} , problem_id = {}", user.getId(), problemId);
}
private void checkProblemValidation(Problem problem) {
if (problem.getEndDate().isBefore(LocalDate.now())) {
throw new ProblemValidationException(HttpStatus.FORBIDDEN.value(),
"문제 수정이 불가합니다. : 이미 종료된 문제입니다.");
}
}
private void checkProblemEndDate(EditProblemRequest request, Problem problem) {
if (request.endDate().isBefore(problem.getStartDate()))
throw new ProblemValidationException(HttpStatus.BAD_REQUEST.value(),
"문제 마감 날짜는 시작 날짜 이전으로 수정할 수 없습니다.");
if (request.endDate().isBefore(LocalDate.now()))
throw new ProblemValidationException(HttpStatus.BAD_REQUEST.value(),
"문제 마감 날짜는 오늘 이전의 날짜로 수정할 수 없습니다.");
}
private void checkProblemStartDate(EditProblemRequest request, Problem problem) {
if (request.startDate().isBefore(LocalDate.now()))
throw new ProblemValidationException(HttpStatus.BAD_REQUEST.value(),
"문제 시작 날짜는 오늘 이전의 날짜로 수정할 수 없습니다.");
if (request.startDate().isAfter(problem.getEndDate()))
throw new ProblemValidationException(HttpStatus.BAD_REQUEST.value(),
"문제 시작 날짜는 마감 날짜 이후로 수정할 수 없습니다.");
}
@Transactional(readOnly = true)
public Page<GetProblemResponse> getInProgressProblems(User user, Long groupId, Boolean unsolvedOnly,
Pageable pageable) {
StudyGroup group = getGroup(groupId);
if (!groupMemberRepository.existsByUserAndStudyGroup(user, group)) {
throw new ProblemValidationException(HttpStatus.FORBIDDEN.value(), "문제를 조회할 권한이 없습니다.");
}
Page<Problem> problems = problemRepository.findAllInProgressProblem(user, group, unsolvedOnly,
pageable);
return problems.map(problem -> getGetProblemResponse(user, group, problem, unsolvedOnly));
}
@Transactional(readOnly = true)
public Page<GetProblemResponse> getExpiredProblems(User user, Long groupId, Pageable pageable) {
StudyGroup group = getGroup(groupId);
if (!groupMemberRepository.existsByUserAndStudyGroup(user, group)) {
throw new ProblemValidationException(HttpStatus.FORBIDDEN.value(), "문제를 조회할 권한이 없습니다.");
}
Page<Problem> problems = problemRepository.findAllExpiredProblem(group, pageable);
return problems.map(problem -> getGetProblemResponse(user, group, problem, false));
}
private GetProblemResponse getGetProblemResponse(User user, StudyGroup group, Problem problem,
boolean unsolvedOnly) {
boolean solved = unsolvedOnly ? false : solutionRepository.existsByUserAndProblemAndResult(user, problem,
BOJResultConstants.CORRECT);
Integer correctCount = solutionRepository.countDistinctUsersWithCorrectSolutionsByProblemId(problem.getId(),
BOJResultConstants.CORRECT);
Integer submitMemberCount = solutionRepository.countDistinctUsersByProblem(problem);
Integer groupMemberCount = groupMemberRepository.countMembersByStudyGroup(group);
Integer accuracy = calculateAccuracy(submitMemberCount, correctCount);
return new GetProblemResponse(
problem.getTitle(),
problem.getId(),
problem.getLink(),
problem.getStartDate(),
problem.getEndDate(),
problem.getLevel(),
solved, submitMemberCount, groupMemberCount, accuracy);
}
@Transactional
public void deleteProblem(User user, Long problemId) {
Problem problem = getProblem(problemId);
StudyGroup group = getGroup(problem.getStudyGroup().getId());
GroupMember groupMember = groupMemberRepository.findByUserAndStudyGroup(user, group)
.orElseThrow(
() -> new StudyGroupValidationException(HttpStatus.FORBIDDEN.value(), "참여하지 않은 그룹 입니다."));
if (RoleOfGroupMember.isParticipant(groupMember)) {
throw new StudyGroupValidationException(HttpStatus.FORBIDDEN.value(),
"문제 삭제 권한이 없습니다. 방장, 부방장일 경우에만 삭제가 가능합니다.");
}
solutionRepository.deleteAllByProblem(problem);
problemRepository.delete(problem);
notificationRepository.deleteAllByProblem(problem);
log.info("success to delete problem user_id={} , problem_id = {}", user.getId(), problemId);
}
@Transactional(readOnly = true)
public List<GetProblemResponse> getDeadlineReachedProblemList(User user, Long groupId) {
StudyGroup group = getGroup(groupId);
if (!groupMemberRepository.existsByUserAndStudyGroup(user, group))
throw new ProblemValidationException(HttpStatus.FORBIDDEN.value(), "문제를 조회할 권한이 없습니다.");
List<Problem> problems = problemRepository.findAllByStudyGroupAndEndDateBetween(group, LocalDate.now(),
LocalDate.now().plusDays(1));
problems.sort(Comparator.comparing(Problem::getEndDate));
return problems.stream().map(problem -> {
Integer correctCount = solutionRepository.countDistinctUsersWithCorrectSolutionsByProblemId(problem.getId(),
BOJResultConstants.CORRECT);
Integer submitMemberCount = solutionRepository.countDistinctUsersByProblem(problem);
Integer groupMemberCount = groupMemberRepository.countMembersByStudyGroup(group);
Integer accuracy = calculateAccuracy(submitMemberCount, correctCount);
return new GetProblemResponse(
problem.getTitle(),
problem.getId(),
problem.getLink(),
problem.getStartDate(),
problem.getEndDate(),
problem.getLevel(),
solutionRepository.existsByUserAndProblemAndResult(user, problem, BOJResultConstants.CORRECT),
submitMemberCount,
groupMemberCount,
accuracy);
}).toList();
}
@Transactional(readOnly = true)
public Page<GetProblemResponse> getQueuedProblems(User user, Long groupId, Pageable pageable) {
StudyGroup group = getGroup(groupId);
GroupMember groupMember = groupMemberRepository.findByUserAndStudyGroup(user, group)
.orElseThrow(
() -> new StudyGroupValidationException(HttpStatus.FORBIDDEN.value(), "참여하지 않은 그룹 입니다."));
if (RoleOfGroupMember.isParticipant(groupMember)) {
throw new ProblemValidationException(HttpStatus.FORBIDDEN.value(),
"예정 문제를 조회할 권한이 없습니다. : 그룹의 방장과 부방장만 볼 수 있습니다.");
}
Page<Problem> problems = problemRepository.findAllQueuedProblem(group, pageable);
return problems
.map(problem -> {
String title = problem.getTitle();
Long problemId = problem.getId();
String link = problem.getLink();
LocalDate startDate = problem.getStartDate();
LocalDate endDate = problem.getEndDate();
Integer level = problem.getLevel();
boolean solved = false;
Integer submitMemberCount = 0;
Integer groupMemberCount = groupMemberRepository.countMembersByStudyGroup(group);
Integer accuracy = 0;
return new GetProblemResponse(title, problemId, link, startDate, endDate, level, solved,
submitMemberCount,
groupMemberCount, accuracy);
});
}
@Transactional(readOnly = true)
public GetProblemResponse getProblem(User user, Long problemId) {
Problem problem = problemRepository.findById(problemId)
.orElseThrow(() -> new CannotFoundProblemException("존재하지 않는 문제입니다."));
if (!groupMemberRepository.existsByUserAndStudyGroup(user, problem.getStudyGroup()))
throw new GroupMemberValidationException(HttpStatus.FORBIDDEN.value(), "참여하지 않은 그룹입니다.");
boolean solved = solutionRepository.existsByUserAndProblemAndResult(user, problem,
BOJResultConstants.CORRECT);
Integer correctCount = solutionRepository.countDistinctUsersWithCorrectSolutionsByProblemId(problem.getId(),
BOJResultConstants.CORRECT);
Integer submitMemberCount = solutionRepository.countDistinctUsersByProblem(problem);
Integer groupMemberCount =
groupMemberRepository.countMembersByStudyGroup(problem.getStudyGroup());
Integer accuracy = calculateAccuracy(submitMemberCount, correctCount);
GetProblemResponse response = new GetProblemResponse(
problem.getTitle(),
problem.getId(),
problem.getLink(),
problem.getStartDate(),
problem.getEndDate(),
problem.getLevel(),
solved, submitMemberCount, groupMemberCount, accuracy);
log.info("success to get problem. problemId:{}", problemId);
return response;
}
@Transactional
@Scheduled(cron = "0 0 0 * * ?", zone = "Asia/Seoul")
public void dailyProblemScheduler() {
LocalDate now = LocalDate.now();
notifyProblemStartsToday(now);
notifyProblemEndsToday(now);
}
private void notifyProblemStartsToday(LocalDate now) {
List<Problem> problems = problemRepository.findAllByStartDate(now);
for (Problem problem : problems) {
notificationService.sendNotificationToMembers(
problem.getStudyGroup(),
groupMemberRepository.findAllByStudyGroup(problem.getStudyGroup()),
problem,
null,
NotificationCategory.PROBLEM_STARTED,
NotificationCategory.PROBLEM_STARTED.getMessage(problem.getTitle())
);
}
}
private void notifyProblemEndsToday(LocalDate now) {
List<Problem> problems = problemRepository.findAllByEndDate(now);
for (Problem problem : problems) {
notificationService.sendNotificationToMembers(
problem.getStudyGroup(),
groupMemberRepository.findAllByStudyGroup(problem.getStudyGroup()),
problem,
null,
NotificationCategory.PROBLEM_DEADLINE_REACHED,
NotificationCategory.PROBLEM_DEADLINE_REACHED.getMessage(problem.getTitle())
);
}
}
private Problem getProblem(Long problemId) {
return problemRepository.findById(problemId)
.orElseThrow(() -> new ProblemValidationException(HttpStatus.NOT_FOUND.value(), "존재하지 않는 문제 입니다."));
}
private StudyGroup getGroup(Long id) {
return studyGroupRepository.findById(id)
.orElseThrow(() -> new StudyGroupValidationException(HttpStatus.NOT_FOUND.value(), "존재하지 않는 그룹 입니다."));
}
private JsonNode fetchProblemDetails(String problemId) {
String url = SOLVED_AC_PROBLEM_API_URL + problemId;
try {
ResponseEntity<String> responseEntity = restTemplate.getForEntity(url, String.class);
String responseBody = responseEntity.getBody();
if (responseBody == null || responseBody.isEmpty()) {
log.error("Unexpected solved.ac API response format : " + responseBody);
throw new SolvedAcApiErrorException(HttpStatus.SERVICE_UNAVAILABLE.value(),
"solved.ac API로부터 예상치 못한 응답을 받았습니다.");
}
ObjectMapper objectMapper = new ObjectMapper();
JsonNode root = objectMapper.readTree(responseBody);
if (!root.isArray()) {
log.error("Unexpected solved.ac API response format : " + responseBody);
throw new SolvedAcApiErrorException(HttpStatus.SERVICE_UNAVAILABLE.value(),
"solved.ac API로부터 예상치 못한 응답을 받았습니다.");
}
if (root.isEmpty())
throw new SolvedAcApiErrorException(HttpStatus.BAD_REQUEST.value(), "백준에 유효하지 않은 문제입니다.");
return root.get(0);
} catch (JsonProcessingException e) {
log.error("Json processing error : " + e.getMessage());
throw new SolvedAcApiErrorException(HttpStatus.INTERNAL_SERVER_ERROR.value(),
"서버에서 solved.ac API JSON 응답 처리 중 오류가 발생했습니다.");
}
}
private int getProblemLevel(JsonNode problemDetails) {
return problemDetails.get("level").asInt();
}
private String getProblemTitle(JsonNode problemDetails) {
return problemDetails.get("titleKo").asText();
}
private String getProblemId(CreateProblemRequest request) {
String url = request.link();
String[] parts = url.split("/");
if (parts.length < 3 || !parts[2].equals(BOJ_PROBLEM_URL))
throw new NotBojLinkException(HttpStatus.BAD_REQUEST.value(), "백준 링크가 아닙니다");
return parts[parts.length - 1];
}
private Integer calculateAccuracy(Integer submitMemberCount, Integer correctCount) {
if (submitMemberCount == 0)
return 0;
Double tempCorrectCount = correctCount.doubleValue();
Double tempSubmitMemberCount = submitMemberCount.doubleValue();
Double tempAccuracy = ((tempCorrectCount / tempSubmitMemberCount) * 100);
return tempAccuracy.intValue();
}
}