refactor: 테스트 GWT로 통일해서 사용할 수 있도록 구성 및 서브에이전트 파일 수정
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
package com.study.course_registration.config;
|
||||
|
||||
import java.time.DayOfWeek;
|
||||
import jakarta.persistence.AttributeConverter;
|
||||
import jakarta.persistence.Converter;
|
||||
|
||||
@Converter(autoApply = true)
|
||||
public class DayOfWeekConverter implements AttributeConverter<DayOfWeek, Integer> {
|
||||
public Integer convertToDatabaseColumn(DayOfWeek day) { return day == null ? null : day.getValue(); }
|
||||
public DayOfWeek convertToEntityAttribute(Integer value) { return value == null ? null : DayOfWeek.of(value); }
|
||||
}
|
||||
@@ -1,10 +1,19 @@
|
||||
package com.study.course_registration.config;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.util.Optional;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.data.auditing.DateTimeProvider;
|
||||
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
|
||||
import org.springframework.scheduling.annotation.EnableScheduling;
|
||||
|
||||
@Configuration
|
||||
@EnableJpaAuditing
|
||||
@Configuration
|
||||
@EnableJpaAuditing(dateTimeProviderRef = "auditingDateTimeProvider")
|
||||
@EnableScheduling
|
||||
public class JpaConfig {
|
||||
|
||||
@Bean
|
||||
DateTimeProvider auditingDateTimeProvider(Clock clock) {
|
||||
return () -> Optional.of(clock.instant());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
package com.study.course_registration.config;
|
||||
|
||||
import java.util.Arrays;
|
||||
import java.util.Set;
|
||||
|
||||
import org.springframework.beans.factory.config.BeanFactoryPostProcessor;
|
||||
import org.springframework.context.annotation.Bean;
|
||||
import org.springframework.context.annotation.Configuration;
|
||||
import org.springframework.core.env.Environment;
|
||||
|
||||
@Configuration(proxyBeanMethods = false)
|
||||
public class RuntimeProfileConfig {
|
||||
private static final Set<String> ENVIRONMENT_PROFILES = Set.of("local", "dev", "prod");
|
||||
private static final String TEST_PROFILE = "test";
|
||||
|
||||
@Bean
|
||||
static BeanFactoryPostProcessor runtimeProfileGuard(Environment environment) {
|
||||
requireValidProfiles(environment.getActiveProfiles());
|
||||
return beanFactory -> {};
|
||||
}
|
||||
|
||||
static void requireValidProfiles(String[] activeProfiles) {
|
||||
long environmentCount = Arrays.stream(activeProfiles)
|
||||
.filter(ENVIRONMENT_PROFILES::contains)
|
||||
.count();
|
||||
boolean testActive = Arrays.asList(activeProfiles).contains(TEST_PROFILE);
|
||||
|
||||
if (testActive && environmentCount == 0) {
|
||||
return;
|
||||
}
|
||||
if (!testActive && environmentCount == 1) {
|
||||
return;
|
||||
}
|
||||
throw new IllegalStateException(
|
||||
"local, dev, prod 중 정확히 하나의 환경 profile을 활성화해야 하며 test와 함께 사용할 수 없습니다.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package com.study.course_registration.config;
|
||||
|
||||
import com.study.course_registration.enums.UserRole;
|
||||
import jakarta.persistence.AttributeConverter;
|
||||
import jakarta.persistence.Converter;
|
||||
|
||||
@Converter(autoApply = true)
|
||||
public class UserRoleConverter implements AttributeConverter<UserRole, String> {
|
||||
public String convertToDatabaseColumn(UserRole role) { return role == null ? null : role.name(); }
|
||||
public UserRole convertToEntityAttribute(String value) { return value == null ? null : UserRole.valueOf(value); }
|
||||
}
|
||||
+3
-1
@@ -7,6 +7,7 @@ import org.springframework.web.bind.annotation.GetMapping;
|
||||
import org.springframework.web.bind.annotation.PathVariable;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RequestHeader;
|
||||
import org.springframework.web.bind.annotation.RequestMapping;
|
||||
import org.springframework.web.bind.annotation.RequestParam;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
@@ -47,8 +48,9 @@ public class CourseRegistrationController {
|
||||
})
|
||||
public CourseRegistrationResponse register(
|
||||
@PathVariable String userId,
|
||||
@RequestHeader(name = "Idempotency-Key", required = false) String idempotencyKey,
|
||||
@Valid @RequestBody CourseRegistrationRequest request) {
|
||||
return courseRegistrationService.register(userId, request);
|
||||
return courseRegistrationService.register(userId, request, idempotencyKey);
|
||||
}
|
||||
|
||||
@GetMapping
|
||||
|
||||
@@ -32,7 +32,7 @@ public class LessonController {
|
||||
public LessonListResponse getLessons(
|
||||
@RequestParam(required = false) String semesterId,
|
||||
@RequestParam(required = false) String subjectId,
|
||||
@RequestParam(defaultValue = "0") @Min(0) int page,
|
||||
@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);
|
||||
}
|
||||
|
||||
@@ -1,24 +0,0 @@
|
||||
package com.study.course_registration.entity;
|
||||
|
||||
import java.time.Instant;
|
||||
|
||||
import jakarta.persistence.MappedSuperclass;
|
||||
import lombok.Getter;
|
||||
|
||||
@MappedSuperclass
|
||||
@Getter
|
||||
public class BaseDeleteEntity {
|
||||
private Instant deletedAt;
|
||||
|
||||
public void delete() {
|
||||
this.deletedAt = Instant.now();
|
||||
}
|
||||
|
||||
public void restore() {
|
||||
this.deletedAt = null;
|
||||
}
|
||||
|
||||
public boolean isDeleted() {
|
||||
return this.deletedAt != null;
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,11 @@
|
||||
package com.study.course_registration.entity;
|
||||
|
||||
import java.util.UUID;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Id;
|
||||
import jakarta.persistence.MappedSuperclass;
|
||||
import jakarta.persistence.PrePersist;
|
||||
import jakarta.persistence.Version;
|
||||
import lombok.Getter;
|
||||
|
||||
@Getter
|
||||
@@ -15,17 +15,15 @@ public abstract class BaseEntity {
|
||||
@Column(length = 36, nullable = false, updatable = false)
|
||||
private String id;
|
||||
|
||||
protected BaseEntity() {
|
||||
}
|
||||
@Version
|
||||
@Column(nullable = false)
|
||||
private Long version;
|
||||
|
||||
protected BaseEntity(String id) {
|
||||
this.id = id;
|
||||
}
|
||||
protected BaseEntity() {}
|
||||
protected BaseEntity(String id) { this.id = id; }
|
||||
|
||||
@PrePersist
|
||||
protected void assignId() {
|
||||
if (id == null) {
|
||||
id = UUID.randomUUID().toString();
|
||||
}
|
||||
if (id == null) id = UUID.randomUUID().toString();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,18 +6,17 @@ import com.study.course_registration.enums.UserRole;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.EnumType;
|
||||
import jakarta.persistence.Enumerated;
|
||||
import jakarta.persistence.FetchType;
|
||||
import jakarta.persistence.ForeignKey;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Entity
|
||||
@NoArgsConstructor
|
||||
@NoArgsConstructor(access = AccessLevel.PROTECTED)
|
||||
@Getter
|
||||
@Table(name = "lessons")
|
||||
public class Lesson extends BaseTimeZoneEntity {
|
||||
@@ -42,7 +41,6 @@ public class Lesson extends BaseTimeZoneEntity {
|
||||
@Column(name = "min_grade")
|
||||
private Long minGrade;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(name = "allowed_role")
|
||||
private UserRole allowedRole;
|
||||
|
||||
|
||||
@@ -6,26 +6,24 @@ import java.util.Objects;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.EnumType;
|
||||
import jakarta.persistence.Enumerated;
|
||||
import jakarta.persistence.FetchType;
|
||||
import jakarta.persistence.ForeignKey;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Entity
|
||||
@Getter
|
||||
@NoArgsConstructor
|
||||
@NoArgsConstructor(access = AccessLevel.PROTECTED)
|
||||
@Table(name = "lesson_schedules")
|
||||
public class LessonSchedule extends BaseTimeZoneEntity {
|
||||
@ManyToOne(fetch = FetchType.LAZY, optional = false)
|
||||
@JoinColumn(name = "lesson_id", nullable = false, foreignKey = @ForeignKey(name = "fk_schedule_lesson"))
|
||||
private Lesson lesson;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(nullable = false, length = 16)
|
||||
private DayOfWeek dayOfWeek;
|
||||
|
||||
|
||||
@@ -3,11 +3,12 @@ package com.study.course_registration.entity;
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Entity
|
||||
@NoArgsConstructor
|
||||
@NoArgsConstructor(access = AccessLevel.PROTECTED)
|
||||
@Getter
|
||||
@Table(name = "professors")
|
||||
public class Professor extends BaseTimeZoneEntity {
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
package com.study.course_registration.entity;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Objects;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.FetchType;
|
||||
import jakarta.persistence.ForeignKey;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
import jakarta.persistence.Table;
|
||||
import jakarta.persistence.UniqueConstraint;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Entity
|
||||
@Getter
|
||||
@NoArgsConstructor(access = AccessLevel.PROTECTED)
|
||||
@Table(name = "registration_idempotencies",
|
||||
uniqueConstraints = @UniqueConstraint(
|
||||
name = "uk_registration_idempotency",
|
||||
columnNames = {"user_id", "idempotency_key"}))
|
||||
public class RegistrationIdempotency extends BaseCreateEntity {
|
||||
@ManyToOne(fetch = FetchType.LAZY, optional = false)
|
||||
@JoinColumn(name = "user_id", nullable = false, foreignKey = @ForeignKey(name = "fk_idempotency_user"))
|
||||
private User user;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY, optional = false)
|
||||
@JoinColumn(name = "lesson_id", nullable = false, foreignKey = @ForeignKey(name = "fk_idempotency_lesson"))
|
||||
private Lesson lesson;
|
||||
|
||||
@ManyToOne(fetch = FetchType.LAZY, optional = false)
|
||||
@JoinColumn(
|
||||
name = "registration_id",
|
||||
nullable = false,
|
||||
foreignKey = @ForeignKey(name = "fk_idempotency_registration"))
|
||||
private UserLesson registration;
|
||||
|
||||
@Column(name = "idempotency_key", nullable = false, length = 100)
|
||||
private String idempotencyKey;
|
||||
|
||||
@Column(name = "total_credits", nullable = false)
|
||||
private Integer totalCredits;
|
||||
|
||||
@Column(name = "expires_at", nullable = false)
|
||||
private Instant expiresAt;
|
||||
|
||||
public RegistrationIdempotency(
|
||||
User user,
|
||||
Lesson lesson,
|
||||
UserLesson registration,
|
||||
String idempotencyKey,
|
||||
Integer totalCredits,
|
||||
Instant expiresAt) {
|
||||
this.user = Objects.requireNonNull(user, "user");
|
||||
this.lesson = Objects.requireNonNull(lesson, "lesson");
|
||||
this.registration = Objects.requireNonNull(registration, "registration");
|
||||
if (idempotencyKey == null || idempotencyKey.isBlank() || idempotencyKey.length() > 100) {
|
||||
throw new IllegalArgumentException("idempotencyKey length must be 1..100");
|
||||
}
|
||||
this.idempotencyKey = idempotencyKey;
|
||||
this.totalCredits = Objects.requireNonNull(totalCredits, "totalCredits");
|
||||
this.expiresAt = Objects.requireNonNull(expiresAt, "expiresAt");
|
||||
}
|
||||
}
|
||||
@@ -8,12 +8,13 @@ import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Table;
|
||||
import jakarta.persistence.UniqueConstraint;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Entity
|
||||
@Getter
|
||||
@NoArgsConstructor
|
||||
@NoArgsConstructor(access = AccessLevel.PROTECTED)
|
||||
@Table(name = "semesters", uniqueConstraints = @UniqueConstraint(name = "uk_semester_name", columnNames = "name"))
|
||||
public class Semester extends BaseTimeZoneEntity {
|
||||
@Column(nullable = false)
|
||||
|
||||
@@ -4,11 +4,12 @@ import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.Table;
|
||||
import jakarta.persistence.UniqueConstraint;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Entity
|
||||
@NoArgsConstructor
|
||||
@NoArgsConstructor(access = AccessLevel.PROTECTED)
|
||||
@Getter
|
||||
@Table(name = "subjects", uniqueConstraints = @UniqueConstraint(name = "uk_subject_code", columnNames = "code"))
|
||||
public class Subject extends BaseTimeZoneEntity {
|
||||
|
||||
@@ -6,15 +6,14 @@ import com.study.course_registration.enums.UserRole;
|
||||
|
||||
import jakarta.persistence.Column;
|
||||
import jakarta.persistence.Entity;
|
||||
import jakarta.persistence.EnumType;
|
||||
import jakarta.persistence.Enumerated;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Entity
|
||||
@Getter
|
||||
@NoArgsConstructor
|
||||
@NoArgsConstructor(access = AccessLevel.PROTECTED)
|
||||
@Table(name = "users")
|
||||
public class User extends BaseTimeZoneEntity {
|
||||
@Column(nullable = false)
|
||||
@@ -23,7 +22,6 @@ public class User extends BaseTimeZoneEntity {
|
||||
@Column(nullable = false)
|
||||
private Long grade;
|
||||
|
||||
@Enumerated(EnumType.STRING)
|
||||
@Column(nullable = false)
|
||||
private UserRole role;
|
||||
|
||||
|
||||
@@ -10,11 +10,12 @@ import jakarta.persistence.ForeignKey;
|
||||
import jakarta.persistence.JoinColumn;
|
||||
import jakarta.persistence.ManyToOne;
|
||||
import jakarta.persistence.Table;
|
||||
import lombok.AccessLevel;
|
||||
import lombok.Getter;
|
||||
import lombok.NoArgsConstructor;
|
||||
|
||||
@Entity
|
||||
@NoArgsConstructor
|
||||
@NoArgsConstructor(access = AccessLevel.PROTECTED)
|
||||
@Getter
|
||||
@Table(name = "user_lessons")
|
||||
public class UserLesson extends BaseCreateEntity {
|
||||
|
||||
@@ -17,8 +17,9 @@ public enum RegistrationErrorCode {
|
||||
SCHEDULE_CONFLICT(HttpStatus.CONFLICT),
|
||||
CREDIT_LIMIT_EXCEEDED(HttpStatus.CONFLICT),
|
||||
CAPACITY_EXCEEDED(HttpStatus.CONFLICT),
|
||||
ALREADY_CANCELED(HttpStatus.CONFLICT),
|
||||
LOCK_TIMEOUT(HttpStatus.SERVICE_UNAVAILABLE);
|
||||
IDEMPOTENCY_KEY_REUSED(HttpStatus.CONFLICT),
|
||||
LOCK_TIMEOUT(HttpStatus.SERVICE_UNAVAILABLE),
|
||||
INTERNAL_SERVER_ERROR(HttpStatus.INTERNAL_SERVER_ERROR);
|
||||
|
||||
private final HttpStatus status;
|
||||
|
||||
|
||||
@@ -1,54 +1,55 @@
|
||||
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;
|
||||
}
|
||||
public GlobalExceptionHandler(Clock clock) { this.clock=clock; }
|
||||
|
||||
@ExceptionHandler(RegistrationException.class)
|
||||
ResponseEntity<ErrorResponse> handleRegistrationException(RegistrationException exception) {
|
||||
return response(exception.getErrorCode(), exception.getMessage());
|
||||
}
|
||||
ResponseEntity<ErrorResponse> registration(RegistrationException e) { return response(e.getErrorCode(),e.getMessage()); }
|
||||
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
ResponseEntity<ErrorResponse> handleValidation(MethodArgumentNotValidException exception) {
|
||||
String message = exception.getBindingResult().getFieldErrors().stream()
|
||||
.findFirst()
|
||||
.map(error -> error.getField() + ": " + error.getDefaultMessage())
|
||||
.orElse("요청 값이 올바르지 않습니다.");
|
||||
return response(RegistrationErrorCode.VALIDATION_ERROR, message);
|
||||
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> handleBadRequest(Exception exception) {
|
||||
return response(RegistrationErrorCode.VALIDATION_ERROR, "요청 값이 올바르지 않습니다.");
|
||||
@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({LockTimeoutException.class, PessimisticLockException.class, PessimisticLockingFailureException.class})
|
||||
ResponseEntity<ErrorResponse> handleLockTimeout(Exception exception) {
|
||||
return response(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(new ErrorResponse(code.name(), message, clock.instant()));
|
||||
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()); }
|
||||
}
|
||||
|
||||
+38
@@ -0,0 +1,38 @@
|
||||
package com.study.course_registration.repository;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.util.Optional;
|
||||
|
||||
import org.springframework.data.jpa.repository.EntityGraph;
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
import org.springframework.data.jpa.repository.Modifying;
|
||||
import org.springframework.data.jpa.repository.Query;
|
||||
import org.springframework.data.repository.query.Param;
|
||||
|
||||
import com.study.course_registration.entity.RegistrationIdempotency;
|
||||
|
||||
public interface RegistrationIdempotencyRepository extends JpaRepository<RegistrationIdempotency, String> {
|
||||
@EntityGraph(attributePaths = {
|
||||
"user", "lesson", "lesson.subject", "registration"
|
||||
})
|
||||
Optional<RegistrationIdempotency> findByUser_IdAndIdempotencyKeyAndExpiresAtAfter(
|
||||
String userId,
|
||||
String idempotencyKey,
|
||||
Instant now);
|
||||
|
||||
@Modifying
|
||||
@Query("""
|
||||
delete from RegistrationIdempotency value
|
||||
where value.user.id = :userId
|
||||
and value.idempotencyKey = :idempotencyKey
|
||||
and value.expiresAt <= :now
|
||||
""")
|
||||
int deleteExpiredKey(
|
||||
@Param("userId") String userId,
|
||||
@Param("idempotencyKey") String idempotencyKey,
|
||||
@Param("now") Instant now);
|
||||
|
||||
@Modifying
|
||||
@Query("delete from RegistrationIdempotency value where value.expiresAt <= :now")
|
||||
int deleteExpired(@Param("now") Instant now);
|
||||
}
|
||||
@@ -1,13 +1,17 @@
|
||||
package com.study.course_registration.repository;
|
||||
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.util.Optional;
|
||||
import java.util.List;
|
||||
|
||||
import org.springframework.data.jpa.repository.JpaRepository;
|
||||
|
||||
import com.study.course_registration.entity.Semester;
|
||||
|
||||
public interface SemesterRepository extends JpaRepository<Semester, String> {
|
||||
Optional<Semester> findFirstByStartDateLessThanEqualAndEndDateGreaterThanEqualOrderByStartDateDesc(
|
||||
List<Semester> findByStartDateLessThanEqualAndEndDateGreaterThanEqual(
|
||||
LocalDate startDate, LocalDate endDate);
|
||||
|
||||
List<Semester> findByRegistrationStartAtLessThanEqualAndRegistrationEndAtGreaterThanEqual(
|
||||
Instant startAt, Instant endAt);
|
||||
}
|
||||
|
||||
@@ -1,14 +1,18 @@
|
||||
package com.study.course_registration.seeder;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.DayOfWeek;
|
||||
import java.time.Instant;
|
||||
import java.time.LocalDate;
|
||||
import java.time.LocalTime;
|
||||
import java.util.ArrayList;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
|
||||
import org.springframework.boot.CommandLineRunner;
|
||||
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
|
||||
import org.springframework.context.annotation.Profile;
|
||||
import org.springframework.jdbc.core.JdbcTemplate;
|
||||
import org.springframework.stereotype.Component;
|
||||
import org.springframework.transaction.annotation.Transactional;
|
||||
|
||||
@@ -19,14 +23,12 @@ 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.repository.LessonRepository;
|
||||
import com.study.course_registration.repository.LessonScheduleRepository;
|
||||
import com.study.course_registration.repository.ProfessorRepository;
|
||||
import com.study.course_registration.repository.SemesterRepository;
|
||||
import com.study.course_registration.repository.SubjectRepository;
|
||||
import com.study.course_registration.repository.UserRepository;
|
||||
import com.study.course_registration.service.policy.LessonSchedulePolicy;
|
||||
|
||||
import jakarta.persistence.EntityManager;
|
||||
|
||||
@Component
|
||||
@Profile({"local", "dev"})
|
||||
@ConditionalOnProperty(name = "app.seed.enabled", havingValue = "true")
|
||||
public class DataSeeder implements CommandLineRunner {
|
||||
public static final String SEMESTER_ID = "00000000-0000-0000-0000-000000000001";
|
||||
@@ -41,81 +43,77 @@ public class DataSeeder implements CommandLineRunner {
|
||||
public static final String POSTGRADUATE_ONLY_ID = "40000000-0000-0000-0000-000000000006";
|
||||
public static final String BOUNDARY_LESSON_ID = "40000000-0000-0000-0000-000000000007";
|
||||
|
||||
private final Clock clock;
|
||||
private final SemesterRepository semesterRepository;
|
||||
private final ProfessorRepository professorRepository;
|
||||
private final SubjectRepository subjectRepository;
|
||||
private final LessonRepository lessonRepository;
|
||||
private final LessonScheduleRepository lessonScheduleRepository;
|
||||
private final UserRepository userRepository;
|
||||
private final JdbcTemplate jdbcTemplate;
|
||||
private final EntityManager entityManager;
|
||||
private final LessonSchedulePolicy schedulePolicy;
|
||||
|
||||
public DataSeeder(Clock clock,
|
||||
SemesterRepository semesterRepository,
|
||||
ProfessorRepository professorRepository,
|
||||
SubjectRepository subjectRepository,
|
||||
LessonRepository lessonRepository,
|
||||
LessonScheduleRepository lessonScheduleRepository,
|
||||
UserRepository userRepository) {
|
||||
this.clock = clock;
|
||||
this.semesterRepository = semesterRepository;
|
||||
this.professorRepository = professorRepository;
|
||||
this.subjectRepository = subjectRepository;
|
||||
this.lessonRepository = lessonRepository;
|
||||
this.lessonScheduleRepository = lessonScheduleRepository;
|
||||
this.userRepository = userRepository;
|
||||
public DataSeeder(JdbcTemplate jdbcTemplate, EntityManager entityManager, LessonSchedulePolicy schedulePolicy) {
|
||||
this.jdbcTemplate = jdbcTemplate;
|
||||
this.entityManager = entityManager;
|
||||
this.schedulePolicy = schedulePolicy;
|
||||
}
|
||||
|
||||
@Override
|
||||
@Transactional
|
||||
public void run(String... args) {
|
||||
if (semesterRepository.existsById(SEMESTER_ID)) {
|
||||
jdbcTemplate.queryForObject(
|
||||
"select name from seed_locks where name = ? for update",
|
||||
String.class, "demo-dataset");
|
||||
if (entityManager.find(Semester.class, SEMESTER_ID) != null) {
|
||||
return;
|
||||
}
|
||||
|
||||
Instant now = clock.instant();
|
||||
LocalDate today = LocalDate.now(clock);
|
||||
Semester semester = semesterRepository.save(new Semester(
|
||||
SEMESTER_ID, "2026-1", today.minusDays(30), today.plusDays(120),
|
||||
now.minusSeconds(86_400), now.plusSeconds(7 * 86_400), 18));
|
||||
Map<String, Semester> semesters = new LinkedHashMap<>();
|
||||
for (SeedTable.Row row : SeedTable.read("seed/demo/semesters.tsv")) {
|
||||
Semester semester = new Semester(row.text("id"), row.text("name"),
|
||||
LocalDate.parse(row.text("startDate")), LocalDate.parse(row.text("endDate")),
|
||||
Instant.parse(row.text("registrationStartAt")), Instant.parse(row.text("registrationEndAt")),
|
||||
row.integer("maxCredits"));
|
||||
entityManager.persist(semester);
|
||||
semesters.put(semester.getId(), semester);
|
||||
}
|
||||
|
||||
List<Professor> professors = professorRepository.saveAll(List.of(
|
||||
new Professor("10000000-0000-0000-0000-000000000001", "김영한"),
|
||||
new Professor("10000000-0000-0000-0000-000000000002", "최태영"),
|
||||
new Professor("10000000-0000-0000-0000-000000000003", "조재한")));
|
||||
Map<String, Professor> professors = new LinkedHashMap<>();
|
||||
for (SeedTable.Row row : SeedTable.read("seed/demo/professors.tsv")) {
|
||||
Professor professor = new Professor(row.text("id"), row.text("name"));
|
||||
entityManager.persist(professor);
|
||||
professors.put(professor.getId(), professor);
|
||||
}
|
||||
|
||||
List<Subject> subjects = subjectRepository.saveAll(List.of(
|
||||
new Subject("20000000-0000-0000-0000-000000000001", "자바 프로그래밍", "CS201", "자바 프로그래밍 기초", 3),
|
||||
new Subject("20000000-0000-0000-0000-000000000002", "자료구조", "CS202", "자료구조 및 알고리즘", 3),
|
||||
new Subject("20000000-0000-0000-0000-000000000003", "데이터베이스", "CS203", "데이터베이스 시스템", 3),
|
||||
new Subject("20000000-0000-0000-0000-000000000004", "컴퓨터 네트워크", "CS204", "네트워크 기초", 3),
|
||||
new Subject("20000000-0000-0000-0000-000000000005", "운영체제", "CS301", "운영체제 핵심", 3),
|
||||
new Subject("20000000-0000-0000-0000-000000000006", "대학원 세미나", "CS401", "대학원 전용 세미나", 3)));
|
||||
Map<String, Subject> subjects = new LinkedHashMap<>();
|
||||
for (SeedTable.Row row : SeedTable.read("seed/demo/subjects.tsv")) {
|
||||
Subject subject = new Subject(row.text("id"), row.text("name"), row.text("code"),
|
||||
row.text("description"), row.integer("credit"));
|
||||
entityManager.persist(subject);
|
||||
subjects.put(subject.getId(), subject);
|
||||
}
|
||||
|
||||
Lesson data01 = new Lesson(DATA_STRUCTURES_01_ID, "자료구조 01분반", subjects.get(1), professors.get(0), semester, 30, null, null);
|
||||
Lesson data02 = new Lesson(DATA_STRUCTURES_02_ID, "자료구조 02분반", subjects.get(1), professors.get(1), semester, 30, null, null);
|
||||
Lesson os = new Lesson(OVERLAP_OS_ID, "운영체제", subjects.get(4), professors.get(1), semester, 30, null, null);
|
||||
Lesson capacityOne = new Lesson(CAPACITY_ONE_ID, "데이터베이스 소수정예", subjects.get(2), professors.get(2), semester, 1, null, null);
|
||||
Lesson minGrade = new Lesson(MIN_GRADE_ID, "고급 네트워크", subjects.get(3), professors.get(2), semester, 30, 3L, null);
|
||||
Lesson postgraduate = new Lesson(POSTGRADUATE_ONLY_ID, "대학원 세미나", subjects.get(5), professors.get(0), semester, 20, null, UserRole.POSTGRADUATE);
|
||||
Lesson boundary = new Lesson(BOUNDARY_LESSON_ID, "자바 프로그래밍", subjects.get(0), professors.get(0), semester, 30, null, null);
|
||||
lessonRepository.saveAll(List.of(data01, data02, os, capacityOne, minGrade, postgraduate, boundary));
|
||||
for (SeedTable.Row row : SeedTable.read("seed/demo/users.tsv")) {
|
||||
entityManager.persist(new User(row.text("id"), row.text("name"), row.longValue("grade"),
|
||||
UserRole.valueOf(row.text("role"))));
|
||||
}
|
||||
|
||||
lessonScheduleRepository.saveAll(List.of(
|
||||
schedule("50000000-0000-0000-0000-000000000001", data01, DayOfWeek.MONDAY, 9, 11),
|
||||
schedule("50000000-0000-0000-0000-000000000002", data02, DayOfWeek.TUESDAY, 9, 11),
|
||||
schedule("50000000-0000-0000-0000-000000000003", os, DayOfWeek.MONDAY, 10, 12),
|
||||
schedule("50000000-0000-0000-0000-000000000004", capacityOne, DayOfWeek.WEDNESDAY, 9, 11),
|
||||
schedule("50000000-0000-0000-0000-000000000005", minGrade, DayOfWeek.THURSDAY, 9, 11),
|
||||
schedule("50000000-0000-0000-0000-000000000006", postgraduate, DayOfWeek.FRIDAY, 9, 11),
|
||||
schedule("50000000-0000-0000-0000-000000000007", boundary, DayOfWeek.MONDAY, 11, 13)));
|
||||
Map<String, Lesson> lessons = new LinkedHashMap<>();
|
||||
for (SeedTable.Row row : SeedTable.read("seed/demo/lessons.tsv")) {
|
||||
String minGrade = row.nullable("minGrade");
|
||||
String allowedRole = row.nullable("allowedRole");
|
||||
Lesson lesson = new Lesson(row.text("id"), row.text("name"),
|
||||
subjects.get(row.text("subjectId")), professors.get(row.text("professorId")),
|
||||
semesters.get(row.text("semesterId")), row.integer("capacity"),
|
||||
minGrade == null ? null : Long.parseLong(minGrade),
|
||||
allowedRole == null ? null : UserRole.valueOf(allowedRole));
|
||||
entityManager.persist(lesson);
|
||||
lessons.put(lesson.getId(), lesson);
|
||||
}
|
||||
|
||||
userRepository.saveAll(List.of(
|
||||
new User(STUDENT_GRADE_1_ID, "학생1", 1L, UserRole.STUDENT),
|
||||
new User(STUDENT_GRADE_2_ID, "학생2", 2L, UserRole.STUDENT),
|
||||
new User(POSTGRADUATE_ID, "대학원생", 3L, UserRole.POSTGRADUATE)));
|
||||
List<LessonSchedule> schedules = new ArrayList<>();
|
||||
for (SeedTable.Row row : SeedTable.read("seed/demo/schedules.tsv")) {
|
||||
schedules.add(new LessonSchedule(row.text("id"), lessons.get(row.text("lessonId")),
|
||||
DayOfWeek.valueOf(row.text("dayOfWeek")), LocalTime.parse(row.text("startTime")),
|
||||
LocalTime.parse(row.text("endTime"))));
|
||||
}
|
||||
schedulePolicy.validate(schedules);
|
||||
schedules.forEach(entityManager::persist);
|
||||
}
|
||||
|
||||
private static LessonSchedule schedule(String id, Lesson lesson, DayOfWeek day, int startHour, int endHour) {
|
||||
return new LessonSchedule(id, lesson, day, LocalTime.of(startHour, 0), LocalTime.of(endHour, 0));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
package com.study.course_registration.seeder;
|
||||
|
||||
import java.io.BufferedReader;
|
||||
import java.io.IOException;
|
||||
import java.io.InputStreamReader;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.IntStream;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.springframework.core.io.ClassPathResource;
|
||||
|
||||
final class SeedTable {
|
||||
private SeedTable() {}
|
||||
|
||||
static List<Row> read(String resource) {
|
||||
try (BufferedReader reader = new BufferedReader(new InputStreamReader(
|
||||
new ClassPathResource(resource).getInputStream(), StandardCharsets.UTF_8))) {
|
||||
List<String> lines = reader.lines().filter(line -> !line.isBlank() && !line.startsWith("#")).toList();
|
||||
String[] headers = lines.getFirst().split("\t", -1);
|
||||
return lines.stream().skip(1).map(line -> row(headers, line)).toList();
|
||||
} catch (IOException exception) {
|
||||
throw new IllegalStateException("seed data를 읽을 수 없습니다: " + resource, exception);
|
||||
}
|
||||
}
|
||||
|
||||
private static Row row(String[] headers, String line) {
|
||||
String[] values = line.split("\t", -1);
|
||||
if (headers.length != values.length) {
|
||||
throw new IllegalStateException("seed column 수가 맞지 않습니다: " + line);
|
||||
}
|
||||
Map<String, String> columns = IntStream.range(0, headers.length)
|
||||
.boxed().collect(Collectors.toMap(index -> headers[index], index -> values[index]));
|
||||
return new Row(columns);
|
||||
}
|
||||
|
||||
record Row(Map<String, String> columns) {
|
||||
String text(String name) { return columns.get(name); }
|
||||
String nullable(String name) {
|
||||
String value = text(name);
|
||||
return value == null || value.isBlank() ? null : value;
|
||||
}
|
||||
int integer(String name) { return Integer.parseInt(text(name)); }
|
||||
long longValue(String name) { return Long.parseLong(text(name)); }
|
||||
}
|
||||
}
|
||||
+106
-109
@@ -1,17 +1,17 @@
|
||||
package com.study.course_registration.service;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.LocalDate;
|
||||
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;
|
||||
@@ -19,165 +19,162 @@ 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.LessonRepository;
|
||||
import com.study.course_registration.repository.LessonScheduleRepository;
|
||||
import com.study.course_registration.repository.SemesterRepository;
|
||||
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 LessonRepository lessonRepository;
|
||||
private final SemesterRepository semesterRepository;
|
||||
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,
|
||||
LessonRepository lessonRepository,
|
||||
SemesterRepository semesterRepository,
|
||||
LessonScheduleRepository lessonScheduleRepository,
|
||||
UserLessonRepository userLessonRepository,
|
||||
RegistrationValidator validator) {
|
||||
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.lessonRepository = lessonRepository;
|
||||
this.semesterRepository = semesterRepository;
|
||||
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) {
|
||||
User user = userRepository.findById(userId)
|
||||
.orElseThrow(() -> error(RegistrationErrorCode.USER_NOT_FOUND, "사용자를 찾을 수 없습니다."));
|
||||
Lesson lesson = lessonRepository.findById(request.lessonId())
|
||||
.orElseThrow(() -> error(RegistrationErrorCode.LESSON_NOT_FOUND, "강의를 찾을 수 없습니다."));
|
||||
return register(userId, request, null);
|
||||
}
|
||||
|
||||
var now = clock.instant();
|
||||
validator.validatePreconditions(user, lesson, now);
|
||||
@Transactional
|
||||
public CourseRegistrationResponse register(String userId, CourseRegistrationRequest request, String idempotencyKey) {
|
||||
LockedRegistration locked = lockManager.lock(userId, request.lessonId());
|
||||
|
||||
// Lock order is a system invariant: User -> Lesson.
|
||||
User lockedUser = userRepository.findByIdForUpdate(userId)
|
||||
.orElseThrow(() -> error(RegistrationErrorCode.USER_NOT_FOUND, "사용자를 찾을 수 없습니다."));
|
||||
Lesson lockedLesson = lessonRepository.findByIdForUpdate(request.lessonId())
|
||||
.orElseThrow(() -> error(RegistrationErrorCode.LESSON_NOT_FOUND, "강의를 찾을 수 없습니다."));
|
||||
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());
|
||||
}
|
||||
}
|
||||
|
||||
List<UserLesson> activeRegistrations = userLessonRepository.findActiveByUserIdAndSemesterId(
|
||||
lockedUser.getId(), lockedLesson.getSemester().getId());
|
||||
Map<String, List<LessonSchedule>> schedules = loadSchedules(activeRegistrations, lockedLesson);
|
||||
long enrolledCount = userLessonRepository.countByLesson_IdAndCanceledAtIsNull(lockedLesson.getId());
|
||||
validator.validatePreconditions(locked.user(), locked.lesson(), requestTime);
|
||||
|
||||
validator.validateLocked(lockedLesson, activeRegistrations, schedules, enrolledCount);
|
||||
int totalCredits = validator.totalCreditsAfter(lockedLesson, activeRegistrations);
|
||||
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());
|
||||
|
||||
UserLesson registration = userLessonRepository.saveAndFlush(new UserLesson(lockedUser, lockedLesson));
|
||||
return new CourseRegistrationResponse(
|
||||
registration.getId(),
|
||||
lockedUser.getId(),
|
||||
lockedLesson.getId(),
|
||||
lockedLesson.getName(),
|
||||
lockedLesson.getSubject().getCode(),
|
||||
lockedLesson.getSubject().getCredit(),
|
||||
registration.getCreatedAt(),
|
||||
totalCredits);
|
||||
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 = resolveSemester(semesterId);
|
||||
List<UserLesson> activeRegistrations = userLessonRepository.findActiveByUserIdAndSemesterId(userId, semester.getId());
|
||||
|
||||
Set<String> lessonIds = activeRegistrations.stream()
|
||||
.map(UserLesson::getLesson)
|
||||
.map(Lesson::getId)
|
||||
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>> schedulesByLesson = groupSchedules(
|
||||
lessonIds.isEmpty() ? List.of() : lessonScheduleRepository.findByLesson_IdInOrderByDayOfWeekAscStartTimeAsc(lessonIds));
|
||||
|
||||
List<RegistrationItemResponse> items = activeRegistrations.stream()
|
||||
.map(registration -> {
|
||||
Lesson lesson = registration.getLesson();
|
||||
List<ScheduleResponse> schedules = schedulesByLesson.getOrDefault(lesson.getId(), List.of()).stream()
|
||||
.map(ScheduleResponse::from)
|
||||
.toList();
|
||||
return new RegistrationItemResponse(
|
||||
registration.getId(), lesson.getId(), lesson.getName(),
|
||||
lesson.getSubject().getCode(), lesson.getSubject().getName(), lesson.getSubject().getCredit(),
|
||||
lesson.getProfessor().getName(), schedules, registration.getCreatedAt());
|
||||
})
|
||||
.toList();
|
||||
|
||||
return new RegistrationListResponse(
|
||||
userId, semester.getId(), semester.getName(), validator.currentCredits(activeRegistrations),
|
||||
semester.getMaxCredits(), items);
|
||||
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, "다른 사용자의 수강신청은 취소할 수 없습니다.");
|
||||
}
|
||||
|
||||
// Mutation paths use the same fixed lock order as registration.
|
||||
userRepository.findByIdForUpdate(userId)
|
||||
.orElseThrow(() -> error(RegistrationErrorCode.USER_NOT_FOUND, "사용자를 찾을 수 없습니다."));
|
||||
Lesson lesson = lessonRepository.findByIdForUpdate(target.getLessonId())
|
||||
.orElseThrow(() -> error(RegistrationErrorCode.LESSON_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()) {
|
||||
throw error(RegistrationErrorCode.ALREADY_CANCELED, "이미 취소된 수강신청입니다.");
|
||||
}
|
||||
var now = clock.instant();
|
||||
validator.validateRegistrationPeriod(lesson, now);
|
||||
if (registration.isCanceled()) return;
|
||||
Instant now = clock.instant();
|
||||
validator.validateRegistrationPeriod(locked.lesson(), now);
|
||||
registration.cancel(now);
|
||||
}
|
||||
|
||||
private Semester resolveSemester(String semesterId) {
|
||||
if (semesterId != null && !semesterId.isBlank()) {
|
||||
return semesterRepository.findById(semesterId)
|
||||
.orElseThrow(() -> error(RegistrationErrorCode.SEMESTER_NOT_FOUND, "학기를 찾을 수 없습니다."));
|
||||
|
||||
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자 이하여야 합니다.");
|
||||
}
|
||||
LocalDate today = LocalDate.now(clock);
|
||||
return semesterRepository
|
||||
.findFirstByStartDateLessThanEqualAndEndDateGreaterThanEqualOrderByStartDateDesc(today, today)
|
||||
.orElseThrow(() -> error(RegistrationErrorCode.SEMESTER_NOT_FOUND, "현재 진행 중인 학기를 찾을 수 없습니다."));
|
||||
return normalized;
|
||||
}
|
||||
|
||||
private Map<String, List<LessonSchedule>> loadSchedules(List<UserLesson> registrations, Lesson candidate) {
|
||||
Set<String> lessonIds = registrations.stream()
|
||||
.map(UserLesson::getLesson)
|
||||
.map(Lesson::getId)
|
||||
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));
|
||||
lessonIds.add(candidate.getId());
|
||||
return groupSchedules(lessonScheduleRepository.findByLesson_IdInOrderByDayOfWeekAscStartTimeAsc(lessonIds));
|
||||
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(
|
||||
schedule -> schedule.getLesson().getId(),
|
||||
LinkedHashMap::new,
|
||||
Collectors.toList()));
|
||||
}
|
||||
|
||||
private static RegistrationException error(RegistrationErrorCode code, String message) {
|
||||
return new RegistrationException(code, message);
|
||||
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); }
|
||||
}
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
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,7 +1,5 @@
|
||||
package com.study.course_registration.service;
|
||||
|
||||
import java.time.Clock;
|
||||
import java.time.LocalDate;
|
||||
import java.util.LinkedHashMap;
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
@@ -25,32 +23,28 @@ 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.SemesterRepository;
|
||||
import com.study.course_registration.repository.UserLessonRepository;
|
||||
|
||||
@Service
|
||||
@Transactional(readOnly = true)
|
||||
public class LessonQueryService {
|
||||
private final Clock clock;
|
||||
private final LessonRepository lessonRepository;
|
||||
private final LessonScheduleRepository lessonScheduleRepository;
|
||||
private final UserLessonRepository userLessonRepository;
|
||||
private final SemesterRepository semesterRepository;
|
||||
private final SemesterResolver semesterResolver;
|
||||
|
||||
public LessonQueryService(Clock clock,
|
||||
LessonRepository lessonRepository,
|
||||
public LessonQueryService(LessonRepository lessonRepository,
|
||||
LessonScheduleRepository lessonScheduleRepository,
|
||||
UserLessonRepository userLessonRepository,
|
||||
SemesterRepository semesterRepository) {
|
||||
this.clock = clock;
|
||||
SemesterResolver semesterResolver) {
|
||||
this.lessonRepository = lessonRepository;
|
||||
this.lessonScheduleRepository = lessonScheduleRepository;
|
||||
this.userLessonRepository = userLessonRepository;
|
||||
this.semesterRepository = semesterRepository;
|
||||
this.semesterResolver = semesterResolver;
|
||||
}
|
||||
|
||||
public LessonListResponse getLessons(String semesterId, String subjectId, int page, int size) {
|
||||
Semester semester = resolveSemester(semesterId);
|
||||
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)
|
||||
@@ -109,16 +103,6 @@ public class LessonQueryService {
|
||||
LinkedHashMap::new));
|
||||
}
|
||||
|
||||
private Semester resolveSemester(String semesterId) {
|
||||
if (semesterId != null && !semesterId.isBlank()) {
|
||||
return semesterRepository.findById(semesterId)
|
||||
.orElseThrow(() -> error(RegistrationErrorCode.SEMESTER_NOT_FOUND, "학기를 찾을 수 없습니다."));
|
||||
}
|
||||
LocalDate today = LocalDate.now(clock);
|
||||
return semesterRepository.findFirstByStartDateLessThanEqualAndEndDateGreaterThanEqualOrderByStartDateDesc(today, today)
|
||||
.orElseThrow(() -> error(RegistrationErrorCode.SEMESTER_NOT_FOUND, "현재 진행 중인 학기를 찾을 수 없습니다."));
|
||||
}
|
||||
|
||||
private static RegistrationException error(RegistrationErrorCode code, String message) {
|
||||
return new RegistrationException(code, message);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
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);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
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) {}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
package com.study.course_registration.service.policy;
|
||||
|
||||
import java.util.List;
|
||||
import java.util.Map;
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.springframework.stereotype.Component;
|
||||
|
||||
import com.study.course_registration.entity.Lesson;
|
||||
import com.study.course_registration.entity.LessonSchedule;
|
||||
|
||||
@Component
|
||||
public class LessonSchedulePolicy {
|
||||
private final ScheduleConflictChecker conflictChecker;
|
||||
|
||||
public LessonSchedulePolicy(ScheduleConflictChecker conflictChecker) {
|
||||
this.conflictChecker = conflictChecker;
|
||||
}
|
||||
|
||||
public void validate(List<LessonSchedule> schedules) {
|
||||
Map<Lesson, List<LessonSchedule>> byLesson = schedules.stream()
|
||||
.collect(Collectors.groupingBy(LessonSchedule::getLesson));
|
||||
|
||||
for (List<LessonSchedule> lessonSchedules : byLesson.values()) {
|
||||
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("같은 강의의 시간표가 겹칩니다.");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -55,8 +55,14 @@ public class RegistrationValidator {
|
||||
}
|
||||
|
||||
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)) {
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
server:
|
||||
address: ${SERVER_ADDRESS:0.0.0.0}
|
||||
|
||||
spring:
|
||||
datasource:
|
||||
url: jdbc:postgresql://${DB_HOST:localhost}:${DB_PORT:5432}/${DB_NAME:course_registration}
|
||||
username: ${DB_USERNAME:course}
|
||||
password: ${DB_PASSWORD:course}
|
||||
hikari:
|
||||
connection-init-sql: SET lock_timeout TO '3s'
|
||||
flyway:
|
||||
locations: classpath:db/migration/postgresql
|
||||
jpa:
|
||||
hibernate:
|
||||
ddl-auto: update
|
||||
show-sql: ${JPA_SHOW_SQL:false}
|
||||
h2:
|
||||
console:
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
server:
|
||||
address: 127.0.0.1
|
||||
|
||||
spring:
|
||||
datasource:
|
||||
url: jdbc:h2:mem:course_db;DB_CLOSE_DELAY=-1;MODE=PostgreSQL;LOCK_TIMEOUT=3000
|
||||
driver-class-name: org.h2.Driver
|
||||
username: sa
|
||||
password:
|
||||
flyway:
|
||||
locations: classpath:db/migration/h2
|
||||
jpa:
|
||||
hibernate:
|
||||
ddl-auto: create-drop
|
||||
show-sql: true
|
||||
properties:
|
||||
hibernate:
|
||||
|
||||
@@ -1,11 +1,16 @@
|
||||
server:
|
||||
address: ${SERVER_ADDRESS:0.0.0.0}
|
||||
|
||||
spring:
|
||||
datasource:
|
||||
url: jdbc:postgresql://${DB_HOST}:${DB_PORT}/${DB_NAME}
|
||||
username: ${DB_USERNAME}
|
||||
password: ${DB_PASSWORD}
|
||||
hikari:
|
||||
connection-init-sql: SET lock_timeout TO '3s'
|
||||
flyway:
|
||||
locations: classpath:db/migration/postgresql
|
||||
jpa:
|
||||
hibernate:
|
||||
ddl-auto: validate
|
||||
show-sql: false
|
||||
h2:
|
||||
console:
|
||||
|
||||
@@ -1,16 +1,25 @@
|
||||
server:
|
||||
address: ${SERVER_ADDRESS:127.0.0.1}
|
||||
port: ${SERVER_PORT:8080}
|
||||
shutdown: graceful
|
||||
|
||||
spring:
|
||||
application:
|
||||
name: ${APP_NAME:course-registration}
|
||||
profiles:
|
||||
default: local
|
||||
jackson:
|
||||
time-zone: UTC
|
||||
jpa:
|
||||
open-in-view: false
|
||||
hibernate:
|
||||
ddl-auto: validate
|
||||
lifecycle:
|
||||
timeout-per-shutdown-phase: 30s
|
||||
datasource:
|
||||
url: ${DB_URL}
|
||||
hikari:
|
||||
connection-timeout: 2000
|
||||
validation-timeout: 1000
|
||||
maximum-pool-size: ${DB_POOL_MAX_SIZE:20}
|
||||
minimum-idle: ${DB_POOL_MIN_IDLE:2}
|
||||
|
||||
springdoc:
|
||||
api-docs:
|
||||
@@ -28,3 +37,13 @@ management:
|
||||
health:
|
||||
probes:
|
||||
enabled: true
|
||||
group:
|
||||
liveness:
|
||||
include: livenessState
|
||||
readiness:
|
||||
include: readinessState,db
|
||||
|
||||
app:
|
||||
idempotency:
|
||||
ttl-seconds: 86400
|
||||
cleanup-delay-ms: 3600000
|
||||
|
||||
@@ -0,0 +1,131 @@
|
||||
CREATE TABLE semesters (
|
||||
id VARCHAR(36) PRIMARY KEY,
|
||||
version BIGINT NOT NULL DEFAULT 0,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
start_date DATE NOT NULL,
|
||||
end_date DATE NOT NULL,
|
||||
registration_start_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
registration_end_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
max_credits INTEGER NOT NULL,
|
||||
created_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
updated_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
CONSTRAINT uk_semester_name UNIQUE (name),
|
||||
CONSTRAINT ck_semester_dates CHECK (end_date >= start_date),
|
||||
CONSTRAINT ck_semester_registration_window CHECK (registration_start_at < registration_end_at),
|
||||
CONSTRAINT ck_semester_max_credits CHECK (max_credits >= 1)
|
||||
);
|
||||
|
||||
CREATE TABLE professors (
|
||||
id VARCHAR(36) PRIMARY KEY,
|
||||
version BIGINT NOT NULL DEFAULT 0,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
created_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
updated_at TIMESTAMP WITH TIME ZONE NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE subjects (
|
||||
id VARCHAR(36) PRIMARY KEY,
|
||||
version BIGINT NOT NULL DEFAULT 0,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
code VARCHAR(255) NOT NULL,
|
||||
description VARCHAR(1000) NOT NULL,
|
||||
credit INTEGER NOT NULL,
|
||||
created_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
updated_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
CONSTRAINT uk_subject_code UNIQUE (code),
|
||||
CONSTRAINT ck_subject_credit CHECK (credit >= 1)
|
||||
);
|
||||
|
||||
CREATE TABLE users (
|
||||
id VARCHAR(36) PRIMARY KEY,
|
||||
version BIGINT NOT NULL DEFAULT 0,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
grade BIGINT NOT NULL,
|
||||
role VARCHAR(64) NOT NULL,
|
||||
created_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
updated_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
CONSTRAINT ck_user_grade CHECK (grade >= 1)
|
||||
);
|
||||
|
||||
CREATE TABLE lessons (
|
||||
id VARCHAR(36) PRIMARY KEY,
|
||||
version BIGINT NOT NULL DEFAULT 0,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
subject_id VARCHAR(36) NOT NULL,
|
||||
professor_id VARCHAR(36) NOT NULL,
|
||||
semester_id VARCHAR(36) NOT NULL,
|
||||
capacity INTEGER NOT NULL,
|
||||
min_grade BIGINT,
|
||||
allowed_role VARCHAR(64),
|
||||
created_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
updated_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
CONSTRAINT fk_lesson_subject FOREIGN KEY (subject_id) REFERENCES subjects(id),
|
||||
CONSTRAINT fk_lesson_professor FOREIGN KEY (professor_id) REFERENCES professors(id),
|
||||
CONSTRAINT fk_lesson_semester FOREIGN KEY (semester_id) REFERENCES semesters(id),
|
||||
CONSTRAINT ck_lesson_capacity CHECK (capacity >= 1),
|
||||
CONSTRAINT ck_lesson_min_grade CHECK (min_grade IS NULL OR min_grade >= 1)
|
||||
);
|
||||
|
||||
CREATE TABLE lesson_schedules (
|
||||
id VARCHAR(36) PRIMARY KEY,
|
||||
version BIGINT NOT NULL DEFAULT 0,
|
||||
lesson_id VARCHAR(36) NOT NULL,
|
||||
day_of_week INTEGER NOT NULL,
|
||||
start_time TIME NOT NULL,
|
||||
end_time TIME NOT NULL,
|
||||
created_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
updated_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
CONSTRAINT fk_schedule_lesson FOREIGN KEY (lesson_id) REFERENCES lessons(id),
|
||||
CONSTRAINT ck_schedule_day CHECK (day_of_week BETWEEN 1 AND 7),
|
||||
CONSTRAINT ck_schedule_time CHECK (start_time < end_time),
|
||||
CONSTRAINT uk_lesson_schedule UNIQUE (lesson_id, day_of_week, start_time, end_time)
|
||||
);
|
||||
|
||||
CREATE TABLE user_lessons (
|
||||
id VARCHAR(36) PRIMARY KEY,
|
||||
version BIGINT NOT NULL DEFAULT 0,
|
||||
user_id VARCHAR(36) NOT NULL,
|
||||
lesson_id VARCHAR(36) NOT NULL,
|
||||
created_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
canceled_at TIMESTAMP WITH TIME ZONE,
|
||||
active_lesson_id VARCHAR(36) GENERATED ALWAYS AS (CASE WHEN canceled_at IS NULL THEN lesson_id END),
|
||||
CONSTRAINT fk_user_lesson_user FOREIGN KEY (user_id) REFERENCES users(id),
|
||||
CONSTRAINT fk_user_lesson_lesson FOREIGN KEY (lesson_id) REFERENCES lessons(id),
|
||||
CONSTRAINT uk_user_active_lesson UNIQUE (user_id, active_lesson_id)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_user_lessons_user_active ON user_lessons(user_id, canceled_at);
|
||||
CREATE INDEX idx_user_lessons_lesson_active ON user_lessons(lesson_id, canceled_at);
|
||||
CREATE INDEX idx_lessons_semester_subject ON lessons(semester_id, subject_id);
|
||||
CREATE INDEX idx_schedules_lesson ON lesson_schedules(lesson_id);
|
||||
|
||||
|
||||
CREATE TABLE registration_idempotencies (
|
||||
id VARCHAR(36) PRIMARY KEY,
|
||||
version BIGINT NOT NULL DEFAULT 0,
|
||||
user_id VARCHAR(36) NOT NULL,
|
||||
lesson_id VARCHAR(36) NOT NULL,
|
||||
registration_id VARCHAR(36) NOT NULL,
|
||||
idempotency_key VARCHAR(100) NOT NULL,
|
||||
total_credits INTEGER NOT NULL,
|
||||
created_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
CONSTRAINT fk_idempotency_user FOREIGN KEY (user_id) REFERENCES users(id),
|
||||
CONSTRAINT fk_idempotency_lesson FOREIGN KEY (lesson_id) REFERENCES lessons(id),
|
||||
CONSTRAINT fk_idempotency_registration FOREIGN KEY (registration_id) REFERENCES user_lessons(id),
|
||||
CONSTRAINT uk_registration_idempotency UNIQUE (user_id, idempotency_key),
|
||||
CONSTRAINT uk_idempotency_registration UNIQUE (registration_id)
|
||||
);
|
||||
CREATE INDEX idx_idempotency_expires_at ON registration_idempotencies(expires_at);
|
||||
|
||||
CREATE TABLE seed_locks (
|
||||
name VARCHAR(100) PRIMARY KEY
|
||||
);
|
||||
INSERT INTO seed_locks(name) VALUES ('demo-dataset');
|
||||
@@ -0,0 +1,124 @@
|
||||
CREATE TABLE semesters (
|
||||
id VARCHAR(36) PRIMARY KEY,
|
||||
version BIGINT NOT NULL DEFAULT 0,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
start_date DATE NOT NULL,
|
||||
end_date DATE NOT NULL,
|
||||
registration_start_at TIMESTAMPTZ NOT NULL,
|
||||
registration_end_at TIMESTAMPTZ NOT NULL,
|
||||
max_credits INTEGER NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL,
|
||||
updated_at TIMESTAMPTZ NOT NULL,
|
||||
CONSTRAINT uk_semester_name UNIQUE (name),
|
||||
CONSTRAINT ck_semester_dates CHECK (end_date >= start_date),
|
||||
CONSTRAINT ck_semester_registration_window CHECK (registration_start_at < registration_end_at),
|
||||
CONSTRAINT ck_semester_max_credits CHECK (max_credits >= 1)
|
||||
);
|
||||
|
||||
CREATE TABLE professors (
|
||||
id VARCHAR(36) PRIMARY KEY,
|
||||
version BIGINT NOT NULL DEFAULT 0,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL,
|
||||
updated_at TIMESTAMPTZ NOT NULL
|
||||
);
|
||||
|
||||
CREATE TABLE subjects (
|
||||
id VARCHAR(36) PRIMARY KEY,
|
||||
version BIGINT NOT NULL DEFAULT 0,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
code VARCHAR(255) NOT NULL,
|
||||
description VARCHAR(1000) NOT NULL,
|
||||
credit INTEGER NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL,
|
||||
updated_at TIMESTAMPTZ NOT NULL,
|
||||
CONSTRAINT uk_subject_code UNIQUE (code),
|
||||
CONSTRAINT ck_subject_credit CHECK (credit >= 1)
|
||||
);
|
||||
|
||||
CREATE TABLE users (
|
||||
id VARCHAR(36) PRIMARY KEY,
|
||||
version BIGINT NOT NULL DEFAULT 0,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
grade BIGINT NOT NULL,
|
||||
role VARCHAR(64) NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL,
|
||||
updated_at TIMESTAMPTZ NOT NULL,
|
||||
CONSTRAINT ck_user_grade CHECK (grade >= 1)
|
||||
);
|
||||
|
||||
CREATE TABLE lessons (
|
||||
id VARCHAR(36) PRIMARY KEY,
|
||||
version BIGINT NOT NULL DEFAULT 0,
|
||||
name VARCHAR(255) NOT NULL,
|
||||
subject_id VARCHAR(36) NOT NULL,
|
||||
professor_id VARCHAR(36) NOT NULL,
|
||||
semester_id VARCHAR(36) NOT NULL,
|
||||
capacity INTEGER NOT NULL,
|
||||
min_grade BIGINT,
|
||||
allowed_role VARCHAR(64),
|
||||
created_at TIMESTAMPTZ NOT NULL,
|
||||
updated_at TIMESTAMPTZ NOT NULL,
|
||||
CONSTRAINT fk_lesson_subject FOREIGN KEY (subject_id) REFERENCES subjects(id),
|
||||
CONSTRAINT fk_lesson_professor FOREIGN KEY (professor_id) REFERENCES professors(id),
|
||||
CONSTRAINT fk_lesson_semester FOREIGN KEY (semester_id) REFERENCES semesters(id),
|
||||
CONSTRAINT ck_lesson_capacity CHECK (capacity >= 1),
|
||||
CONSTRAINT ck_lesson_min_grade CHECK (min_grade IS NULL OR min_grade >= 1)
|
||||
);
|
||||
|
||||
CREATE TABLE lesson_schedules (
|
||||
id VARCHAR(36) PRIMARY KEY,
|
||||
version BIGINT NOT NULL DEFAULT 0,
|
||||
lesson_id VARCHAR(36) NOT NULL,
|
||||
day_of_week INTEGER NOT NULL,
|
||||
start_time TIME WITHOUT TIME ZONE NOT NULL,
|
||||
end_time TIME WITHOUT TIME ZONE NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL,
|
||||
updated_at TIMESTAMPTZ NOT NULL,
|
||||
CONSTRAINT fk_schedule_lesson FOREIGN KEY (lesson_id) REFERENCES lessons(id),
|
||||
CONSTRAINT ck_schedule_day CHECK (day_of_week BETWEEN 1 AND 7),
|
||||
CONSTRAINT ck_schedule_time CHECK (start_time < end_time),
|
||||
CONSTRAINT uk_lesson_schedule UNIQUE (lesson_id, day_of_week, start_time, end_time)
|
||||
);
|
||||
|
||||
CREATE TABLE user_lessons (
|
||||
id VARCHAR(36) PRIMARY KEY,
|
||||
version BIGINT NOT NULL DEFAULT 0,
|
||||
user_id VARCHAR(36) NOT NULL,
|
||||
lesson_id VARCHAR(36) NOT NULL,
|
||||
created_at TIMESTAMPTZ NOT NULL,
|
||||
canceled_at TIMESTAMPTZ,
|
||||
active_lesson_id VARCHAR(36) GENERATED ALWAYS AS (CASE WHEN canceled_at IS NULL THEN lesson_id END) STORED,
|
||||
CONSTRAINT fk_user_lesson_user FOREIGN KEY (user_id) REFERENCES users(id),
|
||||
CONSTRAINT fk_user_lesson_lesson FOREIGN KEY (lesson_id) REFERENCES lessons(id),
|
||||
CONSTRAINT uk_user_active_lesson UNIQUE (user_id, active_lesson_id)
|
||||
);
|
||||
|
||||
CREATE INDEX idx_user_lessons_user_active ON user_lessons(user_id, canceled_at);
|
||||
CREATE INDEX idx_user_lessons_lesson_active ON user_lessons(lesson_id, canceled_at);
|
||||
CREATE INDEX idx_lessons_semester_subject ON lessons(semester_id, subject_id);
|
||||
CREATE INDEX idx_schedules_lesson ON lesson_schedules(lesson_id);
|
||||
|
||||
|
||||
CREATE TABLE registration_idempotencies (
|
||||
id VARCHAR(36) PRIMARY KEY,
|
||||
version BIGINT NOT NULL DEFAULT 0,
|
||||
user_id VARCHAR(36) NOT NULL,
|
||||
lesson_id VARCHAR(36) NOT NULL,
|
||||
registration_id VARCHAR(36) NOT NULL,
|
||||
idempotency_key VARCHAR(100) NOT NULL,
|
||||
total_credits INTEGER NOT NULL,
|
||||
created_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
expires_at TIMESTAMP WITH TIME ZONE NOT NULL,
|
||||
CONSTRAINT fk_idempotency_user FOREIGN KEY (user_id) REFERENCES users(id),
|
||||
CONSTRAINT fk_idempotency_lesson FOREIGN KEY (lesson_id) REFERENCES lessons(id),
|
||||
CONSTRAINT fk_idempotency_registration FOREIGN KEY (registration_id) REFERENCES user_lessons(id),
|
||||
CONSTRAINT uk_registration_idempotency UNIQUE (user_id, idempotency_key),
|
||||
CONSTRAINT uk_idempotency_registration UNIQUE (registration_id)
|
||||
);
|
||||
CREATE INDEX idx_idempotency_expires_at ON registration_idempotencies(expires_at);
|
||||
|
||||
CREATE TABLE seed_locks (
|
||||
name VARCHAR(100) PRIMARY KEY
|
||||
);
|
||||
INSERT INTO seed_locks(name) VALUES ('demo-dataset');
|
||||
@@ -0,0 +1,8 @@
|
||||
id name subjectId professorId semesterId capacity minGrade allowedRole
|
||||
40000000-0000-0000-0000-000000000001 자료구조 01분반 20000000-0000-0000-0000-000000000002 10000000-0000-0000-0000-000000000001 00000000-0000-0000-0000-000000000001 30
|
||||
40000000-0000-0000-0000-000000000002 자료구조 02분반 20000000-0000-0000-0000-000000000002 10000000-0000-0000-0000-000000000002 00000000-0000-0000-0000-000000000001 30
|
||||
40000000-0000-0000-0000-000000000003 운영체제 20000000-0000-0000-0000-000000000005 10000000-0000-0000-0000-000000000002 00000000-0000-0000-0000-000000000001 30
|
||||
40000000-0000-0000-0000-000000000004 데이터베이스 소수정예 20000000-0000-0000-0000-000000000003 10000000-0000-0000-0000-000000000003 00000000-0000-0000-0000-000000000001 1
|
||||
40000000-0000-0000-0000-000000000005 고급 네트워크 20000000-0000-0000-0000-000000000004 10000000-0000-0000-0000-000000000003 00000000-0000-0000-0000-000000000001 30 3
|
||||
40000000-0000-0000-0000-000000000006 대학원 세미나 20000000-0000-0000-0000-000000000006 10000000-0000-0000-0000-000000000001 00000000-0000-0000-0000-000000000001 20 POSTGRADUATE
|
||||
40000000-0000-0000-0000-000000000007 자바 프로그래밍 20000000-0000-0000-0000-000000000001 10000000-0000-0000-0000-000000000001 00000000-0000-0000-0000-000000000001 30
|
||||
|
@@ -0,0 +1,4 @@
|
||||
id name
|
||||
10000000-0000-0000-0000-000000000001 김영한
|
||||
10000000-0000-0000-0000-000000000002 최태영
|
||||
10000000-0000-0000-0000-000000000003 조재한
|
||||
|
@@ -0,0 +1,8 @@
|
||||
id lessonId dayOfWeek startTime endTime
|
||||
50000000-0000-0000-0000-000000000001 40000000-0000-0000-0000-000000000001 MONDAY 09:00 11:00
|
||||
50000000-0000-0000-0000-000000000002 40000000-0000-0000-0000-000000000002 TUESDAY 09:00 11:00
|
||||
50000000-0000-0000-0000-000000000003 40000000-0000-0000-0000-000000000003 MONDAY 10:00 12:00
|
||||
50000000-0000-0000-0000-000000000004 40000000-0000-0000-0000-000000000004 WEDNESDAY 09:00 11:00
|
||||
50000000-0000-0000-0000-000000000005 40000000-0000-0000-0000-000000000005 THURSDAY 09:00 11:00
|
||||
50000000-0000-0000-0000-000000000006 40000000-0000-0000-0000-000000000006 FRIDAY 09:00 11:00
|
||||
50000000-0000-0000-0000-000000000007 40000000-0000-0000-0000-000000000007 MONDAY 11:00 13:00
|
||||
|
@@ -0,0 +1,2 @@
|
||||
id name startDate endDate registrationStartAt registrationEndAt maxCredits
|
||||
00000000-0000-0000-0000-000000000001 current 2000-01-01 2099-12-31 2000-01-01T00:00:00Z 2099-12-31T23:59:59Z 18
|
||||
|
@@ -0,0 +1,7 @@
|
||||
id name code description credit
|
||||
20000000-0000-0000-0000-000000000001 자바 프로그래밍 CS201 자바 프로그래밍 기초 3
|
||||
20000000-0000-0000-0000-000000000002 자료구조 CS202 자료구조 및 알고리즘 3
|
||||
20000000-0000-0000-0000-000000000003 데이터베이스 CS203 데이터베이스 시스템 3
|
||||
20000000-0000-0000-0000-000000000004 컴퓨터 네트워크 CS204 네트워크 기초 3
|
||||
20000000-0000-0000-0000-000000000005 운영체제 CS301 운영체제 핵심 3
|
||||
20000000-0000-0000-0000-000000000006 대학원 세미나 CS401 대학원 전용 세미나 3
|
||||
|
@@ -0,0 +1,4 @@
|
||||
id name grade role
|
||||
30000000-0000-0000-0000-000000000001 학생1 1 STUDENT
|
||||
30000000-0000-0000-0000-000000000002 학생2 2 STUDENT
|
||||
30000000-0000-0000-0000-000000000003 대학원생 3 POSTGRADUATE
|
||||
|
Reference in New Issue
Block a user