From 800e9c065603252a984dab5c9fffbd1dce3cce19 Mon Sep 17 00:00:00 2001 From: doxxx93 Date: Sat, 5 Dec 2026 19:58:02 +0900 Subject: [PATCH 1/6] =?UTF-8?q?feat(participant):=20=EB=81=9D=EB=82=9C=20?= =?UTF-8?q?=EC=8A=A4=ED=84=B0=EB=94=94=EC=9D=98=20=EC=B0=B8=EC=97=AC?= =?UTF-8?q?=EC=9E=90=EB=A5=BC=20=EC=99=84=EC=A3=BC(COMPLETED)=EB=A1=9C=20?= =?UTF-8?q?=EC=A0=84=ED=99=98=ED=95=9C=EB=8B=A4=20(ZAPP-193)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 스터디가 끝나면 ACTIVE 명부 행을 엔티티 메서드로 COMPLETED 로 바꾸고 행마다 study_participant.completed 를 같은 트랜잭션에서 발행한다 - 1분 간격 스케줄러, 배포 전에 끝난 스터디는 V75 로 이벤트 없이 일괄 전환 - 완주자도 일정 · 출석부 · 회고를 보고, 완주한 네비게이터는 계속 고친다 - 보이는 인원은 완주를 세고 정원 판정은 ACTIVE 그대로. 끝난 스터디는 모집 마감 · 신청 409 - 백오피스 반 카드 인원 · 사이트 출석 탭 일괄 변경 · 탈퇴 운영 알림에 완주 행 포함 --- .prober/tests/participant-completion.md | 25 + .../application/StudyApplicationService.java | 4 + .../api/attendance/AttendanceService.java | 6 +- .../attendance/MyAttendanceController.java | 2 +- .../api/auth/AccountDeletionService.java | 8 +- .../security/GroupRosterGuardInterceptor.java | 3 +- .../api/auth/security/RequireGroupRoster.java | 8 +- .../api/meeting/StudyMeetingService.java | 12 +- .../StudyParticipantCompletionScheduler.java | 44 ++ .../StudyParticipantCompletionService.java | 66 +++ .../api/retro/MeetingRetroService.java | 6 +- .../api/study/BackofficeStudyListService.java | 13 +- .../api/study/BackofficeStudyQueryDao.java | 15 +- .../api/study/StudyCaptainGuard.java | 75 +-- .../api/study/StudyListResponse.java | 19 +- .../studyclub/api/study/StudyListService.java | 8 +- .../AdminStudyParticipantController.java | 2 +- .../AdminStudyParticipantQueryService.java | 10 +- .../api/src/main/resources/application.yml | 6 + ...yApplicationSubmissionIntegrationTest.java | 29 ++ .../audit/AuditRetentionIntegrationTest.java | 7 +- .../auth/AccountDeletionIntegrationTest.java | 16 +- ...tedParticipantReadPathIntegrationTest.java | 464 ++++++++++++++++++ ...yParticipantCompletionIntegrationTest.java | 250 ++++++++++ ...udyParticipantCompletionSchedulerTest.java | 26 + .../study/AdminStudyQueryIntegrationTest.java | 53 +- .../api/src/test/resources/application.yml | 5 + .../domain/participant/StudyParticipant.java | 20 + .../StudyParticipantCompleted.java | 38 ++ .../StudyParticipantRepository.java | 36 ++ .../com/studyclub/domain/study/Study.java | 7 +- .../domain/study/StudyLifecycleQuery.java | 11 +- ...complete_participants_of_ended_studies.sql | 12 + .../participant/StudyParticipantTest.java | 33 ++ .../com/studyclub/domain/study/StudyTest.java | 18 + .../features/participants/GroupsSection.tsx | 4 +- .../participants/ParticipantsTab.test.tsx | 12 + .../attendance/AttendanceTabContent.test.tsx | 72 +++ .../attendance/AttendanceTabContent.tsx | 18 +- .../console/components/NextCohortDialog.tsx | 2 +- .../playground/src/proto/specs/club-cohort.ts | 2 +- 41 files changed, 1367 insertions(+), 100 deletions(-) create mode 100644 .prober/tests/participant-completion.md create mode 100644 backend/api/src/main/java/com/studyclub/api/participant/StudyParticipantCompletionScheduler.java create mode 100644 backend/api/src/main/java/com/studyclub/api/participant/StudyParticipantCompletionService.java create mode 100644 backend/api/src/test/java/com/studyclub/api/participant/CompletedParticipantReadPathIntegrationTest.java create mode 100644 backend/api/src/test/java/com/studyclub/api/participant/StudyParticipantCompletionIntegrationTest.java create mode 100644 backend/api/src/test/java/com/studyclub/api/participant/StudyParticipantCompletionSchedulerTest.java create mode 100644 backend/domain/src/main/java/com/studyclub/domain/participant/StudyParticipantCompleted.java create mode 100644 backend/domain/src/main/resources/db/migration/V75__complete_participants_of_ended_studies.sql create mode 100644 frontend/apps/core-front/src/features/attendance/AttendanceTabContent.test.tsx diff --git a/.prober/tests/participant-completion.md b/.prober/tests/participant-completion.md new file mode 100644 index 000000000..94d64ecbf --- /dev/null +++ b/.prober/tests/participant-completion.md @@ -0,0 +1,25 @@ +# 끝난 스터디의 완주 전환 (ZAPP #193) + +대상: stage (`backend-develop` · `back-office-front-develop` · `core-front-develop`). 스펙 [study-participant 「완주」](../../specs/study-participant/spec.md#완주-active--completed). 스테이지의 테스트 계정만 쓴다. 담당 캡틴 계정 하나, 같은 반의 네비게이터 · 크루 계정 하나씩, 그 반에서 참여를 중단한 크루 계정 하나로 한다. 결과 · 캡처에 실제 회원 정보와 토큰을 남기지 않는다. + +준비: 진행 중(OPEN, 시작일 지남)인 테스트 스터디 하나와 지난 회차 하나 이상. 그 스터디의 최근 모집 회차는 마감일이 없거나 아직 지나지 않았고 정원이 남아 있어야 한다(모집이 이미 마감돼 있으면 `CP-LIST-01` · `CP-APPLY-01` 이 이번 변경 없이도 같은 결과를 낸다). 크루가 발표자인 회차가 하나 있으면 `CP-VIEW-01` 을 함께 본다. 화면에서는 종료일을 넣을 수 없으므로 **DB 권한자가 그 스터디의 `STUDY.END_AT` 을 지금보다 몇 분 뒤(UTC)로 바꿔 둔다**. 스테이지는 Flyway 를 끄고 있어 `V75` 가 돌지 않는다. 그래서 전환은 스케줄러로만 확인한다. + +| ID | 절차 | 기대 결과 | +|---|---|---| +| CP-BEFORE-01 | `END_AT` 이 지나기 전에 캡틴으로 백오피스 › 스터디 › 신청자 탭을 연다 | 네비게이터 · 크루가 보이고 인원 수에 든다. 참여 중단한 크루는 보이지 않는다 | +| CP-BEFORE-02 | `END_AT` 이 지나기 전에 `GET /api/studies?keyword={스터디 제목}` | 그 스터디의 `canApply` 가 `true`, `recruitStatus` 가 `RECRUITING` | +| CP-RUN-01 | `END_AT` 이 지나고 1~2분 뒤 같은 탭을 새로고침한다 | 네비게이터 · 크루가 그대로 보이고, `참여 크루 N명` 과 반 카드의 인원도 그대로다(0명으로 바뀌지 않는다). 두 사람의 선택 칸이 잠긴다(완주 행은 반 · 역할을 고치지 않는다) | +| CP-RUN-02 | 서버 로그에서 `완주 전환 실패` 를 찾는다 | 이 스터디로 남은 줄이 없다 | +| CP-VIEW-01 | 크루로 사용자 사이트 › 내 스터디룸 › 그 스터디 › 일정 탭 | 일정이 보인다(403 이 아니다). 크루가 맡은 발표자 칸이 `(참여 종료)` 로 바뀌지 않는다 | +| CP-VIEW-02 | 크루로 출석 탭 | 출석부가 보이고, 네비게이터 · 크루가 명단에 있다. 참여 중단한 크루는 없다 | +| CP-VIEW-03 | 크루로 `GET /api/me/studies/{id}/retros/status` (반을 주지 않는다) | 200 | +| CP-EDIT-01 | 네비게이터로 출석 탭에서 지난 회차의 크루 칸을 출석으로 바꿔 저장 | 저장된다. 새로고침해도 출석으로 남는다 | +| CP-EDIT-02 | 네비게이터로 출석 탭에서 크루의 선택 칸을 고른다 | 선택된다. 「출석 상태」 일괄 변경을 쓸 수 있고, 「참여 중단」 버튼은 잠기며 `끝난 스터디에서는 참여 중단할 수 없습니다.` 가 보인다 | +| CP-MY-01 | 크루로 사용자 사이트 › 내 스터디룸 | 그 스터디 카드가 「참여 종료」 탭에 있고 「완주」 배지와 `완주를 축하합니다!` 출석 점수판이 보인다 | +| CP-DENY-01 | 참여를 중단한 크루로 그 스터디의 일정 탭 | 지금처럼 볼 수 없다(403) | +| CP-LIST-01 | `GET /api/studies?keyword={스터디 제목}` | 그 스터디의 `currentApplicants` 가 0 이 아니라 완주한 사람 수다. `canApply` 는 `false`, `recruitStatus` 는 `RECRUIT_CLOSED` (`CP-BEFORE-02` 에서는 `true` · `RECRUITING`) | +| CP-LIST-02 | 백오피스 스터디 목록을 `지원 현황` 열로 내림차순 정렬 | 그 스터디의 지원 현황이 완주한 사람 수로 보이고, 그 수로 정렬된다(0명으로 맨 뒤에 가지 않는다) | +| CP-APPLY-01 | 디스코드를 연동한 새 크루 계정으로 그 스터디에 `POST /api/studies/{id}/applications` | 409 `모집이 마감되었습니다.` 신청 행이 생기지 않는다 | +| CP-API-01 | 크루로 `GET /api/me/studies/{id}/attendances?studyGroupId={반}` | 200. 네비게이터 · 크루 줄의 `participantStatus` 가 `COMPLETED` | + +로컬 회귀 테스트: `backend/api/src/test/java/com/studyclub/api/participant/` (`StudyParticipantCompletionIntegrationTest` · `StudyParticipantCompletionSchedulerTest` · `CompletedParticipantReadPathIntegrationTest`), `backend/api/src/test/java/com/studyclub/api/application/StudyApplicationSubmissionIntegrationTest` (`rejectsEndedStudy`), `backend/domain/src/test/java/com/studyclub/domain/participant/StudyParticipantTest`, `backend/domain/src/test/java/com/studyclub/domain/study/StudyTest` (`canApply_endedStudy`), 백오피스 `src/features/participants/ParticipantsTab.test.tsx`, core-front `src/features/attendance/AttendanceTabContent.test.tsx`. diff --git a/backend/api/src/main/java/com/studyclub/api/application/StudyApplicationService.java b/backend/api/src/main/java/com/studyclub/api/application/StudyApplicationService.java index 6fa312488..73ac7fb63 100644 --- a/backend/api/src/main/java/com/studyclub/api/application/StudyApplicationService.java +++ b/backend/api/src/main/java/com/studyclub/api/application/StudyApplicationService.java @@ -107,6 +107,10 @@ public Long submit(Long accountId, Long studyId, SubmitStudyApplicationRequest r if (study.getStatus() != StudyStatus.OPEN) { throw new BusinessException(ErrorCode.NOT_FOUND); } + // 끝난 스터디는 받지 않는다. 완주 전환으로 ACTIVE 가 줄면 정원이 다시 비고, 신청서 없는 완주 행이 아래 joinRoster 에서 되살아난다 + if (study.isEnded(Instant.now())) { + throw new BusinessException(ErrorCode.CONFLICT, "모집이 마감되었습니다."); + } StudyRecruitment recruitment = openRecruitment(studyId); checkCapacity(recruitment, studyId); List questions = formQuestionReader.questionsOf(study); diff --git a/backend/api/src/main/java/com/studyclub/api/attendance/AttendanceService.java b/backend/api/src/main/java/com/studyclub/api/attendance/AttendanceService.java index 3e214d06b..ae6128eaa 100644 --- a/backend/api/src/main/java/com/studyclub/api/attendance/AttendanceService.java +++ b/backend/api/src/main/java/com/studyclub/api/attendance/AttendanceService.java @@ -41,6 +41,10 @@ public class AttendanceService { // 자체가 실패할 때만 쓰인다 — 즉 DELETED(회원 탈퇴)인 참가자. private static final String DELETED_ACCOUNT_NICKNAME = "탈퇴한 회원"; + /** 기본 명단({@code includeWithdrawn=false}) — 참여 중과 완주. 끝난 스터디의 출석부가 비지 않게 완주자를 넣는다. */ + private static final Set DEFAULT_ROSTER_STATUSES = + Set.of(ParticipantStatus.ACTIVE, ParticipantStatus.COMPLETED); + private final StudyRepository studyRepository; private final StudyGroupRepository studyGroupRepository; private final StudyParticipantRepository studyParticipantRepository; @@ -101,7 +105,7 @@ public AttendanceResponse getAttendances( includeWithdrawn ? allParticipants : allParticipants.stream() - .filter(p -> p.getStatus() == ParticipantStatus.ACTIVE) + .filter(p -> DEFAULT_ROSTER_STATUSES.contains(p.getStatus())) .toList(); List allMeetings = studyMeetingRepository.findByStudyGroupIdOrderByScheduledAt(studyGroupId); diff --git a/backend/api/src/main/java/com/studyclub/api/attendance/MyAttendanceController.java b/backend/api/src/main/java/com/studyclub/api/attendance/MyAttendanceController.java index 8a0a7bcbf..4e7ae4b1a 100644 --- a/backend/api/src/main/java/com/studyclub/api/attendance/MyAttendanceController.java +++ b/backend/api/src/main/java/com/studyclub/api/attendance/MyAttendanceController.java @@ -41,7 +41,7 @@ public MyAttendanceController( @Operation( summary = "출석 명부 조회", description = - "지정한 분반의 명부. 그 스터디의 활성 참여자(크루 · 다른 반 네비게이터 포함, 보기만) · 그 분반 네비게이터 · 캡틴" + "지정한 분반의 명부. 그 스터디의 참여자(크루 · 다른 반 네비게이터 · 완주자 포함, 보기만) · 그 분반 네비게이터 · 캡틴" + " (specs/authz-guards).") @SecurityRequirement(name = "bearerAuth") @RequireOnboarding diff --git a/backend/api/src/main/java/com/studyclub/api/auth/AccountDeletionService.java b/backend/api/src/main/java/com/studyclub/api/auth/AccountDeletionService.java index 62365240a..b685646f2 100644 --- a/backend/api/src/main/java/com/studyclub/api/auth/AccountDeletionService.java +++ b/backend/api/src/main/java/com/studyclub/api/auth/AccountDeletionService.java @@ -221,7 +221,8 @@ private void cancelEventRegistrations(Long accountId) { // 참여 중단 · 발표 신청과 같은 분반 잠금을 먼저 쥔다 — 그 사이에 커밋된 참여 중단의 상태 · LEFT_AT 을 덮어쓰지 않는다 (share 10-18 D7). // 분반은 ID 오름차순으로 잠근다 — 여러 분반을 잠그는 참여 중단도 이 순서다. 디스코드 출석은 분반이 아니라 회차만, 같은 분반 ID 오름차순으로 잠근다 - // 표시하기 직전에 명부에 있던(ACTIVE·PAUSED) 행을 돌려준다 — 디스코드 role 이 남아 있을 수 있는 곳이다 + // 표시하기 직전에 명부에 있던(ACTIVE·PAUSED·COMPLETED) 행을 돌려준다 — 디스코드 role 이 남아 있을 수 있는 곳이다. 완주해도 role 은 떼지 + // 않는다 private List anonymizeParticipations(Long accountId) { List groupIds = studyParticipantRepository.findStudyGroupIdsByAccountId(accountId); for (Long groupId : groupIds) { @@ -234,8 +235,11 @@ private List anonymizeParticipations(Long accountId) { .filter( p -> p.getStatus() == ParticipantStatus.ACTIVE - || p.getStatus() == ParticipantStatus.PAUSED) + || p.getStatus() == ParticipantStatus.PAUSED + || p.getStatus() == ParticipantStatus.COMPLETED) .toList(); + // 그중 LEADER 행은 권한 말소로 남긴다 — 완주한 네비게이터도 끝난 스터디의 출석 · 일정을 고칠 수 있다 + // (StudyCaptainGuard.NAVIGATOR_STATUSES) for (StudyParticipant participant : onRoster) { if (participant.getParticipantRole() == ParticipantRole.LEADER) { auditRecorder.record( diff --git a/backend/api/src/main/java/com/studyclub/api/auth/security/GroupRosterGuardInterceptor.java b/backend/api/src/main/java/com/studyclub/api/auth/security/GroupRosterGuardInterceptor.java index b6cef87f1..ad463f7f9 100644 --- a/backend/api/src/main/java/com/studyclub/api/auth/security/GroupRosterGuardInterceptor.java +++ b/backend/api/src/main/java/com/studyclub/api/auth/security/GroupRosterGuardInterceptor.java @@ -14,8 +14,7 @@ import org.springframework.web.servlet.HandlerMapping; /** - * {@link RequireGroupRoster} 이 붙은 핸들러 앞에서 그 분반의 활성 참여자·네비게이터·캡틴 여부를 확인한다 - * (specs/authz-guards/spec.md). + * {@link RequireGroupRoster} 이 붙은 핸들러 앞에서 그 분반의 참여자·네비게이터·캡틴 여부를 확인한다 (specs/authz-guards/spec.md). */ @Component public class GroupRosterGuardInterceptor implements HandlerInterceptor { diff --git a/backend/api/src/main/java/com/studyclub/api/auth/security/RequireGroupRoster.java b/backend/api/src/main/java/com/studyclub/api/auth/security/RequireGroupRoster.java index c9dc8e2d9..559806031 100644 --- a/backend/api/src/main/java/com/studyclub/api/auth/security/RequireGroupRoster.java +++ b/backend/api/src/main/java/com/studyclub/api/auth/security/RequireGroupRoster.java @@ -6,9 +6,9 @@ import java.lang.annotation.Target; /** - * 그 분반의 활성 참여자(크루 포함) · 네비게이터 · 캡틴만 호출할 수 있다 — {@link GroupRosterGuardInterceptor} 가 검사한다 - * (specs/authz-guards/spec.md). 조회 전용 엔드포인트에 사용하며, 수정 권한이 필요할 때는 {@link RequireCaptainOrNavigator} - * 를 쓴다. + * 그 분반의 참여자(크루 포함, {@code StudyCaptainGuard.VIEWER_STATUSES}) · 네비게이터 · 캡틴만 호출할 수 있다 — {@link + * GroupRosterGuardInterceptor} 가 검사한다 (specs/authz-guards/spec.md). 조회 전용 엔드포인트에 사용하며, 수정 권한이 필요할 + * 때는 {@link RequireCaptainOrNavigator} 를 쓴다. * *

