diff --git a/.prober/tests/participant-completion.md b/.prober/tests/participant-completion.md new file mode 100644 index 000000000..d6dc56e98 --- /dev/null +++ b/.prober/tests/participant-completion.md @@ -0,0 +1,27 @@ +# 종료된 스터디의 완료 전환 (ZAPP #193) + +대상: stage (`backend-develop` · `back-office-front-develop` · `core-front-develop`). 스펙 [study-participant 「완료」](../../specs/study-participant/spec.md#완료-completed). 스테이지의 테스트 계정만 쓴다. 담당 캡틴 계정 하나, 같은 반의 네비게이터 · 크루 계정 하나씩, 그 반에서 참여를 중단한 크루 계정 하나로 한다. 결과 · 캡처에 실제 회원 정보와 토큰을 남기지 않는다. + +준비: 진행 중(OPEN, 시작일 지남)인 테스트 스터디 하나와 지난 회차 하나 이상. 그 스터디의 최근 모집 회차는 마감일이 없거나 아직 지나지 않았고 정원이 남아 있어야 한다(모집이 이미 마감돼 있으면 `CP-LIST-01` · `CP-APPLY-01` 이 이번 변경 없이도 같은 결과를 낸다). 크루가 발표자인 회차가 하나 있으면 `CP-VIEW-01` 을 함께 본다. 화면에서는 종료일을 넣을 수 없으므로 **DB 권한자가 그 스터디의 `STUDY.END_AT` 을 지금보다 몇 분 뒤(UTC)로 바꿔 둔다**. `CP-CLOSED-01` 용으로 `ACTIVE` 참여자가 있는 다른 테스트 스터디 하나를 `STATUS = CLOSED`, `END_AT` 을 지난 시각으로 바꿔 둔다. 스테이지는 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-RUN-03 | `GET /api/studies/{id}` | `status` 가 `ENDED`(종료로 저장됐다), `recruitStatus` 가 `null`, `canApply` 가 `false` | +| CP-CLOSED-01 | 1~2분 뒤 `CLOSED` 로 둔 스터디를 캡틴으로 백오피스 › 신청자 탭에서 열고, `GET /api/studies/{id}` 를 부른다 | 참여자의 선택 칸이 잠기지 않는다(완료 행만 잠긴다 — 운영 종료는 완료로 넘기지 않는다). API 의 `status` 는 `CLOSED` 그대로다 | +| 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` 는 `null`(`ENDED` 로 저장된 뒤다. `CP-BEFORE-02` 에서는 `true` · `RECRUITING`) | +| CP-LIST-02 | 백오피스 스터디 목록을 `지원 현황` 열로 내림차순 정렬 | 그 스터디의 지원 현황이 완료한 사람 수로 보이고, 그 수로 정렬된다(0명으로 맨 뒤에 가지 않는다) | +| CP-APPLY-01 | 디스코드를 연동한 새 크루 계정으로 그 스터디에 `POST /api/studies/{id}/applications` | 404. 신청 행이 생기지 않는다(`ENDED` 로 저장된 뒤라 `STATUS = OPEN` 검사에서 막힌다) | +| 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` · `endIfDue`), 백오피스 `src/features/participants/ParticipantsTab.test.tsx`, core-front `src/features/attendance/AttendanceTabContent.test.tsx`. diff --git a/01-planning/stories/captain-reregister-cohort/PRD.md b/01-planning/stories/captain-reregister-cohort/PRD.md index dfc9cc23e..e89558aa1 100644 --- a/01-planning/stories/captain-reregister-cohort/PRD.md +++ b/01-planning/stories/captain-reregister-cohort/PRD.md @@ -97,7 +97,7 @@ flowchart LR - **조건**: 창을 열었을 때 - **동작**: 누르면 다음 달 기수를 미공개로 만들고 창을 닫는다. 이어서 참여한 인원을 알린다 -- **데이터**: `POST /api/admin/studies/{studyId}/next-cohort` — `capacity` → 201, 미공개 스터디 · 모집 · 날마다 회차 · 이번 기수 `ACTIVE` 참여자 전원의 `STUDY_PARTICIPANT` +- **데이터**: `POST /api/admin/studies/{studyId}/next-cohort` — `capacity` → 201, 미공개 스터디 · 모집 · 날마다 회차 · 이번 기수 `ACTIVE` · `COMPLETED`(완료) 참여자 전원의 `STUDY_PARTICIPANT` 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..0705b1fd3 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,11 @@ public Long submit(Long accountId, Long studyId, SubmitStudyApplicationRequest r if (study.getStatus() != StudyStatus.OPEN) { throw new BusinessException(ErrorCode.NOT_FOUND); } + // 끝난 스터디는 받지 않는다 — 종료일이 지나 스케줄러가 ENDED 로 저장하기 전 1분이다. 완료 전환으로 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..685d89cf9 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..fd86f53ed 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..a199abb06 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..68cc99faf 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..ec16ab28b --- /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분마다 종료일이 지난 스터디를 종료(ENDED)로 저장하고 명부를 완료로 바꾼다 ({@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..e1a955520 --- /dev/null +++ b/backend/api/src/main/java/com/studyclub/api/participant/StudyParticipantCompletionService.java @@ -0,0 +1,72 @@ +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 com.studyclub.domain.study.StudyStatus; +import java.time.Instant; +import java.util.List; +import org.springframework.context.ApplicationEventPublisher; +import org.springframework.stereotype.Service; +import org.springframework.transaction.annotation.Transactional; + +/** + * 종료일이 지난 스터디를 종료(ENDED)로 저장하고, 같은 트랜잭션에서 명부를 완료로 바꾼다 (specs/study-participant/spec.md 「완료」). 후보는 + * 잠금 없이 고르고, 스터디마다 스터디 행을 잠근 뒤 다시 판정한다 — 고른 뒤 운영자가 종료일을 늦췄을 수 있다. 서버가 여러 대여도 스터디 행 잠금이 줄을 세우고, 늦은 + * 쪽은 바꿀 행이 없어 이벤트를 다시 내지 않는다. 운영 종료(CLOSED)는 완료와 관계없어 건드리지 않는다. + * + *

