|
| 1 | +package com.example.RealMatch.notification.application.event; |
| 2 | + |
| 3 | +import org.slf4j.Logger; |
| 4 | +import org.slf4j.LoggerFactory; |
| 5 | +import org.springframework.stereotype.Component; |
| 6 | +import org.springframework.transaction.event.TransactionPhase; |
| 7 | +import org.springframework.transaction.event.TransactionalEventListener; |
| 8 | + |
| 9 | +import com.example.RealMatch.brand.domain.entity.Brand; |
| 10 | +import com.example.RealMatch.brand.domain.repository.BrandRepository; |
| 11 | +import com.example.RealMatch.business.application.event.CampaignApplySentEvent; |
| 12 | +import com.example.RealMatch.business.application.event.CampaignProposalSentEvent; |
| 13 | +import com.example.RealMatch.business.application.event.CampaignProposalStatusChangedEvent; |
| 14 | +import com.example.RealMatch.business.domain.enums.ProposalDirection; |
| 15 | +import com.example.RealMatch.business.domain.enums.ProposalStatus; |
| 16 | +import com.example.RealMatch.notification.application.dto.CreateNotificationCommand; |
| 17 | +import com.example.RealMatch.notification.application.service.NotificationMessageTemplateService; |
| 18 | +import com.example.RealMatch.notification.application.service.NotificationMessageTemplateService.MessageTemplate; |
| 19 | +import com.example.RealMatch.notification.application.service.NotificationService; |
| 20 | +import com.example.RealMatch.notification.domain.entity.enums.NotificationKind; |
| 21 | +import com.example.RealMatch.notification.domain.entity.enums.ReferenceType; |
| 22 | +import com.example.RealMatch.user.domain.entity.User; |
| 23 | +import com.example.RealMatch.user.domain.repository.UserRepository; |
| 24 | + |
| 25 | +import lombok.RequiredArgsConstructor; |
| 26 | + |
| 27 | +@Component |
| 28 | +@RequiredArgsConstructor |
| 29 | +public class NotificationEventListener { |
| 30 | + |
| 31 | + private static final Logger LOG = LoggerFactory.getLogger(NotificationEventListener.class); |
| 32 | + |
| 33 | + private final NotificationService notificationService; |
| 34 | + private final NotificationMessageTemplateService messageTemplateService; |
| 35 | + private final BrandRepository brandRepository; |
| 36 | + private final UserRepository userRepository; |
| 37 | + |
| 38 | + // ==================== CampaignProposalSentEvent ==================== |
| 39 | + |
| 40 | + /** |
| 41 | + * CampaignProposalSentEvent 구독. |
| 42 | + * proposalDirection=BRAND_TO_CREATOR일 때 PROPOSAL_RECEIVED 알림 생성. |
| 43 | + */ |
| 44 | + @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) |
| 45 | + public void handleCampaignProposalSent(CampaignProposalSentEvent event) { |
| 46 | + if (event == null) { |
| 47 | + LOG.warn("[Notification] Invalid CampaignProposalSentEvent: event is null"); |
| 48 | + return; |
| 49 | + } |
| 50 | + |
| 51 | + if (event.proposalDirection() != ProposalDirection.BRAND_TO_CREATOR) { |
| 52 | + LOG.debug("[Notification] Skipping notification for CREATOR_TO_BRAND proposal. proposalId={}", |
| 53 | + event.proposalId()); |
| 54 | + return; |
| 55 | + } |
| 56 | + |
| 57 | + try { |
| 58 | + String eventId = generateProposalSentEventId(event.proposalId(), event.isReProposal()); |
| 59 | + String brandName = findBrandNameByUserId(event.brandUserId()); |
| 60 | + |
| 61 | + MessageTemplate template = messageTemplateService.createProposalReceivedMessage(brandName); |
| 62 | + |
| 63 | + CreateNotificationCommand command = CreateNotificationCommand.builder() |
| 64 | + .eventId(eventId) |
| 65 | + .userId(event.creatorUserId()) |
| 66 | + .kind(NotificationKind.PROPOSAL_RECEIVED) |
| 67 | + .title(template.title()) |
| 68 | + .body(template.body()) |
| 69 | + .referenceType(ReferenceType.CAMPAIGN_PROPOSAL) |
| 70 | + .referenceId(String.valueOf(event.proposalId())) |
| 71 | + .campaignId(event.campaignId()) |
| 72 | + .proposalId(event.proposalId()) |
| 73 | + .build(); |
| 74 | + |
| 75 | + notificationService.create(command); |
| 76 | + |
| 77 | + LOG.info("[Notification] Created PROPOSAL_RECEIVED. eventId={}, proposalId={}, userId={}", |
| 78 | + eventId, event.proposalId(), event.creatorUserId()); |
| 79 | + } catch (Exception e) { |
| 80 | + LOG.error("[Notification] Failed to create PROPOSAL_RECEIVED. proposalId={}, userId={}", |
| 81 | + event.proposalId(), event.creatorUserId(), e); |
| 82 | + } |
| 83 | + } |
| 84 | + |
| 85 | + // ==================== CampaignProposalStatusChangedEvent ==================== |
| 86 | + |
| 87 | + /** |
| 88 | + * CampaignProposalStatusChangedEvent 구독. |
| 89 | + * <ul> |
| 90 | + * <li>MATCHED → 크리에이터에게 CAMPAIGN_MATCHED + 제안 보낸 사람에게 PROPOSAL_SENT(수락)</li> |
| 91 | + * <li>REJECTED → 제안 보낸 사람에게 PROPOSAL_SENT(거절)</li> |
| 92 | + * </ul> |
| 93 | + * 각 알림 생성은 독립적으로 예외 처리한다. |
| 94 | + */ |
| 95 | + @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) |
| 96 | + public void handleCampaignProposalStatusChanged(CampaignProposalStatusChangedEvent event) { |
| 97 | + if (event == null) { |
| 98 | + LOG.warn("[Notification] Invalid CampaignProposalStatusChangedEvent: event is null"); |
| 99 | + return; |
| 100 | + } |
| 101 | + |
| 102 | + if (event.newStatus() == ProposalStatus.MATCHED) { |
| 103 | + // 1) 크리에이터에게 CAMPAIGN_MATCHED |
| 104 | + createCampaignMatchedNotification(event); |
| 105 | + // 2) 제안 보낸 사람에게 PROPOSAL_SENT (수락) — 독립 try-catch |
| 106 | + createProposalSentNotification(event, true); |
| 107 | + } else if (event.newStatus() == ProposalStatus.REJECTED) { |
| 108 | + createProposalSentNotification(event, false); |
| 109 | + } |
| 110 | + } |
| 111 | + |
| 112 | + /** |
| 113 | + * CAMPAIGN_MATCHED 알림 생성 (크리에이터에게) |
| 114 | + */ |
| 115 | + private void createCampaignMatchedNotification(CampaignProposalStatusChangedEvent event) { |
| 116 | + try { |
| 117 | + String eventId = generateProposalStatusChangedEventId(event.proposalId(), event.newStatus()); |
| 118 | + String brandName = findBrandNameByUserId(event.brandUserId()); |
| 119 | + |
| 120 | + MessageTemplate template = messageTemplateService.createCampaignMatchedMessage(brandName); |
| 121 | + |
| 122 | + CreateNotificationCommand command = CreateNotificationCommand.builder() |
| 123 | + .eventId(eventId) |
| 124 | + .userId(event.creatorUserId()) |
| 125 | + .kind(NotificationKind.CAMPAIGN_MATCHED) |
| 126 | + .title(template.title()) |
| 127 | + .body(template.body()) |
| 128 | + .referenceType(ReferenceType.CAMPAIGN_PROPOSAL) |
| 129 | + .referenceId(String.valueOf(event.proposalId())) |
| 130 | + .campaignId(event.campaignId()) |
| 131 | + .proposalId(event.proposalId()) |
| 132 | + .build(); |
| 133 | + |
| 134 | + notificationService.create(command); |
| 135 | + |
| 136 | + LOG.info("[Notification] Created CAMPAIGN_MATCHED. eventId={}, proposalId={}, userId={}", |
| 137 | + eventId, event.proposalId(), event.creatorUserId()); |
| 138 | + } catch (Exception e) { |
| 139 | + LOG.error("[Notification] Failed to create CAMPAIGN_MATCHED. proposalId={}, userId={}", |
| 140 | + event.proposalId(), event.creatorUserId(), e); |
| 141 | + } |
| 142 | + } |
| 143 | + |
| 144 | + /** |
| 145 | + * PROPOSAL_SENT 알림 생성 (제안 보낸 사람에게, 수락/거절 공통) |
| 146 | + */ |
| 147 | + private void createProposalSentNotification(CampaignProposalStatusChangedEvent event, boolean isAccepted) { |
| 148 | + try { |
| 149 | + String eventId = generateProposalStatusChangedEventId(event.proposalId(), event.newStatus()); |
| 150 | + // proposalDirection을 이용해 senderUserId 결정 (DB 조회 불필요) |
| 151 | + Long senderUserId = event.proposalDirection() == ProposalDirection.BRAND_TO_CREATOR |
| 152 | + ? event.brandUserId() |
| 153 | + : event.creatorUserId(); |
| 154 | + |
| 155 | + String brandName = findBrandNameByUserId(event.brandUserId()); |
| 156 | + |
| 157 | + MessageTemplate template = messageTemplateService.createProposalSentMessage(brandName, isAccepted); |
| 158 | + |
| 159 | + CreateNotificationCommand command = CreateNotificationCommand.builder() |
| 160 | + .eventId(eventId) |
| 161 | + .userId(senderUserId) |
| 162 | + .kind(NotificationKind.PROPOSAL_SENT) |
| 163 | + .title(template.title()) |
| 164 | + .body(template.body()) |
| 165 | + .referenceType(ReferenceType.CAMPAIGN_PROPOSAL) |
| 166 | + .referenceId(String.valueOf(event.proposalId())) |
| 167 | + .campaignId(event.campaignId()) |
| 168 | + .proposalId(event.proposalId()) |
| 169 | + .build(); |
| 170 | + |
| 171 | + notificationService.create(command); |
| 172 | + |
| 173 | + String resultLabel = isAccepted ? "accepted" : "rejected"; |
| 174 | + LOG.info("[Notification] Created PROPOSAL_SENT ({}). eventId={}, proposalId={}, userId={}", |
| 175 | + resultLabel, eventId, event.proposalId(), senderUserId); |
| 176 | + } catch (Exception e) { |
| 177 | + LOG.error("[Notification] Failed to create PROPOSAL_SENT. proposalId={}, newStatus={}", |
| 178 | + event.proposalId(), event.newStatus(), e); |
| 179 | + } |
| 180 | + } |
| 181 | + |
| 182 | + // ==================== CampaignApplySentEvent ==================== |
| 183 | + |
| 184 | + /** |
| 185 | + * CampaignApplySentEvent 구독. |
| 186 | + * 브랜드에게 CAMPAIGN_APPLIED 알림 생성. |
| 187 | + */ |
| 188 | + @TransactionalEventListener(phase = TransactionPhase.AFTER_COMMIT) |
| 189 | + public void handleCampaignApplySent(CampaignApplySentEvent event) { |
| 190 | + if (event == null) { |
| 191 | + LOG.warn("[Notification] Invalid CampaignApplySentEvent: event is null"); |
| 192 | + return; |
| 193 | + } |
| 194 | + |
| 195 | + try { |
| 196 | + String eventId = generateApplySentEventId(event.applyId()); |
| 197 | + User creator = userRepository.findById(event.creatorUserId()) |
| 198 | + .orElseThrow(() -> new IllegalStateException( |
| 199 | + "User not found: " + event.creatorUserId())); |
| 200 | + String creatorName = resolveDisplayName(creator); |
| 201 | + |
| 202 | + MessageTemplate template = messageTemplateService.createCampaignAppliedMessage(creatorName); |
| 203 | + |
| 204 | + CreateNotificationCommand command = CreateNotificationCommand.builder() |
| 205 | + .eventId(eventId) |
| 206 | + .userId(event.brandUserId()) |
| 207 | + .kind(NotificationKind.CAMPAIGN_APPLIED) |
| 208 | + .title(template.title()) |
| 209 | + .body(template.body()) |
| 210 | + .referenceType(ReferenceType.CAMPAIGN_APPLY) |
| 211 | + .referenceId(String.valueOf(event.applyId())) |
| 212 | + .campaignId(event.campaignId()) |
| 213 | + .build(); |
| 214 | + |
| 215 | + notificationService.create(command); |
| 216 | + |
| 217 | + LOG.info("[Notification] Created CAMPAIGN_APPLIED. eventId={}, applyId={}, userId={}", |
| 218 | + eventId, event.applyId(), event.brandUserId()); |
| 219 | + } catch (Exception e) { |
| 220 | + LOG.error("[Notification] Failed to create CAMPAIGN_APPLIED. applyId={}, userId={}", |
| 221 | + event.applyId(), event.brandUserId(), e); |
| 222 | + } |
| 223 | + } |
| 224 | + |
| 225 | + // ==================== 공통 헬퍼 ==================== |
| 226 | + |
| 227 | + /** |
| 228 | + * brandUserId(User PK)로 Brand를 조회하여 brandName을 반환한다. |
| 229 | + */ |
| 230 | + private String findBrandNameByUserId(Long brandUserId) { |
| 231 | + Brand brand = brandRepository.findByUserId(brandUserId) |
| 232 | + .orElseThrow(() -> new IllegalStateException( |
| 233 | + "Brand not found for userId: " + brandUserId)); |
| 234 | + return brand.getBrandName(); |
| 235 | + } |
| 236 | + |
| 237 | + /** |
| 238 | + * User의 표시 이름을 결정한다. (nickname 우선, 없으면 name) |
| 239 | + */ |
| 240 | + private String resolveDisplayName(User user) { |
| 241 | + if (user.getNickname() != null && !user.getNickname().isEmpty()) { |
| 242 | + return user.getNickname(); |
| 243 | + } |
| 244 | + return user.getName(); |
| 245 | + } |
| 246 | + |
| 247 | + // ==================== EventId 생성 (멱등성 보장용) ==================== |
| 248 | + |
| 249 | + /** |
| 250 | + * CampaignProposalSentEvent의 결정적 eventId 생성 |
| 251 | + */ |
| 252 | + private String generateProposalSentEventId(Long proposalId, boolean isReProposal) { |
| 253 | + String type = isReProposal ? "RE_PROPOSAL_SENT" : "PROPOSAL_SENT"; |
| 254 | + return String.format("%s:%d", type, proposalId); |
| 255 | + } |
| 256 | + |
| 257 | + /** |
| 258 | + * CampaignProposalStatusChangedEvent의 결정적 eventId 생성 |
| 259 | + */ |
| 260 | + private String generateProposalStatusChangedEventId(Long proposalId, ProposalStatus newStatus) { |
| 261 | + return String.format("PROPOSAL_STATUS_CHANGED:%d:%s", proposalId, newStatus); |
| 262 | + } |
| 263 | + |
| 264 | + /** |
| 265 | + * CampaignApplySentEvent의 결정적 eventId 생성 |
| 266 | + */ |
| 267 | + private String generateApplySentEventId(Long applyId) { |
| 268 | + return String.format("APPLY_SENT:%d", applyId); |
| 269 | + } |
| 270 | +} |
0 commit comments