Skip to content

Conversation

@move-hoon
Copy link
Member

@move-hoon move-hoon commented Aug 1, 2025

🔗 관련 이슈

📘 작업 유형

  • ✨ Feature (기능 추가)
  • 🐞 Bugfix (버그 수정)
  • 🔧 Refactor (코드 리팩토링)
  • ⚙️ Chore (환경 설정)
  • 📝 Docs (문서 작성 및 수정)
  • ✅ Test (기능 테스트)
  • 🎨 style (코드 스타일 수정)

📙 작업 내역

✨ 감정 태그 통계 기능 구현

  • ReadingRecordTag 조회 기능 추가

    • JpaReadingRecordTagQuerydslRepository 인터페이스 생성
    • countTagsByUserIdAndCategories 메서드로 사용자별 감정 태그 카운팅 기능 구현
    • 3중 조인을 통한 효율적인 데이터 조회 (ReadingRecordTag → ReadingRecord → UserBook → Tag)
  • Seed API 구현

    • SeedController에 사용자별 씨앗(감정 태그) 통계 조회 API 추가
    • /api/v1/seeds/stats 엔드포인트 구현

🔧 컨트롤러 구조 개선

  • API 명세와 구현 분리
    • SeedControllerApi 인터페이스 생성하여 Swagger 명세 분리
    • SeedController는 순수 비즈니스 로직 구현에만 집중
    • 관심사 분리를 통한 코드 가독성 및 재사용성 향상

🧪 테스트 내역

  • 브라우저/기기에서 동작 확인
  • 엣지 케이스 테스트 완료
  • 기존 기능 영향 없음

🎨 스크린샷 또는 시연 영상 (선택)

기능 미리보기 기능 미리보기
기능 설명 기능 설명

✅ PR 체크리스트

  • 커밋 메시지가 명확합니다
  • PR 제목이 컨벤션에 맞습니다
  • 관련 이슈 번호를 작성했습니다
  • 기능이 정상적으로 작동합니다
  • 불필요한 코드를 제거했습니다

💬 추가 설명 or 리뷰 포인트 (선택)

🔍 주요 리뷰 포인트

  1. 3중 조인의 필요성

    -- ReadingRecordTag에서 사용자 정보에 접근하기 위한 조인 경로
    ReadingRecordTag → ReadingRecord → UserBook (userId 접근)
    ReadingRecordTag → Tag (태그 이름으로 필터링)
    • 정규화된 데이터베이스 구조에서 사용자별 감정 태그 통계를 얻기 위한 필수적인 조인
    • 데이터 무결성과 정규화 원칙을 유지하면서 효율적인 조회 구현
  2. 성능 고려사항

    • deletedAt.isNull 조건으로 소프트 삭제된 데이터 제외
    • groupBy(tag.name)으로 태그별 집계 처리
    • 향후 인덱스 최적화 및 캐싱 적용 고려 가능

Summary by CodeRabbit

  • 신규 기능

    • 사용자의 감정 태그(씨앗) 통계 정보를 조회할 수 있는 REST API가 추가되었습니다.
    • 감정 태그 카테고리(따뜻함, 기쁨, 긴장, 슬픔)별로 씨앗 통계를 제공하는 응답 구조가 도입되었습니다.
  • 버그 수정

    • 불필요한 의존성 및 코드 스타일 개선이 일부 클래스에 반영되었습니다.
  • 리팩터링

    • 감정 태그 통계 집계 및 응답 생성을 위한 도메인/서비스/레포지토리 계층이 새롭게 설계되었습니다.

@coderabbitai
Copy link

coderabbitai bot commented Aug 1, 2025

📝 Walkthrough

Walkthrough

이 변경은 "내가 모은 씨앗 카운팅 GET API"를 도메인부터 API 레이어까지 신규로 구현합니다. 주요 변경에는 Seed 관련 컨트롤러, 서비스, 유스케이스, DTO, 도메인 서비스, VO, 인프라 레포지토리 및 쿼리 구현이 포함됩니다. 기존 Book/ReadingRecord 유스케이스 일부 의존성 정리 및 포맷팅 변경도 있습니다.

Changes