path {@code studyId} + query/path {@code studyGroupId} 조합으로 분반을 특정한다. 다른 분반 소속이면 403. */ @@ -20,6 +20,6 @@ String studyGroupIdParam() default "studyGroupId"; - /** true 면 그 분반이 아니어도 같은 스터디의 활성 참여자는 통과한다 — 다른 반을 보기만 하는 조회용. */ + /** true 면 그 분반이 아니어도 같은 스터디의 참여자는 통과한다 — 다른 반을 보기만 하는 조회용. */ boolean wholeStudy() default false; } diff --git a/backend/api/src/main/java/com/studyclub/api/meeting/StudyMeetingService.java b/backend/api/src/main/java/com/studyclub/api/meeting/StudyMeetingService.java index b2200fd12..37d94bb28 100644 --- a/backend/api/src/main/java/com/studyclub/api/meeting/StudyMeetingService.java +++ b/backend/api/src/main/java/com/studyclub/api/meeting/StudyMeetingService.java @@ -186,7 +186,7 @@ private StudyMeetingListResponse listView( List navigatorNames = roster.stream() .filter(p -> p.getParticipantRole() == ParticipantRole.LEADER) - .filter(p -> StudyCaptainGuard.ROSTER_STATUSES.contains(p.getStatus())) + .filter(p -> StudyCaptainGuard.NAVIGATOR_STATUSES.contains(p.getStatus())) .map(p -> nameByAccount.get(p.getAccountId())) .filter(Objects::nonNull) .toList(); @@ -194,7 +194,7 @@ private StudyMeetingListResponse listView( Long myParticipantId = roster.stream() .filter(p -> p.getAccountId().equals(accountId)) - .filter(p -> StudyCaptainGuard.ROSTER_STATUSES.contains(p.getStatus())) + .filter(p -> StudyCaptainGuard.VIEWER_STATUSES.contains(p.getStatus())) .map(StudyParticipant::getId) .findFirst() .orElse(null); @@ -506,7 +506,7 @@ private StudyMeetingListResponse.PresenterView presenter( return new StudyMeetingListResponse.PresenterView( participantId, nameByAccount.get(participant.getAccountId()), - StudyCaptainGuard.ROSTER_STATUSES.contains(participant.getStatus())); + StudyCaptainGuard.VIEWER_STATUSES.contains(participant.getStatus())); } private Map nicknames(List roster) { @@ -537,13 +537,13 @@ private StudyGroup lockGroup(Long groupId) { } // 분반을 안 주면 이 스터디의 내 명부 행이 속한 분반 — 명부에 없는 캡틴은 분반을 골라 와야 한다. - // WITHDRAWN/COMPLETED 행을 건너뛰어 재합류(다른 반) 크루가 구 반 ID 를 받지 않도록 한다. - // 활성 네비게이터는 항상 ACTIVE/PAUSED 행이 있으므로 orElseThrow 에 도달하지 않는다. + // WITHDRAWN 행을 건너뛰어 재합류(다른 반) 크루가 구 반 ID 를 받지 않도록 한다. 완주(COMPLETED)는 끝난 스터디의 내 반이다. + // 네비게이터는 항상 NAVIGATOR_STATUSES 행이 있으므로 orElseThrow 에 도달하지 않는다. private Long myGroupId(Long accountId, Long studyId) { account(accountId); return studyParticipantRepository .findFirstByStudyIdAndAccountIdAndStatusIn( - studyId, accountId, StudyCaptainGuard.ROSTER_STATUSES) + studyId, accountId, StudyCaptainGuard.VIEWER_STATUSES) .map(StudyParticipant::getStudyGroupId) .orElseThrow( () -> diff --git a/backend/api/src/main/java/com/studyclub/api/participant/StudyParticipantCompletionScheduler.java b/backend/api/src/main/java/com/studyclub/api/participant/StudyParticipantCompletionScheduler.java new file mode 100644 index 000000000..194138bc0 --- /dev/null +++ b/backend/api/src/main/java/com/studyclub/api/participant/StudyParticipantCompletionScheduler.java @@ -0,0 +1,44 @@ +package com.studyclub.api.participant; + +import java.time.Instant; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; +import org.springframework.scheduling.annotation.EnableScheduling; +import org.springframework.scheduling.annotation.Scheduled; +import org.springframework.stereotype.Component; + +/** + * 1분마다 끝난 스터디의 명부를 완주로 바꾼다 ({@link StudyParticipantCompletionService}). 클럽 기수는 {@code END_AT}(다음 달 + * 1일 0시)이 지나면 1분 안에 넘어간다. + * + *

스케줄링을 켜는 다른 설정은 각자 끌 수 있어 여기서도 켠다. 테스트는 {@code study.participant-completion.enabled=false} 로 + * 끄고 서비스를 직접 부른다. + */ +@Component +@EnableScheduling +@ConditionalOnProperty(value = "study.participant-completion.enabled", matchIfMissing = true) +public class StudyParticipantCompletionScheduler { + + private static final Logger log = + LoggerFactory.getLogger(StudyParticipantCompletionScheduler.class); + + private final StudyParticipantCompletionService completionService; + + public StudyParticipantCompletionScheduler( + StudyParticipantCompletionService completionService) { + this.completionService = completionService; + } + + @Scheduled(fixedDelayString = "${study.participant-completion.fixed-delay-ms:60000}") + public void run() { + Instant now = Instant.now(); + for (Long studyId : completionService.findCandidates(now)) { + try { + completionService.complete(studyId, now); + } catch (RuntimeException e) { + log.error("완주 전환 실패 studyId={}", studyId, e); + } + } + } +} diff --git a/backend/api/src/main/java/com/studyclub/api/participant/StudyParticipantCompletionService.java b/backend/api/src/main/java/com/studyclub/api/participant/StudyParticipantCompletionService.java new file mode 100644 index 000000000..c353a9682 --- /dev/null +++ b/backend/api/src/main/java/com/studyclub/api/participant/StudyParticipantCompletionService.java @@ -0,0 +1,66 @@ +package com.studyclub.api.participant; + +import com.studyclub.domain.participant.StudyParticipant; +import com.studyclub.domain.participant.StudyParticipantCompleted; +import com.studyclub.domain.participant.StudyParticipantRepository; +import com.studyclub.domain.study.Study; +import com.studyclub.domain.study.StudyRepository; +import java.time.Instant; +import java.util.List; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** + * 끝난 스터디의 명부를 완주로 바꾼다 (specs/study-participant/spec.md 「완주」). 후보는 잠금 없이 고르고, 스터디마다 스터디 행을 잠근 뒤 다시 + * 판정한다 — 고른 뒤 운영자가 종료일을 늦췄을 수 있다. 서버가 여러 대여도 스터디 행 잠금이 줄을 세우고, 늦은 쪽은 바꿀 행이 없어 이벤트를 다시 내지 않는다. + * + *

벌크 UPDATE 를 쓰지 않는다 — 행마다 {@link StudyParticipant#complete()} 를 거쳐야 완주 이벤트가 바뀐 행마다 하나씩 난다. + */ +@Service +public class StudyParticipantCompletionService { + + private final StudyRepository studyRepository; + private final StudyParticipantRepository studyParticipantRepository; + private final ApplicationEventPublisher eventPublisher; + + public StudyParticipantCompletionService( + StudyRepository studyRepository, + StudyParticipantRepository studyParticipantRepository, + ApplicationEventPublisher eventPublisher) { + this.studyRepository = studyRepository; + this.studyParticipantRepository = studyParticipantRepository; + this.eventPublisher = eventPublisher; + } + + /** 끝났는데 완주로 넘어갈 행이 남은 스터디 ID, 오름차순. */ + @Transactional(readOnly = true) + public List findCandidates(Instant now) { + return studyParticipantRepository.findEndedStudyIdsWithStatusIn( + now, StudyParticipant.COMPLETABLE_STATUSES); + } + + /** + * 스터디 하나를 완주 처리한다. 부른 쪽의 트랜잭션에 합류한다 — 스터디를 끝내는 쪽이 같은 트랜잭션에서 스터디 행을 잠그거나 상태를 바꾼 뒤 불러도 그 변경을 보고, + * 같은 행을 다시 기다리지 않는다. 스케줄러는 트랜잭션 없이 부르므로 스터디마다 따로 커밋되고, 실패하면 그 스터디만 롤백된다. + * + * @return 완주로 바꾼 행 수. 스터디가 없거나 아직 안 끝났으면 0 + */ + @Transactional + public int complete(Long studyId, Instant now) { + Study study = studyRepository.findByIdForUpdate(studyId).orElse(null); + if (study == null || !study.isEnded(now)) { + return 0; + } + int completed = 0; + for (StudyParticipant participant : + studyParticipantRepository.findByStudyIdAndStatusInForUpdate( + studyId, StudyParticipant.COMPLETABLE_STATUSES)) { + if (participant.complete()) { + eventPublisher.publishEvent(StudyParticipantCompleted.of(participant)); + completed++; + } + } + return completed; + } +} diff --git a/backend/api/src/main/java/com/studyclub/api/retro/MeetingRetroService.java b/backend/api/src/main/java/com/studyclub/api/retro/MeetingRetroService.java index 4587f23c9..30edcc765 100644 --- a/backend/api/src/main/java/com/studyclub/api/retro/MeetingRetroService.java +++ b/backend/api/src/main/java/com/studyclub/api/retro/MeetingRetroService.java @@ -74,13 +74,13 @@ public MeetingRetroService( @Transactional(readOnly = true) public MeetingRetroResponses.RetroStatus retroStatus( Long accountId, Long studyId, Long studyGroupId) { - // studyGroupId 없으면 내 반 감지 + // studyGroupId 없으면 내 반 감지 — 마지막 회차의 회고 기간은 스터디가 끝난 뒤까지 이어져 완주한 반도 찾는다 Long groupId = studyGroupId; if (groupId == null) { groupId = participantRepository .findFirstByStudyIdAndAccountIdAndStatusIn( - studyId, accountId, StudyCaptainGuard.ROSTER_STATUSES) + studyId, accountId, StudyCaptainGuard.VIEWER_STATUSES) .map(StudyParticipant::getStudyGroupId) .orElseThrow( () -> @@ -479,7 +479,7 @@ private boolean isNavigatorOrCaptain(Account account, Long accountId, Long group groupId, accountId, List.of(ParticipantRole.LEADER), - StudyCaptainGuard.ROSTER_STATUSES); + StudyCaptainGuard.NAVIGATOR_STATUSES); } /** retroIds 에 달린 공감 전체를 한 번에 조회해 retroId → section → 수 로 집계한다. */ diff --git a/backend/api/src/main/java/com/studyclub/api/study/BackofficeStudyListService.java b/backend/api/src/main/java/com/studyclub/api/study/BackofficeStudyListService.java index 55bc43a55..b074b333c 100644 --- a/backend/api/src/main/java/com/studyclub/api/study/BackofficeStudyListService.java +++ b/backend/api/src/main/java/com/studyclub/api/study/BackofficeStudyListService.java @@ -127,11 +127,17 @@ private List toSummaries( StudyRecruitment::getStudyId, r -> r, (a, b) -> a)); // 정원을 차지하는 인원 — 명부 ACTIVE 중 정원 역할 (결정 D4-A, study-recruit-status/spec.md) - Map crewCounts = + Map capacityHolders = studyParticipantRepository .countCapacityHoldersByStudyIds(studyIds, ParticipantRole.CAPACITY_ROLES) .stream() .collect(Collectors.toMap(row -> (Long) row[0], row -> (Long) row[1])); + // 보이는 인원 — 끝난 스터디는 완주자를 센다. 「인원」 정렬(BackofficeStudyQueryDao.CREW_COUNT)과 같은 기준 + Map crewCounts = + studyParticipantRepository + .countCrewByStudyIds(studyIds, ParticipantRole.CAPACITY_ROLES) + .stream() + .collect(Collectors.toMap(row -> (Long) row[0], row -> (Long) row[1])); Map programs = studyProgramRepository @@ -164,6 +170,8 @@ private List toSummaries( : null; Instant deadline = recruitment != null ? recruitment.getRecruitDeadlineAt() : null; + long capacityHolderCount = + capacityHolders.getOrDefault(study.getId(), 0L); long crewCount = crewCounts.getOrDefault(study.getId(), 0L); StudyProgram program = Optional.ofNullable(programs.get(study.getProgramId())) @@ -187,7 +195,8 @@ private List toSummaries( program.getStudyKind(), capacity, crewCount, - study.recruitStatus(crewCount, deadline, capacity, asOf), + study.recruitStatus( + capacityHolderCount, deadline, capacity, asOf), recruitment != null ? recruitment.getStartAt() : null, deadline, TimeZoneFormatService.formatDeadline( diff --git a/backend/api/src/main/java/com/studyclub/api/study/BackofficeStudyQueryDao.java b/backend/api/src/main/java/com/studyclub/api/study/BackofficeStudyQueryDao.java index cd17802c4..2e99cf5a4 100644 --- a/backend/api/src/main/java/com/studyclub/api/study/BackofficeStudyQueryDao.java +++ b/backend/api/src/main/java/com/studyclub/api/study/BackofficeStudyQueryDao.java @@ -23,20 +23,29 @@ class BackofficeStudyQueryDao implements BackofficeStudyDao { // 정원을 차지하는 인원 — 명부 ACTIVE 중 정원 역할 (결정 D4-A, study-recruit-status/spec.md). // Study.recruitStatus() 에 crewCount 로 넘기는 값과 같은 기준이다. - private static final String CREW_COUNT = + private static final String CAPACITY_HOLDER_COUNT = "(SELECT COUNT(p.ID) FROM STUDY_PARTICIPANT p" + " WHERE p.STUDY_ID = s.ID" + " AND p.STATUS = 'ACTIVE'" + " AND p.PARTICIPANT_ROLE IN ('MEMBER', 'LEADER'))"; + // 보이는 인원 — 완주(COMPLETED)도 센다. 「인원」 정렬이 끝난 스터디를 0명으로 밀어내지 않게. + // StudyParticipantRepository.countCrewByStudyIds 와 같은 기준이다. + private static final String CREW_COUNT = + "(SELECT COUNT(p.ID) FROM STUDY_PARTICIPANT p" + + " WHERE p.STUDY_ID = s.ID" + + " AND p.STATUS IN ('ACTIVE', 'COMPLETED')" + + " AND p.PARTICIPANT_ROLE IN ('MEMBER', 'LEADER'))"; + // Study.recruitStatus()의 조회 조건. 명부 ACTIVE 인원을 세며 신청서 수를 쓰지 않는다 (결정 D4-A). - // OPEN의 null 마감·null 정원·모집 회차 없음도 기존 엔티티와 동일하게 처리한다. + // OPEN의 null 마감·null 정원·모집 회차 없음도 기존 엔티티와 동일하게 처리한다. END_AT 이 지난 OPEN 은 끝난 스터디라 모집 마감이다. // 정책 변경 시 AdminStudyQueryIntegrationTest의 엔티티 대비 검증도 함께 유지한다. private static final String RECRUITING = "(s.STATUS = 'OPEN'" + + " AND (s.END_AT IS NULL OR s.END_AT > :asOf)" + " AND (r.RECRUIT_DEADLINE_AT IS NULL OR r.RECRUIT_DEADLINE_AT > :asOf)" + " AND (r.RECRUITMENT_CAPACITY IS NULL OR " - + CREW_COUNT + + CAPACITY_HOLDER_COUNT + " < r.RECRUITMENT_CAPACITY))"; private static final String RECRUIT_ORDER = "CASE WHEN " + RECRUITING + " THEN 0 ELSE 1 END"; diff --git a/backend/api/src/main/java/com/studyclub/api/study/StudyCaptainGuard.java b/backend/api/src/main/java/com/studyclub/api/study/StudyCaptainGuard.java index efd505579..648908b60 100644 --- a/backend/api/src/main/java/com/studyclub/api/study/StudyCaptainGuard.java +++ b/backend/api/src/main/java/com/studyclub/api/study/StudyCaptainGuard.java @@ -29,16 +29,26 @@ public class StudyCaptainGuard { private static final List NAVIGATOR_ROLES = List.of(ParticipantRole.LEADER); - // 참여 중단(WITHDRAWN)만 뺀다 — 완주자도 지난 자료는 본다 - private static final List LINK_VIEWER_STATUSES = + /** + * 분반의 활성 명부 — 쉬는 중(PAUSED)도 그 분반 사람이다. 공지 받는 사람 · 발표자 후보 · 새 회차의 출석 행처럼 앞으로의 일에 끼는 사람을 고를 때 쓴다. + * 완주(COMPLETED)는 끝난 스터디에만 있어 넣지 않는다. + */ + public static final List ROSTER_STATUSES = + List.of(ParticipantStatus.ACTIVE, ParticipantStatus.PAUSED); + + /** 그 스터디를 보는 참여자 — 참여 중단 · 탈퇴만 뺀다. 완주한 사람도 끝난 스터디의 일정 · 출석부 · 회고 · 자료 링크를 계속 본다. */ + public static final List VIEWER_STATUSES = List.of( ParticipantStatus.ACTIVE, ParticipantStatus.PAUSED, ParticipantStatus.COMPLETED); - /** 분반의 활성 명부 — 쉬는 중(PAUSED)도 그 분반 사람이다. */ - public static final List ROSTER_STATUSES = - List.of(ParticipantStatus.ACTIVE, ParticipantStatus.PAUSED); + /** 네비게이터 권한을 주는 명부 행 — 완주한 네비게이터도 끝난 스터디의 출석 · 일정을 고친다. */ + public static final List NAVIGATOR_STATUSES = + List.of( + ParticipantStatus.ACTIVE, + ParticipantStatus.PAUSED, + ParticipantStatus.COMPLETED); private final AccountRepository accountRepository; private final StudyParticipantRepository studyParticipantRepository; @@ -65,7 +75,7 @@ public void assertCaptainOrNavigator(Long accountId, Long studyId, String messag if (account(accountId).getSystemRole() == SystemRole.ADMIN) { return; } - if (!isActiveNavigatorOfStudy(accountId, studyId)) { + if (!isNavigatorOfStudy(accountId, studyId)) { throw new BusinessException(ErrorCode.FORBIDDEN, message); } } @@ -87,15 +97,16 @@ public void assertCaptainOrNavigatorOfGroup( if (account(accountId).getSystemRole() == SystemRole.ADMIN) { return; } - if (!isActiveNavigatorOfGroup(accountId, studyGroupId)) { + if (!isNavigatorOfGroup(accountId, studyGroupId)) { throw new BusinessException(ErrorCode.FORBIDDEN, message); } } /** - * 출석부에서 참여 중단 — 담당 캡틴({@code STUDY.OWNER_CAPTAIN_ID}, NULL 이면 캡틴 누구나)이거나 그 분반의 살아 있는 - * 네비게이터. 크루로 참여한 다른 캡틴은 막는다 — 출석 쓰기 가드({@link #assertCaptainOrNavigatorOfGroup})는 ADMIN 이면 - * 누구나 통과시키므로 쓰지 않는다 (specs/study-participant/spec.md 권한). + * 출석부에서 참여 중단 — 담당 캡틴({@code STUDY.OWNER_CAPTAIN_ID}, NULL 이면 캡틴 누구나)이거나 그 분반의 + * 네비게이터({@link #NAVIGATOR_STATUSES}). 크루로 참여한 다른 캡틴은 막는다 — 출석 쓰기 가드({@link + * #assertCaptainOrNavigatorOfGroup})는 ADMIN 이면 누구나 통과시키므로 쓰지 않는다 + * (specs/study-participant/spec.md 권한). * * @return 담당 캡틴이면 true, 네비게이터면 false — 네비게이터는 같은 분반의 행만 중단할 수 있다 */ @@ -108,7 +119,7 @@ public boolean assertCanWithdrawInGroup( studyParticipantRepository .findByStudyGroupIdAndAccountId(studyGroupId, accountId) .filter(p -> p.getParticipantRole() == ParticipantRole.LEADER) - .filter(p -> ROSTER_STATUSES.contains(p.getStatus())) + .filter(p -> NAVIGATOR_STATUSES.contains(p.getStatus())) .isPresent(); if (!navigator) { throw new BusinessException(ErrorCode.FORBIDDEN, message); @@ -139,8 +150,7 @@ private static boolean isOwnerCaptain(Long accountId, Account caller, Long owner */ public boolean canEditGroup(Long accountId, Long ownerCaptainId, Long studyGroupId) { account(accountId); - return accountId.equals(ownerCaptainId) - || isActiveNavigatorOfGroup(accountId, studyGroupId); + return accountId.equals(ownerCaptainId) || isNavigatorOfGroup(accountId, studyGroupId); } public void assertCanEditGroup( @@ -151,9 +161,9 @@ public void assertCanEditGroup( } /** - * 「스터디 일정」 보기 — 고칠 수 있는 사람이거나 그 스터디의 활성 참여자(ACTIVE·PAUSED). 크루 · 네비게이터도 캡틴처럼 같은 스터디의 다른 - * 반을 본다 — 보기만 하고 고치기는 {@link #canEditGroup} 그대로다. 참여를 중단한 사람은 들어오지 못한다. 분반이 이 스터디 소속인지는 부르는 쪽이 - * 먼저 확인한다. + * 「스터디 일정」 보기 — 고칠 수 있는 사람이거나 그 스터디의 참여자({@link #VIEWER_STATUSES}). 크루 · 네비게이터도 캡틴처럼 같은 + * 스터디의 다른 반을 본다 — 보기만 하고 고치기는 {@link #canEditGroup} 그대로다. 참여를 중단한 사람은 들어오지 못한다. 분반이 이 스터디 소속인지는 + * 부르는 쪽이 먼저 확인한다. * * @return 고칠 수 있으면 true */ @@ -162,15 +172,16 @@ public boolean assertCanViewGroup( if (canEditGroup(accountId, ownerCaptainId, studyGroupId)) { return true; } - if (!isActiveMemberOfStudy(accountId, studyId)) { + if (!isViewerOfStudy(accountId, studyId)) { throw new BusinessException(ErrorCode.FORBIDDEN, message); } return false; } /** - * 분반 출석부 보기 — 위 {@link #assertCaptainOrNavigatorOfGroup} 에 더해 그 분반의 활성 참여자도 본다. 크루는 내 분반 - * 전원의 출석을 보기만 한다 (specs/study-meeting/spec.md 구현 메모). 다른 분반은 403. + * 분반 출석부 보기 — 위 {@link #assertCaptainOrNavigatorOfGroup} 에 더해 그 분반의 참여자({@link + * #VIEWER_STATUSES})도 본다. 크루는 내 분반 전원의 출석을 보기만 한다 (specs/study-meeting/spec.md 구현 메모). 다른 분반은 + * 403. */ public void assertCaptainNavigatorOrMemberOfGroup( Long accountId, Long studyId, Long studyGroupId, String message) { @@ -178,7 +189,7 @@ public void assertCaptainNavigatorOrMemberOfGroup( accountId != null && studyParticipantRepository .findByStudyGroupIdAndAccountId(studyGroupId, accountId) - .filter(p -> ROSTER_STATUSES.contains(p.getStatus())) + .filter(p -> VIEWER_STATUSES.contains(p.getStatus())) .filter(p -> studyId.equals(p.getStudyId())) .isPresent(); if (member) { @@ -188,8 +199,8 @@ public void assertCaptainNavigatorOrMemberOfGroup( } /** - * 출석부 보기 — 캡틴 · 그 분반 네비게이터에 더해 그 스터디의 활성 참여자도 본다. 크루 · 네비게이터는 같은 스터디의 다른 반 출석도 보기만 한다. - * 다른 스터디의 분반이면 400. + * 출석부 보기 — 캡틴 · 그 분반 네비게이터에 더해 그 스터디의 참여자({@link #VIEWER_STATUSES})도 본다. 크루 · 네비게이터는 같은 + * 스터디의 다른 반 출석도 보기만 한다. 다른 스터디의 분반이면 400. */ public void assertCaptainNavigatorOrMemberOfStudy( Long accountId, Long studyId, Long studyGroupId, String message) { @@ -198,7 +209,7 @@ public void assertCaptainNavigatorOrMemberOfStudy( .findById(studyGroupId) .filter(group -> studyId.equals(group.getStudyId())) .isPresent() - && isActiveMemberOfStudy(accountId, studyId)) { + && isViewerOfStudy(accountId, studyId)) { return; } assertCaptainOrNavigatorOfGroup(accountId, studyId, studyGroupId, message); @@ -214,30 +225,30 @@ public boolean isCaptainOrNavigator(Long accountId, Long studyId) { .map( account -> account.getSystemRole() == SystemRole.ADMIN - || isActiveNavigatorOfStudy(accountId, studyId)) + || isNavigatorOfStudy(accountId, studyId)) .orElse(false); } /* - * 네비게이터 권한은 살아 있는 명부 행(ACTIVE · PAUSED)의 LEADER 에만 준다. 백오피스에서 담당 캡틴이 네비게이터를 중단시키면 그 행은 + * 네비게이터 권한은 NAVIGATOR_STATUSES 인 명부 행의 LEADER 에만 준다. 백오피스에서 담당 캡틴이 네비게이터를 중단시키면 그 행은 * WITHDRAWN · LEADER 로 남는다 — 역할을 MEMBER 로 내리지 않는 것은 중단 직전 역할을 withdrawn 이벤트가 실어야 하기 때문이다 (DSC-06 * 네비게이터 role 회수). 그래서 역할만 보지 않고 상태도 본다. */ - private boolean isActiveNavigatorOfStudy(Long accountId, Long studyId) { + private boolean isNavigatorOfStudy(Long accountId, Long studyId) { return studyParticipantRepository .existsByStudyIdAndAccountIdAndParticipantRoleInAndStatusIn( - studyId, accountId, NAVIGATOR_ROLES, ROSTER_STATUSES); + studyId, accountId, NAVIGATOR_ROLES, NAVIGATOR_STATUSES); } - private boolean isActiveMemberOfStudy(Long accountId, Long studyId) { + private boolean isViewerOfStudy(Long accountId, Long studyId) { return studyParticipantRepository.existsByStudyIdAndAccountIdAndStatusIn( - studyId, accountId, ROSTER_STATUSES); + studyId, accountId, VIEWER_STATUSES); } - private boolean isActiveNavigatorOfGroup(Long accountId, Long studyGroupId) { + private boolean isNavigatorOfGroup(Long accountId, Long studyGroupId) { return studyParticipantRepository .existsByStudyGroupIdAndAccountIdAndParticipantRoleInAndStatusIn( - studyGroupId, accountId, NAVIGATOR_ROLES, ROSTER_STATUSES); + studyGroupId, accountId, NAVIGATOR_ROLES, NAVIGATOR_STATUSES); } /** @@ -250,7 +261,7 @@ public boolean canSeePrivateLinks(Long accountId, Long studyId) { return false; } return studyParticipantRepository.existsByStudyIdAndAccountIdAndStatusIn( - studyId, accountId, LINK_VIEWER_STATUSES) + studyId, accountId, VIEWER_STATUSES) || accountRepository .findById(accountId) .map(account -> account.getSystemRole() == SystemRole.ADMIN) diff --git a/backend/api/src/main/java/com/studyclub/api/study/StudyListResponse.java b/backend/api/src/main/java/com/studyclub/api/study/StudyListResponse.java index d59de07af..433fbc031 100644 --- a/backend/api/src/main/java/com/studyclub/api/study/StudyListResponse.java +++ b/backend/api/src/main/java/com/studyclub/api/study/StudyListResponse.java @@ -40,11 +40,17 @@ public record StudySummary( FormattedInstant startAtFormatted, Instant endAt, boolean closingSoon) { - /** {@code studyKind} 는 프로그램의 값이라 밖에서 받는다 — docs/erd/STUDY_PROGRAM.md. */ + /** + * {@code studyKind} 는 프로그램의 값이라 밖에서 받는다 — docs/erd/STUDY_PROGRAM.md. + * + * @param capacityHolderCount 정원을 차지하는 인원 — 모집 판정의 재료 (결정 D4-A) + * @param crewCount 보이는 인원 {@code currentApplicants} — 끝난 스터디는 완주자를 센다 + */ public static StudySummary from( Study study, StudyKind studyKind, - long applicantCount, + long capacityHolderCount, + long crewCount, Instant recruitDeadlineAt, Integer recruitmentCapacity, RecruitmentTimeZones recruitmentTimeZones, @@ -61,12 +67,13 @@ public static StudySummary from( RecruitmentTimeZonesView.from(recruitmentTimeZones), recruitmentTimeZones.label(), study.getStatus(), - study.phase(applicantCount, recruitDeadlineAt, recruitmentCapacity), + study.phase(capacityHolderCount, recruitDeadlineAt, recruitmentCapacity), study.recruitStatus( - applicantCount, recruitDeadlineAt, recruitmentCapacity, now), - study.canApply(applicantCount, recruitDeadlineAt, recruitmentCapacity, now), + capacityHolderCount, recruitDeadlineAt, recruitmentCapacity, now), + study.canApply( + capacityHolderCount, recruitDeadlineAt, recruitmentCapacity, now), recruitmentCapacity, - applicantCount, + crewCount, recruitDeadlineAt, TimeZoneFormatService.formatDeadline(recruitDeadlineAt, displayTimeZone, now), study.getStartAt(), diff --git a/backend/api/src/main/java/com/studyclub/api/study/StudyListService.java b/backend/api/src/main/java/com/studyclub/api/study/StudyListService.java index 1eea98c71..baf36bb76 100644 --- a/backend/api/src/main/java/com/studyclub/api/study/StudyListService.java +++ b/backend/api/src/main/java/com/studyclub/api/study/StudyListService.java @@ -61,11 +61,16 @@ public StudyListResponse list( studyRecruitmentRepository.findLatestByStudyIdIn(studyIds); // 정원을 차지하는 인원 — 명부 ACTIVE 중 정원 역할 (결정 D4-A, study-recruit-status/spec.md) - Map crewCounts = + Map capacityHolders = studyParticipantRepository .countCapacityHoldersByStudyIds(studyIds, ParticipantRole.CAPACITY_ROLES) .stream() .collect(Collectors.toMap(row -> (Long) row[0], row -> (Long) row[1])); + Map crewCounts = + studyParticipantRepository + .countCrewByStudyIds(studyIds, ParticipantRole.CAPACITY_ROLES) + .stream() + .collect(Collectors.toMap(row -> (Long) row[0], row -> (Long) row[1])); Map deadlines = latestRecruitments.stream() @@ -113,6 +118,7 @@ public StudyListResponse list( + study .getProgramId())) .getStudyKind(), + capacityHolders.getOrDefault(study.getId(), 0L), crewCounts.getOrDefault(study.getId(), 0L), deadlines.get(study.getId()), capacities.get(study.getId()), diff --git a/backend/api/src/main/java/com/studyclub/api/studygroup/AdminStudyParticipantController.java b/backend/api/src/main/java/com/studyclub/api/studygroup/AdminStudyParticipantController.java index a22f922a2..9bc44fb2d 100644 --- a/backend/api/src/main/java/com/studyclub/api/studygroup/AdminStudyParticipantController.java +++ b/backend/api/src/main/java/com/studyclub/api/studygroup/AdminStudyParticipantController.java @@ -35,7 +35,7 @@ public AdminStudyParticipantController( @Operation( summary = "참여 명단", description = - "ADMIN만 호출 가능. 반 · 담당(네비게이터)과 함께 준다. 기본은 ACTIVE · PAUSED," + "ADMIN만 호출 가능. 반 · 담당(네비게이터)과 함께 준다. 기본은 ACTIVE · PAUSED · COMPLETED," + " includeLeft=true 면 WITHDRAWN 도. DELETED(탈퇴)는 늘 뺀다.") @GetMapping public StudyParticipantsResponse list( diff --git a/backend/api/src/main/java/com/studyclub/api/studygroup/AdminStudyParticipantQueryService.java b/backend/api/src/main/java/com/studyclub/api/studygroup/AdminStudyParticipantQueryService.java index 2ede8b720..2a53a9035 100644 --- a/backend/api/src/main/java/com/studyclub/api/studygroup/AdminStudyParticipantQueryService.java +++ b/backend/api/src/main/java/com/studyclub/api/studygroup/AdminStudyParticipantQueryService.java @@ -36,15 +36,21 @@ @Service public class AdminStudyParticipantQueryService { - /** 기본 명단 — 참여 중인 행. 인원(participantCount)도 이 상태만 센다. */ + /** + * 기본 명단 — 참여 중이거나 완주한 행. 인원(participantCount)도 이 상태만 센다. 끝난 스터디는 크루가 완주로 넘어가 완주자가 명단과 인원이 된다. + */ private static final List CURRENT_STATUSES = - List.of(ParticipantStatus.ACTIVE, ParticipantStatus.PAUSED); + List.of( + ParticipantStatus.ACTIVE, + ParticipantStatus.PAUSED, + ParticipantStatus.COMPLETED); /** includeLeft — 하차(WITHDRAWN)까지. 탈퇴(DELETED)는 늘 뺀다. */ private static final List WITH_LEFT_STATUSES = List.of( ParticipantStatus.ACTIVE, ParticipantStatus.PAUSED, + ParticipantStatus.COMPLETED, ParticipantStatus.WITHDRAWN); private final StudyRepository studyRepository; diff --git a/backend/api/src/main/resources/application.yml b/backend/api/src/main/resources/application.yml index da43e1689..78f22c6e7 100644 --- a/backend/api/src/main/resources/application.yml +++ b/backend/api/src/main/resources/application.yml @@ -223,6 +223,12 @@ event: enabled: ${EVENT_END_SETTLEMENT_ENABLED:true} fixed-delay-ms: ${EVENT_END_SETTLEMENT_FIXED_DELAY_MS:60000} +# 끝난 스터디의 명부를 완주(COMPLETED)로 바꾸는 주기 (specs/study-participant 「완주」). +study: + participant-completion: + enabled: ${STUDY_PARTICIPANT_COMPLETION_ENABLED:true} + fixed-delay-ms: ${STUDY_PARTICIPANT_COMPLETION_FIXED_DELAY_MS:60000} + # 정리 작업은 전용 실행기에서 실행 완료 후 하루 간격. 알림의 30초 폴링은 별도다. cleanup: enabled: ${CLEANUP_ENABLED:true} diff --git a/backend/api/src/test/java/com/studyclub/api/application/StudyApplicationSubmissionIntegrationTest.java b/backend/api/src/test/java/com/studyclub/api/application/StudyApplicationSubmissionIntegrationTest.java index 66b67d355..ff9f162c1 100644 --- a/backend/api/src/test/java/com/studyclub/api/application/StudyApplicationSubmissionIntegrationTest.java +++ b/backend/api/src/test/java/com/studyclub/api/application/StudyApplicationSubmissionIntegrationTest.java @@ -622,6 +622,35 @@ void acceptsRecruitmentWithoutDeadline() { assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CREATED); } + @Test + @DisplayName("실패 - 끝난 스터디(END_AT 경과)는 모집이 열려 있어도 409 이고, 신청서 없는 완주 행을 되살리지 않는다") + void rejectsEndedStudy() { + jdbcTemplate.update( + "UPDATE STUDY_RECRUITMENT SET RECRUIT_DEADLINE_AT = NULL WHERE ID = ?", + RECRUITMENT_ID); + jdbcTemplate.update( + "UPDATE STUDY SET END_AT = ? WHERE ID = ?", + Timestamp.from(Instant.now().minusSeconds(60)), + STUDY_ID); + insertParticipant(LINKED_ACCOUNT_ID, "COMPLETED", "LEADER"); + + var response = + rest.postForEntity( + "/api/studies/" + STUDY_ID + "/applications", + authenticatedRequest(LINKED_ACCOUNT_ID, validRequest()), + Map.class); + + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CONFLICT); + assertThat(response.getBody()).containsEntry("errorMessage", "모집이 마감되었습니다."); + assertThat(applicationCount()).isZero(); + assertThat( + jdbcTemplate.queryForList( + "SELECT STATUS FROM STUDY_PARTICIPANT WHERE STUDY_ID = ?", + String.class, + STUDY_ID)) + .containsExactly("COMPLETED"); + } + @Test @DisplayName("실패 - 모든 비공개 상태는 404로 응답하고 신청을 저장하지 않는다") void rejectsNonOpenStudies() { diff --git a/backend/api/src/test/java/com/studyclub/api/audit/AuditRetentionIntegrationTest.java b/backend/api/src/test/java/com/studyclub/api/audit/AuditRetentionIntegrationTest.java index 0615768d7..1adc35a0f 100644 --- a/backend/api/src/test/java/com/studyclub/api/audit/AuditRetentionIntegrationTest.java +++ b/backend/api/src/test/java/com/studyclub/api/audit/AuditRetentionIntegrationTest.java @@ -73,8 +73,9 @@ void recordsRevokedAuthorityOnAccountDeletion() { RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(request)); accountDeletion.deleteAccount(account.getId(), LeaveReason.OTHER); assertThat(accounts.existsById(account.getId())).isFalse(); + // 캡틴 권한 1건 + 권한이 남아 있던 네비게이터 행(ACTIVE · PAUSED · COMPLETED) 3건 assertThat(repository.findAll()) - .hasSize(3) + .hasSize(4) .allSatisfy( entry -> { assertThat(entry.getActorAccountId()).isEqualTo(account.getId()); @@ -85,11 +86,11 @@ void recordsRevokedAuthorityOnAccountDeletion() { }); assertThat(repository.findAll()) .filteredOn(e -> e.getParticipantId() != null) - .hasSize(2) + .hasSize(3) .allSatisfy( e -> assertThat(e.getParticipantRole()).isEqualTo(ParticipantRole.LEADER)); assertThatThrownBy(() -> accountDeletion.deleteAccount(account.getId(), LeaveReason.OTHER)); - assertThat(repository.count()).isEqualTo(3); + assertThat(repository.count()).isEqualTo(4); } @Test diff --git a/backend/api/src/test/java/com/studyclub/api/auth/AccountDeletionIntegrationTest.java b/backend/api/src/test/java/com/studyclub/api/auth/AccountDeletionIntegrationTest.java index 4d224f679..52eb4bffb 100644 --- a/backend/api/src/test/java/com/studyclub/api/auth/AccountDeletionIntegrationTest.java +++ b/backend/api/src/test/java/com/studyclub/api/auth/AccountDeletionIntegrationTest.java @@ -133,10 +133,18 @@ void deletesAccountAndRelatedData() { .participantRole(ParticipantRole.LEADER) .joinedAt(Instant.now()) .build()); - // 운영자 알림 대상 — PAUSED 는 명부에 남아 있어 싣고, 이미 하차한 WITHDRAWN 은 뺀다. + // 운영자 알림 대상 — PAUSED 는 명부에 남아 있고 COMPLETED 는 디스코드 role 이 남아 싣는다. 이미 하차한 WITHDRAWN 은 뺀다. for (ParticipantStatus status : - List.of(ParticipantStatus.PAUSED, ParticipantStatus.WITHDRAWN)) { - Long studyId = status == ParticipantStatus.PAUSED ? 9004L : 9005L; + List.of( + ParticipantStatus.PAUSED, + ParticipantStatus.WITHDRAWN, + ParticipantStatus.COMPLETED)) { + Long studyId = + switch (status) { + case PAUSED -> 9004L; + case WITHDRAWN -> 9005L; + default -> 9006L; + }; studyParticipantRepository.save( StudyParticipant.builder() .accountId(accountId) @@ -267,7 +275,7 @@ void deletesAccountAndRelatedData() { e -> { assertThat(e.nickname()).isEqualTo(account.getNickname()); assertThat(e.discordUserId()).isNull(); - assertThat(e.studyIds()).containsExactlyInAnyOrder(9001L, 9004L); + assertThat(e.studyIds()).containsExactlyInAnyOrder(9001L, 9004L, 9006L); assertThat(e.navigator()).isTrue(); }); } diff --git a/backend/api/src/test/java/com/studyclub/api/participant/CompletedParticipantReadPathIntegrationTest.java b/backend/api/src/test/java/com/studyclub/api/participant/CompletedParticipantReadPathIntegrationTest.java new file mode 100644 index 000000000..2a51e64de --- /dev/null +++ b/backend/api/src/test/java/com/studyclub/api/participant/CompletedParticipantReadPathIntegrationTest.java @@ -0,0 +1,464 @@ +package com.studyclub.api.participant; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.studyclub.api.auth.JwtService; +import com.studyclub.domain.account.AccountRepository; +import com.studyclub.domain.account.SystemRole; +import com.studyclub.domain.participant.ParticipantRole; +import com.studyclub.domain.participant.ParticipantStatus; +import com.studyclub.domain.participant.StudyParticipant; +import com.studyclub.domain.participant.StudyParticipantRepository; +import com.studyclub.domain.study.Study; +import com.studyclub.domain.study.StudyCategory; +import com.studyclub.domain.study.StudyGroup; +import com.studyclub.domain.study.StudyGroupRepository; +import com.studyclub.domain.study.StudyKind; +import com.studyclub.domain.study.StudyMeeting; +import com.studyclub.domain.study.StudyMeetingRepository; +import com.studyclub.domain.study.StudyProgram; +import com.studyclub.domain.study.StudyProgramRepository; +import com.studyclub.domain.study.StudyRecruitment; +import com.studyclub.domain.study.StudyRecruitmentRepository; +import com.studyclub.domain.study.StudyRepository; +import com.studyclub.domain.study.StudyStatus; +import java.sql.Timestamp; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.resttestclient.TestRestTemplate; +import org.springframework.boot.resttestclient.autoconfigure.AutoConfigureTestRestTemplate; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.http.HttpEntity; +import org.springframework.http.HttpHeaders; +import org.springframework.http.HttpMethod; +import org.springframework.http.HttpStatus; +import org.springframework.http.ResponseEntity; +import org.springframework.jdbc.core.JdbcTemplate; + +/** + * 완주한 사람이 끝난 스터디를 계속 본다 (specs/study-participant/spec.md 「완주」 읽기 경로). 픽스처는 ACTIVE 로 넣고 완주 전환 서비스로 + * 바꾼다. + */ +@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) +@AutoConfigureTestRestTemplate +class CompletedParticipantReadPathIntegrationTest { + + private static final Long CAPTAIN_ID = 19351L; + private static final Long NAVIGATOR_ID = 19352L; + private static final Long CREW_ID = 19353L; + private static final Long WITHDRAWN_ID = 19354L; + private static final Long RUNNING_CREW_ID = 19355L; + private static final String KEYWORD = "완주읽기경로"; + + @Autowired TestRestTemplate rest; + @Autowired JwtService jwt; + @Autowired AccountRepository accountRepository; + @Autowired JdbcTemplate jdbcTemplate; + @Autowired StudyParticipantCompletionService completionService; + + @Autowired StudyProgramRepository studyProgramRepo; + @Autowired StudyRepository studyRepo; + @Autowired StudyRecruitmentRepository recruitmentRepo; + @Autowired StudyGroupRepository studyGroupRepo; + @Autowired StudyMeetingRepository studyMeetingRepo; + @Autowired StudyParticipantRepository studyParticipantRepo; + + private final List studyIds = new ArrayList<>(); + private Long programId; + private Study ended; + private StudyGroup group; + private StudyMeeting meeting; + private StudyParticipant navigator; + private StudyParticipant crew; + private StudyParticipant withdrawn; + + @BeforeEach + void setUp() { + insertAccountIfAbsent(CAPTAIN_ID, "완주캡틴", "captain@completed-read.com", SystemRole.ADMIN); + insertAccountIfAbsent(NAVIGATOR_ID, "완주네비", "nav@completed-read.com", SystemRole.MEMBER); + insertAccountIfAbsent(CREW_ID, "완주크루", "crew@completed-read.com", SystemRole.MEMBER); + insertAccountIfAbsent( + WITHDRAWN_ID, "중단크루", "withdrawn@completed-read.com", SystemRole.MEMBER); + insertAccountIfAbsent( + RUNNING_CREW_ID, "진행크루", "running@completed-read.com", SystemRole.MEMBER); + + programId = + studyProgramRepo + .save( + StudyProgram.builder() + .title("완주 읽기 경로 프로그램") + .studyKind(StudyKind.STUDY) + .build()) + .getId(); + Instant now = Instant.now(); + ended = saveStudy(KEYWORD + " 끝난 스터디", now.minus(1, ChronoUnit.DAYS)); + group = + studyGroupRepo.save( + new StudyGroup( + ended.getId(), + "A반", + now.minus(60, ChronoUnit.DAYS), + "Asia/Seoul", + 10)); + navigator = saveParticipant(NAVIGATOR_ID, group, ParticipantRole.LEADER); + crew = saveParticipant(CREW_ID, group, ParticipantRole.MEMBER); + withdrawn = saveParticipant(WITHDRAWN_ID, group, ParticipantRole.MEMBER); + withdrawn.markWithdrawn(now.minus(20, ChronoUnit.DAYS)); + studyParticipantRepo.save(withdrawn); + + meeting = new StudyMeeting(group.getId(), now.minus(7, ChronoUnit.DAYS), null, null); + meeting.assignPresenters(crew.getId(), null); + meeting = studyMeetingRepo.save(meeting); + + assertThat(completionService.complete(ended.getId(), now)).isEqualTo(2); + } + + @AfterEach + void cleanUp() { + for (Long studyId : studyIds) { + jdbcTemplate.update("DELETE FROM STUDY_ATTENDANCE WHERE STUDY_ID = ?", studyId); + jdbcTemplate.update( + "DELETE FROM STUDY_MEETING WHERE STUDY_GROUP_ID IN" + + " (SELECT ID FROM STUDY_GROUP WHERE STUDY_ID = ?)", + studyId); + jdbcTemplate.update("DELETE FROM STUDY_PARTICIPANT WHERE STUDY_ID = ?", studyId); + jdbcTemplate.update("DELETE FROM STUDY_GROUP WHERE STUDY_ID = ?", studyId); + jdbcTemplate.update("DELETE FROM STUDY_RECRUITMENT WHERE STUDY_ID = ?", studyId); + jdbcTemplate.update("DELETE FROM STUDY WHERE ID = ?", studyId); + } + studyIds.clear(); + jdbcTemplate.update("DELETE FROM STUDY_PROGRAM WHERE ID = ?", programId); + } + + @Test + @DisplayName("완주한 크루가 내 반의 「스터디 일정」을 본다 — 내 명부 행 · 네비게이터 이름 · 발표자가 그대로 보인다") + void completedCrewSeesSchedule() { + ResponseEntity response = + get("/api/studies/{studyId}/meetings", CREW_ID, ended.getId()); + + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + Map body = response.getBody(); + Map me = (Map) body.get("me"); + assertThat(((Number) me.get("participantId")).longValue()).isEqualTo(crew.getId()); + assertThat(me.get("canEdit")).isEqualTo(false); + assertThat(((Map) body.get("studyGroup")).get("navigatorName")).isEqualTo("완주네비"); + Map presenter = + (Map) ((Map) ((List) body.get("meetings")).get(0)).get("presenter1"); + assertThat(presenter.get("active")).isEqualTo(true); + } + + @Test + @DisplayName("완주한 네비게이터는 끝난 스터디의 일정을 고칠 수 있는 사람으로 남는다") + void completedNavigatorCanStillEdit() { + ResponseEntity response = + get( + "/api/studies/{studyId}/meetings?studyGroupId={groupId}", + NAVIGATOR_ID, + ended.getId(), + group.getId()); + + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(((Map) response.getBody().get("me")).get("canEdit")).isEqualTo(true); + // 발표자 후보는 진행 중 명부(ROSTER_STATUSES)라 완주자가 들지 않는다 + assertThat((List) response.getBody().get("participants")).isEmpty(); + } + + @Test + @DisplayName("완주한 크루는 발표 신청을 못 한다 — 발표 신청은 진행 중 명부만") + void completedCrewCannotSignUpPresenter() { + ResponseEntity response = + rest.exchange( + "/api/studies/{studyId}/meetings/{meetingId}/presenters/2/me", + HttpMethod.PUT, + new HttpEntity<>(headers(CREW_ID)), + Map.class, + ended.getId(), + meeting.getId()); + + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); + } + + @Test + @DisplayName("완주한 네비게이터도 끝난 스터디에서는 참여 중단을 못 한다 — 409, 명부 그대로") + void completedNavigatorCannotWithdraw() { + Map body = + Map.of( + "studyGroupId", + group.getId(), + "updates", + List.of(), + "withdrawals", + List.of(crew.getId())); + + ResponseEntity response = + rest.exchange( + "/api/me/studies/{studyId}/attendances", + HttpMethod.POST, + new HttpEntity<>(body, headers(NAVIGATOR_ID)), + Map.class, + ended.getId()); + + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.CONFLICT); + assertThat(studyParticipantRepo.findById(crew.getId()).orElseThrow().getStatus()) + .isEqualTo(ParticipantStatus.COMPLETED); + } + + @Test + @DisplayName("참여를 중단한 사람은 끝난 스터디의 일정도 여전히 403") + void withdrawnStillForbidden() { + ResponseEntity response = + get( + "/api/studies/{studyId}/meetings?studyGroupId={groupId}", + WITHDRAWN_ID, + ended.getId(), + group.getId()); + + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.FORBIDDEN); + } + + @Test + @DisplayName("완주한 크루가 출석부를 본다 — 기본 명단에 완주자가 있고 참여 중단은 빠진다") + void completedCrewSeesAttendance() { + ResponseEntity response = + get( + "/api/me/studies/{studyId}/attendances?studyGroupId={groupId}", + CREW_ID, + ended.getId(), + group.getId()); + + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + List participants = (List) response.getBody().get("participants"); + assertThat(participants) + .extracting(p -> ((Number) ((Map) p).get("participantId")).longValue()) + .containsExactlyInAnyOrder(navigator.getId(), crew.getId()); + assertThat(participants) + .extracting(p -> (Object) ((Map) p).get("participantStatus")) + .containsOnly("COMPLETED"); + } + + @Test + @DisplayName("완주한 네비게이터가 끝난 스터디의 출석을 고친다") + void completedNavigatorEditsAttendance() { + Map body = + Map.of( + "studyGroupId", + group.getId(), + "updates", + List.of( + Map.of( + "meetingId", + meeting.getId(), + "participantId", + crew.getId(), + "status", + "PRESENT"))); + + ResponseEntity response = + rest.exchange( + "/api/me/studies/{studyId}/attendances", + HttpMethod.POST, + new HttpEntity<>(body, headers(NAVIGATOR_ID)), + Map.class, + ended.getId()); + + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.NO_CONTENT); + } + + @Test + @DisplayName("완주한 크루의 회고 상태 — 반을 주지 않아도 내 반을 찾는다") + void completedCrewSeesRetroStatus() { + ResponseEntity response = + get("/api/me/studies/{studyId}/retros/status", CREW_ID, ended.getId()); + + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + } + + @Test + @DisplayName("백오피스 참여 명단 — 완주자가 기본 명단에 보이고 인원으로 센다, includeLeft 면 참여 중단도") + void backofficeTableShowsCompleted() { + ResponseEntity response = + get("/api/admin/studies/{studyId}/participants", CAPTAIN_ID, ended.getId()); + + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(response.getBody().get("participantCount")).isEqualTo(2); + assertThat((List) response.getBody().get("participants")) + .extracting(p -> (Object) ((Map) p).get("status")) + .containsExactlyInAnyOrder("COMPLETED", "COMPLETED"); + + ResponseEntity withLeft = + get( + "/api/admin/studies/{studyId}/participants?includeLeft=true", + CAPTAIN_ID, + ended.getId()); + assertThat(withLeft.getBody().get("participantCount")).isEqualTo(2); + assertThat((List) withLeft.getBody().get("participants")).hasSize(3); + } + + @Test + @DisplayName("목록 인원 — 끝난 스터디는 완주자를 세고, 백오피스 「인원」 정렬에서도 0명으로 밀리지 않는다") + void listCountsCompleted() { + Study running = saveStudy(KEYWORD + " 진행 스터디", null); + StudyGroup runningGroup = + studyGroupRepo.save( + new StudyGroup(running.getId(), "A반", Instant.now(), "Asia/Seoul", 10)); + saveParticipant(RUNNING_CREW_ID, runningGroup, ParticipantRole.MEMBER); + + ResponseEntity site = get("/api/studies?keyword={keyword}", null, KEYWORD); + assertThat(site.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(applicantsById(site.getBody())) + .containsEntry(ended.getId(), 2L) + .containsEntry(running.getId(), 1L); + + ResponseEntity admin = + get( + "/api/admin/studies?keyword={keyword}&sort=APPLICANTS_DESC", + CAPTAIN_ID, + KEYWORD); + assertThat(admin.getStatusCode()).isEqualTo(HttpStatus.OK); + assertThat(applicantsById(admin.getBody())) + .containsEntry(ended.getId(), 2L) + .containsEntry(running.getId(), 1L); + assertThat(studyIdsOf(admin.getBody())).containsExactly(ended.getId(), running.getId()); + } + + @Test + @DisplayName("모집 판정은 ACTIVE 만 센다 — 완주 행은 보이는 인원에만 들어간다") + void recruitJudgementCountsActiveOnly() { + // 완주 행은 끝난 스터디에만 생기므로, 정원 판정과 보이는 인원의 기준을 가르려고 진행 중 스터디에 직접 넣는다 + Study recruiting = saveStudy(KEYWORD + " 모집 스터디", null); + recruitmentRepo.save( + StudyRecruitment.builder() + .studyId(recruiting.getId()) + .title("모집") + .description("모집 설명") + .startAt(Instant.now().minus(7, ChronoUnit.DAYS)) + .recruitmentCapacity(1) + .build()); + jdbcTemplate.update( + "UPDATE STUDY SET START_AT = ? WHERE ID = ?", + Timestamp.from(Instant.now().plus(30, ChronoUnit.DAYS)), + recruiting.getId()); + StudyGroup recruitingGroup = + studyGroupRepo.save( + new StudyGroup(recruiting.getId(), "A반", null, "Asia/Seoul", 10)); + StudyParticipant done = + saveParticipant(RUNNING_CREW_ID, recruitingGroup, ParticipantRole.MEMBER); + jdbcTemplate.update( + "UPDATE STUDY_PARTICIPANT SET STATUS = 'COMPLETED' WHERE ID = ?", done.getId()); + + ResponseEntity site = get("/api/studies?keyword={keyword}", null, KEYWORD); + Map item = itemOf(site.getBody(), recruiting.getId()); + assertThat(item.get("recruitStatus")).isEqualTo("RECRUITING"); + assertThat(item.get("canApply")).isEqualTo(true); + assertThat(((Number) item.get("currentApplicants")).longValue()).isEqualTo(1L); + + ResponseEntity admin = + get("/api/admin/studies?studyId={studyId}", CAPTAIN_ID, recruiting.getId()); + Map adminItem = itemOf(admin.getBody(), recruiting.getId()); + assertThat(adminItem.get("recruitStatus")).isEqualTo("RECRUITING"); + assertThat(((Number) adminItem.get("currentApplicants")).longValue()).isEqualTo(1L); + } + + // ── helpers ────────────────────────────────────────────────────────────── + + private Study saveStudy(String title, Instant endAt) { + Study study = + studyRepo.save( + Study.builder() + .programId(programId) + .title(title) + .oneLineSummary("테스트용") + .category(StudyCategory.ALGORITHM) + .description("설명") + .status(StudyStatus.OPEN) + .startAt(Instant.now().minus(60, ChronoUnit.DAYS)) + .endAt(endAt) + .createdBy(CAPTAIN_ID) + .ownerCaptainId(CAPTAIN_ID) + .build()); + studyIds.add(study.getId()); + return study; + } + + private StudyParticipant saveParticipant( + Long accountId, StudyGroup group, ParticipantRole role) { + return studyParticipantRepo.save( + StudyParticipant.builder() + .accountId(accountId) + .studyGroupId(group.getId()) + .studyId(group.getStudyId()) + .status(ParticipantStatus.ACTIVE) + .participantRole(role) + .joinedAt(Instant.now().minus(50, ChronoUnit.DAYS)) + .build()); + } + + private static Map applicantsById(Map body) { + Map result = new HashMap<>(); + for (Object item : (List) body.get("items")) { + Map map = (Map) item; + result.put( + ((Number) map.get("studyId")).longValue(), + ((Number) map.get("currentApplicants")).longValue()); + } + return result; + } + + private static List studyIdsOf(Map body) { + return ((List) body.get("items")) + .stream() + .map(item -> ((Number) ((Map) item).get("studyId")).longValue()) + .toList(); + } + + private static Map itemOf(Map body, Long studyId) { + return ((List) body.get("items")) + .stream() + .map(item -> (Map) item) + .filter(item -> ((Number) item.get("studyId")).longValue() == studyId) + .findFirst() + .orElseThrow(() -> new AssertionError("study not listed: " + studyId)); + } + + @SuppressWarnings("rawtypes") + private ResponseEntity get(String url, Long accountId, Object... uriVariables) { + HttpHeaders headers = accountId == null ? new HttpHeaders() : headers(accountId); + return rest.exchange( + url, HttpMethod.GET, new HttpEntity<>(headers), Map.class, uriVariables); + } + + private HttpHeaders headers(Long accountId) { + String email = accountRepository.findById(accountId).orElseThrow().getEmail(); + HttpHeaders headers = new HttpHeaders(); + headers.setBearerAuth(jwt.issueAccess(String.valueOf(accountId), email)); + return headers; + } + + private void insertAccountIfAbsent(Long id, String nickname, String email, SystemRole role) { + if (accountRepository.findById(id).isPresent()) { + return; + } + Timestamp now = Timestamp.from(Instant.now()); + jdbcTemplate.update( + "INSERT INTO ACCOUNT (ID, EMAIL, NICKNAME, SYSTEM_ROLE, TIME_ZONE," + + " ONBOARDING_COMPLETED_AT, CREATED_AT, UPDATED_AT)" + + " VALUES (?, ?, ?, ?, ?, ?, ?, ?)", + id, + email, + nickname, + role.name(), + "Asia/Seoul", + now, + now, + now); + } +} diff --git a/backend/api/src/test/java/com/studyclub/api/participant/StudyParticipantCompletionIntegrationTest.java b/backend/api/src/test/java/com/studyclub/api/participant/StudyParticipantCompletionIntegrationTest.java new file mode 100644 index 000000000..10b7789ae --- /dev/null +++ b/backend/api/src/test/java/com/studyclub/api/participant/StudyParticipantCompletionIntegrationTest.java @@ -0,0 +1,250 @@ +package com.studyclub.api.participant; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.studyclub.domain.participant.ParticipantRole; +import com.studyclub.domain.participant.ParticipantStatus; +import com.studyclub.domain.participant.StudyParticipant; +import com.studyclub.domain.participant.StudyParticipantCompleted; +import com.studyclub.domain.participant.StudyParticipantRepository; +import com.studyclub.domain.study.Study; +import com.studyclub.domain.study.StudyCategory; +import com.studyclub.domain.study.StudyGroup; +import com.studyclub.domain.study.StudyGroupRepository; +import com.studyclub.domain.study.StudyKind; +import com.studyclub.domain.study.StudyProgram; +import com.studyclub.domain.study.StudyProgramRepository; +import com.studyclub.domain.study.StudyRepository; +import com.studyclub.domain.study.StudyStatus; +import java.sql.Timestamp; +import java.time.Instant; +import java.time.temporal.ChronoUnit; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.AfterEach; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.test.context.event.ApplicationEvents; +import org.springframework.test.context.event.RecordApplicationEvents; + +/** 완주 전환 (specs/study-participant/spec.md 「완주」). 스케줄러는 테스트 설정에서 꺼져 있어 서비스를 직접 부른다. */ +@SpringBootTest +@RecordApplicationEvents +class StudyParticipantCompletionIntegrationTest { + + private static final long ACCOUNT_BASE = 19300L; + + @Autowired StudyParticipantCompletionService completionService; + @Autowired StudyProgramRepository studyProgramRepo; + @Autowired StudyRepository studyRepo; + @Autowired StudyGroupRepository studyGroupRepo; + @Autowired StudyParticipantRepository studyParticipantRepo; + @Autowired JdbcTemplate jdbcTemplate; + @Autowired ApplicationEvents events; + + private final List studyIds = new ArrayList<>(); + private Long programId; + private Instant now; + private long nextAccountId; + + @BeforeEach + void setUp() { + now = Instant.now(); + nextAccountId = ACCOUNT_BASE; + programId = + studyProgramRepo + .save( + StudyProgram.builder() + .title("완주 테스트 프로그램") + .studyKind(StudyKind.STUDY) + .build()) + .getId(); + } + + @AfterEach + void cleanUp() { + for (Long studyId : studyIds) { + jdbcTemplate.update("DELETE FROM STUDY_PARTICIPANT WHERE STUDY_ID = ?", studyId); + jdbcTemplate.update("DELETE FROM STUDY_GROUP WHERE STUDY_ID = ?", studyId); + jdbcTemplate.update("DELETE FROM STUDY WHERE ID = ?", studyId); + } + studyIds.clear(); + jdbcTemplate.update("DELETE FROM STUDY_PROGRAM WHERE ID = ?", programId); + } + + @Test + @DisplayName("끝난 스터디의 ACTIVE 만 COMPLETED · 행마다 이벤트 1건(행위자 없음), 나머지 상태는 그대로이고 이벤트 0건") + void completesOnlyActiveRowsOfEndedStudy() { + Study study = saveStudy(StudyStatus.OPEN, now.minus(1, ChronoUnit.DAYS)); + StudyGroup group = saveGroup(study); + StudyParticipant leader = + saveParticipant(group, ParticipantRole.LEADER, ParticipantStatus.ACTIVE); + StudyParticipant crew = + saveParticipant(group, ParticipantRole.MEMBER, ParticipantStatus.ACTIVE); + StudyParticipant paused = + saveParticipant(group, ParticipantRole.MEMBER, ParticipantStatus.PAUSED); + StudyParticipant withdrawn = + saveParticipant(group, ParticipantRole.MEMBER, ParticipantStatus.WITHDRAWN); + StudyParticipant deleted = + saveParticipant(group, ParticipantRole.MEMBER, ParticipantStatus.DELETED); + StudyParticipant completed = + saveParticipant(group, ParticipantRole.MEMBER, ParticipantStatus.COMPLETED); + + assertThat(completionService.findCandidates(now)).contains(study.getId()); + assertThat(completionService.complete(study.getId(), now)).isEqualTo(2); + + for (StudyParticipant p : List.of(leader, crew)) { + StudyParticipant reloaded = reload(p); + assertThat(reloaded.getStatus()).isEqualTo(ParticipantStatus.COMPLETED); + assertThat(reloaded.getLeftAt()).isNull(); + assertThat(reloaded.getParticipantRole()).isEqualTo(p.getParticipantRole()); + } + assertThat(reload(paused).getStatus()).isEqualTo(ParticipantStatus.PAUSED); + assertThat(reload(withdrawn).getStatus()).isEqualTo(ParticipantStatus.WITHDRAWN); + assertThat(reload(deleted).getStatus()).isEqualTo(ParticipantStatus.DELETED); + assertThat(reload(completed).getStatus()).isEqualTo(ParticipantStatus.COMPLETED); + + List published = completedEvents(); + assertThat(published) + .extracting(StudyParticipantCompleted::participantId) + .containsExactlyInAnyOrder(leader.getId(), crew.getId()); + assertThat(published) + .allSatisfy( + event -> { + assertThat(event.name()).isEqualTo("study_participant.completed"); + assertThat(event.studyId()).isEqualTo(study.getId()); + assertThat(event.aggregateType()).isEqualTo("study_participant"); + assertThat(event.aggregateId()) + .isEqualTo(String.valueOf(event.participantId())); + assertThat(event.actorId()).isNull(); + assertThat(event.occurredAt()).isNotNull(); + }); + assertThat(published) + .filteredOn(event -> event.participantId().equals(leader.getId())) + .singleElement() + .extracting(StudyParticipantCompleted::accountId) + .isEqualTo(leader.getAccountId()); + } + + @Test + @DisplayName("두 번 돌려도 이벤트가 늘지 않고, 바꿀 행이 없는 스터디는 후보에서 빠진다") + void secondRunPublishesNothing() { + Study study = saveStudy(StudyStatus.OPEN, now.minus(1, ChronoUnit.DAYS)); + StudyGroup group = saveGroup(study); + saveParticipant(group, ParticipantRole.MEMBER, ParticipantStatus.ACTIVE); + + assertThat(completionService.complete(study.getId(), now)).isEqualTo(1); + assertThat(completionService.complete(study.getId(), now)).isZero(); + + assertThat(completedEvents()).hasSize(1); + assertThat(completionService.findCandidates(now)).doesNotContain(study.getId()); + } + + @Test + @DisplayName("운영 종료(CLOSED) · ENDED 스터디도 종료일 없이 완주로 넘어간다") + void completesClosedAndEndedStudies() { + Study closed = saveStudy(StudyStatus.CLOSED, null); + saveParticipant(saveGroup(closed), ParticipantRole.MEMBER, ParticipantStatus.ACTIVE); + Study ended = saveStudy(StudyStatus.ENDED, null); + saveParticipant(saveGroup(ended), ParticipantRole.MEMBER, ParticipantStatus.ACTIVE); + + assertThat(completionService.findCandidates(now)).contains(closed.getId(), ended.getId()); + assertThat(completionService.complete(closed.getId(), now)).isEqualTo(1); + assertThat(completionService.complete(ended.getId(), now)).isEqualTo(1); + assertThat(completedEvents()).hasSize(2); + } + + @Test + @DisplayName("끝나지 않은 스터디(종료일 전 · 종료일 없음) · 작성 중(DRAFT) 스터디는 후보가 아니고, 직접 불러도 0건") + void skipsStudiesNotEnded() { + Study running = saveStudy(StudyStatus.OPEN, now.plus(10, ChronoUnit.DAYS)); + StudyParticipant inRunning = + saveParticipant( + saveGroup(running), ParticipantRole.MEMBER, ParticipantStatus.ACTIVE); + Study noEnd = saveStudy(StudyStatus.ONGOING, null); + StudyParticipant inNoEnd = + saveParticipant(saveGroup(noEnd), ParticipantRole.MEMBER, ParticipantStatus.ACTIVE); + Study draft = saveStudy(StudyStatus.DRAFT, now.minus(1, ChronoUnit.DAYS)); + StudyParticipant inDraft = + saveParticipant(saveGroup(draft), ParticipantRole.MEMBER, ParticipantStatus.ACTIVE); + + assertThat(completionService.findCandidates(now)) + .doesNotContain(running.getId(), noEnd.getId(), draft.getId()); + for (Study study : List.of(running, noEnd, draft)) { + assertThat(completionService.complete(study.getId(), now)).isZero(); + } + assertThat(completionService.complete(-1L, now)).isZero(); + + for (StudyParticipant p : List.of(inRunning, inNoEnd, inDraft)) { + assertThat(reload(p).getStatus()).isEqualTo(ParticipantStatus.ACTIVE); + } + assertThat(completedEvents()).isEmpty(); + } + + @Test + @DisplayName("고른 뒤 종료일이 늦춰졌으면 잠근 뒤 다시 판정해 건너뛴다") + void rechecksEndAfterLock() { + Study study = saveStudy(StudyStatus.OPEN, now.minus(1, ChronoUnit.DAYS)); + StudyParticipant crew = + saveParticipant(saveGroup(study), ParticipantRole.MEMBER, ParticipantStatus.ACTIVE); + assertThat(completionService.findCandidates(now)).contains(study.getId()); + + jdbcTemplate.update( + "UPDATE STUDY SET END_AT = ? WHERE ID = ?", + Timestamp.from(now.plus(7, ChronoUnit.DAYS)), + study.getId()); + + assertThat(completionService.complete(study.getId(), now)).isZero(); + assertThat(reload(crew).getStatus()).isEqualTo(ParticipantStatus.ACTIVE); + assertThat(completedEvents()).isEmpty(); + } + + private List completedEvents() { + return events.stream(StudyParticipantCompleted.class).toList(); + } + + private Study saveStudy(StudyStatus status, Instant endAt) { + Study study = + studyRepo.save( + Study.builder() + .programId(programId) + .title("완주 테스트 스터디") + .oneLineSummary("테스트용") + .category(StudyCategory.ALGORITHM) + .description("설명") + .status(status) + .startAt(now.minus(60, ChronoUnit.DAYS)) + .endAt(endAt) + .build()); + studyIds.add(study.getId()); + return study; + } + + private StudyGroup saveGroup(Study study) { + return studyGroupRepo.save( + new StudyGroup(study.getId(), "A반", study.getStartAt(), "Asia/Seoul", 10)); + } + + private StudyParticipant saveParticipant( + StudyGroup group, ParticipantRole role, ParticipantStatus status) { + boolean left = status == ParticipantStatus.WITHDRAWN || status == ParticipantStatus.DELETED; + return studyParticipantRepo.save( + StudyParticipant.builder() + .accountId(nextAccountId++) + .studyGroupId(group.getId()) + .studyId(group.getStudyId()) + .status(status) + .participantRole(role) + .joinedAt(now.minus(50, ChronoUnit.DAYS)) + .leftAt(left ? now.minus(10, ChronoUnit.DAYS) : null) + .build()); + } + + private StudyParticipant reload(StudyParticipant participant) { + return studyParticipantRepo.findById(participant.getId()).orElseThrow(); + } +} diff --git a/backend/api/src/test/java/com/studyclub/api/participant/StudyParticipantCompletionSchedulerTest.java b/backend/api/src/test/java/com/studyclub/api/participant/StudyParticipantCompletionSchedulerTest.java new file mode 100644 index 000000000..58d28dd01 --- /dev/null +++ b/backend/api/src/test/java/com/studyclub/api/participant/StudyParticipantCompletionSchedulerTest.java @@ -0,0 +1,26 @@ +package com.studyclub.api.participant; + +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.util.List; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +class StudyParticipantCompletionSchedulerTest { + + @Test + @DisplayName("한 스터디가 실패해도 다음 후보를 계속 처리한다") + void continuesAfterFailure() { + StudyParticipantCompletionService service = mock(StudyParticipantCompletionService.class); + when(service.findCandidates(any())).thenReturn(List.of(1L, 2L)); + when(service.complete(eq(1L), any())).thenThrow(new IllegalStateException("boom")); + + new StudyParticipantCompletionScheduler(service).run(); + + verify(service).complete(eq(2L), any()); + } +} diff --git a/backend/api/src/test/java/com/studyclub/api/study/AdminStudyQueryIntegrationTest.java b/backend/api/src/test/java/com/studyclub/api/study/AdminStudyQueryIntegrationTest.java index 615f48d37..9b20a9be7 100644 --- a/backend/api/src/test/java/com/studyclub/api/study/AdminStudyQueryIntegrationTest.java +++ b/backend/api/src/test/java/com/studyclub/api/study/AdminStudyQueryIntegrationTest.java @@ -127,30 +127,51 @@ void statusFilterMatchesDomain() { } @Test - @DisplayName("SQL 모집 필터는 공통 엔티티의 상태·마감 경계·정원 판정과 일치한다") + @DisplayName("SQL 모집 필터는 공통 엔티티의 상태·종료·마감 경계·정원 판정과 일치한다") void recruitmentMatchesDomain() { List recruiting = new ArrayList<>(); List notRecruiting = new ArrayList<>(); List closedOpen = new ArrayList<>(); + // 상태 필터 OPEN 은 날짜까지 읽은 상태(statusAsOf)로 거른다 — END_AT 이 지난 OPEN 은 ENDED 로 빠진다 + List closedOpenAsOf = new ArrayList<>(); long id = 1; for (StudyStatus status : StudyStatus.values()) { for (Instant deadline : new Instant[] {null, AS_OF.minusSeconds(1), AS_OF, AS_OF.plusSeconds(1)}) { for (Integer capacity : new Integer[] {null, 1, 2}) { - study(id, "상태 " + id, "", status, null); - recruitment(id, id, deadline, capacity); - // 정원 판정은 명부 기준 (결정 D4-A) — 1명 ACTIVE 참여자 삽입 - group(id, id); - participant(id, id, id, "ACTIVE"); - RecruitStatus expected = - Study.builder() - .status(status) - .build() - .recruitStatus(1, deadline, capacity, AS_OF); - if (expected == RecruitStatus.RECRUITING) recruiting.add(id); - else notRecruiting.add(id); - if (expected == RecruitStatus.RECRUIT_CLOSED) closedOpen.add(id); - id++; + // 종료는 OPEN 의 모집 판정만 바꾼다. 다른 상태까지 곱하면 한 쪽(100건)을 넘는다 + Instant[] endAts = + status == StudyStatus.OPEN + ? new Instant[] {null, AS_OF, AS_OF.plusSeconds(1)} + : new Instant[] {null}; + for (Instant endAt : endAts) { + study(id, "상태 " + id, "", status, null); + jdbc.update( + "UPDATE STUDY SET END_AT=? WHERE ID=?", + endAt == null ? null : Timestamp.from(endAt), + id); + recruitment(id, id, deadline, capacity); + // 정원 판정은 명부 기준 (결정 D4-A) — 1명 ACTIVE 참여자 삽입 + group(id, id); + participant(id, id, id, "ACTIVE"); + RecruitStatus expected = + Study.builder() + .status(status) + .endAt(endAt) + .build() + .recruitStatus(1, deadline, capacity, AS_OF); + if (expected == RecruitStatus.RECRUITING) recruiting.add(id); + else notRecruiting.add(id); + if (expected == RecruitStatus.RECRUIT_CLOSED) closedOpen.add(id); + if (expected == RecruitStatus.RECRUIT_CLOSED + && Study.builder() + .status(status) + .endAt(endAt) + .build() + .statusAsOf(AS_OF) + == StudyStatus.OPEN) closedOpenAsOf.add(id); + id++; + } } } } @@ -166,7 +187,7 @@ void recruitmentMatchesDomain() { null, null, StudyStatus.OPEN))) - .containsExactlyInAnyOrderElementsOf(closedOpen); + .containsExactlyInAnyOrderElementsOf(closedOpenAsOf); var legacy = new BackofficeStudyListFilter( StudyCategory.OTHER, diff --git a/backend/api/src/test/resources/application.yml b/backend/api/src/test/resources/application.yml index b6de9e08c..7e5b38082 100644 --- a/backend/api/src/test/resources/application.yml +++ b/backend/api/src/test/resources/application.yml @@ -59,6 +59,11 @@ event: end-settlement: enabled: false +# 완주 전환도 같은 이유로 끈다. 테스트는 StudyParticipantCompletionService 를 직접 부른다. +study: + participant-completion: + enabled: false + cleanup: enabled: false diff --git a/backend/domain/src/main/java/com/studyclub/domain/participant/StudyParticipant.java b/backend/domain/src/main/java/com/studyclub/domain/participant/StudyParticipant.java index 37d7b2991..23a828827 100644 --- a/backend/domain/src/main/java/com/studyclub/domain/participant/StudyParticipant.java +++ b/backend/domain/src/main/java/com/studyclub/domain/participant/StudyParticipant.java @@ -15,6 +15,7 @@ import jakarta.persistence.Table; import jakarta.persistence.UniqueConstraint; import java.time.Instant; +import java.util.Set; import lombok.AccessLevel; import lombok.AllArgsConstructor; import lombok.Builder; @@ -41,6 +42,10 @@ @AllArgsConstructor(access = AccessLevel.PRIVATE) public class StudyParticipant extends BaseEntity { + /** 스터디가 끝날 때 완주로 넘어가는 상태. 쉬는 중(PAUSED)은 기획이 정하기 전까지 그대로 둔다 (지금은 PAUSED 로 바꾸는 경로가 없다). */ + public static final Set COMPLETABLE_STATUSES = + Set.of(ParticipantStatus.ACTIVE); + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @@ -158,6 +163,21 @@ public void undoWithdrawal() { this.leftAt = null; } + /** + * 완주 — 끝난 스터디의 명부 행을 {@code COMPLETED} 로 바꾼다 (specs/study-participant/spec.md 「완주」). 스터디가 끝났는지는 + * 부르는 서비스가 스터디 행을 잠그고 확인한다. {@link #COMPLETABLE_STATUSES} 밖의 행은 그대로 둔다 — 중단 · 탈퇴한 사람은 완주가 아니고, + * 이미 완주한 행을 다시 바꾸면 완주 이벤트가 두 번 난다. {@code leftAt} 은 비워 둔다 — 출석률 분모를 스터디 끝까지 그대로 센다. + * + * @return 이번에 바뀌었으면 true + */ + public boolean complete() { + if (!COMPLETABLE_STATUSES.contains(status)) { + return false; + } + this.status = ParticipantStatus.COMPLETED; + return true; + } + /** * 회원 탈퇴 — 명부 행을 지우지 않고 표시만 바꾼다. 행을 지우면 이미 쌓인 STUDY_ATTENDANCE(ACCOUNT_ID 로만 연결, FK 없음)가 갈 곳을 잃어 * 집계에서 통째로 빠진다(specs/user-leave/spec.md). ACCOUNT_ID 는 그대로 둔다 — 참조할 ACCOUNT 행 자체가 없어져 더는 사람으로 diff --git a/backend/domain/src/main/java/com/studyclub/domain/participant/StudyParticipantCompleted.java b/backend/domain/src/main/java/com/studyclub/domain/participant/StudyParticipantCompleted.java new file mode 100644 index 000000000..b7d64be02 --- /dev/null +++ b/backend/domain/src/main/java/com/studyclub/domain/participant/StudyParticipantCompleted.java @@ -0,0 +1,38 @@ +package com.studyclub.domain.participant; + +import com.studyclub.common.event.DomainEvent; +import com.studyclub.common.event.EventMeta; + +/** + * 명부 행이 완주(COMPLETED)로 바뀌었다. 완주 전환 트랜잭션 안에서 바뀐 행마다 하나 발행된다 (specs/domain-events/spec.md). 이미 완주한 행은 + * 다시 발행하지 않는다. + */ +public record StudyParticipantCompleted( + EventMeta meta, Long studyId, Long participantId, Long accountId) implements DomainEvent { + + public static final String NAME = "study_participant.completed"; + + /** 스터디가 끝나서 시스템이 바꾼다 — 행위자가 없다. */ + public static StudyParticipantCompleted of(StudyParticipant participant) { + return new StudyParticipantCompleted( + EventMeta.now(null), + participant.getStudyId(), + participant.getId(), + participant.getAccountId()); + } + + @Override + public String name() { + return NAME; + } + + @Override + public String aggregateType() { + return "study_participant"; + } + + @Override + public String aggregateId() { + return String.valueOf(participantId); + } +} diff --git a/backend/domain/src/main/java/com/studyclub/domain/participant/StudyParticipantRepository.java b/backend/domain/src/main/java/com/studyclub/domain/participant/StudyParticipantRepository.java index 76e9108bb..639853ca3 100644 --- a/backend/domain/src/main/java/com/studyclub/domain/participant/StudyParticipantRepository.java +++ b/backend/domain/src/main/java/com/studyclub/domain/participant/StudyParticipantRepository.java @@ -31,6 +31,26 @@ List findByStudyIdAndStatusIn( + " AND p.status = com.studyclub.domain.participant.ParticipantStatus.ACTIVE") List findActiveInOngoingStudies(@Param("asOf") Instant asOf); + /** 완주 전환 후보 — 끝난 스터디({@code Study#isEnded}) 중 완주로 넘어갈 행이 남은 스터디 ID, 오름차순. */ + @Query( + "SELECT DISTINCT s.id FROM StudyParticipant p, Study s" + + " WHERE p.studyId = s.id" + + " AND p.status IN :statuses" + + " AND " + + StudyLifecycleQuery.ENDED_JPQL + + " ORDER BY s.id") + List findEndedStudyIdsWithStatusIn( + @Param("asOf") Instant asOf, @Param("statuses") Collection statuses); + + /** 완주 전환 — 스터디 행을 잠근 뒤 바꿀 행을 잠그고 최신 값으로 읽는다. 같은 때 커밋된 참여 중단 · 회원 탈퇴를 덮어쓰지 않는다. */ + @Lock(LockModeType.PESSIMISTIC_WRITE) + @Query( + "SELECT p FROM StudyParticipant p" + + " WHERE p.studyId = :studyId AND p.status IN :statuses ORDER BY p.id") + List findByStudyIdAndStatusInForUpdate( + @Param("studyId") Long studyId, + @Param("statuses") Collection statuses); + void deleteByStudyId(Long studyId); /** 내 스터디 목록(MyStudyQueryService)과 회원 탈퇴 익명화(AccountDeletionService) 공용 조회. */ @@ -132,6 +152,22 @@ List countCapacityHoldersByStudyIds( @Param("studyIds") Collection studyIds, @Param("roles") Collection roles); + /** + * 목록에 보이는 인원 — 정원 역할 중 참여 중(ACTIVE)과 완주(COMPLETED). 끝난 스터디의 크루는 완주로 넘어가므로 ACTIVE 만 세면 0명이 된다. + * 모집 판정에는 쓰지 않는다 — 정원은 {@link #countCapacityHoldersByStudyIds} (결정 D4-A). + */ + @Query( + "SELECT participant.studyId, COUNT(participant) FROM StudyParticipant participant " + + "WHERE participant.studyId IN :studyIds " + + "AND participant.status IN (" + + "com.studyclub.domain.participant.ParticipantStatus.ACTIVE, " + + "com.studyclub.domain.participant.ParticipantStatus.COMPLETED) " + + "AND participant.participantRole IN :roles " + + "GROUP BY participant.studyId") + List countCrewByStudyIds( + @Param("studyIds") Collection studyIds, + @Param("roles") Collection roles); + /** * 웹 기준 navigator 의 디스코드 ID — 안 끝난 스터디(OPEN · ONGOING 이고 END_AT 전) 어디서든 명부가 LEADER · (ACTIVE · * PAUSED)이고 디스코드를 연동한 계정. navigator role 은 길드에 하나라 「다른 진행 중 스터디에서 활성 LEADER 면 떼지 않는다」(DSC-08)와 diff --git a/backend/domain/src/main/java/com/studyclub/domain/study/Study.java b/backend/domain/src/main/java/com/studyclub/domain/study/Study.java index 2142fff8b..d5cf6c913 100644 --- a/backend/domain/src/main/java/com/studyclub/domain/study/Study.java +++ b/backend/domain/src/main/java/com/studyclub/domain/study/Study.java @@ -175,6 +175,10 @@ public RecruitStatus recruitStatus( if (status != StudyStatus.OPEN) { return null; } + // 끝난 스터디는 모집이 닫혀 있다. 완주 전환이 ACTIVE 를 COMPLETED 로 바꾸면 정원을 차지하는 인원이 줄어 다시 열린 것처럼 보이기 때문이다 + if (isEnded(asOf)) { + return RecruitStatus.RECRUIT_CLOSED; + } boolean deadlinePassed = recruitDeadlineAt != null && !asOf.isBefore(recruitDeadlineAt); boolean capacityReached = recruitmentCapacity != null && crewCount >= recruitmentCapacity; return (deadlinePassed || capacityReached) @@ -183,7 +187,8 @@ public RecruitStatus recruitStatus( } /** - * 지금 신청할 수 있는가 — 마감 UTC 순간 · 정원 · 공개 상태만 본다. 조회자 시간대는 보지 않아 서울 · LA · 토론토에서 같은 값이다 (PRD §6). + * 지금 신청할 수 있는가 — 종료 · 마감 UTC 순간 · 정원 · 공개 상태만 본다. 조회자 시간대는 보지 않아 서울 · LA · 토론토에서 같은 값이다 (PRD + * §6). */ public boolean canApply( long crewCount, Instant recruitDeadlineAt, Integer recruitmentCapacity, Instant asOf) { diff --git a/backend/domain/src/main/java/com/studyclub/domain/study/StudyLifecycleQuery.java b/backend/domain/src/main/java/com/studyclub/domain/study/StudyLifecycleQuery.java index f218b0303..184a1a9e8 100644 --- a/backend/domain/src/main/java/com/studyclub/domain/study/StudyLifecycleQuery.java +++ b/backend/domain/src/main/java/com/studyclub/domain/study/StudyLifecycleQuery.java @@ -7,13 +7,18 @@ private StudyLifecycleQuery() {} private static final String STATUS = "com.studyclub.domain.study.StudyStatus."; - /** JPQL — 끝났다 ({@link Study#isEnded(java.time.Instant)}). */ + /** + * JPQL — 끝났다 ({@link Study#isEnded(java.time.Instant)}). 작성 중(DRAFT)은 {@code END_AT} 이 지나도 끝나지 + * 않는다. + */ public static final String ENDED_JPQL = - "(s.status IN (" + "(s.status <> " + + STATUS + + "DRAFT AND (s.status IN (" + STATUS + "ENDED, " + STATUS - + "CLOSED) OR (s.endAt IS NOT NULL AND s.endAt <= :asOf))"; + + "CLOSED) OR (s.endAt IS NOT NULL AND s.endAt <= :asOf)))"; /** JPQL — 진행 중 ({@link Study#isOngoing}). */ public static final String ONGOING_JPQL = diff --git a/backend/domain/src/main/resources/db/migration/V75__complete_participants_of_ended_studies.sql b/backend/domain/src/main/resources/db/migration/V75__complete_participants_of_ended_studies.sql new file mode 100644 index 000000000..fde254ac2 --- /dev/null +++ b/backend/domain/src/main/resources/db/migration/V75__complete_participants_of_ended_studies.sql @@ -0,0 +1,12 @@ +-- V75 — 이미 끝난 스터디의 참여 중(ACTIVE) 명부를 완주(COMPLETED)로 (specs/study-participant/spec.md 「완주」) +-- 배포 뒤에는 완주 전환 스케줄러가 행마다 study_participant.completed 를 내며 바꾼다. 이미 끝난 스터디는 여기서 이벤트 없이 바꾼다 — +-- 옛 크루에게 완주 알림이 한꺼번에 가지 않게. +-- 끝남 판정은 Study.isEnded · StudyLifecycleQuery.ENDED_JPQL 과 같다: 작성 중(DRAFT)이 아니고, ENDED · CLOSED 이거나 END_AT 이 지났다. +-- END_AT 은 UTC 로 저장된다 (serverTimezone=UTC). + +UPDATE STUDY_PARTICIPANT p + JOIN STUDY s ON s.ID = p.STUDY_ID +SET p.STATUS = 'COMPLETED' +WHERE p.STATUS = 'ACTIVE' + AND s.STATUS <> 'DRAFT' + AND (s.STATUS IN ('ENDED', 'CLOSED') OR (s.END_AT IS NOT NULL AND s.END_AT <= UTC_TIMESTAMP(6))); diff --git a/backend/domain/src/test/java/com/studyclub/domain/participant/StudyParticipantTest.java b/backend/domain/src/test/java/com/studyclub/domain/participant/StudyParticipantTest.java index 281f4659a..e2fe21606 100644 --- a/backend/domain/src/test/java/com/studyclub/domain/participant/StudyParticipantTest.java +++ b/backend/domain/src/test/java/com/studyclub/domain/participant/StudyParticipantTest.java @@ -76,6 +76,39 @@ void withdrawRejectsFinishedRows() { } } + @Test + @DisplayName("완주 - ACTIVE 는 COMPLETED 가 되고 true, leftAt 은 비워 둔다") + void completeActive() { + StudyParticipant participant = participantWith(ParticipantStatus.ACTIVE, null); + + assertThat(participant.complete()).isTrue(); + assertThat(participant.getStatus()).isEqualTo(ParticipantStatus.COMPLETED); + assertThat(participant.getLeftAt()).isNull(); + } + + @Test + @DisplayName("완주 - PAUSED · WITHDRAWN · DELETED · COMPLETED 는 그대로 두고 false") + void completeLeavesOtherStatuses() { + Instant leftAt = Instant.parse("2026-03-01T00:00:00Z"); + for (ParticipantStatus status : + new ParticipantStatus[] { + ParticipantStatus.PAUSED, + ParticipantStatus.WITHDRAWN, + ParticipantStatus.DELETED, + ParticipantStatus.COMPLETED + }) { + Instant before = + status == ParticipantStatus.WITHDRAWN || status == ParticipantStatus.DELETED + ? leftAt + : null; + StudyParticipant participant = participantWith(status, before); + + assertThat(participant.complete()).as(status.name()).isFalse(); + assertThat(participant.getStatus()).isEqualTo(status); + assertThat(participant.getLeftAt()).isEqualTo(before); + } + } + @Test @DisplayName("회원 탈퇴 - ACTIVE(leftAt 없음)였다면 탈퇴 시각을 leftAt 으로 채운다") void setsLeftAtForActiveParticipant() { diff --git a/backend/domain/src/test/java/com/studyclub/domain/study/StudyTest.java b/backend/domain/src/test/java/com/studyclub/domain/study/StudyTest.java index 8830b118b..2b09d8f2a 100644 --- a/backend/domain/src/test/java/com/studyclub/domain/study/StudyTest.java +++ b/backend/domain/src/test/java/com/studyclub/domain/study/StudyTest.java @@ -268,6 +268,24 @@ void canApply_capacityAndStatus() { assertThat(getStudy(StudyStatus.DRAFT).canApply(0, deadline, null, now)).isFalse(); } + @Test + @DisplayName("신청 가능: 끝난 스터디(END_AT 경과)는 마감 · 정원이 비어 있어도 불가 — 완주 전환으로 ACTIVE 가 줄어도 다시 열리지 않는다") + void canApply_endedStudy() { + Instant now = Instant.parse("2026-09-01T00:00:00Z"); + + assertThat( + phased(StudyStatus.OPEN, now.minusSeconds(86400 * 30), now.minusSeconds(1)) + .canApply(0, null, null, now)) + .isFalse(); + assertThat( + phased( + StudyStatus.OPEN, + now.plusSeconds(86400), + now.plusSeconds(86400 * 30)) + .canApply(0, null, null, now)) + .isTrue(); + } + @Test @DisplayName("주소: 빈 문자열·공백은 null 로 저장하고, 앞뒤 공백은 자른다") void changeLinks_blankBecomesNull() { diff --git a/frontend/apps/back-office-front/src/features/participants/GroupsSection.tsx b/frontend/apps/back-office-front/src/features/participants/GroupsSection.tsx index 8dca5b070..a4ad4aa0d 100644 --- a/frontend/apps/back-office-front/src/features/participants/GroupsSection.tsx +++ b/frontend/apps/back-office-front/src/features/participants/GroupsSection.tsx @@ -65,7 +65,9 @@ export function GroupsSection({ { data.participants.filter( - (p) => p.groupId === group.groupId && (p.status === 'ACTIVE' || p.status === 'PAUSED'), + (p) => + p.groupId === group.groupId && + (p.status === 'ACTIVE' || p.status === 'PAUSED' || p.status === 'COMPLETED'), ).length } 명 diff --git a/frontend/apps/back-office-front/src/features/participants/ParticipantsTab.test.tsx b/frontend/apps/back-office-front/src/features/participants/ParticipantsTab.test.tsx index e9cc8540a..8e3d425c5 100644 --- a/frontend/apps/back-office-front/src/features/participants/ParticipantsTab.test.tsx +++ b/frontend/apps/back-office-front/src/features/participants/ParticipantsTab.test.tsx @@ -247,6 +247,18 @@ describe('참여자 반 편성', () => { expect(screen.queryByText('승인')).not.toBeInTheDocument(); }); + it('끝난 스터디의 완주 크루를 반 인원으로 세고, 반 · 역할은 고치지 못하게 잠근다', async () => { + const response = structuredClone(data); + for (const p of response.participants) p.status = 'COMPLETED'; + mount(response); + + expect(await screen.findByText('참여 크루 2명')).toBeVisible(); + const defaultGroup = screen.getByRole('button', { name: '기본반 수정' }).closest('.card') as HTMLElement; + expect(within(defaultGroup).getByText('2명')).toBeVisible(); + expect(screen.getByRole('checkbox', { name: '한국크루 선택' })).toBeDisabled(); + expect(screen.getByRole('checkbox', { name: '북미캡틴 선택' })).toBeDisabled(); + }); + it('변경을 모아 변경한 행만 한 요청으로 저장한다', async () => { const fetch = mount(data, async (_, init) => { const { changes } = JSON.parse(init.body as string); diff --git a/frontend/apps/core-front/src/features/attendance/AttendanceTabContent.test.tsx b/frontend/apps/core-front/src/features/attendance/AttendanceTabContent.test.tsx new file mode 100644 index 000000000..4484ed1c0 --- /dev/null +++ b/frontend/apps/core-front/src/features/attendance/AttendanceTabContent.test.tsx @@ -0,0 +1,72 @@ +import type { Study } from '@studyclub/types'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; +import { render, screen } from '@testing-library/react'; +import userEvent from '@testing-library/user-event'; +import { beforeEach, describe, expect, it, vi } from 'vitest'; + +import { AttendanceTabContent } from './AttendanceTabContent'; +import type { ApiAttendance } from './types'; + +const group = { id: '31', name: '기본반', timeZone: 'Asia/Seoul', startAt: '2026-10-01T11:00:00Z' }; + +const attendance: ApiAttendance = { + study: { id: 7, title: '끝난 스터디', participantCount: 2, totalMeetings: 1, avgAttendanceRate: null }, + meetings: [{ id: 501, scheduledAt: '2026-10-08T11:00:00Z' }], + participants: [ + { + participantId: 11, + displayName: '네비', + participantRole: 'LEADER', + captain: false, + participantStatus: 'COMPLETED', + leftAt: null, + attendances: [{ meetingId: 501, status: 'PRESENT' }], + attendanceRate: 1, + }, + { + participantId: 12, + displayName: '크루', + participantRole: 'MEMBER', + captain: false, + participantStatus: 'COMPLETED', + leftAt: null, + attendances: [{ meetingId: 501, status: 'ABSENT' }], + attendanceRate: 0, + }, + ], +}; + +describe('AttendanceTabContent', () => { + beforeEach(() => { + // 표 가로 스크롤 그림자를 재는 데 쓴다 — jsdom 에는 없다 + vi.stubGlobal( + 'ResizeObserver', + class { + observe() {} + disconnect() {} + }, + ); + }); + + it('끝난 스터디의 완주 크루도 골라서 일괄 변경할 수 있지만, 참여 중단은 잠근다', async () => { + const user = userEvent.setup(); + render( + + undefined} + canEdit + /> + , + ); + + await user.click(screen.getByRole('checkbox', { name: '크루 선택' })); + + expect(screen.getByRole('combobox', { name: '바꿀 출석 상태' })).toBeEnabled(); + expect(screen.getByRole('button', { name: '참여 중단' })).toBeDisabled(); + expect(screen.getByText('끝난 스터디에서는 참여 중단할 수 없습니다.')).toBeInTheDocument(); + }); +}); diff --git a/frontend/apps/core-front/src/features/attendance/AttendanceTabContent.tsx b/frontend/apps/core-front/src/features/attendance/AttendanceTabContent.tsx index 847ca0210..b566cda00 100644 --- a/frontend/apps/core-front/src/features/attendance/AttendanceTabContent.tsx +++ b/frontend/apps/core-front/src/features/attendance/AttendanceTabContent.tsx @@ -143,6 +143,8 @@ type Person = { leftAt: string | null; manageable: boolean; withdrawable: boolean; + /** 끝난 스터디의 완주 행 — 출석은 고치지만 참여 중단은 서버가 409 로 막는다. */ + completed: boolean; /** 서버가 계산한 출석률 (0–1 소수). 편집 중이 아닐 때 이 값을 그대로 보여 준다. */ attendanceRate: number | null; }; @@ -216,8 +218,9 @@ export function AttendanceTabContent({ ? ('navigator' as const) : undefined, leftAt: p.leftAt, - manageable: p.participantStatus === 'ACTIVE', + manageable: p.participantStatus === 'ACTIVE' || p.participantStatus === 'COMPLETED', withdrawable: !me && !p.captain && p.participantRole?.toLowerCase() !== 'leader', + completed: p.participantStatus === 'COMPLETED', attendanceRate: p.attendanceRate, }; }) @@ -277,6 +280,7 @@ export function AttendanceTabContent({ const selected = selectable.filter((id) => picked.has(id)); const allPicked = selectable.length > 0 && selected.length === selectable.length; const blockedNames = people.filter((p) => selected.includes(p.id) && !p.withdrawable).map((p) => p.name); + const endedPicked = people.some((p) => selected.includes(p.id) && p.completed); const withdrawIds = people.filter((p) => !p.leftAt && toWithdraw.has(p.id)).map((p) => p.id); const withdrawNames = people.filter((p) => withdrawIds.includes(p.id)).map((p) => p.name); @@ -488,7 +492,7 @@ export function AttendanceTabContent({