Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
785eba5
feat: 배지 관련 예외 추가
kon28289 Feb 19, 2026
551e77c
feat: 배지 관련 예외 추가
kon28289 Feb 20, 2026
9365d77
feat: 배지 컨트롤러 추가
kon28289 Feb 20, 2026
1dbad2c
feat: 배지 도메인 추가
kon28289 Feb 20, 2026
a8c0fff
feat: 배지 dto 추가
kon28289 Feb 20, 2026
d075a0f
feat: 학습 세션 dto 추가
kon28289 Feb 20, 2026
96b8f34
feat: 회원가입 완료 시 웰컴 배지 정보도 함께 제공
kon28289 Feb 20, 2026
284043f
docs: 배지 스웨거 문서화 추가
kon28289 Feb 20, 2026
20f8d9f
test: 통계 통합 테스트 수정
kon28289 Feb 20, 2026
70948f1
test: 베지 단위 테스트 추가
kon28289 Feb 20, 2026
2e3cd4d
test: 유저 통합 테스트 수정
kon28289 Feb 20, 2026
a9bc32d
feat: 회원가입 완료 후 전송하는 dto 변경
kon28289 Feb 20, 2026
0b11773
feat: 대표배지 상태 변경 메서드 추가
kon28289 Feb 20, 2026
836345c
docs: 유저 스웨거 문서화
kon28289 Feb 20, 2026
a7e8e8e
docs: 공부 세션 스웨거 문서화 수정
kon28289 Feb 20, 2026
10b4f83
feat: 공부 세션 종료 시 업적을 달성한 배지 제공
kon28289 Feb 20, 2026
f3b4e79
feat: 전체 공부 시간 조회하는 메서드 추가
kon28289 Feb 20, 2026
e77ea63
feat: 연속 공부 일수를 측정하는 메서드 추가
kon28289 Feb 20, 2026
656cb8f
feat: 시즌 랭킹 스냅샷 1·2·3등 조회 메서드 추가
kon28289 Feb 20, 2026
4792c44
feat: 시즌 종료 시 랭킹 배지 지급 및 로그 추가
kon28289 Feb 20, 2026
061ef7a
feat: 배지 레파지토리 추가
kon28289 Feb 20, 2026
6c3e380
feat: 배지 서비스 추가
kon28289 Feb 20, 2026
e5bef8d
chore: userBadge 도메인 접근 제어자 추가
kon28289 Feb 21, 2026
82e577b
chore: Spring Data JPA 컨벤션에 맞게 단일 조회 시 반환 타입을 Optional로 변경
kon28289 Feb 21, 2026
2a5234c
chore: 예외 타입 오타 수정 및 접두사 충돌 제거
kon28289 Feb 21, 2026
4a9adbc
fix: 공부 세션 종료 트랜잭션과 배지 지급 트랜잭션 분리
kon28289 Feb 21, 2026
1abe266
refactor: 연속 공부일수 계산 쿼리를 일별 집계+윈도우 함수 기반으로 최적화
kon28289 Feb 21, 2026
a14b0f1
fix: 시즌 전환 시 랭킹 배지 지급 실패를 try-catch로 처리
kon28289 Feb 21, 2026
61b97b3
refactor: end API를 세션 종료 전용으로 단순화하고 배지 지급을 AFTER_COMMIT 이벤트로 처리
kon28289 Feb 21, 2026
df00557
test: 공부 세션 테스트 수정
kon28289 Feb 21, 2026
25872ce
docs: 공부 세션 스웨거 문서화
kon28289 Feb 21, 2026
043fbcb
docs: 공부 세션 스웨거 문서화
kon28289 Feb 21, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
183 changes: 183 additions & 0 deletions src/main/java/com/gpt/geumpumtabackend/badge/api/BadgeApi.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,183 @@
package com.gpt.geumpumtabackend.badge.api;