Cohort / File(s) Change Summary
Seed API 신규 도입
apis/src/main/kotlin/org/yapp/apis/seed/controller/SeedController.kt, apis/src/main/kotlin/org/yapp/apis/seed/controller/SeedControllerApi.kt, apis/src/main/kotlin/org/yapp/apis/seed/dto/response/SeedStatsResponse.kt, apis/src/main/kotlin/org/yapp/apis/seed/service/SeedService.kt, apis/src/main/kotlin/org/yapp/apis/seed/usecase/SeedUseCase.kt
Seed(씨앗) 카테고리별 카운트 조회 API 컨트롤러, API 인터페이스, 응답 DTO, 서비스, 유스케이스 신규 추가
Seed 도메인 계층 구현
domain/src/main/kotlin/org/yapp/domain/readingrecordtag/ReadingRecordTagDomainService.kt, domain/src/main/kotlin/org/yapp/domain/readingrecordtag/vo/TagStatsVO.kt, domain/src/main/kotlin/org/yapp/domain/readingrecordtag/ReadingRecordTagRepository.kt
도메인 서비스, VO, 레포지토리 메서드 추가로 씨앗(감정 태그) 카테고리별 카운트 조회 로직 구현
Seed 인프라스트럭처 계층 구현
infra/src/main/kotlin/org/yapp/infra/readingrecordtag/repository/JpaReadingRecordTagQuerydslRepository.kt, infra/src/main/kotlin/org/yapp/infra/readingrecordtag/repository/JpaReadingRecordTagRepository.kt, infra/src/main/kotlin/org/yapp/infra/readingrecordtag/repository/impl/JpaReadingRecordTagQuerydslRepositoryImpl.kt, infra/src/main/kotlin/org/yapp/infra/readingrecordtag/repository/impl/ReadingRecordTagRepositoryImpl.kt
QueryDSL 기반 카테고리별 태그 카운트 쿼리 인터페이스/구현 추가, 기존 레포지토리 확장 및 위임 구현
Seed 공통 유틸리티
global-utils/src/main/kotlin/org/yapp/globalutils/tag/GeneralEmotionTagCategory.kt
감정 태그 카테고리 enum 및 displayName 매핑 유틸 추가
Book/ReadingRecord 유스케이스 포맷팅 및 의존성 정리
apis/src/main/kotlin/org/yapp/apis/book/usecase/BookUseCase.kt, apis/src/main/kotlin/org/yapp/apis/readingrecord/usecase/ReadingRecordUseCase.kt
BookUseCase 생성자 포맷팅 정리, ReadingRecordUseCase에서 불필요한 의존성 및 import 제거

Sequence Diagram(s)

sequenceDiagram
    participant Client
    participant SeedController
    participant SeedUseCase
    participant UserAuthService
    participant SeedService
    participant ReadingRecordTagDomainService
    participant ReadingRecordTagRepository

    Client->>SeedController: GET /api/v1/seeds/stats (인증된 userId)
    SeedController->>SeedUseCase: getSeedStats(userId)
    SeedUseCase->>UserAuthService: validateUserExists(userId)
    UserAuthService-->>SeedUseCase: (유저 존재 여부 반환)
    SeedUseCase->>SeedService: getSeedStatsByUserId(userId)
    SeedService->>ReadingRecordTagDomainService: countTagsByUserIdAndCategories(userId, 카테고리목록)
    ReadingRecordTagDomainService->>ReadingRecordTagRepository: countTagsByUserIdAndCategories(userId, 카테고리목록)
    ReadingRecordTagRepository-->>ReadingRecordTagDomainService: Map<카테고리, 개수>
    ReadingRecordTagDomainService-->>SeedService: TagStatsVO
    SeedService-->>SeedUseCase: SeedStatsResponse
    SeedUseCase-->>SeedController: SeedStatsResponse
    SeedController-->>Client: 200 OK + SeedStatsResponse
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~20 minutes

Assessment against linked issues

