Repository navigation
#35 공동구매 참여 API 구현 #38
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
Changes from all commits
be8275c
d60a1c7
3bab4d8
17a5b78
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,67 @@ | ||
| package com.ttuk.participation; | ||
|
|
||
| import com.ttuk.global.entity.BaseTimeEntity; | ||
| import com.ttuk.grouppurchase.GroupPurchase; | ||
| import com.ttuk.member.Member; | ||
| import jakarta.persistence.*; | ||
| import lombok.AccessLevel; | ||
| import lombok.Builder; | ||
| import lombok.Getter; | ||
| import lombok.NoArgsConstructor; | ||
| import org.hibernate.annotations.JdbcTypeCode; | ||
| import org.hibernate.type.SqlTypes; | ||
|
|
||
| import java.time.LocalDateTime; | ||
|
|
||
| @Entity | ||
| @Getter | ||
| @NoArgsConstructor(access = AccessLevel.PROTECTED) | ||
| @Table(uniqueConstraints = @UniqueConstraint( | ||
| name = "uk_participation_joined_member", | ||
| columnNames = {"group_purchase_id", "joined_member_id"})) | ||
| public class Participation extends BaseTimeEntity { | ||
|
|
||
| @Id | ||
| @GeneratedValue(strategy = GenerationType.IDENTITY) | ||
| private Long id; | ||
|
|
||
| @ManyToOne(fetch = FetchType.LAZY, optional = false) | ||
| @JoinColumn(name = "group_purchase_id", | ||
| foreignKey = @ForeignKey(name = "fk_participation_group_purchase")) | ||
| private GroupPurchase groupPurchase; | ||
|
|
||
| @ManyToOne(fetch = FetchType.LAZY, optional = false) | ||
| @JoinColumn(name = "member_id", | ||
| foreignKey = @ForeignKey(name = "fk_participation_member")) | ||
| private Member member; | ||
|
|
||
| @Column(nullable = false) | ||
| private int quantity; | ||
|
|
||
| @Enumerated(EnumType.STRING) | ||
| @JdbcTypeCode(SqlTypes.VARCHAR) | ||
| @Column(nullable = false, length = 20) | ||
| private ParticipationStatus status; | ||
|
|
||
| @Column(nullable = false) | ||
| private LocalDateTime joinedAt; | ||
|
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. BaseTimeEntity 의 createdAt 과 joinedAt 이 사실상 같은 값이에요. 두 값이 달라질 수 있는 경우가 없다면 하나만 써도 돼요.
Collaborator
Author
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. 말씀해 주신 대로 지금은 joinedAt을 저장 직전에 같은 Clock으로 넣고, createdAt은 저장 시점에 Auditing이 넣어서 값은 사실상 같습니다. 다만 createdAt은 행이 DB에 만들어진 시각을 남기는 감사용 값이고, joinedAt은 회원이 참여한 시각이라는 비즈니스 값이라 의미가 다르다고 생각했습니다. 지금은 행을 만드는 순간이 곧 참여한 순간이라 같지만, 나중에 데이터를 이관하거나 참여 행을 뒤늦게 보정해 만드는 경우가 생기면 두 값이 갈라질 수 있습니다. |
||
|
|
||
| private LocalDateTime canceledAt; | ||
|
|
||
| // JOINED일 때만 member_id, 그 외에는 NULL인 DB 계산 컬럼. | ||
| // (group_purchase_id, joined_member_id) 유니크로 같은 회원의 JOINED를 하나로 제한하고, | ||
| // NULL은 서로 중복으로 보지 않아 취소 기록은 여러 개 남길 수 있다. | ||
| @Column(name = "joined_member_id", | ||
| columnDefinition = "bigint generated always as (case when status = 'JOINED' then member_id end) virtual", | ||
| insertable = false, updatable = false) | ||
| private Long joinedMemberId; | ||
|
|
||
| @Builder | ||
| private Participation(GroupPurchase groupPurchase, Member member, int quantity, LocalDateTime joinedAt) { | ||
| this.groupPurchase = groupPurchase; | ||
| this.member = member; | ||
| this.quantity = quantity; | ||
| this.joinedAt = joinedAt; | ||
| this.status = ParticipationStatus.JOINED; | ||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,35 @@ | ||
| package com.ttuk.participation; | ||
|
|
||
| import com.ttuk.global.auth.Login; | ||
| import com.ttuk.global.auth.LoginMember; | ||
| import com.ttuk.global.auth.RequireRole; | ||
| import com.ttuk.global.response.ApiResponse; | ||
| import com.ttuk.member.MemberRole; | ||
| import com.ttuk.participation.dto.ParticipationCreateRequest; | ||
| import com.ttuk.participation.dto.ParticipationCreateResponse; | ||
| import jakarta.validation.Valid; | ||
| import lombok.RequiredArgsConstructor; | ||
| import org.springframework.http.HttpStatus; | ||
| import org.springframework.http.ResponseEntity; | ||
| import org.springframework.web.bind.annotation.*; | ||
|
|
||
| @RestController | ||
| @RequiredArgsConstructor | ||
| @RequestMapping("/api/group-purchases/{groupPurchaseId}/participants") | ||
| public class ParticipationController { | ||
|
|
||
| private final ParticipationService participationService; | ||
|
|
||
| @PostMapping | ||
| @RequireRole(MemberRole.BUYER) | ||
| public ResponseEntity<ApiResponse<ParticipationCreateResponse>> join(@PathVariable Long groupPurchaseId, | ||
| @Valid @RequestBody ParticipationCreateRequest request, | ||
| @Login LoginMember loginMember) { | ||
|
|
||
| ParticipationCreateResponse response = participationService.join(groupPurchaseId, loginMember.memberId(), request.quantity()); | ||
| return ResponseEntity.status(HttpStatus.CREATED).body(ApiResponse.success(response)); | ||
|
|
||
| } | ||
|
|
||
|
|
||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,19 @@ | ||
| package com.ttuk.participation; | ||
|
|
||
| import org.springframework.data.jpa.repository.JpaRepository; | ||
| import org.springframework.data.jpa.repository.Query; | ||
| import org.springframework.data.repository.query.Param; | ||
|
|
||
| public interface ParticipationRepository extends JpaRepository<Participation, Long> { | ||
|
|
||
| @Query(""" | ||
| select case when count(p) > 0 then true else false end | ||
| from Participation p | ||
| where p.groupPurchase.id = :groupPurchaseId | ||
| and p.member.id = :memberId | ||
| and p.status = com.ttuk.participation.ParticipationStatus.JOINED | ||
| """) | ||
| boolean existsJoined(@Param("groupPurchaseId") Long groupPurchaseId, | ||
| @Param("memberId") Long memberId); | ||
|
|
||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,72 @@ | ||
| package com.ttuk.participation; | ||
|
|
||
| import com.ttuk.global.error.BusinessException; | ||
| import com.ttuk.global.error.ErrorCode; | ||
| import com.ttuk.grouppurchase.GroupPurchaseRepository; | ||
| import com.ttuk.grouppurchase.redis.GroupPurchaseRedisRepository; | ||
| import com.ttuk.grouppurchase.redis.JoinResult; | ||
| import com.ttuk.member.MemberRepository; | ||
| import com.ttuk.participation.dto.ParticipationCreateResponse; | ||
| import lombok.RequiredArgsConstructor; | ||
| import lombok.extern.slf4j.Slf4j; | ||
| import org.springframework.dao.DataIntegrityViolationException; | ||
| import org.springframework.stereotype.Service; | ||
|
|
||
| import java.time.Clock; | ||
| import java.time.LocalDateTime; | ||
|
|
||
| @Slf4j | ||
| @Service | ||
| @RequiredArgsConstructor | ||
| public class ParticipationService { | ||
|
|
||
| private final GroupPurchaseRedisRepository groupPurchaseRedisRepository; | ||
| private final GroupPurchaseRepository groupPurchaseRepository; | ||
| private final MemberRepository memberRepository; | ||
| private final ParticipationRepository participationRepository; | ||
| private final Clock clock; | ||
|
|
||
| public ParticipationCreateResponse join(Long groupPurchaseId, Long memberId, int quantity) { | ||
| JoinResult result = groupPurchaseRedisRepository.join(groupPurchaseId, memberId); | ||
|
|
||
| return switch (result.outcome()) { | ||
| case JOINED -> saveParticipation(groupPurchaseId, memberId, quantity, result); | ||
| case NOT_OPEN -> throw new BusinessException(ErrorCode.GROUP_PURCHASE_NOT_OPEN); | ||
| case FULL -> throw new BusinessException(ErrorCode.GROUP_PURCHASE_FULL); | ||
| case INVALID_HEADCOUNT -> throw new IllegalStateException("Redis 참여 인원 값이 올바르지 않습니다. groupPurchaseId=" + groupPurchaseId); | ||
| case ALREADY_JOINED -> throw new BusinessException(ErrorCode.ALREADY_JOINED); | ||
| case NOT_INITIALIZED -> throw notInitialized(groupPurchaseId); | ||
| }; | ||
| } | ||
|
|
||
| // Redis Lua가 중복 참여를 먼저 막으므로, 여기서 같은 회원의 JOINED가 이미 있다는 건 | ||
| // Redis 참여자에 빠져 있던 기존 참여자가 Lua를 통과한 경우다. 이때 Redis에 들어간 참여는 | ||
| // 오히려 DB와 맞는 상태라 되돌리지 않고, 사용자에게는 이미 참여 중이라고 응답한다. | ||
| private ParticipationCreateResponse saveParticipation(Long groupPurchaseId, Long memberId, | ||
| int quantity, JoinResult result) { | ||
| try { | ||
| participationRepository.save(Participation.builder() | ||
| .groupPurchase(groupPurchaseRepository.getReferenceById(groupPurchaseId)) | ||
| .member(memberRepository.getReferenceById(memberId)) | ||
| .quantity(quantity) | ||
| .joinedAt(LocalDateTime.now(clock)) | ||
| .build()); | ||
| } catch (DataIntegrityViolationException e) { | ||
| if (participationRepository.existsJoined(groupPurchaseId, memberId)) { | ||
| log.warn("참여 저장: DB에 이미 JOINED 참여가 있음. Redis 참여자에 빠져 있던 회원으로 보고 Redis는 그대로 둠. " | ||
| + "groupPurchaseId={}, memberId={}", groupPurchaseId, memberId); | ||
| throw new BusinessException(ErrorCode.ALREADY_JOINED); | ||
| } | ||
| throw e; | ||
| } | ||
|
|
||
| return new ParticipationCreateResponse(result.headcount(), result.price()); | ||
| } | ||
|
|
||
| private RuntimeException notInitialized(Long groupPurchaseId) { | ||
| if (!groupPurchaseRepository.existsById(groupPurchaseId)) { | ||
| return new BusinessException(ErrorCode.GROUP_PURCHASE_NOT_FOUND); | ||
| } | ||
| return new IllegalStateException("Redis가 초기화되지 않은 공동구매입니다. id=" + groupPurchaseId); | ||
|
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. meta 키는 마감 하루 뒤에 만료돼요. 그래서 오래전에 마감된 공동구매에 참여를 요청하면 NOT_INITIALIZED 가 오고, 여기서 500 이 나요. 지금 원인이 Redis 초기화 실패인지 이미 마감된 것인지 구분하지 않아서 생기는 문제예요. DB 의 마감 시각과 상태를 보고, 마감됐으면 409 GROUP_PURCHASE_NOT_OPEN 을 돌려주면 좋겠어요
Collaborator
Author
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(#36 lazy init·보상)에서 반영했습니다. NOT_INITIALIZED가 오면 DB에서 공동구매를 조회해, 없으면 404, 상태가 OPEN이 아니거나 마감 시각이 지났으면 409 GROUP_PURCHASE_NOT_OPEN을 돌려주도록 했습니다. 그래서 meta가 만료된 오래전 마감 공동구매나 판매자가 취소한 공동구매는 409로 응답하고, 참여 가능한 상태인데 Redis 키만 없는 경우에는 키를 다시 만든 뒤 참여를 재시도합니다. |
||
| } | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,8 @@ | ||
| package com.ttuk.participation; | ||
|
|
||
| public enum ParticipationStatus { | ||
|
|
||
| JOINED, | ||
| CANCELED | ||
|
|
||
| } |
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,13 @@ | ||
| package com.ttuk.participation.dto; | ||
|
|
||
| import jakarta.validation.constraints.Max; | ||
| import jakarta.validation.constraints.Min; | ||
| import jakarta.validation.constraints.NotNull; | ||
|
|
||
| public record ParticipationCreateRequest( | ||
| @NotNull | ||
| @Min(1) | ||
| @Max(10) | ||
| Integer quantity | ||
|
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. 수량을 1~10개로 받는데, 할인 단계는 수량이 아니라 참여 인원으로만 계산돼요. 그래서 10개를 사는 사람도 인원 1명으로 세져요. 의도가 맞는지 확인해 주세요.
Collaborator
Author
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. 네, 의도한 동작입니다. 이 서비스는 사람이 많이 모일수록 가격이 내려가는 공동구매라서, 할인 단계와 정원은 모두 참여한 사람 수로 계산하도록 명세에서 정했습니다. 수량으로 세면 한 명이 여러 개를 사서 혼자 할인 단계를 올릴 수 있어, 사람을 모으는 공동구매의 의미가 사라진다고 판단했습니다. 수량은 할인 계산에는 쓰지 않고, 정산 때 수량 × 확정 단가로 결제 금액을 계산하는 데만 사용합니다. |
||
| ) { | ||
| } | ||
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,10 @@ | ||
| package com.ttuk.participation.dto; | ||
|
|
||
| public record ParticipationCreateResponse( | ||
|
|
||
| int currentHeadcount, | ||
| int currentPrice | ||
|
|
||
| ) { | ||
|
|
||
| } |
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.
중복 참여를 지금은 Redis 의 SISMEMBER 로만 막고 있어요. 다음 PR의 lazy init 이나 보상 처리로 Redis 값이 다시 만들어지면, 같은 회원의 참여 행이 DB 에 두 번 들어갈 수 있어요. (group_purchase_id, member_id) 유니크 제약을 마지막 방어선으로 두면 좋겠어요. 취소 후 재참여를 허용할 계획이라면, 그때 이 제약을 어떻게 할지도 함께 정해 주세요.
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.
말씀해 주신 대로 지금은 중복 참여를 Redis의 SISMEMBER로만 막고 있어서, Redis 키가 사라진 뒤 lazy init으로 참여자 Set이 비어 있는 채로 다시 만들어지면 같은 회원의 JOINED 행이 DB에 두 번 들어갈 수 있습니다. 그래서 DB에도 마지막 방어선이 필요하다고 생각합니다.
다만 취소는 행을 지우지 않고 CANCELED로 바꾸고 재참여는 새 행을 만드는 구조라, (group_purchase_id, member_id)에 단순 유니크 제약을 걸면 재참여가 막힙니다. 막아야 하는 건 같은 회원의 JOINED 행이 두 개가 되는 경우라서, status가 JOINED일 때만 member_id 값을 갖고 그 외에는 NULL인 생성 컬럼을 두고 (group_purchase_id, 이 컬럼)에 유니크 제약을 걸려고 합니다. MySQL 유니크 인덱스는 NULL끼리 중복으로 보지 않아 취소 기록은 여러 개 남길 수 있고, JOINED 행만 하나로 제한됩니다. 제약에 걸리면 지금은 500이 나가서, 제약 위반을 잡아 ALREADY_JOINED로 응답하도록 함께 처리하겠습니다.