Skip to content

Commit 0eac67f

Browse files
committed
docs : 알림 메서드 설명 주석 추가
1 parent 38b32c4 commit 0eac67f

File tree

9 files changed

+105
-39
lines changed

9 files changed

+105
-39
lines changed

src/main/java/cmf/commitField/domain/commit/scheduler/CommitScheduler.java

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,6 @@
11
package cmf.commitField.domain.commit.scheduler;
22

33
import cmf.commitField.domain.commit.totalCommit.service.TotalCommitService;
4-
import cmf.commitField.domain.noti.noti.entity.NotiDetailType;
5-
import cmf.commitField.domain.noti.noti.entity.NotiType;
6-
import cmf.commitField.domain.noti.noti.event.NotiEvent;
74
import cmf.commitField.domain.noti.noti.service.CommitSteakNotiService;
85
import cmf.commitField.domain.noti.noti.service.NotiService;
96
import cmf.commitField.domain.user.entity.User;
@@ -29,8 +26,6 @@ public class CommitScheduler {
2926
private final UserRepository userRepository;
3027
private final StringRedisTemplate redisTemplate;
3128
private final AtomicInteger counter = new AtomicInteger(0);
32-
private final SimpMessagingTemplate messagingTemplate;
33-
private final NotiService notiService;
3429
private final CommitSteakNotiService commitSteakNotiService;
3530

3631
private final ApplicationEventPublisher eventPublisher;
@@ -110,6 +105,7 @@ private void processUserCommit(String username) {
110105
CommitUpdateEvent event = new CommitUpdateEvent(this, username, newCommitCount);
111106
eventPublisher.publishEvent(event); // 이벤트 발생
112107

108+
// 커밋 업데이트가 있고, 연속 커밋이 3일 이상, 10의 배수 이상인 경우 알림 생성
113109
commitSteakNotiService.checkAndCreateSteakNoti(user, currentStreakCommit);
114110

115111
System.out.println("CommitCreatedEvent published for user: " + username);

src/main/java/cmf/commitField/domain/noti/noti/controller/ApiV1NotiController.java

Lines changed: 8 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@
44
import cmf.commitField.domain.noti.noti.service.NotiService;
55
import cmf.commitField.domain.user.entity.User;
66
import cmf.commitField.domain.user.repository.UserRepository;
7+
import cmf.commitField.domain.user.service.UserService;
78
import cmf.commitField.global.error.ErrorCode;
89
import cmf.commitField.global.exception.CustomException;
910
import cmf.commitField.global.globalDto.GlobalResponse;
@@ -29,32 +30,22 @@
2930
@Slf4j
3031
public class ApiV1NotiController {
3132
private final NotiService notiService;
32-
private final UserRepository userRepository;
33-
34-
// private final NotiWebSocketHandler notiWebSocketHandler;
35-
private final ApplicationEventPublisher eventPublisher;
33+
private final UserService userService;
3634

3735

3836
@GetMapping("")
3937
public GlobalResponse<List<NotiDto>> getNoti(@AuthenticationPrincipal OAuth2User oAuth2User) {
4038
String username = oAuth2User.getName();
41-
User user = userRepository.findByUsername(username).orElseThrow(() -> new CustomException(ErrorCode.NOT_FOUND_USER));
39+
User user = userService.findByUsername(username);
4240
List<NotiDto> notis = notiService.getNotReadNoti(user);
4341
return GlobalResponse.success(notis);
4442
}
4543

4644
@PostMapping("/read")
47-
public GlobalResponse<Object> readNoti() {
48-
Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
49-
50-
if (authentication instanceof OAuth2AuthenticationToken) {
51-
OAuth2User principal = (OAuth2User) authentication.getPrincipal();
52-
Map<String, Object> attributes = principal.getAttributes();
53-
String username = (String) attributes.get("login"); // GitHub ID
54-
User user = userRepository.findByUsername(username).orElseThrow(() -> new CustomException(ErrorCode.NOT_FOUND_USER));
55-
notiService.read(user);
56-
return GlobalResponse.success("알림을 읽음 처리했습니다.");
57-
}
58-
return GlobalResponse.error(ErrorCode.LOGIN_REQUIRED);
45+
public GlobalResponse<Object> readNoti(@AuthenticationPrincipal OAuth2User oAuth2User) {
46+
String username = oAuth2User.getName();
47+
User user = userService.findByUsername(username);
48+
notiService.read(user);
49+
return GlobalResponse.success("알림을 읽음 처리했습니다.");
5950
}
6051
}

src/main/java/cmf/commitField/domain/noti/noti/dto/NotiDto.java

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,13 +12,14 @@ public class NotiDto {
1212
private String message;
1313
private String formattedCreatedAt; // 변환된 날짜를 저장할 필드
1414

15-
// JPQL에서 사용할 수 있도록 필드 값 직접 받는 생성자 추가
15+
// 필드 값 직접 받는 생성자 추가
1616
public NotiDto(Long id, String message, LocalDateTime createdAt) {
1717
this.id = id;
1818
this.message = message;
1919
this.formattedCreatedAt = formatCreatedAt(createdAt); // 변환된 날짜 저장
2020
}
2121

22+
// 날짜 변환 메서드 (오늘, 어제, 3일 전까지 이후 yyyy-MM-dd)
2223
private String formatCreatedAt(LocalDateTime createdAt) {
2324
LocalDateTime today = LocalDateTime.now();
2425
long daysBetween = ChronoUnit.DAYS.between(createdAt, today);

src/main/java/cmf/commitField/domain/noti/noti/entity/NotiDetailType.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,12 @@ public String[] getParamNames() {
2727
return paramNames;
2828
}
2929

30+
/**
31+
* 메시지 포맷팅입니다.
32+
* 잘못된 파라미터 개수일 경우 IllegalArgumentException을 던집니다.
33+
* @param params
34+
* @return template에 파라미터를 적용한 메시지
35+
*/
3036
public String formatMessage(Object... params) {
3137
if (paramNames.length != params.length) {
3238
throw new IllegalArgumentException("🚨 잘못된 파라미터 개수! 필요: " +

src/main/java/cmf/commitField/domain/noti/noti/repository/NotiRepository.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,5 +25,6 @@ public interface NotiRepository extends JpaRepository<Noti, Long> {
2525
// 최근 10일 내 동일한 커밋 부재 알림이 있는지 확인
2626
boolean existsByReceiverAndTypeCodeAndType2CodeAndCreatedAtAfter(User receiver, NotiType type, NotiDetailType detailType, LocalDateTime after);
2727

28+
// 해당 타입의 알림이 오늘 이후에 있는지 확인
2829
boolean existsByReceiverAndType2CodeAndCreatedAtAfter(User receiver, NotiDetailType notiDetailType, LocalDateTime todayStart);
2930
}

src/main/java/cmf/commitField/domain/noti/noti/service/CommitAbsenceNotiService.java

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,7 +42,11 @@ public void sendCommitAbsenceNoti() {
4242
}
4343
}
4444

45-
// 최근 10일 내 커밋 부재 알림이 있었는지 확인
45+
/**
46+
* 최근 10일 내 커밋 부재 알림이 있었는지 확인
47+
* @param user
48+
* @return
49+
*/
4650
private boolean hasRecentAbsenceNoti(User user) {
4751
log.info("커밋 부재 알림 확인: {}", user.getUsername());
4852
LocalDateTime checkDate = LocalDateTime.now().minusDays(10);

src/main/java/cmf/commitField/domain/noti/noti/service/CommitSteakNotiService.java

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -42,6 +42,11 @@ public void sendCommitSteakNoti() {
4242
}
4343
}
4444

45+
/**
46+
* 연속 커밋 알림을 생성
47+
* @param user
48+
* @param currentStreakCommit
49+
*/
4550
public void checkAndCreateSteakNoti(User user, int currentStreakCommit) {
4651
boolean alreadyNotified = notiRepository.existsByReceiverAndType2CodeAndCreatedAtAfter(
4752
user, NotiDetailType.STREAK_CONTINUED, LocalDate.now().atStartOfDay()
@@ -57,7 +62,7 @@ public void checkAndCreateSteakNoti(User user, int currentStreakCommit) {
5762

5863

5964
/**
60-
* 특정 연속 커밋 횟수에 도달했는지 확인
65+
* 특정 연속 커밋 횟수(3회, 10의 배수 횟수)에 도달했는지 확인
6166
*/
6267
public boolean shouldNotify(int streak) {
6368
return streak == 3 || (streak % 10 == 0);

src/main/java/cmf/commitField/domain/noti/noti/service/NotiService.java

Lines changed: 69 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,19 @@ public class NotiService {
2727
private final NotiRepository notiRepository;
2828
private final ApplicationEventPublisher eventPublisher;
2929

30-
// 알림 생성
30+
/**
31+
* 알림 생성 공통 로직입니다.
32+
* 받아온 params를 이용하여 메시지를 생성하고 알림 엔티티를 생성합니다.
33+
* 메시지에 필요한 파라미터는 NotiDetailType에 정의된 순서대로 전달해야 합니다.
34+
* 만약 NotiDetailType에 정의된 파라미터가 없는 경우에는 빈 배열을 전달해야 합니다.
35+
* 데이터베이스에 알림 엔티티를 저장하고 WebSocket 이벤트를 발생시킵니다.
36+
* @param receiver
37+
* @param notiType
38+
* @param notiDetailType
39+
* @param relId
40+
* @param relTypeCode
41+
* @param params
42+
*/
3143
@Transactional
3244
public void createNoti(User receiver, NotiType notiType, NotiDetailType notiDetailType, Long relId, String relTypeCode, Object... params) {
3345
// 메시지 생성
@@ -53,66 +65,109 @@ public void createNoti(User receiver, NotiType notiType, NotiDetailType notiDeta
5365
eventPublisher.publishEvent(event);
5466
}
5567

56-
// 알림 조회
68+
/**
69+
* 알림 조회
70+
* @param receiver
71+
* @return
72+
*/
5773
public List<NotiDto> getNotReadNoti(User receiver) {
5874
List<NotiDto> notis = notiRepository.findNotiDtoByReceiverId(receiver.getId(), false).orElse(null);
5975
return notis;
6076
}
6177

62-
// 시즌 알림 확인
78+
/**
79+
* 시즌 알림 확인
80+
* 알림이 없을 경우 예외 발생
81+
* @param receiver
82+
* @param seasonId
83+
* @return List
84+
*/
6385
public List<Noti> getSeasonNotiCheck(User receiver, long seasonId) {
6486
return notiRepository.findNotiByReceiverAndRelId(receiver, seasonId)
6587
.orElseThrow(() -> new CustomException(ErrorCode.ERROR_CHECK)); // 알림이 없을 경우 예외 발생
6688
}
6789

68-
// 새 시즌 알림 생성
90+
/**
91+
* 새 시즌 알림 생성
92+
* @param season
93+
* @param user
94+
*/
6995
@Transactional
7096
public void createNewSeasonNoti(Season season, User user) {
7197
createNoti(user, NotiType.SEASON, NotiDetailType.SEASON_START, season.getId(), season.getModelName(), season.getName());
7298
}
7399

74-
// 랭킹 업 알림 생성
100+
/**
101+
* 랭킹 업 알림 생성
102+
* @param user
103+
*/
75104
@Transactional
76105
public void createRankUpNoti(User user) {
77106
createNoti(user, NotiType.RANK, NotiDetailType.RANK_UP, 0L, null, getDisplayName(user), user.getTier().name());
78107
}
79108

80-
// 연속 커밋 축하 알림 생성
109+
/**
110+
* 연속 커밋 축하 알림 생성
111+
* @param user
112+
* @param days
113+
*/
81114
@Transactional
82115
public void createStreakCommitNoti(User user, String days) {
83116
createNoti(user, NotiType.STREAK, NotiDetailType.STREAK_CONTINUED, 0L, null, getDisplayName(user), days);
84117
}
85118

86-
// 커밋 부재 알림 생성
119+
/**
120+
* 커밋 부재 알림 생성
121+
* @param user
122+
*/
87123
@Transactional
88124
public void createStreakBrokenNoti(User user) {
89125
createNoti(user, NotiType.STREAK, NotiDetailType.STREAK_BROKEN, 0L, null, getDisplayName(user));
90126
}
91127

92-
// 업적 알림 생성
128+
/**
129+
* 업적 알림 생성
130+
* @param user
131+
* @param achievementName
132+
*/
133+
// TODO: 업적 로직 구현 후 사용
93134
@Transactional
94135
public void createAchievementNoti(User user, String achievementName) {
95136
createNoti(user, NotiType.ACHIEVEMENT, NotiDetailType.ACHIEVEMENT_COMPLETED, 0L, null, getDisplayName(user), achievementName);
96137
}
97138

98-
// 공지사항 알림 생성
139+
/**
140+
* 공지사항 알림 생성
141+
* @param user
142+
* @param noticeTitle
143+
*/
144+
// TODO: 공지사항 로직 구현 후 사용
99145
@Transactional
100146
public void createNoticeNoti(User user, String noticeTitle) {
101147
createNoti(user, NotiType.NOTICE, NotiDetailType.NOTICE_CREATED, 0L, null, noticeTitle);
102148
}
103149

104-
// 읽음 처리
150+
/**
151+
* 알림 읽음 처리:
152+
* 알림 버튼 클릭 시 모든 알림이 읽음 상태로 변경되기 때문에
153+
* 사용자의 모든 알림의 상태를 true로 변경하는 메서드
154+
* @param receiver
155+
*/
105156
@Transactional
106-
public List<Noti> read(User receiver) {
107-
System.out.println("알림 읽음 처리");
157+
public void read(User receiver) {
158+
log.info("✅ read notis");
108159
List<Noti> notis = notiRepository.findNotiByReceiver(receiver).orElseThrow(() -> new CustomException(ErrorCode.NOT_FOUND_USER));
109160
notis.forEach(noti -> {
110161
noti.setRead(true);
111162
});
112-
System.out.println("알림 읽음 처리 끝");
113-
return notis;
114163
}
115164

165+
/**
166+
* 닉네임 여부에 따라 표시 이름 반환:
167+
* 닉네임이 있으면 닉네임, 없으면 유저네임 반환
168+
* @param user
169+
* @return
170+
*/
116171
private String getDisplayName(User user) {
117172
return user.getNickname() != null ? user.getNickname() : user.getUsername();
118173
}

src/main/java/cmf/commitField/domain/user/service/UserService.java

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,8 @@
1313
import cmf.commitField.domain.user.entity.User;
1414
import cmf.commitField.domain.user.repository.TierRegacyRepository;
1515
import cmf.commitField.domain.user.repository.UserRepository;
16+
import cmf.commitField.global.error.ErrorCode;
17+
import cmf.commitField.global.exception.CustomException;
1618
import lombok.RequiredArgsConstructor;
1719
import org.springframework.data.redis.core.StringRedisTemplate;
1820
import org.springframework.stereotype.Service;
@@ -111,4 +113,9 @@ public void updateUserCommitCount(String username, long count){
111113
user.addCommitCount(count);
112114
userRepository.save(user);
113115
}
116+
117+
public User findByUsername(String username) {
118+
return userRepository.findByUsername(username).orElseThrow(() -> new
119+
CustomException(ErrorCode.NOT_FOUND_USER));
120+
}
114121
}

0 commit comments

Comments
 (0)