Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package ct01.n06.backend.config;

Check warning on line 1 in backend/src/main/java/ct01/n06/backend/config/EmailRabbitMQConfig.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Rename this package name to match the regular expression '^[a-z_]+(\.[a-z_][a-z0-9_]*)*$'.

See more on https://sonarcloud.io/project/issues?id=NguyenTuKien_SSLINK&issues=AZ3B3qaGzR5Y5AHZTMGO&open=AZ3B3qaGzR5Y5AHZTMGO&pullRequest=46

import org.springframework.amqp.core.Binding;
import org.springframework.amqp.core.BindingBuilder;
import org.springframework.amqp.core.DirectExchange;
import org.springframework.amqp.core.Queue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class EmailRabbitMQConfig {

public static final String QUEUE_NAME = "notification_email_queue";
public static final String EXCHANGE_NAME = "notification_email_exchange";
public static final String ROUTING_KEY = "notification.email.send";

@Bean
public Queue notificationEmailQueue() {
return new Queue(QUEUE_NAME, true);
}

@Bean
public DirectExchange notificationEmailExchange() {
return new DirectExchange(EXCHANGE_NAME);
}

@Bean
public Binding bindingNotificationEmailQueue(Queue notificationEmailQueue, DirectExchange notificationEmailExchange) {
return BindingBuilder.bind(notificationEmailQueue).to(notificationEmailExchange).with(ROUTING_KEY);
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
package ct01.n06.backend.consumer;

Check warning on line 1 in backend/src/main/java/ct01/n06/backend/consumer/EmailNotificationConsumer.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Rename this package name to match the regular expression '^[a-z_]+(\.[a-z_][a-z0-9_]*)*$'.

See more on https://sonarcloud.io/project/issues?id=NguyenTuKien_SSLINK&issues=AZ3B3qaQzR5Y5AHZTMGP&open=AZ3B3qaQzR5Y5AHZTMGP&pullRequest=46

import java.nio.file.Path;
import java.util.List;

import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import ct01.n06.backend.config.EmailRabbitMQConfig;
import ct01.n06.backend.dto.mail.NotificationEmailJob;
import ct01.n06.backend.service.EmailService;
import ct01.n06.backend.service.EmailService.EmailRecipient;
import ct01.n06.backend.service.EmailService.EmailSendSummary;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@RequiredArgsConstructor
public class EmailNotificationConsumer {

private final EmailService emailService;

@RabbitListener(queues = EmailRabbitMQConfig.QUEUE_NAME)
public void processNotificationEmail(NotificationEmailJob job) {
if (job == null) {
log.warn("Nhận email job rỗng, bỏ qua.");
return;
}

List<EmailRecipient> recipients = job.recipients() == null
? List.of()
: job.recipients().stream()
.filter(recipient -> recipient != null && StringUtils.hasText(recipient.email()))
.map(recipient -> new EmailRecipient(recipient.email().trim(), recipient.fullName()))
.toList();

if (recipients.isEmpty()) {
log.warn("Email job không có người nhận hợp lệ: subject={}", job.subject());
return;
}

Path attachmentPath = StringUtils.hasText(job.attachmentPath()) ? Path.of(job.attachmentPath()) : null;
EmailSendSummary summary = emailService.sendNotificationEmail(
job.subject(),
job.content(),
job.senderName(),
recipients,
job.attachmentName(),
attachmentPath
);

log.info(
"Đã xử lý email job: subject={}, recipients={}, sent={}, failed={}",
job.subject(),
recipients.size(),
summary.sentCount(),
summary.failedCount()
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,8 @@
public record LecturerNotificationCreateResponse(
Long notificationId,
int totalRecipients,
int sentEmailCount,
int failedEmailCount,
int queuedEmailCount,
int failedQueueCount,
String createdAt,
String attachmentName
) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package ct01.n06.backend.dto.mail;

Check warning on line 1 in backend/src/main/java/ct01/n06/backend/dto/mail/NotificationEmailJob.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Rename this package name to match the regular expression '^[a-z_]+(\.[a-z_][a-z0-9_]*)*$'.

See more on https://sonarcloud.io/project/issues?id=NguyenTuKien_SSLINK&issues=AZ3B3qWczR5Y5AHZTMGM&open=AZ3B3qWczR5Y5AHZTMGM&pullRequest=46

import java.util.List;

public record NotificationEmailJob(
String subject,
String content,
String senderName,
List<Recipient> recipients,
String attachmentName,
String attachmentPath
) {

public record Recipient(String email, String fullName) {
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package ct01.n06.backend.service;

Check warning on line 1 in backend/src/main/java/ct01/n06/backend/service/EmailQueueService.java

View check run for this annotation

SonarQubeCloud / SonarCloud Code Analysis

Rename this package name to match the regular expression '^[a-z_]+(\.[a-z_][a-z0-9_]*)*$'.

See more on https://sonarcloud.io/project/issues?id=NguyenTuKien_SSLINK&issues=AZ3B3qZ9zR5Y5AHZTMGN&open=AZ3B3qZ9zR5Y5AHZTMGN&pullRequest=46

import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import ct01.n06.backend.config.EmailRabbitMQConfig;
import ct01.n06.backend.dto.mail.NotificationEmailJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
@RequiredArgsConstructor
public class EmailQueueService {

private final RabbitTemplate rabbitTemplate;

public void enqueueNotificationEmail(NotificationEmailJob job) {
if (job == null) {
log.warn("Bỏ qua enqueue email vì job rỗng.");
return;
}

rabbitTemplate.convertAndSend(
EmailRabbitMQConfig.EXCHANGE_NAME,
EmailRabbitMQConfig.ROUTING_KEY,
job
);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,17 +14,22 @@
import java.util.Map;
import java.util.UUID;

import org.springframework.amqp.AmqpException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.PageRequest;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronization;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import ct01.n06.backend.dto.common.SimpleMessageResponse;
import ct01.n06.backend.dto.lecturer.CreateLecturerNotificationRequest;
import ct01.n06.backend.dto.lecturer.LecturerNotificationCreateResponse;
import ct01.n06.backend.dto.mail.NotificationEmailJob;
import ct01.n06.backend.dto.mail.NotificationEmailJob.Recipient;
import ct01.n06.backend.dto.student.StudentNotificationListResponse;
import ct01.n06.backend.dto.student.StudentNotificationListResponse.StudentNotificationItem;
import ct01.n06.backend.dto.student.StudentNotificationUnreadResponse;
Expand All @@ -42,9 +47,7 @@
import ct01.n06.backend.repository.NotificationRecipientRepository;
import ct01.n06.backend.repository.NotificationRepository;
import ct01.n06.backend.repository.StudentRepository;
import ct01.n06.backend.service.EmailService;
import ct01.n06.backend.service.EmailService.EmailRecipient;
import ct01.n06.backend.service.EmailService.EmailSendSummary;
import ct01.n06.backend.service.EmailQueueService;
import ct01.n06.backend.service.NotificationService;
import ct01.n06.backend.service.UserService;
import lombok.RequiredArgsConstructor;
Expand All @@ -63,7 +66,7 @@ public class NotificationServiceImpl implements NotificationService {
private final NotificationRepository notificationRepository;
private final NotificationRecipientRepository notificationRecipientRepository;
private final LecturerRepository lecturerRepository;
private final EmailService emailService;
private final EmailQueueService emailQueueService;

@Value("${notification.attachment.dir:./backend/storage/notifications}")
private String attachmentDirectory;
Expand Down Expand Up @@ -123,7 +126,7 @@ public LecturerNotificationCreateResponse createLecturerNotification(
.toList();
notificationRecipientRepository.saveAll(recipientEntities);

EmailSendSummary emailSummary = sendNotificationEmail(savedNotification, recipients, attachment);
int queuedEmailCount = enqueueNotificationEmail(savedNotification, recipients, attachment);

String createdAt = savedNotification.getCreatedAt() != null
? savedNotification.getCreatedAt().format(UI_TIME_FORMAT)
Expand All @@ -132,8 +135,8 @@ public LecturerNotificationCreateResponse createLecturerNotification(
return new LecturerNotificationCreateResponse(
savedNotification.getId(),
recipients.size(),
emailSummary.sentCount(),
emailSummary.failedCount(),
queuedEmailCount,
queuedEmailCount == recipients.size() ? 0 : recipients.size() - queuedEmailCount,
createdAt,
savedNotification.getAttachmentName()
);
Expand Down Expand Up @@ -258,14 +261,15 @@ public void createStudentCheckinNotification(StudentEntity student, EventEntity
}

String recipientName = StringUtils.hasText(resolvedStudent.getFullName()) ? resolvedStudent.getFullName() : "Bạn";
emailService.sendNotificationEmail(
NotificationEmailJob job = new NotificationEmailJob(
"[UniPoint] " + title,
content,
"Hệ thống UniPoint",
List.of(new EmailRecipient(email.trim(), recipientName)),
List.of(new Recipient(email.trim(), recipientName)),
null,
null
);
emailQueueService.enqueueNotificationEmail(job);
} catch (Exception ex) {
log.warn("Gửi email thông báo check-in thất bại: studentId={}, eventId={}",
student.getId(),
Expand Down Expand Up @@ -335,17 +339,17 @@ private List<StudentEntity> resolveRecipients(
return filtered;
}

private EmailSendSummary sendNotificationEmail(
private int enqueueNotificationEmail(
NotificationEntity notification,
List<StudentEntity> recipients,
StoredAttachment attachment
) {
Map<String, EmailRecipient> uniqueRecipients = new LinkedHashMap<>();
Map<String, Recipient> uniqueRecipients = new LinkedHashMap<>();

for (StudentEntity student : recipients) {
String email = student.getUserEntity().getEmail();
String normalizedEmail = email.trim().toLowerCase(Locale.ROOT);
uniqueRecipients.putIfAbsent(normalizedEmail, new EmailRecipient(email.trim(), student.getFullName()));
uniqueRecipients.putIfAbsent(normalizedEmail, new Recipient(email.trim(), student.getFullName()));
}

String senderName = "Giảng viên";
Expand All @@ -356,14 +360,42 @@ private EmailSendSummary sendNotificationEmail(
}
}

return emailService.sendNotificationEmail(
NotificationEmailJob job = new NotificationEmailJob(
"[UniPoint] " + notification.getTitle(),
notification.getContent(),
senderName,
new ArrayList<>(uniqueRecipients.values()),
attachment != null ? attachment.fileName() : null,
attachment != null ? attachment.absolutePath() : null
attachment != null ? attachment.absolutePath().toString() : null
);

if (!TransactionSynchronizationManager.isSynchronizationActive()) {
try {
emailQueueService.enqueueNotificationEmail(job);
return uniqueRecipients.size();
} catch (AmqpException ex) {
log.error("Không thể đẩy email vào queue", ex);
return 0;
}
}

TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() {
@Override
public void afterCommit() {
try {
emailQueueService.enqueueNotificationEmail(job);
log.info(
"Đã đẩy email thông báo vào queue: notificationId={}, recipients={}",
notification.getId(),
uniqueRecipients.size()
);
} catch (AmqpException ex) {
log.error("Không thể đẩy email thông báo vào queue: notificationId={}", notification.getId(), ex);
}
}
});

return uniqueRecipients.size();
}

private StoredAttachment storeAttachment(MultipartFile file) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -360,7 +360,7 @@ function EventDashboard({
}, [onCreateEventRequestHandled, shouldOpenCreateEventModal])

const content = (
<div className="flex-1 overflow-y-auto p-8">
<div className="flex-1 overflow-y-auto p-3 sm:p-5 md:p-8">
<div className="max-w-7xl mx-auto space-y-6">
<EventStats onCreateEvent={handleCreateEvent} />
<FilterBar
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -211,11 +211,11 @@ export default function LecturerNotificationCenter() {

{result && (
<div className="rounded-xl border border-emerald-200 bg-emerald-50 px-4 py-3 text-sm text-emerald-700">
<p className="font-semibold">Gửi thông báo thành công</p>
<p className="font-semibold">Thông báo đã được ghi nhận</p>
<p>
notificationId: {result.notificationId} - Người nhận: {result.totalRecipients} - Email gửi thành công:
notificationId: {result.notificationId} - Người nhận: {result.totalRecipients} - Email đã xếp hàng:
{" "}
{result.sentEmailCount}/{result.totalRecipients}
{result.queuedEmailCount}/{result.totalRecipients}
</p>
</div>
)}
Expand Down
Loading
Loading