벌크 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; + } + + /** 종료일이 지나 ENDED 로 저장할 스터디와 ENDED 인데 완료로 넘어갈 행이 남은 스터디 ID, 오름차순. */ + @Transactional(readOnly = true) + public List findCandidates(Instant now) { + return studyParticipantRepository.findStudyIdsToComplete( + now, StudyParticipant.COMPLETABLE_STATUSES); + } + + /** + * 스터디 하나를 종료로 저장하고 명부를 완료 처리한다. 부른 쪽의 트랜잭션에 합류한다 — 같은 트랜잭션에서 스터디 행을 잠그거나 바꾼 뒤 불러도 그 변경을 보고, 같은 + * 행을 다시 기다리지 않는다. 스케줄러는 트랜잭션 없이 부르므로 스터디마다 따로 커밋되고, 실패하면 그 스터디만 롤백된다(ENDED 저장도 함께). + * + * @return 완료로 바꾼 행 수. 스터디가 없거나 종료(ENDED)가 아니면(종료일 전 · 운영 종료 · 작성 중) 0 + */ + @Transactional + public int complete(Long studyId, Instant now) { + Study study = studyRepository.findByIdForUpdate(studyId).orElse(null); + if (study == null) { + return 0; + } + study.endIfDue(now); + if (study.getStatus() != StudyStatus.ENDED) { + 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..5b90c674d 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..3851b30ec 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..98f403ed8 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..1eb6b4bb3 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..9e27bc92f 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..704ec56b2 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..20fb2aa4c 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} +# 종료일이 지난 스터디를 ENDED 로 저장하고 명부를 완료(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..aa5a66e11 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..d20cd7813 --- /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..40602dafe --- /dev/null +++ b/backend/api/src/test/java/com/studyclub/api/participant/StudyParticipantCompletionIntegrationTest.java @@ -0,0 +1,281 @@ +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( + "종료일이 지난 스터디를 ENDED 로 저장하고 ACTIVE · PAUSED 만 COMPLETED · 행마다 이벤트 1건(행위자 없음)," + + " 나머지 상태는 그대로이고 이벤트 0건") + void endsStudyAndCompletesActiveAndPausedRows() { + 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(3); + assertThat(reload(study).getStatus()).isEqualTo(StudyStatus.ENDED); + + for (StudyParticipant p : List.of(leader, crew, paused)) { + StudyParticipant reloaded = reload(p); + assertThat(reloaded.getStatus()).isEqualTo(ParticipantStatus.COMPLETED); + assertThat(reloaded.getLeftAt()).isNull(); + assertThat(reloaded.getParticipantRole()).isEqualTo(p.getParticipantRole()); + } + 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(), paused.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(reload(study).getStatus()).isEqualTo(StudyStatus.ENDED); + assertThat(completionService.findCandidates(now)).doesNotContain(study.getId()); + } + + @Test + @DisplayName("ENDED 스터디는 종료일 없이도 넘어가고, 운영 종료(CLOSED)는 종료일이 지나도 후보가 아니며 그대로 둔다") + void completesEndedButNotClosedStudies() { + Study ended = saveStudy(StudyStatus.ENDED, null); + saveParticipant(saveGroup(ended), ParticipantRole.MEMBER, ParticipantStatus.ACTIVE); + Study closed = saveStudy(StudyStatus.CLOSED, now.minus(1, ChronoUnit.DAYS)); + StudyParticipant inClosed = + saveParticipant( + saveGroup(closed), ParticipantRole.MEMBER, ParticipantStatus.ACTIVE); + + assertThat(completionService.findCandidates(now)) + .contains(ended.getId()) + .doesNotContain(closed.getId()); + assertThat(completionService.complete(ended.getId(), now)).isEqualTo(1); + assertThat(completionService.complete(closed.getId(), now)).isZero(); + + assertThat(reload(closed).getStatus()).isEqualTo(StudyStatus.CLOSED); + assertThat(reload(inClosed).getStatus()).isEqualTo(ParticipantStatus.ACTIVE); + assertThat(completedEvents()).hasSize(1); + } + + @Test + @DisplayName("명부가 빈 스터디도 종료일이 지나면 ENDED 로 저장되고, 그 뒤로는 후보에서 빠진다") + void endsStudyWithEmptyRoster() { + Study study = saveStudy(StudyStatus.OPEN, now.minus(1, ChronoUnit.DAYS)); + + assertThat(completionService.findCandidates(now)).contains(study.getId()); + assertThat(completionService.complete(study.getId(), now)).isZero(); + + assertThat(reload(study).getStatus()).isEqualTo(StudyStatus.ENDED); + assertThat(completionService.findCandidates(now)).doesNotContain(study.getId()); + assertThat(completedEvents()).isEmpty(); + } + + @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(reload(running).getStatus()).isEqualTo(StudyStatus.OPEN); + assertThat(reload(noEnd).getStatus()).isEqualTo(StudyStatus.ONGOING); + assertThat(reload(draft).getStatus()).isEqualTo(StudyStatus.DRAFT); + 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(reload(study).getStatus()).isEqualTo(StudyStatus.OPEN); + 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(); + } + + private Study reload(Study study) { + return studyRepo.findById(study.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..c644d19bc 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..9b5c0a9e3 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,12 @@ @AllArgsConstructor(access = AccessLevel.PRIVATE) public class StudyParticipant extends BaseEntity { + /** + * 스터디가 종료(ENDED)될 때 완료로 넘어가는 상태. 쉬는 중(PAUSED)도 참여 중처럼 넘긴다 (2026-12-05 기획 결정, PAUSED 는 없앨 예정). + */ + public static final Set COMPLETABLE_STATUSES = + Set.of(ParticipantStatus.ACTIVE, ParticipantStatus.PAUSED); + @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @@ -158,6 +165,22 @@ public void undoWithdrawal() { this.leftAt = null; } + /** + * 완료 — 종료(ENDED)된 스터디의 명부 행을 {@code COMPLETED} 로 바꾼다 (specs/study-participant/spec.md 「완료」). + * 스터디가 종료됐는지는 부르는 서비스가 스터디 행을 잠그고 확인한다. {@link #COMPLETABLE_STATUSES} 밖의 행은 그대로 둔다 — 중단 · 탈퇴한 + * 사람은 완료가 아니고, 이미 완료한 행을 다시 바꾸면 완료 이벤트가 두 번 난다. {@code leftAt} 은 비워 둔다 — 출석률 분모를 스터디 끝까지 그대로 + * 센다. 완주(결석 0회 등)는 저장하지 않고 계산한다. + * + * @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..499c9ec6e --- /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..2fa01e8d2 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,31 @@ List findByStudyIdAndStatusIn( + " AND p.status = com.studyclub.domain.participant.ParticipantStatus.ACTIVE") List findActiveInOngoingStudies(@Param("asOf") Instant asOf); + /** + * 완료 전환 후보, ID 오름차순 — 종료일이 지났는데 아직 종료(ENDED)로 저장되지 않은 공개 스터디({@code Study#endIfDue})와, 이미 ENDED + * 인데 완료로 넘어갈 행이 남은 스터디. 운영 종료(CLOSED) · 작성 중(DRAFT)은 들지 않는다. + */ + @Query( + "SELECT s.id FROM Study s" + + " WHERE (s.status IN (com.studyclub.domain.study.StudyStatus.OPEN," + + " com.studyclub.domain.study.StudyStatus.ONGOING)" + + " AND s.endAt IS NOT NULL AND s.endAt <= :asOf)" + + " OR (s.status = com.studyclub.domain.study.StudyStatus.ENDED" + + " AND EXISTS (SELECT p.id FROM StudyParticipant p" + + " WHERE p.studyId = s.id AND p.status IN :statuses))" + + " ORDER BY s.id") + List findStudyIdsToComplete( + @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 +157,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..e90f11a1a 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) { @@ -230,8 +235,9 @@ public boolean isPubliclyVisible() { } /** - * 날짜까지 읽은 지금 상태. 저장된 {@code STATUS} 는 {@code OPEN → ONGOING → ENDED} 로 넘어가지 않아(study-meeting 결정 - * 5) 진행 중 · 종료는 {@code START_AT} · {@code END_AT} 경과로 판정한다. 쿼리판은 {@link StudyLifecycleQuery} — + * 날짜까지 읽은 지금 상태. 저장된 {@code STATUS} 는 {@code ONGOING} 으로 넘어가지 않아(study-meeting 결정 5) 진행 중은 + * {@code START_AT} 경과로 판정한다. {@code ENDED} 는 종료일이 지나면 완료 전환 스케줄러가 1분 안에 저장하고({@link + * #endIfDue}), 그 사이에도 끝난 것으로 읽도록 {@code END_AT} 경과를 같이 본다. 쿼리판은 {@link StudyLifecycleQuery} — * 한쪽만 고치면 어긋난다. */ public StudyStatus statusAsOf(Instant asOf) { @@ -252,8 +258,9 @@ public boolean isOngoing(Instant asOf) { } /** - * 끝난 스터디 — 운영자가 끝냈거나({@code ENDED} · {@code CLOSED}) {@code END_AT} 이 지났다. 명부 · 공지를 더 바꾸지 않는다 - * (specs/study-participant/spec.md · specs/study-notice/spec.md). + * 끝난 스터디 — 종료({@code ENDED}) · 운영 종료({@code CLOSED}) 이거나 {@code END_AT} 이 지났다. 명부 · 공지를 더 바꾸지 + * 않는다 (specs/study-participant/spec.md · specs/study-notice/spec.md). 명부를 완료로 넘기는 계기는 이것이 아니라 + * {@link #endIfDue} 다 — 운영 종료는 완료와 관계없다. */ public boolean isEnded(Instant asOf) { StudyStatus current = statusAsOf(asOf); @@ -264,6 +271,22 @@ public boolean isEnded() { return isEnded(Instant.now()); } + /** + * 종료일({@code END_AT})이 지난 공개 스터디({@code OPEN} · {@code ONGOING})를 종료({@code ENDED})로 저장한다. 부르는 + * 서비스가 같은 트랜잭션에서 명부를 완료로 바꾼다 (specs/study-participant/spec.md 「완료」). 작성 중({@code DRAFT}) · 운영 + * 종료({@code CLOSED}) · 이미 {@code ENDED} 인 스터디와 종료일이 없거나 남은 스터디는 그대로 둔다. + * + * @return 이번에 {@code ENDED} 로 바뀌었으면 true + */ + public boolean endIfDue(Instant asOf) { + boolean open = status == StudyStatus.OPEN || status == StudyStatus.ONGOING; + if (!open || endAt == null || asOf.isBefore(endAt)) { + return false; + } + this.status = StudyStatus.ENDED; + return true; + } + public void replaceApplicationForm(String applicationForm) { this.applicationForm = applicationForm; } 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/java/com/studyclub/domain/study/StudyStatus.java b/backend/domain/src/main/java/com/studyclub/domain/study/StudyStatus.java index fe4ce5da5..3b8220e05 100644 --- a/backend/domain/src/main/java/com/studyclub/domain/study/StudyStatus.java +++ b/backend/domain/src/main/java/com/studyclub/domain/study/StudyStatus.java @@ -9,6 +9,9 @@ public enum StudyStatus { ENDED, CLOSED; - /** 운영자가 끝낸 상태값 — 날짜 경과는 빠져 있다. 끝났는지 판정은 {@link Study#isEnded(java.time.Instant)}. */ + /** + * 끝난 상태값 — {@code ENDED} 는 종료일이 지나면 스케줄러가 1분 안에 저장한다({@link Study#endIfDue}). 그 1분까지 보는 판정은 + * {@link Study#isEnded(java.time.Instant)}. + */ public static final List ENDED_STATUSES = List.of(ENDED, CLOSED); } 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..a921ff950 --- /dev/null +++ b/backend/domain/src/main/resources/db/migration/V75__complete_participants_of_ended_studies.sql @@ -0,0 +1,13 @@ +-- V75 — 이미 끝난 스터디의 명부(ACTIVE · PAUSED)를 완료(COMPLETED)로 (specs/study-participant/spec.md 「완료」) +-- 배포 뒤에는 완료 전환 스케줄러가 종료일이 지난 스터디를 ENDED 로 저장하면서 행마다 study_participant.completed 를 내며 바꾼다. +-- 이미 끝난 스터디는 여기서 이벤트 없이 바꾼다 — 옛 크루에게 알림이 한꺼번에 가지 않게. 그 스터디들의 STATUS 는 배포 뒤 스케줄러가 +-- ENDED 로 저장하고, 바꿀 행이 남지 않아 이벤트도 내지 않는다. +-- 대상은 스케줄러(StudyParticipantRepository.findStudyIdsToComplete)와 같다: ENDED 이거나, OPEN · ONGOING 인데 END_AT 이 지났다. +-- 운영 종료(CLOSED)는 완료와 관계없어 빠진다. 작성 중(DRAFT)도 빠진다. 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 IN ('ACTIVE', 'PAUSED') + AND (s.STATUS = 'ENDED' + OR (s.STATUS IN ('OPEN', 'ONGOING') AND 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..00f09295b 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,41 @@ void withdrawRejectsFinishedRows() { } } + @Test + @DisplayName("완료 - ACTIVE · PAUSED 는 COMPLETED 가 되고 true, leftAt 은 비워 둔다") + void completeActiveAndPaused() { + for (ParticipantStatus status : + new ParticipantStatus[] {ParticipantStatus.ACTIVE, ParticipantStatus.PAUSED}) { + StudyParticipant participant = participantWith(status, null); + + assertThat(participant.complete()).as(status.name()).isTrue(); + assertThat(participant.getStatus()).isEqualTo(ParticipantStatus.COMPLETED); + assertThat(participant.getLeftAt()).isNull(); + } + } + + @Test + @DisplayName("완료 - WITHDRAWN · DELETED · COMPLETED 는 그대로 두고 false") + void completeLeavesOtherStatuses() { + Instant leftAt = Instant.parse("2026-03-01T00:00:00Z"); + for (ParticipantStatus status : + new ParticipantStatus[] { + 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..98b4ef4e5 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() { @@ -280,6 +298,32 @@ void changeLinks_blankBecomesNull() { assertThat(study.getDriveUrl()).isNull(); } + @Test + @DisplayName("종료 저장: 종료일이 지난 OPEN · ONGOING 만 ENDED 가 되고 true, 나머지는 그대로 false") + void endIfDue() { + Instant now = Instant.now(); + for (StudyStatus status : new StudyStatus[] {StudyStatus.OPEN, StudyStatus.ONGOING}) { + var pastEnd = phased(status, days(-30), days(-1)); + assertThat(pastEnd.endIfDue(now)).as(status.name()).isTrue(); + assertThat(pastEnd.getStatus()).isEqualTo(StudyStatus.ENDED); + assertThat(pastEnd.endIfDue(now)).as("이미 ENDED").isFalse(); + } + var atEnd = phased(StudyStatus.OPEN, days(-30), now); + assertThat(atEnd.endIfDue(now)).as("종료일 그 시각").isTrue(); + + for (Study study : + new Study[] { + phased(StudyStatus.OPEN, days(-1), days(30)), + phased(StudyStatus.OPEN, days(-1), null), + phased(StudyStatus.DRAFT, days(-30), days(-1)), + phased(StudyStatus.CLOSED, days(-30), days(-1)) + }) { + StudyStatus before = study.getStatus(); + assertThat(study.endIfDue(now)).as(before.name()).isFalse(); + assertThat(study.getStatus()).isEqualTo(before); + } + } + private static Instant days(long days) { return Instant.now().plus(days, ChronoUnit.DAYS); } diff --git a/docs/erd/ADMIN_AUDIT_LOG.md b/docs/erd/ADMIN_AUDIT_LOG.md index babb7df32..6b6e83c87 100644 --- a/docs/erd/ADMIN_AUDIT_LOG.md +++ b/docs/erd/ADMIN_AUDIT_LOG.md @@ -47,7 +47,7 @@ | `PARTICIPANT_ROLE` | 백오피스 신청자 탭에서 명부 행의 역할(네비게이터 지정 · 해제)을 바꿨다 ([study-group](../../specs/study-group/spec.md)). 역할이 실제로 바뀐 행만 | 변경 전 역할(`MEMBER` · `LEADER`) / 명부 행 ID — 역할은 둘뿐이라 변경 후 값은 BEFORE 의 반대다 | | `OWNER_CAPTAIN` | 백오피스 신청자 탭에서 스터디의 담당 캡틴(`STUDY.OWNER_CAPTAIN_ID`)을 바꿨다 ([study-group](../../specs/study-group/spec.md#담당-캡틴-바꾸기)). 값이 실제로 바뀐 경우만. `TARGET_ACCOUNT_ID` = 새 담당 캡틴 (2026-11-16) | 옛 담당 캡틴 계정 ID(없었으면 NULL) / 스터디 ID | | `ACCOUNT_ROLE_REVOKE` | 캡틴 본인의 계정 탈퇴로 권한 말소 | ADMIN / NONE | -| `PARTICIPANT_REVOKE` | ACTIVE/PAUSED 네비게이터의 계정 탈퇴로 권한 말소. 참여 행마다 1건 | LEADER / NONE | +| `PARTICIPANT_REVOKE` | ACTIVE/PAUSED/COMPLETED 네비게이터의 계정 탈퇴로 권한 말소(완료한 네비게이터도 권한이 남는다). 참여 행마다 1건 | LEADER / NONE | | `EVENT_CANCEL` | 캡틴이 행사를 실제로 `CANCELLED` 로 바꿨다 — 함께 취소된 신청이 0건이어도 남긴다. 이미 취소된 행사 · 409 실패는 남기지 않는다 ([event-status](../../specs/event-status/spec.md#행사-취소-감사-기록-s4), PR #479 S4). `TARGET_ACCOUNT_ID` = NULL, `CLUB_EVENT_ID` = 행사. 이메일 · 답변 · 취소 안내 본문은 넣지 않는다 | 취소 직전 행사 상태(`PUBLISHED` · `CLOSED`) / 함께 취소된 신청 수(10진 문자열, `0` 포함) | ## 제약 diff --git a/docs/erd/STUDY.md b/docs/erd/STUDY.md index 767b54618..f38b4a1ab 100644 --- a/docs/erd/STUDY.md +++ b/docs/erd/STUDY.md @@ -53,7 +53,7 @@ | `DRAFT` | 작성 중 / 모집 전. 비공개 | 전부 가능 | | `OPEN` | 개설 — 공개하며 모집을 시작한 단계 | 기본 정보 일부 잠김 (기간) | | `ONGOING` | (미팅) 진행 중 | 기본 정보 일부 잠김 (기간) | -| `ENDED` | (미팅) 종료 | 읽기 전용 | +| `ENDED` | 종료 — 종료일(`END_AT`)이 지나면 시스템이 저장한다 (2026-12-05) | 읽기 전용 | | `CLOSED` | 채널 삭제 완료 — 운영 종료 | 읽기 전용 | **단계 이름에 「공개」를 쓰지 않는다.** `DRAFT` 를 벗어난 네 단계(`OPEN`·`ONGOING`·`ENDED`·`CLOSED`) 는 @@ -68,7 +68,8 @@ stateDiagram-v2 DRAFT --> OPEN : 캡틴이 모집 시작 OPEN --> DRAFT : 공개 취소 OPEN --> ONGOING : 네비게이터가 첫 미팅 등록 - ONGOING --> ENDED : 네비게이터 종료 처리 / 마지막 미팅으로부터 N주 경과 + OPEN --> ENDED : 종료일 경과 (시스템) + ONGOING --> ENDED : 종료일 경과 (시스템) ENDED --> CLOSED : 캡틴이 채널 삭제 후 운영 종료 CLOSED --> [*] ``` @@ -78,10 +79,10 @@ stateDiagram-v2 | 생성 → `DRAFT` | 캡틴 | | | `DRAFT` → `OPEN` | 캡틴이 공개하며 모집 시작 | `STUDY_RECRUITMENT.START_AT` 를 채운다 — **공개가 된다** | | `OPEN` → `ONGOING` | 네비게이터가 첫 미팅([STUDY_MEETING](./STUDY_MEETING.md))을 등록 — **지금은 일으키지 않는다** (아래 메모) | | -| `ONGOING` → `ENDED` | 네비게이터가 종료 처리, 또는 마지막 미팅으로부터 N주 경과 (시스템) | | -| `ENDED` → `CLOSED` | 캡틴이 채널을 삭제하고 운영을 종료 | | +| `OPEN` · `ONGOING` → `ENDED` | 종료일(`END_AT`)이 지나면 완료 전환 스케줄러가 1분 안에 저장한다 (시스템, 2026-12-05 기획 결정). 저장된 상태는 `ONGOING` 으로 넘어가지 않아 지금은 `OPEN` 에서 넘어간다 | 같은 트랜잭션에서 명부의 `ACTIVE` · `PAUSED` 를 `COMPLETED` 로 바꾼다 ([STUDY_PARTICIPANT](./STUDY_PARTICIPANT.md), [study-participant 「완료」](../../specs/study-participant/spec.md#완료-completed)) | +| `ENDED` → `CLOSED` | 캡틴이 채널을 삭제하고 운영을 종료 (백오피스 「운영 종료」 버튼 — 아직 없음) | 명부는 바꾸지 않는다. 운영 종료는 완료와 관계없다 | -`START_AT` / `END_AT`(진행 일정)은 화면에 보이는 값일 뿐 **상태를 바꾸지 않는다** — 상태는 위 전이로만 바뀐다. +`START_AT`(진행 시작일)은 **상태를 바꾸지 않는다**. `END_AT`(종료일)은 지나면 `ENDED` 로 저장하는 계기다 (2026-12-05, 위 전이표). 그전까지 종료일이 지난 `OPEN` 행이 날짜로만 끝난 것으로 읽혔다. [POL-0002](../../01-planning/_registry/policies/POL-0002-study-status.md) 의 「`END_AT` 은 상태를 바꾸지 않는다」와 어긋나며, 정책 문서는 기획이 고친다. > **메모 (2026-10-02) — `OPEN → ONGOING` 은 아직 아무도 일으키지 않는다.** 회차 등록 API([study-meeting 스펙](../../specs/study-meeting/spec.md#결정-사항) 결정 5)는 > 첫 회차를 등록해도 `STATUS` 를 바꾸지 않기로 했다. `Study.recruitStatus()` 가 `STATUS = OPEN` 일 때만 값을 주고 그 밖엔 null 이라, @@ -161,7 +162,7 @@ stateDiagram-v2 | (보이지 않음) | `DRAFT` | 공개 전 | | 모집 중 | `OPEN` | 공개됨. 모집 중/마감은 [모집 상태](#모집-상태-계산--저장-안-함)로 다시 가른다 | | 진행 중 | `ONGOING` | (미팅) 진행 중 | -| 종료 | `ENDED` · `CLOSED` | 미팅이 더 이상 없거나 네비게이터가 종료 처리한 것. 채널 삭제(`CLOSED`)는 운영 내부 정리라 사용자에게는 구분하지 않는다 | +| 종료 | `ENDED` · `CLOSED` | 종료일이 지난 것(시스템이 `ENDED` 로 저장한다, 2026-12-05) 또는 운영 종료한 것. 채널 삭제(`CLOSED`)는 운영 내부 정리라 사용자에게는 구분하지 않는다 | ### 공개 여부 diff --git a/docs/erd/STUDY_PARTICIPANT.md b/docs/erd/STUDY_PARTICIPANT.md index 834a58f9d..a1518b844 100644 --- a/docs/erd/STUDY_PARTICIPANT.md +++ b/docs/erd/STUDY_PARTICIPANT.md @@ -14,7 +14,7 @@ | STATUS | VARCHAR(20) | N | 아래 | | PARTICIPANT_ROLE | VARCHAR(20) | N | 아래 | | JOINED_AT | DATETIME | N | 편입 시각 | -| LEFT_AT | DATETIME | Y | 참여가 끝난 시각. `WITHDRAWN`·`DELETED` 일 때만 값이 있다. 출석률 집계가 이 시각까지의 회차만 분모에 넣는다(2026-10-01) | +| LEFT_AT | DATETIME | Y | 참여가 끝난 시각. `WITHDRAWN`·`DELETED` 일 때만 값이 있다(`COMPLETED` 는 비어 있다). 출석률 집계가 이 시각까지의 회차만 분모에 넣는다(2026-10-01) | ## 관계 - N : 1 [ACCOUNT](./ACCOUNT.md), [STUDY_CLASS](./STUDY_CLASS.md) @@ -27,7 +27,7 @@ | `ACTIVE` | 참여 중. 기본값 | | `PAUSED` | 잠시 쉼 (출석 집계 제외) | | `WITHDRAWN` | 참여 중단 — 하차 · 제명을 가르지 않는다. 삭제 대신 이 상태. `LEFT_AT` 에 중단 시각. 네비게이터 · 담당 캡틴이 출석부에서 중단시킬 수 있다 ([참여 중단 스펙](../../specs/study-participant/spec.md)) | -| `COMPLETED` | 완주 (STUDY ENDED 시 ACTIVE → COMPLETED 일괄) | +| `COMPLETED` | 완료 — 스터디가 종료될 때까지 참여를 중단하지 않고 남은 사람. 스터디가 종료(`ENDED`)될 때 `ACTIVE` · `PAUSED` 행이 넘어온다. 종료일(`END_AT`)이 지나면 1분 간격 스케줄러가 스터디를 `ENDED` 로 저장하고, 같은 트랜잭션에서 행마다 엔티티 메서드로 바꾸며 `study_participant.completed` 를 낸다. 운영 종료(`CLOSED`)는 넘기지 않는다. `LEFT_AT` 은 비워 둔다. 배포 전에 이미 끝난 스터디는 `V75` 가 이벤트 없이 한 번에 바꿨다. 완주(일반 스터디는 결석 0회, 클럽은 완료 전원)는 저장하지 않고 계산한다 ([완료 스펙](../../specs/study-participant/spec.md#완료-completed), 2026-12-05) | | `DELETED` | 회원 탈퇴로 사라진 행. 삭제 대신 이 상태 — 행을 지우면 STUDY_ATTENDANCE(ACCOUNT_ID 로만 연결, FK 없음)가 출석률 집계에서 통째로 빠지기 때문([user-leave spec](../../specs/user-leave/spec.md)). `LEFT_AT` 에 탈퇴 시각. ACCOUNT_ID 는 그대로 둔다 — 참조할 ACCOUNT 행 자체가 없어져 더는 사람으로 되짚을 수 없다 | ```mermaid @@ -37,7 +37,8 @@ stateDiagram-v2 PAUSED --> ACTIVE : 복귀 ACTIVE --> WITHDRAWN : 하차 PAUSED --> WITHDRAWN : 하차 - ACTIVE --> COMPLETED : 스터디 종료 + ACTIVE --> COMPLETED : 스터디 종료 (스케줄러) + PAUSED --> COMPLETED : 스터디 종료 (스케줄러) ACTIVE --> DELETED : 회원 탈퇴 PAUSED --> DELETED : 회원 탈퇴 COMPLETED --> DELETED : 회원 탈퇴 diff --git a/docs/share/2026-12-05-study-end-and-participant-completion.md b/docs/share/2026-12-05-study-end-and-participant-completion.md new file mode 100644 index 000000000..77f458cd9 --- /dev/null +++ b/docs/share/2026-12-05-study-end-and-participant-completion.md @@ -0,0 +1,48 @@ +--- +상태: 결정됨 +물어볼 사람: 기획 (세은) +반영: + - specs/study-participant · study · study-recruit-status · study-application · club-cohort · domain-events, ERD STUDY · STUDY_PARTICIPANT — 됨 (#591) + - 01-planning/_registry/policies/POL-0002-study-status.md (「`END_AT` 은 상태를 바꾸지 않는다」) — 안 됨 (기획) + - 01-planning/_registry/policies/POL-0013-web-notification.md N06 행 (「`COMPLETED` 가 되면 N06」) — 확인 필요 (N06 대상 미정) + - 01-planning/stories/crew-joined-studies/PRD.md (완료와 완주 나눠 보이기) — 안 됨 (후속 이슈) +공유: 공유전 +--- + +# 스터디가 끝나면 시스템이 「종료」로 저장하고, 끝까지 남은 사람을 「완료」로 바꾼다 + +## 미리 알아야 할 것 + +- **명부**는 스터디마다 누가 참여하는지 적은 표다. 사람마다 참여 상태가 있다. 참여 중(`ACTIVE`), 쉬는 중(`PAUSED`), 참여 중단(`WITHDRAWN`), 완료(`COMPLETED`)다. +- **스터디 상태**도 따로 있다. 모집 중(`OPEN`), 종료(`ENDED`), 운영 종료(`CLOSED`) 등이다. 종료일(`END_AT`)은 스터디가 끝나는 날짜다. +- 지금까지는 스터디가 끝나도 상태를 바꾸는 코드가 없었다. 종료일이 지나도 `OPEN` 으로 남았고, 명부의 `COMPLETED` 는 아무도 쓰지 않는 값이었다. +- 근거: [PR #591 세은님 코멘트](https://github.com/StudyClub-PlusPlus/studyclub-engineering/pull/591#issuecomment-7441529954). + +## 한 줄 요약 + +종료일이 지나면 1분 안에 시스템이 스터디를 `ENDED` 로 저장하고, 그때 남아 있던 사람을 `COMPLETED`(완료)로 바꾼다. 완주는 저장하지 않고 계산한다. + +## 왜 — 지금 뭐가 문제인가 + +- 완주 알림(N06)과 클럽 다음 기수 준비가 「참여자가 완료로 바뀌는 순간」을 기다린다. 그런데 그 순간을 만드는 코드가 없었다. +- 「완주」라는 말이 두 가지 뜻으로 쓰였다. 끝까지 남은 사람과 결석 없이 끝낸 사람이다. + +마라톤에 비유하면, 완료는 결승선을 넘은 사람이고 완주는 그중 한 번도 쉬지 않은 사람이다. 결승선을 넘었는지는 기록해 두고, 쉬었는지는 기록을 보고 계산한다. + +## 정해진 것 + +1. **완료와 완주를 나눈다.** 완료(`COMPLETED`)는 끝까지 남은 사람이고 상태로 저장한다. 완주는 저장하지 않는다. 일반 스터디는 완료한 사람 중 결석 0회, 클럽은 완료한 사람 전원이다. 지각 · 사유 결석은 결석이 아니다. +2. **종료는 자동이다.** 종료일이 지나면 시스템이 `ENDED` 로 저장한다. 운영 종료(`CLOSED`)는 백오피스 버튼으로 하는 수동 작업이다. 종료일 입력 칸과 버튼은 아직 없다. +3. **운영 종료는 완료와 관계없다.** 참여 상태는 스터디가 `ENDED` 로 바뀔 때만 완료로 바뀐다. +4. **쉬는 중(`PAUSED`)도 완료로 넘긴다.** `PAUSED` 는 나중에 없앤다. +5. **디스코드 role 은 회수하지 않는다.** 완료한 네비게이터도 출석을 고칠 수 있다. +6. **운영 규칙:** 캡틴이 미팅이 끝날 때 출석을 모두 체크한다. + +아직 정하지 않은 것도 있다. N06 완주 알림을 완주한 사람에게만 보낼지, 완료한 사람 모두에게 문구를 나눠 보낼지다. `ENDED` 를 거치지 않고 운영 종료된 스터디의 명부를 어떻게 할지도 버튼을 만들 때 정한다. + +## 영향 — 누가 무엇을 해야 하나 + +- **기획(세은님):** POL-0002 를 이 결정에 맞춘다. N06 대상을 정한다. 완주 계산 · 내 스터디 표시 · 종료일 입력 칸 · 운영 종료 버튼 같은 후속 작업은 ZAPP 이슈로 #193 에 잇는다. +- **알림(N06) 담당:** `study_participant.completed` 이벤트는 완료마다 한 번 난다(#591). 완주만 알릴지는 위 결정을 기다린다. +- **클럽 기수 배치(ST-021) 담당:** 기수의 `ENDED` 저장과 참여자 전환은 공통 전환이 한다. 클럽 전용 배치를 따로 두지 않는다. 기수의 종료일은 다음 달 1일 0시(KST)로 넣는다. +- **화면을 만드는 사람:** 종료일이 지난 스터디는 `status` 가 `ENDED`, `recruitStatus` 가 `null` 이다. 신청하면 `404` 다. diff --git a/docs/share/README.md b/docs/share/README.md index 6f355eb64..4753d959a 100644 --- a/docs/share/README.md +++ b/docs/share/README.md @@ -105,6 +105,7 @@ | 날짜 | 건 | 상태 | 반영 | 공유 | |---|---|---|---|---| +| 2026-12-05 | [스터디가 끝나면 시스템이 「종료」로 저장하고, 끝까지 남은 사람을 「완료」로 바꾼다](2026-12-05-study-end-and-participant-completion.md) | 결정됨 | 일부 (POL-0002 · POL-0013 N06 · crew-joined-studies PRD) | 공유전 | | 2026-12-05 | [기존 업무 기능을 유지하고 회원 알림의 발송 조건을 확정했다](2026-12-05-web-notification-policy-decisions.md) | 결정됨 | 일부 (기획·프로토 됨, #589 spec 반영 대기) | 공유전 | | 2026-12-04 | [출결 수동 변경 알림으로 범위 조정](2026-12-04-attendance-change-notifications.md) | 결정됨 | 일부 (#589 웹 알림 스펙·계획·태스크 반영 필요) | 공유전 | | 2026-12-03 | [회원 웹 알림 생성·수신·읽음 정책](2026-12-03-web-notification-policy.md) | 결정됨 | 됨 (정책·PRD·인수 기준·기존 메일 계약 경계, 웹 API 계약 후속) | 공유전 | 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..92f7053dd 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..77459fc07 --- /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..f3bc129b7 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({