Skip to content

fix :: 외출 출석 오처리 수정 및 NonUniqueResultException 버그 수정 - #673

Merged
1210thatman merged 7 commits into
developfrom
fix/picnic-period-overlap-bug
Jun 4, 2026
Merged

1210thatman merged 7 commits into
developfrom
fix/picnic-period-overlap-bug

Conversation

@1210thatman

@1210thatman 1210thatman commented Jun 2, 2026 •

Copy link
Copy Markdown
Member

Summary

  • 5교시~6교시 시간 겹침으로 인한 외출 출석 오처리 수정
  • tbl_attendance, tbl_status 중복 행으로 인한 NonUniqueResultException 수정

[1] 5교시~6교시 시간 겹침 버그

문제 원인

AttendanceService의 교시 시간 정의에서 5교시 종료 시간(14:40)과 6교시 시작 시간(14:30)이 10분 겹치는 버그가 있었습니다.

// 수정 전
LocalTime.of(13, 30) to LocalTime.of(14, 40), // 5교시
LocalTime.of(14, 30) to LocalTime.of(15, 30), // 6교시  ← 14:30~14:40 겹침

ApplicationType.TIME 기반 외출 신청 승인 시 아래 필터가 사용됩니다.

periods.filter { it.first.isBefore(endTime) && it.second.isAfter(startTime) }

예를 들어 14:30~14:35 외출 신청 시 5교시와 6교시가 모두 매칭되어 6교시 출석까지 GO_OUT으로 잘못 변경되는 문제가 발생했습니다.

수정 내용

// 수정 후
LocalTime.of(13, 30) to LocalTime.of(14, 40), // 5교시
LocalTime.of(14, 40) to LocalTime.of(15, 30), // 6교시  ← 14:40으로 정정

또한 getMatchPeriods의 경계 시각 판단 로직을 반열린 구간으로 통일하여 translateApplication과 updateAttendanceToApplication의 결과가 일치하도록 수정했습니다.


[2] NonUniqueResultException 버그

문제 원인

org.springframework.dao.IncorrectResultSizeDataAccessException:
query did not return a unique result: 2

tbl_attendance, tbl_status 테이블에 user_id UNIQUE 제약이 없어 중복 행이 존재하는 경우, Spring Data JPA의 findByUserId 단건 조회(getSingleResult())가 예외를 던집니다.

tbl_status의 중복 행 문제는 SaveAllStatusUserService의 주석에서 이미 인지되고 있었으나 단건 조회 쿼리는 수정되지 않은 상태였습니다.

수정 내용

변경 내용
AttendanceRepository findByUserId → findFirstByUserId (LIMIT 1 적용)
StatusRepository findByUserId → findFirstByUserId (LIMIT 1 적용)
어댑터 2곳 ?.let null-safe 처리
Flyway 마이그레이션 기존 중복 행 제거 + UNIQUE(user_id) 제약 추가

Test plan

  • TIME 타입 5교시 범위 외출 승인 시 6교시(period6)가 GO_OUT으로 바뀌지 않는지 확인
  • TIME 타입 6교시 범위 외출 승인 시 period6만 GO_OUT으로 변경되는지 확인
  • PERIOD 타입 외출 신청은 영향 없음 확인
  • 외출/조기귀가 승인 시 출석 업데이트 정상 동작 확인
  • /status/change 정상 동작 확인
  • 마이그레이션 실행 후 tbl_attendance, tbl_status 중복 행 없음 확인

🤖 Generated with Claude Code

5교시 종료 시간(14:40)과 6교시 시작 시간(14:30)이 10분 겹쳐
TIME 타입 외출 신청 시 해당 구간의 기간 매칭이 중복되는 버그 수정

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@coderabbitai

coderabbitai Bot commented Jun 2, 2026 •

Copy link
Copy Markdown

Warning

Review limit reached

@1210thatman, we couldn't start this review because you've reached your PR review rate limit.

More reviews will be available in 16 minutes and 29 seconds. Learn how PR review limits work.

Your organization has run out of usage credits. Purchase more in the billing tab.

⌛ How to resolve this issue?

After more reviews become available, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

