From 238490aafeda76a5147ccc5842250d4ffe5e30dc Mon Sep 17 00:00:00 2001 From: doxxx93 Date: Sun, 6 Dec 2026 16:35:56 +0900 Subject: [PATCH 1/4] =?UTF-8?q?feat(participant):=20=EC=99=84=EC=A3=BC?= =?UTF-8?q?=EB=A5=BC=20=EA=B2=B0=EC=84=9D=200=EB=B2=88=20=EA=B8=B0?= =?UTF-8?q?=EC=A4=80=EC=9C=BC=EB=A1=9C=20=EA=B3=84=EC=82=B0=ED=95=B4=20?= =?UTF-8?q?=EB=82=B4=20=EC=8A=A4=ED=84=B0=EB=94=94=EC=99=80=20=EC=8B=A0?= =?UTF-8?q?=EC=B2=AD=EC=9E=90=20=EC=9D=B4=EB=A0=A5=EC=97=90=20=EB=8B=B4?= =?UTF-8?q?=EB=8A=94=EB=8B=A4=20(ZAPP-194)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 완주 판정은 StudyParticipantFinish.finished() 한 곳: COMPLETED 이고 클럽이거나 결석 0번 - 재료는 findFinishesByAccountIds 쿼리 한 번. 종료일 전에 시작한 회차의 ABSENT 만 센다 - 내 스터디 응답에 items[].finished 를 더한다 - 신청자의 지난 완주율(completionRate)을 COMPLETED 비율에서 완주 비율로 바꾼다 - 내 스터디 화면은 완주 카드와 회색 「완료」 카드를 나눠 보이고, 완주 카드를 먼저 둔다 --- .../AdminApplicationQueryService.java | 15 +- .../api/participant/MyStudyQueryService.java | 16 +- .../participant/ParticipantHubResponses.java | 1 + .../AdminApplicationIntegrationTest.java | 100 ++++++++++++ .../participant/MyStudyIntegrationTest.java | 154 ++++++++++++++++++ .../participant/StudyParticipantFinish.java | 23 +++ .../participant/StudyParticipantHistory.java | 37 ++++- .../StudyParticipantRepository.java | 37 +++-- .../StudyParticipantFinishTest.java | 46 ++++++ .../StudyParticipantHistoryTest.java | 60 +++++++ .../e2e/specs/joined-studies.spec.ts | 40 ++++- .../src/app/[locale]/my/joined/page.tsx | 31 ++-- .../src/features/my-studies/mapper.test.ts | 6 + .../src/features/my-studies/mapper.ts | 1 + .../src/features/my-studies/model.ts | 17 +- .../features/my-studies/response-schema.ts | 2 + .../src/features/my-studies/types.ts | 3 + frontend/packages/mock/src/msw/handlers/me.ts | 5 +- 18 files changed, 544 insertions(+), 50 deletions(-) create mode 100644 backend/domain/src/main/java/com/studyclub/domain/participant/StudyParticipantFinish.java create mode 100644 backend/domain/src/test/java/com/studyclub/domain/participant/StudyParticipantFinishTest.java create mode 100644 backend/domain/src/test/java/com/studyclub/domain/participant/StudyParticipantHistoryTest.java diff --git a/backend/api/src/main/java/com/studyclub/api/application/AdminApplicationQueryService.java b/backend/api/src/main/java/com/studyclub/api/application/AdminApplicationQueryService.java index 05ce2dd28..5a15f256c 100644 --- a/backend/api/src/main/java/com/studyclub/api/application/AdminApplicationQueryService.java +++ b/backend/api/src/main/java/com/studyclub/api/application/AdminApplicationQueryService.java @@ -15,11 +15,10 @@ import com.studyclub.domain.study.StudyRecruitment; import com.studyclub.domain.study.StudyRecruitmentRepository; import com.studyclub.domain.study.StudyRepository; +import java.time.Instant; import java.util.Collections; import java.util.List; import java.util.Map; -import java.util.function.Function; -import java.util.stream.Collectors; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import tools.jackson.core.JacksonException; @@ -73,17 +72,13 @@ public StudyApplicationsResponse getApplications( Map histories = applicationRows.isEmpty() ? Map.of() - : studyParticipantRepository - .findHistoriesByAccountIds( + : StudyParticipantHistory.of( + studyParticipantRepository.findFinishesByAccountIds( applicationRows.stream() .map(StudyApplicationWithAccount::accountId) .toList(), - studyId) - .stream() - .collect( - Collectors.toMap( - StudyParticipantHistory::accountId, - Function.identity())); + Instant.now()), + studyId); // 사본이 없는 신청이 남은 기수는 그 뒤로 폼이 저장된 적이 없다 — 지금 폼이 그 신청이 받은 질문이다 List formQuestions = applicationRows.stream().anyMatch(row -> row.questionsSnapshot() == null) diff --git a/backend/api/src/main/java/com/studyclub/api/participant/MyStudyQueryService.java b/backend/api/src/main/java/com/studyclub/api/participant/MyStudyQueryService.java index 3d8d2db9f..6450791e8 100644 --- a/backend/api/src/main/java/com/studyclub/api/participant/MyStudyQueryService.java +++ b/backend/api/src/main/java/com/studyclub/api/participant/MyStudyQueryService.java @@ -10,6 +10,7 @@ import com.studyclub.domain.attendance.StudyAttendanceRepository; import com.studyclub.domain.participant.ParticipantStatus; import com.studyclub.domain.participant.StudyParticipant; +import com.studyclub.domain.participant.StudyParticipantFinish; import com.studyclub.domain.participant.StudyParticipantRepository; import com.studyclub.domain.study.MeetingSchedule; import com.studyclub.domain.study.Study; @@ -24,6 +25,7 @@ import java.util.Comparator; import java.util.List; import java.util.Map; +import java.util.Set; import java.util.function.Function; import java.util.stream.Collectors; import org.springframework.stereotype.Service; @@ -32,7 +34,7 @@ /** * 내 스터디 목록 — 명부 행마다 스터디 하나, 내 반의 회차와 회차별 내 출석을 붙인다 (specs/my-studies/spec.md). 탭·페이징은 화면이 한다. * - *

쿼리는 명부 · 스터디 · 회차 · 출석 네 번이다. 명부 행 수와 무관하다. + *

쿼리는 명부 · 스터디 · 회차 · 출석 · 프로그램 · 완주 재료 여섯 번이다. 명부 행 수와 무관하다. */ @Service public class MyStudyQueryService { @@ -62,6 +64,7 @@ public MyStudyListResponse getMyStudies(Long accountId) { if (participants.isEmpty()) { return new MyStudyListResponse(List.of()); } + Instant now = Instant.now(); List studyIds = participants.stream().map(StudyParticipant::getStudyId).toList(); List groupIds = participants.stream().map(StudyParticipant::getStudyGroupId).toList(); @@ -86,8 +89,14 @@ public MyStudyListResponse getMyStudies(Long accountId) { .toList()) .stream() .collect(Collectors.toMap(StudyProgram::getId, p -> p)); + Set finishedParticipantIds = + studyParticipantRepository + .findFinishesByAccountIds(List.of(accountId), now) + .stream() + .filter(StudyParticipantFinish::finished) + .map(StudyParticipantFinish::participantId) + .collect(Collectors.toSet()); - Instant now = Instant.now(); List items = new ArrayList<>(); for (StudyParticipant participant : participants) { Study study = studyById.get(participant.getStudyId()); @@ -105,6 +114,7 @@ public MyStudyListResponse getMyStudies(Long accountId) { participant, study, program.getStudyKind(), + finishedParticipantIds.contains(participant.getId()), meetings, attendanceByMeetingId, now)); @@ -119,6 +129,7 @@ private MyStudy toMyStudy( StudyParticipant participant, Study study, StudyKind studyKind, + boolean finished, List meetings, Map attendanceByMeetingId, Instant now) { @@ -148,6 +159,7 @@ private MyStudy toMyStudy( study.getStartAt(), study.getEndAt(), relation, + finished, participant.getStatus(), participant.getParticipantRole(), study.isOwnedBy(participant.getAccountId()), diff --git a/backend/api/src/main/java/com/studyclub/api/participant/ParticipantHubResponses.java b/backend/api/src/main/java/com/studyclub/api/participant/ParticipantHubResponses.java index fb81a680c..37f7980b0 100644 --- a/backend/api/src/main/java/com/studyclub/api/participant/ParticipantHubResponses.java +++ b/backend/api/src/main/java/com/studyclub/api/participant/ParticipantHubResponses.java @@ -30,6 +30,7 @@ public record MyStudy( Instant startAt, Instant endAt, MyStudyRelation relation, + boolean finished, ParticipantStatus participantStatus, ParticipantRole participantRole, boolean captain, diff --git a/backend/api/src/test/java/com/studyclub/api/application/AdminApplicationIntegrationTest.java b/backend/api/src/test/java/com/studyclub/api/application/AdminApplicationIntegrationTest.java index b833c46db..a3f6cfe23 100644 --- a/backend/api/src/test/java/com/studyclub/api/application/AdminApplicationIntegrationTest.java +++ b/backend/api/src/test/java/com/studyclub/api/application/AdminApplicationIntegrationTest.java @@ -5,7 +5,26 @@ import com.studyclub.api.auth.JwtService; import com.studyclub.domain.account.AccountRepository; import com.studyclub.domain.account.SystemRole; +import com.studyclub.domain.attendance.AttendanceStatus; +import com.studyclub.domain.attendance.StudyAttendance; +import com.studyclub.domain.attendance.StudyAttendanceRepository; +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.StudyRepository; +import com.studyclub.domain.study.StudyStatus; import java.sql.Timestamp; +import java.time.Duration; import java.time.Instant; import java.util.List; import java.util.Map; @@ -20,6 +39,7 @@ 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; @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @@ -45,6 +65,18 @@ class AdminApplicationIntegrationTest { @Autowired JdbcTemplate jdbcTemplate; + @Autowired StudyProgramRepository studyProgramRepository; + + @Autowired StudyRepository studyRepository; + + @Autowired StudyGroupRepository studyGroupRepository; + + @Autowired StudyMeetingRepository studyMeetingRepository; + + @Autowired StudyParticipantRepository studyParticipantRepository; + + @Autowired StudyAttendanceRepository studyAttendanceRepository; + @BeforeEach void seed() { Timestamp now = Timestamp.from(Instant.now()); @@ -93,6 +125,28 @@ void captainReadsApplications() { assertThat(answers).containsEntry("reason", "같이 공부하고 싶습니다."); } + @Test + @DisplayName("성공 - 지난 완주는 완료 행 수가 아니라 완주 규칙으로 센다: 일반 스터디는 결석 0번, 클럽은 완료 전원") + void countsPreviousFinishesByFinishRule() { + completedWithOneAbsence(StudyKind.STUDY); + completedWithOneAbsence(StudyKind.CLUB); + + ResponseEntity response = + rest.exchange( + "/api/admin/studies/" + STUDY_ID + "/applications", + HttpMethod.GET, + authenticatedRequest(ADMIN_ID), + Map.class); + + assertThat(response.getStatusCode()).isEqualTo(HttpStatus.OK); + @SuppressWarnings("unchecked") + Map application = + (Map) ((List) response.getBody().get("applications")).get(0); + // 지난 참여 4건(완료 3 · 참여 중단 1) 중 완주는 결석 없는 일반 스터디와 클럽 2건 + assertThat(application).containsEntry("previousParticipationCount", 4); + assertThat(application).containsEntry("completionRate", 50); + } + @Test @DisplayName("성공 - 사본이 없는 신청은 지금 폼 질문을 그 신청이 받은 질문으로 준다") void fallsBackToCurrentFormForApplicationWithoutSnapshot() { @@ -271,6 +325,8 @@ private void insertAccount(Long id, String email, SystemRole role, Timestamp now } private void cleanSeedRows() { + jdbcTemplate.update("DELETE FROM STUDY_ATTENDANCE WHERE ACCOUNT_ID = ?", APPLICANT_ID); + jdbcTemplate.update("DELETE FROM STUDY_PARTICIPANT WHERE ACCOUNT_ID = ?", APPLICANT_ID); jdbcTemplate.update( "DELETE FROM STUDY_APPLICATION WHERE RECRUITMENT_ID IN (?, ?)", RECRUITMENT_ID, @@ -367,6 +423,50 @@ private void insertParticipantHistory( now); } + /** 신청자가 지난달 끝난 스터디를 완료했고, 지난 회차 하나에 결석했다. */ + private void completedWithOneAbsence(StudyKind kind) { + Instant startAt = Instant.now().minus(Duration.ofDays(60)); + StudyProgram program = + studyProgramRepository.save( + StudyProgram.builder().title("지난 스터디").studyKind(kind).build()); + Study study = + studyRepository.save( + Study.builder() + .programId(program.getId()) + .title("지난 스터디") + .oneLineSummary("한 줄 소개") + .category(StudyCategory.SOFTWARE) + .status(StudyStatus.ENDED) + .startAt(startAt) + .endAt(Instant.now().minus(Duration.ofDays(30))) + .build()); + StudyGroup group = + studyGroupRepository.save( + new StudyGroup(study.getId(), "수요일반", startAt, "Asia/Seoul", 10)); + studyParticipantRepository.save( + StudyParticipant.builder() + .accountId(APPLICANT_ID) + .studyId(study.getId()) + .studyGroupId(group.getId()) + .status(ParticipantStatus.COMPLETED) + .participantRole(ParticipantRole.MEMBER) + .joinedAt(startAt) + .build()); + Instant held = startAt.plus(Duration.ofDays(7)); + Long meetingId = + studyMeetingRepository + .save(new StudyMeeting(group.getId(), held, held, null)) + .getId(); + studyAttendanceRepository.save( + StudyAttendance.builder() + .accountId(APPLICANT_ID) + .studyId(study.getId()) + .studyGroupId(group.getId()) + .studyMeetingId(meetingId) + .status(AttendanceStatus.ABSENT) + .build()); + } + private void insertApplication(Timestamp now) { jdbcTemplate.update( "INSERT INTO STUDY_APPLICATION (ACCOUNT_ID, RECRUITMENT_ID, FORM_ANSWER," diff --git a/backend/api/src/test/java/com/studyclub/api/participant/MyStudyIntegrationTest.java b/backend/api/src/test/java/com/studyclub/api/participant/MyStudyIntegrationTest.java index 7a4875097..dc68efe95 100644 --- a/backend/api/src/test/java/com/studyclub/api/participant/MyStudyIntegrationTest.java +++ b/backend/api/src/test/java/com/studyclub/api/participant/MyStudyIntegrationTest.java @@ -94,12 +94,14 @@ void splitsRelationsAndHidesLinksFromWithdrawn() { assertThat(item(items, upcoming)).containsEntry("relation", "UPCOMING"); assertThat(item(items, ongoing)) .containsEntry("relation", "ONGOING") + .containsEntry("finished", false) .containsEntry("discordChannelUrl", DISCORD_URL); assertThat(item(items, completed)) .containsEntry("relation", "COMPLETED") .containsEntry("driveUrl", DRIVE_URL); assertThat(item(items, withdrawn)) .containsEntry("relation", "WITHDRAWN") + .containsEntry("finished", false) .containsEntry("discordChannelUrl", null) .containsEntry("driveUrl", null); // 시작일 최신순 @@ -201,8 +203,160 @@ void flagsCaptainOnlyForStudiesICreated() { assertThat(item(items, others)).containsEntry("captain", false); } + @Test + @DisplayName("성공 - 완료한 일반 스터디는 결석이 0번일 때만 완주이고, 지각 · 휴가는 결석이 아니다") + void finishedOnlyWithoutAbsence() { + Long clean = + enrollEnded("결석 없음", StudyKind.STUDY, now.minus(DAY), ParticipantStatus.COMPLETED); + StudyParticipant cleanMe = participant(MEMBER_ID, clean); + attend( + cleanMe, + meeting(cleanMe, now.minus(DAY.multipliedBy(21)), true), + AttendanceStatus.PRESENT); + attend( + cleanMe, + meeting(cleanMe, now.minus(DAY.multipliedBy(14)), true), + AttendanceStatus.LATE); + attend( + cleanMe, + meeting(cleanMe, now.minus(DAY.multipliedBy(7)), true), + AttendanceStatus.EXCUSED); + Long absent = + enrollEnded("결석 1번", StudyKind.STUDY, now.minus(DAY), ParticipantStatus.COMPLETED); + StudyParticipant absentMe = participant(MEMBER_ID, absent); + attend( + absentMe, + meeting(absentMe, now.minus(DAY.multipliedBy(14)), true), + AttendanceStatus.PRESENT); + attend( + absentMe, + meeting(absentMe, now.minus(DAY.multipliedBy(7)), true), + AttendanceStatus.ABSENT); + + List> items = items(MEMBER_ID); + + assertThat(item(items, clean)) + .containsEntry("relation", "COMPLETED") + .containsEntry("finished", true); + assertThat(item(items, absent)) + .containsEntry("relation", "COMPLETED") + .containsEntry("finished", false); + } + + @Test + @DisplayName("성공 - 종료일 뒤에 잡힌 회차와 시작 전 회차에 미리 깔린 결석은 세지 않는다") + void ignoresAbsenceOutsideStudyPeriod() { + Instant endAt = now.minus(DAY.multipliedBy(3)); + Long ended = enrollEnded("종료일 뒤 회차", StudyKind.STUDY, endAt, ParticipantStatus.COMPLETED); + StudyParticipant me = participant(MEMBER_ID, ended); + attend(me, meeting(me, endAt.minus(DAY.multipliedBy(7)), true), AttendanceStatus.PRESENT); + // 종료일 뒤 회차 — 열리지 않은 것, 디스코드가 연 것, 아직 오지 않은 것 + attend(me, meeting(me, endAt.plus(DAY), false), AttendanceStatus.ABSENT); + attend(me, meeting(me, endAt.plus(DAY.multipliedBy(2)), true), AttendanceStatus.ABSENT); + attend(me, meeting(me, now.plus(DAY), false), AttendanceStatus.ABSENT); + Long noEndAt = enrollEnded("종료일 없음", StudyKind.STUDY, null, ParticipantStatus.COMPLETED); + StudyParticipant noEndMe = participant(MEMBER_ID, noEndAt); + attend( + noEndMe, + meeting(noEndMe, now.minus(DAY.multipliedBy(7)), true), + AttendanceStatus.PRESENT); + attend(noEndMe, meeting(noEndMe, now.plus(DAY), false), AttendanceStatus.ABSENT); + + List> items = items(MEMBER_ID); + + assertThat(item(items, ended)).containsEntry("finished", true); + assertThat(item(items, noEndAt)).containsEntry("finished", true); + } + + @Test + @DisplayName("성공 - 클럽은 완료하면 결석이 있어도 완주이고, 완료가 아니면 결석이 없어도 완주가 아니다") + void clubFinishesOnCompletionOnly() { + Long club = enrollEnded("클럽", StudyKind.CLUB, now.minus(DAY), ParticipantStatus.COMPLETED); + StudyParticipant clubMe = participant(MEMBER_ID, club); + attend( + clubMe, + meeting(clubMe, now.minus(DAY.multipliedBy(7)), true), + AttendanceStatus.ABSENT); + Long withdrawnClub = + enrollEnded("중단한 클럽", StudyKind.CLUB, now.minus(DAY), ParticipantStatus.WITHDRAWN); + + List> items = items(MEMBER_ID); + + assertThat(item(items, club)).containsEntry("finished", true); + assertThat(item(items, withdrawnClub)).containsEntry("finished", false); + } + + @Test + @DisplayName("성공 - 반을 옮겼으면 옛 반 회차의 결석도 센다") + void countsAbsenceInPreviousGroup() { + Long studyId = + enrollEnded("반 이동", StudyKind.STUDY, now.minus(DAY), ParticipantStatus.COMPLETED); + StudyParticipant me = participant(MEMBER_ID, studyId); + StudyGroup previous = + studyGroupRepository.save( + new StudyGroup( + studyId, + "월요일반", + now.minus(DAY.multipliedBy(60)), + "Asia/Seoul", + 10)); + Long previousMeeting = + studyMeetingRepository + .save( + new StudyMeeting( + previous.getId(), + now.minus(DAY.multipliedBy(30)), + now.minus(DAY.multipliedBy(30)), + null)) + .getId(); + studyAttendanceRepository.save( + StudyAttendance.builder() + .accountId(MEMBER_ID) + .studyId(studyId) + .studyGroupId(previous.getId()) + .studyMeetingId(previousMeeting) + .status(AttendanceStatus.ABSENT) + .build()); + attend(me, meeting(me, now.minus(DAY.multipliedBy(7)), true), AttendanceStatus.PRESENT); + + assertThat(item(items(MEMBER_ID), studyId)).containsEntry("finished", false); + } + // ── helpers ────────────────────────────────────────────────────────────── + /** 끝난 스터디 · 반 · MEMBER_ID 명부 한 줄. 60일 전에 시작했고 그때 편입했다. 종료일은 null 이면 없다. */ + private Long enrollEnded( + String title, StudyKind kind, Instant endAt, ParticipantStatus status) { + Instant startAt = now.minus(DAY.multipliedBy(60)); + StudyProgram program = + studyProgramRepository.save( + StudyProgram.builder().title(title).studyKind(kind).build()); + Study study = + studyRepository.save( + Study.builder() + .programId(program.getId()) + .title(title) + .oneLineSummary("소개") + .category(StudyCategory.SOFTWARE) + .status(StudyStatus.ENDED) + .startAt(startAt) + .endAt(endAt) + .build()); + StudyGroup group = + studyGroupRepository.save( + new StudyGroup(study.getId(), "수요일반", startAt, "Asia/Seoul", 10)); + studyParticipantRepository.save( + StudyParticipant.builder() + .accountId(MEMBER_ID) + .studyId(study.getId()) + .studyGroupId(group.getId()) + .status(status) + .participantRole(ParticipantRole.MEMBER) + .joinedAt(startAt) + .build()); + return study.getId(); + } + /** 스터디 · 반 · MEMBER_ID 명부 한 줄. 명부 편입은 10일 전. */ private Long enroll(String title, Instant startAt, ParticipantStatus status) { return enroll(title, startAt, status, null); diff --git a/backend/domain/src/main/java/com/studyclub/domain/participant/StudyParticipantFinish.java b/backend/domain/src/main/java/com/studyclub/domain/participant/StudyParticipantFinish.java new file mode 100644 index 000000000..b210d7795 --- /dev/null +++ b/backend/domain/src/main/java/com/studyclub/domain/participant/StudyParticipantFinish.java @@ -0,0 +1,23 @@ +package com.studyclub.domain.participant; + +import com.studyclub.domain.study.StudyKind; + +/** + * 명부 행 하나의 완주 판정 재료. 쓰는 곳마다 같은 회차를 세도록 {@link StudyParticipantRepository#findFinishesByAccountIds} + * 로만 만든다. + * + * @param studyKind 스터디 행이 없으면 null + */ +public record StudyParticipantFinish( + Long participantId, + Long accountId, + Long studyId, + ParticipantStatus status, + StudyKind studyKind, + long absences) { + + public boolean finished() { + return status == ParticipantStatus.COMPLETED + && (studyKind == StudyKind.CLUB || absences == 0); + } +} diff --git a/backend/domain/src/main/java/com/studyclub/domain/participant/StudyParticipantHistory.java b/backend/domain/src/main/java/com/studyclub/domain/participant/StudyParticipantHistory.java index dd1b3f5dd..78d6e4960 100644 --- a/backend/domain/src/main/java/com/studyclub/domain/participant/StudyParticipantHistory.java +++ b/backend/domain/src/main/java/com/studyclub/domain/participant/StudyParticipantHistory.java @@ -1,13 +1,46 @@ package com.studyclub.domain.participant; +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +/** 신청자의 지난 참여 — 이 기수를 뺀 명부 중 완료 · 참여 중단으로 끝난 참여 수와 그중 완주 수 (specs/study-application/spec.md). */ public record StudyParticipantHistory( - Long accountId, long previousParticipationCount, long completedParticipationCount) { + Long accountId, long previousParticipationCount, long finishedParticipationCount) { + + private static final Set PAST_STATUSES = + Set.of(ParticipantStatus.COMPLETED, ParticipantStatus.WITHDRAWN); + + /** 계정별로 센다. 지난 참여가 없는 계정은 결과에 없다. */ + public static Map of( + Collection finishes, Long currentStudyId) { + Map histories = new HashMap<>(); + for (StudyParticipantFinish finish : finishes) { + if (finish.studyId().equals(currentStudyId) + || !PAST_STATUSES.contains(finish.status())) { + continue; + } + histories.merge( + finish.accountId(), + new StudyParticipantHistory(finish.accountId(), 1, finish.finished() ? 1 : 0), + StudyParticipantHistory::plus); + } + return histories; + } public Integer completionRate() { if (previousParticipationCount == 0) { return null; } return Math.toIntExact( - Math.round(completedParticipationCount * 100.0 / previousParticipationCount)); + Math.round(finishedParticipationCount * 100.0 / previousParticipationCount)); + } + + private StudyParticipantHistory plus(StudyParticipantHistory other) { + return new StudyParticipantHistory( + accountId, + previousParticipationCount + other.previousParticipationCount, + finishedParticipationCount + other.finishedParticipationCount); } } 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 2fa01e8d2..1618aa720 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 @@ -234,20 +234,27 @@ long countByStudyIdAndStatusAndParticipantRoleIn( + " AND p.participantRole = com.studyclub.domain.participant.ParticipantRole.LEADER") List findLeadersByStudyIdIn(@Param("studyIds") Collection studyIds); + /** + * 완주 판정 재료 ({@link StudyParticipantFinish}). 내 스터디 목록과 신청자의 지난 완주 횟수가 같이 쓴다. + * + *

회차를 만들 때 반 명부 전원에게 ABSENT 가 미리 깔리므로, 시작 전 회차와 종료일 뒤에 잡힌 회차는 세지 않는다. 스터디 행이 없는 명부 행도 지난 참여 + * 수에서 빠지지 않게 스터디는 바깥 조인한다. + */ @Query( - "SELECT new com.studyclub.domain.participant.StudyParticipantHistory(" - + "participant.accountId, COUNT(participant), " - + "SUM(CASE WHEN participant.status = " - + "com.studyclub.domain.participant.ParticipantStatus.COMPLETED " - + "THEN 1 ELSE 0 END)) " - + "FROM StudyParticipant participant " - + "WHERE participant.accountId IN :accountIds " - + "AND participant.studyId <> :currentStudyId " - + "AND participant.status IN (" - + "com.studyclub.domain.participant.ParticipantStatus.COMPLETED, " - + "com.studyclub.domain.participant.ParticipantStatus.WITHDRAWN) " - + "GROUP BY participant.accountId") - List findHistoriesByAccountIds( - @Param("accountIds") Collection accountIds, - @Param("currentStudyId") Long currentStudyId); + """ + SELECT new com.studyclub.domain.participant.StudyParticipantFinish( + p.id, p.accountId, p.studyId, p.status, sp.studyKind, + (SELECT COUNT(a) FROM StudyAttendance a, StudyMeeting m + WHERE a.studyMeetingId = m.id + AND a.studyId = p.studyId AND a.accountId = p.accountId + AND a.status = com.studyclub.domain.attendance.AttendanceStatus.ABSENT + AND COALESCE(m.startAt, m.scheduledAt) <= :asOf + AND (s.endAt IS NULL OR COALESCE(m.startAt, m.scheduledAt) < s.endAt))) + FROM StudyParticipant p + LEFT JOIN Study s ON s.id = p.studyId + LEFT JOIN StudyProgram sp ON sp.id = s.programId + WHERE p.accountId IN :accountIds + """) + List findFinishesByAccountIds( + @Param("accountIds") Collection accountIds, @Param("asOf") Instant asOf); } diff --git a/backend/domain/src/test/java/com/studyclub/domain/participant/StudyParticipantFinishTest.java b/backend/domain/src/test/java/com/studyclub/domain/participant/StudyParticipantFinishTest.java new file mode 100644 index 000000000..62e5711cb --- /dev/null +++ b/backend/domain/src/test/java/com/studyclub/domain/participant/StudyParticipantFinishTest.java @@ -0,0 +1,46 @@ +package com.studyclub.domain.participant; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.studyclub.domain.study.StudyKind; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; +import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.EnumSource; + +class StudyParticipantFinishTest { + + private static StudyParticipantFinish finish( + ParticipantStatus status, StudyKind kind, long absences) { + return new StudyParticipantFinish(1L, 1L, 1L, status, kind, absences); + } + + @Test + @DisplayName("완주 - 클럽은 완료하면 결석이 있어도 완주다") + void clubCompletedIsFinished() { + assertThat(finish(ParticipantStatus.COMPLETED, StudyKind.CLUB, 3).finished()).isTrue(); + } + + @Test + @DisplayName("완주 - 일반 스터디는 완료하고 결석이 0번이면 완주다") + void studyCompletedWithoutAbsenceIsFinished() { + assertThat(finish(ParticipantStatus.COMPLETED, StudyKind.STUDY, 0).finished()).isTrue(); + } + + @Test + @DisplayName("완주 - 일반 스터디는 결석이 1번이라도 있으면 완료일 뿐 완주가 아니다") + void studyCompletedWithAbsenceIsNotFinished() { + assertThat(finish(ParticipantStatus.COMPLETED, StudyKind.STUDY, 1).finished()).isFalse(); + } + + @ParameterizedTest + @EnumSource( + value = ParticipantStatus.class, + names = "COMPLETED", + mode = EnumSource.Mode.EXCLUDE) + @DisplayName("완주 - 완료(COMPLETED)가 아니면 클럽이어도 · 결석이 없어도 완주가 아니다") + void notCompletedIsNotFinished(ParticipantStatus status) { + assertThat(finish(status, StudyKind.CLUB, 0).finished()).isFalse(); + assertThat(finish(status, StudyKind.STUDY, 0).finished()).isFalse(); + } +} diff --git a/backend/domain/src/test/java/com/studyclub/domain/participant/StudyParticipantHistoryTest.java b/backend/domain/src/test/java/com/studyclub/domain/participant/StudyParticipantHistoryTest.java new file mode 100644 index 000000000..4a3e4e621 --- /dev/null +++ b/backend/domain/src/test/java/com/studyclub/domain/participant/StudyParticipantHistoryTest.java @@ -0,0 +1,60 @@ +package com.studyclub.domain.participant; + +import static org.assertj.core.api.Assertions.assertThat; + +import com.studyclub.domain.study.StudyKind; +import java.util.List; +import java.util.Map; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +class StudyParticipantHistoryTest { + + private static final Long CURRENT_STUDY_ID = 100L; + + private static StudyParticipantFinish row( + Long accountId, Long studyId, ParticipantStatus status, StudyKind kind, long absences) { + return new StudyParticipantFinish( + accountId * 1000 + studyId, accountId, studyId, status, kind, absences); + } + + @Test + @DisplayName("지난 참여 - 이 기수를 뺀 완료 · 참여 중단 수와 그중 완주 수를 계정별로 센다") + void countsPastParticipationsAndFinishes() { + Map histories = + StudyParticipantHistory.of( + List.of( + row(1L, 1L, ParticipantStatus.COMPLETED, StudyKind.STUDY, 0), + row(1L, 2L, ParticipantStatus.COMPLETED, StudyKind.STUDY, 1), + row(1L, 3L, ParticipantStatus.COMPLETED, StudyKind.CLUB, 2), + row(1L, 4L, ParticipantStatus.WITHDRAWN, StudyKind.STUDY, 0), + row(2L, 1L, ParticipantStatus.COMPLETED, StudyKind.STUDY, 1)), + CURRENT_STUDY_ID); + + assertThat(histories.get(1L).previousParticipationCount()).isEqualTo(4); + assertThat(histories.get(1L).finishedParticipationCount()).isEqualTo(2); + assertThat(histories.get(1L).completionRate()).isEqualTo(50); + assertThat(histories.get(2L).previousParticipationCount()).isEqualTo(1); + assertThat(histories.get(2L).completionRate()).isZero(); + } + + @Test + @DisplayName("지난 참여 - 이 기수 · 진행 중 · 회원 탈퇴 행은 세지 않고, 남는 참여가 없으면 계정이 빠진다") + void skipsCurrentStudyAndUnfinishedRows() { + Map histories = + StudyParticipantHistory.of( + List.of( + row( + 1L, + CURRENT_STUDY_ID, + ParticipantStatus.COMPLETED, + StudyKind.CLUB, + 0), + row(1L, 2L, ParticipantStatus.ACTIVE, StudyKind.STUDY, 0), + row(1L, 3L, ParticipantStatus.PAUSED, StudyKind.STUDY, 0), + row(1L, 4L, ParticipantStatus.DELETED, StudyKind.STUDY, 0)), + CURRENT_STUDY_ID); + + assertThat(histories).isEmpty(); + } +} diff --git a/frontend/apps/core-front/e2e/specs/joined-studies.spec.ts b/frontend/apps/core-front/e2e/specs/joined-studies.spec.ts index 13b1dd54b..b5fda1125 100644 --- a/frontend/apps/core-front/e2e/specs/joined-studies.spec.ts +++ b/frontend/apps/core-front/e2e/specs/joined-studies.spec.ts @@ -4,7 +4,7 @@ import { expect, test } from '@playwright/test'; const DAY = 24 * 60 * 60 * 1000; const at = (offsetDays: number) => new Date(Date.now() + offsetDays * DAY).toISOString(); -/** GET /api/me/studies 고정 응답 — 참여중 1건 · 완주 1건. 백엔드 없이 화면을 본다. */ +/** GET /api/me/studies 고정 응답 — 참여중 1건 · 완주 1건 · 완료 1건. 백엔드 없이 화면을 본다. */ const MY_STUDIES = { items: [ { @@ -39,18 +39,44 @@ const MY_STUDIES = { startAt: at(-90), endAt: at(-30), relation: 'COMPLETED', + finished: true, participantStatus: 'COMPLETED', participantRole: 'MEMBER', captain: false, discordChannelUrl: null, driveUrl: null, - attendanceRate: 0.5, + attendanceRate: 0.75, meetings: [-60, -45].map((d, i) => ({ meetingId: 2000 + i, sequence: i + 1, scheduledAt: at(d), startAt: null, endAt: null, + attendanceStatus: i === 0 ? 'PRESENT' : 'LATE', + countedInRate: true, + })), + }, + { + studyId: 103, + title: 'E2E 완료 스터디', + category: 'BACKEND', + studyKind: 'STUDY', + startAt: at(-80), + endAt: at(-20), + relation: 'COMPLETED', + finished: false, + participantStatus: 'COMPLETED', + participantRole: 'MEMBER', + captain: false, + discordChannelUrl: null, + driveUrl: null, + attendanceRate: 0.5, + meetings: [-50, -35].map((d, i) => ({ + meetingId: 3000 + i, + sequence: i + 1, + scheduledAt: at(d), + startAt: null, + endAt: null, attendanceStatus: i === 0 ? 'PRESENT' : 'ABSENT', countedInRate: true, })), @@ -155,8 +181,14 @@ test.describe('내 스터디 (crew-joined-studies) — 기본 화면 및 인터 await page.getByRole('tab', { name: '참여 종료' }).click(); await expect(page.getByRole('tab', { name: '참여 종료' })).toHaveAttribute('aria-selected', 'true'); - // 완주 점수판("완주를 축하합니다!") 노출 확인 - await expect(page.getByText(/완주를 축하합니다!/).first()).toBeVisible(); + // 완주 카드만 점수판("완주를 축하합니다!")을 받고, 결석이 있는 완료 카드는 「완료」 배지만 받는다 + const endedCards = page.getByRole('listitem').filter({ hasText: /완주|완료|종료/ }); + await expect(endedCards.filter({ hasText: '완주를 축하합니다!' }).first()).toBeVisible(); + const completedCard = endedCards.filter({ has: page.getByText('완료', { exact: true }) }).first(); + await expect(completedCard).toBeVisible(); + await expect(completedCard).not.toContainText('완주'); + // 참여 종료 탭은 완주 카드가 먼저 + await expect(endedCards.first()).toContainText('완주를 축하합니다!'); // 3. 전체 탭 await page.getByRole('tab', { name: '전체' }).click(); diff --git a/frontend/apps/core-front/src/app/[locale]/my/joined/page.tsx b/frontend/apps/core-front/src/app/[locale]/my/joined/page.tsx index 740e6d80b..977f99996 100644 --- a/frontend/apps/core-front/src/app/[locale]/my/joined/page.tsx +++ b/frontend/apps/core-front/src/app/[locale]/my/joined/page.tsx @@ -15,12 +15,14 @@ import { getUser } from '@/features/auth/auth'; import { IS_DEV, syncPreview } from '@/features/auth/preview'; import { StudyFeedbackButton } from '@/features/feedback/StudyFeedbackButton'; import { + COMPLETED_BADGE, LEFT_BADGE, LIFE_LABEL, SCHEDULE_ROLE_LABEL, addDays, durationOf, isCompleted, + isFinished, lifeStatus, mondayOf, upcomingMeeting, @@ -127,7 +129,7 @@ function studiesIn( return t(a.title, locale).localeCompare(t(b.title, locale), locale); }; return [...list].sort( - (a, b) => (filter === 'ended' ? Number(isCompleted(b)) - Number(isCompleted(a)) : 0) || byKey(a, b), + (a, b) => (filter === 'ended' ? Number(isFinished(b)) - Number(isFinished(a)) : 0) || byKey(a, b), ); } @@ -262,13 +264,18 @@ function MissionClear({ book }: { book: MyAttendanceBook }) { function StudyItem({ study, locale, wallTz }: { study: JoinedStudy; locale: Locale; wallTz: WallTz }) { const { icon: Icon } = categoryMeta(study.category); const life = lifeStatus(study); - const completed = isCompleted(study); - const left = life === 'ended' && !completed; + const finished = isFinished(study); + const left = life === 'ended' && !isCompleted(study); const book = myAttendanceBook(study); // 이 스터디에서 내 역할 — 서버의 participantRole·captain 이 정한다 const role = study.role; // 카드는 스터디 일정으로 간다. 참여를 중단한 스터디는 더 이상 참가자가 아니라 링크가 없다. - const linked = !(life === 'ended' && !completed); + const linked = !left; + const badge = left + ? LEFT_BADGE + : isCompleted(study) + ? COMPLETED_BADGE + : { label: LIFE_LABEL[life], tone: LIFE_TONE[life] }; return (

  • @@ -277,17 +284,17 @@ function StudyItem({ study, locale, wallTz }: { study: JoinedStudy; locale: Loca className={cx( 'relative flex gap-4 overflow-hidden', linked && 'cursor-pointer transition-colors hover:border-border-strong hover:bg-surface-1', - completed && 'border-warning-400 bg-warning-50 shadow-sm', + finished && 'border-warning-400 bg-warning-50 shadow-sm', )} > - {completed &&