-
Notifications
You must be signed in to change notification settings - Fork 1
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: 스터디 수료 시 회비 할인 쿠폰 발급 기능 구현 #843
Changes from all commits
717c4dc
5ea880e
8b58b81
252019d
79621f6
cd7d83f
c36e7fc
a4459fd
24f3cf2
1e7a9a2
b5988e1
8e7723e
6b025a9
4671bef
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,23 @@ | ||
package com.gdschongik.gdsc.domain.coupon.application; | ||
|
||
import com.gdschongik.gdsc.domain.study.domain.StudyHistoriesCompletedEvent; | ||
import lombok.RequiredArgsConstructor; | ||
import lombok.extern.slf4j.Slf4j; | ||
import org.springframework.stereotype.Component; | ||
import org.springframework.transaction.event.TransactionPhase; | ||
import org.springframework.transaction.event.TransactionalEventListener; | ||
|
||
@Slf4j | ||
@Component | ||
@RequiredArgsConstructor | ||
public class CouponEventHandler { | ||
// TODO: 여기서는 쿠폰 외 도메인의 이벤트를 받아서 쿠폰 서비스를 호출. 다른 핸들러는 반대로 되어있으므로 수정 필요 | ||
|
||
private final CouponService couponService; | ||
|
||
@TransactionalEventListener(phase = TransactionPhase.BEFORE_COMMIT) | ||
public void handleStudyHistoryCompletedEvent(StudyHistoriesCompletedEvent event) { | ||
log.info("[CouponEventHandler] 스터디 수료 이벤트 수신: studyHistoryIds={}", event.studyHistoryIds()); | ||
couponService.createAndIssueCouponByStudyHistories(event.studyHistoryIds()); | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -12,8 +12,11 @@ | |
import com.gdschongik.gdsc.domain.coupon.dto.request.IssuedCouponQueryOption; | ||
import com.gdschongik.gdsc.domain.coupon.dto.response.CouponResponse; | ||
import com.gdschongik.gdsc.domain.coupon.dto.response.IssuedCouponResponse; | ||
import com.gdschongik.gdsc.domain.coupon.util.CouponNameUtil; | ||
import com.gdschongik.gdsc.domain.member.dao.MemberRepository; | ||
import com.gdschongik.gdsc.domain.member.domain.Member; | ||
import com.gdschongik.gdsc.domain.study.dao.StudyHistoryRepository; | ||
import com.gdschongik.gdsc.domain.study.domain.StudyHistory; | ||
import com.gdschongik.gdsc.global.exception.CustomException; | ||
import com.gdschongik.gdsc.global.util.MemberUtil; | ||
import java.util.List; | ||
|
@@ -30,7 +33,9 @@ | |
@Transactional(readOnly = true) | ||
public class CouponService { | ||
|
||
private final CouponNameUtil couponNameUtil; | ||
private final MemberUtil memberUtil; | ||
private final StudyHistoryRepository studyHistoryRepository; | ||
private final CouponRepository couponRepository; | ||
private final IssuedCouponRepository issuedCouponRepository; | ||
private final MemberRepository memberRepository; | ||
|
@@ -87,4 +92,28 @@ public List<IssuedCouponResponse> findMyUsableIssuedCoupons() { | |
.map(IssuedCouponResponse::from) | ||
.toList(); | ||
} | ||
|
||
@Transactional | ||
public void createAndIssueCouponByStudyHistories(List<Long> studyHistoryIds) { | ||
List<StudyHistory> studyHistories = studyHistoryRepository.findAllById(studyHistoryIds); | ||
List<Long> studentIds = studyHistories.stream() | ||
.map(studyHistory -> studyHistory.getStudent().getId()) | ||
.toList(); | ||
List<Member> students = memberRepository.findAllById(studentIds); | ||
|
||
String couponName = couponNameUtil.generateStudyCompletionCouponName( | ||
studyHistories.get(0).getStudy()); | ||
// TODO: 요청할 때마다 새로운 쿠폰 생성되는 문제 수정: 스터디마다 하나의 쿠폰만 존재하도록 쿠폰 타입 및 참조 식별자 추가 | ||
Coupon coupon = Coupon.create(couponName, Money.from(5000L)); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🛠️ Refactor suggestion 할인 금액이 하드코딩되어 있습니다. 쿠폰의 할인 금액이 5000원으로 하드코딩되어 있습니다. 이는 유연성이 떨어지며, 향후 할인 금액 변경 시 코드 수정이 필요합니다. 할인 금액을 설정 파일이나 데이터베이스에서 관리하는 것을 추천드립니다: - Coupon coupon = Coupon.create(couponName, Money.from(5000L));
+ Coupon coupon = Coupon.create(couponName, Money.from(couponProperties.getStudyCompletionDiscountAmount()));
|
||
couponRepository.save(coupon); | ||
|
||
List<IssuedCoupon> issuedCoupons = students.stream() | ||
.map(student -> IssuedCoupon.create(coupon, student)) | ||
.toList(); | ||
issuedCouponRepository.saveAll(issuedCoupons); | ||
|
||
log.info( | ||
"[CouponService] 스터디 수료 쿠폰 발급: issuedCouponIds={}", | ||
issuedCoupons.stream().map(IssuedCoupon::getId).toList()); | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,16 @@ | ||
package com.gdschongik.gdsc.domain.coupon.util; | ||
|
||
import com.gdschongik.gdsc.domain.study.domain.Study; | ||
import com.gdschongik.gdsc.global.util.formatter.SemesterFormatter; | ||
import lombok.RequiredArgsConstructor; | ||
import org.springframework.stereotype.Component; | ||
|
||
@Component | ||
@RequiredArgsConstructor | ||
public class CouponNameUtil { | ||
|
||
public String generateStudyCompletionCouponName(Study study) { | ||
String academicYearAndSemesterName = SemesterFormatter.format(study); | ||
return academicYearAndSemesterName + " " + study.getTitle() + " 수료 쿠폰"; | ||
} | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -6,6 +6,7 @@ | |
import com.gdschongik.gdsc.domain.study.dao.StudyHistoryRepository; | ||
import com.gdschongik.gdsc.domain.study.dao.StudyRepository; | ||
import com.gdschongik.gdsc.domain.study.domain.Study; | ||
import com.gdschongik.gdsc.domain.study.domain.StudyHistoriesCompletedEvent; | ||
import com.gdschongik.gdsc.domain.study.domain.StudyHistory; | ||
import com.gdschongik.gdsc.domain.study.domain.StudyHistoryValidator; | ||
import com.gdschongik.gdsc.domain.study.domain.StudyValidator; | ||
|
@@ -15,6 +16,7 @@ | |
import java.util.List; | ||
import lombok.RequiredArgsConstructor; | ||
import lombok.extern.slf4j.Slf4j; | ||
import org.springframework.context.ApplicationEventPublisher; | ||
import org.springframework.stereotype.Service; | ||
import org.springframework.transaction.annotation.Transactional; | ||
|
||
|
@@ -23,6 +25,7 @@ | |
@RequiredArgsConstructor | ||
public class MentorStudyHistoryService { | ||
|
||
private final ApplicationEventPublisher applicationEventPublisher; | ||
private final MemberUtil memberUtil; | ||
private final StudyValidator studyValidator; | ||
private final StudyHistoryValidator studyHistoryValidator; | ||
|
@@ -43,6 +46,9 @@ public void completeStudy(StudyCompleteRequest request) { | |
|
||
studyHistories.forEach(StudyHistory::complete); | ||
|
||
applicationEventPublisher.publishEvent(new StudyHistoriesCompletedEvent( | ||
studyHistories.stream().map(StudyHistory::getId).toList())); | ||
Comment on lines
+49
to
+50
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 철회랑 다르게 이 부분은 ApplicationEventPublisher를 써서 이벤트 발행한 이유가 있나요? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. StudyHistory ID 여러 개를 묶어서 하나의 이벤트로 발행해야 하기 때문에 StudyHistory 내부에서 발행하는게 불가능합니다 There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 아 맞네요 |
||
|
||
log.info( | ||
"[MentorStudyHistoryService] 스터디 수료 처리: studyId={}, studentIds={}", | ||
request.studyId(), | ||
|
@@ -63,6 +69,8 @@ public void withdrawStudyCompletion(StudyCompleteRequest request) { | |
|
||
studyHistories.forEach(StudyHistory::withdrawCompletion); | ||
|
||
studyHistoryRepository.saveAll(studyHistories); | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🛠️ Refactor suggestion 불필요한 saveAll 호출이 있습니다.
- studyHistoryRepository.saveAll(studyHistories); There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 엔티티 수정 시 변경 감지 기능만으로는 이벤트가 발행되지 않습니다. 도메인 이벤트 발행을 위해서는 명시적 save 호출이 필요합니다. 앞으로 JPA 변경 감지로 인한 명시적 save 호출과 관련된 변경내용은 제안하지 않아도 됩니다. There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. @uwoobeat 이해했습니다. JPA 변경 감지와 도메인 이벤트 발행에 대한 설명 감사합니다. 앞으로는 이러한 맥락에서의 명시적 save 호출에 대해 제안하지 않도록 하겠습니다. ✏️ Learnings added
|
||
|
||
log.info( | ||
"[MentorStudyHistoryService] 스터디 수료 철회: studyId={}, studentIds={}", | ||
request.studyId(), | ||
|
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
package com.gdschongik.gdsc.domain.study.domain; | ||
|
||
import java.util.List; | ||
import lombok.NonNull; | ||
|
||
public record StudyHistoriesCompletedEvent(@NonNull List<Long> studyHistoryIds) {} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,6 @@ | ||
package com.gdschongik.gdsc.domain.study.domain; | ||
|
||
public record StudyHistoryCompletionWithdrawnEvent(long studyHistoryId) { | ||
// TODO: 이벤트 내부 필드의 식별자 값은 항상 not null이므로, primitive 타입으로 사용하도록 변경 | ||
// TODO: 스터디 철회 시 기존에 발행된 쿠폰 회수하는 로직 구현 | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
package com.gdschongik.gdsc.domain.coupon.util; | ||
|
||
import static com.gdschongik.gdsc.global.common.constant.RecruitmentConstant.*; | ||
import static com.gdschongik.gdsc.global.common.constant.StudyConstant.*; | ||
import static org.assertj.core.api.Assertions.*; | ||
|
||
import com.gdschongik.gdsc.domain.common.model.SemesterType; | ||
import com.gdschongik.gdsc.domain.common.vo.Period; | ||
import com.gdschongik.gdsc.domain.member.domain.Member; | ||
import com.gdschongik.gdsc.domain.study.domain.Study; | ||
import com.gdschongik.gdsc.helper.FixtureHelper; | ||
import org.junit.jupiter.api.Test; | ||
|
||
class CouponNameUtilTest { | ||
|
||
CouponNameUtil couponNameUtil = new CouponNameUtil(); | ||
FixtureHelper fixtureHelper = new FixtureHelper(); | ||
|
||
@Test | ||
void 스터디_수료_쿠폰_이름이_생성된다() { | ||
// given | ||
Member mentor = fixtureHelper.createMentor(1L); | ||
Study study = Study.create( | ||
2025, | ||
SemesterType.FIRST, | ||
"기초 백엔드 스터디", | ||
mentor, | ||
STUDY_ONGOING_PERIOD, | ||
Period.of(START_DATE.minusDays(10), START_DATE.minusDays(5)), | ||
TOTAL_WEEK, | ||
ONLINE_STUDY, | ||
DAY_OF_WEEK, | ||
STUDY_START_TIME, | ||
STUDY_END_TIME); | ||
|
||
// when | ||
String couponName = couponNameUtil.generateStudyCompletionCouponName(study); | ||
|
||
// then | ||
assertThat(couponName).isEqualTo("2025-1 기초 백엔드 스터디 수료 쿠폰"); | ||
} | ||
Comment on lines
+19
to
+41
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 🛠️ Refactor suggestion 테스트 케이스 보완이 필요합니다. 현재는 정상 케이스만 테스트하고 있습니다. 다음과 같은 테스트 케이스들을 추가하는 것이 좋을 것 같습니다:
@Test
void null_스터디_입력시_예외가_발생한다() {
assertThatThrownBy(() -> couponNameUtil.generateStudyCompletionCouponName(null))
.isInstanceOf(IllegalArgumentException.class)
.hasMessage("스터디 정보는 null일 수 없습니다.");
}
@Test
void 특수문자가_포함된_스터디_제목으로_쿠폰_이름이_생성된다() {
Study study = Study.create(
2025,
SemesterType.FIRST,
"백엔드 스터디 (Spring)",
mentor,
STUDY_ONGOING_PERIOD,
Period.of(START_DATE.minusDays(10), START_DATE.minusDays(5)),
TOTAL_WEEK,
ONLINE_STUDY,
DAY_OF_WEEK,
STUDY_START_TIME,
STUDY_END_TIME);
String couponName = couponNameUtil.generateStudyCompletionCouponName(study);
assertThat(couponName).isEqualTo("2025-1 백엔드 스터디 (Spring) 수료 쿠폰");
} |
||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -69,6 +69,7 @@ class 스터디_수료_철회시 { | |
mentor, Period.of(now.plusDays(5), now.plusDays(10)), Period.of(now.minusDays(5), now)); | ||
|
||
StudyHistory studyHistory = StudyHistory.create(student, study); | ||
fixtureHelper.setId(studyHistory, 1L); // TODO: 이벤트 ID 필드를 원시 타입으로 설정하는 것 vs setId를 테스트 사용 강제 간 trade-off 고민 | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. pr description에 써두신 내용 읽어봤는데요, There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. 저도 동의합니다! |
||
studyHistory.complete(); | ||
|
||
// when | ||
|
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
NPE 방지가 필요합니다.
studyHistories
리스트가 비어있을 경우get(0)
호출 시IndexOutOfBoundsException
이 발생할 수 있습니다. 리스트가 비어있지 않은지 검증이 필요합니다.