🚦 How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans include higher PR review limits than trial, open-source, and free plans. In all cases, reviews become available again over time. During sustained high-volume PR review activity, CodeRabbit may temporarily slow when the next review becomes available.

Please see our Fair Usage Limits Policy for further information.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: c2010f5d-e0aa-4c3b-9515-01cb90510f50

📥 Commits

Reviewing files that changed from the base of the PR and between 8052778 and 312ab38.

📒 Files selected for processing (2)
  • src/main/kotlin/dsm/pick2024/domain/attendance/domain/service/AttendanceService.kt
  • src/main/resources/db/migration/V202606041000__deduplicate_and_add_unique_constraints.sql

Walkthrough

AttendanceService의 6교시 시작 시각을 14:30 → 14:40으로 변경하고, getMatchPeriods를 구간 겹침(overlap) 기준으로 바꿔 매칭 교시를 결정합니다. 또한 Attendance/Status 리포지토리 조회 시그니처가 첫번째 항목(널 가능) 반환으로 변경되고, 관련 어댑터들은 안전 호출로 매핑하도록 수정되었습니다. DB 마이그레이션으로 tbl_attendance/tbl_status의 user_id 중복 제거 및 유니크 제약이 추가됩니다.

Changes

출결 및 퍼시스턴스 변경

Layer / File(s) Summary
교시 정의 및 매칭 로직 변경
src/main/kotlin/dsm/pick2024/domain/attendance/domain/service/AttendanceService.kt
6교시 시작 시간을 LocalTime.of(14, 30) → LocalTime.of(14, 40)으로 변경하고, getMatchPeriods를 포함 범위 검사에서 구간 중첩(period.first < endTime && period.second > startTime) 기반으로 매칭 인덱스를 수집하도록 변경함.
Attendance 리포지토리 시그니처 및 어댑터 매핑
src/main/kotlin/dsm/pick2024/domain/attendance/persistence/repository/AttendanceRepository.kt, src/main/kotlin/dsm/pick2024/domain/attendance/persistence/AttendancePersistenceAdapter.kt
findByUserId → findFirstByUserId(널 가능)로 변경하고, 어댑터에서 결과를 ?.let { ... }로 안전하게 매핑하도록 수정함.
Status 리포지토리 시그니처 및 어댑터 매핑
src/main/kotlin/dsm/pick2024/domain/status/persistence/repository/StatusRepository.kt, src/main/kotlin/dsm/pick2024/domain/status/persistence/StatusPersistenceAdapterPort.kt
findFirstByUserId(userId): StatusJpaEntity?를 추가(기존 findByUserId 제거)하고, 어댑터에서 ?.let { statusMapper.toDomain(it) } 형태로 매핑함.
DB 마이그레이션: 중복 제거 및 유니크 제약 추가
src/main/resources/db/migration/V202606041000__deduplicate_and_add_unique_constraints.sql
tbl_attendance와 tbl_status의 user_id 중복 행들을 자기조인 삭제로 제거한 뒤 각각 uk_attendance_user_id, uk_status_user_id 유니크 제약을 추가하는 마이그레이션을 추가함.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Possibly related PRs

Suggested labels

bug, hotfix

Suggested reviewers

  • imhanseong
  • ByunDohwi

Poem

