-
Notifications
You must be signed in to change notification settings - Fork 2
#92 [BE] SISC1-204 [FEAT] 출석 세션 기능 개선 #97
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
The head ref may contain hidden characters: "SISC1-204-BE-\uCD9C\uC11D-\uC138\uC158-\uAE30\uB2A5-\uAC1C\uC120"
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
ded8071
[BE] SISC1-201 [DOCS] Swagger 고도화 - API 응답 형식 정의
ochanhyeok 9374b39
Merge branch 'main' of https://github.com/SISC-IT/sisc-web into SISC1…
ochanhyeok 03367dc
Merge branch 'main' of https://github.com/SISC-IT/sisc-web into SISC1…
ochanhyeok e095c18
Merge branch 'main' of https://github.com/SISC-IT/sisc-web into SISC1…
ochanhyeok a959271
feat: 출석체크 세션 기능 개선 및 라운드 엔티티/출석 API 추가
ochanhyeok 5b1ebdc
[BE] SISC-151 [REFACTOR] 출석 관리 CodeRabbit 리뷰 개선사항 적용
ochanhyeok b85370c
[BE] SISC-151 [REFACTOR] 출석 관리 추가 수정
ochanhyeok 4da0215
[BE] SISC-151 [REFACTOR] 출석 관리 추가 수정
ochanhyeok 7006a86
[BE] SISC-151 [REFACTOR] 출석 관리 추가 수정 @Valid 추가
ochanhyeok 926508f
[BE] SISC-151 [REFACTOR] 출석 관리 추가 수정
ochanhyeok 7389724
[BE] SISC-151 [REFACTOR] 불필요한 api 삭제
ochanhyeok File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
254 changes: 254 additions & 0 deletions
254
.../src/main/java/org/sejongisc/backend/attendance/controller/AttendanceRoundController.java
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,254 @@ | ||
| package org.sejongisc.backend.attendance.controller; | ||
|
|
||
| import io.jsonwebtoken.JwtException; | ||
| import io.swagger.v3.oas.annotations.Operation; | ||
| import io.swagger.v3.oas.annotations.tags.Tag; | ||
| import jakarta.servlet.http.HttpServletRequest; | ||
| import jakarta.validation.Valid; | ||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.sejongisc.backend.attendance.dto.AttendanceCheckInRequest; | ||
| import org.sejongisc.backend.attendance.dto.AttendanceCheckInResponse; | ||
| import org.sejongisc.backend.attendance.dto.AttendanceRoundRequest; | ||
| import org.sejongisc.backend.attendance.dto.AttendanceRoundResponse; | ||
| import org.sejongisc.backend.attendance.service.AttendanceRoundService; | ||
| import org.sejongisc.backend.attendance.service.AttendanceService; | ||
| import org.sejongisc.backend.common.auth.jwt.JwtProvider; | ||
| import org.springframework.http.HttpStatus; | ||
| import org.springframework.http.ResponseEntity; | ||
| import org.springframework.security.access.prepost.PreAuthorize; | ||
| import org.springframework.security.authentication.AnonymousAuthenticationToken; | ||
| import org.springframework.security.core.Authentication; | ||
| import org.springframework.web.bind.annotation.*; | ||
|
|
||
| import java.time.LocalDate; | ||
| import java.util.List; | ||
| import java.util.UUID; | ||
|
|
||
| @RestController | ||
| @RequestMapping("/api/attendance") | ||
| @RequiredArgsConstructor | ||
| @Slf4j | ||
| @Tag( | ||
| name = "출석 라운드(Attendance Round) API", | ||
| description = "출석 라운드(주차별 회차) 생성, 조회, 수정, 삭제 및 출석 체크인 관련 API" | ||
| ) | ||
| public class AttendanceRoundController { | ||
|
|
||
| private final AttendanceRoundService attendanceRoundService; | ||
| private final AttendanceService attendanceService; | ||
| private final JwtProvider jwtProvider; | ||
|
|
||
| /** | ||
| * 라운드 생성 | ||
| * POST /api/attendance/sessions/{sessionId}/rounds | ||
| */ | ||
| @Operation( | ||
| summary = "라운드 생성", | ||
| description = "세션에 새로운 출석 라운드를 생성합니다. " + | ||
| "라운드 날짜, 시작 시간, 출석 가능 시간을 설정할 수 있습니다." | ||
| ) | ||
| @PostMapping("/sessions/{sessionId}/rounds") | ||
| @PreAuthorize("hasRole('PRESIDENT') or hasRole('VICE_PRESIDENT')") | ||
| public ResponseEntity<AttendanceRoundResponse> createRound( | ||
| @PathVariable UUID sessionId, | ||
| @Valid @RequestBody AttendanceRoundRequest request) { | ||
| log.info("📋 라운드 생성 요청 도착:"); | ||
| log.info(" - sessionId: {}", sessionId); | ||
| log.info(" - roundDate: {} (타입: {})", request.getRoundDate(), request.getRoundDate() != null ? request.getRoundDate().getClass().getSimpleName() : "null"); | ||
| log.info(" - startTime: {} (타입: {})", request.getStartTime(), request.getStartTime() != null ? request.getStartTime().getClass().getSimpleName() : "null"); | ||
| log.info(" - allowedMinutes: {}", request.getAllowedMinutes()); | ||
|
|
||
| if (request.getStartTime() != null) { | ||
| log.info(" - startTime 상세: 시간={}, 분={}, 초={}", | ||
| request.getStartTime().getHour(), | ||
| request.getStartTime().getMinute(), | ||
| request.getStartTime().getSecond()); | ||
| } | ||
|
|
||
| AttendanceRoundResponse response = attendanceRoundService.createRound(sessionId, request); | ||
| return ResponseEntity.status(HttpStatus.CREATED).body(response); | ||
| } | ||
|
|
||
| /** | ||
| * 라운드 조회 (개별) | ||
| * GET /api/attendance/rounds/{roundId} | ||
| */ | ||
| @Operation( | ||
| summary = "라운드 조회", | ||
| description = "지정된 라운드 ID로 라운드 정보를 조회합니다. " + | ||
| "라운드의 상태, 날짜, 시간, 참석 현황 등의 정보를 반환합니다." | ||
| ) | ||
| @GetMapping("/rounds/{roundId}") | ||
| public ResponseEntity<AttendanceRoundResponse> getRound(@PathVariable UUID roundId) { | ||
| log.info("라운드 조회: roundId={}", roundId); | ||
| AttendanceRoundResponse response = attendanceRoundService.getRound(roundId); | ||
| return ResponseEntity.ok(response); | ||
| } | ||
|
|
||
| /** | ||
| * 세션 내 라운드 목록 조회 | ||
| * GET /api/attendance/sessions/{sessionId}/rounds | ||
| */ | ||
| @Operation( | ||
| summary = "세션의 라운드 목록 조회", | ||
| description = "지정된 세션에 속한 모든 라운드 목록을 조회합니다. " + | ||
| "각 라운드의 상태, 시간, 참석 현황을 포함합니다." | ||
| ) | ||
| @GetMapping("/sessions/{sessionId}/rounds") | ||
| public ResponseEntity<List<AttendanceRoundResponse>> getRoundsBySession( | ||
| @PathVariable UUID sessionId) { | ||
| log.info("세션 내 라운드 목록 조회: sessionId={}", sessionId); | ||
| List<AttendanceRoundResponse> response = attendanceRoundService.getRoundsBySession(sessionId); | ||
| return ResponseEntity.ok(response); | ||
| } | ||
|
|
||
| /** | ||
| * 라운드 정보 수정 | ||
| * PUT /api/attendance/rounds/{roundId} | ||
| */ | ||
| @Operation( | ||
| summary = "라운드 정보 수정", | ||
| description = "지정된 라운드의 정보를 수정합니다. " + | ||
| "라운드 날짜, 시작 시간, 출석 가능 시간 등을 변경할 수 있습니다." | ||
| ) | ||
| @PutMapping("/rounds/{roundId}") | ||
| @PreAuthorize("hasRole('PRESIDENT') or hasRole('VICE_PRESIDENT')") | ||
| public ResponseEntity<AttendanceRoundResponse> updateRound( | ||
| @PathVariable UUID roundId, | ||
| @Valid @RequestBody AttendanceRoundRequest request) { | ||
| log.info("라운드 수정: roundId={}", roundId); | ||
| AttendanceRoundResponse response = attendanceRoundService.updateRound(roundId, request); | ||
| return ResponseEntity.ok(response); | ||
| } | ||
|
|
||
| /** | ||
| * 라운드 삭제 | ||
| * DELETE /api/attendance/rounds/{roundId} | ||
| */ | ||
| @Operation( | ||
| summary = "라운드 삭제", | ||
| description = "지정된 라운드를 삭제합니다. " + | ||
| "라운드와 관련된 모든 출석 기록도 함께 삭제됩니다." | ||
| ) | ||
| @DeleteMapping("/rounds/{roundId}") | ||
| @PreAuthorize("hasRole('PRESIDENT') or hasRole('VICE_PRESIDENT')") | ||
| public ResponseEntity<Void> deleteRound(@PathVariable UUID roundId) { | ||
| log.info("라운드 삭제: roundId={}", roundId); | ||
| attendanceRoundService.deleteRound(roundId); | ||
| return ResponseEntity.noContent().build(); | ||
| } | ||
|
|
||
| /** | ||
| * 라운드 기반 출석 체크인 | ||
| * POST /api/attendance/rounds/check-in | ||
| */ | ||
| @Operation( | ||
| summary = "라운드 출석 체크인", | ||
| description = "라운드에 출석 체크인을 기록합니다. " + | ||
| "라운드 ID와 위치 정보(위도, 경도)를 전송하면 출석 여부를 판단합니다. " + | ||
| "인증되지 않은 사용자는 이름을 입력하여 익명으로 출석할 수 있습니다." | ||
| ) | ||
| @PostMapping("/rounds/check-in") | ||
| public ResponseEntity<AttendanceCheckInResponse> checkInByRound( | ||
| @Valid @RequestBody AttendanceCheckInRequest request, | ||
| Authentication authentication, | ||
| HttpServletRequest httpRequest) { | ||
| UUID userId; | ||
|
|
||
| // 인증된 경우 사용자 ID 추출, 미인증인 경우 임시 ID 생성 | ||
| if (authentication != null && authentication.isAuthenticated() | ||
| && !(authentication instanceof AnonymousAuthenticationToken)) { | ||
| userId = extractUserId(authentication, httpRequest); | ||
| log.info("라운드 출석 체크인 요청 (인증됨): roundId={}, userId={}", request.getRoundId(), userId); | ||
| } else { | ||
| // 미인증 사용자: 임시 ID 사용 | ||
| userId = UUID.randomUUID(); | ||
| log.info("라운드 출석 체크인 요청 (미인증): roundId={}, 임시userId={}", request.getRoundId(), userId); | ||
| } | ||
|
|
||
| AttendanceCheckInResponse response = attendanceService.checkInByRound(request, userId); | ||
| return ResponseEntity.ok(response); | ||
| } | ||
|
|
||
| /** | ||
| * Authentication에서 사용자 ID를 추출합니다. | ||
| * JWT 토큰을 파싱하여 UUID를 반환하며, 파싱에 실패하면 예외를 던집니다. | ||
| * | ||
| * @param authentication 스프링 시큐리티 Authentication 객체 | ||
| * @param httpRequest HTTP 요청 객체 | ||
| * @return 추출된 사용자 UUID | ||
| * @throws IllegalStateException JWT 파싱 또는 UUID 변환에 실패한 경우 | ||
| */ | ||
| private UUID extractUserId(Authentication authentication, HttpServletRequest httpRequest) { | ||
| try { | ||
| // JWT 토큰에서 Authorization 헤더 추출 | ||
| String authHeader = httpRequest.getHeader("Authorization"); | ||
| if (authHeader == null || !authHeader.startsWith("Bearer ")) { | ||
| throw new IllegalStateException("Authorization 헤더가 없거나 형식이 올바르지 않습니다."); | ||
| } | ||
|
|
||
| String token = authHeader.substring(7); | ||
| // JwtProvider를 통해 uid 클레임에서 userId 추출 | ||
| String userIdStr = jwtProvider.getUserIdFromToken(token); | ||
| if (userIdStr == null || userIdStr.isBlank()) { | ||
| throw new IllegalStateException("토큰에서 사용자 ID를 찾을 수 없습니다."); | ||
| } | ||
|
|
||
| return UUID.fromString(userIdStr); | ||
| } catch (JwtException e) { | ||
| log.error("JWT 파싱 실패: {}", e.getMessage(), e); | ||
| throw new IllegalStateException("인증 정보가 유효하지 않습니다. JWT 파싱에 실패했습니다.", e); | ||
| } catch (IllegalArgumentException e) { | ||
| log.error("UUID 변환 실패: {}", e.getMessage(), e); | ||
| throw new IllegalStateException("사용자 ID가 유효한 UUID 형식이 아닙니다.", e); | ||
| } catch (Exception e) { | ||
| log.error("사용자 ID 추출 중 오류 발생: {}", e.getMessage(), e); | ||
| throw new IllegalStateException("사용자 ID를 확인할 수 없습니다.", e); | ||
| } | ||
| } | ||
|
|
||
| /** | ||
| * 특정 날짜의 라운드 조회 | ||
| * GET /api/attendance/sessions/{sessionId}/rounds/by-date | ||
| */ | ||
| @Operation( | ||
| summary = "특정 날짜의 라운드 조회", | ||
| description = "지정된 세션과 날짜로 라운드를 조회합니다. " + | ||
| "특정 날짜에만 진행되는 라운드를 찾을 때 사용합니다." | ||
| ) | ||
| @GetMapping("/sessions/{sessionId}/rounds/by-date") | ||
| public ResponseEntity<AttendanceRoundResponse> getRoundByDate( | ||
| @PathVariable UUID sessionId, | ||
| @RequestParam LocalDate date) { | ||
| log.info("날짜별 라운드 조회: sessionId={}, date={}", sessionId, date); | ||
| AttendanceRoundResponse response = attendanceRoundService.getRoundByDate(sessionId, date); | ||
| return ResponseEntity.ok(response); | ||
| } | ||
|
|
||
| /** | ||
| * 라운드별 출석 명단 조회 | ||
| * GET /api/attendance/rounds/{roundId}/attendances | ||
| */ | ||
| @Operation( | ||
| summary = "라운드별 출석 명단 조회", | ||
| description = "지정된 라운드의 모든 출석 기록을 조회합니다. " + | ||
| "참석자, 지각자, 결석자 등의 출석 상태별 명단을 반환합니다." | ||
| ) | ||
| @GetMapping("/rounds/{roundId}/attendances") | ||
| @PreAuthorize("hasRole('PRESIDENT') or hasRole('VICE_PRESIDENT')") | ||
| public ResponseEntity<?> getAttendancesByRound( | ||
| @PathVariable UUID roundId) { | ||
| log.info("라운드별 출석 명단 조회: roundId={}", roundId); | ||
| // 라운드 조회 및 해당 라운드의 모든 출석 기록 반환 | ||
| try { | ||
| var round = attendanceService.getAttendancesByRound(roundId); | ||
| return ResponseEntity.ok(round); | ||
| } catch (Exception e) { | ||
| log.error("라운드별 출석 명단 조회 실패: {}", e.getMessage()); | ||
| return ResponseEntity.status(400).body(new java.util.HashMap<String, String>() {{ | ||
| put("error", "라운드를 찾을 수 없습니다"); | ||
| }}); | ||
| } | ||
| } | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.