Objective Addressed Explanation
내가 모은 씨앗 카운팅 GET API 구현 (#69)

Assessment against linked issues: Out-of-scope changes

해당 이슈의 목적과 직접적으로 관련 없는 변경사항은 발견되지 않았습니다.

Possibly related PRs

Suggested labels

✨ feat

✨ Finishing Touches
  • 📝 Generate Docstrings
🧪 Generate unit tests
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch BOOK-204-feature/#69

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
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai generate unit tests to generate unit tests for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@sonarqubecloud
Copy link

sonarqubecloud bot commented Aug 1, 2025

Quality Gate Failed Quality Gate failed

Failed conditions
10.6% Coverage on New Code (required ≥ 80%)

See analysis details on SonarQube Cloud

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 4

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: ASSERTIVE
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between fcafa33 and a68002e.

📒 Files selected for processing (15)
  • apis/src/main/kotlin/org/yapp/apis/book/usecase/BookUseCase.kt (0 hunks)
  • apis/src/main/kotlin/org/yapp/apis/readingrecord/usecase/ReadingRecordUseCase.kt (1 hunks)
  • apis/src/main/kotlin/org/yapp/apis/seed/controller/SeedController.kt (1 hunks)
  • apis/src/main/kotlin/org/yapp/apis/seed/controller/SeedControllerApi.kt (1 hunks)
  • apis/src/main/kotlin/org/yapp/apis/seed/dto/response/SeedStatsResponse.kt (1 hunks)
  • apis/src/main/kotlin/org/yapp/apis/seed/service/SeedService.kt (1 hunks)
  • apis/src/main/kotlin/org/yapp/apis/seed/usecase/SeedUseCase.kt (1 hunks)
  • domain/src/main/kotlin/org/yapp/domain/readingrecordtag/ReadingRecordTagDomainService.kt (1 hunks)
  • domain/src/main/kotlin/org/yapp/domain/readingrecordtag/ReadingRecordTagRepository.kt (1 hunks)
  • domain/src/main/kotlin/org/yapp/domain/readingrecordtag/vo/TagStatsVO.kt (1 hunks)
  • global-utils/src/main/kotlin/org/yapp/globalutils/tag/GeneralEmotionTagCategory.kt (1 hunks)
  • infra/src/main/kotlin/org/yapp/infra/readingrecordtag/repository/JpaReadingRecordTagQuerydslRepository.kt (1 hunks)
  • infra/src/main/kotlin/org/yapp/infra/readingrecordtag/repository/JpaReadingRecordTagRepository.kt (1 hunks)
  • infra/src/main/kotlin/org/yapp/infra/readingrecordtag/repository/impl/JpaReadingRecordTagQuerydslRepositoryImpl.kt (1 hunks)
  • infra/src/main/kotlin/org/yapp/infra/readingrecordtag/repository/impl/ReadingRecordTagRepositoryImpl.kt (2 hunks)
💤 Files with no reviewable changes (1)
  • apis/src/main/kotlin/org/yapp/apis/book/usecase/BookUseCase.kt
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (1)
  • GitHub Check: build-validation
🔇 Additional comments (20)
domain/src/main/kotlin/org/yapp/domain/readingrecordtag/ReadingRecordTagRepository.kt (1)

8-8: 새로운 메서드 시그니처가 적절합니다

countTagsByUserIdAndCategories 메서드의 시그니처가 명확하고 용도에 적합합니다. 사용자별 카테고리 태그 통계 조회라는 요구사항을 잘 반영한 인터페이스 설계입니다.

infra/src/main/kotlin/org/yapp/infra/readingrecordtag/repository/JpaReadingRecordTagRepository.kt (1)

7-7: QueryDSL 확장이 적절하게 구현되었습니다

JpaReadingRecordTagQuerydslRepository를 추가로 확장하여 커스텀 쿼리 메서드를 통합한 것이 Spring Data JPA의 모범 사례를 따르고 있습니다.

domain/src/main/kotlin/org/yapp/domain/readingrecordtag/ReadingRecordTagDomainService.kt (1)

7-15: 도메인 서비스가 클린 아키텍처 원칙을 잘 따르고 있습니다

@DomainService 어노테이션을 사용한 명확한 계층 구분과 리포지토리 위임 후 값 객체로 래핑하는 패턴이 적절합니다. 단일 책임 원칙을 잘 지키고 있습니다.

apis/src/main/kotlin/org/yapp/apis/seed/controller/SeedController.kt (1)

11-23: SeedController 예외 처리: 전역 핸들러에서 이미 처리 중

UseCase 계층(getSeedStats)에서 발생하는 CommonException, IllegalArgumentException 등은
GlobalExceptionHandler에서 전역으로 처리되고 있어 컨트롤러에서 별도 예외 핸들러를 추가할 필요가 없습니다.

  • 전역 예외 처리 클래스:
    global-utils/src/main/kotlin/org/yapp/globalutils/exception/GlobalExceptionHandler.kt
apis/src/main/kotlin/org/yapp/apis/seed/service/SeedService.kt (1)

13-13: 메서드명과 매개변수 검증

userId 매개변수에 대한 null 체크나 유효성 검증이 없습니다. 하지만 도메인 서비스나 상위 레이어에서 검증되고 있다면 현재 구현이 적절합니다.

apis/src/main/kotlin/org/yapp/apis/seed/usecase/SeedUseCase.kt (1)

10-20: 깔끔한 UseCase 구현

사용자 존재 검증 후 씨앗 통계를 조회하는 로직이 명확하고, @Transactional(readOnly = true) 어노테이션으로 읽기 전용 트랜잭션을 적절히 설정했습니다. 관심사의 분리도 잘 되어 있습니다.

global-utils/src/main/kotlin/org/yapp/globalutils/tag/GeneralEmotionTagCategory.kt (1)

3-18: 잘 구현된 감정 태그 카테고리 열거형

한국어 displayName과 효율적인 lookup을 위한 companion object 구현이 깔끔합니다. associateBy를 사용한 맵 생성과 null-safe한 fromDisplayName 함수도 적절합니다.

apis/src/main/kotlin/org/yapp/apis/seed/controller/SeedControllerApi.kt (1)

16-41: API 명세 인터페이스 설계 우수

OpenAPI 어노테이션을 통한 API 문서화가 잘 되어 있고, 응답 코드(200, 404)와 스키마 정의가 적절합니다. 인터페이스와 구현체를 분리하여 코드 가독성과 재사용성을 높인 점도 좋습니다.

domain/src/main/kotlin/org/yapp/domain/readingrecordtag/vo/TagStatsVO.kt (1)

6-13: 검증 로직과 불변성 보장 우수

private constructor와 init 블록의 검증 로직으로 데이터 무결성을 잘 보장하고 있습니다. EnumMap 사용도 성능상 적절한 선택입니다.

infra/src/main/kotlin/org/yapp/infra/readingrecordtag/repository/impl/ReadingRecordTagRepositoryImpl.kt (4)

1-1: 패키지 구조 개선이 적절합니다.

구현체를 impl 서브패키지로 이동한 것은 코드 구조화에 도움이 됩니다.


7-8: 필요한 import 추가가 적절합니다.

새로운 기능 구현을 위한 JpaReadingRecordTagRepositoryUUID import가 올바르게 추가되었습니다.


19-21: UUID 타입 사용 개선이 좋습니다.

완전한 패키지명 대신 import된 UUID 타입을 직접 사용하는 것이 더 깔끔합니다.


23-25: 리포지토리 위임 패턴이 올바르게 구현되었습니다.

도메인 레이어의 인터페이스를 구현하면서 JPA 리포지토리에 위임하는 구조가 적절합니다. 메서드 시그니처도 사용 목적에 맞게 설계되었습니다.

infra/src/main/kotlin/org/yapp/infra/readingrecordtag/repository/impl/JpaReadingRecordTagQuerydslRepositoryImpl.kt (4)

27-29: 빈 카테고리 리스트에 대한 방어적 프로그래밍이 우수합니다.

빈 카테고리 리스트에 대해 조기 반환하는 것은 불필요한 데이터베이스 쿼리를 방지하고 성능을 개선합니다.


46-50: 결과 매핑에서 null 안전성이 잘 처리되었습니다.

tuple[tag.name] ?: ""tuple[readingRecordTag.count()]?.toInt() ?: 0을 통해 null 값에 대한 기본값 처리가 적절합니다.


53-67: 확장 함수를 통한 코드 가독성 개선이 훌륭합니다.

QueryDSL 엔티티에 확장 함수를 추가하여 predicate 로직을 캡슐화한 것이 코드 가독성과 재사용성을 크게 향상시킵니다.


31-44: 인덱스 정의 확인 및 성능 보장 요청

현재 코드베이스 내 마이그레이션 SQL(.sql/.xml)과 JPA 엔티티(@Index, @table(indexes))에서 user_book.user_idtag.name 컬럼에 대한 인덱스 생성 구문이 확인되지 않습니다. 대용량 데이터에서 쿼리 성능을 보장하기 위해 다음을 검토해 주세요:

  • 운영 데이터베이스 스키마에서 직접 인덱스 존재 여부 확인
    • MySQL: SHOW INDEX FROM user_book;, SHOW INDEX FROM tag;
    • PostgreSQL: \d+ user_book, \d+ tag
  • 누락된 경우 마이그레이션 SQL 또는 Liquibase/XML 파일에 CREATE INDEX/<createIndex> 추가
  • JPA 엔티티에 @Index 또는 @Table(indexes = ...) 어노테이션으로 인덱스 정의

위 사항을 직접 확인하고, 인덱스가 없을 시 적절히 추가해 주세요.

apis/src/main/kotlin/org/yapp/apis/seed/dto/response/SeedStatsResponse.kt (3)

6-8: private 생성자와 팩토리 메서드 패턴이 잘 적용되었습니다.

DTO의 생성을 제어하고 불변성을 보장하는 설계가 우수합니다. 중첩된 SeedCategoryStats 클래스도 동일한 패턴을 따라 일관성이 있습니다.

Also applies to: 9-11


21-29: 도메인에서 API로의 변환 로직이 적절합니다.

TagStatsVO에서 SeedStatsResponse로의 변환이 올바르게 구현되었습니다. getOrDefault(category, 0)를 사용하여 누락된 카테고리에 대해 기본값 0을 제공하는 것이 좋은 방어적 프로그래밍입니다.


22-22: 확인 완료: Kotlin 버전 1.9.25 사용 중
buildSrc/src/main/kotlin/Versions.kt에서 const val KOTLIN = "1.9.25"로 설정되어 있어, Kotlin 1.9.0부터 지원되는 GeneralEmotionTagCategory.entries 프로퍼티 사용이 안전합니다.

@move-hoon move-hoon merged commit fa125d1 into develop Aug 1, 2025
5 of 6 checks passed
@move-hoon move-hoon deleted the BOOK-204-feature/#69 branch August 12, 2025 06:29
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[BOOK-204/feat] 내가 모은 씨앗 카운팅 GET API 구현

2 participants