refactor: dip 적용으로 의존성을 느슨한 결합으로 전환 및 디자인 패턴 적용
This commit is contained in:
@@ -102,6 +102,29 @@ POST는 선택적으로 Idempotency-Key 헤더를 받습니다.
|
||||
- 만료 행은 주기적으로 정리하고, 만료된 key는 새 요청에서 다시 사용할 수 있다.
|
||||
- DELETE는 이미 취소된 건을 다시 취소해도 204
|
||||
|
||||
## Architecture
|
||||
|
||||
런타임 경계는 다음 방향으로만 의존합니다.
|
||||
|
||||
Web Controller / DTO / FailureHttpMapper
|
||||
-> Application UseCase / Query
|
||||
-> Domain Policy / ordered RegistrationRule
|
||||
-> Application Port
|
||||
-> Infrastructure JPA Adapter
|
||||
-> Spring Data Repository
|
||||
|
||||
application action은 `RegisterCourseUseCase`, `CancelRegistrationUseCase`, `GetRegistrationsQuery`, `GetLessonsQuery`, `GetLessonQuery`, `CleanupIdempotencyUseCase`로 분리합니다.
|
||||
|
||||
수강신청 정책은 `RegistrationContext`를 입력으로 받고 `RegistrationPolicy`가 R1~R8의 관측 가능한 우선순서를 명시적인 ordered rule list로 유지합니다. Application은 Spring Data JPA repository, `@Lock`, `Page`, projection 구현을 알지 않습니다.
|
||||
|
||||
실패도 의미에 따라 분리합니다.
|
||||
|
||||
- `ApplicationFailure`: resource not found / business rejection / authorization / request validation / retryable infrastructure
|
||||
- `SystemInvariantViolation`: 중복 활성 학기, 필수 시간표 누락 등 사용자 재시도로 해결되지 않는 invariant 위반
|
||||
- HTTP status는 `RegistrationErrorCode`가 아니라 Web의 `FailureHttpMapper`가 결정
|
||||
- business rejection은 ERROR stacktrace를 남기지 않고 metric으로 집계
|
||||
- retryable failure는 WARN, system invariant와 unexpected failure는 ERROR
|
||||
|
||||
## Concurrency invariant
|
||||
|
||||
mutation 경로는 한 곳에서 아래 순서로 lock을 획득합니다.
|
||||
@@ -111,11 +134,13 @@ mutation 경로는 한 곳에서 아래 순서로 lock을 획득합니다.
|
||||
-> R1~R8 검증
|
||||
-> INSERT / cancel
|
||||
|
||||
RegistrationLockManagerTest가 User -> Lesson 호출 순서를 직접 검증하고, ArchitectureTest가 신청 서비스에서 LessonRepository를 직접 우회하지 못하도록 고정합니다.
|
||||
`JpaRegistrationContextLoader`가 User → Lesson 순서로 실제 row lock을 획득합니다. 해당 context loader 테스트가 순서를 직접 검증하고, `ArchitectureTest`는 application/domain/web이 persistence 경계를 우회하지 못하도록 고정합니다.
|
||||
|
||||
## Master data policy
|
||||
|
||||
현재 API에는 Semester/Subject/Professor/Lesson/User를 수정하는 마스터 CRUD가 없습니다. 신청 transaction은 User → Lesson을 락 쿼리로 **처음 읽는 것**을 전제로 하므로, 런타임 마스터 수정 기능을 추가할 때는 같은 transaction 안에서 어떤 값을 최신으로 보장할지 다시 설계해야 합니다.
|
||||
현재 API에는 Semester/Subject/Professor/Lesson/User를 수정하는 마스터 CRUD가 없습니다. 신청 transaction은 User → Lesson을 락 쿼리로 **처음 읽는 것**을 전제로 합니다.
|
||||
|
||||
운영 규칙은 **수강신청 기간 동안 판정에 사용되는 master policy data를 수정하지 않는다**입니다. 대상은 최소한 `Subject.credit`, `Semester.maxCredits`, `Semester.registrationStartAt/registrationEndAt`, `Lesson.capacity/minGrade/allowedRole`, `LessonSchedule`입니다. 향후 관리자 수정 기능을 추가할 때는 이 freeze 규칙과 일관된 snapshot 보장 방식을 함께 재설계해야 합니다.
|
||||
|
||||
ID는 현재 Java에서 `String UUID`, DB에서 `VARCHAR(36)`을 유지합니다. PostgreSQL native `uuid` 전환은 API/JPA 타입과 H2/PostgreSQL migration을 함께 바꾸는 별도 스키마 변경으로 분리합니다.
|
||||
|
||||
@@ -182,7 +207,7 @@ fixture는 support/fixture에 모읍니다.
|
||||
주요 테스트:
|
||||
|
||||
- controller HTTP status/JSON 계약
|
||||
- service 신청/취소/조회
|
||||
- application UseCase/Query 신청·취소·조회
|
||||
- repository 학기 scope/집계/DB unique
|
||||
- domain entity invariant
|
||||
- R1~R8 우선순위/경계값
|
||||
@@ -194,7 +219,7 @@ fixture는 support/fixture에 모읍니다.
|
||||
- 동일 학생 시간표 경쟁
|
||||
- 동일 학생 동일 강의 경쟁
|
||||
- Seeder 재실행
|
||||
- 락 순서 / architecture rule
|
||||
- context loader의 User → Lesson 락 순서 / architecture rule
|
||||
|
||||
./gradlew test
|
||||
./gradlew jacocoTestReport
|
||||
|
||||
+41
-25
@@ -295,14 +295,15 @@ R1은 `registrationEndAt` 정각까지 포함한다. 따라서 `now.isAfter(regi
|
||||
|
||||
### 5.5 구현 메모
|
||||
|
||||
- 락 획득은 `RegistrationLockManager` 한 곳으로 모으고 항상 User → Lesson 순서를 강제한다
|
||||
- JPA Repository의 락 조회는 `@Lock(LockModeType.PESSIMISTIC_WRITE)`를 사용한다
|
||||
- 서비스 mutation 전체에 `@Transactional`을 건다. 락은 커밋 시점에 풀린다
|
||||
- application은 `RegistrationContextLoader` port만 알고, `JpaRegistrationContextLoader`가 실제 User → Lesson 락 순서와 JPA 조회 전략을 구현한다
|
||||
- Spring Data Repository의 `@Lock(LockModeType.PESSIMISTIC_WRITE)`는 infrastructure adapter 뒤에서만 사용한다
|
||||
- `RegisterCourseUseCase`/`CancelRegistrationUseCase` mutation 전체에 `@Transactional`을 건다. 락은 커밋 시점에 풀린다
|
||||
- H2와 PostgreSQL 모두 `FOR UPDATE`를 지원하지만 **락 타임아웃 적용 방식은 같지 않다**
|
||||
- H2 local/test: JDBC URL의 `LOCK_TIMEOUT=3000`
|
||||
- PostgreSQL dev/prod: connection 초기 SQL `SET lock_timeout TO '3s'`
|
||||
- 락 타임아웃은 503 `LOCK_TIMEOUT`으로 변환하고 `Retry-After` 1~3초를 내려 재시도 동시화를 완화한다
|
||||
- 엔티티에는 `@Version`을 둬 예상하지 못한 동시 갱신도 감지한다
|
||||
- 수강신청 기간에는 판정에 쓰는 master policy data(`Subject.credit`, `Semester.maxCredits`, 신청 기간, `Lesson.capacity/minGrade/allowedRole`, `LessonSchedule`)를 수정하지 않는다. 향후 관리자 수정 기능이 생기면 이 전제를 대체할 snapshot/lock 전략을 먼저 정의한다.
|
||||
|
||||
### 5.6 이 설계의 비용
|
||||
|
||||
@@ -366,7 +367,7 @@ Response `201 Created`
|
||||
GET /api/v1/users/{userId}/registrations?semesterId={semesterId}
|
||||
```
|
||||
|
||||
`semesterId` 생략 시 `SemesterResolver`가 현재 시각이 신청 기간 `[registrationStartAt, registrationEndAt]`에 포함되는 학기를 우선 선택한다. 그런 학기가 없으면 오늘이 `[startDate, endDate]`에 포함되는 학기를 fallback으로 쓴다. 같은 기준에 맞는 학기가 2개 이상이면 임의로 하나를 고르지 않고 데이터 오류로 실패시킨다.
|
||||
`semesterId` 생략 시 `SemesterSelectionPolicy`가 현재 시각이 신청 기간 `[registrationStartAt, registrationEndAt]`에 포함되는 학기를 우선 선택한다. 그런 학기가 없으면 오늘이 `[startDate, endDate]`에 포함되는 학기를 fallback으로 쓴다. 같은 기준에 맞는 학기가 2개 이상이면 임의로 하나를 고르지 않고 데이터 오류로 실패시킨다.
|
||||
|
||||
Response `200 OK`
|
||||
|
||||
@@ -543,6 +544,24 @@ User 락은 R5~R7 직렬화와 일관된 판정을 담당하고, DB UNIQUE는 R4
|
||||
|
||||
---
|
||||
|
||||
### 8.3 실패 taxonomy와 HTTP 경계
|
||||
|
||||
`RegistrationErrorCode`는 HTTP status를 알지 않는다. Application/Domain은 실패의 의미만 만들고, Web의 `FailureHttpMapper`가 기존 API status 계약으로 변환한다.
|
||||
|
||||
| 분류 | 예 | 로그/복구 |
|
||||
|---|---|---|
|
||||
| Request validation | 잘못된 body, Idempotency-Key 길이 | 400, ERROR stacktrace 없음 |
|
||||
| Resource not found | 사용자/강의/학기/신청 없음 | 404, 정상 application failure |
|
||||
| Business rejection | 정원/학점/시간표/중복/기간 | 403/409, ERROR stacktrace 없음, metric 집계 |
|
||||
| Authorization failure | 다른 사용자 신청 취소 | 403 |
|
||||
| Retryable infrastructure | DB lock timeout | 503 + Retry-After, WARN |
|
||||
| System invariant violation | 활성 학기 중복, 필수 시간표 누락 | 500, ERROR + invariant metric |
|
||||
| Unexpected failure | 분류되지 않은 예외 | 500, ERROR |
|
||||
|
||||
`SystemInvariantViolation`은 사용자의 입력을 바꿔 해결할 수 있는 실패가 아니다. 신청 가능한 강의에 시간표가 없으면 domain/application은 HTTP 500 표현을 직접 만들지 않고 invariant failure를 발생시키며, Web adapter가 외부 계약상 500으로 변환한다.
|
||||
|
||||
---
|
||||
|
||||
## 9. 시드 데이터 요구사항
|
||||
|
||||
`DataSeeder`는 `local/dev` profile에서만 존재하며 `app.seed.enabled=true`일 때 아래 demo 데이터를 넣는다. `prod`에서는 profile과 설정 양쪽에서 비활성화한다. 10절의 테스트 시나리오가 이 데이터를 전제한다.
|
||||
@@ -619,28 +638,25 @@ User 락은 R5~R7 직렬화와 일관된 판정을 담당하고, DB UNIQUE는 R4
|
||||
|
||||
---
|
||||
|
||||
## 11. 구현 시 건드릴 파일
|
||||
## 11. 구현 구조
|
||||
|
||||
| 파일 | 작업 |
|
||||
|---|---|
|
||||
| `entity/Semester.java` | 신규 |
|
||||
| `entity/LessonSchedule.java` | 신규 |
|
||||
| `entity/Subject.java` | `credit` 추가 |
|
||||
| `entity/Lesson.java` | `semester`/`capacity`/`minGrade`/`allowedRole` 추가, `startTime`/`endTime` 제거 |
|
||||
| `entity/UserLesson.java` | 대리키 PK로 변경, `canceledAt` 추가 |
|
||||
| `entity/UserLessonId.java` | **삭제** |
|
||||
| `entity/BaseCreateEntity.java` | `BaseEntity` 상속하도록 변경 |
|
||||
| `repository/SemesterRepository.java` | 신규 |
|
||||
| `repository/LessonScheduleRepository.java` | 신규 |
|
||||
| `repository/UserRepository.java` | `findByIdForUpdate` (비관적 락) 추가 |
|
||||
| `repository/LessonRepository.java` | `findByIdForUpdate` (비관적 락), 목록 조회 쿼리 추가 |
|
||||
| `repository/UserLessonRepository.java` | ID 타입 `String`으로 변경, 유효 신청 조회 쿼리 추가 |
|
||||
| `service/CourseRegistrationService.java` | 신청/취소/조회 구현 (5.3절 절차) |
|
||||
| `controller/CourseRegistrationController.java` | 엔드포인트 5개 |
|
||||
| `dto/` | `RequestDto`/`ResponseDto` 삭제하고 용도별 DTO로 분리 |
|
||||
| `exception/` | 신규 — 도메인 예외 + `@RestControllerAdvice` |
|
||||
| `enums/` | `RegistrationErrorCode` 신규 |
|
||||
| `seeder/DataSeeder.java` | 9절 demo TSV 조립, 고정 기간 사용, `seed_locks FOR UPDATE`로 다중 Pod 직렬화 |
|
||||
| 영역 | 주요 타입 | 책임 |
|
||||
|---|---|---|
|
||||
| `web/controller` | `CourseRegistrationController`, `LessonController` | HTTP input/output, DTO ↔ application command/result 변환 |
|
||||
| `web/error` | `ApiExceptionHandler`, `FailureHttpMapper`, `FailureMetrics` | failure → HTTP/log/metric 표현 |
|
||||
| `application/registration` | `RegisterCourseUseCase`, `CancelRegistrationUseCase`, `GetRegistrationsQuery` | transaction과 업무 흐름 orchestration |
|
||||
| `application/lesson` | `GetLessonsQuery`, `GetLessonQuery` | 강의 조회 UseCase |
|
||||
| `application/idempotency` | `IdempotencyPolicy`, `CleanupIdempotencyUseCase` | replay/TTL/cleanup 의미 |
|
||||
| `application/*/port` | `RegistrationContextLoader`, `RegistrationReader`, `RegistrationWriter`, `LessonQueryPort`, `SemesterQueryPort`, `IdempotencyPort` | application이 요구하는 persistence capability |
|
||||
| `domain/registration` | `RegistrationContext`, `RegistrationPolicy`, `RegistrationRule` | decision data와 ordered policy |
|
||||
| `domain/registration/rule` | R1~R8 rule | 한 규칙당 한 변경 이유 |
|
||||
| `domain/schedule` | `LessonSchedulePolicy`, `ScheduleConflictChecker` | 시간표 invariant/충돌 |
|
||||
| `infrastructure/persistence` | `Jpa*Adapter`, `JpaRegistrationContextLoader` | Spring Data/JPA query, lock, pagination, projection |
|
||||
| `infrastructure/scheduling` | `IdempotencyRetentionJob` | scheduler adapter |
|
||||
| `failure` | `ApplicationFailure`, `SystemInvariantViolation` | HTTP와 독립된 실패 의미 |
|
||||
| `infrastructure/persistence/repository` | Spring Data repository | JPA adapter가 사용하는 persistence mechanism |
|
||||
|
||||
의존 방향은 `web -> application -> domain/port <- infrastructure`를 유지한다. `ArchitectureTest`가 application의 raw repository/Spring Data JPA 접근, domain의 상위 계층 접근, web의 infrastructure 직접 접근을 금지한다.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
package com.study.course_registration.application.common;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.LocalTime;
|
||||
|
||||
import com.study.course_registration.entity.LessonSchedule;
|
||||
|
||||
public record ScheduleSlot(
|
||||
DayOfWeek dayOfWeek,
|
||||
LocalTime startTime,
|
||||
LocalTime endTime) {
|
||||
|
||||
public static ScheduleSlot from(LessonSchedule schedule) {
|
||||
return new ScheduleSlot(
|
||||
schedule.getDayOfWeek(),
|
||||
schedule.getStartTime(),
|
||||
schedule.getEndTime());
|
||||
}
|
||||
}
|
||||
+24
@@ -0,0 +1,24 @@
|
||||
package com.study.course_registration.application.idempotency;
|
||||
|
||||
import java.time.Clock;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.study.course_registration.application.idempotency.port.IdempotencyPort;
|
||||
|
||||
@Service
|
||||
public class CleanupIdempotencyUseCase {
|
||||
private final Clock clock;
|
||||
private final IdempotencyPort idempotencies;
|
||||
|
||||
public CleanupIdempotencyUseCase(Clock clock, IdempotencyPort idempotencies) {
|
||||
this.clock = clock;
|
||||
this.idempotencies = idempotencies;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void execute() {
|
||||
idempotencies.deleteExpired(clock.instant());
|
||||
}
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
package com.study.course_registration.application.idempotency;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.study.course_registration.application.idempotency.port.IdempotencyPort;
|
||||
import com.study.course_registration.entity.Lesson;
|
||||
import com.study.course_registration.entity.RegistrationIdempotency;
|
||||
import com.study.course_registration.entity.User;
|
||||
import com.study.course_registration.entity.UserLesson;
|
||||
import com.study.course_registration.failure.BusinessRejection;
|
||||
import com.study.course_registration.failure.RequestValidationFailure;
|
||||
|
||||
@Component
|
||||
public class IdempotencyPolicy {
|
||||
private final IdempotencyPort idempotencies;
|
||||
private final long ttlSeconds;
|
||||
|
||||
public IdempotencyPolicy(
|
||||
IdempotencyPort idempotencies,
|
||||
@Value("${app.idempotency.ttl-seconds:86400}") long ttlSeconds) {
|
||||
this.idempotencies = idempotencies;
|
||||
this.ttlSeconds = ttlSeconds;
|
||||
}
|
||||
|
||||
public Decision evaluate(String userId, String lessonId, String rawKey, Instant now) {
|
||||
String key = normalize(rawKey);
|
||||
if (key == null) {
|
||||
return Decision.withoutKey();
|
||||
}
|
||||
|
||||
idempotencies.deleteExpiredKey(userId, key, now);
|
||||
Optional<RegistrationIdempotency> previous = idempotencies.findActive(userId, key, now);
|
||||
if (previous.isEmpty()) {
|
||||
return Decision.newRequest(key);
|
||||
}
|
||||
|
||||
RegistrationIdempotency stored = previous.get();
|
||||
if (!stored.getLesson().getId().equals(lessonId)) {
|
||||
throw BusinessRejection.idempotencyKeyReused();
|
||||
}
|
||||
return Decision.replay(key, stored);
|
||||
}
|
||||
|
||||
public void record(
|
||||
Decision decision,
|
||||
User user,
|
||||
Lesson lesson,
|
||||
UserLesson registration,
|
||||
int totalCredits,
|
||||
Instant now) {
|
||||
if (decision.key() == null || decision.replay().isPresent()) {
|
||||
return;
|
||||
}
|
||||
idempotencies.save(new RegistrationIdempotency(
|
||||
user,
|
||||
lesson,
|
||||
registration,
|
||||
decision.key(),
|
||||
totalCredits,
|
||||
now.plusSeconds(ttlSeconds)));
|
||||
}
|
||||
|
||||
private static String normalize(String value) {
|
||||
if (value == null || value.isBlank()) {
|
||||
return null;
|
||||
}
|
||||
String normalized = value.trim();
|
||||
if (normalized.length() > 100) {
|
||||
throw RequestValidationFailure.idempotencyKeyTooLong();
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
public record Decision(String key, Optional<RegistrationIdempotency> replay) {
|
||||
static Decision withoutKey() {
|
||||
return new Decision(null, Optional.empty());
|
||||
}
|
||||
|
||||
static Decision newRequest(String key) {
|
||||
return new Decision(key, Optional.empty());
|
||||
}
|
||||
|
||||
static Decision replay(String key, RegistrationIdempotency stored) {
|
||||
return new Decision(key, Optional.of(stored));
|
||||
}
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package com.study.course_registration.application.idempotency.port;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
|
||||
import com.study.course_registration.entity.RegistrationIdempotency;
|
||||
|
||||
public interface IdempotencyPort {
|
||||
Optional<RegistrationIdempotency> findActive(String userId, String key, Instant now);
|
||||
|
||||
void deleteExpiredKey(String userId, String key, Instant now);
|
||||
|
||||
void deleteExpired(Instant now);
|
||||
|
||||
RegistrationIdempotency save(RegistrationIdempotency idempotency);
|
||||
}
|
||||
@@ -0,0 +1,51 @@
|
||||
package com.study.course_registration.application.lesson;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.study.course_registration.application.common.ScheduleSlot;
|
||||
import com.study.course_registration.application.lesson.port.LessonQueryPort;
|
||||
import com.study.course_registration.entity.Lesson;
|
||||
import com.study.course_registration.failure.ResourceNotFound;
|
||||
|
||||
@Service
|
||||
@Transactional(readOnly = true)
|
||||
public class GetLessonQuery {
|
||||
private final LessonQueryPort lessons;
|
||||
|
||||
public GetLessonQuery(LessonQueryPort lessons) {
|
||||
this.lessons = lessons;
|
||||
}
|
||||
|
||||
public LessonDetailResult execute(String lessonId) {
|
||||
Lesson lesson = lessons.findDetailed(lessonId)
|
||||
.orElseThrow(ResourceNotFound::lesson);
|
||||
|
||||
List<ScheduleSlot> schedules = lessons.findSchedules(List.of(lessonId)).stream()
|
||||
.map(ScheduleSlot::from)
|
||||
.toList();
|
||||
|
||||
Map<String, Long> counts = lessons.countActiveEnrollments(List.of(lessonId));
|
||||
long enrolledCount = counts.getOrDefault(lessonId, 0L);
|
||||
|
||||
return new LessonDetailResult(
|
||||
lesson.getId(),
|
||||
lesson.getName(),
|
||||
lesson.getSubject().getCode(),
|
||||
lesson.getSubject().getName(),
|
||||
lesson.getSubject().getDescription(),
|
||||
lesson.getSubject().getCredit(),
|
||||
lesson.getProfessor().getName(),
|
||||
lesson.getSemester().getName(),
|
||||
lesson.getCapacity(),
|
||||
enrolledCount,
|
||||
lesson.getMinGrade(),
|
||||
lesson.getAllowedRole(),
|
||||
lesson.getSemester().getRegistrationStartAt(),
|
||||
lesson.getSemester().getRegistrationEndAt(),
|
||||
schedules);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
package com.study.course_registration.application.lesson;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.study.course_registration.application.common.ScheduleSlot;
|
||||
import com.study.course_registration.application.lesson.LessonListResult.LessonItemResult;
|
||||
import com.study.course_registration.application.lesson.port.LessonQueryPort;
|
||||
import com.study.course_registration.application.lesson.port.LessonQueryPort.LessonPage;
|
||||
import com.study.course_registration.application.semester.SemesterSelectionPolicy;
|
||||
import com.study.course_registration.entity.Lesson;
|
||||
import com.study.course_registration.entity.LessonSchedule;
|
||||
import com.study.course_registration.entity.Semester;
|
||||
|
||||
@Service
|
||||
@Transactional(readOnly = true)
|
||||
public class GetLessonsQuery {
|
||||
private final LessonQueryPort lessons;
|
||||
private final SemesterSelectionPolicy semesterSelectionPolicy;
|
||||
|
||||
public GetLessonsQuery(
|
||||
LessonQueryPort lessons,
|
||||
SemesterSelectionPolicy semesterSelectionPolicy) {
|
||||
this.lessons = lessons;
|
||||
this.semesterSelectionPolicy = semesterSelectionPolicy;
|
||||
}
|
||||
|
||||
public LessonListResult execute(String semesterId, String subjectId, int page, int size) {
|
||||
Semester semester = semesterSelectionPolicy.resolve(semesterId);
|
||||
LessonPage lessonPage = lessons.findPage(semester.getId(), subjectId, page, size);
|
||||
List<String> lessonIds = lessonPage.lessons().stream()
|
||||
.map(Lesson::getId)
|
||||
.toList();
|
||||
|
||||
Map<String, List<LessonSchedule>> schedules = groupSchedules(
|
||||
lessonIds.isEmpty() ? List.of() : lessons.findSchedules(lessonIds));
|
||||
Map<String, Long> counts = lessonIds.isEmpty()
|
||||
? Map.of()
|
||||
: lessons.countActiveEnrollments(lessonIds);
|
||||
|
||||
List<LessonItemResult> items = lessonPage.lessons().stream()
|
||||
.map(lesson -> new LessonItemResult(
|
||||
lesson.getId(),
|
||||
lesson.getName(),
|
||||
lesson.getSubject().getCode(),
|
||||
lesson.getSubject().getName(),
|
||||
lesson.getSubject().getCredit(),
|
||||
lesson.getProfessor().getName(),
|
||||
lesson.getCapacity(),
|
||||
counts.getOrDefault(lesson.getId(), 0L),
|
||||
lesson.getMinGrade(),
|
||||
lesson.getAllowedRole(),
|
||||
schedules.getOrDefault(lesson.getId(), List.of()).stream()
|
||||
.map(ScheduleSlot::from)
|
||||
.toList()))
|
||||
.toList();
|
||||
|
||||
return new LessonListResult(
|
||||
page,
|
||||
size,
|
||||
lessonPage.totalElements(),
|
||||
items);
|
||||
}
|
||||
|
||||
private static Map<String, List<LessonSchedule>> groupSchedules(List<LessonSchedule> schedules) {
|
||||
return schedules.stream().collect(Collectors.groupingBy(
|
||||
schedule -> schedule.getLesson().getId(),
|
||||
LinkedHashMap::new,
|
||||
Collectors.toList()));
|
||||
}
|
||||
}
|
||||
+4
-4
@@ -1,12 +1,12 @@
|
||||
package com.study.course_registration.dto.lesson;
|
||||
package com.study.course_registration.application.lesson;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
import com.study.course_registration.dto.ScheduleResponse;
|
||||
import com.study.course_registration.application.common.ScheduleSlot;
|
||||
import com.study.course_registration.enums.UserRole;
|
||||
|
||||
public record LessonDetailResponse(
|
||||
public record LessonDetailResult(
|
||||
String lessonId,
|
||||
String lessonName,
|
||||
String subjectCode,
|
||||
@@ -21,5 +21,5 @@ public record LessonDetailResponse(
|
||||
UserRole allowedRole,
|
||||
Instant registrationStartAt,
|
||||
Instant registrationEndAt,
|
||||
List<ScheduleResponse> schedules) {
|
||||
List<ScheduleSlot> schedules) {
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package com.study.course_registration.application.lesson;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.study.course_registration.application.common.ScheduleSlot;
|
||||
import com.study.course_registration.enums.UserRole;
|
||||
|
||||
public record LessonListResult(
|
||||
Integer page,
|
||||
Integer size,
|
||||
Long totalElements,
|
||||
List<LessonItemResult> lessons) {
|
||||
|
||||
public record LessonItemResult(
|
||||
String lessonId,
|
||||
String lessonName,
|
||||
String subjectCode,
|
||||
String subjectName,
|
||||
Integer credit,
|
||||
String professorName,
|
||||
Integer capacity,
|
||||
Long enrolledCount,
|
||||
Long minGrade,
|
||||
UserRole allowedRole,
|
||||
List<ScheduleSlot> schedules) {
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.study.course_registration.application.lesson.port;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
|
||||
import com.study.course_registration.entity.Lesson;
|
||||
import com.study.course_registration.entity.LessonSchedule;
|
||||
|
||||
public interface LessonQueryPort {
|
||||
LessonPage findPage(String semesterId, String subjectId, int page, int size);
|
||||
|
||||
Optional<Lesson> findDetailed(String lessonId);
|
||||
|
||||
List<LessonSchedule> findSchedules(Collection<String> lessonIds);
|
||||
|
||||
Map<String, Long> countActiveEnrollments(Collection<String> lessonIds);
|
||||
|
||||
record LessonPage(List<Lesson> lessons, long totalElements) {
|
||||
}
|
||||
}
|
||||
+60
@@ -0,0 +1,60 @@
|
||||
package com.study.course_registration.application.registration;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.study.course_registration.application.registration.port.RegistrationContextLoader;
|
||||
import com.study.course_registration.application.registration.port.RegistrationContextLoader.LockedRegistration;
|
||||
import com.study.course_registration.application.registration.port.RegistrationReader;
|
||||
import com.study.course_registration.application.registration.port.RegistrationWriter;
|
||||
import com.study.course_registration.application.registration.port.RegistrationReader.RegistrationTarget;
|
||||
import com.study.course_registration.domain.registration.rule.RegistrationPeriodRule;
|
||||
import com.study.course_registration.entity.UserLesson;
|
||||
import com.study.course_registration.failure.AuthorizationFailure;
|
||||
import com.study.course_registration.failure.ResourceNotFound;
|
||||
|
||||
@Service
|
||||
public class CancelRegistrationUseCase {
|
||||
private final Clock clock;
|
||||
private final RegistrationReader registrations;
|
||||
private final RegistrationWriter registrationWriter;
|
||||
private final RegistrationContextLoader contextLoader;
|
||||
private final RegistrationPeriodRule periodRule;
|
||||
|
||||
public CancelRegistrationUseCase(
|
||||
Clock clock,
|
||||
RegistrationReader registrations,
|
||||
RegistrationWriter registrationWriter,
|
||||
RegistrationContextLoader contextLoader,
|
||||
RegistrationPeriodRule periodRule) {
|
||||
this.clock = clock;
|
||||
this.registrations = registrations;
|
||||
this.registrationWriter = registrationWriter;
|
||||
this.contextLoader = contextLoader;
|
||||
this.periodRule = periodRule;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void execute(String userId, String registrationId) {
|
||||
RegistrationTarget target = registrations.findTarget(registrationId)
|
||||
.orElseThrow(ResourceNotFound::registration);
|
||||
if (!target.userId().equals(userId)) {
|
||||
throw AuthorizationFailure.registrationForbidden();
|
||||
}
|
||||
|
||||
LockedRegistration locked = contextLoader.lockForUpdate(userId, target.lessonId());
|
||||
UserLesson registration = registrations.findRegistration(registrationId)
|
||||
.orElseThrow(ResourceNotFound::registration);
|
||||
if (registration.isCanceled()) {
|
||||
return;
|
||||
}
|
||||
|
||||
Instant now = clock.instant();
|
||||
periodRule.validate(locked.lesson(), now);
|
||||
registration.cancel(now);
|
||||
registrationWriter.save(registration);
|
||||
}
|
||||
}
|
||||
+94
@@ -0,0 +1,94 @@
|
||||
package com.study.course_registration.application.registration;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.study.course_registration.application.common.ScheduleSlot;
|
||||
import com.study.course_registration.application.registration.RegistrationListResult.RegistrationItemResult;
|
||||
import com.study.course_registration.application.registration.port.RegistrationReader;
|
||||
import com.study.course_registration.application.semester.SemesterSelectionPolicy;
|
||||
import com.study.course_registration.entity.Lesson;
|
||||
import com.study.course_registration.entity.LessonSchedule;
|
||||
import com.study.course_registration.entity.Semester;
|
||||
import com.study.course_registration.entity.UserLesson;
|
||||
import com.study.course_registration.failure.ResourceNotFound;
|
||||
|
||||
@Service
|
||||
@Transactional(readOnly = true)
|
||||
public class GetRegistrationsQuery {
|
||||
private final RegistrationReader registrations;
|
||||
private final SemesterSelectionPolicy semesterSelectionPolicy;
|
||||
|
||||
public GetRegistrationsQuery(
|
||||
RegistrationReader registrations,
|
||||
SemesterSelectionPolicy semesterSelectionPolicy) {
|
||||
this.registrations = registrations;
|
||||
this.semesterSelectionPolicy = semesterSelectionPolicy;
|
||||
}
|
||||
|
||||
public RegistrationListResult execute(String userId, String semesterId) {
|
||||
if (!registrations.userExists(userId)) {
|
||||
throw ResourceNotFound.user();
|
||||
}
|
||||
|
||||
Semester semester = semesterSelectionPolicy.resolve(semesterId);
|
||||
List<UserLesson> active = registrations.findActive(userId, semester.getId());
|
||||
Set<String> lessonIds = active.stream()
|
||||
.map(UserLesson::getLesson)
|
||||
.map(Lesson::getId)
|
||||
.collect(Collectors.toCollection(LinkedHashSet::new));
|
||||
|
||||
Map<String, List<LessonSchedule>> schedules = groupSchedules(
|
||||
lessonIds.isEmpty() ? List.of() : registrations.findSchedules(lessonIds));
|
||||
|
||||
List<RegistrationItemResult> items = active.stream()
|
||||
.map(registration -> toItem(registration, schedules))
|
||||
.toList();
|
||||
|
||||
int totalCredits = active.stream()
|
||||
.map(UserLesson::getLesson)
|
||||
.map(Lesson::getSubject)
|
||||
.mapToInt(subject -> subject.getCredit())
|
||||
.sum();
|
||||
|
||||
return new RegistrationListResult(
|
||||
userId,
|
||||
semester.getId(),
|
||||
semester.getName(),
|
||||
totalCredits,
|
||||
semester.getMaxCredits(),
|
||||
items);
|
||||
}
|
||||
|
||||
private static RegistrationItemResult toItem(
|
||||
UserLesson registration,
|
||||
Map<String, List<LessonSchedule>> schedules) {
|
||||
Lesson lesson = registration.getLesson();
|
||||
return new RegistrationItemResult(
|
||||
registration.getId(),
|
||||
lesson.getId(),
|
||||
lesson.getName(),
|
||||
lesson.getSubject().getCode(),
|
||||
lesson.getSubject().getName(),
|
||||
lesson.getSubject().getCredit(),
|
||||
lesson.getProfessor().getName(),
|
||||
schedules.getOrDefault(lesson.getId(), List.of()).stream()
|
||||
.map(ScheduleSlot::from)
|
||||
.toList(),
|
||||
registration.getCreatedAt());
|
||||
}
|
||||
|
||||
private static Map<String, List<LessonSchedule>> groupSchedules(List<LessonSchedule> schedules) {
|
||||
return schedules.stream().collect(Collectors.groupingBy(
|
||||
schedule -> schedule.getLesson().getId(),
|
||||
LinkedHashMap::new,
|
||||
Collectors.toList()));
|
||||
}
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.study.course_registration.application.registration;
|
||||
|
||||
public record RegisterCourseCommand(
|
||||
String userId,
|
||||
String lessonId,
|
||||
String idempotencyKey) {
|
||||
}
|
||||
+90
@@ -0,0 +1,90 @@
|
||||
package com.study.course_registration.application.registration;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.study.course_registration.application.idempotency.IdempotencyPolicy;
|
||||
import com.study.course_registration.application.idempotency.IdempotencyPolicy.Decision;
|
||||
import com.study.course_registration.application.registration.port.RegistrationContextLoader;
|
||||
import com.study.course_registration.application.registration.port.RegistrationWriter;
|
||||
import com.study.course_registration.domain.registration.RegistrationContext;
|
||||
import com.study.course_registration.domain.registration.RegistrationPolicy;
|
||||
import com.study.course_registration.domain.registration.rule.RegistrationPeriodRule;
|
||||
import com.study.course_registration.entity.RegistrationIdempotency;
|
||||
import com.study.course_registration.entity.UserLesson;
|
||||
|
||||
@Service
|
||||
public class RegisterCourseUseCase {
|
||||
private final Clock clock;
|
||||
private final RegistrationContextLoader contextLoader;
|
||||
private final RegistrationWriter registrations;
|
||||
private final RegistrationPolicy registrationPolicy;
|
||||
private final RegistrationPeriodRule periodRule;
|
||||
private final IdempotencyPolicy idempotencyPolicy;
|
||||
private final RegistrationResultAssembler resultAssembler;
|
||||
|
||||
public RegisterCourseUseCase(
|
||||
Clock clock,
|
||||
RegistrationContextLoader contextLoader,
|
||||
RegistrationWriter registrations,
|
||||
RegistrationPolicy registrationPolicy,
|
||||
RegistrationPeriodRule periodRule,
|
||||
IdempotencyPolicy idempotencyPolicy,
|
||||
RegistrationResultAssembler resultAssembler) {
|
||||
this.clock = clock;
|
||||
this.contextLoader = contextLoader;
|
||||
this.registrations = registrations;
|
||||
this.registrationPolicy = registrationPolicy;
|
||||
this.periodRule = periodRule;
|
||||
this.idempotencyPolicy = idempotencyPolicy;
|
||||
this.resultAssembler = resultAssembler;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public RegistrationResult execute(RegisterCourseCommand command) {
|
||||
Instant requestTime = clock.instant();
|
||||
RegistrationContext context = contextLoader.loadForRegistration(
|
||||
command.userId(),
|
||||
command.lessonId(),
|
||||
requestTime);
|
||||
|
||||
Decision decision = idempotencyPolicy.evaluate(
|
||||
command.userId(),
|
||||
command.lessonId(),
|
||||
command.idempotencyKey(),
|
||||
requestTime);
|
||||
|
||||
if (decision.replay().isPresent()) {
|
||||
RegistrationIdempotency stored = decision.replay().orElseThrow();
|
||||
return resultAssembler.assemble(
|
||||
stored.getRegistration(),
|
||||
stored.getUser(),
|
||||
stored.getLesson(),
|
||||
stored.getTotalCredits());
|
||||
}
|
||||
|
||||
registrationPolicy.validate(context);
|
||||
periodRule.validate(context.lesson(), clock.instant());
|
||||
|
||||
int totalCredits = context.totalCreditsAfter();
|
||||
UserLesson registration = registrations.save(
|
||||
new UserLesson(context.user(), context.lesson()));
|
||||
|
||||
idempotencyPolicy.record(
|
||||
decision,
|
||||
context.user(),
|
||||
context.lesson(),
|
||||
registration,
|
||||
totalCredits,
|
||||
requestTime);
|
||||
|
||||
return resultAssembler.assemble(
|
||||
registration,
|
||||
context.user(),
|
||||
context.lesson(),
|
||||
totalCredits);
|
||||
}
|
||||
}
|
||||
+27
@@ -0,0 +1,27 @@
|
||||
package com.study.course_registration.application.registration;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
import com.study.course_registration.application.common.ScheduleSlot;
|
||||
|
||||
public record RegistrationListResult(
|
||||
String userId,
|
||||
String semesterId,
|
||||
String semesterName,
|
||||
Integer totalCredits,
|
||||
Integer maxCredits,
|
||||
List<RegistrationItemResult> registrations) {
|
||||
|
||||
public record RegistrationItemResult(
|
||||
String registrationId,
|
||||
String lessonId,
|
||||
String lessonName,
|
||||
String subjectCode,
|
||||
String subjectName,
|
||||
Integer credit,
|
||||
String professorName,
|
||||
List<ScheduleSlot> schedules,
|
||||
Instant registeredAt) {
|
||||
}
|
||||
}
|
||||
+2
-2
@@ -1,8 +1,8 @@
|
||||
package com.study.course_registration.dto.registration;
|
||||
package com.study.course_registration.application.registration;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
public record CourseRegistrationResponse(
|
||||
public record RegistrationResult(
|
||||
String registrationId,
|
||||
String userId,
|
||||
String lessonId,
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.study.course_registration.application.registration;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.study.course_registration.entity.Lesson;
|
||||
import com.study.course_registration.entity.User;
|
||||
import com.study.course_registration.entity.UserLesson;
|
||||
|
||||
@Component
|
||||
public class RegistrationResultAssembler {
|
||||
public RegistrationResult assemble(
|
||||
UserLesson registration,
|
||||
User user,
|
||||
Lesson lesson,
|
||||
int totalCredits) {
|
||||
return new RegistrationResult(
|
||||
registration.getId(),
|
||||
user.getId(),
|
||||
lesson.getId(),
|
||||
lesson.getName(),
|
||||
lesson.getSubject().getCode(),
|
||||
lesson.getSubject().getCredit(),
|
||||
registration.getCreatedAt(),
|
||||
totalCredits);
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package com.study.course_registration.application.registration.port;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
import com.study.course_registration.domain.registration.RegistrationContext;
|
||||
import com.study.course_registration.entity.Lesson;
|
||||
import com.study.course_registration.entity.User;
|
||||
|
||||
public interface RegistrationContextLoader {
|
||||
RegistrationContext loadForRegistration(String userId, String lessonId, Instant now);
|
||||
|
||||
LockedRegistration lockForUpdate(String userId, String lessonId);
|
||||
|
||||
record LockedRegistration(User user, Lesson lesson) {
|
||||
}
|
||||
}
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
package com.study.course_registration.application.registration.port;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import com.study.course_registration.entity.LessonSchedule;
|
||||
import com.study.course_registration.entity.UserLesson;
|
||||
|
||||
public interface RegistrationReader {
|
||||
boolean userExists(String userId);
|
||||
|
||||
Optional<RegistrationTarget> findTarget(String registrationId);
|
||||
|
||||
Optional<UserLesson> findRegistration(String registrationId);
|
||||
|
||||
List<UserLesson> findActive(String userId, String semesterId);
|
||||
|
||||
List<LessonSchedule> findSchedules(Collection<String> lessonIds);
|
||||
|
||||
record RegistrationTarget(String userId, String lessonId) {
|
||||
}
|
||||
}
|
||||
+7
@@ -0,0 +1,7 @@
|
||||
package com.study.course_registration.application.registration.port;
|
||||
|
||||
import com.study.course_registration.entity.UserLesson;
|
||||
|
||||
public interface RegistrationWriter {
|
||||
UserLesson save(UserLesson registration);
|
||||
}
|
||||
+49
@@ -0,0 +1,49 @@
|
||||
package com.study.course_registration.application.semester;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.study.course_registration.application.semester.port.SemesterQueryPort;
|
||||
import com.study.course_registration.entity.Semester;
|
||||
import com.study.course_registration.failure.ResourceNotFound;
|
||||
import com.study.course_registration.failure.SystemInvariantViolation;
|
||||
|
||||
@Component
|
||||
public class SemesterSelectionPolicy {
|
||||
private final Clock clock;
|
||||
private final SemesterQueryPort semesters;
|
||||
|
||||
public SemesterSelectionPolicy(Clock clock, SemesterQueryPort semesters) {
|
||||
this.clock = clock;
|
||||
this.semesters = semesters;
|
||||
}
|
||||
|
||||
public Semester resolve(String semesterId) {
|
||||
if (semesterId != null && !semesterId.isBlank()) {
|
||||
return semesters.findById(semesterId).orElseThrow(ResourceNotFound::semester);
|
||||
}
|
||||
|
||||
Instant now = clock.instant();
|
||||
List<Semester> registrationSemesters = semesters.findRegistrationSemesters(now);
|
||||
if (registrationSemesters.size() > 1) {
|
||||
throw SystemInvariantViolation.multipleRegistrationSemesters();
|
||||
}
|
||||
if (registrationSemesters.size() == 1) {
|
||||
return registrationSemesters.getFirst();
|
||||
}
|
||||
|
||||
LocalDate today = LocalDate.now(clock);
|
||||
List<Semester> academicSemesters = semesters.findAcademicSemesters(today);
|
||||
if (academicSemesters.size() > 1) {
|
||||
throw SystemInvariantViolation.multipleAcademicSemesters();
|
||||
}
|
||||
if (academicSemesters.size() == 1) {
|
||||
return academicSemesters.getFirst();
|
||||
}
|
||||
throw ResourceNotFound.currentSemester();
|
||||
}
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
package com.study.course_registration.application.semester.port;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import com.study.course_registration.entity.Semester;
|
||||
|
||||
public interface SemesterQueryPort {
|
||||
Optional<Semester> findById(String semesterId);
|
||||
|
||||
List<Semester> findRegistrationSemesters(Instant now);
|
||||
|
||||
List<Semester> findAcademicSemesters(LocalDate today);
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.study.course_registration.domain.registration;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import com.study.course_registration.entity.Lesson;
|
||||
import com.study.course_registration.entity.LessonSchedule;
|
||||
import com.study.course_registration.entity.User;
|
||||
import com.study.course_registration.entity.UserLesson;
|
||||
|
||||
public record RegistrationContext(
|
||||
User user,
|
||||
Lesson lesson,
|
||||
List<UserLesson> activeRegistrations,
|
||||
Map<String, List<LessonSchedule>> schedulesByLessonId,
|
||||
long enrolledCount,
|
||||
Instant now) {
|
||||
|
||||
public List<LessonSchedule> candidateSchedules() {
|
||||
return schedulesByLessonId.getOrDefault(lesson.getId(), List.of());
|
||||
}
|
||||
|
||||
public List<LessonSchedule> schedulesOf(UserLesson registration) {
|
||||
return schedulesByLessonId.getOrDefault(registration.getLesson().getId(), List.of());
|
||||
}
|
||||
|
||||
public int currentCredits() {
|
||||
return activeRegistrations.stream()
|
||||
.map(UserLesson::getLesson)
|
||||
.map(Lesson::getSubject)
|
||||
.mapToInt(subject -> subject.getCredit())
|
||||
.sum();
|
||||
}
|
||||
|
||||
public int totalCreditsAfter() {
|
||||
return currentCredits() + lesson.getSubject().getCredit();
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
package com.study.course_registration.domain.registration;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.study.course_registration.domain.registration.rule.AlreadyRegisteredRule;
|
||||
import com.study.course_registration.domain.registration.rule.CapacityRule;
|
||||
import com.study.course_registration.domain.registration.rule.CreditLimitRule;
|
||||
import com.study.course_registration.domain.registration.rule.DuplicateSubjectRule;
|
||||
import com.study.course_registration.domain.registration.rule.GradeEligibilityRule;
|
||||
import com.study.course_registration.domain.registration.rule.RegistrationPeriodRule;
|
||||
import com.study.course_registration.domain.registration.rule.RoleEligibilityRule;
|
||||
import com.study.course_registration.domain.registration.rule.ScheduleAvailabilityRule;
|
||||
import com.study.course_registration.domain.registration.rule.ScheduleConflictRule;
|
||||
|
||||
@Component
|
||||
public class RegistrationPolicy {
|
||||
private final List<RegistrationRule> orderedRules;
|
||||
|
||||
public RegistrationPolicy(
|
||||
RegistrationPeriodRule registrationPeriodRule,
|
||||
GradeEligibilityRule gradeEligibilityRule,
|
||||
RoleEligibilityRule roleEligibilityRule,
|
||||
AlreadyRegisteredRule alreadyRegisteredRule,
|
||||
DuplicateSubjectRule duplicateSubjectRule,
|
||||
ScheduleAvailabilityRule scheduleAvailabilityRule,
|
||||
ScheduleConflictRule scheduleConflictRule,
|
||||
CreditLimitRule creditLimitRule,
|
||||
CapacityRule capacityRule) {
|
||||
this.orderedRules = List.of(
|
||||
registrationPeriodRule,
|
||||
gradeEligibilityRule,
|
||||
roleEligibilityRule,
|
||||
alreadyRegisteredRule,
|
||||
duplicateSubjectRule,
|
||||
scheduleAvailabilityRule,
|
||||
scheduleConflictRule,
|
||||
creditLimitRule,
|
||||
capacityRule);
|
||||
}
|
||||
|
||||
public void validate(RegistrationContext context) {
|
||||
orderedRules.forEach(rule -> rule.validate(context));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
package com.study.course_registration.domain.registration;
|
||||
|
||||
public interface RegistrationRule {
|
||||
void validate(RegistrationContext context);
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.study.course_registration.domain.registration.rule;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.study.course_registration.domain.registration.RegistrationContext;
|
||||
import com.study.course_registration.domain.registration.RegistrationRule;
|
||||
import com.study.course_registration.failure.BusinessRejection;
|
||||
|
||||
@Component
|
||||
public class AlreadyRegisteredRule implements RegistrationRule {
|
||||
@Override
|
||||
public void validate(RegistrationContext context) {
|
||||
boolean duplicate = context.activeRegistrations().stream()
|
||||
.anyMatch(registration -> registration.getLesson().getId().equals(context.lesson().getId()));
|
||||
if (duplicate) {
|
||||
throw BusinessRejection.alreadyRegistered();
|
||||
}
|
||||
}
|
||||
}
|
||||
+19
@@ -0,0 +1,19 @@
|
||||
package com.study.course_registration.domain.registration.rule;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.study.course_registration.domain.registration.RegistrationContext;
|
||||
import com.study.course_registration.domain.registration.RegistrationRule;
|
||||
import com.study.course_registration.failure.BusinessRejection;
|
||||
|
||||
@Component
|
||||
public class CapacityRule implements RegistrationRule {
|
||||
@Override
|
||||
public void validate(RegistrationContext context) {
|
||||
if (context.enrolledCount() >= context.lesson().getCapacity()) {
|
||||
throw BusinessRejection.capacityExceeded(
|
||||
context.enrolledCount(),
|
||||
context.lesson().getCapacity());
|
||||
}
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.study.course_registration.domain.registration.rule;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.study.course_registration.domain.registration.RegistrationContext;
|
||||
import com.study.course_registration.domain.registration.RegistrationRule;
|
||||
import com.study.course_registration.failure.BusinessRejection;
|
||||
|
||||
@Component
|
||||
public class CreditLimitRule implements RegistrationRule {
|
||||
@Override
|
||||
public void validate(RegistrationContext context) {
|
||||
int current = context.currentCredits();
|
||||
int requested = context.lesson().getSubject().getCredit();
|
||||
int max = context.lesson().getSemester().getMaxCredits();
|
||||
if (current + requested > max) {
|
||||
throw BusinessRejection.creditLimitExceeded(current, requested, max);
|
||||
}
|
||||
}
|
||||
}
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.study.course_registration.domain.registration.rule;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.study.course_registration.domain.registration.RegistrationContext;
|
||||
import com.study.course_registration.domain.registration.RegistrationRule;
|
||||
import com.study.course_registration.failure.BusinessRejection;
|
||||
|
||||
@Component
|
||||
public class DuplicateSubjectRule implements RegistrationRule {
|
||||
@Override
|
||||
public void validate(RegistrationContext context) {
|
||||
boolean duplicate = context.activeRegistrations().stream()
|
||||
.anyMatch(registration -> registration.getLesson().getSubject().getId()
|
||||
.equals(context.lesson().getSubject().getId()));
|
||||
if (duplicate) {
|
||||
throw BusinessRejection.duplicateSubject();
|
||||
}
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.study.course_registration.domain.registration.rule;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.study.course_registration.domain.registration.RegistrationContext;
|
||||
import com.study.course_registration.domain.registration.RegistrationRule;
|
||||
import com.study.course_registration.failure.BusinessRejection;
|
||||
|
||||
@Component
|
||||
public class GradeEligibilityRule implements RegistrationRule {
|
||||
@Override
|
||||
public void validate(RegistrationContext context) {
|
||||
Long minGrade = context.lesson().getMinGrade();
|
||||
if (minGrade != null && context.user().getGrade() < minGrade) {
|
||||
throw BusinessRejection.notEligibleGrade(context.user().getGrade(), minGrade);
|
||||
}
|
||||
}
|
||||
}
|
||||
+25
@@ -0,0 +1,25 @@
|
||||
package com.study.course_registration.domain.registration.rule;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.study.course_registration.domain.registration.RegistrationContext;
|
||||
import com.study.course_registration.domain.registration.RegistrationRule;
|
||||
import com.study.course_registration.entity.Lesson;
|
||||
import com.study.course_registration.failure.BusinessRejection;
|
||||
|
||||
@Component
|
||||
public class RegistrationPeriodRule implements RegistrationRule {
|
||||
@Override
|
||||
public void validate(RegistrationContext context) {
|
||||
validate(context.lesson(), context.now());
|
||||
}
|
||||
|
||||
public void validate(Lesson lesson, Instant now) {
|
||||
if (now.isBefore(lesson.getSemester().getRegistrationStartAt())
|
||||
|| now.isAfter(lesson.getSemester().getRegistrationEndAt())) {
|
||||
throw BusinessRejection.registrationPeriodClosed();
|
||||
}
|
||||
}
|
||||
}
|
||||
+18
@@ -0,0 +1,18 @@
|
||||
package com.study.course_registration.domain.registration.rule;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.study.course_registration.domain.registration.RegistrationContext;
|
||||
import com.study.course_registration.domain.registration.RegistrationRule;
|
||||
import com.study.course_registration.failure.BusinessRejection;
|
||||
|
||||
@Component
|
||||
public class RoleEligibilityRule implements RegistrationRule {
|
||||
@Override
|
||||
public void validate(RegistrationContext context) {
|
||||
if (context.lesson().getAllowedRole() != null
|
||||
&& context.user().getRole() != context.lesson().getAllowedRole()) {
|
||||
throw BusinessRejection.notEligibleRole(context.lesson().getAllowedRole());
|
||||
}
|
||||
}
|
||||
}
|
||||
+22
@@ -0,0 +1,22 @@
|
||||
package com.study.course_registration.domain.registration.rule;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.study.course_registration.domain.registration.RegistrationContext;
|
||||
import com.study.course_registration.domain.registration.RegistrationRule;
|
||||
import com.study.course_registration.failure.SystemInvariantViolation;
|
||||
|
||||
@Component
|
||||
public class ScheduleAvailabilityRule implements RegistrationRule {
|
||||
@Override
|
||||
public void validate(RegistrationContext context) {
|
||||
if (context.candidateSchedules().isEmpty()) {
|
||||
throw SystemInvariantViolation.missingCandidateSchedule();
|
||||
}
|
||||
context.activeRegistrations().forEach(registration -> {
|
||||
if (context.schedulesOf(registration).isEmpty()) {
|
||||
throw SystemInvariantViolation.missingExistingSchedule();
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
package com.study.course_registration.domain.registration.rule;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.study.course_registration.domain.registration.RegistrationContext;
|
||||
import com.study.course_registration.domain.registration.RegistrationRule;
|
||||
import com.study.course_registration.entity.LessonSchedule;
|
||||
import com.study.course_registration.entity.UserLesson;
|
||||
import com.study.course_registration.failure.BusinessRejection;
|
||||
import com.study.course_registration.domain.schedule.ScheduleConflictChecker;
|
||||
|
||||
@Component
|
||||
public class ScheduleConflictRule implements RegistrationRule {
|
||||
private final ScheduleConflictChecker conflictChecker;
|
||||
|
||||
public ScheduleConflictRule(ScheduleConflictChecker conflictChecker) {
|
||||
this.conflictChecker = conflictChecker;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void validate(RegistrationContext context) {
|
||||
for (UserLesson registration : context.activeRegistrations()) {
|
||||
for (LessonSchedule candidate : context.candidateSchedules()) {
|
||||
for (LessonSchedule existing : context.schedulesOf(registration)) {
|
||||
if (conflictChecker.overlaps(candidate, existing)) {
|
||||
throw BusinessRejection.scheduleConflict(
|
||||
candidate.getDayOfWeek(),
|
||||
candidate.getStartTime(),
|
||||
candidate.getEndTime());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+4
-2
@@ -1,4 +1,4 @@
|
||||
package com.study.course_registration.service.policy;
|
||||
package com.study.course_registration.domain.schedule;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -8,6 +8,8 @@ import org.springframework.stereotype.Component;
|
||||
|
||||
import com.study.course_registration.entity.Lesson;
|
||||
import com.study.course_registration.entity.LessonSchedule;
|
||||
import com.study.course_registration.failure.SystemInvariantViolation;
|
||||
import com.study.course_registration.domain.schedule.ScheduleConflictChecker;
|
||||
|
||||
@Component
|
||||
public class LessonSchedulePolicy {
|
||||
@@ -25,7 +27,7 @@ public class LessonSchedulePolicy {
|
||||
for (int left = 0; left < lessonSchedules.size(); left++) {
|
||||
for (int right = left + 1; right < lessonSchedules.size(); right++) {
|
||||
if (conflictChecker.overlaps(lessonSchedules.get(left), lessonSchedules.get(right))) {
|
||||
throw new IllegalArgumentException("같은 강의의 시간표가 겹칩니다.");
|
||||
throw SystemInvariantViolation.overlappingLessonSchedule();
|
||||
}
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.study.course_registration.service.policy;
|
||||
package com.study.course_registration.domain.schedule;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
@@ -1,15 +0,0 @@
|
||||
package com.study.course_registration.dto;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.LocalTime;
|
||||
|
||||
import com.study.course_registration.entity.LessonSchedule;
|
||||
|
||||
public record ScheduleResponse(
|
||||
DayOfWeek dayOfWeek,
|
||||
LocalTime startTime,
|
||||
LocalTime endTime) {
|
||||
public static ScheduleResponse from(LessonSchedule schedule) {
|
||||
return new ScheduleResponse(schedule.getDayOfWeek(), schedule.getStartTime(), schedule.getEndTime());
|
||||
}
|
||||
}
|
||||
@@ -1,20 +0,0 @@
|
||||
package com.study.course_registration.dto.lesson;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.study.course_registration.dto.ScheduleResponse;
|
||||
import com.study.course_registration.enums.UserRole;
|
||||
|
||||
public record LessonItemResponse(
|
||||
String lessonId,
|
||||
String lessonName,
|
||||
String subjectCode,
|
||||
String subjectName,
|
||||
Integer credit,
|
||||
String professorName,
|
||||
Integer capacity,
|
||||
Long enrolledCount,
|
||||
Long minGrade,
|
||||
UserRole allowedRole,
|
||||
List<ScheduleResponse> schedules) {
|
||||
}
|
||||
@@ -1,10 +0,0 @@
|
||||
package com.study.course_registration.dto.lesson;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record LessonListResponse(
|
||||
Integer page,
|
||||
Integer size,
|
||||
Long totalElements,
|
||||
List<LessonItemResponse> lessons) {
|
||||
}
|
||||
-18
@@ -1,18 +0,0 @@
|
||||
package com.study.course_registration.dto.registration;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
import com.study.course_registration.dto.ScheduleResponse;
|
||||
|
||||
public record RegistrationItemResponse(
|
||||
String registrationId,
|
||||
String lessonId,
|
||||
String lessonName,
|
||||
String subjectCode,
|
||||
String subjectName,
|
||||
Integer credit,
|
||||
String professorName,
|
||||
List<ScheduleResponse> schedules,
|
||||
Instant registeredAt) {
|
||||
}
|
||||
-12
@@ -1,12 +0,0 @@
|
||||
package com.study.course_registration.dto.registration;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
public record RegistrationListResponse(
|
||||
String userId,
|
||||
String semesterId,
|
||||
String semesterName,
|
||||
Integer totalCredits,
|
||||
Integer maxCredits,
|
||||
List<RegistrationItemResponse> registrations) {
|
||||
}
|
||||
@@ -1,33 +1,21 @@
|
||||
package com.study.course_registration.enums;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
|
||||
public enum RegistrationErrorCode {
|
||||
VALIDATION_ERROR(HttpStatus.BAD_REQUEST),
|
||||
USER_NOT_FOUND(HttpStatus.NOT_FOUND),
|
||||
LESSON_NOT_FOUND(HttpStatus.NOT_FOUND),
|
||||
SEMESTER_NOT_FOUND(HttpStatus.NOT_FOUND),
|
||||
REGISTRATION_NOT_FOUND(HttpStatus.NOT_FOUND),
|
||||
NOT_ELIGIBLE_GRADE(HttpStatus.FORBIDDEN),
|
||||
NOT_ELIGIBLE_ROLE(HttpStatus.FORBIDDEN),
|
||||
REGISTRATION_FORBIDDEN(HttpStatus.FORBIDDEN),
|
||||
REGISTRATION_PERIOD_CLOSED(HttpStatus.CONFLICT),
|
||||
ALREADY_REGISTERED(HttpStatus.CONFLICT),
|
||||
DUPLICATE_SUBJECT(HttpStatus.CONFLICT),
|
||||
SCHEDULE_CONFLICT(HttpStatus.CONFLICT),
|
||||
CREDIT_LIMIT_EXCEEDED(HttpStatus.CONFLICT),
|
||||
CAPACITY_EXCEEDED(HttpStatus.CONFLICT),
|
||||
IDEMPOTENCY_KEY_REUSED(HttpStatus.CONFLICT),
|
||||
LOCK_TIMEOUT(HttpStatus.SERVICE_UNAVAILABLE),
|
||||
INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
|
||||
private final HttpStatus status;
|
||||
|
||||
RegistrationErrorCode(HttpStatus status) {
|
||||
this.status = status;
|
||||
}
|
||||
|
||||
public HttpStatus getStatus() {
|
||||
return status;
|
||||
}
|
||||
VALIDATION_ERROR,
|
||||
USER_NOT_FOUND,
|
||||
LESSON_NOT_FOUND,
|
||||
SEMESTER_NOT_FOUND,
|
||||
REGISTRATION_NOT_FOUND,
|
||||
NOT_ELIGIBLE_GRADE,
|
||||
NOT_ELIGIBLE_ROLE,
|
||||
REGISTRATION_FORBIDDEN,
|
||||
REGISTRATION_PERIOD_CLOSED,
|
||||
ALREADY_REGISTERED,
|
||||
DUPLICATE_SUBJECT,
|
||||
SCHEDULE_CONFLICT,
|
||||
CREDIT_LIMIT_EXCEEDED,
|
||||
CAPACITY_EXCEEDED,
|
||||
IDEMPOTENCY_KEY_REUSED,
|
||||
LOCK_TIMEOUT,
|
||||
INTERNAL_SERVER_ERROR
|
||||
}
|
||||
|
||||
@@ -1,6 +0,0 @@
|
||||
package com.study.course_registration.exception;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
public record ErrorResponse(String code, String message, Instant timestamp) {
|
||||
}
|
||||
@@ -1,55 +0,0 @@
|
||||
package com.study.course_registration.exception;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.dao.PessimisticLockingFailureException;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
import com.study.course_registration.enums.RegistrationErrorCode;
|
||||
import jakarta.persistence.LockTimeoutException;
|
||||
import jakarta.persistence.PessimisticLockException;
|
||||
import jakarta.validation.ConstraintViolationException;
|
||||
|
||||
@RestControllerAdvice
|
||||
public class GlobalExceptionHandler {
|
||||
private static final Logger log=LoggerFactory.getLogger(GlobalExceptionHandler.class);
|
||||
private final Clock clock;
|
||||
public GlobalExceptionHandler(Clock clock) { this.clock=clock; }
|
||||
|
||||
@ExceptionHandler(RegistrationException.class)
|
||||
ResponseEntity<ErrorResponse> registration(RegistrationException e) { return response(e.getErrorCode(),e.getMessage()); }
|
||||
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
ResponseEntity<ErrorResponse> validation(MethodArgumentNotValidException e) {
|
||||
String message=e.getBindingResult().getFieldErrors().stream().findFirst()
|
||||
.map(x -> x.getField()+": "+x.getDefaultMessage()).orElse("요청 값이 올바르지 않습니다.");
|
||||
return response(RegistrationErrorCode.VALIDATION_ERROR,message);
|
||||
}
|
||||
|
||||
@ExceptionHandler({ConstraintViolationException.class,HttpMessageNotReadableException.class})
|
||||
ResponseEntity<ErrorResponse> badRequest(Exception e) { return response(RegistrationErrorCode.VALIDATION_ERROR,"요청 값이 올바르지 않습니다."); }
|
||||
|
||||
@ExceptionHandler({LockTimeoutException.class,PessimisticLockException.class,PessimisticLockingFailureException.class})
|
||||
ResponseEntity<ErrorResponse> handleLockTimeout(Exception e) {
|
||||
String retryAfter = Integer.toString(ThreadLocalRandom.current().nextInt(1, 4));
|
||||
return ResponseEntity.status(RegistrationErrorCode.LOCK_TIMEOUT.getStatus()).header(HttpHeaders.RETRY_AFTER, retryAfter)
|
||||
.body(body(RegistrationErrorCode.LOCK_TIMEOUT,"다른 요청이 처리 중입니다. 잠시 후 다시 시도해 주세요."));
|
||||
}
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
ResponseEntity<ErrorResponse> handleUnexpected(Exception e) {
|
||||
log.error("Unhandled request failure",e);
|
||||
return response(RegistrationErrorCode.INTERNAL_SERVER_ERROR,"서버 내부 오류가 발생했습니다.");
|
||||
}
|
||||
|
||||
private ResponseEntity<ErrorResponse> response(RegistrationErrorCode code,String message) {
|
||||
return ResponseEntity.status(code.getStatus()).body(body(code,message));
|
||||
}
|
||||
private ErrorResponse body(RegistrationErrorCode code,String message) { return new ErrorResponse(code.name(),message,clock.instant()); }
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
package com.study.course_registration.exception;
|
||||
|
||||
import com.study.course_registration.enums.RegistrationErrorCode;
|
||||
|
||||
public class RegistrationException extends RuntimeException {
|
||||
private final RegistrationErrorCode errorCode;
|
||||
|
||||
public RegistrationException(RegistrationErrorCode errorCode, String message) {
|
||||
super(message);
|
||||
this.errorCode = errorCode;
|
||||
}
|
||||
|
||||
public RegistrationErrorCode getErrorCode() {
|
||||
return errorCode;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package com.study.course_registration.failure;
|
||||
|
||||
import com.study.course_registration.enums.RegistrationErrorCode;
|
||||
|
||||
public abstract class ApplicationFailure extends RuntimeException {
|
||||
private final RegistrationErrorCode errorCode;
|
||||
|
||||
protected ApplicationFailure(RegistrationErrorCode errorCode, String message) {
|
||||
super(message);
|
||||
this.errorCode = errorCode;
|
||||
}
|
||||
|
||||
protected ApplicationFailure(RegistrationErrorCode errorCode, String message, Throwable cause) {
|
||||
super(message, cause);
|
||||
this.errorCode = errorCode;
|
||||
}
|
||||
|
||||
public RegistrationErrorCode getErrorCode() {
|
||||
return errorCode;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package com.study.course_registration.failure;
|
||||
|
||||
import com.study.course_registration.enums.RegistrationErrorCode;
|
||||
|
||||
public final class AuthorizationFailure extends ApplicationFailure {
|
||||
private AuthorizationFailure(RegistrationErrorCode code, String message) {
|
||||
super(code, message);
|
||||
}
|
||||
|
||||
public static AuthorizationFailure registrationForbidden() {
|
||||
return new AuthorizationFailure(
|
||||
RegistrationErrorCode.REGISTRATION_FORBIDDEN,
|
||||
"다른 사용자의 수강신청은 취소할 수 없습니다.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package com.study.course_registration.failure;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.LocalTime;
|
||||
|
||||
import com.study.course_registration.enums.RegistrationErrorCode;
|
||||
import com.study.course_registration.enums.UserRole;
|
||||
|
||||
public final class BusinessRejection extends ApplicationFailure {
|
||||
private BusinessRejection(RegistrationErrorCode code, String message) {
|
||||
super(code, message);
|
||||
}
|
||||
|
||||
public static BusinessRejection registrationPeriodClosed() {
|
||||
return new BusinessRejection(
|
||||
RegistrationErrorCode.REGISTRATION_PERIOD_CLOSED,
|
||||
"수강신청 기간이 아닙니다.");
|
||||
}
|
||||
|
||||
public static BusinessRejection notEligibleGrade(long currentGrade, long minGrade) {
|
||||
return new BusinessRejection(
|
||||
RegistrationErrorCode.NOT_ELIGIBLE_GRADE,
|
||||
"수강 가능한 학년이 아닙니다. (현재 " + currentGrade + "학년, 최소 " + minGrade + "학년)");
|
||||
}
|
||||
|
||||
public static BusinessRejection notEligibleRole(UserRole requiredRole) {
|
||||
return new BusinessRejection(
|
||||
RegistrationErrorCode.NOT_ELIGIBLE_ROLE,
|
||||
"수강 가능한 역할이 아닙니다. (필요 역할: " + requiredRole + ")");
|
||||
}
|
||||
|
||||
public static BusinessRejection alreadyRegistered() {
|
||||
return new BusinessRejection(
|
||||
RegistrationErrorCode.ALREADY_REGISTERED,
|
||||
"이미 신청한 강의입니다.");
|
||||
}
|
||||
|
||||
public static BusinessRejection duplicateSubject() {
|
||||
return new BusinessRejection(
|
||||
RegistrationErrorCode.DUPLICATE_SUBJECT,
|
||||
"같은 과목의 다른 분반을 이미 신청했습니다.");
|
||||
}
|
||||
|
||||
public static BusinessRejection scheduleConflict(
|
||||
DayOfWeek dayOfWeek,
|
||||
LocalTime startTime,
|
||||
LocalTime endTime) {
|
||||
return new BusinessRejection(
|
||||
RegistrationErrorCode.SCHEDULE_CONFLICT,
|
||||
"기존 수업과 시간이 겹칩니다. (" + dayOfWeek + " " + startTime + "-" + endTime + ")");
|
||||
}
|
||||
|
||||
public static BusinessRejection creditLimitExceeded(int current, int requested, int max) {
|
||||
return new BusinessRejection(
|
||||
RegistrationErrorCode.CREDIT_LIMIT_EXCEEDED,
|
||||
"신청 학점이 상한을 넘습니다. (" + current + " + " + requested + " > " + max + ")");
|
||||
}
|
||||
|
||||
public static BusinessRejection capacityExceeded(long enrolled, int capacity) {
|
||||
return new BusinessRejection(
|
||||
RegistrationErrorCode.CAPACITY_EXCEEDED,
|
||||
"정원이 가득 찼습니다. (" + enrolled + "/" + capacity + ")");
|
||||
}
|
||||
|
||||
public static BusinessRejection idempotencyKeyReused() {
|
||||
return new BusinessRejection(
|
||||
RegistrationErrorCode.IDEMPOTENCY_KEY_REUSED,
|
||||
"동일한 Idempotency-Key를 다른 강의에 사용할 수 없습니다.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.study.course_registration.failure;
|
||||
|
||||
public enum InvariantCode {
|
||||
MULTIPLE_ACTIVE_REGISTRATION_SEMESTERS,
|
||||
MULTIPLE_ACTIVE_ACADEMIC_SEMESTERS,
|
||||
MISSING_CANDIDATE_LESSON_SCHEDULE,
|
||||
MISSING_EXISTING_LESSON_SCHEDULE,
|
||||
OVERLAPPING_LESSON_SCHEDULE
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
package com.study.course_registration.failure;
|
||||
|
||||
import com.study.course_registration.enums.RegistrationErrorCode;
|
||||
|
||||
public final class RequestValidationFailure extends ApplicationFailure {
|
||||
private RequestValidationFailure(String message) {
|
||||
super(RegistrationErrorCode.VALIDATION_ERROR, message);
|
||||
}
|
||||
|
||||
public static RequestValidationFailure idempotencyKeyTooLong() {
|
||||
return new RequestValidationFailure("Idempotency-Key는 100자 이하여야 합니다.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package com.study.course_registration.failure;
|
||||
|
||||
import com.study.course_registration.enums.RegistrationErrorCode;
|
||||
|
||||
public final class ResourceNotFound extends ApplicationFailure {
|
||||
private ResourceNotFound(RegistrationErrorCode code, String message) {
|
||||
super(code, message);
|
||||
}
|
||||
|
||||
public static ResourceNotFound user() {
|
||||
return new ResourceNotFound(RegistrationErrorCode.USER_NOT_FOUND, "사용자를 찾을 수 없습니다.");
|
||||
}
|
||||
|
||||
public static ResourceNotFound lesson() {
|
||||
return new ResourceNotFound(RegistrationErrorCode.LESSON_NOT_FOUND, "강의를 찾을 수 없습니다.");
|
||||
}
|
||||
|
||||
public static ResourceNotFound semester() {
|
||||
return new ResourceNotFound(RegistrationErrorCode.SEMESTER_NOT_FOUND, "학기를 찾을 수 없습니다.");
|
||||
}
|
||||
|
||||
public static ResourceNotFound currentSemester() {
|
||||
return new ResourceNotFound(RegistrationErrorCode.SEMESTER_NOT_FOUND, "현재 수강 가능한 학기를 찾을 수 없습니다.");
|
||||
}
|
||||
|
||||
public static ResourceNotFound registration() {
|
||||
return new ResourceNotFound(RegistrationErrorCode.REGISTRATION_NOT_FOUND, "수강신청 건을 찾을 수 없습니다.");
|
||||
}
|
||||
}
|
||||
+15
@@ -0,0 +1,15 @@
|
||||
package com.study.course_registration.failure;
|
||||
|
||||
import com.study.course_registration.enums.RegistrationErrorCode;
|
||||
|
||||
public final class RetryableInfrastructureFailure extends ApplicationFailure {
|
||||
private RetryableInfrastructureFailure(String message, Throwable cause) {
|
||||
super(RegistrationErrorCode.LOCK_TIMEOUT, message, cause);
|
||||
}
|
||||
|
||||
public static RetryableInfrastructureFailure lockTimeout(Throwable cause) {
|
||||
return new RetryableInfrastructureFailure(
|
||||
"다른 요청이 처리 중입니다. 잠시 후 다시 시도해 주세요.",
|
||||
cause);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package com.study.course_registration.failure;
|
||||
|
||||
public final class SystemInvariantViolation extends RuntimeException {
|
||||
private final InvariantCode invariantCode;
|
||||
|
||||
private SystemInvariantViolation(InvariantCode invariantCode, String message) {
|
||||
super(message);
|
||||
this.invariantCode = invariantCode;
|
||||
}
|
||||
|
||||
public static SystemInvariantViolation multipleRegistrationSemesters() {
|
||||
return new SystemInvariantViolation(
|
||||
InvariantCode.MULTIPLE_ACTIVE_REGISTRATION_SEMESTERS,
|
||||
"동시에 두 개 이상의 수강신청 학기가 활성화되어 있습니다.");
|
||||
}
|
||||
|
||||
public static SystemInvariantViolation multipleAcademicSemesters() {
|
||||
return new SystemInvariantViolation(
|
||||
InvariantCode.MULTIPLE_ACTIVE_ACADEMIC_SEMESTERS,
|
||||
"동시에 두 개 이상의 학기가 진행 중입니다.");
|
||||
}
|
||||
|
||||
public static SystemInvariantViolation missingCandidateSchedule() {
|
||||
return new SystemInvariantViolation(
|
||||
InvariantCode.MISSING_CANDIDATE_LESSON_SCHEDULE,
|
||||
"신청 가능한 강의에 시간표가 없습니다.");
|
||||
}
|
||||
|
||||
public static SystemInvariantViolation missingExistingSchedule() {
|
||||
return new SystemInvariantViolation(
|
||||
InvariantCode.MISSING_EXISTING_LESSON_SCHEDULE,
|
||||
"기존 신청 강의에 시간표가 없습니다.");
|
||||
}
|
||||
|
||||
public static SystemInvariantViolation overlappingLessonSchedule() {
|
||||
return new SystemInvariantViolation(
|
||||
InvariantCode.OVERLAPPING_LESSON_SCHEDULE,
|
||||
"같은 강의의 시간표가 겹칩니다.");
|
||||
}
|
||||
|
||||
public InvariantCode getInvariantCode() {
|
||||
return invariantCode;
|
||||
}
|
||||
}
|
||||
+39
@@ -0,0 +1,39 @@
|
||||
package com.study.course_registration.infrastructure.persistence;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.study.course_registration.application.idempotency.port.IdempotencyPort;
|
||||
import com.study.course_registration.entity.RegistrationIdempotency;
|
||||
import com.study.course_registration.infrastructure.persistence.repository.RegistrationIdempotencyRepository;
|
||||
|
||||
@Component
|
||||
public class JpaIdempotencyAdapter implements IdempotencyPort {
|
||||
private final RegistrationIdempotencyRepository repository;
|
||||
|
||||
public JpaIdempotencyAdapter(RegistrationIdempotencyRepository repository) {
|
||||
this.repository = repository;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<RegistrationIdempotency> findActive(String userId, String key, Instant now) {
|
||||
return repository.findByUser_IdAndIdempotencyKeyAndExpiresAtAfter(userId, key, now);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteExpiredKey(String userId, String key, Instant now) {
|
||||
repository.deleteExpiredKey(userId, key, now);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void deleteExpired(Instant now) {
|
||||
repository.deleteExpired(now);
|
||||
}
|
||||
|
||||
@Override
|
||||
public RegistrationIdempotency save(RegistrationIdempotency idempotency) {
|
||||
return repository.saveAndFlush(idempotency);
|
||||
}
|
||||
}
|
||||
+71
@@ -0,0 +1,71 @@
|
||||
package com.study.course_registration.infrastructure.persistence;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.study.course_registration.application.lesson.port.LessonQueryPort;
|
||||
import com.study.course_registration.entity.Lesson;
|
||||
import com.study.course_registration.entity.LessonSchedule;
|
||||
import com.study.course_registration.infrastructure.persistence.repository.LessonRepository;
|
||||
import com.study.course_registration.infrastructure.persistence.repository.LessonScheduleRepository;
|
||||
import com.study.course_registration.infrastructure.persistence.repository.UserLessonRepository;
|
||||
|
||||
@Component
|
||||
public class JpaLessonQueryAdapter implements LessonQueryPort {
|
||||
private final LessonRepository lessons;
|
||||
private final LessonScheduleRepository schedules;
|
||||
private final UserLessonRepository registrations;
|
||||
|
||||
public JpaLessonQueryAdapter(
|
||||
LessonRepository lessons,
|
||||
LessonScheduleRepository schedules,
|
||||
UserLessonRepository registrations) {
|
||||
this.lessons = lessons;
|
||||
this.schedules = schedules;
|
||||
this.registrations = registrations;
|
||||
}
|
||||
|
||||
@Override
|
||||
public LessonPage findPage(String semesterId, String subjectId, int page, int size) {
|
||||
Pageable pageable = PageRequest.of(
|
||||
page,
|
||||
size,
|
||||
Sort.by(Sort.Order.asc("name"), Sort.Order.asc("id")));
|
||||
|
||||
Page<Lesson> result = subjectId == null || subjectId.isBlank()
|
||||
? lessons.findBySemester_Id(semesterId, pageable)
|
||||
: lessons.findBySemester_IdAndSubject_Id(semesterId, subjectId, pageable);
|
||||
|
||||
return new LessonPage(result.getContent(), result.getTotalElements());
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Lesson> findDetailed(String lessonId) {
|
||||
return lessons.findDetailedById(lessonId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<LessonSchedule> findSchedules(Collection<String> lessonIds) {
|
||||
return schedules.findByLesson_IdInOrderByDayOfWeekAscStartTimeAsc(lessonIds);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Map<String, Long> countActiveEnrollments(Collection<String> lessonIds) {
|
||||
return registrations.countActiveByLessonIds(lessonIds).stream()
|
||||
.collect(Collectors.toMap(
|
||||
UserLessonRepository.LessonEnrollmentCount::getLessonId,
|
||||
UserLessonRepository.LessonEnrollmentCount::getEnrolledCount,
|
||||
(left, right) -> left,
|
||||
LinkedHashMap::new));
|
||||
}
|
||||
}
|
||||
+89
@@ -0,0 +1,89 @@
|
||||
package com.study.course_registration.infrastructure.persistence;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.springframework.dao.PessimisticLockingFailureException;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.study.course_registration.application.registration.port.RegistrationContextLoader;
|
||||
import com.study.course_registration.domain.registration.RegistrationContext;
|
||||
import com.study.course_registration.entity.Lesson;
|
||||
import com.study.course_registration.entity.LessonSchedule;
|
||||
import com.study.course_registration.entity.User;
|
||||
import com.study.course_registration.entity.UserLesson;
|
||||
import com.study.course_registration.failure.ResourceNotFound;
|
||||
import com.study.course_registration.failure.RetryableInfrastructureFailure;
|
||||
import com.study.course_registration.infrastructure.persistence.repository.LessonRepository;
|
||||
import com.study.course_registration.infrastructure.persistence.repository.LessonScheduleRepository;
|
||||
import com.study.course_registration.infrastructure.persistence.repository.UserLessonRepository;
|
||||
import com.study.course_registration.infrastructure.persistence.repository.UserRepository;
|
||||
|
||||
import jakarta.persistence.LockTimeoutException;
|
||||
import jakarta.persistence.PessimisticLockException;
|
||||
|
||||
@Component
|
||||
public class JpaRegistrationContextLoader implements RegistrationContextLoader {
|
||||
private final UserRepository users;
|
||||
private final LessonRepository lessons;
|
||||
private final UserLessonRepository registrations;
|
||||
private final LessonScheduleRepository schedules;
|
||||
|
||||
public JpaRegistrationContextLoader(
|
||||
UserRepository users,
|
||||
LessonRepository lessons,
|
||||
UserLessonRepository registrations,
|
||||
LessonScheduleRepository schedules) {
|
||||
this.users = users;
|
||||
this.lessons = lessons;
|
||||
this.registrations = registrations;
|
||||
this.schedules = schedules;
|
||||
}
|
||||
|
||||
@Override
|
||||
public RegistrationContext loadForRegistration(String userId, String lessonId, Instant now) {
|
||||
LockedRegistration locked = lockForUpdate(userId, lessonId);
|
||||
List<UserLesson> active = registrations.findActiveByUserIdAndSemesterId(
|
||||
locked.user().getId(),
|
||||
locked.lesson().getSemester().getId());
|
||||
|
||||
Set<String> lessonIds = active.stream()
|
||||
.map(UserLesson::getLesson)
|
||||
.map(Lesson::getId)
|
||||
.collect(Collectors.toCollection(LinkedHashSet::new));
|
||||
lessonIds.add(locked.lesson().getId());
|
||||
|
||||
Map<String, List<LessonSchedule>> schedulesByLessonId =
|
||||
schedules.findByLesson_IdInOrderByDayOfWeekAscStartTimeAsc(lessonIds).stream()
|
||||
.collect(Collectors.groupingBy(
|
||||
schedule -> schedule.getLesson().getId(),
|
||||
LinkedHashMap::new,
|
||||
Collectors.toList()));
|
||||
|
||||
long enrolled = registrations.countByLesson_IdAndCanceledAtIsNull(locked.lesson().getId());
|
||||
|
||||
return new RegistrationContext(
|
||||
locked.user(),
|
||||
locked.lesson(),
|
||||
active,
|
||||
schedulesByLessonId,
|
||||
enrolled,
|
||||
now);
|
||||
}
|
||||
|
||||
@Override
|
||||
public LockedRegistration lockForUpdate(String userId, String lessonId) {
|
||||
try {
|
||||
User user = users.findByIdForUpdate(userId).orElseThrow(ResourceNotFound::user);
|
||||
Lesson lesson = lessons.findByIdForUpdate(lessonId).orElseThrow(ResourceNotFound::lesson);
|
||||
return new LockedRegistration(user, lesson);
|
||||
} catch (PessimisticLockingFailureException | LockTimeoutException | PessimisticLockException exception) {
|
||||
throw RetryableInfrastructureFailure.lockTimeout(exception);
|
||||
}
|
||||
}
|
||||
}
|
||||
+62
@@ -0,0 +1,62 @@
|
||||
package com.study.course_registration.infrastructure.persistence;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.study.course_registration.application.registration.port.RegistrationReader;
|
||||
import com.study.course_registration.application.registration.port.RegistrationWriter;
|
||||
import com.study.course_registration.entity.LessonSchedule;
|
||||
import com.study.course_registration.entity.UserLesson;
|
||||
import com.study.course_registration.infrastructure.persistence.repository.LessonScheduleRepository;
|
||||
import com.study.course_registration.infrastructure.persistence.repository.UserLessonRepository;
|
||||
import com.study.course_registration.infrastructure.persistence.repository.UserRepository;
|
||||
|
||||
@Component
|
||||
public class JpaRegistrationPersistenceAdapter implements RegistrationReader, RegistrationWriter {
|
||||
private final UserRepository users;
|
||||
private final UserLessonRepository registrations;
|
||||
private final LessonScheduleRepository schedules;
|
||||
|
||||
public JpaRegistrationPersistenceAdapter(
|
||||
UserRepository users,
|
||||
UserLessonRepository registrations,
|
||||
LessonScheduleRepository schedules) {
|
||||
this.users = users;
|
||||
this.registrations = registrations;
|
||||
this.schedules = schedules;
|
||||
}
|
||||
|
||||
@Override
|
||||
public boolean userExists(String userId) {
|
||||
return users.existsById(userId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<RegistrationTarget> findTarget(String registrationId) {
|
||||
return registrations.findTargetById(registrationId)
|
||||
.map(target -> new RegistrationTarget(target.getUserId(), target.getLessonId()));
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<UserLesson> findRegistration(String registrationId) {
|
||||
return registrations.findById(registrationId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<UserLesson> findActive(String userId, String semesterId) {
|
||||
return registrations.findActiveByUserIdAndSemesterId(userId, semesterId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<LessonSchedule> findSchedules(Collection<String> lessonIds) {
|
||||
return schedules.findByLesson_IdInOrderByDayOfWeekAscStartTimeAsc(lessonIds);
|
||||
}
|
||||
|
||||
@Override
|
||||
public UserLesson save(UserLesson registration) {
|
||||
return registrations.saveAndFlush(registration);
|
||||
}
|
||||
}
|
||||
+36
@@ -0,0 +1,36 @@
|
||||
package com.study.course_registration.infrastructure.persistence;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.study.course_registration.application.semester.port.SemesterQueryPort;
|
||||
import com.study.course_registration.entity.Semester;
|
||||
import com.study.course_registration.infrastructure.persistence.repository.SemesterRepository;
|
||||
|
||||
@Component
|
||||
public class JpaSemesterQueryAdapter implements SemesterQueryPort {
|
||||
private final SemesterRepository repository;
|
||||
|
||||
public JpaSemesterQueryAdapter(SemesterRepository repository) {
|
||||
this.repository = repository;
|
||||
}
|
||||
|
||||
@Override
|
||||
public Optional<Semester> findById(String semesterId) {
|
||||
return repository.findById(semesterId);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Semester> findRegistrationSemesters(Instant now) {
|
||||
return repository.findByRegistrationStartAtLessThanEqualAndRegistrationEndAtGreaterThanEqual(now, now);
|
||||
}
|
||||
|
||||
@Override
|
||||
public List<Semester> findAcademicSemesters(LocalDate today) {
|
||||
return repository.findByStartDateLessThanEqualAndEndDateGreaterThanEqual(today, today);
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.study.course_registration.repository;
|
||||
package com.study.course_registration.infrastructure.persistence.repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.study.course_registration.repository;
|
||||
package com.study.course_registration.infrastructure.persistence.repository;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.study.course_registration.repository;
|
||||
package com.study.course_registration.infrastructure.persistence.repository;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.study.course_registration.repository;
|
||||
package com.study.course_registration.infrastructure.persistence.repository;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.study.course_registration.repository;
|
||||
package com.study.course_registration.infrastructure.persistence.repository;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.study.course_registration.repository;
|
||||
package com.study.course_registration.infrastructure.persistence.repository;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.study.course_registration.repository;
|
||||
package com.study.course_registration.infrastructure.persistence.repository;
|
||||
|
||||
import java.util.Collection;
|
||||
import java.util.List;
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.study.course_registration.repository;
|
||||
package com.study.course_registration.infrastructure.persistence.repository;
|
||||
|
||||
import java.util.Optional;
|
||||
|
||||
+20
@@ -0,0 +1,20 @@
|
||||
package com.study.course_registration.infrastructure.scheduling;
|
||||
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.study.course_registration.application.idempotency.CleanupIdempotencyUseCase;
|
||||
|
||||
@Component
|
||||
public class IdempotencyRetentionJob {
|
||||
private final CleanupIdempotencyUseCase cleanupIdempotencyUseCase;
|
||||
|
||||
public IdempotencyRetentionJob(CleanupIdempotencyUseCase cleanupIdempotencyUseCase) {
|
||||
this.cleanupIdempotencyUseCase = cleanupIdempotencyUseCase;
|
||||
}
|
||||
|
||||
@Scheduled(fixedDelayString = "${app.idempotency.cleanup-delay-ms:3600000}")
|
||||
public void cleanup() {
|
||||
cleanupIdempotencyUseCase.execute();
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,7 @@ import com.study.course_registration.entity.Semester;
|
||||
import com.study.course_registration.entity.Subject;
|
||||
import com.study.course_registration.entity.User;
|
||||
import com.study.course_registration.enums.UserRole;
|
||||
import com.study.course_registration.service.policy.LessonSchedulePolicy;
|
||||
import com.study.course_registration.domain.schedule.LessonSchedulePolicy;
|
||||
|
||||
import jakarta.persistence.EntityManager;
|
||||
|
||||
|
||||
@@ -1,180 +0,0 @@
|
||||
package com.study.course_registration.service;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.LinkedHashSet;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.Optional;
|
||||
import java.util.Set;
|
||||
import java.util.stream.Collectors;
|
||||
import org.springframework.beans.factory.annotation.Value;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
import com.study.course_registration.dto.ScheduleResponse;
|
||||
import com.study.course_registration.dto.registration.CourseRegistrationRequest;
|
||||
import com.study.course_registration.dto.registration.CourseRegistrationResponse;
|
||||
import com.study.course_registration.dto.registration.RegistrationItemResponse;
|
||||
import com.study.course_registration.dto.registration.RegistrationListResponse;
|
||||
import com.study.course_registration.entity.Lesson;
|
||||
import com.study.course_registration.entity.LessonSchedule;
|
||||
import com.study.course_registration.entity.RegistrationIdempotency;
|
||||
import com.study.course_registration.entity.Semester;
|
||||
import com.study.course_registration.entity.User;
|
||||
import com.study.course_registration.entity.UserLesson;
|
||||
import com.study.course_registration.enums.RegistrationErrorCode;
|
||||
import com.study.course_registration.exception.RegistrationException;
|
||||
import com.study.course_registration.repository.LessonScheduleRepository;
|
||||
import com.study.course_registration.repository.RegistrationIdempotencyRepository;
|
||||
import com.study.course_registration.repository.UserLessonRepository;
|
||||
import com.study.course_registration.repository.UserRepository;
|
||||
import com.study.course_registration.service.lock.RegistrationLockManager;
|
||||
import com.study.course_registration.service.lock.RegistrationLockManager.LockedRegistration;
|
||||
import com.study.course_registration.service.policy.RegistrationValidator;
|
||||
|
||||
@Service
|
||||
public class CourseRegistrationService {
|
||||
private final Clock clock;
|
||||
private final UserRepository userRepository;
|
||||
private final LessonScheduleRepository lessonScheduleRepository;
|
||||
private final UserLessonRepository userLessonRepository;
|
||||
private final RegistrationIdempotencyRepository idempotencies;
|
||||
private final RegistrationValidator validator;
|
||||
private final SemesterResolver semesterResolver;
|
||||
private final RegistrationLockManager lockManager;
|
||||
private final long idempotencyTtlSeconds;
|
||||
|
||||
public CourseRegistrationService(Clock clock, UserRepository userRepository,
|
||||
LessonScheduleRepository lessonScheduleRepository, UserLessonRepository userLessonRepository,
|
||||
RegistrationIdempotencyRepository idempotencies, RegistrationValidator validator,
|
||||
SemesterResolver semesterResolver, RegistrationLockManager lockManager,
|
||||
@Value("${app.idempotency.ttl-seconds:86400}") long idempotencyTtlSeconds) {
|
||||
this.clock = clock;
|
||||
this.userRepository = userRepository;
|
||||
this.lessonScheduleRepository = lessonScheduleRepository;
|
||||
this.userLessonRepository = userLessonRepository;
|
||||
this.idempotencies = idempotencies;
|
||||
this.validator = validator;
|
||||
this.semesterResolver = semesterResolver;
|
||||
this.lockManager = lockManager;
|
||||
this.idempotencyTtlSeconds = idempotencyTtlSeconds;
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public CourseRegistrationResponse register(String userId, CourseRegistrationRequest request) {
|
||||
return register(userId, request, null);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public CourseRegistrationResponse register(String userId, CourseRegistrationRequest request, String idempotencyKey) {
|
||||
LockedRegistration locked = lockManager.lock(userId, request.lessonId());
|
||||
|
||||
String normalizedKey = normalizeIdempotencyKey(idempotencyKey);
|
||||
Instant requestTime = clock.instant();
|
||||
if (normalizedKey != null) {
|
||||
idempotencies.deleteExpiredKey(userId, normalizedKey, requestTime);
|
||||
Optional<RegistrationIdempotency> previous =
|
||||
idempotencies.findByUser_IdAndIdempotencyKeyAndExpiresAtAfter(
|
||||
userId, normalizedKey, requestTime);
|
||||
if (previous.isPresent()) {
|
||||
RegistrationIdempotency stored = previous.get();
|
||||
if (!stored.getLesson().getId().equals(request.lessonId())) {
|
||||
throw error(RegistrationErrorCode.IDEMPOTENCY_KEY_REUSED,
|
||||
"동일한 Idempotency-Key를 다른 강의에 사용할 수 없습니다.");
|
||||
}
|
||||
return response(stored.getRegistration(), stored.getUser(), stored.getLesson(), stored.getTotalCredits());
|
||||
}
|
||||
}
|
||||
|
||||
validator.validatePreconditions(locked.user(), locked.lesson(), requestTime);
|
||||
|
||||
List<UserLesson> active = userLessonRepository.findActiveByUserIdAndSemesterId(
|
||||
locked.user().getId(), locked.lesson().getSemester().getId());
|
||||
Map<String, List<LessonSchedule>> schedules = loadSchedules(active, locked.lesson());
|
||||
long enrolled = userLessonRepository.countByLesson_IdAndCanceledAtIsNull(locked.lesson().getId());
|
||||
|
||||
validator.validateLocked(locked.lesson(), active, schedules, enrolled);
|
||||
validator.validateRegistrationPeriod(locked.lesson(), clock.instant());
|
||||
|
||||
int totalCredits = validator.totalCreditsAfter(locked.lesson(), active);
|
||||
UserLesson registration = userLessonRepository.saveAndFlush(new UserLesson(locked.user(), locked.lesson()));
|
||||
if (normalizedKey != null) {
|
||||
idempotencies.saveAndFlush(new RegistrationIdempotency(
|
||||
locked.user(),
|
||||
locked.lesson(),
|
||||
registration,
|
||||
normalizedKey,
|
||||
totalCredits,
|
||||
requestTime.plusSeconds(idempotencyTtlSeconds)));
|
||||
}
|
||||
return response(registration, locked.user(), locked.lesson(), totalCredits);
|
||||
}
|
||||
|
||||
@Transactional(readOnly = true)
|
||||
public RegistrationListResponse getRegistrations(String userId, String semesterId) {
|
||||
if (!userRepository.existsById(userId)) throw error(RegistrationErrorCode.USER_NOT_FOUND, "사용자를 찾을 수 없습니다.");
|
||||
Semester semester = semesterResolver.resolve(semesterId);
|
||||
List<UserLesson> active = userLessonRepository.findActiveByUserIdAndSemesterId(userId, semester.getId());
|
||||
Set<String> lessonIds = active.stream().map(UserLesson::getLesson).map(Lesson::getId)
|
||||
.collect(Collectors.toCollection(LinkedHashSet::new));
|
||||
Map<String,List<LessonSchedule>> schedules = groupSchedules(lessonIds.isEmpty() ? List.of()
|
||||
: lessonScheduleRepository.findByLesson_IdInOrderByDayOfWeekAscStartTimeAsc(lessonIds));
|
||||
List<RegistrationItemResponse> items = active.stream().map(registration -> {
|
||||
Lesson lesson=registration.getLesson();
|
||||
return new RegistrationItemResponse(registration.getId(), lesson.getId(), lesson.getName(),
|
||||
lesson.getSubject().getCode(), lesson.getSubject().getName(), lesson.getSubject().getCredit(),
|
||||
lesson.getProfessor().getName(), schedules.getOrDefault(lesson.getId(),List.of()).stream()
|
||||
.map(ScheduleResponse::from).toList(), registration.getCreatedAt());
|
||||
}).toList();
|
||||
return new RegistrationListResponse(userId, semester.getId(), semester.getName(),
|
||||
validator.currentCredits(active), semester.getMaxCredits(), items);
|
||||
}
|
||||
|
||||
@Transactional
|
||||
public void cancel(String userId, String registrationId) {
|
||||
UserLessonRepository.RegistrationTarget target = userLessonRepository.findTargetById(registrationId)
|
||||
.orElseThrow(() -> error(RegistrationErrorCode.REGISTRATION_NOT_FOUND, "수강신청 건을 찾을 수 없습니다."));
|
||||
if (!target.getUserId().equals(userId)) throw error(RegistrationErrorCode.REGISTRATION_FORBIDDEN, "다른 사용자의 수강신청은 취소할 수 없습니다.");
|
||||
LockedRegistration locked = lockManager.lock(userId, target.getLessonId());
|
||||
UserLesson registration = userLessonRepository.findById(registrationId)
|
||||
.orElseThrow(() -> error(RegistrationErrorCode.REGISTRATION_NOT_FOUND, "수강신청 건을 찾을 수 없습니다."));
|
||||
if (registration.isCanceled()) return;
|
||||
Instant now = clock.instant();
|
||||
validator.validateRegistrationPeriod(locked.lesson(), now);
|
||||
registration.cancel(now);
|
||||
}
|
||||
|
||||
|
||||
private CourseRegistrationResponse response(
|
||||
UserLesson registration,
|
||||
User user,
|
||||
Lesson lesson,
|
||||
int totalCredits) {
|
||||
return new CourseRegistrationResponse(
|
||||
registration.getId(), user.getId(), lesson.getId(), lesson.getName(),
|
||||
lesson.getSubject().getCode(), lesson.getSubject().getCredit(),
|
||||
registration.getCreatedAt(), totalCredits);
|
||||
}
|
||||
|
||||
private static String normalizeIdempotencyKey(String value) {
|
||||
if (value == null || value.isBlank()) return null;
|
||||
String normalized = value.trim();
|
||||
if (normalized.length() > 100) {
|
||||
throw error(RegistrationErrorCode.VALIDATION_ERROR, "Idempotency-Key는 100자 이하여야 합니다.");
|
||||
}
|
||||
return normalized;
|
||||
}
|
||||
|
||||
private Map<String,List<LessonSchedule>> loadSchedules(List<UserLesson> registrations, Lesson candidate) {
|
||||
Set<String> ids=registrations.stream().map(UserLesson::getLesson).map(Lesson::getId)
|
||||
.collect(Collectors.toCollection(LinkedHashSet::new));
|
||||
ids.add(candidate.getId());
|
||||
return groupSchedules(lessonScheduleRepository.findByLesson_IdInOrderByDayOfWeekAscStartTimeAsc(ids));
|
||||
}
|
||||
|
||||
private static Map<String,List<LessonSchedule>> groupSchedules(List<LessonSchedule> schedules) {
|
||||
return schedules.stream().collect(Collectors.groupingBy(s -> s.getLesson().getId(),LinkedHashMap::new,Collectors.toList()));
|
||||
}
|
||||
private static RegistrationException error(RegistrationErrorCode code,String message) { return new RegistrationException(code,message); }
|
||||
}
|
||||
@@ -1,26 +0,0 @@
|
||||
package com.study.course_registration.service;
|
||||
|
||||
import java.time.Clock;
|
||||
|
||||
import org.springframework.scheduling.annotation.Scheduled;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.study.course_registration.repository.RegistrationIdempotencyRepository;
|
||||
|
||||
@Component
|
||||
public class IdempotencyRetentionJob {
|
||||
private final Clock clock;
|
||||
private final RegistrationIdempotencyRepository repository;
|
||||
|
||||
public IdempotencyRetentionJob(Clock clock, RegistrationIdempotencyRepository repository) {
|
||||
this.clock = clock;
|
||||
this.repository = repository;
|
||||
}
|
||||
|
||||
@Scheduled(fixedDelayString = "${app.idempotency.cleanup-delay-ms:3600000}")
|
||||
@Transactional
|
||||
public void cleanup() {
|
||||
repository.deleteExpired(clock.instant());
|
||||
}
|
||||
}
|
||||
@@ -1,109 +0,0 @@
|
||||
package com.study.course_registration.service;
|
||||
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.springframework.data.domain.Page;
|
||||
import org.springframework.data.domain.PageRequest;
|
||||
import org.springframework.data.domain.Pageable;
|
||||
import org.springframework.data.domain.Sort;
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
import com.study.course_registration.dto.ScheduleResponse;
|
||||
import com.study.course_registration.dto.lesson.LessonDetailResponse;
|
||||
import com.study.course_registration.dto.lesson.LessonItemResponse;
|
||||
import com.study.course_registration.dto.lesson.LessonListResponse;
|
||||
import com.study.course_registration.entity.Lesson;
|
||||
import com.study.course_registration.entity.LessonSchedule;
|
||||
import com.study.course_registration.entity.Semester;
|
||||
import com.study.course_registration.enums.RegistrationErrorCode;
|
||||
import com.study.course_registration.exception.RegistrationException;
|
||||
import com.study.course_registration.repository.LessonRepository;
|
||||
import com.study.course_registration.repository.LessonScheduleRepository;
|
||||
import com.study.course_registration.repository.UserLessonRepository;
|
||||
|
||||
@Service
|
||||
@Transactional(readOnly = true)
|
||||
public class LessonQueryService {
|
||||
private final LessonRepository lessonRepository;
|
||||
private final LessonScheduleRepository lessonScheduleRepository;
|
||||
private final UserLessonRepository userLessonRepository;
|
||||
private final SemesterResolver semesterResolver;
|
||||
|
||||
public LessonQueryService(LessonRepository lessonRepository,
|
||||
LessonScheduleRepository lessonScheduleRepository,
|
||||
UserLessonRepository userLessonRepository,
|
||||
SemesterResolver semesterResolver) {
|
||||
this.lessonRepository = lessonRepository;
|
||||
this.lessonScheduleRepository = lessonScheduleRepository;
|
||||
this.userLessonRepository = userLessonRepository;
|
||||
this.semesterResolver = semesterResolver;
|
||||
}
|
||||
|
||||
public LessonListResponse getLessons(String semesterId, String subjectId, int page, int size) {
|
||||
Semester semester = semesterResolver.resolve(semesterId);
|
||||
Pageable pageable = PageRequest.of(page, size, Sort.by(Sort.Order.asc("name"), Sort.Order.asc("id")));
|
||||
Page<Lesson> lessonPage = subjectId == null || subjectId.isBlank()
|
||||
? lessonRepository.findBySemester_Id(semester.getId(), pageable)
|
||||
: lessonRepository.findBySemester_IdAndSubject_Id(semester.getId(), subjectId, pageable);
|
||||
|
||||
List<String> lessonIds = lessonPage.getContent().stream().map(Lesson::getId).toList();
|
||||
Map<String, List<LessonSchedule>> schedules = loadSchedules(lessonIds);
|
||||
Map<String, Long> counts = loadCounts(lessonIds);
|
||||
|
||||
List<LessonItemResponse> items = lessonPage.getContent().stream()
|
||||
.map(lesson -> toItem(lesson, schedules.getOrDefault(lesson.getId(), List.of()), counts.getOrDefault(lesson.getId(), 0L)))
|
||||
.toList();
|
||||
|
||||
return new LessonListResponse(page, size, lessonPage.getTotalElements(), items);
|
||||
}
|
||||
|
||||
public LessonDetailResponse getLesson(String lessonId) {
|
||||
Lesson lesson = lessonRepository.findDetailedById(lessonId)
|
||||
.orElseThrow(() -> error(RegistrationErrorCode.LESSON_NOT_FOUND, "강의를 찾을 수 없습니다."));
|
||||
List<ScheduleResponse> schedules = lessonScheduleRepository.findByLesson_IdOrderByDayOfWeekAscStartTimeAsc(lessonId)
|
||||
.stream().map(ScheduleResponse::from).toList();
|
||||
long enrolledCount = userLessonRepository.countByLesson_IdAndCanceledAtIsNull(lessonId);
|
||||
|
||||
return new LessonDetailResponse(
|
||||
lesson.getId(), lesson.getName(), lesson.getSubject().getCode(), lesson.getSubject().getName(),
|
||||
lesson.getSubject().getDescription(), lesson.getSubject().getCredit(), lesson.getProfessor().getName(),
|
||||
lesson.getSemester().getName(), lesson.getCapacity(), enrolledCount, lesson.getMinGrade(), lesson.getAllowedRole(),
|
||||
lesson.getSemester().getRegistrationStartAt(), lesson.getSemester().getRegistrationEndAt(), schedules);
|
||||
}
|
||||
|
||||
private LessonItemResponse toItem(Lesson lesson, List<LessonSchedule> schedules, long enrolledCount) {
|
||||
return new LessonItemResponse(
|
||||
lesson.getId(), lesson.getName(), lesson.getSubject().getCode(), lesson.getSubject().getName(),
|
||||
lesson.getSubject().getCredit(), lesson.getProfessor().getName(), lesson.getCapacity(), enrolledCount,
|
||||
lesson.getMinGrade(), lesson.getAllowedRole(), schedules.stream().map(ScheduleResponse::from).toList());
|
||||
}
|
||||
|
||||
private Map<String, List<LessonSchedule>> loadSchedules(List<String> lessonIds) {
|
||||
if (lessonIds.isEmpty()) {
|
||||
return Map.of();
|
||||
}
|
||||
return lessonScheduleRepository.findByLesson_IdInOrderByDayOfWeekAscStartTimeAsc(lessonIds).stream()
|
||||
.collect(Collectors.groupingBy(
|
||||
schedule -> schedule.getLesson().getId(), LinkedHashMap::new, Collectors.toList()));
|
||||
}
|
||||
|
||||
private Map<String, Long> loadCounts(List<String> lessonIds) {
|
||||
if (lessonIds.isEmpty()) {
|
||||
return Map.of();
|
||||
}
|
||||
return userLessonRepository.countActiveByLessonIds(lessonIds).stream()
|
||||
.collect(Collectors.toMap(
|
||||
UserLessonRepository.LessonEnrollmentCount::getLessonId,
|
||||
UserLessonRepository.LessonEnrollmentCount::getEnrolledCount,
|
||||
(left, right) -> left,
|
||||
LinkedHashMap::new));
|
||||
}
|
||||
|
||||
private static RegistrationException error(RegistrationErrorCode code, String message) {
|
||||
return new RegistrationException(code, message);
|
||||
}
|
||||
}
|
||||
@@ -1,57 +0,0 @@
|
||||
package com.study.course_registration.service;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.study.course_registration.entity.Semester;
|
||||
import com.study.course_registration.enums.RegistrationErrorCode;
|
||||
import com.study.course_registration.exception.RegistrationException;
|
||||
import com.study.course_registration.repository.SemesterRepository;
|
||||
|
||||
@Component
|
||||
public class SemesterResolver {
|
||||
private final Clock clock;
|
||||
private final SemesterRepository semesterRepository;
|
||||
|
||||
public SemesterResolver(Clock clock, SemesterRepository semesterRepository) {
|
||||
this.clock = clock;
|
||||
this.semesterRepository = semesterRepository;
|
||||
}
|
||||
|
||||
public Semester resolve(String semesterId) {
|
||||
if (semesterId != null && !semesterId.isBlank()) {
|
||||
return semesterRepository.findById(semesterId)
|
||||
.orElseThrow(() -> notFound("학기를 찾을 수 없습니다."));
|
||||
}
|
||||
|
||||
Instant now = clock.instant();
|
||||
List<Semester> registrationSemesters =
|
||||
semesterRepository.findByRegistrationStartAtLessThanEqualAndRegistrationEndAtGreaterThanEqual(
|
||||
now, now);
|
||||
if (registrationSemesters.size() > 1) {
|
||||
throw new IllegalStateException("동시에 두 개 이상의 수강신청 학기가 활성화되어 있습니다.");
|
||||
}
|
||||
if (registrationSemesters.size() == 1) {
|
||||
return registrationSemesters.getFirst();
|
||||
}
|
||||
|
||||
LocalDate today = LocalDate.now(clock);
|
||||
List<Semester> academicSemesters =
|
||||
semesterRepository.findByStartDateLessThanEqualAndEndDateGreaterThanEqual(today, today);
|
||||
if (academicSemesters.size() > 1) {
|
||||
throw new IllegalStateException("동시에 두 개 이상의 학기가 진행 중입니다.");
|
||||
}
|
||||
if (academicSemesters.size() == 1) {
|
||||
return academicSemesters.getFirst();
|
||||
}
|
||||
throw notFound("현재 수강 가능한 학기를 찾을 수 없습니다.");
|
||||
}
|
||||
|
||||
private static RegistrationException notFound(String message) {
|
||||
return new RegistrationException(RegistrationErrorCode.SEMESTER_NOT_FOUND, message);
|
||||
}
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
package com.study.course_registration.service.lock;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
import com.study.course_registration.entity.Lesson;
|
||||
import com.study.course_registration.entity.User;
|
||||
import com.study.course_registration.enums.RegistrationErrorCode;
|
||||
import com.study.course_registration.exception.RegistrationException;
|
||||
import com.study.course_registration.repository.LessonRepository;
|
||||
import com.study.course_registration.repository.UserRepository;
|
||||
|
||||
@Component
|
||||
public class RegistrationLockManager {
|
||||
private final UserRepository userRepository;
|
||||
private final LessonRepository lessonRepository;
|
||||
|
||||
public RegistrationLockManager(UserRepository userRepository, LessonRepository lessonRepository) {
|
||||
this.userRepository = userRepository;
|
||||
this.lessonRepository = lessonRepository;
|
||||
}
|
||||
|
||||
public LockedRegistration lock(String userId, String lessonId) {
|
||||
User user = userRepository.findByIdForUpdate(userId)
|
||||
.orElseThrow(() -> new RegistrationException(RegistrationErrorCode.USER_NOT_FOUND, "사용자를 찾을 수 없습니다."));
|
||||
Lesson lesson = lessonRepository.findByIdForUpdate(lessonId)
|
||||
.orElseThrow(() -> new RegistrationException(RegistrationErrorCode.LESSON_NOT_FOUND, "강의를 찾을 수 없습니다."));
|
||||
return new LockedRegistration(user, lesson);
|
||||
}
|
||||
|
||||
public record LockedRegistration(User user, Lesson lesson) {}
|
||||
}
|
||||
-106
@@ -1,106 +0,0 @@
|
||||
package com.study.course_registration.service.policy;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.study.course_registration.entity.Lesson;
|
||||
import com.study.course_registration.entity.LessonSchedule;
|
||||
import com.study.course_registration.entity.User;
|
||||
import com.study.course_registration.entity.UserLesson;
|
||||
import com.study.course_registration.enums.RegistrationErrorCode;
|
||||
import com.study.course_registration.exception.RegistrationException;
|
||||
|
||||
@Component
|
||||
public class RegistrationValidator {
|
||||
private final ScheduleConflictChecker scheduleConflictChecker;
|
||||
|
||||
public RegistrationValidator(ScheduleConflictChecker scheduleConflictChecker) {
|
||||
this.scheduleConflictChecker = scheduleConflictChecker;
|
||||
}
|
||||
|
||||
public void validatePreconditions(User user, Lesson lesson, Instant now) {
|
||||
validateRegistrationPeriod(lesson, now);
|
||||
if (lesson.getMinGrade() != null && user.getGrade() < lesson.getMinGrade()) {
|
||||
throw error(RegistrationErrorCode.NOT_ELIGIBLE_GRADE,
|
||||
"수강 가능한 학년이 아닙니다. (현재 " + user.getGrade() + "학년, 최소 " + lesson.getMinGrade() + "학년)");
|
||||
}
|
||||
if (lesson.getAllowedRole() != null && user.getRole() != lesson.getAllowedRole()) {
|
||||
throw error(RegistrationErrorCode.NOT_ELIGIBLE_ROLE,
|
||||
"수강 가능한 역할이 아닙니다. (필요 역할: " + lesson.getAllowedRole() + ")");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
public void validateRegistrationPeriod(Lesson lesson, Instant now) {
|
||||
if (now.isBefore(lesson.getSemester().getRegistrationStartAt())
|
||||
|| now.isAfter(lesson.getSemester().getRegistrationEndAt())) {
|
||||
throw error(RegistrationErrorCode.REGISTRATION_PERIOD_CLOSED, "수강신청 기간이 아닙니다.");
|
||||
}
|
||||
}
|
||||
|
||||
public void validateLocked(Lesson lesson,
|
||||
List<UserLesson> activeRegistrations,
|
||||
Map<String, List<LessonSchedule>> schedulesByLessonId,
|
||||
long enrolledCount) {
|
||||
if (activeRegistrations.stream().anyMatch(registration -> registration.getLesson().getId().equals(lesson.getId()))) {
|
||||
throw error(RegistrationErrorCode.ALREADY_REGISTERED, "이미 신청한 강의입니다.");
|
||||
}
|
||||
|
||||
if (activeRegistrations.stream().anyMatch(registration ->
|
||||
registration.getLesson().getSubject().getId().equals(lesson.getSubject().getId()))) {
|
||||
throw error(RegistrationErrorCode.DUPLICATE_SUBJECT, "같은 과목의 다른 분반을 이미 신청했습니다.");
|
||||
}
|
||||
|
||||
List<LessonSchedule> candidateSchedules = schedulesByLessonId.getOrDefault(lesson.getId(), List.of());
|
||||
if (candidateSchedules.isEmpty()) {
|
||||
throw error(RegistrationErrorCode.INTERNAL_SERVER_ERROR, "강의 시간표가 없습니다.");
|
||||
}
|
||||
for (UserLesson registration : activeRegistrations) {
|
||||
List<LessonSchedule> existingSchedules = schedulesByLessonId.getOrDefault(registration.getLesson().getId(), List.of());
|
||||
if (existingSchedules.isEmpty()) {
|
||||
throw error(RegistrationErrorCode.INTERNAL_SERVER_ERROR, "기존 신청 강의 시간표가 없습니다.");
|
||||
}
|
||||
for (LessonSchedule candidate : candidateSchedules) {
|
||||
for (LessonSchedule existing : existingSchedules) {
|
||||
if (scheduleConflictChecker.overlaps(candidate, existing)) {
|
||||
throw error(RegistrationErrorCode.SCHEDULE_CONFLICT,
|
||||
"기존 수업과 시간이 겹칩니다. (" + candidate.getDayOfWeek() + " "
|
||||
+ candidate.getStartTime() + "-" + candidate.getEndTime() + ")");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int currentCredits = currentCredits(activeRegistrations);
|
||||
int requestedCredits = lesson.getSubject().getCredit();
|
||||
int maxCredits = lesson.getSemester().getMaxCredits();
|
||||
if (currentCredits + requestedCredits > maxCredits) {
|
||||
throw error(RegistrationErrorCode.CREDIT_LIMIT_EXCEEDED,
|
||||
"신청 학점이 상한을 넘습니다. (" + currentCredits + " + " + requestedCredits + " > " + maxCredits + ")");
|
||||
}
|
||||
|
||||
if (enrolledCount >= lesson.getCapacity()) {
|
||||
throw error(RegistrationErrorCode.CAPACITY_EXCEEDED,
|
||||
"정원이 가득 찼습니다. (" + enrolledCount + "/" + lesson.getCapacity() + ")");
|
||||
}
|
||||
}
|
||||
|
||||
public int totalCreditsAfter(Lesson lesson, List<UserLesson> activeRegistrations) {
|
||||
return currentCredits(activeRegistrations) + lesson.getSubject().getCredit();
|
||||
}
|
||||
|
||||
public int currentCredits(List<UserLesson> activeRegistrations) {
|
||||
return activeRegistrations.stream()
|
||||
.map(UserLesson::getLesson)
|
||||
.map(Lesson::getSubject)
|
||||
.mapToInt(subject -> subject.getCredit())
|
||||
.sum();
|
||||
}
|
||||
|
||||
private static RegistrationException error(RegistrationErrorCode code, String message) {
|
||||
return new RegistrationException(code, message);
|
||||
}
|
||||
}
|
||||
+22
-11
@@ -1,4 +1,4 @@
|
||||
package com.study.course_registration.controller;
|
||||
package com.study.course_registration.web.controller;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
@@ -13,10 +13,13 @@ import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.study.course_registration.dto.registration.CourseRegistrationRequest;
|
||||
import com.study.course_registration.dto.registration.CourseRegistrationResponse;
|
||||
import com.study.course_registration.dto.registration.RegistrationListResponse;
|
||||
import com.study.course_registration.service.CourseRegistrationService;
|
||||
import com.study.course_registration.application.registration.CancelRegistrationUseCase;
|
||||
import com.study.course_registration.application.registration.GetRegistrationsQuery;
|
||||
import com.study.course_registration.application.registration.RegisterCourseCommand;
|
||||
import com.study.course_registration.application.registration.RegisterCourseUseCase;
|
||||
import com.study.course_registration.web.dto.registration.CourseRegistrationRequest;
|
||||
import com.study.course_registration.web.dto.registration.CourseRegistrationResponse;
|
||||
import com.study.course_registration.web.dto.registration.RegistrationListResponse;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.media.Content;
|
||||
@@ -30,10 +33,17 @@ import jakarta.validation.Valid;
|
||||
@RequestMapping("/api/v1/users/{userId}/registrations")
|
||||
@Tag(name = "Registrations", description = "수강신청/조회/취소 API")
|
||||
public class CourseRegistrationController {
|
||||
private final CourseRegistrationService courseRegistrationService;
|
||||
private final RegisterCourseUseCase registerCourse;
|
||||
private final GetRegistrationsQuery getRegistrations;
|
||||
private final CancelRegistrationUseCase cancelRegistration;
|
||||
|
||||
public CourseRegistrationController(CourseRegistrationService courseRegistrationService) {
|
||||
this.courseRegistrationService = courseRegistrationService;
|
||||
public CourseRegistrationController(
|
||||
RegisterCourseUseCase registerCourse,
|
||||
GetRegistrationsQuery getRegistrations,
|
||||
CancelRegistrationUseCase cancelRegistration) {
|
||||
this.registerCourse = registerCourse;
|
||||
this.getRegistrations = getRegistrations;
|
||||
this.cancelRegistration = cancelRegistration;
|
||||
}
|
||||
|
||||
@PostMapping
|
||||
@@ -50,7 +60,8 @@ public class CourseRegistrationController {
|
||||
@PathVariable String userId,
|
||||
@RequestHeader(name = "Idempotency-Key", required = false) String idempotencyKey,
|
||||
@Valid @RequestBody CourseRegistrationRequest request) {
|
||||
return courseRegistrationService.register(userId, request, idempotencyKey);
|
||||
return CourseRegistrationResponse.from(registerCourse.execute(
|
||||
new RegisterCourseCommand(userId, request.lessonId(), idempotencyKey)));
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
@@ -58,7 +69,7 @@ public class CourseRegistrationController {
|
||||
public RegistrationListResponse getRegistrations(
|
||||
@PathVariable String userId,
|
||||
@RequestParam(required = false) String semesterId) {
|
||||
return courseRegistrationService.getRegistrations(userId, semesterId);
|
||||
return RegistrationListResponse.from(getRegistrations.execute(userId, semesterId));
|
||||
}
|
||||
|
||||
@DeleteMapping("/{registrationId}")
|
||||
@@ -67,6 +78,6 @@ public class CourseRegistrationController {
|
||||
public void cancel(
|
||||
@PathVariable String userId,
|
||||
@PathVariable String registrationId) {
|
||||
courseRegistrationService.cancel(userId, registrationId);
|
||||
cancelRegistration.execute(userId, registrationId);
|
||||
}
|
||||
}
|
||||
+13
-9
@@ -1,4 +1,4 @@
|
||||
package com.study.course_registration.controller;
|
||||
package com.study.course_registration.web.controller;
|
||||
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
import org.springframework.web.bind.annotation.GetMapping;
|
||||
@@ -7,9 +7,10 @@ import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.study.course_registration.dto.lesson.LessonDetailResponse;
|
||||
import com.study.course_registration.dto.lesson.LessonListResponse;
|
||||
import com.study.course_registration.service.LessonQueryService;
|
||||
import com.study.course_registration.application.lesson.GetLessonQuery;
|
||||
import com.study.course_registration.application.lesson.GetLessonsQuery;
|
||||
import com.study.course_registration.web.dto.lesson.LessonDetailResponse;
|
||||
import com.study.course_registration.web.dto.lesson.LessonListResponse;
|
||||
|
||||
import io.swagger.v3.oas.annotations.Operation;
|
||||
import io.swagger.v3.oas.annotations.tags.Tag;
|
||||
@@ -21,10 +22,12 @@ import jakarta.validation.constraints.Min;
|
||||
@RequestMapping("/api/v1/lessons")
|
||||
@Tag(name = "Lessons", description = "개설 강의 조회 API")
|
||||
public class LessonController {
|
||||
private final LessonQueryService lessonQueryService;
|
||||
private final GetLessonsQuery getLessons;
|
||||
private final GetLessonQuery getLesson;
|
||||
|
||||
public LessonController(LessonQueryService lessonQueryService) {
|
||||
this.lessonQueryService = lessonQueryService;
|
||||
public LessonController(GetLessonsQuery getLessons, GetLessonQuery getLesson) {
|
||||
this.getLessons = getLessons;
|
||||
this.getLesson = getLesson;
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
@@ -34,12 +37,13 @@ public class LessonController {
|
||||
@RequestParam(required = false) String subjectId,
|
||||
@RequestParam(defaultValue = "0") @Min(0) @Max(1_000_000) int page,
|
||||
@RequestParam(defaultValue = "20") @Min(1) @Max(100) int size) {
|
||||
return lessonQueryService.getLessons(semesterId, subjectId, page, size);
|
||||
return LessonListResponse.from(
|
||||
getLessons.execute(semesterId, subjectId, page, size));
|
||||
}
|
||||
|
||||
@GetMapping("/{lessonId}")
|
||||
@Operation(summary = "개설 강의 상세 조회")
|
||||
public LessonDetailResponse getLesson(@PathVariable String lessonId) {
|
||||
return lessonQueryService.getLesson(lessonId);
|
||||
return LessonDetailResponse.from(getLesson.execute(lessonId));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
package com.study.course_registration.web.dto;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.LocalTime;
|
||||
|
||||
import com.study.course_registration.application.common.ScheduleSlot;
|
||||
|
||||
public record ScheduleResponse(
|
||||
DayOfWeek dayOfWeek,
|
||||
LocalTime startTime,
|
||||
LocalTime endTime) {
|
||||
|
||||
public static ScheduleResponse from(ScheduleSlot slot) {
|
||||
return new ScheduleResponse(slot.dayOfWeek(), slot.startTime(), slot.endTime());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,45 @@
|
||||
package com.study.course_registration.web.dto.lesson;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
import com.study.course_registration.application.lesson.LessonDetailResult;
|
||||
import com.study.course_registration.web.dto.ScheduleResponse;
|
||||
import com.study.course_registration.enums.UserRole;
|
||||
|
||||
public record LessonDetailResponse(
|
||||
String lessonId,
|
||||
String lessonName,
|
||||
String subjectCode,
|
||||
String subjectName,
|
||||
String subjectDescription,
|
||||
Integer credit,
|
||||
String professorName,
|
||||
String semesterName,
|
||||
Integer capacity,
|
||||
Long enrolledCount,
|
||||
Long minGrade,
|
||||
UserRole allowedRole,
|
||||
Instant registrationStartAt,
|
||||
Instant registrationEndAt,
|
||||
List<ScheduleResponse> schedules) {
|
||||
|
||||
public static LessonDetailResponse from(LessonDetailResult result) {
|
||||
return new LessonDetailResponse(
|
||||
result.lessonId(),
|
||||
result.lessonName(),
|
||||
result.subjectCode(),
|
||||
result.subjectName(),
|
||||
result.subjectDescription(),
|
||||
result.credit(),
|
||||
result.professorName(),
|
||||
result.semesterName(),
|
||||
result.capacity(),
|
||||
result.enrolledCount(),
|
||||
result.minGrade(),
|
||||
result.allowedRole(),
|
||||
result.registrationStartAt(),
|
||||
result.registrationEndAt(),
|
||||
result.schedules().stream().map(ScheduleResponse::from).toList());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
package com.study.course_registration.web.dto.lesson;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.study.course_registration.application.lesson.LessonListResult.LessonItemResult;
|
||||
import com.study.course_registration.web.dto.ScheduleResponse;
|
||||
import com.study.course_registration.enums.UserRole;
|
||||
|
||||
public record LessonItemResponse(
|
||||
String lessonId,
|
||||
String lessonName,
|
||||
String subjectCode,
|
||||
String subjectName,
|
||||
Integer credit,
|
||||
String professorName,
|
||||
Integer capacity,
|
||||
Long enrolledCount,
|
||||
Long minGrade,
|
||||
UserRole allowedRole,
|
||||
List<ScheduleResponse> schedules) {
|
||||
|
||||
public static LessonItemResponse from(LessonItemResult result) {
|
||||
return new LessonItemResponse(
|
||||
result.lessonId(),
|
||||
result.lessonName(),
|
||||
result.subjectCode(),
|
||||
result.subjectName(),
|
||||
result.credit(),
|
||||
result.professorName(),
|
||||
result.capacity(),
|
||||
result.enrolledCount(),
|
||||
result.minGrade(),
|
||||
result.allowedRole(),
|
||||
result.schedules().stream().map(ScheduleResponse::from).toList());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
package com.study.course_registration.web.dto.lesson;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.study.course_registration.application.lesson.LessonListResult;
|
||||
|
||||
public record LessonListResponse(
|
||||
Integer page,
|
||||
Integer size,
|
||||
Long totalElements,
|
||||
List<LessonItemResponse> lessons) {
|
||||
|
||||
public static LessonListResponse from(LessonListResult result) {
|
||||
return new LessonListResponse(
|
||||
result.page(),
|
||||
result.size(),
|
||||
result.totalElements(),
|
||||
result.lessons().stream().map(LessonItemResponse::from).toList());
|
||||
}
|
||||
}
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.study.course_registration.dto.registration;
|
||||
package com.study.course_registration.web.dto.registration;
|
||||
|
||||
import jakarta.validation.constraints.NotBlank;
|
||||
|
||||
+28
@@ -0,0 +1,28 @@
|
||||
package com.study.course_registration.web.dto.registration;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
import com.study.course_registration.application.registration.RegistrationResult;
|
||||
|
||||
public record CourseRegistrationResponse(
|
||||
String registrationId,
|
||||
String userId,
|
||||
String lessonId,
|
||||
String lessonName,
|
||||
String subjectCode,
|
||||
Integer credit,
|
||||
Instant registeredAt,
|
||||
Integer totalCredits) {
|
||||
|
||||
public static CourseRegistrationResponse from(RegistrationResult result) {
|
||||
return new CourseRegistrationResponse(
|
||||
result.registrationId(),
|
||||
result.userId(),
|
||||
result.lessonId(),
|
||||
result.lessonName(),
|
||||
result.subjectCode(),
|
||||
result.credit(),
|
||||
result.registeredAt(),
|
||||
result.totalCredits());
|
||||
}
|
||||
}
|
||||
+32
@@ -0,0 +1,32 @@
|
||||
package com.study.course_registration.web.dto.registration;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.List;
|
||||
|
||||
import com.study.course_registration.application.registration.RegistrationListResult.RegistrationItemResult;
|
||||
import com.study.course_registration.web.dto.ScheduleResponse;
|
||||
|
||||
public record RegistrationItemResponse(
|
||||
String registrationId,
|
||||
String lessonId,
|
||||
String lessonName,
|
||||
String subjectCode,
|
||||
String subjectName,
|
||||
Integer credit,
|
||||
String professorName,
|
||||
List<ScheduleResponse> schedules,
|
||||
Instant registeredAt) {
|
||||
|
||||
public static RegistrationItemResponse from(RegistrationItemResult result) {
|
||||
return new RegistrationItemResponse(
|
||||
result.registrationId(),
|
||||
result.lessonId(),
|
||||
result.lessonName(),
|
||||
result.subjectCode(),
|
||||
result.subjectName(),
|
||||
result.credit(),
|
||||
result.professorName(),
|
||||
result.schedules().stream().map(ScheduleResponse::from).toList(),
|
||||
result.registeredAt());
|
||||
}
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
package com.study.course_registration.web.dto.registration;
|
||||
|
||||
import java.util.List;
|
||||
|
||||
import com.study.course_registration.application.registration.RegistrationListResult;
|
||||
|
||||
public record RegistrationListResponse(
|
||||
String userId,
|
||||
String semesterId,
|
||||
String semesterName,
|
||||
Integer totalCredits,
|
||||
Integer maxCredits,
|
||||
List<RegistrationItemResponse> registrations) {
|
||||
|
||||
public static RegistrationListResponse from(RegistrationListResult result) {
|
||||
return new RegistrationListResponse(
|
||||
result.userId(),
|
||||
result.semesterId(),
|
||||
result.semesterName(),
|
||||
result.totalCredits(),
|
||||
result.maxCredits(),
|
||||
result.registrations().stream()
|
||||
.map(RegistrationItemResponse::from)
|
||||
.toList());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,9 @@
|
||||
package com.study.course_registration.web.error;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
public record ApiErrorResponse(
|
||||
String code,
|
||||
String message,
|
||||
Instant timestamp) {
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package com.study.course_registration.web.error;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.util.concurrent.ThreadLocalRandom;
|
||||
|
||||
import org.slf4j.Logger;
|
||||
import org.slf4j.LoggerFactory;
|
||||
import org.springframework.dao.PessimisticLockingFailureException;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.http.converter.HttpMessageNotReadableException;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
|
||||
import com.study.course_registration.enums.RegistrationErrorCode;
|
||||
import com.study.course_registration.failure.ApplicationFailure;
|
||||
import com.study.course_registration.failure.RetryableInfrastructureFailure;
|
||||
import com.study.course_registration.failure.SystemInvariantViolation;
|
||||
|
||||
import jakarta.persistence.LockTimeoutException;
|
||||
import jakarta.persistence.PessimisticLockException;
|
||||
import jakarta.validation.ConstraintViolationException;
|
||||
|
||||
@RestControllerAdvice
|
||||
public class ApiExceptionHandler {
|
||||
private static final Logger log = LoggerFactory.getLogger(ApiExceptionHandler.class);
|
||||
|
||||
private final Clock clock;
|
||||
private final FailureHttpMapper httpMapper;
|
||||
private final FailureMetrics metrics;
|
||||
|
||||
public ApiExceptionHandler(Clock clock, FailureHttpMapper httpMapper, FailureMetrics metrics) {
|
||||
this.clock = clock;
|
||||
this.httpMapper = httpMapper;
|
||||
this.metrics = metrics;
|
||||
}
|
||||
|
||||
@ExceptionHandler(RetryableInfrastructureFailure.class)
|
||||
ResponseEntity<ApiErrorResponse> retryable(RetryableInfrastructureFailure failure) {
|
||||
metrics.record(failure);
|
||||
log.warn("Retryable infrastructure failure: {}", failure.getMessage());
|
||||
return lockTimeoutResponse(failure.getMessage());
|
||||
}
|
||||
|
||||
@ExceptionHandler(ApplicationFailure.class)
|
||||
ResponseEntity<ApiErrorResponse> application(ApplicationFailure failure) {
|
||||
metrics.record(failure);
|
||||
return ResponseEntity.status(httpMapper.map(failure.getErrorCode()))
|
||||
.body(body(failure.getErrorCode(), failure.getMessage()));
|
||||
}
|
||||
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
ResponseEntity<ApiErrorResponse> validation(MethodArgumentNotValidException exception) {
|
||||
String message = exception.getBindingResult().getFieldErrors().stream()
|
||||
.findFirst()
|
||||
.map(error -> error.getField() + ": " + error.getDefaultMessage())
|
||||
.orElse("요청 값이 올바르지 않습니다.");
|
||||
return badRequest(message);
|
||||
}
|
||||
|
||||
@ExceptionHandler({ConstraintViolationException.class, HttpMessageNotReadableException.class})
|
||||
ResponseEntity<ApiErrorResponse> badRequest(Exception exception) {
|
||||
return badRequest("요청 값이 올바르지 않습니다.");
|
||||
}
|
||||
|
||||
@ExceptionHandler(SystemInvariantViolation.class)
|
||||
ResponseEntity<ApiErrorResponse> invariant(SystemInvariantViolation failure) {
|
||||
metrics.record(failure);
|
||||
log.error("System invariant violation [{}]", failure.getInvariantCode(), failure);
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.body(body(RegistrationErrorCode.INTERNAL_SERVER_ERROR, "서버 내부 오류가 발생했습니다."));
|
||||
}
|
||||
|
||||
@ExceptionHandler({LockTimeoutException.class, PessimisticLockException.class, PessimisticLockingFailureException.class})
|
||||
ResponseEntity<ApiErrorResponse> rawLockTimeout(Exception exception) {
|
||||
log.warn("Persistence lock timeout: {}", exception.getMessage());
|
||||
return lockTimeoutResponse("다른 요청이 처리 중입니다. 잠시 후 다시 시도해 주세요.");
|
||||
}
|
||||
|
||||
@ExceptionHandler(Exception.class)
|
||||
ResponseEntity<ApiErrorResponse> unexpected(Exception exception) {
|
||||
log.error("Unhandled request failure", exception);
|
||||
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
|
||||
.body(body(RegistrationErrorCode.INTERNAL_SERVER_ERROR, "서버 내부 오류가 발생했습니다."));
|
||||
}
|
||||
|
||||
private ResponseEntity<ApiErrorResponse> badRequest(String message) {
|
||||
return ResponseEntity.status(HttpStatus.BAD_REQUEST)
|
||||
.body(body(RegistrationErrorCode.VALIDATION_ERROR, message));
|
||||
}
|
||||
|
||||
private ResponseEntity<ApiErrorResponse> lockTimeoutResponse(String message) {
|
||||
String retryAfter = Integer.toString(ThreadLocalRandom.current().nextInt(1, 4));
|
||||
return ResponseEntity.status(HttpStatus.SERVICE_UNAVAILABLE)
|
||||
.header(HttpHeaders.RETRY_AFTER, retryAfter)
|
||||
.body(body(RegistrationErrorCode.LOCK_TIMEOUT, message));
|
||||
}
|
||||
|
||||
private ApiErrorResponse body(RegistrationErrorCode code, String message) {
|
||||
return new ApiErrorResponse(code.name(), message, clock.instant());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
package com.study.course_registration.web.error;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.study.course_registration.enums.RegistrationErrorCode;
|
||||
|
||||
@Component
|
||||
public class FailureHttpMapper {
|
||||
public HttpStatus map(RegistrationErrorCode code) {
|
||||
return switch (code) {
|
||||
case VALIDATION_ERROR -> HttpStatus.BAD_REQUEST;
|
||||
case USER_NOT_FOUND, LESSON_NOT_FOUND, SEMESTER_NOT_FOUND, REGISTRATION_NOT_FOUND ->
|
||||
HttpStatus.NOT_FOUND;
|
||||
case NOT_ELIGIBLE_GRADE, NOT_ELIGIBLE_ROLE, REGISTRATION_FORBIDDEN ->
|
||||
HttpStatus.FORBIDDEN;
|
||||
case REGISTRATION_PERIOD_CLOSED, ALREADY_REGISTERED, DUPLICATE_SUBJECT,
|
||||
SCHEDULE_CONFLICT, CREDIT_LIMIT_EXCEEDED, CAPACITY_EXCEEDED,
|
||||
IDEMPOTENCY_KEY_REUSED -> HttpStatus.CONFLICT;
|
||||
case LOCK_TIMEOUT -> HttpStatus.SERVICE_UNAVAILABLE;
|
||||
case INTERNAL_SERVER_ERROR -> HttpStatus.INTERNAL_SERVER_ERROR;
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package com.study.course_registration.web.error;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.study.course_registration.failure.ApplicationFailure;
|
||||
import com.study.course_registration.failure.BusinessRejection;
|
||||
import com.study.course_registration.failure.RetryableInfrastructureFailure;
|
||||
import com.study.course_registration.failure.SystemInvariantViolation;
|
||||
|
||||
import io.micrometer.core.instrument.MeterRegistry;
|
||||
|
||||
@Component
|
||||
public class FailureMetrics {
|
||||
private final MeterRegistry registry;
|
||||
|
||||
public FailureMetrics(MeterRegistry registry) {
|
||||
this.registry = registry;
|
||||
}
|
||||
|
||||
public void record(ApplicationFailure failure) {
|
||||
String category = failure instanceof BusinessRejection
|
||||
? "business_rejection"
|
||||
: failure instanceof RetryableInfrastructureFailure
|
||||
? "retryable_infrastructure"
|
||||
: "application_failure";
|
||||
registry.counter(
|
||||
"application_failure_total",
|
||||
"category", category,
|
||||
"reason", failure.getErrorCode().name().toLowerCase())
|
||||
.increment();
|
||||
}
|
||||
|
||||
public void record(SystemInvariantViolation failure) {
|
||||
registry.counter(
|
||||
"system_invariant_violation_total",
|
||||
"reason", failure.getInvariantCode().name().toLowerCase())
|
||||
.increment();
|
||||
}
|
||||
}
|
||||
@@ -4,60 +4,88 @@ import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes;
|
||||
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;
|
||||
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noFields;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
import com.tngtech.archunit.core.domain.JavaClasses;
|
||||
import com.tngtech.archunit.core.importer.ClassFileImporter;
|
||||
|
||||
import java.nio.file.Path;
|
||||
|
||||
import jakarta.persistence.ManyToMany;
|
||||
import jakarta.persistence.OneToMany;
|
||||
import jakarta.persistence.OneToOne;
|
||||
|
||||
class ArchitectureTest {
|
||||
@Test
|
||||
@DisplayName("수강신청 mutation → RegistrationLockManager 의존")
|
||||
void registrationMutationUsesLockBoundary() {
|
||||
JavaClasses classes = new ClassFileImporter().importPath(Path.of("build/classes/java/main"));
|
||||
private final JavaClasses classes =
|
||||
new ClassFileImporter().importPath(Path.of("build/classes/java/main"));
|
||||
|
||||
@Test
|
||||
@DisplayName("수강신청 UseCase → RegistrationContextLoader port 의존")
|
||||
void registrationMutationUsesContextPort() {
|
||||
classes()
|
||||
.that().haveSimpleName("CourseRegistrationService")
|
||||
.should().dependOnClassesThat().haveSimpleName("RegistrationLockManager")
|
||||
.that().haveSimpleName("RegisterCourseUseCase")
|
||||
.should().dependOnClassesThat().haveSimpleName("RegistrationContextLoader")
|
||||
.check(classes);
|
||||
|
||||
noClasses()
|
||||
.that().haveSimpleName("CourseRegistrationService")
|
||||
.should().dependOnClassesThat().haveSimpleName("LessonRepository")
|
||||
classes()
|
||||
.that().haveSimpleName("CancelRegistrationUseCase")
|
||||
.should().dependOnClassesThat().haveSimpleName("RegistrationContextLoader")
|
||||
.check(classes);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("새 service → registration write repository 우회 금지")
|
||||
void registrationWriteRepositoriesStayInsideApprovedServices() {
|
||||
JavaClasses classes = new ClassFileImporter().importPath(Path.of("build/classes/java/main"));
|
||||
|
||||
@DisplayName("application → Spring Data JPA·repository·web 표현 의존 금지")
|
||||
void applicationDoesNotKnowPersistenceMechanismOrWebRepresentation() {
|
||||
noClasses()
|
||||
.that().resideInAPackage("..service..")
|
||||
.and().doNotHaveSimpleName("CourseRegistrationService")
|
||||
.and().doNotHaveSimpleName("LessonQueryService")
|
||||
.should().dependOnClassesThat().haveSimpleName("UserLessonRepository")
|
||||
.that().resideInAPackage("..application..")
|
||||
.should().dependOnClassesThat().resideInAnyPackage(
|
||||
"..repository..",
|
||||
"org.springframework.data..",
|
||||
"jakarta.persistence..",
|
||||
"..web..",
|
||||
"..dto..")
|
||||
.check(classes);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("domain → application·infrastructure·web·repository 의존 금지")
|
||||
void domainStaysInsideDomainBoundary() {
|
||||
noClasses()
|
||||
.that().resideInAPackage("..service..")
|
||||
.and().doNotHaveSimpleName("CourseRegistrationService")
|
||||
.and().doNotHaveSimpleName("IdempotencyRetentionJob")
|
||||
.should().dependOnClassesThat().haveSimpleName("RegistrationIdempotencyRepository")
|
||||
.that().resideInAPackage("..domain..")
|
||||
.should().dependOnClassesThat().resideInAnyPackage(
|
||||
"..application..",
|
||||
"..infrastructure..",
|
||||
"..web..",
|
||||
"..repository..",
|
||||
"org.springframework.data..",
|
||||
"jakarta.persistence..")
|
||||
.check(classes);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("web → repository·infrastructure 직접 접근 금지")
|
||||
void webDependsOnApplicationBoundary() {
|
||||
noClasses()
|
||||
.that().resideInAPackage("..web..")
|
||||
.should().dependOnClassesThat().resideInAnyPackage(
|
||||
"..repository..",
|
||||
"..infrastructure..")
|
||||
.check(classes);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("JPA repository → infrastructure 밖 application에서 직접 참조 금지")
|
||||
void rawRepositoriesStayBehindInfrastructureAdapters() {
|
||||
noClasses()
|
||||
.that().resideInAPackage("..application..")
|
||||
.should().dependOnClassesThat().resideInAPackage("..repository..")
|
||||
.check(classes);
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("엔티티 연관관계 → ManyToOne만 허용")
|
||||
void entityAssociationsUseManyToOneOnly() {
|
||||
JavaClasses classes = new ClassFileImporter().importPath(Path.of("build/classes/java/main"));
|
||||
|
||||
noFields()
|
||||
.that().areDeclaredInClassesThat().resideInAPackage("..entity..")
|
||||
.should().beAnnotatedWith(OneToOne.class)
|
||||
|
||||
+3
-1
@@ -16,6 +16,7 @@ import org.springframework.test.web.servlet.MockMvc;
|
||||
import com.study.course_registration.entity.Lesson;
|
||||
import com.study.course_registration.entity.Subject;
|
||||
import com.study.course_registration.enums.RegistrationErrorCode;
|
||||
import com.study.course_registration.web.error.FailureHttpMapper;
|
||||
import com.study.course_registration.support.CourseIntegrationTest;
|
||||
import com.study.course_registration.support.Rejections;
|
||||
import com.study.course_registration.support.Scenario;
|
||||
@@ -30,6 +31,7 @@ import com.study.course_registration.support.http.JsonBody;
|
||||
@AutoConfigureMockMvc
|
||||
@DisplayName("수강신청 API")
|
||||
class CourseRegistrationApiTest {
|
||||
private static final FailureHttpMapper HTTP = new FailureHttpMapper();
|
||||
private static final Rejections<ApiError, RegistrationErrorCode> API =
|
||||
Rejections.of(ApiError.class, CourseRegistrationApiTest::errorCodeOf);
|
||||
|
||||
@@ -270,7 +272,7 @@ class CourseRegistrationApiTest {
|
||||
|
||||
private static RegistrationErrorCode errorCodeOf(ApiError error) {
|
||||
RegistrationErrorCode code = RegistrationErrorCode.valueOf(error.code());
|
||||
assertThat(error.status()).isEqualTo(code.getStatus().value());
|
||||
assertThat(error.status()).isEqualTo(HTTP.map(code).value());
|
||||
return code;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -10,6 +10,7 @@ import org.springframework.boot.webmvc.test.autoconfigure.AutoConfigureMockMvc;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import com.study.course_registration.enums.RegistrationErrorCode;
|
||||
import com.study.course_registration.web.error.FailureHttpMapper;
|
||||
import com.study.course_registration.support.CourseIntegrationTest;
|
||||
import com.study.course_registration.support.Rejections;
|
||||
import com.study.course_registration.support.Scenario;
|
||||
@@ -23,6 +24,7 @@ import com.study.course_registration.support.http.JsonBody;
|
||||
@AutoConfigureMockMvc
|
||||
@DisplayName("강의 API")
|
||||
class LessonApiTest {
|
||||
private static final FailureHttpMapper HTTP = new FailureHttpMapper();
|
||||
private static final Rejections<ApiError, RegistrationErrorCode> API =
|
||||
Rejections.of(ApiError.class, LessonApiTest::errorCodeOf);
|
||||
|
||||
@@ -102,7 +104,7 @@ class LessonApiTest {
|
||||
|
||||
private static RegistrationErrorCode errorCodeOf(ApiError error) {
|
||||
RegistrationErrorCode code = RegistrationErrorCode.valueOf(error.code());
|
||||
assertThat(error.status()).isEqualTo(code.getStatus().value());
|
||||
assertThat(error.status()).isEqualTo(HTTP.map(code).value());
|
||||
return code;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,41 +0,0 @@
|
||||
package com.study.course_registration.exception;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.ZoneOffset;
|
||||
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.springframework.http.HttpHeaders;
|
||||
import org.springframework.http.ResponseEntity;
|
||||
|
||||
import com.study.course_registration.support.fixture.TestData;
|
||||
|
||||
import jakarta.persistence.LockTimeoutException;
|
||||
|
||||
class GlobalExceptionHandlerTest {
|
||||
private final GlobalExceptionHandler handler =
|
||||
new GlobalExceptionHandler(Clock.fixed(TestData.NOW, ZoneOffset.UTC));
|
||||
|
||||
@Test
|
||||
@DisplayName("락 타임아웃 → 503 + Retry-After")
|
||||
void lockTimeout() {
|
||||
ResponseEntity<ErrorResponse> response = handler.handleLockTimeout(new LockTimeoutException());
|
||||
|
||||
assertThat(response.getStatusCode().value()).isEqualTo(503);
|
||||
assertThat(Integer.parseInt(response.getHeaders().getFirst(HttpHeaders.RETRY_AFTER)))
|
||||
.isBetween(1, 3);
|
||||
assertThat(response.getBody().code()).isEqualTo("LOCK_TIMEOUT");
|
||||
}
|
||||
|
||||
@Test
|
||||
@DisplayName("예상 못한 예외 → 500 공통 에러")
|
||||
void fallback() {
|
||||
ResponseEntity<ErrorResponse> response = handler.handleUnexpected(new RuntimeException("boom"));
|
||||
|
||||
assertThat(response.getStatusCode().value()).isEqualTo(500);
|
||||
assertThat(response.getBody().code()).isEqualTo("INTERNAL_SERVER_ERROR");
|
||||
assertThat(response.getBody().timestamp()).isEqualTo(TestData.NOW);
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.study.course_registration.repository;
|
||||
package com.study.course_registration.infrastructure.persistence.repository;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.study.course_registration.repository;
|
||||
package com.study.course_registration.infrastructure.persistence.repository;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.study.course_registration.repository;
|
||||
package com.study.course_registration.infrastructure.persistence.repository;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.study.course_registration.repository;
|
||||
package com.study.course_registration.infrastructure.persistence.repository;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
|
||||
|
||||
+1
-1
@@ -1,4 +1,4 @@
|
||||
package com.study.course_registration.repository;
|
||||
package com.study.course_registration.infrastructure.persistence.repository;
|
||||
|
||||
import static org.assertj.core.api.Assertions.assertThat;
|
||||
import static org.assertj.core.api.Assertions.assertThatThrownBy;
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
package com.study.course_registration.repository;
|
||||
package com.study.course_registration.infrastructure.persistence.repository;
|
||||
|
||||
import org.junit.jupiter.api.BeforeEach;
|
||||
import org.junit.jupiter.api.DisplayName;
|
||||
|
||||
@@ -10,9 +10,9 @@ import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.ActiveProfiles;
|
||||
|
||||
import com.study.course_registration.entity.Semester;
|
||||
import com.study.course_registration.repository.LessonRepository;
|
||||
import com.study.course_registration.repository.SemesterRepository;
|
||||
import com.study.course_registration.repository.UserRepository;
|
||||
import com.study.course_registration.infrastructure.persistence.repository.LessonRepository;
|
||||
import com.study.course_registration.infrastructure.persistence.repository.SemesterRepository;
|
||||
import com.study.course_registration.infrastructure.persistence.repository.UserRepository;
|
||||
|
||||
@SpringBootTest
|
||||
@ActiveProfiles("local")
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user