From 82c418cfc45e4f87c9aac03b4937fdc737dc7be4 Mon Sep 17 00:00:00 2001 From: MinhToanSBO Date: Sat, 18 Apr 2026 11:06:25 +0700 Subject: [PATCH 1/8] =?UTF-8?q?ADD:=20Th=C3=AAm=20t=C3=ADnh=20n=C4=83ng=20?= =?UTF-8?q?khai=20b=C3=A1o=20minh=20ch=E1=BB=A9ng=20v=C3=A0=20duy=E1=BB=87?= =?UTF-8?q?t=20minh=20ch=E1=BB=A9ng?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../n06/backend/constant/RecordConstant.java | 2 + .../MonitorEvidenceDeclarationController.java | 64 +++ .../StudentEvidenceDeclarationController.java | 70 +++ .../CreateEvidenceDeclarationRequest.java | 18 + .../EvidenceDeclarationDetailResponse.java | 24 + .../EvidenceDeclarationItemResponse.java | 15 + .../EvidenceDeclarationListResponse.java | 12 + .../ReviewEvidenceDeclarationRequest.java | 7 + .../UpdateEvidenceDeclarationRequest.java | 16 + .../ct01/n06/backend/entity/RecordEntity.java | 6 + .../backend/repository/RecordRepository.java | 42 ++ .../service/EvidenceDeclarationService.java | 37 ++ .../impl/EvidenceDeclarationServiceImpl.java | 372 +++++++++++++++ .../service/impl/RecordServiceImpl.java | 3 + frontend/src/api/evidenceDeclarationApi.js | 64 +++ .../monitor/components/MonitorClass.jsx | 312 ++----------- .../components/MonitorClassMembersTab.jsx | 137 ++++++ .../components/MonitorEvidenceReviewTab.jsx | 329 +++++++++++++ .../components/MonitorScoreManagementTab.jsx | 302 ++++++++++++ .../features/student/components/QRScanner.jsx | 397 ++++++---------- .../StudentEvidenceDeclarationPanel.jsx | 432 ++++++++++++++++++ .../hooks/useStudentEvidenceDeclarations.js | 105 +++++ frontend/src/pages/StudentPage.jsx | 9 +- 23 files changed, 2230 insertions(+), 545 deletions(-) create mode 100644 backend/src/main/java/ct01/n06/backend/controller/monitor/MonitorEvidenceDeclarationController.java create mode 100644 backend/src/main/java/ct01/n06/backend/controller/student/StudentEvidenceDeclarationController.java create mode 100644 backend/src/main/java/ct01/n06/backend/dto/evidence/CreateEvidenceDeclarationRequest.java create mode 100644 backend/src/main/java/ct01/n06/backend/dto/evidence/EvidenceDeclarationDetailResponse.java create mode 100644 backend/src/main/java/ct01/n06/backend/dto/evidence/EvidenceDeclarationItemResponse.java create mode 100644 backend/src/main/java/ct01/n06/backend/dto/evidence/EvidenceDeclarationListResponse.java create mode 100644 backend/src/main/java/ct01/n06/backend/dto/evidence/ReviewEvidenceDeclarationRequest.java create mode 100644 backend/src/main/java/ct01/n06/backend/dto/evidence/UpdateEvidenceDeclarationRequest.java create mode 100644 backend/src/main/java/ct01/n06/backend/service/EvidenceDeclarationService.java create mode 100644 backend/src/main/java/ct01/n06/backend/service/impl/EvidenceDeclarationServiceImpl.java create mode 100644 frontend/src/api/evidenceDeclarationApi.js create mode 100644 frontend/src/features/monitor/components/MonitorClassMembersTab.jsx create mode 100644 frontend/src/features/monitor/components/MonitorEvidenceReviewTab.jsx create mode 100644 frontend/src/features/monitor/components/MonitorScoreManagementTab.jsx create mode 100644 frontend/src/features/student/components/StudentEvidenceDeclarationPanel.jsx create mode 100644 frontend/src/features/student/hooks/useStudentEvidenceDeclarations.js diff --git a/backend/src/main/java/ct01/n06/backend/constant/RecordConstant.java b/backend/src/main/java/ct01/n06/backend/constant/RecordConstant.java index 4641382..8d7ecf1 100644 --- a/backend/src/main/java/ct01/n06/backend/constant/RecordConstant.java +++ b/backend/src/main/java/ct01/n06/backend/constant/RecordConstant.java @@ -16,4 +16,6 @@ private RecordConstant() { public static final String COL_ACTIVITY_TIME = "activity_time"; public static final String COL_STATUS = "status"; public static final String COL_APPROVER_ID = "approver_id"; + public static final String COL_REVIEW_NOTE = "review_note"; + public static final String COL_REVIEWED_AT = "reviewed_at"; } diff --git a/backend/src/main/java/ct01/n06/backend/controller/monitor/MonitorEvidenceDeclarationController.java b/backend/src/main/java/ct01/n06/backend/controller/monitor/MonitorEvidenceDeclarationController.java new file mode 100644 index 0000000..81debda --- /dev/null +++ b/backend/src/main/java/ct01/n06/backend/controller/monitor/MonitorEvidenceDeclarationController.java @@ -0,0 +1,64 @@ +package ct01.n06.backend.controller.monitor; + +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import ct01.n06.backend.dto.evidence.EvidenceDeclarationDetailResponse; +import ct01.n06.backend.dto.evidence.EvidenceDeclarationListResponse; +import ct01.n06.backend.dto.evidence.ReviewEvidenceDeclarationRequest; +import ct01.n06.backend.entity.enums.RecordStatus; +import ct01.n06.backend.service.EvidenceDeclarationService; +import ct01.n06.backend.service.UserService; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; + +@RestController +@RequestMapping("/v1/monitor/evidence-declarations") +@RequiredArgsConstructor +public class MonitorEvidenceDeclarationController { + + private final EvidenceDeclarationService evidenceDeclarationService; + private final UserService userService; + + @PreAuthorize("hasRole('MONITOR')") + @GetMapping + public EvidenceDeclarationListResponse getDeclarations( + @RequestParam(required = false) RecordStatus status, + @RequestParam(required = false) Long semesterId, + @RequestParam(defaultValue = "0") int page, + @RequestParam(defaultValue = "20") int size) { + return evidenceDeclarationService.getMonitorDeclarations( + userService.requireCurrentUserId(), status, semesterId, page, size); + } + + @PreAuthorize("hasRole('MONITOR')") + @GetMapping("/{declarationId}") + public EvidenceDeclarationDetailResponse getDeclarationDetail(@PathVariable Long declarationId) { + return evidenceDeclarationService.getMonitorDeclarationDetail( + userService.requireCurrentUserId(), declarationId); + } + + @PreAuthorize("hasRole('MONITOR')") + @PostMapping("/{declarationId}/approve") + public EvidenceDeclarationDetailResponse approveMonitorDeclaration( + @PathVariable Long declarationId, + @RequestBody @Valid ReviewEvidenceDeclarationRequest request) { + return evidenceDeclarationService.approveMonitorDeclaration( + userService.requireCurrentUserId(), declarationId, request); + } + + @PreAuthorize("hasRole('MONITOR')") + @PostMapping("/{declarationId}/reject") + public EvidenceDeclarationDetailResponse rejectMonitorDeclaration( + @PathVariable Long declarationId, + @RequestBody @Valid ReviewEvidenceDeclarationRequest request) { + return evidenceDeclarationService.rejectMonitorDeclaration( + userService.requireCurrentUserId(), declarationId, request); + } +} diff --git a/backend/src/main/java/ct01/n06/backend/controller/student/StudentEvidenceDeclarationController.java b/backend/src/main/java/ct01/n06/backend/controller/student/StudentEvidenceDeclarationController.java new file mode 100644 index 0000000..37959c1 --- /dev/null +++ b/backend/src/main/java/ct01/n06/backend/controller/student/StudentEvidenceDeclarationController.java @@ -0,0 +1,70 @@ +package ct01.n06.backend.controller.student; + +import org.springframework.security.access.prepost.PreAuthorize; +import org.springframework.web.bind.annotation.DeleteMapping; +import org.springframework.web.bind.annotation.GetMapping; +import org.springframework.web.bind.annotation.PathVariable; +import org.springframework.web.bind.annotation.PostMapping; +import org.springframework.web.bind.annotation.PutMapping; +import org.springframework.web.bind.annotation.RequestBody; +import org.springframework.web.bind.annotation.RequestMapping; +import org.springframework.web.bind.annotation.RequestParam; +import org.springframework.web.bind.annotation.RestController; + +import ct01.n06.backend.dto.common.SimpleMessageResponse; +import ct01.n06.backend.dto.evidence.CreateEvidenceDeclarationRequest; +import ct01.n06.backend.dto.evidence.EvidenceDeclarationDetailResponse; +import ct01.n06.backend.dto.evidence.EvidenceDeclarationListResponse; +import ct01.n06.backend.dto.evidence.UpdateEvidenceDeclarationRequest; +import ct01.n06.backend.entity.enums.RecordStatus; +import ct01.n06.backend.service.EvidenceDeclarationService; +import ct01.n06.backend.service.UserService; +import jakarta.validation.Valid; +import lombok.RequiredArgsConstructor; + +@RestController +@RequestMapping("/v1/student/evidence-declarations") +@RequiredArgsConstructor +public class StudentEvidenceDeclarationController { + + private final EvidenceDeclarationService evidenceDeclarationService; + private final UserService userService; + + @PreAuthorize("hasAnyRole('STUDENT', 'MONITOR')") + @PostMapping + public EvidenceDeclarationDetailResponse createDeclaration( + @RequestBody @Valid CreateEvidenceDeclarationRequest request) { + return evidenceDeclarationService.createStudentDeclaration(userService.requireCurrentUserId(), request); + } + + @PreAuthorize("hasAnyRole('STUDENT', 'MONITOR')") + @GetMapping + public EvidenceDeclarationListResponse getDeclarations( + @RequestParam(required = false) RecordStatus status, + @RequestParam(required = false) Long semesterId, + @RequestParam(defaultValue = "0") int page, + @RequestParam(defaultValue = "20") int size) { + return evidenceDeclarationService.getStudentDeclarations(userService.requireCurrentUserId(), status, + semesterId, page, size); + } + + @PreAuthorize("hasAnyRole('STUDENT', 'MONITOR')") + @GetMapping("/{declarationId}") + public EvidenceDeclarationDetailResponse getDeclarationDetail(@PathVariable Long declarationId) { + return evidenceDeclarationService.getStudentDeclarationDetail(userService.requireCurrentUserId(), declarationId); + } + + @PreAuthorize("hasAnyRole('STUDENT', 'MONITOR')") + @PutMapping("/{declarationId}") + public EvidenceDeclarationDetailResponse updateDeclaration(@PathVariable Long declarationId, + @RequestBody @Valid UpdateEvidenceDeclarationRequest request) { + return evidenceDeclarationService.updateStudentDeclaration(userService.requireCurrentUserId(), declarationId, + request); + } + + @PreAuthorize("hasAnyRole('STUDENT', 'MONITOR')") + @DeleteMapping("/{declarationId}") + public SimpleMessageResponse deleteDeclaration(@PathVariable Long declarationId) { + return evidenceDeclarationService.deleteStudentDeclaration(userService.requireCurrentUserId(), declarationId); + } +} diff --git a/backend/src/main/java/ct01/n06/backend/dto/evidence/CreateEvidenceDeclarationRequest.java b/backend/src/main/java/ct01/n06/backend/dto/evidence/CreateEvidenceDeclarationRequest.java new file mode 100644 index 0000000..6950741 --- /dev/null +++ b/backend/src/main/java/ct01/n06/backend/dto/evidence/CreateEvidenceDeclarationRequest.java @@ -0,0 +1,18 @@ +package ct01.n06.backend.dto.evidence; + +import java.time.LocalDate; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; + +public record CreateEvidenceDeclarationRequest( + @NotNull(message = "Học kỳ là bắt buộc.") + Long semesterId, + @NotBlank(message = "Tên minh chứng không được để trống.") + String customName, + @NotBlank(message = "Đường dẫn minh chứng không được để trống.") + String evidenceUrl, + @NotNull(message = "Ngày hoạt động là bắt buộc.") + LocalDate activityDate +) { +} diff --git a/backend/src/main/java/ct01/n06/backend/dto/evidence/EvidenceDeclarationDetailResponse.java b/backend/src/main/java/ct01/n06/backend/dto/evidence/EvidenceDeclarationDetailResponse.java new file mode 100644 index 0000000..77f77fd --- /dev/null +++ b/backend/src/main/java/ct01/n06/backend/dto/evidence/EvidenceDeclarationDetailResponse.java @@ -0,0 +1,24 @@ +package ct01.n06.backend.dto.evidence; + +public record EvidenceDeclarationDetailResponse( + Long id, + String studentId, + String studentName, + Long classId, + String classCode, + Long semesterId, + String semesterName, + Long criteriaId, + String criteriaCode, + String criteriaName, + String customName, + String evidenceUrl, + String activityTime, + String status, + String reviewNote, + String approverId, + String approverName, + String createdAt, + String reviewedAt +) { +} diff --git a/backend/src/main/java/ct01/n06/backend/dto/evidence/EvidenceDeclarationItemResponse.java b/backend/src/main/java/ct01/n06/backend/dto/evidence/EvidenceDeclarationItemResponse.java new file mode 100644 index 0000000..3108167 --- /dev/null +++ b/backend/src/main/java/ct01/n06/backend/dto/evidence/EvidenceDeclarationItemResponse.java @@ -0,0 +1,15 @@ +package ct01.n06.backend.dto.evidence; + +public record EvidenceDeclarationItemResponse( + Long id, + String studentName, + String customName, + String evidenceUrl, + String semesterName, + String activityTime, + String status, + String reviewNote, + String createdAt, + String reviewedAt +) { +} diff --git a/backend/src/main/java/ct01/n06/backend/dto/evidence/EvidenceDeclarationListResponse.java b/backend/src/main/java/ct01/n06/backend/dto/evidence/EvidenceDeclarationListResponse.java new file mode 100644 index 0000000..61b2b02 --- /dev/null +++ b/backend/src/main/java/ct01/n06/backend/dto/evidence/EvidenceDeclarationListResponse.java @@ -0,0 +1,12 @@ +package ct01.n06.backend.dto.evidence; + +import java.util.List; + +public record EvidenceDeclarationListResponse( + int page, + int size, + long totalItems, + int totalPages, + List items +) { +} diff --git a/backend/src/main/java/ct01/n06/backend/dto/evidence/ReviewEvidenceDeclarationRequest.java b/backend/src/main/java/ct01/n06/backend/dto/evidence/ReviewEvidenceDeclarationRequest.java new file mode 100644 index 0000000..bce75dc --- /dev/null +++ b/backend/src/main/java/ct01/n06/backend/dto/evidence/ReviewEvidenceDeclarationRequest.java @@ -0,0 +1,7 @@ +package ct01.n06.backend.dto.evidence; + +public record ReviewEvidenceDeclarationRequest( + Long criteriaId, + String reviewNote +) { +} diff --git a/backend/src/main/java/ct01/n06/backend/dto/evidence/UpdateEvidenceDeclarationRequest.java b/backend/src/main/java/ct01/n06/backend/dto/evidence/UpdateEvidenceDeclarationRequest.java new file mode 100644 index 0000000..60397f5 --- /dev/null +++ b/backend/src/main/java/ct01/n06/backend/dto/evidence/UpdateEvidenceDeclarationRequest.java @@ -0,0 +1,16 @@ +package ct01.n06.backend.dto.evidence; + +import java.time.LocalDate; + +import jakarta.validation.constraints.NotBlank; +import jakarta.validation.constraints.NotNull; + +public record UpdateEvidenceDeclarationRequest( + @NotBlank(message = "Tên minh chứng không được để trống.") + String customName, + @NotBlank(message = "Đường dẫn minh chứng không được để trống.") + String evidenceUrl, + @NotNull(message = "Ngày hoạt động là bắt buộc.") + LocalDate activityDate +) { +} diff --git a/backend/src/main/java/ct01/n06/backend/entity/RecordEntity.java b/backend/src/main/java/ct01/n06/backend/entity/RecordEntity.java index 336ba52..bcd5646 100644 --- a/backend/src/main/java/ct01/n06/backend/entity/RecordEntity.java +++ b/backend/src/main/java/ct01/n06/backend/entity/RecordEntity.java @@ -69,4 +69,10 @@ public class RecordEntity extends BaseJpaAuditingEntity { @ManyToOne(fetch = FetchType.LAZY) @JoinColumn(name = RecordConstant.COL_APPROVER_ID) private UserEntity approver; + + @Column(name = RecordConstant.COL_REVIEW_NOTE, length = 1000) + private String reviewNote; + + @Column(name = RecordConstant.COL_REVIEWED_AT) + private LocalDateTime reviewedAt; } \ No newline at end of file diff --git a/backend/src/main/java/ct01/n06/backend/repository/RecordRepository.java b/backend/src/main/java/ct01/n06/backend/repository/RecordRepository.java index dda212a..c974374 100644 --- a/backend/src/main/java/ct01/n06/backend/repository/RecordRepository.java +++ b/backend/src/main/java/ct01/n06/backend/repository/RecordRepository.java @@ -62,6 +62,48 @@ Optional findByStudentAndSemesterAndEvent( List findByStudent_IdAndSemester_IdAndStatus(String studentId, Long semesterId, RecordStatus status); + @EntityGraph(attributePaths = {"semester", "criteria", "approver"}) + @Query(""" + select r + from RecordEntity r + where r.event is null + and r.student.id = :studentId + and (:status is null or r.status = :status) + and (:semesterId is null or r.semester.id = :semesterId) + order by r.createdAt desc + """) + Page findEvidenceDeclarationsForStudent( + @Param("studentId") String studentId, + @Param("status") RecordStatus status, + @Param("semesterId") Long semesterId, + Pageable pageable + ); + + @EntityGraph(attributePaths = {"student", "student.classEntity", "semester", "criteria", "approver"}) + @Query(""" + select r + from RecordEntity r + join r.student s + left join s.classEntity c + where r.event is null + and c.id = :classId + and (:status is null or r.status = :status) + and (:semesterId is null or r.semester.id = :semesterId) + order by r.createdAt desc + """) + Page findEvidenceDeclarationsForClass( + @Param("classId") Long classId, + @Param("status") RecordStatus status, + @Param("semesterId") Long semesterId, + Pageable pageable + ); + + @EntityGraph(attributePaths = {"semester", "criteria", "approver"}) + Optional findByIdAndStudent_IdAndEventIsNull(Long id, String studentId); + + @EntityGraph(attributePaths = {"student", "student.classEntity", "semester", "criteria", "approver"}) + Optional findByIdAndEventIsNull(Long id); + long countDistinctStudent_IdByEvent_IdAndStatus(Long eventId, RecordStatus status); @Query(""" diff --git a/backend/src/main/java/ct01/n06/backend/service/EvidenceDeclarationService.java b/backend/src/main/java/ct01/n06/backend/service/EvidenceDeclarationService.java new file mode 100644 index 0000000..b352c22 --- /dev/null +++ b/backend/src/main/java/ct01/n06/backend/service/EvidenceDeclarationService.java @@ -0,0 +1,37 @@ +package ct01.n06.backend.service; + +import ct01.n06.backend.dto.common.SimpleMessageResponse; +import ct01.n06.backend.dto.evidence.CreateEvidenceDeclarationRequest; +import ct01.n06.backend.dto.evidence.EvidenceDeclarationDetailResponse; +import ct01.n06.backend.dto.evidence.EvidenceDeclarationListResponse; +import ct01.n06.backend.dto.evidence.ReviewEvidenceDeclarationRequest; +import ct01.n06.backend.dto.evidence.UpdateEvidenceDeclarationRequest; +import ct01.n06.backend.entity.enums.RecordStatus; + +public interface EvidenceDeclarationService { + + EvidenceDeclarationDetailResponse createStudentDeclaration(String userId, + CreateEvidenceDeclarationRequest request); + + EvidenceDeclarationListResponse getStudentDeclarations(String userId, RecordStatus status, + Long semesterId, int page, int size); + + EvidenceDeclarationDetailResponse getStudentDeclarationDetail(String userId, Long declarationId); + + EvidenceDeclarationDetailResponse updateStudentDeclaration(String userId, Long declarationId, + UpdateEvidenceDeclarationRequest request); + + SimpleMessageResponse deleteStudentDeclaration(String userId, Long declarationId); + + EvidenceDeclarationListResponse getMonitorDeclarations(String userId, RecordStatus status, + Long semesterId, int page, int size); + + EvidenceDeclarationDetailResponse getMonitorDeclarationDetail(String userId, Long declarationId); + + EvidenceDeclarationDetailResponse approveMonitorDeclaration(String userId, Long declarationId, + ReviewEvidenceDeclarationRequest request); + + EvidenceDeclarationDetailResponse rejectMonitorDeclaration(String userId, Long declarationId, + ReviewEvidenceDeclarationRequest request); + +} diff --git a/backend/src/main/java/ct01/n06/backend/service/impl/EvidenceDeclarationServiceImpl.java b/backend/src/main/java/ct01/n06/backend/service/impl/EvidenceDeclarationServiceImpl.java new file mode 100644 index 0000000..43e7e0b --- /dev/null +++ b/backend/src/main/java/ct01/n06/backend/service/impl/EvidenceDeclarationServiceImpl.java @@ -0,0 +1,372 @@ +package ct01.n06.backend.service.impl; + +import java.time.LocalDateTime; +import java.time.format.DateTimeFormatter; + +import org.springframework.data.domain.Page; +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.util.StringUtils; + +import ct01.n06.backend.dto.common.SimpleMessageResponse; +import ct01.n06.backend.dto.evidence.CreateEvidenceDeclarationRequest; +import ct01.n06.backend.dto.evidence.EvidenceDeclarationDetailResponse; +import ct01.n06.backend.dto.evidence.EvidenceDeclarationItemResponse; +import ct01.n06.backend.dto.evidence.EvidenceDeclarationListResponse; +import ct01.n06.backend.dto.evidence.ReviewEvidenceDeclarationRequest; +import ct01.n06.backend.dto.evidence.UpdateEvidenceDeclarationRequest; +import ct01.n06.backend.entity.ClassEntity; +import ct01.n06.backend.entity.CriteriaEntity; +import ct01.n06.backend.entity.NotificationEntity; +import ct01.n06.backend.entity.NotificationRecipientEntity; +import ct01.n06.backend.entity.RecordEntity; +import ct01.n06.backend.entity.SemesterEntity; +import ct01.n06.backend.entity.StudentEntity; +import ct01.n06.backend.entity.UserEntity; +import ct01.n06.backend.entity.enums.NotificationType; +import ct01.n06.backend.entity.enums.RecordStatus; +import ct01.n06.backend.exception.ApiException; +import ct01.n06.backend.repository.ClassRepository; +import ct01.n06.backend.repository.CriteriaRepository; +import ct01.n06.backend.repository.NotificationRecipientRepository; +import ct01.n06.backend.repository.NotificationRepository; +import ct01.n06.backend.repository.RecordRepository; +import ct01.n06.backend.repository.SemesterRepository; +import ct01.n06.backend.repository.StudentRepository; +import ct01.n06.backend.service.EvidenceDeclarationService; +import ct01.n06.backend.service.UserService; + +@Service +public class EvidenceDeclarationServiceImpl implements EvidenceDeclarationService { + + private static final DateTimeFormatter UI_TIME_FORMAT = DateTimeFormatter.ofPattern("dd/MM/yyyy HH:mm"); + private static final int MAX_PAGE_SIZE = 100; + + private final RecordRepository recordRepository; + private final StudentRepository studentRepository; + private final ClassRepository classRepository; + private final SemesterRepository semesterRepository; + private final CriteriaRepository criteriaRepository; + private final UserService userService; + private final NotificationRepository notificationRepository; + private final NotificationRecipientRepository notificationRecipientRepository; + + public EvidenceDeclarationServiceImpl(RecordRepository recordRepository, + StudentRepository studentRepository, + ClassRepository classRepository, + SemesterRepository semesterRepository, + CriteriaRepository criteriaRepository, + UserService userService, + NotificationRepository notificationRepository, + NotificationRecipientRepository notificationRecipientRepository) { + this.recordRepository = recordRepository; + this.studentRepository = studentRepository; + this.classRepository = classRepository; + this.semesterRepository = semesterRepository; + this.criteriaRepository = criteriaRepository; + this.userService = userService; + this.notificationRepository = notificationRepository; + this.notificationRecipientRepository = notificationRecipientRepository; + } + + @Override + @Transactional + public EvidenceDeclarationDetailResponse createStudentDeclaration(String userId, + CreateEvidenceDeclarationRequest request) { + StudentEntity student = getStudentByUserId(userId); + SemesterEntity semester = getSemesterById(request.semesterId()); + + validateUrl(request.evidenceUrl()); + + RecordEntity declaration = RecordEntity.builder() + .student(student) + .semester(semester) + .event(null) + .criteria(null) + .customName(request.customName().trim()) + .evidenceUrl(request.evidenceUrl().trim()) + .activityTime(request.activityDate().atStartOfDay()) + .status(RecordStatus.PENDING) + .approver(null) + .reviewNote(null) + .reviewedAt(null) + .build(); + + return toDetailResponse(recordRepository.save(declaration)); + } + + @Override + @Transactional(readOnly = true) + public EvidenceDeclarationListResponse getStudentDeclarations(String userId, RecordStatus status, + Long semesterId, int page, int size) { + StudentEntity student = getStudentByUserId(userId); + Page declarations = recordRepository.findEvidenceDeclarationsForStudent( + student.getId(), + status, + semesterId, + buildPageRequest(page, size) + ); + return toListResponse(declarations); + } + + @Override + @Transactional(readOnly = true) + public EvidenceDeclarationDetailResponse getStudentDeclarationDetail(String userId, Long declarationId) { + StudentEntity student = getStudentByUserId(userId); + RecordEntity declaration = getStudentDeclarationOrThrow(student.getId(), declarationId); + return toDetailResponse(declaration); + } + + @Override + @Transactional + public EvidenceDeclarationDetailResponse updateStudentDeclaration(String userId, Long declarationId, + UpdateEvidenceDeclarationRequest request) { + StudentEntity student = getStudentByUserId(userId); + RecordEntity declaration = getStudentDeclarationOrThrow(student.getId(), declarationId); + + ensurePending(declaration); + validateUrl(request.evidenceUrl()); + + declaration.setCustomName(request.customName().trim()); + declaration.setEvidenceUrl(request.evidenceUrl().trim()); + declaration.setActivityTime(request.activityDate().atStartOfDay()); + + return toDetailResponse(recordRepository.save(declaration)); + } + + @Override + @Transactional + public SimpleMessageResponse deleteStudentDeclaration(String userId, Long declarationId) { + StudentEntity student = getStudentByUserId(userId); + RecordEntity declaration = getStudentDeclarationOrThrow(student.getId(), declarationId); + + ensurePending(declaration); + recordRepository.delete(declaration); + return new SimpleMessageResponse("Đã xóa minh chứng thành công."); + } + + @Override + @Transactional(readOnly = true) + public EvidenceDeclarationListResponse getMonitorDeclarations(String userId, RecordStatus status, + Long semesterId, int page, int size) { + ClassEntity managedClass = getMonitorManagedClass(userId); + Page declarations = recordRepository.findEvidenceDeclarationsForClass( + managedClass.getId(), + status, + semesterId, + buildPageRequest(page, size) + ); + return toListResponse(declarations); + } + + @Override + @Transactional(readOnly = true) + public EvidenceDeclarationDetailResponse getMonitorDeclarationDetail(String userId, Long declarationId) { + ClassEntity managedClass = getMonitorManagedClass(userId); + RecordEntity declaration = getDeclarationForClassScope(declarationId, managedClass.getId()); + return toDetailResponse(declaration); + } + + @Override + @Transactional + public EvidenceDeclarationDetailResponse approveMonitorDeclaration(String userId, Long declarationId, + ReviewEvidenceDeclarationRequest request) { + return processMonitorReview(userId, declarationId, request, RecordStatus.APPROVED); + } + + @Override + @Transactional + public EvidenceDeclarationDetailResponse rejectMonitorDeclaration(String userId, Long declarationId, + ReviewEvidenceDeclarationRequest request) { + return processMonitorReview(userId, declarationId, request, RecordStatus.REJECTED); + } + + private EvidenceDeclarationDetailResponse processMonitorReview(String userId, Long declarationId, + ReviewEvidenceDeclarationRequest request, RecordStatus targetStatus) { + ClassEntity managedClass = getMonitorManagedClass(userId); + RecordEntity declaration = getDeclarationForClassScope(declarationId, managedClass.getId()); + ensurePending(declaration); + + String reviewNote = normalizeReviewNote(request != null ? request.reviewNote() : null); + + CriteriaEntity criteria = resolveCriteriaForApproval(request, targetStatus); + + UserEntity approver = userService.requireCurrentUser(); + declaration.setStatus(targetStatus); + declaration.setCriteria(criteria); + declaration.setReviewNote(reviewNote); + declaration.setApprover(approver); + declaration.setReviewedAt(LocalDateTime.now()); + + RecordEntity saved = recordRepository.save(declaration); + createResultNotification(saved, targetStatus == RecordStatus.APPROVED); + return toDetailResponse(saved); + } + + private CriteriaEntity resolveCriteriaForApproval(ReviewEvidenceDeclarationRequest request, + RecordStatus targetStatus) { + if (targetStatus != RecordStatus.APPROVED || request == null || request.criteriaId() == null) { + return null; + } + + return criteriaRepository.findById(request.criteriaId()) + .orElseThrow(() -> new ApiException(HttpStatus.BAD_REQUEST, "Tiêu chí không tồn tại.")); + } + + private StudentEntity getStudentByUserId(String userId) { + return studentRepository.findByUserEntityId(userId) + .orElseThrow(() -> new ApiException(HttpStatus.NOT_FOUND, "Không tìm thấy thông tin sinh viên.")); + } + + private SemesterEntity getSemesterById(Long semesterId) { + return semesterRepository.findById(semesterId) + .orElseThrow(() -> new ApiException(HttpStatus.BAD_REQUEST, "Học kỳ không tồn tại.")); + } + + private RecordEntity getStudentDeclarationOrThrow(String studentId, Long declarationId) { + return recordRepository.findByIdAndStudent_IdAndEventIsNull(declarationId, studentId) + .orElseThrow(() -> new ApiException(HttpStatus.NOT_FOUND, "Không tìm thấy minh chứng.")); + } + + private RecordEntity getDeclarationForClassScope(Long declarationId, Long classId) { + RecordEntity declaration = recordRepository.findByIdAndEventIsNull(declarationId) + .orElseThrow(() -> new ApiException(HttpStatus.NOT_FOUND, "Không tìm thấy minh chứng.")); + + if (declaration.getStudent() == null + || declaration.getStudent().getClassEntity() == null + || !classId.equals(declaration.getStudent().getClassEntity().getId())) { + throw new ApiException(HttpStatus.FORBIDDEN, "Bạn không có quyền duyệt minh chứng này."); + } + + return declaration; + } + + private ClassEntity getMonitorManagedClass(String userId) { + StudentEntity monitorStudent = getStudentByUserId(userId); + return classRepository.findByMonitor_Id(monitorStudent.getId()) + .orElseThrow(() -> new ApiException(HttpStatus.FORBIDDEN, + "Bạn không có quyền thao tác minh chứng.")); + } + + private void ensurePending(RecordEntity declaration) { + if (declaration.getStatus() != RecordStatus.PENDING) { + throw new ApiException(HttpStatus.CONFLICT, + "Minh chứng đã được xử lý, không thể thay đổi thêm."); + } + } + + private void validateUrl(String url) { + if (!StringUtils.hasText(url)) { + throw new ApiException(HttpStatus.BAD_REQUEST, "Đường dẫn minh chứng không được để trống."); + } + + String normalized = url.trim().toLowerCase(); + if (!normalized.startsWith("http://") && !normalized.startsWith("https://")) { + throw new ApiException(HttpStatus.BAD_REQUEST, + "Đường dẫn minh chứng phải bắt đầu bằng http:// hoặc https://"); + } + } + + private String normalizeReviewNote(String reviewNote) { + if (!StringUtils.hasText(reviewNote)) { + return null; + } + return reviewNote.trim(); + } + + private void createResultNotification(RecordEntity declaration, boolean approved) { + if (declaration.getStudent() == null) { + return; + } + + String statusLabel = approved ? "Đã duyệt" : "Từ chối"; + String title = "Kết quả duyệt minh chứng"; + String content = "Minh chứng '" + declaration.getCustomName() + "' đã được cập nhật trạng thái: " + + statusLabel + "."; + + if (!approved && StringUtils.hasText(declaration.getReviewNote())) { + content += " Lý do: " + declaration.getReviewNote(); + } + + NotificationEntity notification = NotificationEntity.builder() + .sender(declaration.getApprover()) + .title(title) + .content(content) + .targetType(NotificationType.STUDENT) + .classEntity(declaration.getStudent().getClassEntity()) + .attachmentName(null) + .attachmentPath(null) + .build(); + + NotificationEntity saved = notificationRepository.save(notification); + NotificationRecipientEntity recipient = NotificationRecipientEntity.builder() + .notification(saved) + .student(declaration.getStudent()) + .read(false) + .readAt(null) + .build(); + + notificationRecipientRepository.save(recipient); + } + + private EvidenceDeclarationListResponse toListResponse(Page page) { + return new EvidenceDeclarationListResponse( + page.getNumber(), + page.getSize(), + page.getTotalElements(), + page.getTotalPages(), + page.getContent().stream().map(this::toItemResponse).toList() + ); + } + + private EvidenceDeclarationItemResponse toItemResponse(RecordEntity record) { + return new EvidenceDeclarationItemResponse( + record.getId(), + record.getStudent() != null ? record.getStudent().getFullName() : null, + record.getCustomName(), + record.getEvidenceUrl(), + record.getSemester() != null ? record.getSemester().getName() : null, + formatDateTime(record.getActivityTime()), + record.getStatus() != null ? record.getStatus().name() : RecordStatus.PENDING.name(), + record.getReviewNote(), + formatDateTime(record.getCreatedAt()), + formatDateTime(record.getReviewedAt()) + ); + } + + private EvidenceDeclarationDetailResponse toDetailResponse(RecordEntity record) { + return new EvidenceDeclarationDetailResponse( + record.getId(), + record.getStudent() != null ? record.getStudent().getId() : null, + record.getStudent() != null ? record.getStudent().getFullName() : null, + record.getStudent() != null && record.getStudent().getClassEntity() != null + ? record.getStudent().getClassEntity().getId() : null, + record.getStudent() != null && record.getStudent().getClassEntity() != null + ? record.getStudent().getClassEntity().getClassCode() : null, + record.getSemester() != null ? record.getSemester().getId() : null, + record.getSemester() != null ? record.getSemester().getName() : null, + record.getCriteria() != null ? record.getCriteria().getId() : null, + record.getCriteria() != null ? record.getCriteria().getCode() : null, + record.getCriteria() != null ? record.getCriteria().getName() : null, + record.getCustomName(), + record.getEvidenceUrl(), + formatDateTime(record.getActivityTime()), + record.getStatus() != null ? record.getStatus().name() : RecordStatus.PENDING.name(), + record.getReviewNote(), + record.getApprover() != null ? record.getApprover().getId() : null, + record.getApprover() != null ? record.getApprover().getUsername() : null, + formatDateTime(record.getCreatedAt()), + formatDateTime(record.getReviewedAt()) + ); + } + + private String formatDateTime(LocalDateTime value) { + return value != null ? value.format(UI_TIME_FORMAT) : null; + } + + private PageRequest buildPageRequest(int page, int size) { + return PageRequest.of(Math.max(page, 0), Math.min(Math.max(size, 1), MAX_PAGE_SIZE)); + } +} \ No newline at end of file diff --git a/backend/src/main/java/ct01/n06/backend/service/impl/RecordServiceImpl.java b/backend/src/main/java/ct01/n06/backend/service/impl/RecordServiceImpl.java index e813b2e..684f53c 100644 --- a/backend/src/main/java/ct01/n06/backend/service/impl/RecordServiceImpl.java +++ b/backend/src/main/java/ct01/n06/backend/service/impl/RecordServiceImpl.java @@ -26,6 +26,9 @@ public Map calculateAutoScores(final String studentId, final Lon final Map autoScores = new HashMap<>(); for (final RecordEntity record : records) { + if (record.getCriteria() == null || record.getCriteria().getPointPerItem() == null) { + continue; + } String criteriaCode = record.getCriteria().getCode(); double point = record.getCriteria().getPointPerItem().doubleValue(); autoScores.put(criteriaCode, autoScores.getOrDefault(criteriaCode, 0.0) + point); diff --git a/frontend/src/api/evidenceDeclarationApi.js b/frontend/src/api/evidenceDeclarationApi.js new file mode 100644 index 0000000..49dba04 --- /dev/null +++ b/frontend/src/api/evidenceDeclarationApi.js @@ -0,0 +1,64 @@ +import { apiRequest } from "../shared/api/http"; + +function buildQuery(params) { + const search = new URLSearchParams(); + + Object.entries(params).forEach(([key, value]) => { + if (value !== undefined && value !== null && value !== "") { + search.append(key, String(value)); + } + }); + + const query = search.toString(); + return query ? `?${query}` : ""; +} + +export async function createEvidenceDeclaration(payload) { + return apiRequest("/v1/student/evidence-declarations", { + method: "POST", + body: JSON.stringify(payload), + }); +} + +export async function getStudentEvidenceDeclarations({ status, semesterId, page = 0, size = 20 } = {}) { + return apiRequest( + `/v1/student/evidence-declarations${buildQuery({ status, semesterId, page, size })}`, + ); +} + +export async function updateEvidenceDeclaration(id, payload) { + return apiRequest(`/v1/student/evidence-declarations/${id}`, { + method: "PUT", + body: JSON.stringify(payload), + }); +} + +export async function deleteEvidenceDeclaration(id) { + return apiRequest(`/v1/student/evidence-declarations/${id}`, { + method: "DELETE", + }); +} + +export async function getMonitorEvidenceDeclarations({ status, semesterId, page = 0, size = 20 } = {}) { + return apiRequest( + `/v1/monitor/evidence-declarations${buildQuery({ status, semesterId, page, size })}`, + ); +} + +export async function getMonitorEvidenceDeclarationDetail(id) { + return apiRequest(`/v1/monitor/evidence-declarations/${id}`); +} + +export async function approveMonitorEvidenceDeclaration(id, payload = {}) { + return apiRequest(`/v1/monitor/evidence-declarations/${id}/approve`, { + method: "POST", + body: JSON.stringify(payload), + }); +} + +export async function rejectMonitorEvidenceDeclaration(id, payload = {}) { + return apiRequest(`/v1/monitor/evidence-declarations/${id}/reject`, { + method: "POST", + body: JSON.stringify(payload), + }); +} diff --git a/frontend/src/features/monitor/components/MonitorClass.jsx b/frontend/src/features/monitor/components/MonitorClass.jsx index 570b9f9..00aaf72 100644 --- a/frontend/src/features/monitor/components/MonitorClass.jsx +++ b/frontend/src/features/monitor/components/MonitorClass.jsx @@ -1,284 +1,40 @@ -import { useState, useEffect, useMemo } from "react"; -import { useAuth } from "../../../context/AuthContext"; -import { useCurrentSemester } from "../../../hooks/useCurrentSemester"; -import { useMonitorEvaluationList } from "../hooks/useMonitorEvaluationList"; -import MonitorReviewModal from "./MonitorReviewModal"; -import "../../../styles/MonitorClass.css"; +import { useState } from "react"; +import MonitorClassMembersTab from "./MonitorClassMembersTab"; +import MonitorEvidenceReviewTab from "./MonitorEvidenceReviewTab"; +import MonitorScoreManagementTab from "./MonitorScoreManagementTab"; -const STATUS_DISPLAY = { - SUBMITTED: { label: "SUBMITTED", badge: "badge-submitted" }, - MONITOR_APPROVED: { label: "MONITOR_APPROVED", badge: "badge-monitor_approved" }, - FINALIZED: { label: "FINALIZED", badge: "badge-finalized" }, - DRAFT: { label: "DRAFT", badge: "badge-draft" }, - OPEN: { label: "NOT_SUBMITTED", badge: "badge-not_submitted" }, -}; - -function getInitials(name) { - if (!name) return "NA"; - const parts = name.split(' '); - if (parts.length >= 2) { - return `${parts[parts.length - 2][0]}${parts[parts.length - 1][0]}`.toUpperCase(); - } - return name.substring(0, 2).toUpperCase(); -} +const MONITOR_TABS = [ + { key: "members", label: "Thành viên lớp" }, + { key: "evidence", label: "Duyệt minh chứng" }, + { key: "evaluation", label: "Quản lý phiếu điểm" }, +]; export default function MonitorClass() { - const { user } = useAuth(); - - const { semesters, activeSemesterId, loading: semesterLoading, error: semesterError } = useCurrentSemester(); - const [selectedSemester, setSelectedSemester] = useState(null); - const [activeModalStudent, setActiveModalStudent] = useState(null); - - useEffect(() => { - if (activeSemesterId && !selectedSemester) { - setSelectedSemester(activeSemesterId); - } - }, [activeSemesterId, selectedSemester]); - - const { - students, - stats, - isLoading: listLoading, - error: listError, - fetchClassList, - } = useMonitorEvaluationList(selectedSemester); - - useEffect(() => { - if (selectedSemester) { - fetchClassList(); - } - }, [selectedSemester, fetchClassList]); - - const [currentPage, setCurrentPage] = useState(1); - const itemsPerPage = 10; - - const paginatedStudents = useMemo(() => { - const start = (currentPage - 1) * itemsPerPage; - return students.slice(start, start + itemsPerPage); - }, [students, currentPage]); - - const totalPages = Math.ceil(students.length / itemsPerPage); - - const handleExportExcel = () => { - // Basic export functionality - const tableHeader = `MSSVHọ và TênĐiểm tổng kếtTrạng thái`; - const tableRows = students.map(s => `${s.studentCode}${s.fullName}${s.finalScore || '--'}${s.status || 'NOT_SUBMITTED'}`).join(''); - const excelHtml = `${tableHeader}${tableRows}
`; - - const blob = new Blob([excelHtml], { type: "application/vnd.ms-excel;charset=utf-8;" }); - const url = URL.createObjectURL(blob); - const link = document.createElement("a"); - link.href = url; - link.download = `Danh_Sach_Ren_Luyen.xls`; - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - URL.revokeObjectURL(url); - }; - - const loading = semesterLoading || listLoading; - const error = semesterError || listError; - - if (loading && students.length === 0) { - return
Đang tải dữ liệu lớp...
; - } - - if (error) { - return
Hệ thống báo lỗi: {error}
; - } - - if (semesters.length === 0) { - return
Hệ thống chưa cấu hình học kỳ.
; - } - - const selectedSemesterObj = semesters.find(s => s.id === Number(selectedSemester)); - const semesterName = selectedSemesterObj?.name || 'Học kỳ...'; - - return ( -
-
-
-

Quản lý điểm rèn luyện {user?.classCode ? `- Lớp ${user.classCode}` : ''}

-

Theo dõi và phê duyệt kết quả rèn luyện học kỳ hiện tại của sinh viên.

-
-
-
- calendar_today - -
- -
-
- -
-
-
- person -
-
- TỔNG SỐ SINH VIÊN - {String(stats.total).padStart(2, '0')} -
-
- -
-
- check_circle -
-
- SỐ PHIẾU ĐÃ NỘP - {String(stats.submittedCount).padStart(2, '0')} -
-
-
- -
-
- more_horiz -
-
- SỐ PHIẾU CHƯA NỘP - {String(stats.notSubmittedCount).padStart(2, '0')} - Yêu cầu nhắc nhở -
-
-
- -
-
-

Danh sách đánh giá điểm rèn luyện

-
- -
-
- - - - - - - - - - - - - - {paginatedStudents.length === 0 ? ( - - - - ) : ( - paginatedStudents.map((student, index) => { - const sType = (!student.status || student.status === 'OPEN') ? 'OPEN' : student.status; - const statusMeta = STATUS_DISPLAY[sType] || STATUS_DISPLAY['OPEN']; - - return ( - - - - - - - - - ); - }) - )} - -
STTMã sinh viênHọ và tênĐiểm tổng kếtTrạng tháiHành động
Không có dữ liệu đánh giá cho học kỳ này.
- {String((currentPage - 1) * itemsPerPage + index + 1).padStart(2, '0')} - {student.studentCode} -
-
- {getInitials(student.fullName)} -
-
- {student.fullName} -
-
-
{student.finalScore || '--'} - - {statusMeta.label} - - - -
- - {students.length > 0 && ( -
-
- Hiển thị {paginatedStudents.length} trong số {students.length} sinh viên -
-
- - - {Array.from({ length: totalPages }, (_, i) => i + 1).map(page => ( - - ))} - - + const [activeTab, setActiveTab] = useState("members"); + + return ( +
+
+
+ {MONITOR_TABS.map((tab) => ( + + ))} +
-
- )} -
- {activeModalStudent && ( - setActiveModalStudent(null)} - onSuccess={() => { - setActiveModalStudent(null); - fetchClassList(); - }} - /> - )} -
- ); + {activeTab === "members" ? : null} + {activeTab === "evidence" ? : null} + {activeTab === "evaluation" ? : null} + + ); } diff --git a/frontend/src/features/monitor/components/MonitorClassMembersTab.jsx b/frontend/src/features/monitor/components/MonitorClassMembersTab.jsx new file mode 100644 index 0000000..9d6da13 --- /dev/null +++ b/frontend/src/features/monitor/components/MonitorClassMembersTab.jsx @@ -0,0 +1,137 @@ +import { useMemo, useState } from "react"; +import { useAuth } from "../../../context/AuthContext"; +import { useMonitorData } from "../hooks/useMonitorData"; + +function monitorBadge(isMonitor) { + if (!isMonitor) { + return Thành viên; + } + return Lớp trưởng; +} + +function statusBadge(status) { + const normalized = String(status || "").toUpperCase(); + if (normalized === "ACTIVE") { + return Hoạt động; + } + if (normalized === "INACTIVE") { + return Tạm khóa; + } + return {status || "--"}; +} + +export default function MonitorClassMembersTab() { + const { user } = useAuth(); + const { data, loading, error } = useMonitorData(user?.userId); + const [keyword, setKeyword] = useState(""); + + const members = useMemo( + () => (Array.isArray(data?.members) ? data.members : []).filter((member) => member && typeof member === "object"), + [data?.members], + ); + const normalizedKeyword = keyword.trim().toLowerCase(); + + const filteredMembers = useMemo(() => { + if (!normalizedKeyword) { + return members; + } + return members.filter((member) => { + const studentCode = String(member.studentCode || "").toLowerCase(); + const fullName = String(member.fullName || "").toLowerCase(); + const email = String(member.email || "").toLowerCase(); + return studentCode.includes(normalizedKeyword) + || fullName.includes(normalizedKeyword) + || email.includes(normalizedKeyword); + }); + }, [members, normalizedKeyword]); + + const activeCount = members.filter((member) => String(member.accountStatus || "").toUpperCase() === "ACTIVE").length; + + if (loading) { + return
Đang tải thành viên lớp...
; + } + + if (error) { + return ( +
+ Không tải được danh sách thành viên lớp: {error} +
+ ); + } + + return ( +
+
+
+

Thành viên lớp {data?.classCode || ""}

+

Danh sách thành viên theo lớp để theo dõi điểm và trạng thái tài khoản.

+
+
+ setKeyword(e.target.value)} + placeholder="Tìm theo MSSV, họ tên, email" + className="w-full rounded-lg border border-slate-200 bg-slate-50 px-3 py-2 text-sm outline-none focus:ring-2 focus:ring-primary" + /> +
+
+ +
+
+

Khoa

+

{data?.facultyName || "--"}

+
+
+

Tổng thành viên

+

{data?.totalMembers || 0}

+
+
+

Đang hoạt động

+

{activeCount}

+
+
+ +
+ + + + + + + + + + + + + + {filteredMembers.length === 0 ? ( + + + + ) : ( + filteredMembers.map((member, index) => ( + + + + + + + + + + )) + )} + +
MSSVHọ và tênEmailĐiểm tổngBắt buộcVai tròTrạng thái
+ {members.length === 0 ? "Chưa có thành viên trong lớp." : "Không có kết quả phù hợp từ khóa tìm kiếm."} +
{member.studentCode || "--"}{member.fullName || "--"}{member.email || "--"} + {member.totalPoint ?? 0} điểm + {member.mandatoryParticipation ?? "--"}{monitorBadge(member.monitor)}{statusBadge(member.accountStatus)}
+
+
+ ); +} diff --git a/frontend/src/features/monitor/components/MonitorEvidenceReviewTab.jsx b/frontend/src/features/monitor/components/MonitorEvidenceReviewTab.jsx new file mode 100644 index 0000000..2ad2688 --- /dev/null +++ b/frontend/src/features/monitor/components/MonitorEvidenceReviewTab.jsx @@ -0,0 +1,329 @@ +import { useCallback, useEffect, useState } from "react"; +import { + approveMonitorEvidenceDeclaration, + getMonitorEvidenceDeclarationDetail, + getMonitorEvidenceDeclarations, + rejectMonitorEvidenceDeclaration, +} from "../../../api/evidenceDeclarationApi"; +import { useCurrentSemester } from "../../../hooks/useCurrentSemester"; + +const STATUS_OPTIONS = [ + { value: "", label: "Tất cả" }, + { value: "PENDING", label: "Chờ duyệt" }, + { value: "APPROVED", label: "Đã duyệt" }, + { value: "REJECTED", label: "Từ chối" }, +]; + +function statusLabel(status) { + if (status === "APPROVED") return "Đã duyệt"; + if (status === "REJECTED") return "Từ chối"; + return "Chờ duyệt"; +} + +function statusPillClass(status) { + if (status === "APPROVED") { + return "border border-green-200 bg-green-50 text-green-700"; + } + if (status === "REJECTED") { + return "border border-red-200 bg-red-50 text-red-700"; + } + return "border border-yellow-200 bg-yellow-50 text-yellow-700"; +} + +export default function MonitorEvidenceReviewTab() { + const { semesters, activeSemesterId } = useCurrentSemester(); + const [selectedSemester, setSelectedSemester] = useState(""); + const [status, setStatus] = useState(""); + const [items, setItems] = useState([]); + const [loading, setLoading] = useState(false); + const [error, setError] = useState(""); + const [workingId, setWorkingId] = useState(null); + const [detailOpen, setDetailOpen] = useState(false); + const [detailLoading, setDetailLoading] = useState(false); + const [detailError, setDetailError] = useState(""); + const [detailItem, setDetailItem] = useState(null); + + useEffect(() => { + if (!selectedSemester && activeSemesterId) { + setSelectedSemester(String(activeSemesterId)); + } + }, [activeSemesterId, selectedSemester]); + + const loadData = useCallback(async () => { + if (!selectedSemester) { + setItems([]); + return; + } + + setLoading(true); + setError(""); + try { + const payload = await getMonitorEvidenceDeclarations({ + semesterId: Number(selectedSemester), + status: status || undefined, + page: 0, + size: 100, + }); + setItems(Array.isArray(payload?.items) ? payload.items : []); + } catch (err) { + setError(err.message || "Không tải được danh sách minh chứng."); + } finally { + setLoading(false); + } + }, [selectedSemester, status]); + + useEffect(() => { + loadData(); + }, [loadData]); + + const runReviewAction = useCallback(async (id, action) => { + setWorkingId(id); + setError(""); + try { + if (action === "approve") { + await approveMonitorEvidenceDeclaration(id, {}); + } else { + await rejectMonitorEvidenceDeclaration(id, {}); + } + await loadData(); + } catch (err) { + setError(err.message || "Không thể xử lý minh chứng."); + } finally { + setWorkingId(null); + } + }, [loadData]); + + const handleApprove = async (id) => { + await runReviewAction(id, "approve"); + }; + + const handleReject = async (id) => { + await runReviewAction(id, "reject"); + }; + + const handleViewDetail = async (id) => { + setDetailOpen(true); + setDetailLoading(true); + setDetailError(""); + setDetailItem(null); + + try { + const detail = await getMonitorEvidenceDeclarationDetail(id); + setDetailItem(detail || null); + } catch (err) { + setDetailError(err.message || "Không tải được chi tiết minh chứng."); + } finally { + setDetailLoading(false); + } + }; + + return ( +
+
+
+

Duyệt minh chứng lớp

+

Lớp trưởng duyệt minh chứng của sinh viên trong lớp phụ trách.

+
+
+ +
+ + + +
+ + {error ?
{error}
: null} + +
+ + + + + + + + + + + + {loading ? ( + + + + ) : items.length === 0 ? ( + + + + ) : ( + items.map((item) => ( + + + + + + + + )) + )} + +
Ngày gửiSinh viênMinh chứngTrạng tháiHành động
+ Đang tải minh chứng... +
+ Không có minh chứng trong bộ lọc hiện tại. +
{item.createdAt || "--"}{item.studentName || "--"} +
{item.customName || "--"}
+ {item.reviewNote ?
Ghi chú: {item.reviewNote}
: null} +
+ + {statusLabel(item.status)} + + + {item.status === "PENDING" ? ( +
+ + + +
+ ) : ( +
+ +
+ )} +
+
+ + {detailOpen ? ( +
+
+
+
+

Chi tiết minh chứng

+
+ +
+ + {detailLoading ?

Đang tải chi tiết...

: null} + {detailError ?

{detailError}

: null} + + {!detailLoading && !detailError && detailItem ? ( +
+
+ Sinh viên: + {detailItem.studentName || "--"} +
+
+ Lớp: + {detailItem.classCode || "--"} +
+
+ Học kỳ: + {detailItem.semesterName || "--"} +
+
+ Trạng thái: + + {statusLabel(detailItem.status)} + +
+
+ Tên minh chứng: + {detailItem.customName || "--"} +
+
+ Thời gian hoạt động: + {detailItem.activityTime || "--"} +
+
+ Đường dẫn minh chứng: + {detailItem.evidenceUrl ? ( + + Mở tài liệu minh chứng + + ) : ( + -- + )} +
+ {detailItem.reviewNote ? ( +
+ Ghi chú duyệt: + {detailItem.reviewNote} +
+ ) : null} +
+ Ngày gửi: + {detailItem.createdAt || "--"} +
+
+ Ngày xử lý: + {detailItem.reviewedAt || "--"} +
+
+ ) : null} +
+
+ ) : null} +
+ ); +} diff --git a/frontend/src/features/monitor/components/MonitorScoreManagementTab.jsx b/frontend/src/features/monitor/components/MonitorScoreManagementTab.jsx new file mode 100644 index 0000000..00bba27 --- /dev/null +++ b/frontend/src/features/monitor/components/MonitorScoreManagementTab.jsx @@ -0,0 +1,302 @@ +import { useEffect, useMemo, useState } from "react"; +import { useAuth } from "../../../context/AuthContext"; +import { useCurrentSemester } from "../../../hooks/useCurrentSemester"; +import { useMonitorEvaluationList } from "../hooks/useMonitorEvaluationList"; +import MonitorReviewModal from "./MonitorReviewModal"; +import "../../../styles/MonitorClass.css"; + +const STATUS_DISPLAY = { + SUBMITTED: { label: "SUBMITTED", badge: "badge-submitted" }, + MONITOR_APPROVED: { label: "MONITOR_APPROVED", badge: "badge-monitor_approved" }, + FINALIZED: { label: "FINALIZED", badge: "badge-finalized" }, + DRAFT: { label: "DRAFT", badge: "badge-draft" }, + OPEN: { label: "NOT_SUBMITTED", badge: "badge-not_submitted" }, +}; + +function getInitials(name) { + if (!name) return "NA"; + const parts = name.split(" "); + if (parts.length >= 2) { + return `${parts[parts.length - 2][0]}${parts[parts.length - 1][0]}`.toUpperCase(); + } + return name.substring(0, 2).toUpperCase(); +} + +export default function MonitorScoreManagementTab() { + const { user } = useAuth(); + + const { semesters, activeSemesterId, loading: semesterLoading, error: semesterError } = useCurrentSemester(); + const [selectedSemester, setSelectedSemester] = useState(null); + const [activeModalStudent, setActiveModalStudent] = useState(null); + + useEffect(() => { + if (activeSemesterId && !selectedSemester) { + setSelectedSemester(activeSemesterId); + } + }, [activeSemesterId, selectedSemester]); + + const { + students, + stats, + isLoading: listLoading, + error: listError, + fetchClassList, + } = useMonitorEvaluationList(selectedSemester); + + useEffect(() => { + if (selectedSemester) { + fetchClassList(); + } + }, [selectedSemester, fetchClassList]); + + const [currentPage, setCurrentPage] = useState(1); + const itemsPerPage = 10; + + const paginatedStudents = useMemo(() => { + const start = (currentPage - 1) * itemsPerPage; + return students.slice(start, start + itemsPerPage); + }, [students, currentPage]); + + const totalPages = Math.ceil(students.length / itemsPerPage); + + const handleExportExcel = () => { + const tableHeader = "MSSVHọ và TênĐiểm tổng kếtTrạng thái"; + const tableRows = students + .map( + (s) => + `${s.studentCode}${s.fullName}${s.finalScore || "--"}${s.status || "NOT_SUBMITTED"}`, + ) + .join(""); + const excelHtml = `${tableHeader}${tableRows}
`; + + const blob = new Blob([excelHtml], { type: "application/vnd.ms-excel;charset=utf-8;" }); + const url = URL.createObjectURL(blob); + const link = document.createElement("a"); + link.href = url; + link.download = "Danh_Sach_Ren_Luyen.xls"; + document.body.appendChild(link); + link.click(); + document.body.removeChild(link); + URL.revokeObjectURL(url); + }; + + const loading = semesterLoading || listLoading; + const error = semesterError || listError; + + if (loading && students.length === 0) { + return
Đang tải dữ liệu lớp...
; + } + + if (error) { + return ( +
+ Hệ thống báo lỗi: {error} +
+ ); + } + + if (semesters.length === 0) { + return ( +
+ Hệ thống chưa cấu hình học kỳ. +
+ ); + } + + const selectedSemesterObj = semesters.find((s) => s.id === Number(selectedSemester)); + const semesterName = selectedSemesterObj?.name || "Học kỳ..."; + + return ( +
+
+
+

Quản lý phiếu điểm rèn luyện {user?.classCode ? `- Lớp ${user.classCode}` : ""}

+

Theo dõi và phê duyệt kết quả rèn luyện học kỳ hiện tại của sinh viên.

+
+
+
+ + calendar_today + + +
+ +
+
+ +
+
+
+ person +
+
+ TỔNG SỐ SINH VIÊN + {String(stats.total).padStart(2, "0")} +
+
+ +
+
+ check_circle +
+
+ SỐ PHIẾU ĐÃ NỘP + {String(stats.submittedCount).padStart(2, "0")} +
+
+
+ +
+
+ more_horiz +
+
+ SỐ PHIẾU CHƯA NỘP + {String(stats.notSubmittedCount).padStart(2, "0")} + Yêu cầu nhắc nhở +
+
+
+ +
+
+

Danh sách đánh giá điểm rèn luyện

+
+ +
+
+ + + + + + + + + + + + + + {paginatedStudents.length === 0 ? ( + + + + ) : ( + paginatedStudents.map((student, index) => { + const sType = !student.status || student.status === "OPEN" ? "OPEN" : student.status; + const statusMeta = STATUS_DISPLAY[sType] || STATUS_DISPLAY.OPEN; + + return ( + + + + + + + + + ); + }) + )} + +
STTMã sinh viênHọ và tênĐiểm tổng kếtTrạng tháiHành động
+ Không có dữ liệu đánh giá cho học kỳ này. +
+ {String((currentPage - 1) * itemsPerPage + index + 1).padStart(2, "0")} + {student.studentCode} +
+
{getInitials(student.fullName)}
+
{student.fullName}
+
+
+ {student.finalScore || "--"} + + {statusMeta.label} + + +
+ + {students.length > 0 && ( +
+
Hiển thị {paginatedStudents.length} trong số {students.length} sinh viên
+
+ + + {Array.from({ length: totalPages }, (_, i) => i + 1).map((page) => ( + + ))} + + +
+
+ )} +
+ + {activeModalStudent && ( + setActiveModalStudent(null)} + onSuccess={() => { + setActiveModalStudent(null); + fetchClassList(); + }} + /> + )} +
+ ); +} diff --git a/frontend/src/features/student/components/QRScanner.jsx b/frontend/src/features/student/components/QRScanner.jsx index c134da6..97b3853 100644 --- a/frontend/src/features/student/components/QRScanner.jsx +++ b/frontend/src/features/student/components/QRScanner.jsx @@ -76,8 +76,6 @@ const handleCheckinSubmit = async ({ qrData, eventId }) => { } function QRScanner() { - const [activeTab, setActiveTab] = useState('qr') // 'qr' | 'evidence' - // QR Scanner States const [permissionStatus, setPermissionStatus] = useState('idle') const [isScanning, setIsScanning] = useState(false) @@ -296,9 +294,6 @@ function QRScanner() { } }, [handlePinSubmit, isProcessing, pinDigits, scanCompleted]) - const activeTabClass = "flex-1 py-4 text-sm font-bold border-b-[3px] border-primary text-primary transition-all flex items-center justify-center gap-2" - const inactiveTabClass = "flex-1 py-4 text-sm font-medium text-slate-500 hover:bg-primary/5 transition-all flex items-center justify-center gap-2 border-b-[3px] border-transparent" - return (
{toastMessage && ( @@ -310,277 +305,159 @@ function QRScanner() {
- {/* Tabs */} -
- - -
- - {/* Tab Content */}
- {activeTab === 'qr' && ( -
-

Nhập mã PIN điểm danh

-

Nhập đúng mã PIN 6 chữ số được cung cấp bởi ban tổ chức.

- - {scanCompleted && notice.type === 'success' && ( -
-
- task_alt -
-

Điểm danh thành công

-

{notice.message}

-
- - -
+
+

Nhập mã PIN điểm danh

+

Nhập đúng mã PIN 6 chữ số được cung cấp bởi ban tổ chức.

+ + {scanCompleted && notice.type === 'success' && ( +
+
+ task_alt +
+

Điểm danh thành công

+

{notice.message}

+
+ +
- )} - - {!IS_PIN_ONLY && ( -
- {/* html5-qrcode renderer block */} -
div]:!h-full [&>div]:!w-full [&_video]:!h-full [&_video]:!w-full [&_video]:!object-cover ${isScanning ? 'opacity-100' : 'opacity-0 pointer-events-none'}`} - /> - - {!isScanning && !scanCompleted && ( - <> -
-
-
-
-
-
- qr_code_2 -
- -
- -
- - )} +
+ )} + + {!IS_PIN_ONLY && ( +
+
div]:!h-full [&>div]:!w-full [&_video]:!h-full [&_video]:!w-full [&_video]:!object-cover ${isScanning ? 'opacity-100' : 'opacity-0 pointer-events-none'}`} + /> + + {!isScanning && !scanCompleted && ( + <> +
+
+
+
+
+
+ qr_code_2 +
- {isScanning && !isProcessing && ( -
-
- )} - - {/* Scanning frame overlay */} - {isScanning && ( -
-
-
-
-
-
-
- {isProcessing && ( -
- sync -
- )} -
-
-
- )} + + )} -
- )} - - {/* Notice Block beneath Scanner */} - {notice.message && notice.type === 'error' && ( -
- - {notice.type === 'success' ? 'check_circle' : 'error'} - -
-

- {notice.type === 'success' ? 'Thành công!' : 'Lỗi!'} -

-

- {notice.message} -

-
- -
- )} - - {!scanCompleted && !isScanning && !notice.message && ( -
-
-
- Nhập mã PIN -
+ {isScanning && !isProcessing && ( +
+
-
-
- {pinDigits.map((digit, index) => ( - { - pinInputRefs.current[index] = el - }} - className="w-12 h-12 text-center text-lg font-bold bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-700 rounded-lg focus:ring-2 focus:ring-primary outline-none transition-all" - value={digit} - onChange={(e) => handlePinInputChange(index, e.target.value)} - onKeyDown={(e) => handlePinInputKeyDown(index, e)} - disabled={isProcessing} - /> - ))} + )} + + {isScanning && ( +
+
+
+
+
+
+
+ {isProcessing && ( +
+ sync +
+ )} +
-
+ )} +
+ )} + + {notice.message && notice.type === 'error' && ( +
+ + {notice.type === 'success' ? 'check_circle' : 'error'} + +
+

+ {notice.type === 'success' ? 'Thành công!' : 'Lỗi!'} +

+

+ {notice.message} +

- )} -
- )} - - {activeTab === 'evidence' && ( -
-

Khai báo minh chứng sự kiện ngoài

-
e.preventDefault()}> -
- - -
-
- - -
-
- - + +
+ )} + + {!scanCompleted && !isScanning && !notice.message && ( +
+
+
+ Nhập mã PIN +
-
- -
- - +
+
+ {pinDigits.map((digit, index) => ( + { + pinInputRefs.current[index] = el + }} + className="w-12 h-12 text-center text-lg font-bold bg-slate-50 dark:bg-slate-900 border border-slate-200 dark:border-slate-700 rounded-lg focus:ring-2 focus:ring-primary outline-none transition-all" + value={digit} + onChange={(e) => handlePinInputChange(index, e.target.value)} + onKeyDown={(e) => handlePinInputKeyDown(index, e)} + disabled={isProcessing} + /> + ))}
-
-
- -
- - -
-

Danh sách minh chứng đã gửi

-
- - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
Ngày gửiTên minh chứngLoạiTrạng tháiThao tác
12/10/2023Giấy khen SV 5 tốtHọc thuật - - Chờ duyệt - - - -
05/09/2023Chiến dịch Mùa hè xanhTình nguyện - - Đã duyệt - - - -
20/08/2023Hiến máu nhân đạoXã hội - - Từ chối - - - -
+
-
- )} + )} +
diff --git a/frontend/src/features/student/components/StudentEvidenceDeclarationPanel.jsx b/frontend/src/features/student/components/StudentEvidenceDeclarationPanel.jsx new file mode 100644 index 0000000..7a12cbd --- /dev/null +++ b/frontend/src/features/student/components/StudentEvidenceDeclarationPanel.jsx @@ -0,0 +1,432 @@ +import { useMemo, useState } from "react"; +import { useCurrentSemester } from "../../../hooks/useCurrentSemester"; +import { useStudentEvidenceDeclarations } from "../hooks/useStudentEvidenceDeclarations"; + +const STATUS_OPTIONS = [ + { value: "", label: "Tất cả" }, + { value: "PENDING", label: "Chờ duyệt" }, + { value: "APPROVED", label: "Đã duyệt" }, + { value: "REJECTED", label: "Từ chối" }, +]; + +const EVENT_TYPE_OPTIONS = [ + "Tình nguyện", + "Hội thảo & Tọa đàm", + "Cuộc thi học thuật", + "Hoạt động thể thao", +]; + +function statusBadgeClass(status) { + if (status === "APPROVED") { + return "border border-green-200 bg-green-50 text-green-700 dark:border-green-700/40 dark:bg-green-900/20 dark:text-green-300"; + } + if (status === "REJECTED") { + return "border border-red-200 bg-red-50 text-red-700 dark:border-red-700/40 dark:bg-red-900/20 dark:text-red-300"; + } + return "border border-yellow-200 bg-yellow-50 text-yellow-700 dark:border-yellow-700/40 dark:bg-yellow-900/20 dark:text-yellow-300"; +} + +function statusLabel(status) { + if (status === "APPROVED") return "Đã duyệt"; + if (status === "REJECTED") return "Từ chối"; + return "Chờ duyệt"; +} + +export default function StudentEvidenceDeclarationPanel() { + const { semesters, activeSemesterId, loading: semesterLoading } = useCurrentSemester(); + const [selectedSemester, setSelectedSemester] = useState(""); + const [statusFilter, setStatusFilter] = useState(""); + const [editingId, setEditingId] = useState(null); + const [detailOpen, setDetailOpen] = useState(false); + const [detailItem, setDetailItem] = useState(null); + const [form, setForm] = useState({ + eventType: EVENT_TYPE_OPTIONS[0], + customName: "", + evidenceUrl: "", + activityDate: "", + }); + + const semesterValue = selectedSemester || (activeSemesterId ? String(activeSemesterId) : ""); + + const { + items, + loading, + submitting, + error, + createDeclaration, + updateDeclaration, + removeDeclaration, + } = useStudentEvidenceDeclarations({ + semesterId: semesterValue || undefined, + status: statusFilter || undefined, + page: 0, + size: 20, + }); + + const formTitle = useMemo( + () => (editingId ? "Cập nhật minh chứng" : "Khai báo minh chứng sự kiện ngoài"), + [editingId], + ); + + const resetForm = () => { + setEditingId(null); + setForm({ + eventType: EVENT_TYPE_OPTIONS[0], + customName: "", + evidenceUrl: "", + activityDate: "", + }); + }; + + const handleSubmit = async (event) => { + event.preventDefault(); + + if (!semesterValue) { + alert("Vui lòng chọn học kỳ."); + return; + } + + const finalName = `${form.eventType}: ${form.customName}`.trim(); + const payload = { + semesterId: Number(semesterValue), + customName: finalName, + evidenceUrl: form.evidenceUrl, + activityDate: form.activityDate, + }; + + try { + if (editingId) { + await updateDeclaration(editingId, { + customName: payload.customName, + evidenceUrl: payload.evidenceUrl, + activityDate: payload.activityDate, + }); + } else { + await createDeclaration(payload); + } + resetForm(); + } catch { + // Error message has been set by hook state. + } + }; + + const handleEdit = (item) => { + setEditingId(item.id); + setForm((prev) => ({ + ...prev, + customName: item.customName || "", + evidenceUrl: item.evidenceUrl || "", + activityDate: "", + })); + }; + + const handleDelete = async (id) => { + const ok = window.confirm("Bạn có chắc muốn xóa minh chứng này?"); + if (!ok) { + return; + } + try { + await removeDeclaration(id); + if (editingId === id) { + resetForm(); + } + } catch { + // Error message has been set by hook state. + } + }; + + const handleOpenDetail = (item) => { + setDetailItem(item); + setDetailOpen(true); + }; + + const handleCloseDetail = () => { + setDetailOpen(false); + setDetailItem(null); + }; + + return ( +
+
+
+

{formTitle}

+

Khai báo minh chứng sẽ được lớp trưởng xét duyệt theo học kỳ.

+
+ verified_user +
+ + {error ? ( +
+ {error} +
+ ) : null} + +
+
+ + +
+ +
+ + +
+ +
+ + setForm((prev) => ({ ...prev, customName: e.target.value }))} + disabled={submitting} + required + /> +
+ +
+ + setForm((prev) => ({ ...prev, activityDate: e.target.value }))} + disabled={submitting} + required + /> +
+ +
+ + setForm((prev) => ({ ...prev, evidenceUrl: e.target.value }))} + disabled={submitting} + required + /> +
+ +
+ {editingId ? ( + + ) : null} + +
+
+ +
+
+

+ Danh sách minh chứng đã gửi +

+ +
+ +
+ + + + + + + + + + + + {loading ? ( + + + + ) : items.length === 0 ? ( + + + + ) : ( + items.map((item) => ( + + + + + + + + )) + )} + +
Ngày gửiTên minh chứngHọc kỳTrạng tháiThao tác
+ Đang tải danh sách minh chứng... +
+ Chưa có minh chứng nào trong bộ lọc hiện tại. +
{item.createdAt || "--"}{item.customName || "--"}{item.semesterName || "--"} +
+ {statusLabel(item.status)} +
+ {item.reviewNote ? ( +

{item.reviewNote}

+ ) : null} +
+ {item.status === "PENDING" ? ( +
+ + + +
+ ) : ( +
+ +
+ )} +
+
+
+ + {detailOpen ? ( +
+
event.stopPropagation()} + > +
+
+

Chi tiết minh chứng

+

Thông tin đầy đủ của minh chứng đã khai báo

+
+ +
+ +
+
+

Tên minh chứng

+

{detailItem?.customName || "--"}

+
+
+

Học kỳ

+

{detailItem?.semesterName || "--"}

+
+
+

Ngày gửi

+

{detailItem?.createdAt || "--"}

+
+
+

Trạng thái

+
+ + {statusLabel(detailItem?.status)} + +
+
+
+

Link minh chứng

+ {detailItem?.evidenceUrl ? ( + + {detailItem.evidenceUrl} + + ) : ( +

--

+ )} +
+ {detailItem?.reviewNote ? ( +
+

Ghi chú duyệt

+

{detailItem.reviewNote}

+
+ ) : null} +
+
+
+ ) : null} +
+ ); +} diff --git a/frontend/src/features/student/hooks/useStudentEvidenceDeclarations.js b/frontend/src/features/student/hooks/useStudentEvidenceDeclarations.js new file mode 100644 index 0000000..8d60a1b --- /dev/null +++ b/frontend/src/features/student/hooks/useStudentEvidenceDeclarations.js @@ -0,0 +1,105 @@ +import { useCallback, useEffect, useState } from "react"; +import { + createEvidenceDeclaration, + deleteEvidenceDeclaration, + getStudentEvidenceDeclarations, + updateEvidenceDeclaration, +} from "../../../api/evidenceDeclarationApi"; + +export function useStudentEvidenceDeclarations({ semesterId, status, page = 0, size = 20 }) { + const [items, setItems] = useState([]); + const [pagination, setPagination] = useState({ + page, + size, + totalItems: 0, + totalPages: 0, + }); + const [loading, setLoading] = useState(true); + const [submitting, setSubmitting] = useState(false); + const [error, setError] = useState(""); + + const fetchDeclarations = useCallback(async () => { + setLoading(true); + setError(""); + + try { + const response = await getStudentEvidenceDeclarations({ + semesterId, + status, + page, + size, + }); + + const list = Array.isArray(response?.items) ? response.items : []; + setItems(list); + setPagination({ + page: response?.page ?? page, + size: response?.size ?? size, + totalItems: response?.totalItems ?? 0, + totalPages: response?.totalPages ?? 0, + }); + } catch (err) { + setError(err.message || "Không thể tải danh sách minh chứng."); + } finally { + setLoading(false); + } + }, [page, semesterId, size, status]); + + useEffect(() => { + fetchDeclarations(); + }, [fetchDeclarations]); + + const createDeclaration = useCallback(async (payload) => { + setSubmitting(true); + setError(""); + try { + await createEvidenceDeclaration(payload); + await fetchDeclarations(); + } catch (err) { + setError(err.message || "Không thể tạo minh chứng."); + throw err; + } finally { + setSubmitting(false); + } + }, [fetchDeclarations]); + + const updateDeclaration = useCallback(async (id, payload) => { + setSubmitting(true); + setError(""); + try { + await updateEvidenceDeclaration(id, payload); + await fetchDeclarations(); + } catch (err) { + setError(err.message || "Không thể cập nhật minh chứng."); + throw err; + } finally { + setSubmitting(false); + } + }, [fetchDeclarations]); + + const removeDeclaration = useCallback(async (id) => { + setSubmitting(true); + setError(""); + try { + await deleteEvidenceDeclaration(id); + await fetchDeclarations(); + } catch (err) { + setError(err.message || "Không thể xóa minh chứng."); + throw err; + } finally { + setSubmitting(false); + } + }, [fetchDeclarations]); + + return { + items, + pagination, + loading, + submitting, + error, + fetchDeclarations, + createDeclaration, + updateDeclaration, + removeDeclaration, + }; +} diff --git a/frontend/src/pages/StudentPage.jsx b/frontend/src/pages/StudentPage.jsx index 8fa2aab..00766c3 100644 --- a/frontend/src/pages/StudentPage.jsx +++ b/frontend/src/pages/StudentPage.jsx @@ -5,7 +5,6 @@ import { getStudentNotificationUnreadCount } from "../api/notificationStatistics import StudentDashboard from "../features/student/components/StudentDashboard"; import QRScanner from "../features/student/components/QRScanner"; import StudentMobileNav from "../features/student/components/StudentMobileNav"; -import StudentPlaceholderPanel from "../features/student/components/StudentPlaceholderPanel"; import StudentSidebar from "../features/student/components/StudentSidebar"; import StudentTopHeader from "../features/student/components/StudentTopHeader"; import StudentEventsPanel from "../features/student/components/StudentEventsPanel"; @@ -13,6 +12,7 @@ import StudentAttendancePanel from "../features/student/components/StudentAttend import StudentStatisticsPanel from "../features/student/components/StudentStatisticsPanel"; import StudentNotificationsPanel from "../features/student/components/StudentNotificationsPanel"; import StudentEvaluationBoard from "../features/student/StudentEvaluationBoard"; +import StudentEvidenceDeclarationPanel from "../features/student/components/StudentEvidenceDeclarationPanel"; function normalizeRole(role) { if (!role) return ""; @@ -52,12 +52,7 @@ const FEATURE_COMPONENTS = { notifications: StudentNotificationsPanel, evaluation: StudentEvaluationBoard, "manage-class": MonitorClass, - evidence: () => ( - - ), + evidence: StudentEvidenceDeclarationPanel, }; export default function StudentPage() { From 8d44f9da9781c71f794bf75837a7c0ee359a82c0 Mon Sep 17 00:00:00 2001 From: MinhToanSBO Date: Sat, 18 Apr 2026 11:28:29 +0700 Subject: [PATCH 2/8] =?UTF-8?q?Update:=20Thay=20=C4=91=E1=BB=95i=20giao=20?= =?UTF-8?q?di=E1=BB=87n=20gi=E1=BA=A3ng=20vi=C3=AAn/=20sinh=20vi=C3=AAn=20?= =?UTF-8?q?tr=E1=BB=B1c=20quan=20h=C6=A1n=20v=C3=A0=20=C4=91=E1=BA=B9p=20h?= =?UTF-8?q?=C6=A1n?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../LecturerDashboardSummaryResponse.java | 1 + .../service/impl/LecturerServiceImpl.java | 2 + .../admin/components/AdminTopHeader.jsx | 3 - .../components/LecturerDashboardOverview.jsx | 419 ++++++-------- .../lecturer/components/LecturerSidebar.jsx | 48 +- .../student/components/StudentDashboard.jsx | 514 +++++++++--------- .../student/components/StudentTopHeader.jsx | 5 +- frontend/src/pages/LecturerPage.jsx | 2 + 8 files changed, 477 insertions(+), 517 deletions(-) diff --git a/backend/src/main/java/ct01/n06/backend/dto/lecturer/LecturerDashboardSummaryResponse.java b/backend/src/main/java/ct01/n06/backend/dto/lecturer/LecturerDashboardSummaryResponse.java index f4e13fc..00484b8 100644 --- a/backend/src/main/java/ct01/n06/backend/dto/lecturer/LecturerDashboardSummaryResponse.java +++ b/backend/src/main/java/ct01/n06/backend/dto/lecturer/LecturerDashboardSummaryResponse.java @@ -4,6 +4,7 @@ public record LecturerDashboardSummaryResponse( long totalEvents, + long totalStudents, long participatingStudents, long pendingEvidence, long newNotifications, diff --git a/backend/src/main/java/ct01/n06/backend/service/impl/LecturerServiceImpl.java b/backend/src/main/java/ct01/n06/backend/service/impl/LecturerServiceImpl.java index 552da14..595bc6e 100644 --- a/backend/src/main/java/ct01/n06/backend/service/impl/LecturerServiceImpl.java +++ b/backend/src/main/java/ct01/n06/backend/service/impl/LecturerServiceImpl.java @@ -139,6 +139,7 @@ public LecturerDashboardSummaryResponse getDashboardSummary() { Optional activeSemesterOpt = semesterRepository.findFirstByIsActiveTrueOrderByStartDateDesc(); long totalEvents = eventRepository.countByCreatedBy_Id(currentUserId); + long totalStudents = students.size(); long participatingStudents = 0; long pendingEvidence = 0; @@ -170,6 +171,7 @@ public LecturerDashboardSummaryResponse getDashboardSummary() { return new LecturerDashboardSummaryResponse( totalEvents, + totalStudents, participatingStudents, pendingEvidence, newNotifications, diff --git a/frontend/src/features/admin/components/AdminTopHeader.jsx b/frontend/src/features/admin/components/AdminTopHeader.jsx index f011864..b4770b8 100644 --- a/frontend/src/features/admin/components/AdminTopHeader.jsx +++ b/frontend/src/features/admin/components/AdminTopHeader.jsx @@ -16,9 +16,6 @@
- diff --git a/frontend/src/features/lecturer/components/LecturerDashboardOverview.jsx b/frontend/src/features/lecturer/components/LecturerDashboardOverview.jsx index e44d51b..cbc28e8 100644 --- a/frontend/src/features/lecturer/components/LecturerDashboardOverview.jsx +++ b/frontend/src/features/lecturer/components/LecturerDashboardOverview.jsx @@ -1,265 +1,204 @@ -const SUMMARY_CARD_CONFIG = [ - { - id: "events", - label: "Tổng sự kiện", - valueKey: "totalEvents", - icon: "event", - color: "text-blue-600", - bg: "bg-blue-100 dark:bg-blue-900/30", - }, - { - id: "students", - label: "Sinh viên tham gia", - valueKey: "participatingStudents", - icon: "groups", - color: "text-green-600", - bg: "bg-green-100 dark:bg-green-900/30", - }, - { - id: "pending", - label: "Minh chứng chờ duyệt", - valueKey: "pendingEvidence", - icon: "assignment_late", - color: "text-amber-600", - bg: "bg-amber-100 dark:bg-amber-900/30", - }, +const KPI_CARDS = [ + { + id: "events", + label: "Tổng sự kiện", + valueKey: "totalEvents", + icon: "event", + color: "text-blue-600", + bg: "bg-blue-100", + }, + { + id: "students", + label: "Sinh viên tham gia", + valueKey: "participatingStudents", + icon: "groups", + color: "text-emerald-600", + bg: "bg-emerald-100", + }, + { + id: "pending", + label: "Minh chứng chờ duyệt", + valueKey: "pendingEvidence", + icon: "assignment_late", + color: "text-amber-600", + bg: "bg-amber-100", + }, + { + id: "managedStudents", + label: "Sinh viên quản lý", + valueKey: "totalStudents", + icon: "groups", + color: "text-rose-600", + bg: "bg-rose-100", + }, ]; const SCORE_DISTRIBUTION_META = [ - { key: "excellent", label: "Xuất sắc", color: "bg-primary" }, - { key: "good", label: "Tốt", color: "bg-blue-500" }, - { key: "fair", label: "Khá", color: "bg-amber-500" }, - { key: "average", label: "Trung bình", color: "bg-slate-300" }, -]; - -const EVENT_ICON_META = [ - { - icon: "rocket_launch", - iconColor: "text-indigo-600", - iconBg: "bg-indigo-50 dark:bg-indigo-900/20", - }, - { - icon: "volunteer_activism", - iconColor: "text-emerald-600", - iconBg: "bg-emerald-50 dark:bg-emerald-900/20", - }, - { - icon: "sports_basketball", - iconColor: "text-orange-600", - iconBg: "bg-orange-50 dark:bg-orange-900/20", - }, - { - icon: "event_available", - iconColor: "text-sky-600", - iconBg: "bg-sky-50 dark:bg-sky-900/20", - }, - { - icon: "campaign", - iconColor: "text-pink-600", - iconBg: "bg-pink-50 dark:bg-pink-900/20", - }, + { key: "excellent", label: "Xuất sắc", color: "bg-primary" }, + { key: "good", label: "Tốt", color: "bg-blue-500" }, + { key: "fair", label: "Khá", color: "bg-amber-500" }, + { key: "average", label: "Trung bình", color: "bg-slate-400" }, ]; function formatNumber(value) { - const safe = Number(value); - return new Intl.NumberFormat("vi-VN").format(Number.isFinite(safe) ? safe : 0); + const safe = Number(value); + return new Intl.NumberFormat("vi-VN").format(Number.isFinite(safe) ? safe : 0); } function formatPercent(value) { - const safe = Number(value); - if (!Number.isFinite(safe)) { - return "0%"; - } - const rounded = Math.round(safe * 10) / 10; - return `${rounded % 1 === 0 ? rounded.toFixed(0) : rounded.toFixed(1)}%`; + const safe = Number(value); + if (!Number.isFinite(safe)) { + return "0%"; + } + const rounded = Math.round(safe * 10) / 10; + return `${rounded % 1 === 0 ? rounded.toFixed(0) : rounded.toFixed(1)}%`; } function normalizeDistribution(summary) { - const rawItems = Array.isArray(summary?.scoreDistribution) ? summary.scoreDistribution : []; - const byKey = rawItems.reduce((acc, item) => { - if (item?.key) { - acc[item.key] = Number(item.percentage) || 0; - } - return acc; - }, {}); + const rawItems = Array.isArray(summary?.scoreDistribution) ? summary.scoreDistribution : []; + const byKey = rawItems.reduce((acc, item) => { + if (item?.key) { + acc[item.key] = Number(item.percentage) || 0; + } + return acc; + }, {}); - return SCORE_DISTRIBUTION_META.map((meta) => ({ - ...meta, - percentage: byKey[meta.key] ?? 0, - })); + return SCORE_DISTRIBUTION_META.map((meta) => ({ + ...meta, + percentage: Math.max(0, Math.min(100, byKey[meta.key] ?? 0)), + })); } export default function LecturerDashboardOverview({ summary, onCreateEvent, loadingSummary = false }) { - const resolvedSummary = { - totalEvents: summary?.totalEvents ?? 0, - participatingStudents: summary?.participatingStudents ?? 0, - pendingEvidence: summary?.pendingEvidence ?? 0, - }; - const passRate = Number.isFinite(Number(summary?.passRate)) ? Number(summary.passRate) : 0; - const normalizedPassRate = Math.max(0, Math.min(100, passRate)); - const scoreDistribution = normalizeDistribution(summary); - const upcomingEvents = Array.isArray(summary?.upcomingEvents) ? summary.upcomingEvents : []; + const resolvedSummary = { + totalEvents: Number(summary?.totalEvents) || 0, + totalStudents: Number(summary?.totalStudents) || 0, + participatingStudents: Number(summary?.participatingStudents) || 0, + pendingEvidence: Number(summary?.pendingEvidence) || 0, + newNotifications: Number(summary?.newNotifications) || 0, + }; - return ( -
-
- {SUMMARY_CARD_CONFIG.map((card) => ( -
-
- {card.icon} -
-
-

{card.label}

-

- {formatNumber(resolvedSummary[card.valueKey])} -

-
-
- ))} -
+ const passRate = Math.max(0, Math.min(100, Number(summary?.passRate) || 0)); + const scoreDistribution = normalizeDistribution(summary); + const upcomingEvents = Array.isArray(summary?.upcomingEvents) ? summary.upcomingEvents.slice(0, 5) : []; -
-
-
-

Phân bố điểm rèn luyện

- -
+ return ( +
+
+
+
+

Dashboard Giảng viên

+

+ Tổng quan lớp phụ trách, tiến độ duyệt minh chứng và sức khỏe điểm rèn luyện theo học kỳ. +

+
+
+ +
+
+
-
-
-
-
-
- - {formatPercent(normalizedPassRate)} - - Đạt yêu cầu -
-
+
+ {KPI_CARDS.map((card) => ( +
+
+
+

{card.label}

+

+ {formatNumber(resolvedSummary[card.valueKey])} +

+
+ + {card.icon} + +
+
+ ))} +
-
- {scoreDistribution.map((item) => ( -
-
- - {item.label} -
- - {formatPercent(item.percentage)} - -
- ))} -
-
-
+
+
+
+

Sự kiện sắp diễn ra

+ +
-
-
-

Sự kiện sắp diễn ra

- -
+ {loadingSummary ? ( +

Đang tải dữ liệu sự kiện...

+ ) : upcomingEvents.length === 0 ? ( +

Chưa có sự kiện sắp tới trong kỳ này.

+ ) : ( +
+ {upcomingEvents.map((event, index) => ( +
+
+
+

{event.title || "Sự kiện chưa đặt tên"}

+

+ {event.dateLabel || "--/--/----"} · {event.timeLabel || "--:-- - --:--"} +

+

{event.location || "Địa điểm chưa cập nhật"}

+
+
+

Đã đăng ký

+

{formatNumber(event.attendeeCount)}

+
+
+
+ ))} +
+ )} +
-
- - - - - - - - - - - - {loadingSummary ? ( - Array.from({ length: 3 }).map((_, index) => ( - - - - - - - - )) - ) : upcomingEvents.length === 0 ? ( - - - - ) : ( - upcomingEvents.map((event, index) => { - const iconMeta = EVENT_ICON_META[index % EVENT_ICON_META.length]; - return ( - - - - - - - - ); - }) - )} - -
Sự kiệnThời gianĐịa điểmSố lượngThao tác
-
-
-
+
+

Ưu tiên xử lý

+
+
+

Minh chứng đang chờ

+

{formatNumber(resolvedSummary.pendingEvidence)}

+

Nên xử lý trong ngày để tránh dồn backlog.

+
+
+

Thông báo mới

+

{formatNumber(resolvedSummary.newNotifications)}

+

Kiểm tra phản hồi từ lớp và hệ thống.

-
-
-
-
-
-
-
-
-
-
- Chưa có sự kiện sắp diễn ra. -
-
-
- {iconMeta.icon} +
+

Tỷ lệ đạt điểm chuẩn

+

{formatPercent(passRate)}

+
+
-

- {event.title || "Sự kiện chưa đặt tên"} -

-
-
-

{event.dateLabel || "--/--/----"}

-

{event.timeLabel || "--:-- - --:--"}

-
{event.location || "Chưa cập nhật"} -
- {formatNumber(event.attendeeCount)} - /-- -
-
- -
-
-
-
-
- ); +
+
+ + + +
+

Phân bố điểm rèn luyện

+
+ {scoreDistribution.map((item) => ( +
+
+

{item.label}

+

{formatPercent(item.percentage)}

+
+
+ +
+
+ ))} +
+
+
+ ); } diff --git a/frontend/src/features/lecturer/components/LecturerSidebar.jsx b/frontend/src/features/lecturer/components/LecturerSidebar.jsx index 9139f50..c8bd1ac 100644 --- a/frontend/src/features/lecturer/components/LecturerSidebar.jsx +++ b/frontend/src/features/lecturer/components/LecturerSidebar.jsx @@ -12,33 +12,33 @@ export default function LecturerSidebar({
school
-

UniPoint

+

UniPoint Lecture

diff --git a/frontend/src/features/student/components/StudentDashboard.jsx b/frontend/src/features/student/components/StudentDashboard.jsx index 1a70861..dfe54e2 100644 --- a/frontend/src/features/student/components/StudentDashboard.jsx +++ b/frontend/src/features/student/components/StudentDashboard.jsx @@ -1,284 +1,306 @@ import { useAuth } from "../../../context/AuthContext"; import { useStudentDashboard } from "../hooks/useStudentDashboard"; import { useStudentScoreTrend } from "../hooks/useStudentScoreTrend"; -import "../../../styles/StudentDashboard.css"; function getGreetingName(name) { - if (!name) { - return "bạn"; - } - const parts = name.split(" ").filter(Boolean); - return parts[parts.length - 1] || name; -} - -function getEventBadge(startTime) { - if (!startTime) { - return { day: "--", month: "TH--" }; - } - const [datePart] = startTime.split(" "); - const [day, month] = datePart.split("/"); - const monthNumber = Number(month); - return { - day: day || "--", - month: Number.isNaN(monthNumber) ? "TH--" : `TH${monthNumber}`, - }; + if (!name) { + return "bạn"; + } + const parts = String(name).split(" ").filter(Boolean); + return parts[parts.length - 1] || name; } function parseUiDate(createdAt) { - if (!createdAt) { - return null; - } - const [datePart] = createdAt.split(" "); - if (!datePart) { - return null; - } - const [dd, mm, yyyy] = datePart.split("/").map(Number); - if (!dd || !mm || !yyyy) { - return null; - } - return new Date(yyyy, mm - 1, dd); + if (!createdAt) { + return null; + } + const [datePart] = String(createdAt).split(" "); + if (!datePart) { + return null; + } + const [dd, mm, yyyy] = datePart.split("/").map(Number); + if (!dd || !mm || !yyyy) { + return null; + } + return new Date(yyyy, mm - 1, dd); } function getHistoryDateLabel(createdAt) { - const date = parseUiDate(createdAt); - if (!date) { - return "GẦN ĐÂY"; - } - - const current = new Date(); - current.setHours(0, 0, 0, 0); + const date = parseUiDate(createdAt); + if (!date) { + return "GẦN ĐÂY"; + } - const compare = new Date(date); - compare.setHours(0, 0, 0, 0); + const current = new Date(); + current.setHours(0, 0, 0, 0); - const diffDays = Math.round((current - compare) / (1000 * 60 * 60 * 24)); + const compare = new Date(date); + compare.setHours(0, 0, 0, 0); - if (diffDays === 0) { - return "HÔM NAY"; - } - if (diffDays === 1) { - return "HÔM QUA"; - } + const diffDays = Math.round((current - compare) / (1000 * 60 * 60 * 24)); + if (diffDays === 0) { + return "HÔM NAY"; + } + if (diffDays === 1) { + return "HÔM QUA"; + } - const day = String(compare.getDate()).padStart(2, "0"); - const month = compare.getMonth() + 1; - return `${day} THG ${month}`; + const day = String(compare.getDate()).padStart(2, "0"); + const month = compare.getMonth() + 1; + return `${day} THG ${month}`; } function getHistoryHint(status) { - switch (status) { - case "APPROVED": - return "+2 điểm rèn luyện"; - case "REJECTED": - return "Cần cập nhật minh chứng"; - default: - return "Đang chờ duyệt"; - } + switch (status) { + case "APPROVED": + return "+2 điểm rèn luyện"; + case "REJECTED": + return "Cần cập nhật minh chứng"; + default: + return "Đang chờ duyệt"; + } +} + +function statusPill(status) { + const upper = String(status || "PENDING").toUpperCase(); + if (upper === "APPROVED") { + return "border border-green-200 bg-green-50 text-green-700"; + } + if (upper === "REJECTED") { + return "border border-red-200 bg-red-50 text-red-700"; + } + return "border border-yellow-200 bg-yellow-50 text-yellow-700"; +} + +function statusLabel(status) { + const upper = String(status || "PENDING").toUpperCase(); + if (upper === "APPROVED") return "Đã duyệt"; + if (upper === "REJECTED") return "Từ chối"; + return "Chờ duyệt"; } export default function StudentDashboard({ onNavigate }) { - const { user } = useAuth(); - const { dashboard, loading, error } = useStudentDashboard(user?.userId); - const { trend, loading: trendLoading, error: trendError } = useStudentScoreTrend(user?.userId); + const { user } = useAuth(); + const { dashboard, loading, error } = useStudentDashboard(user?.userId); + const { trend, loading: trendLoading, error: trendError } = useStudentScoreTrend(user?.userId); - if (loading) { - return
Đang tải dashboard sinh viên...
; - } + if (loading) { + return
Đang tải dashboard sinh viên...
; + } - if (error) { - return
Không thể tải dữ liệu: {error}
; - } + if (error) { + return
Không thể tải dữ liệu: {error}
; + } - if (!dashboard) { - return
Không có dữ liệu dashboard.
; - } + if (!dashboard) { + return
Không có dữ liệu dashboard.
; + } - const safeScore = Math.max(0, Math.min(100, Number(dashboard.totalScore) || 0)); - const upcomingEvents = Array.isArray(dashboard.upcomingEvents) ? dashboard.upcomingEvents : []; - const attendedEvents = Array.isArray(dashboard.attendedEvents) ? dashboard.attendedEvents : []; - const history = Array.isArray(dashboard.history) ? dashboard.history : []; - const greetingName = getGreetingName(dashboard.fullName); + const safeScore = Math.max(0, Math.min(100, Number(dashboard.totalScore) || 0)); + const upcomingEvents = Array.isArray(dashboard.upcomingEvents) ? dashboard.upcomingEvents : []; + const attendedEvents = Array.isArray(dashboard.attendedEvents) ? dashboard.attendedEvents : []; + const history = Array.isArray(dashboard.history) ? dashboard.history : []; + const greetingName = getGreetingName(dashboard.fullName); + const pendingCount = history.filter((item) => String(item?.status || "").toUpperCase() === "PENDING").length; + const approvedCount = history.filter((item) => String(item?.status || "").toUpperCase() === "APPROVED").length; + const latestHistory = history.slice(0, 5); + const latestEvents = upcomingEvents.slice(0, 4); + + return ( +
+
+
+
+

Chào {greetingName},

+

+ {dashboard.classCode || "--"} · {dashboard.facultyName || "Khoa chưa cập nhật"} +

+

+ Bạn có {pendingCount} minh chứng đang chờ duyệt và đã hoàn thành {approvedCount} minh chứng. +

+
+
+ + + +
+
+
- return ( -
-
-
-
- school -
-
-

Chào buổi sáng, {greetingName}!

-

- Lớp: {dashboard.classCode || "--"} ·{" "} - {dashboard.facultyName || "Khoa đang cập nhật"} -

-
-
+
+
+

Điểm rèn luyện

+

+ {safeScore} + /100 +

+
+ +
+
-
- - -
-
+
+

Sự kiện đã tham gia

+

{dashboard.joinedActivities ?? attendedEvents.length ?? 0}

+

Tổng số hoạt động trong học kỳ hiện tại

+
-
-
-
-

Điểm rèn luyện

- +{(safeScore / 15).toFixed(1)} -
-

- {safeScore}/100 Tốt -

-
- -
-
+
+

Minh chứng chờ duyệt

+

{pendingCount}

+ +
-
onNavigate?.("history")} - > -
-

Hoạt động tham gia

- event_available -
-

{dashboard.joinedActivities}

- Trong học kỳ này -
-
+
+

Sắp diễn ra

+

{latestEvents.length}

+ +
+
-
+
+
+
+

Lịch sử hoạt động gần đây

+ +
-
-
-

Lịch sử hoạt động

-
+ {latestHistory.length === 0 ? ( +

Chưa có dữ liệu hoạt động.

+ ) : ( +
+ {latestHistory.map((item) => ( +
+
+

{item.title || "Hoạt động"}

+

+ {getHistoryDateLabel(item.createdAt)} · {getHistoryHint((item.status || "PENDING").toUpperCase())} +

+
+ + {statusLabel(item.status)} + +
+ ))} +
+ )} +
- {history.length === 0 ? ( -

Chưa có hoạt động.

- ) : ( -
    - {history.map((item) => { - const status = (item.status || "PENDING").toLowerCase(); - return ( -
  • - -
    -

    {getHistoryDateLabel(item.createdAt)}

    - {item.title} - {getHistoryHint((item.status || "PENDING").toUpperCase())} +
    +

    Việc cần làm

    +
    + + +
    -
  • - ); - })} -
- )} -
-
+ +
-
-
-
-

Xu hướng điểm theo học kỳ

-
+
+
+

Xu hướng điểm theo học kỳ

+ +
- {trendLoading ? ( -

Đang tải xu hướng điểm...

- ) : trendError ? ( -

- {trendError} -

- ) : trend.length === 0 ? ( -

Chưa có dữ liệu điểm theo học kỳ.

- ) : ( -
- {trend.map((item) => { - const safeScore = Math.max(0, Math.min(100, Number(item.finalScore) || 0)); - const delta = Number(item.deltaFromPrevious); - const hasDelta = Number.isFinite(delta); - const deltaLabel = hasDelta ? `${delta > 0 ? "+" : ""}${delta}` : "--"; - const deltaColor = !hasDelta - ? "#64748b" - : delta > 0 - ? "#16a34a" - : delta < 0 - ? "#dc2626" - : "#64748b"; + {trendLoading ? ( +

Đang tải xu hướng điểm...

+ ) : trendError ? ( +

{trendError}

+ ) : trend.length === 0 ? ( +

Chưa có dữ liệu điểm theo học kỳ.

+ ) : ( +
+ {trend.map((item) => { + const trendScore = Math.max(0, Math.min(100, Number(item.finalScore) || 0)); + const delta = Number(item.deltaFromPrevious); + const hasDelta = Number.isFinite(delta); + const deltaLabel = hasDelta ? `${delta > 0 ? "+" : ""}${delta}` : "--"; + const deltaClass = !hasDelta + ? "text-slate-500" + : delta > 0 + ? "text-green-600" + : delta < 0 + ? "text-red-600" + : "text-slate-500"; - return ( -
-
- - {item.semesterName || "Học kỳ"} - -
- - {item.rankLabel || "--"} - - - Δ {deltaLabel} - -
-
-
- Điểm: {safeScore}/100 -
-
- + return ( +
+
+

{item.semesterName || "Học kỳ"}

+ Δ {deltaLabel} +
+

{trendScore}/100 · {item.rankLabel || "--"}

+
+ +
+
+ ); + })}
-
- ); - })} -
- )} -
-
-
- ); + )} + +
+ ); } diff --git a/frontend/src/features/student/components/StudentTopHeader.jsx b/frontend/src/features/student/components/StudentTopHeader.jsx index be40fed..81a219c 100644 --- a/frontend/src/features/student/components/StudentTopHeader.jsx +++ b/frontend/src/features/student/components/StudentTopHeader.jsx @@ -5,14 +5,11 @@
school
-

Điểm rèn luyện

+

UniPoint

- diff --git a/frontend/src/pages/LecturerPage.jsx b/frontend/src/pages/LecturerPage.jsx index 64e8006..c73ec3b 100644 --- a/frontend/src/pages/LecturerPage.jsx +++ b/frontend/src/pages/LecturerPage.jsx @@ -36,6 +36,7 @@ export default function LecturerPage() { const [dashboardSummaryLoading, setDashboardSummaryLoading] = useState(true); const [dashboardSummary, setDashboardSummary] = useState({ totalEvents: 0, + totalStudents: 0, participatingStudents: 0, pendingEvidence: 0, newNotifications: 0, @@ -56,6 +57,7 @@ export default function LecturerPage() { if (!ignore && data) { setDashboardSummary({ totalEvents: data.totalEvents || 0, + totalStudents: data.totalStudents || 0, participatingStudents: data.participatingStudents || 0, pendingEvidence: data.pendingEvidence || 0, newNotifications: Number(data.newNotifications || 0), From bf704e840137810257b2c1277585cc442ec6561c Mon Sep 17 00:00:00 2001 From: MinhToanSBO Date: Sun, 19 Apr 2026 00:00:36 +0700 Subject: [PATCH 3/8] =?UTF-8?q?FIX:=20S=E1=BB=ADa=20m=E1=BB=99t=20s?= =?UTF-8?q?=E1=BB=91=20l=E1=BB=97i=20t=E1=BB=91i=20=C6=B0u?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../backend/repository/RecordRepository.java | 82 +++---- .../impl/EvidenceDeclarationServiceImpl.java | 25 +- .../admin/components/AdminStatistics.jsx | 53 +++-- .../components/MonitorEvidenceReviewTab.jsx | 225 ++++++++++++++++-- 4 files changed, 292 insertions(+), 93 deletions(-) diff --git a/backend/src/main/java/ct01/n06/backend/repository/RecordRepository.java b/backend/src/main/java/ct01/n06/backend/repository/RecordRepository.java index c974374..8891c8e 100644 --- a/backend/src/main/java/ct01/n06/backend/repository/RecordRepository.java +++ b/backend/src/main/java/ct01/n06/backend/repository/RecordRepository.java @@ -62,47 +62,47 @@ Optional findByStudentAndSemesterAndEvent( List findByStudent_IdAndSemester_IdAndStatus(String studentId, Long semesterId, RecordStatus status); - @EntityGraph(attributePaths = {"semester", "criteria", "approver"}) - @Query(""" - select r - from RecordEntity r - where r.event is null - and r.student.id = :studentId - and (:status is null or r.status = :status) - and (:semesterId is null or r.semester.id = :semesterId) - order by r.createdAt desc - """) - Page findEvidenceDeclarationsForStudent( - @Param("studentId") String studentId, - @Param("status") RecordStatus status, - @Param("semesterId") Long semesterId, - Pageable pageable - ); - - @EntityGraph(attributePaths = {"student", "student.classEntity", "semester", "criteria", "approver"}) - @Query(""" - select r - from RecordEntity r - join r.student s - left join s.classEntity c - where r.event is null - and c.id = :classId - and (:status is null or r.status = :status) - and (:semesterId is null or r.semester.id = :semesterId) - order by r.createdAt desc - """) - Page findEvidenceDeclarationsForClass( - @Param("classId") Long classId, - @Param("status") RecordStatus status, - @Param("semesterId") Long semesterId, - Pageable pageable - ); - - @EntityGraph(attributePaths = {"semester", "criteria", "approver"}) - Optional findByIdAndStudent_IdAndEventIsNull(Long id, String studentId); - - @EntityGraph(attributePaths = {"student", "student.classEntity", "semester", "criteria", "approver"}) - Optional findByIdAndEventIsNull(Long id); + @EntityGraph(attributePaths = {"semester", "criteria", "approver"}) + @Query(""" + select r + from RecordEntity r + where r.event is null + and r.student.id = :studentId + and (:status is null or r.status = :status) + and (:semesterId is null or r.semester.id = :semesterId) + order by r.createdAt desc + """) + Page findEvidenceDeclarationsForStudent( + @Param("studentId") String studentId, + @Param("status") RecordStatus status, + @Param("semesterId") Long semesterId, + Pageable pageable + ); + + @EntityGraph(attributePaths = {"student", "student.classEntity", "semester", "criteria", "approver"}) + @Query(""" + select r + from RecordEntity r + join r.student s + left join s.classEntity c + where r.event is null + and c.id = :classId + and (:status is null or r.status = :status) + and (:semesterId is null or r.semester.id = :semesterId) + order by r.createdAt desc + """) + Page findEvidenceDeclarationsForClass( + @Param("classId") Long classId, + @Param("status") RecordStatus status, + @Param("semesterId") Long semesterId, + Pageable pageable + ); + + @EntityGraph(attributePaths = {"semester", "criteria", "approver"}) + Optional findByIdAndStudent_IdAndEventIsNull(Long id, String studentId); + + @EntityGraph(attributePaths = {"student", "student.classEntity", "semester", "criteria", "approver"}) + Optional findByIdAndEventIsNull(Long id); long countDistinctStudent_IdByEvent_IdAndStatus(Long eventId, RecordStatus status); diff --git a/backend/src/main/java/ct01/n06/backend/service/impl/EvidenceDeclarationServiceImpl.java b/backend/src/main/java/ct01/n06/backend/service/impl/EvidenceDeclarationServiceImpl.java index 43e7e0b..8f4939f 100644 --- a/backend/src/main/java/ct01/n06/backend/service/impl/EvidenceDeclarationServiceImpl.java +++ b/backend/src/main/java/ct01/n06/backend/service/impl/EvidenceDeclarationServiceImpl.java @@ -36,7 +36,6 @@ import ct01.n06.backend.repository.SemesterRepository; import ct01.n06.backend.repository.StudentRepository; import ct01.n06.backend.service.EvidenceDeclarationService; -import ct01.n06.backend.service.UserService; @Service public class EvidenceDeclarationServiceImpl implements EvidenceDeclarationService { @@ -49,7 +48,6 @@ public class EvidenceDeclarationServiceImpl implements EvidenceDeclarationServic private final ClassRepository classRepository; private final SemesterRepository semesterRepository; private final CriteriaRepository criteriaRepository; - private final UserService userService; private final NotificationRepository notificationRepository; private final NotificationRecipientRepository notificationRecipientRepository; @@ -58,7 +56,6 @@ public EvidenceDeclarationServiceImpl(RecordRepository recordRepository, ClassRepository classRepository, SemesterRepository semesterRepository, CriteriaRepository criteriaRepository, - UserService userService, NotificationRepository notificationRepository, NotificationRecipientRepository notificationRecipientRepository) { this.recordRepository = recordRepository; @@ -66,7 +63,6 @@ public EvidenceDeclarationServiceImpl(RecordRepository recordRepository, this.classRepository = classRepository; this.semesterRepository = semesterRepository; this.criteriaRepository = criteriaRepository; - this.userService = userService; this.notificationRepository = notificationRepository; this.notificationRecipientRepository = notificationRecipientRepository; } @@ -185,7 +181,8 @@ public EvidenceDeclarationDetailResponse rejectMonitorDeclaration(String userId, private EvidenceDeclarationDetailResponse processMonitorReview(String userId, Long declarationId, ReviewEvidenceDeclarationRequest request, RecordStatus targetStatus) { - ClassEntity managedClass = getMonitorManagedClass(userId); + StudentEntity monitorStudent = getStudentByUserId(userId); + ClassEntity managedClass = getManagedClassForMonitor(monitorStudent); RecordEntity declaration = getDeclarationForClassScope(declarationId, managedClass.getId()); ensurePending(declaration); @@ -193,7 +190,10 @@ private EvidenceDeclarationDetailResponse processMonitorReview(String userId, Lo CriteriaEntity criteria = resolveCriteriaForApproval(request, targetStatus); - UserEntity approver = userService.requireCurrentUser(); + UserEntity approver = monitorStudent.getUserEntity(); + if (approver == null) { + throw new ApiException(HttpStatus.FORBIDDEN, "Bạn không có quyền duyệt minh chứng này."); + } declaration.setStatus(targetStatus); declaration.setCriteria(criteria); declaration.setReviewNote(reviewNote); @@ -207,10 +207,15 @@ private EvidenceDeclarationDetailResponse processMonitorReview(String userId, Lo private CriteriaEntity resolveCriteriaForApproval(ReviewEvidenceDeclarationRequest request, RecordStatus targetStatus) { - if (targetStatus != RecordStatus.APPROVED || request == null || request.criteriaId() == null) { + if (targetStatus != RecordStatus.APPROVED) { return null; } + if (request == null || request.criteriaId() == null) { + throw new ApiException(HttpStatus.BAD_REQUEST, + "Tiêu chí là bắt buộc khi duyệt minh chứng."); + } + return criteriaRepository.findById(request.criteriaId()) .orElseThrow(() -> new ApiException(HttpStatus.BAD_REQUEST, "Tiêu chí không tồn tại.")); } @@ -245,6 +250,10 @@ private RecordEntity getDeclarationForClassScope(Long declarationId, Long classI private ClassEntity getMonitorManagedClass(String userId) { StudentEntity monitorStudent = getStudentByUserId(userId); + return getManagedClassForMonitor(monitorStudent); + } + + private ClassEntity getManagedClassForMonitor(StudentEntity monitorStudent) { return classRepository.findByMonitor_Id(monitorStudent.getId()) .orElseThrow(() -> new ApiException(HttpStatus.FORBIDDEN, "Bạn không có quyền thao tác minh chứng.")); @@ -369,4 +378,4 @@ private String formatDateTime(LocalDateTime value) { private PageRequest buildPageRequest(int page, int size) { return PageRequest.of(Math.max(page, 0), Math.min(Math.max(size, 1), MAX_PAGE_SIZE)); } -} \ No newline at end of file +} diff --git a/frontend/src/features/admin/components/AdminStatistics.jsx b/frontend/src/features/admin/components/AdminStatistics.jsx index eff663f..26d1971 100644 --- a/frontend/src/features/admin/components/AdminStatistics.jsx +++ b/frontend/src/features/admin/components/AdminStatistics.jsx @@ -187,7 +187,7 @@ function PieChartCard({ title, description, data }) { function LineChartCard({ title, description, data }) { const width = 760; const height = 280; - const padding = { top: 20, right: 24, bottom: 56, left: 48 }; + const padding = { top: 20, right: 44, bottom: 56, left: 48 }; const chartWidth = width - padding.left - padding.right; const chartHeight = height - padding.top - padding.bottom; const baselineY = padding.top + chartHeight; @@ -269,29 +269,34 @@ function LineChartCard({ title, description, data }) { /> ) : null} - {points.map((point) => ( - - - - {(point.label || "").length > 12 ? `${point.label.slice(0, 11)}…` : point.label} - - - {formatNumber(point.value)} - - - ))} + {points.map((point) => { + const labelText = + (point.label || "").length > 12 ? `${point.label.slice(0, 11)}…` : point.label; + + return ( + + + + {labelText} + + + {formatNumber(point.value)} + + + ); + })}
) : ( diff --git a/frontend/src/features/monitor/components/MonitorEvidenceReviewTab.jsx b/frontend/src/features/monitor/components/MonitorEvidenceReviewTab.jsx index 2ad2688..abf986e 100644 --- a/frontend/src/features/monitor/components/MonitorEvidenceReviewTab.jsx +++ b/frontend/src/features/monitor/components/MonitorEvidenceReviewTab.jsx @@ -5,6 +5,7 @@ import { getMonitorEvidenceDeclarations, rejectMonitorEvidenceDeclaration, } from "../../../api/evidenceDeclarationApi"; +import { getAllCriteria } from "../../../api/evaluationApi"; import { useCurrentSemester } from "../../../hooks/useCurrentSemester"; const STATUS_OPTIONS = [ @@ -13,6 +14,7 @@ const STATUS_OPTIONS = [ { value: "APPROVED", label: "Đã duyệt" }, { value: "REJECTED", label: "Từ chối" }, ]; +const PAGE_SIZE = 20; function statusLabel(status) { if (status === "APPROVED") return "Đã duyệt"; @@ -22,12 +24,12 @@ function statusLabel(status) { function statusPillClass(status) { if (status === "APPROVED") { - return "border border-green-200 bg-green-50 text-green-700"; + return "border border-green-200 bg-green-50 text-green-700 dark:border-green-700/40 dark:bg-green-900/20 dark:text-green-300"; } if (status === "REJECTED") { - return "border border-red-200 bg-red-50 text-red-700"; + return "border border-red-200 bg-red-50 text-red-700 dark:border-red-700/40 dark:bg-red-900/20 dark:text-red-300"; } - return "border border-yellow-200 bg-yellow-50 text-yellow-700"; + return "border border-yellow-200 bg-yellow-50 text-yellow-700 dark:border-yellow-700/40 dark:bg-yellow-900/20 dark:text-yellow-300"; } export default function MonitorEvidenceReviewTab() { @@ -36,12 +38,39 @@ export default function MonitorEvidenceReviewTab() { const [status, setStatus] = useState(""); const [items, setItems] = useState([]); const [loading, setLoading] = useState(false); + const [loadingMore, setLoadingMore] = useState(false); const [error, setError] = useState(""); const [workingId, setWorkingId] = useState(null); + const [page, setPage] = useState(0); + const [totalPages, setTotalPages] = useState(0); const [detailOpen, setDetailOpen] = useState(false); const [detailLoading, setDetailLoading] = useState(false); const [detailError, setDetailError] = useState(""); const [detailItem, setDetailItem] = useState(null); + const [criteriaList, setCriteriaList] = useState([]); + const [criteriaLoading, setCriteriaLoading] = useState(false); + const [reviewOpen, setReviewOpen] = useState(false); + const [reviewAction, setReviewAction] = useState("approve"); + const [reviewTarget, setReviewTarget] = useState(null); + const [reviewCriteriaId, setReviewCriteriaId] = useState(""); + const [reviewNote, setReviewNote] = useState(""); + + useEffect(() => { + const loadCriteria = async () => { + setCriteriaLoading(true); + try { + const data = await getAllCriteria(); + const normalized = Array.isArray(data) ? data : []; + setCriteriaList(normalized); + } catch { + setCriteriaList([]); + } finally { + setCriteriaLoading(false); + } + }; + + loadCriteria(); + }, []); useEffect(() => { if (!selectedSemester && activeSemesterId) { @@ -49,56 +78,116 @@ export default function MonitorEvidenceReviewTab() { } }, [activeSemesterId, selectedSemester]); - const loadData = useCallback(async () => { + const loadData = useCallback(async (targetPage = 0, options = {}) => { + const { append = false } = options; if (!selectedSemester) { setItems([]); + setPage(0); + setTotalPages(0); return; } - setLoading(true); + if (append) { + setLoadingMore(true); + } else { + setLoading(true); + } setError(""); try { const payload = await getMonitorEvidenceDeclarations({ semesterId: Number(selectedSemester), status: status || undefined, - page: 0, - size: 100, + page: targetPage, + size: PAGE_SIZE, }); - setItems(Array.isArray(payload?.items) ? payload.items : []); + const nextItems = Array.isArray(payload?.items) ? payload.items : []; + setItems((prev) => (append ? [...prev, ...nextItems] : nextItems)); + setPage(Number.isFinite(payload?.page) ? payload.page : targetPage); + setTotalPages(Number.isFinite(payload?.totalPages) ? payload.totalPages : 0); } catch (err) { setError(err.message || "Không tải được danh sách minh chứng."); } finally { - setLoading(false); + if (append) { + setLoadingMore(false); + } else { + setLoading(false); + } } }, [selectedSemester, status]); useEffect(() => { - loadData(); + loadData(0, { append: false }); }, [loadData]); - const runReviewAction = useCallback(async (id, action) => { + const runReviewAction = useCallback(async (id, action, payload) => { setWorkingId(id); setError(""); try { if (action === "approve") { - await approveMonitorEvidenceDeclaration(id, {}); + await approveMonitorEvidenceDeclaration(id, payload); } else { - await rejectMonitorEvidenceDeclaration(id, {}); + await rejectMonitorEvidenceDeclaration(id, payload); } - await loadData(); + await loadData(0, { append: false }); + return true; } catch (err) { setError(err.message || "Không thể xử lý minh chứng."); + return false; } finally { setWorkingId(null); } }, [loadData]); - const handleApprove = async (id) => { - await runReviewAction(id, "approve"); + const openReviewModal = (item, action) => { + setReviewTarget(item); + setReviewAction(action); + setReviewNote(""); + setReviewCriteriaId( + action === "approve" && criteriaList.length > 0 + ? String(criteriaList[0].id) + : "", + ); + setReviewOpen(true); + }; + + const closeReviewModal = () => { + setReviewOpen(false); + setReviewTarget(null); + setReviewNote(""); + setReviewCriteriaId(""); + }; + + const handleSubmitReview = async () => { + if (!reviewTarget?.id) { + return; + } + + if (reviewAction === "approve" && !reviewCriteriaId) { + setError("Vui lòng chọn tiêu chí trước khi duyệt minh chứng."); + return; + } + + const payload = { + reviewNote: reviewNote.trim() || undefined, + }; + + if (reviewAction === "approve") { + payload.criteriaId = Number(reviewCriteriaId); + } + + const success = await runReviewAction(reviewTarget.id, reviewAction, payload); + if (success) { + closeReviewModal(); + } }; - const handleReject = async (id) => { - await runReviewAction(id, "reject"); + const hasMore = page + 1 < totalPages; + + const handleLoadMore = async () => { + if (!hasMore || loadingMore) { + return; + } + await loadData(page + 1, { append: true }); }; const handleViewDetail = async (id) => { @@ -198,7 +287,7 @@ export default function MonitorEvidenceReviewTab() {
+
+

+ Trang {Math.min(page + 1, Math.max(totalPages, 1))}/{Math.max(totalPages, 1)} +

+ {hasMore ? ( + + ) : null} +
+ + {reviewOpen ? ( +
+
+
+
+

+ {reviewAction === "approve" ? "Xác nhận duyệt minh chứng" : "Xác nhận từ chối minh chứng"} +

+

+ {reviewTarget?.customName || "Minh chứng"} +

+
+ +
+ + {reviewAction === "approve" ? ( +
+ + +
+ ) : null} + +
+ +