🐰 나는 토끼, 코드밭을 뛰네,
여섯 번째 종소리, 십사 반 사십분에 맞추네.
작은 시간 한 줄이 경계를 바꾸고,
겹침을 세어 교시를 찾으며,
DB에 중복을 정리한 뒤 깔끔히 잠그네.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 0.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed PR 제목이 PR의 주요 변경사항을 정확하게 반영하고 있습니다. '외출 출석 오처리 수정'은 교시 시간 겹침 문제를 다루며, 'NonUniqueResultException 버그 수정'은 데이터베이스 제약 추가를 다룹니다.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/picnic-period-overlap-bug

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@src/main/kotlin/dsm/pick2024/domain/attendance/domain/service/AttendanceService.kt`:
- Line 20: getMatchPeriods currently treats period ranges as inclusive at both
ends which conflicts with translateApplication/updateAttendanceToApplication's
overlap logic and causes boundary times (e.g., 14:40) to match the previous
period; update getMatchPeriods to use the same half-open/overlap rule as
updateAttendanceToApplication and translateApplication (i.e., treat period end
as exclusive) so comparisons use start <= time && time < end (or the equivalent
overlap check used elsewhere); adjust any helper comparisons in getMatchPeriods
to reference the existing period identifiers (period start/end variables used in
getMatchPeriods) to keep behavior consistent with translateApplication() and
updateAttendanceToApplication().
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 95bd7b4e-aa13-4295-87e4-3a1acc514c6d

📥 Commits

Reviewing files that changed from the base of the PR and between 44ece16 and 04df5a3.

📒 Files selected for processing (1)
  • src/main/kotlin/dsm/pick2024/domain/attendance/domain/service/AttendanceService.kt

start..endAt 양끝 포함 비교로 인해 14:40 등 경계 시각이
이전 교시에 잡혀 translateApplication과 updateAttendanceToApplication의
결과가 불일치하던 문제 수정

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@1210thatman 1210thatman self-assigned this Jun 4, 2026
ByunDohwi
ByunDohwi previously approved these changes Jun 4, 2026
1210thatman and others added 3 commits June 4, 2026 19:27
중복 행 존재 시 getSingleResult() 호출로 발생하는
NonUniqueResultException 방지를 위해 LIMIT 1이 적용되는
findFirstByUserId로 변경

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
tbl_status 중복 행으로 인한 NonUniqueResultException 방지
SaveAllStatusUserService에서 이미 중복 행 존재를 인지하고 있었으나
단건 조회 쿼리는 수정되지 않은 상태였음

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
- user_id 기준 중복 행 제거 (가장 작은 id 1건 유지)
- UNIQUE(user_id) 제약 추가로 동일 문제 재발 방지

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@1210thatman 1210thatman changed the title fix :: 5교시~6교시 교시 시간 겹침으로 인한 외출 출석 오처리 수정 fix :: 외출 출석 오처리 수정 및 NonUniqueResultException 버그 수정 Jun 4, 2026

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@src/main/kotlin/dsm/pick2024/domain/attendance/domain/service/AttendanceService.kt`:
- Around line 171-175: The bug is that getMatchPeriods uses half-open overlap
(period.first.isBefore(endTime) && period.second.isAfter(startTime)) so
zero-length intervals (startTime == endTime) never match, but
checkApplicationTime currently allows startTime == endTime; make them consistent
by tightening checkApplicationTime to reject zero-length intervals—change its
validation to require startTime.isBefore(endTime) (i.e., disallow startTime ==
endTime) in the checkApplicationTime function so requests that pass creation
also pass approval, and keep getMatchPeriods as-is.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yaml

Review profile: CHILL

Plan: Pro

Run ID: 83208d5a-652b-43ae-ae40-4ac4a0ceac61

📥 Commits

Reviewing files that changed from the base of the PR and between 04df5a3 and 8052778.

📒 Files selected for processing (6)
  • src/main/kotlin/dsm/pick2024/domain/attendance/domain/service/AttendanceService.kt
  • src/main/kotlin/dsm/pick2024/domain/attendance/persistence/AttendancePersistenceAdapter.kt
  • src/main/kotlin/dsm/pick2024/domain/attendance/persistence/repository/AttendanceRepository.kt
  • src/main/kotlin/dsm/pick2024/domain/status/persistence/StatusPersistenceAdapterPort.kt
  • src/main/kotlin/dsm/pick2024/domain/status/persistence/repository/StatusRepository.kt
  • src/main/resources/db/migration/V202606041000__deduplicate_and_add_unique_constraints.sql

1210thatman and others added 2 commits June 4, 2026 19:37
getMatchPeriods는 반열린 구간 겹침을 사용하므로
startTime == endTime이면 항상 빈 매칭으로 InvalidPeriodException 발생
checkApplicationTime도 동일 기준으로 맞춰 신청·승인 단계 불일치 제거

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
동료가 이미 중복 데이터를 직접 정리했으므로
UNIQUE 제약 추가만 남기고 DELETE 구문 제거

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
@1210thatman
1210thatman merged commit a6bea9e into develop Jun 4, 2026
1 check passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants