Skip to content
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

feat: 수료 철회시 쿠폰 회수 이벤트 구현 #857

Merged

Conversation

Sangwook02
Copy link
Member

@Sangwook02 Sangwook02 commented Jan 28, 2025

🌱 관련 이슈

📌 작업 내용 및 특이사항

  • 수료 처리하여 쿠폰이 발급되었지만 이를 철회했다가 다시 수료처리한다면 IssuedCoupon이 두 개 존재하게 됩니다. 하나는 revoke가 true고 하나는 false가 됩니다. 따라서 Revoke가 false인 발급 쿠폰을 가져오도록 해야합니다.

📝 참고사항

📚 기타

Summary by CodeRabbit

  • 새로운 기능

    • 스터디 완료 쿠폰 취소 기능 추가
    • 스터디 이력에 따른 쿠폰 관리 기능 개선
    • 회원 객체를 기반으로 한 쿠폰 필터링 기능 추가
  • 버그 수정

    • 쿠폰 발급 및 취소 프로세스의 트랜잭션 안정성 강화
  • 리팩토링

    • 쿠폰 관련 이벤트 핸들러 및 서비스 로직 최적화
    • 쿠폰 조회 및 필터링 메서드 개선

@Sangwook02 Sangwook02 self-assigned this Jan 28, 2025
@Sangwook02 Sangwook02 requested a review from a team as a code owner January 28, 2025 13:35
Copy link

coderabbitai bot commented Jan 28, 2025

Walkthrough

이 풀 리퀘스트는 스터디 수료 철회 시 발급된 쿠폰을 회수하는 새로운 기능을 추가합니다. CouponEventHandler에 새로운 이벤트 핸들러 메서드를 도입하고, CouponService에 쿠폰 회수 로직을 구현했습니다. 또한 IssuedCouponCustomRepository와 관련 클래스들에 쿠폰 조회 및 회수를 위한 메서드를 추가했습니다.

Changes

파일 변경 요약
src/.../CouponEventHandler.java 스터디 수료 철회 이벤트 핸들러 메서드 추가
src/.../CouponService.java 쿠폰 회수 메서드 revokeStudyCompletionCouponByStudyHistoryId 추가
src/.../IssuedCouponCustomRepository.java 비취소 쿠폰 조회 메서드 추가
src/.../IssuedCouponCustomRepositoryImpl.java 쿠폰 조회 쿼리 구현
src/.../IssuedCouponQueryMethod.java 멤버 기반 필터링 메서드 추가

Assessment against linked issues

목표 해결 여부 설명
스터디 수료 철회 시 쿠폰 회수 기능 추가 [#841]

Possibly related PRs

Suggested labels

✨ feature

Suggested reviewers

  • kckc0608

Poem

🐰 쿠폰 회수의 토끼 춤 🎫
스터디 철회, 쿠폰도 춤추네
이벤트 핸들러 깡총깡총
기능은 쉽게, 코드는 깔끔하게
토끼의 마법, 완성! 🎉

✨ Finishing Touches
  • 📝 Generate Docstrings (Beta)

Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

❤️ 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.
    • Generate unit testing code for this file.
    • 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 generate unit testing code for this file.
    • @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 generate unit testing code.
    • @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.

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. (Beta)
  • @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.

CodeRabbit Configuration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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.

Copy link

Job Summary for Gradle

Check Style and Test to Develop :: build-test
Gradle Root Project Requested Tasks Gradle Version Build Outcome Build Scan®
gdsc check 8.5 Build Scan published

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: 1

🧹 Nitpick comments (3)
src/main/java/com/gdschongik/gdsc/domain/coupon/application/CouponEventHandler.java (1)

Line range hint 15-15: 도메인 이벤트 처리 방향성 검토가 필요합니다.

TODO 주석에서 언급된 것처럼, 도메인 이벤트 처리 방향이 일관되지 않은 것으로 보입니다. 아키텍처 일관성을 위해 이벤트 처리 방향을 통일하는 것이 좋겠습니다.

src/main/java/com/gdschongik/gdsc/domain/coupon/dao/IssuedCouponCustomRepositoryImpl.java (2)

41-52: 메서드에 JavaDoc 문서화가 필요합니다.

비즈니스 로직의 명확한 이해를 위해 다음 내용을 포함한 문서화를 추가해주세요:

  • 메서드의 목적
  • 각 매개변수의 역할
  • 반환값의 의미
  • 쿠폰 회수 로직에서의 역할

예시:

/**
 * 취소되지 않은(revoked=false) 발급된 쿠폰을 조회합니다.
 *
 * @param couponType 조회할 쿠폰의 유형
 * @param member 쿠폰을 발급받은 회원
 * @param study 쿠폰이 발급된 스터디
 * @return 조건에 맞는 발급된 쿠폰 (Optional)
 */

41-52: 매개변수 유효성 검사 추가를 고려해주세요.

null 매개변수로 인한 잠재적인 문제를 방지하기 위해 다음과 같은 검증 로직 추가를 제안드립니다:

@Override
public Optional<IssuedCoupon> findNonRevokedIssuedCouponByCouponTypeAndMemberAndStudy(
        CouponType couponType, Member member, Study study) {
    Objects.requireNonNull(couponType, "쿠폰 타입은 null일 수 없습니다");
    Objects.requireNonNull(member, "회원은 null일 수 없습니다");
    Objects.requireNonNull(study, "스터디는 null일 수 없습니다");
    
    return Optional.ofNullable(queryFactory
            .selectFrom(issuedCoupon)
            // ... 나머지 쿼리 로직 ...
}
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 3f5ea6e and e15cc21.

📒 Files selected for processing (5)
  • src/main/java/com/gdschongik/gdsc/domain/coupon/application/CouponEventHandler.java (2 hunks)
  • src/main/java/com/gdschongik/gdsc/domain/coupon/application/CouponService.java (3 hunks)
  • src/main/java/com/gdschongik/gdsc/domain/coupon/dao/IssuedCouponCustomRepository.java (1 hunks)
  • src/main/java/com/gdschongik/gdsc/domain/coupon/dao/IssuedCouponCustomRepositoryImpl.java (2 hunks)
  • src/main/java/com/gdschongik/gdsc/domain/coupon/dao/IssuedCouponQueryMethod.java (2 hunks)
🧰 Additional context used
📓 Learnings (1)
src/main/java/com/gdschongik/gdsc/domain/coupon/application/CouponService.java (1)
Learnt from: kckc0608
PR: GDSC-Hongik/gdsc-server#847
File: src/main/java/com/gdschongik/gdsc/domain/coupon/application/CouponService.java:115-115
Timestamp: 2025-01-22T12:27:00.185Z
Learning: Discount amounts in the coupon domain should be managed as constants rather than hardcoded values, especially for specific coupon types like study completion coupons.
🔇 Additional comments (5)
src/main/java/com/gdschongik/gdsc/domain/coupon/dao/IssuedCouponCustomRepository.java (1)

16-17: 메서드 시그니처가 명확하고 적절합니다!

Optional 반환 타입을 사용하여 결과가 없을 수 있는 상황을 잘 처리했습니다.

src/main/java/com/gdschongik/gdsc/domain/coupon/application/CouponEventHandler.java (1)

25-29: 이벤트 핸들러 구현이 깔끔합니다!

기존 패턴을 일관되게 따르고 있으며, BEFORE_COMMIT 페이즈를 적절히 사용하고 있습니다.

src/main/java/com/gdschongik/gdsc/domain/coupon/dao/IssuedCouponQueryMethod.java (1)

20-22: 쿼리 메서드 구현이 일관성 있고 안전합니다!

null 체크를 통한 안전한 처리와 기존 쿼리 메서드들과의 일관된 패턴을 잘 유지하고 있습니다.

src/main/java/com/gdschongik/gdsc/domain/coupon/application/CouponService.java (1)

133-148: 쿠폰 회수 메서드 구현이 견고합니다!

  • 트랜잭션 처리가 적절합니다
  • 예외 처리가 명확합니다
  • 로깅이 충분합니다
src/main/java/com/gdschongik/gdsc/domain/coupon/dao/IssuedCouponCustomRepositoryImpl.java (1)

6-14: 새로운 import 문이 적절히 추가되었습니다!

새로운 기능 구현에 필요한 클래스들이 명확하게 import 되었습니다.

@@ -109,7 +110,7 @@ public void createAndIssueCouponByStudyHistories(List<Long> studyHistoryIds) {
List<Member> students = memberRepository.findAllById(studentIds);
Study study = studyHistories.get(0).getStudy();

Coupon coupon = findOrCreate(CouponType.STUDY_COMPLETION, study);
Coupon coupon = findOrCreate(STUDY_COMPLETION, study);
Copy link

Choose a reason for hiding this comment

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

🛠️ Refactor suggestion

상수로 관리되어야 할 할인 금액이 하드코딩되어 있습니다.

이전 피드백에 따르면, 특정 쿠폰 타입의 할인 금액은 상수로 관리되어야 합니다. Money.FIVE_THOUSAND을 쿠폰 타입별 상수로 분리하는 것이 좋겠습니다.

+ private static final Money STUDY_COMPLETION_DISCOUNT_AMOUNT = Money.FIVE_THOUSAND;

 private Coupon findOrCreate(CouponType couponType, Study study) {
     return couponRepository.findByCouponTypeAndStudy(couponType, study).orElseGet(() -> {
         String couponName = couponNameUtil.generateStudyCompletionCouponName(study);
-        Coupon coupon = Coupon.createAutomatic(couponName, Money.FIVE_THOUSAND, couponType, study);
+        Coupon coupon = Coupon.createAutomatic(couponName, STUDY_COMPLETION_DISCOUNT_AMOUNT, couponType, study);
         return couponRepository.save(coupon);
     });
 }

Committable suggestion skipped: line range outside the PR's diff.

import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;

public interface IssuedCouponCustomRepository {

Page<IssuedCoupon> findAllIssuedCoupons(IssuedCouponQueryOption queryOption, Pageable pageable);

Optional<IssuedCoupon> findNonRevokedIssuedCouponByCouponTypeAndMemberAndStudy(
Copy link
Member

Choose a reason for hiding this comment

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

Suggested change
Optional<IssuedCoupon> findNonRevokedIssuedCouponByCouponTypeAndMemberAndStudy(
Optional<IssuedCoupon> findUnrevokedIssuedStudyCoupon(

spring data jpa 사용하는게 아니라서, byCouponTypeAnd... 는 안붙여줘도 파라미터 단에서 충분히 파악 가능한 컨텍스트일 것 같네요.

Copy link
Member Author

Choose a reason for hiding this comment

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

안 그래도 이 부분 고민하긴 했는데 다른 querydsl 쿼리들을 저런식으로 네이밍한 것 같아서 일단 이렇게 해뒀습니다.
일단 이 부분은 제안 내용으로 수정하고 이외 쿼리들은 여유있을때 별도 이슈에서 처리하겠습니다~

Copy link
Member

Choose a reason for hiding this comment

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

굿입니다 이슈 추가부탁드려요

return Optional.ofNullable(queryFactory
.selectFrom(issuedCoupon)
.leftJoin(issuedCoupon.coupon, coupon)
.where(hasRevoked(false)
Copy link
Member

Choose a reason for hiding this comment

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

fk 잡혀있는 eqMember -> eqStudy를 먼저 걸고, 그 다음에 eqType과 hasRevoked 순서로 where 조건 거는 게 더 나을 것 같네요.

Copy link
Member Author

Choose a reason for hiding this comment

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

맞네요
좋은 지적 감사드려요

Copy link

Job Summary for Gradle

Check Style and Test to Develop :: build-test
Gradle Root Project Requested Tasks Gradle Version Build Outcome Build Scan®
gdsc check 8.5 Build Scan published

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: 0

🧹 Nitpick comments (2)
src/main/java/com/gdschongik/gdsc/domain/coupon/dao/IssuedCouponCustomRepositoryImpl.java (2)

46-49: 쿼리 성능 최적화를 위한 where 조건 순서 개선이 필요합니다.

FK 관계와 인덱스 활용을 고려하여 where 조건의 순서를 다음과 같이 변경하는 것이 좋을 것 같습니다:

-                .where(eqMember(member)
-                        .and(coupon.study.eq(study))
-                        .and(hasRevoked(false))
-                        .and(coupon.couponType.eq(couponType)))
+                .where(coupon.study.eq(study)
+                        .and(eqMember(member))
+                        .and(coupon.couponType.eq(couponType))
+                        .and(hasRevoked(false)))

변경 이유:

  1. FK 관계가 있는 study 조건을 먼저 적용하여 초기 결과셋을 최소화
  2. member와 couponType으로 추가 필터링
  3. 마지막으로 revoked 상태 확인

43-45: leftJoin 사용이 필요한지 검토가 필요합니다.

현재 쿼리에서는 coupon 엔티티의 필드들을 where 절에서만 사용하고 있습니다. 이 경우 leftJoin 대신 innerJoin을 사용하는 것이 더 적절할 것 같습니다.

-                .leftJoin(issuedCoupon.coupon, coupon)
+                .join(issuedCoupon.coupon, coupon)
📜 Review details

Configuration used: CodeRabbit UI
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e15cc21 and fd45b35.

📒 Files selected for processing (3)
  • src/main/java/com/gdschongik/gdsc/domain/coupon/application/CouponService.java (3 hunks)
  • src/main/java/com/gdschongik/gdsc/domain/coupon/dao/IssuedCouponCustomRepository.java (1 hunks)
  • src/main/java/com/gdschongik/gdsc/domain/coupon/dao/IssuedCouponCustomRepositoryImpl.java (2 hunks)
🚧 Files skipped from review as they are similar to previous changes (1)
  • src/main/java/com/gdschongik/gdsc/domain/coupon/application/CouponService.java
🔇 Additional comments (1)
src/main/java/com/gdschongik/gdsc/domain/coupon/dao/IssuedCouponCustomRepository.java (1)

16-16: 메서드 구현이 적절해 보입니다.

Optional 반환 타입의 사용과 메서드 시그니처가 명확하며, 이전 리뷰에서 논의된 네이밍 컨벤션이 잘 반영되었습니다.

Copy link
Member

@kckc0608 kckc0608 left a comment

Choose a reason for hiding this comment

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

lgtm

Copy link
Member

@uwoobeat uwoobeat left a comment

Choose a reason for hiding this comment

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

lgtm

@Sangwook02 Sangwook02 merged commit 621c9a2 into develop Jan 30, 2025
1 check passed
@Sangwook02 Sangwook02 deleted the feature/841-revoke-coupon-on-study-completion-withdrawal branch January 30, 2025 11:09
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.

✨ 스터디 수료 철회 시 발급된 쿠폰 회수하는 기능 추가
3 participants