-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRewardService.java
More file actions
69 lines (61 loc) · 2.73 KB
/
RewardService.java
File metadata and controls
69 lines (61 loc) · 2.73 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
package org.runimo.runimo.rewards.service;
import java.util.NoSuchElementException;
import java.util.Optional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.runimo.runimo.item.domain.Egg;
import org.runimo.runimo.records.domain.RunningRecord;
import org.runimo.runimo.records.service.RecordFinder;
import org.runimo.runimo.rewards.service.dto.RewardClaimCommand;
import org.runimo.runimo.rewards.service.dto.RewardResponse;
import org.runimo.runimo.rewards.service.eggs.EggGrantService;
import org.runimo.runimo.rewards.service.lovepoint.LoveGrantService;
import org.runimo.runimo.user.domain.User;
import org.runimo.runimo.user.service.UserFinder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
@Slf4j
@Service
@RequiredArgsConstructor
public class RewardService {
private final RecordFinder recordFinder;
private final UserFinder userFinder;
private final EggGrantService eggGrantService;
private final LoveGrantService loveGrantService;
@Transactional
public RewardResponse claimReward(RewardClaimCommand command) {
RunningRecord runningRecord = recordFinder.findByPublicId(command.recordPublicId())
.orElseThrow(NoSuchElementException::new);
validateRecord(runningRecord);
Egg grantedEgg = rewardEgg(command);
Long grantedLoveAmount = loveGrantService.grantLoveToUserWithDistance(runningRecord);
runningRecord.reward(command.userId());
return RewardResponse.of(grantedEgg, grantedLoveAmount);
}
private Egg rewardEgg(RewardClaimCommand command) {
User user = userFinder.findUserById(command.userId())
.orElseThrow(NoSuchElementException::new);
if (validateRecordIsFirstRecordOfWeek(command)) {
return eggGrantService.grantRandomEggToUser(user);
}
return Egg.EMPTY;
}
private void validateRecord(RunningRecord runningRecord) {
if (runningRecord.isRecordAlreadyRewarded()) {
throw new IllegalStateException("이미 보상이 지급되었습니다.");
}
}
private boolean validateRecordIsFirstRecordOfWeek(RewardClaimCommand command) {
Optional<RunningRecord> firstRecordOfWeek = recordFinder.findFirstRunOfCurrentWeek(
command.userId());
if (firstRecordOfWeek.isEmpty()) {
log.info("유저 {}의 첫번째 달리기 기록이 없습니다.", command.userId());
return false;
}
if (!command.recordPublicId().equals(firstRecordOfWeek.get().getRecordPublicId())) {
log.info("유저 {}의 첫번째 달리기 기록이 아닙니다.", command.userId());
return false;
}
return true;
}
}