diff --git a/backend/src/main/java/ct01/n06/backend/config/EmailRabbitMQConfig.java b/backend/src/main/java/ct01/n06/backend/config/EmailRabbitMQConfig.java new file mode 100644 index 0000000..d419a08 --- /dev/null +++ b/backend/src/main/java/ct01/n06/backend/config/EmailRabbitMQConfig.java @@ -0,0 +1,31 @@ +package ct01.n06.backend.config; + +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); + } +} \ No newline at end of file diff --git a/backend/src/main/java/ct01/n06/backend/consumer/EmailNotificationConsumer.java b/backend/src/main/java/ct01/n06/backend/consumer/EmailNotificationConsumer.java new file mode 100644 index 0000000..79ef2fe --- /dev/null +++ b/backend/src/main/java/ct01/n06/backend/consumer/EmailNotificationConsumer.java @@ -0,0 +1,62 @@ +package ct01.n06.backend.consumer; + +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 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() + ); + } +} \ No newline at end of file diff --git a/backend/src/main/java/ct01/n06/backend/dto/lecturer/LecturerNotificationCreateResponse.java b/backend/src/main/java/ct01/n06/backend/dto/lecturer/LecturerNotificationCreateResponse.java index bd99502..74a83c5 100644 --- a/backend/src/main/java/ct01/n06/backend/dto/lecturer/LecturerNotificationCreateResponse.java +++ b/backend/src/main/java/ct01/n06/backend/dto/lecturer/LecturerNotificationCreateResponse.java @@ -3,8 +3,8 @@ public record LecturerNotificationCreateResponse( Long notificationId, int totalRecipients, - int sentEmailCount, - int failedEmailCount, + int queuedEmailCount, + int failedQueueCount, String createdAt, String attachmentName ) { diff --git a/backend/src/main/java/ct01/n06/backend/dto/mail/NotificationEmailJob.java b/backend/src/main/java/ct01/n06/backend/dto/mail/NotificationEmailJob.java new file mode 100644 index 0000000..66c809a --- /dev/null +++ b/backend/src/main/java/ct01/n06/backend/dto/mail/NotificationEmailJob.java @@ -0,0 +1,16 @@ +package ct01.n06.backend.dto.mail; + +import java.util.List; + +public record NotificationEmailJob( + String subject, + String content, + String senderName, + List recipients, + String attachmentName, + String attachmentPath +) { + + public record Recipient(String email, String fullName) { + } +} \ No newline at end of file diff --git a/backend/src/main/java/ct01/n06/backend/service/EmailQueueService.java b/backend/src/main/java/ct01/n06/backend/service/EmailQueueService.java new file mode 100644 index 0000000..6dcf8c7 --- /dev/null +++ b/backend/src/main/java/ct01/n06/backend/service/EmailQueueService.java @@ -0,0 +1,30 @@ +package ct01.n06.backend.service; + +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 + ); + } +} \ No newline at end of file diff --git a/backend/src/main/java/ct01/n06/backend/service/impl/NotificationServiceImpl.java b/backend/src/main/java/ct01/n06/backend/service/impl/NotificationServiceImpl.java index d582bad..57dff41 100644 --- a/backend/src/main/java/ct01/n06/backend/service/impl/NotificationServiceImpl.java +++ b/backend/src/main/java/ct01/n06/backend/service/impl/NotificationServiceImpl.java @@ -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; @@ -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; @@ -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; @@ -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) @@ -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() ); @@ -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(), @@ -335,17 +339,17 @@ private List resolveRecipients( return filtered; } - private EmailSendSummary sendNotificationEmail( + private int enqueueNotificationEmail( NotificationEntity notification, List recipients, StoredAttachment attachment ) { - Map uniqueRecipients = new LinkedHashMap<>(); + Map 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"; @@ -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) { diff --git a/frontend/src/features/lecturer/components/EventDashboard.jsx b/frontend/src/features/lecturer/components/EventDashboard.jsx index a78ed0e..6fdec0a 100644 --- a/frontend/src/features/lecturer/components/EventDashboard.jsx +++ b/frontend/src/features/lecturer/components/EventDashboard.jsx @@ -360,7 +360,7 @@ function EventDashboard({ }, [onCreateEventRequestHandled, shouldOpenCreateEventModal]) const content = ( -
+
-

Gửi thông báo thành công

+

Thông báo đã được ghi nhận

- 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}

)} diff --git a/frontend/src/features/lecturer/components/LecturerStudentManagement.jsx b/frontend/src/features/lecturer/components/LecturerStudentManagement.jsx index d1a4601..7c002a5 100644 --- a/frontend/src/features/lecturer/components/LecturerStudentManagement.jsx +++ b/frontend/src/features/lecturer/components/LecturerStudentManagement.jsx @@ -341,6 +341,80 @@ export default function LecturerStudentManagement() { {flash.message &&
{flash.message}
} + {/* ── MOBILE: Card layout (< 768px) ── */} +
+ {pageRows.length === 0 ? ( +
Không có sinh viên phù hợp bộ lọc.
+ ) : pageRows.map((row) => ( +
+ {/* Name + badges */} +
+
+ {row.fullName} + {row.email} +
+
+ + {ROLE_LABEL[row.role] || row.role} + + + {STATUS_LABEL[row.accountStatus] || row.accountStatus} + +
+
+ + {/* Meta */} +
+ 📋 {row.studentCode} · {row.classCode} + ⭐ {row.totalPoint ?? 0} điểm + 🎯 {row.mandatoryStatus} +
+ + {/* Actions */} +
+ + + +
+
+ ))} +
+ + {/* ── DESKTOP: Table layout (≥ 768px) ── */}
@@ -390,41 +464,25 @@ export default function LecturerStudentManagement() { title="Gán lớp trưởng" onClick={() => runAction( - () => - apiRequest( - `/lecturer/students/${row.studentId}/monitor?lecturerId=${lecturerId}`, - { method: "PUT" }, - ), + () => apiRequest(`/lecturer/students/${row.studentId}/monitor?lecturerId=${lecturerId}`, { method: "PUT" }), `Đã gán ${row.fullName} làm lớp trưởng.`, ) } - > - ☆ - + >☆ + >{row.accountStatus === "LOCKED" ? "🔓" : "🔒"} + >🗑 @@ -456,24 +508,24 @@ export default function LecturerStudentManagement() { Hiển thị {(currentPage - 1) * PAGE_SIZE + (pageRows.length ? 1 : 0)} - {(currentPage - 1) * PAGE_SIZE + pageRows.length} trong tổng số {filteredCount} sinh viên
- + {currentPage} - +
+ + {/* Mobile pagination */} +
+ + Trang {currentPage} / {totalPages} · {filteredCount} sinh viên + +
+ + {currentPage} + +
+
{showManualModal && ( diff --git a/frontend/src/shared/components/CreateEventModal.jsx b/frontend/src/shared/components/CreateEventModal.jsx index 8f65ea0..5339a49 100644 --- a/frontend/src/shared/components/CreateEventModal.jsx +++ b/frontend/src/shared/components/CreateEventModal.jsx @@ -310,10 +310,10 @@ function CreateEventModal({ isOpen, onClose, onSuccess, initialEvent = null }) { } return ( -
-
+
+
{/* Header */} -
+

{isEditMode ? 'Cập nhật sự kiện' : 'Tạo sự kiện mới'}

@@ -331,7 +331,7 @@ function CreateEventModal({ isOpen, onClose, onSuccess, initialEvent = null }) { {/* Scrollable body */}

-
+ {error && (
{error} @@ -339,7 +339,7 @@ function CreateEventModal({ isOpen, onClose, onSuccess, initialEvent = null }) { )} {/* Desktop: 2 columns side by side | Mobile: single column */} -
+
{/* ── LEFT COLUMN ── */}
@@ -392,10 +392,10 @@ function CreateEventModal({ isOpen, onClose, onSuccess, initialEvent = null }) { Mô tả sự kiện