import com.gpt.geumpumtabackend.badge.dto.request.BadgeCreateRequest;
import com.gpt.geumpumtabackend.badge.dto.request.RepresentativeBadgeRequest;
import com.gpt.geumpumtabackend.badge.dto.response.BadgeCreateResponse;
import com.gpt.geumpumtabackend.badge.dto.response.BadgeResponse;
import com.gpt.geumpumtabackend.badge.dto.response.MyBadgeResponse;
import com.gpt.geumpumtabackend.badge.dto.response.MyBadgeStatusResponse;
import com.gpt.geumpumtabackend.badge.dto.response.RepresentativeBadgeResponse;
import com.gpt.geumpumtabackend.global.aop.AssignUserId;
import com.gpt.geumpumtabackend.global.config.swagger.SwaggerApiFailedResponse;
import com.gpt.geumpumtabackend.global.config.swagger.SwaggerApiResponses;
import com.gpt.geumpumtabackend.global.config.swagger.SwaggerApiSuccessResponse;
import com.gpt.geumpumtabackend.global.exception.ExceptionType;
import com.gpt.geumpumtabackend.global.response.ResponseBody;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.media.Content;
import io.swagger.v3.oas.annotations.media.Schema;
import io.swagger.v3.oas.annotations.responses.ApiResponse;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Tag(name = "배지 API", description = """
배지 생성/조회/삭제 및 사용자 배지 조회 기능을 제공합니다.
""")
public interface BadgeApi {

@Operation(
summary = "배지 생성",
description = """
ADMIN 권한으로 새로운 배지를 생성합니다.
- code: 배지 고유 코드 (중복 불가)
- badgeType: 배지 종류
- thresholdValue: 누적 시간/연속 일수 계열 배지 기준값
- rank: 시즌 랭킹 배지 등수 값(예: 1,2,3)
"""
)
@ApiResponse(content = @Content(schema = @Schema(implementation = BadgeCreateResponse.class)))
@SwaggerApiResponses(
success = @SwaggerApiSuccessResponse(
response = BadgeCreateResponse.class,
description = "배지 생성 성공"
),
errors = {
@SwaggerApiFailedResponse(ExceptionType.NEED_AUTHORIZED),
@SwaggerApiFailedResponse(ExceptionType.ACCESS_DENIED),
@SwaggerApiFailedResponse(ExceptionType.BADGE_CODE_ALREADY_EXISTS)
}
)
@PostMapping
@PreAuthorize("isAuthenticated() and hasRole('ADMIN')")
ResponseEntity<ResponseBody<BadgeCreateResponse>> createBadge(
@RequestBody @Valid BadgeCreateRequest request
);

@Operation(
summary = "전체 배지 조회",
description = "ADMIN 권한으로 전체 배지 목록을 조회합니다."
)
@ApiResponse(content = @Content(schema = @Schema(implementation = BadgeResponse.class)))
@SwaggerApiResponses(
success = @SwaggerApiSuccessResponse(
response = BadgeResponse.class,
description = "전체 배지 조회 성공"
),
errors = {
@SwaggerApiFailedResponse(ExceptionType.NEED_AUTHORIZED),
@SwaggerApiFailedResponse(ExceptionType.ACCESS_DENIED)
}
)
@GetMapping
@PreAuthorize("isAuthenticated() and hasRole('ADMIN')")
ResponseEntity<ResponseBody<List<BadgeResponse>>> getAllBadges();

@Operation(
summary = "배지 삭제",
description = """
ADMIN 권한으로 배지를 삭제합니다.
이미 사용자에게 지급된 이력이 있으면 삭제할 수 없고 B004(BADGE_IN_USE)를 반환합니다.
"""
)
@ApiResponse(content = @Content(schema = @Schema(implementation = ResponseBody.class)))
@SwaggerApiResponses(
success = @SwaggerApiSuccessResponse(description = "배지 삭제 성공"),
errors = {
@SwaggerApiFailedResponse(ExceptionType.NEED_AUTHORIZED),
@SwaggerApiFailedResponse(ExceptionType.ACCESS_DENIED),
@SwaggerApiFailedResponse(ExceptionType.BADGE_NOT_FOUND),
@SwaggerApiFailedResponse(ExceptionType.BADGE_IN_USE)
}
)
@DeleteMapping("/{badgeId}")
@PreAuthorize("isAuthenticated() and hasRole('ADMIN')")
ResponseEntity<ResponseBody<Void>> deleteBadge(
@PathVariable Long badgeId
);

@Operation(
summary = "내 배지 조회",
description = """
항상 전체 배지 목록을 반환합니다.
각 원소는 아래 정보를 포함합니다.
- owned: 사용자의 배지 보유 여부
- awardedAt: 배지 획득 시각 (owned=false이면 null)
"""
)
@ApiResponse(content = @Content(schema = @Schema(implementation = MyBadgeStatusResponse.class)))
@SwaggerApiResponses(
success = @SwaggerApiSuccessResponse(
response = MyBadgeStatusResponse.class,
description = "내 배지 조회 성공"
),
errors = {
@SwaggerApiFailedResponse(ExceptionType.NEED_AUTHORIZED),
@SwaggerApiFailedResponse(ExceptionType.USER_NOT_FOUND)
}
)
@GetMapping("/me")
@AssignUserId
@PreAuthorize("isAuthenticated() and hasRole('USER')")
ResponseEntity<ResponseBody<List<MyBadgeStatusResponse>>> getMyBadges(
@Parameter(hidden = true) Long userId
);

@Operation(
summary = "대표 배지 설정",
description = """
보유한 배지 중 하나를 대표 배지로 설정합니다.
요청은 badgeCode 기준으로 처리됩니다.
"""
)
@ApiResponse(content = @Content(schema = @Schema(implementation = RepresentativeBadgeResponse.class)))
@SwaggerApiResponses(
success = @SwaggerApiSuccessResponse(
response = RepresentativeBadgeResponse.class,
description = "대표 배지 설정 성공"
),
errors = {
@SwaggerApiFailedResponse(ExceptionType.NEED_AUTHORIZED),
@SwaggerApiFailedResponse(ExceptionType.USER_NOT_FOUND),
@SwaggerApiFailedResponse(ExceptionType.BADGE_NOT_FOUND),
@SwaggerApiFailedResponse(ExceptionType.BADGE_NOT_OWNED)
}
)
@PostMapping("/me/representative-badge")
@AssignUserId
@PreAuthorize("isAuthenticated() and hasRole('USER')")
ResponseEntity<ResponseBody<RepresentativeBadgeResponse>> setRepresentativeBadge(
@RequestBody RepresentativeBadgeRequest request,
@Parameter(hidden = true) Long userId
);

@Operation(
summary = "미확인 배지 조회",
description = """
사용자의 미확인 배지 목록을 조회합니다.
조회된 배지는 같은 요청 트랜잭션에서 확인 처리(notifiedAt 설정)됩니다.
"""
)
@ApiResponse(content = @Content(schema = @Schema(implementation = MyBadgeResponse.class)))
@SwaggerApiResponses(
success = @SwaggerApiSuccessResponse(
response = MyBadgeResponse.class,
description = "미확인 배지 조회 성공"
),
errors = {
@SwaggerApiFailedResponse(ExceptionType.NEED_AUTHORIZED),
@SwaggerApiFailedResponse(ExceptionType.USER_NOT_FOUND)
}
)
@GetMapping("/unnotified")
@AssignUserId
@PreAuthorize("isAuthenticated() and hasRole('USER')")
ResponseEntity<ResponseBody<List<MyBadgeResponse>>> getUnnotifiedBadges(
@Parameter(hidden = true) Long userId
);
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,90 @@
package com.gpt.geumpumtabackend.badge.controller;

import com.gpt.geumpumtabackend.badge.api.BadgeApi;
import com.gpt.geumpumtabackend.badge.dto.request.BadgeCreateRequest;
import com.gpt.geumpumtabackend.badge.dto.request.RepresentativeBadgeRequest;
import com.gpt.geumpumtabackend.badge.dto.response.BadgeCreateResponse;
import com.gpt.geumpumtabackend.badge.dto.response.BadgeResponse;
import com.gpt.geumpumtabackend.badge.dto.response.MyBadgeResponse;
import com.gpt.geumpumtabackend.badge.dto.response.MyBadgeStatusResponse;
import com.gpt.geumpumtabackend.badge.dto.response.RepresentativeBadgeResponse;
import com.gpt.geumpumtabackend.badge.service.BadgeService;
import com.gpt.geumpumtabackend.global.aop.AssignUserId;
import com.gpt.geumpumtabackend.global.response.ResponseBody;
import com.gpt.geumpumtabackend.global.response.ResponseUtil;
import lombok.RequiredArgsConstructor;
import jakarta.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequiredArgsConstructor
@RequestMapping("/api/v1/badge")
public class BadgeController implements BadgeApi {

private final BadgeService badgeService;

@PostMapping
@PreAuthorize("isAuthenticated() and hasRole('ADMIN')")
public ResponseEntity<ResponseBody<BadgeCreateResponse>> createBadge(
@RequestBody @Valid BadgeCreateRequest request
){
return ResponseEntity.ok(ResponseUtil.createSuccessResponse(
badgeService.createBadge(request)
));
}

@GetMapping
@PreAuthorize("isAuthenticated() and hasRole('ADMIN')")
public ResponseEntity<ResponseBody<List<BadgeResponse>>> getAllBadges() {
return ResponseEntity.ok(ResponseUtil.createSuccessResponse(
badgeService.getAllBadges()
));
}

@DeleteMapping("/{badgeId}")
@PreAuthorize("isAuthenticated() and hasRole('ADMIN')")
public ResponseEntity<ResponseBody<Void>> deleteBadge(
@PathVariable Long badgeId
) {
badgeService.deleteBadge(badgeId);
return ResponseEntity.ok(ResponseUtil.createSuccessResponse());
}

@GetMapping("/me")
@AssignUserId
@PreAuthorize("isAuthenticated() and hasRole('USER')")
public ResponseEntity<ResponseBody<List<MyBadgeStatusResponse>>> getMyBadges(
Long userId
){
return ResponseEntity.ok(ResponseUtil.createSuccessResponse(
badgeService.getMyBadges(userId)
));
}

@PostMapping("/me/representative-badge")
@AssignUserId
@PreAuthorize("isAuthenticated() and hasRole('USER')")
public ResponseEntity<ResponseBody<RepresentativeBadgeResponse>> setRepresentativeBadge(
@RequestBody RepresentativeBadgeRequest request,
Long userId
){
return ResponseEntity.ok(ResponseUtil.createSuccessResponse(
badgeService.setRepresentativeBadge(request, userId)
));
}

@GetMapping("/unnotified")
@AssignUserId
@PreAuthorize("isAuthenticated() and hasRole('USER')")
public ResponseEntity<ResponseBody<List<MyBadgeResponse>>> getUnnotifiedBadges(
Long userId
){
return ResponseEntity.ok(ResponseUtil.createSuccessResponse(
badgeService.getUnnotifiedBadges(userId)
));
}
}
54 changes: 54 additions & 0 deletions src/main/java/com/gpt/geumpumtabackend/badge/domain/Badge.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
package com.gpt.geumpumtabackend.badge.domain;

import com.gpt.geumpumtabackend.global.base.BaseEntity;
import jakarta.persistence.*;
import lombok.Builder;
import lombok.Getter;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;

@Entity
@Getter
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class Badge extends BaseEntity {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(unique = true)
private String code;

private String name;

private String description;

private String iconUrl;

@Enumerated(EnumType.STRING)
private BadgeType badgeType;

private Long thresholdValue;

@Column(name = "badge_rank")
private Long rank;

@Builder
private Badge(
String code,
String name,
String description,
String iconUrl,
BadgeType badgeType,
Long thresholdValue,
Long rank
) {
this.code = code;
this.name = name;
this.description = description;
this.iconUrl = iconUrl;
this.badgeType = badgeType;
this.thresholdValue = thresholdValue;
this.rank = rank;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
package com.gpt.geumpumtabackend.badge.domain;

public enum BadgeType {
WELCOME,
STREAK_DAYS,
TOTAL_HOURS,
SEASON_PERSONAL_RANK
}
41 changes: 41 additions & 0 deletions src/main/java/com/gpt/geumpumtabackend/badge/domain/UserBadge.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
package com.gpt.geumpumtabackend.badge.domain;

import jakarta.persistence.*;
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.time.LocalDateTime;

@Entity
@Getter
@NoArgsConstructor
@Table(
name = "user_badge",
uniqueConstraints = @UniqueConstraint(name="uk_user_badge", columnNames = {"user_id", "badge_id"})
)
public class UserBadge {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

@Column(name = "user_id")
private Long userId;

@Column(name = "badge_id")
private Long badgeId;

private LocalDateTime awardedAt;

private LocalDateTime notifiedAt;

public UserBadge(Long userId, Long badgeId, LocalDateTime awardedAt, LocalDateTime notifiedAt) {
this.userId = userId;
this.badgeId = badgeId;
this.awardedAt = awardedAt;
this.notifiedAt = notifiedAt;
}

public void markNotified(LocalDateTime notifiedAt) {
this.notifiedAt = notifiedAt;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package com.gpt.geumpumtabackend.badge.dto.request;

import com.gpt.geumpumtabackend.badge.domain.BadgeType;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;

public record BadgeCreateRequest(
@NotBlank String code,
@NotBlank String name,
@NotBlank String description,
@NotBlank String iconUrl,
@NotNull BadgeType badgeType,
Long thresholdValue,
Long rank
) {
}
Loading