NotificationService.java
15.4 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
package com.ecommerce.notification.service;
import com.ecommerce.notification.model.Notification;
import com.ecommerce.notification.model.dto.NotificationRequest;
import com.ecommerce.notification.model.dto.NotificationResponse;
import com.ecommerce.notification.repository.NotificationRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
@Slf4j
@Service
@RequiredArgsConstructor
public class NotificationService {
private final NotificationRepository notificationRepository;
private final EmailService emailService;
private final SmsService smsService;
private final PushNotificationService pushNotificationService;
private final TemplateService templateService;
private final RabbitMQService rabbitMQService;
@Transactional
@Caching(evict = {
@CacheEvict(value = "notifications", allEntries = true),
@CacheEvict(value = "notification", key = "#result.notificationId")
})
public NotificationResponse sendNotification(NotificationRequest request) {
// Validate notification request
validateNotificationRequest(request);
// Create notification record
Notification notification = new Notification();
mapNotificationRequestToEntity(request, notification);
// Process template if template name is provided
if (request.getTemplateName() != null) {
processTemplate(notification, request.getVariables());
}
Notification savedNotification = notificationRepository.save(notification);
// Send notification based on type
boolean sent = sendNotificationByType(savedNotification);
// Update notification status
if (sent) {
savedNotification.setStatus("SENT");
savedNotification.setSentAt(LocalDateTime.now());
} else {
savedNotification.setStatus("FAILED");
savedNotification.setRetryCount(savedNotification.getRetryCount() + 1);
}
Notification updatedNotification = notificationRepository.save(savedNotification);
log.info("Notification {}: {}", sent ? "sent" : "failed", updatedNotification.getNotificationId());
return mapNotificationToResponse(updatedNotification);
}
@Cacheable(value = "notification", key = "#notificationId")
public NotificationResponse getNotification(String notificationId) {
Notification notification = notificationRepository.findByNotificationId(notificationId)
.orElseThrow(() -> new RuntimeException("Notification not found: " + notificationId));
return mapNotificationToResponse(notification);
}
@Cacheable(value = "notifications", key = "#userId + '-' + #pageable.pageNumber")
public Page<NotificationResponse> getNotificationsByUser(Long userId, Pageable pageable) {
return notificationRepository.findByUserId(userId, pageable)
.map(this::mapNotificationToResponse);
}
@Cacheable(value = "notifications", key = "#email + '-' + #pageable.pageNumber")
public Page<NotificationResponse> getNotificationsByEmail(String email, Pageable pageable) {
return notificationRepository.findByEmail(email, pageable)
.map(this::mapNotificationToResponse);
}
@Cacheable(value = "notifications", key = "#type + '-' + #pageable.pageNumber")
public Page<NotificationResponse> getNotificationsByType(String type, Pageable pageable) {
return notificationRepository.findByType(type, pageable)
.map(this::mapNotificationToResponse);
}
@Cacheable(value = "notifications", key = "#channel + '-' + #pageable.pageNumber")
public Page<NotificationResponse> getNotificationsByChannel(String channel, Pageable pageable) {
return notificationRepository.findByChannel(channel, pageable)
.map(this::mapNotificationToResponse);
}
@Cacheable(value = "notifications", key = "#pageable.pageNumber + '-' + #pageable.pageSize")
public Page<NotificationResponse> getAllNotifications(Pageable pageable) {
return notificationRepository.findAll(pageable)
.map(this::mapNotificationToResponse);
}
@Transactional
@Caching(evict = {
@CacheEvict(value = "notifications", allEntries = true),
@CacheEvict(value = "notification", key = "#notificationId")
})
public NotificationResponse markAsRead(String notificationId) {
Notification notification = notificationRepository.findByNotificationId(notificationId)
.orElseThrow(() -> new RuntimeException("Notification not found: " + notificationId));
notification.setReadAt(LocalDateTime.now());
Notification updatedNotification = notificationRepository.save(notification);
return mapNotificationToResponse(updatedNotification);
}
@Transactional
@Caching(evict = {
@CacheEvict(value = "notifications", allEntries = true),
@CacheEvict(value = "notification", key = "#notificationId")
})
public NotificationResponse retryNotification(String notificationId) {
Notification notification = notificationRepository.findByNotificationId(notificationId)
.orElseThrow(() -> new RuntimeException("Notification not found: " + notificationId));
if (!"FAILED".equals(notification.getStatus())) {
throw new RuntimeException("Only failed notifications can be retried");
}
if (notification.getRetryCount() >= notification.getMaxRetries()) {
throw new RuntimeException("Maximum retry attempts reached");
}
boolean sent = sendNotificationByType(notification);
if (sent) {
notification.setStatus("SENT");
notification.setSentAt(LocalDateTime.now());
} else {
notification.setRetryCount(notification.getRetryCount() + 1);
}
Notification updatedNotification = notificationRepository.save(notification);
log.info("Notification retry {}: {}", sent ? "succeeded" : "failed", notificationId);
return mapNotificationToResponse(updatedNotification);
}
@Transactional
public void processPendingNotifications() {
List<Notification> pendingNotifications = notificationRepository.findPendingNotifications();
for (Notification notification : pendingNotifications) {
try {
boolean sent = sendNotificationByType(notification);
if (sent) {
notification.setStatus("SENT");
notification.setSentAt(LocalDateTime.now());
} else {
notification.setRetryCount(notification.getRetryCount() + 1);
if (notification.getRetryCount() >= notification.getMaxRetries()) {
notification.setStatus("FAILED");
notification.setFailureReason("Max retry attempts reached");
}
}
notificationRepository.save(notification);
log.info("Processed pending notification: {} -> {}",
notification.getNotificationId(), notification.getStatus());
} catch (Exception e) {
log.error("Failed to process pending notification: {}", notification.getNotificationId(), e);
}
}
}
public Map<String, Object> getNotificationStatistics(LocalDateTime startDate, LocalDateTime endDate) {
Long pendingCount = notificationRepository.countByStatus("PENDING");
Long sentCount = notificationRepository.countByStatus("SENT");
Long failedCount = notificationRepository.countByStatus("FAILED");
List<Object[]> channelStats = notificationRepository.getChannelStats(startDate, endDate);
Map<String, Long> channelCounts = new HashMap<>();
for (Object[] stat : channelStats) {
channelCounts.put((String) stat[0], (Long) stat[1]);
}
Map<String, Object> stats = new HashMap<>();
stats.put("pendingNotifications", pendingCount);
stats.put("sentNotifications", sentCount);
stats.put("failedNotifications", failedCount);
stats.put("channelStats", channelCounts);
stats.put("startDate", startDate);
stats.put("endDate", endDate);
return stats;
}
private void validateNotificationRequest(NotificationRequest request) {
if (request.getUserId() == null && request.getEmail() == null &&
request.getPhone() == null && request.getDeviceToken() == null) {
throw new RuntimeException("At least one recipient (userId, email, phone, or deviceToken) is required");
}
if (request.getTemplateName() == null && request.getContent() == null) {
throw new RuntimeException("Either template name or content is required");
}
}
private void processTemplate(Notification notification, Map<String, Object> variables) {
try {
Map<String, Object> templateResult = templateService.processTemplate(
notification.getTemplateName(),
notification.getType(),
variables
);
if (templateResult.containsKey("subject")) {
notification.setSubject((String) templateResult.get("subject"));
}
if (templateResult.containsKey("content")) {
notification.setContent((String) templateResult.get("content"));
}
} catch (Exception e) {
log.warn("Template processing failed for {}: {}", notification.getTemplateName(), e.getMessage());
// Continue without template if processing fails
}
}
private boolean sendNotificationByType(Notification notification) {
try {
switch (notification.getType().toUpperCase()) {
case "EMAIL":
return emailService.sendEmail(notification);
case "SMS":
return smsService.sendSms(notification);
case "PUSH":
return pushNotificationService.sendPushNotification(notification);
default:
throw new RuntimeException("Unsupported notification type: " + notification.getType());
}
} catch (Exception e) {
log.error("Failed to send {} notification: {}", notification.getType(), notification.getNotificationId(), e);
notification.setFailureReason(e.getMessage());
return false;
}
}
private void mapNotificationRequestToEntity(NotificationRequest request, Notification notification) {
notification.setUserId(request.getUserId());
notification.setEmail(request.getEmail());
notification.setPhone(request.getPhone());
notification.setDeviceToken(request.getDeviceToken());
notification.setType(request.getType());
notification.setChannel(request.getChannel());
notification.setTemplateName(request.getTemplateName());
notification.setSubject(request.getSubject());
notification.setContent(request.getContent());
notification.setPriority(request.getPriority());
notification.setReferenceType(request.getReferenceType());
notification.setReferenceId(request.getReferenceId());
if (request.getMetadata() != null) {
// Convert metadata map to JSON string
notification.setMetadata(convertMapToJson(request.getMetadata()));
}
}
private NotificationResponse mapNotificationToResponse(Notification notification) {
NotificationResponse response = new NotificationResponse();
response.setNotificationId(notification.getNotificationId());
response.setUserId(notification.getUserId());
response.setEmail(notification.getEmail());
response.setPhone(notification.getPhone());
response.setType(notification.getType());
response.setChannel(notification.getChannel());
response.setTemplateName(notification.getTemplateName());
response.setSubject(notification.getSubject());
response.setContent(notification.getContent());
response.setStatus(notification.getStatus());
response.setPriority(notification.getPriority());
response.setReferenceType(notification.getReferenceType());
response.setReferenceId(notification.getReferenceId());
response.setFailureReason(notification.getFailureReason());
response.setRetryCount(notification.getRetryCount());
response.setCreatedAt(notification.getCreatedAt());
response.setSentAt(notification.getSentAt());
response.setDeliveredAt(notification.getDeliveredAt());
response.setReadAt(notification.getReadAt());
if (notification.getMetadata() != null) {
// Convert metadata JSON string to map
response.setMetadata(convertJsonToMap(notification.getMetadata()));
}
return response;
}
private String convertMapToJson(Map<String, Object> map) {
try {
// Simple JSON conversion - in production use Jackson ObjectMapper
StringBuilder json = new StringBuilder("{");
for (Map.Entry<String, Object> entry : map.entrySet()) {
json.append("\"").append(entry.getKey()).append("\":\"")
.append(entry.getValue()).append("\",");
}
if (json.length() > 1) {
json.deleteCharAt(json.length() - 1);
}
json.append("}");
return json.toString();
} catch (Exception e) {
log.warn("Failed to convert map to JSON: {}", e.getMessage());
return "{}";
}
}
private Map<String, Object> convertJsonToMap(String json) {
try {
// Simple JSON parsing - in production use Jackson ObjectMapper
Map<String, Object> map = new HashMap<>();
if (json != null && json.startsWith("{") && json.endsWith("}")) {
String content = json.substring(1, json.length() - 1);
String[] pairs = content.split(",");
for (String pair : pairs) {
String[] keyValue = pair.split(":");
if (keyValue.length == 2) {
String key = keyValue[0].replace("\"", "").trim();
String value = keyValue[1].replace("\"", "").trim();
map.put(key, value);
}
}
}
return map;
} catch (Exception e) {
log.warn("Failed to convert JSON to map: {}", e.getMessage());
return new HashMap<>();
}
}
}