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

[#326] 후원 및 환불 api 리팩토링 및 구현 #327

Merged
merged 16 commits into from
Sep 7, 2021
Merged
Show file tree
Hide file tree
Changes from 12 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -71,18 +71,15 @@ public void sendAccountReject(String mailAddress, String rejectReason) {
sendMail("정산 계좌 승인 반려", message, mailAddress);
}

public void sendDonationComplete(Payment payment, Member member) {
public void sendChargeComplete(Payment payment) {
Context context = new Context();
context.setVariable("page_url", CREATOR_PREFIX_DOMAIN + payment.getItemName());
Copy link
Collaborator

Choose a reason for hiding this comment

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

이제 쓰이지 않는 CREATOR_PREFIX_DOMAIN 상수는 제거하자

context.setVariable("item_name", payment.getItemName());
context.setVariable("merchant_id", payment.getMerchantUid());
context.setVariable("creator_name", member.getNickname());
context.setVariable("donation_amount", payment.getAmount());
context.setVariable("charge_amount", payment.getAmount());
context.setVariable("date", payment.getCreatedAt().now().
format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss")));



String message = templateEngine.process("mail-donation-complete.html", context);
String message = templateEngine.process("mail-charge-complete.html", context);
sendMail("후원 성공", message, payment.getEmail());

}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@

import com.example.tyfserver.auth.dto.LoginMember;
import com.example.tyfserver.donation.dto.DonationMessageRequest;
import com.example.tyfserver.donation.dto.DonationRequest;
import com.example.tyfserver.donation.dto.DonationResponse;
import com.example.tyfserver.donation.exception.DonationMessageRequestException;
import com.example.tyfserver.donation.exception.DonationRequestException;
import com.example.tyfserver.donation.service.DonationService;
import com.example.tyfserver.payment.dto.PaymentCompleteRequest;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
Expand All @@ -24,14 +24,15 @@ public class DonationController {

private final DonationService donationService;

//todo: 이 부분 완전 바뀌어야함
// @PostMapping
// public ResponseEntity<DonationResponse> createDonation(@Valid @RequestBody PaymentCompleteRequest paymentCompleteRequest, BindingResult result) {
// if (result.hasErrors()) {
// throw new DonationRequestException();
// }
// return ResponseEntity.status(HttpStatus.CREATED).body(donationService.createDonation(paymentCompleteRequest));
// }
@PostMapping
public ResponseEntity<DonationResponse> createDonation(@Valid @RequestBody DonationRequest donationRequest,
BindingResult result, LoginMember loginMember) {
if (result.hasErrors()) {
throw new DonationRequestException();
}
return ResponseEntity.status(HttpStatus.CREATED)
.body(donationService.createDonation(donationRequest, loginMember.getId()));
}

@PostMapping("/{donationId}/messages")
public ResponseEntity<Void> addDonationMessage(@PathVariable Long donationId,
Expand Down
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
package com.example.tyfserver.donation.domain;

import com.example.tyfserver.common.domain.BaseTimeEntity;
import com.example.tyfserver.donation.exception.DonationAlreadyCancelledException;
import com.example.tyfserver.member.domain.Member;
import lombok.AccessLevel;
import lombok.Getter;
Expand Down Expand Up @@ -29,27 +28,16 @@ public class Donation extends BaseTimeEntity {
@JoinColumn(name = "member_id")
private Member member;

@Enumerated(value = EnumType.STRING)
private DonationStatus status = DonationStatus.REFUNDABLE;
public Donation(Message message, long point) {
this(null, message, point);
}

public Donation(Long id, Message message, long point) {
this.id = id;
this.message = message;
this.point = point;
}

public Donation(long point) {
this(null, Message.defaultMessage(), point);
}

public Donation(Message message) {
this(null, message, 0L);
}

public Donation(Message message, long point) {
this(null, message, point);
}

public void to(final Member member) {
this.member = member;
}
Expand All @@ -69,26 +57,4 @@ public String getMessage() {
public boolean isSecret() {
return message.isSecret();
}

public void toCancelled() {
status = DonationStatus.CANCELLED;
}

public void toExchanged() {
status = DonationStatus.EXCHANGED;
}

public void toExchangeable() {
status = DonationStatus.EXCHANGEABLE;
}

public void validateIsNotCancelled() {
if (status == DonationStatus.CANCELLED) {
throw new DonationAlreadyCancelledException();
}
}

public boolean isNotRefundable() {
return status != DonationStatus.REFUNDABLE;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
package com.example.tyfserver.donation.domain;

public enum DonationType {
Copy link
Collaborator

Choose a reason for hiding this comment

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

Donation이 창작자, 후원자로 바뀌게 한다면 얘는 필요 없어지겠다

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

응 맞어! 그리고 지금 코드도 이 enum을 사용하고 있지는 않아 미리 만들어뒀어! 그리고 Donation 엔티티 필드에 DonationStatus 가 아직 있는데 이것도 삭제해야하는데 아직 삭제안했업

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

말 나온김에 DonationStatus Donation 필드에서 빼놔야겠다

DONATED, DONATING;
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,6 @@
@NoArgsConstructor(access = AccessLevel.PROTECTED)
public class Message {

public static final String DEFAULT_NAME = "익명인";
public static final String DEFAULT_MESSAGE = "당신을 응원합니다.";
public static final String SECRET_NAME = "익명인";
public static final String SECRET_MESSAGE = "비공개 메세지입니다.";
Expand All @@ -22,13 +21,13 @@ public class Message {

private boolean secret;

public Message(String name) {
this(name, DEFAULT_MESSAGE, false);
}

public Message(String name, String message, boolean secret) {
this.name = name;
this.message = message;
this.secret = secret;
}

public static Message defaultMessage() {
return new Message(Message.DEFAULT_NAME, Message.DEFAULT_MESSAGE, false);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,10 @@ public class DonationRequest {
@NotBlank
private String pageName;
@Positive
private Long donationAmount;
private Long point;

public DonationRequest(String pageName, Long donationAmount) {
public DonationRequest(String pageName, Long point) {
this.pageName = pageName;
this.donationAmount = donationAmount;
this.point = point;
}
}
Original file line number Diff line number Diff line change
@@ -1,18 +1,16 @@
package com.example.tyfserver.donation.service;

import com.example.tyfserver.common.util.SmtpMailConnector;
import com.example.tyfserver.donation.domain.Donation;
import com.example.tyfserver.donation.domain.DonationStatus;
import com.example.tyfserver.donation.domain.Message;
import com.example.tyfserver.donation.dto.DonationMessageRequest;
import com.example.tyfserver.donation.dto.DonationRequest;
import com.example.tyfserver.donation.dto.DonationResponse;
import com.example.tyfserver.donation.exception.DonationNotFoundException;
import com.example.tyfserver.donation.repository.DonationRepository;
import com.example.tyfserver.member.domain.Member;
import com.example.tyfserver.member.exception.MemberNotFoundException;
import com.example.tyfserver.member.repository.MemberRepository;
import com.example.tyfserver.payment.domain.Payment;
import com.example.tyfserver.payment.dto.PaymentCompleteRequest;
import com.example.tyfserver.payment.service.PaymentService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
Expand All @@ -28,22 +26,21 @@ public class DonationService {

private final DonationRepository donationRepository;
private final MemberRepository memberRepository;
private final PaymentService paymentService;
private final SmtpMailConnector mailConnector;

//todo: 완전 바뀌어야할 로직
// public DonationResponse createDonation(PaymentCompleteRequest paymentCompleteRequest) {
// Payment payment = paymentService.completePayment(paymentCompleteRequest);
// Donation donation = new Donation(payment);
// Member member = memberRepository.findByPageName(payment.getItemName())
// .orElseThrow(MemberNotFoundException::new);
//
// Donation savedDonation = donationRepository.save(donation);
// member.addDonation(savedDonation);
//
// mailConnector.sendDonationComplete(payment, member);
// return new DonationResponse(savedDonation);
// }

public DonationResponse createDonation(DonationRequest donationRequest, long id) {
Member donator = findMember(id);
Member creator = memberRepository.findByPageName(donationRequest.getPageName())
.orElseThrow(MemberNotFoundException::new);

donator.validateEnoughPoint(donationRequest.getPoint());

Message message = new Message(donator.getNickname());
Donation creatorDonation = new Donation(message, donationRequest.getPoint());
Donation savedDonation = donationRepository.save(creatorDonation);
creator.addDonation(savedDonation);

return new DonationResponse(savedDonation);
}

public void addMessageToDonation(final Long donationId, final DonationMessageRequest donationMessageRequest) {
Donation donation = donationRepository.findById(donationId)
Expand All @@ -53,14 +50,18 @@ public void addMessageToDonation(final Long donationId, final DonationMessageReq
}

public List<DonationResponse> findMyDonations(Long memberId, Pageable pageable) {
Member findMember = memberRepository.findById(memberId)
.orElseThrow(MemberNotFoundException::new);
Member findMember = findMember(memberId);

List<Donation> donations = donationRepository.findDonationByMemberAndStatusNotOrderByCreatedAtDesc(findMember, DonationStatus.CANCELLED, pageable);

return privateDonationResponses(donations);
}

private Member findMember(Long memberId) {
return memberRepository.findById(memberId)
.orElseThrow(MemberNotFoundException::new);
}

public List<DonationResponse> findPublicDonations(String pageName) {
Member findMember = memberRepository.findByPageName(pageName)
.orElseThrow(MemberNotFoundException::new);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import com.example.tyfserver.auth.domain.Oauth2Type;
import com.example.tyfserver.common.domain.BaseTimeEntity;
import com.example.tyfserver.donation.domain.Donation;
import com.example.tyfserver.member.exception.NotEnoughPointException;
import com.example.tyfserver.payment.domain.Payment;
import lombok.AccessLevel;
import lombok.Getter;
Expand Down Expand Up @@ -92,6 +93,10 @@ public void updateNickname(String nickname) {
this.nickname = nickname;
}

public long getAvailablePoint() {
return this.availablePoint.getPoint();
}

public long getDonatedPoint() {
return this.donatedPoint.getPoint();
}
Expand Down Expand Up @@ -120,6 +125,12 @@ public void registerAccount(String accountHolder, String accountNumber, String b
this.account.register(accountHolder, accountNumber, bank, bankBookUrl);
}

public void validateEnoughPoint(Long point) {
if (availablePoint.lessThan(point)) {
throw new NotEnoughPointException();
}
}

public AccountStatus getAccountStatus() {
return this.account.getStatus();
}
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
package com.example.tyfserver.member.domain;

import com.example.tyfserver.member.exception.NotEnoughPointException;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.NoArgsConstructor;
Expand All @@ -24,8 +25,12 @@ public void add(final long donationAmount) {

public void reduce(final long amount) {
if (amount > point) {
throw new RuntimeException("포인트가 총액보다 적게 있습니다.");
throw new NotEnoughPointException();
}
this.point -= amount;
}

public boolean lessThan(Long point) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

오 메소드 명 좋다.

Copy link
Collaborator

Choose a reason for hiding this comment

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

근데 payment도메인의 reduce 함수에서 "포인트가 총액보다 적게 있습니다" 예외가 RuntimeException으로 되어있당

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

오 땡큐 이거 예외 만들어놓앗는데 여기다가 적용안했네 굿

return this.point < point;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,23 +15,26 @@ public class MemberResponse {
private String pageName;
private String bio;
private String profileImage;
private long point;
private boolean bankRegistered;

public MemberResponse(Member member) {
this(member.getEmail(), member.getNickname(), member.getPageName(),
member.getBio(), member.getProfileImage(), isBankRegistered(member));
member.getBio(), member.getProfileImage(), member.getAvailablePoint(), isBankRegistered(member));
Copy link
Collaborator

Choose a reason for hiding this comment

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

MemberResponse에 AvailablePoint만 주는 이유는

members/me/point API가 있어서 겠쥬?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

이 API는 현재 보유 포인트 달라고 했어서 이거 준거야!
그때 얘기하기로 도네받은 포인트는 그 정산탭 가면 보이니깐 어쩌고 저쩌고 했던걸로 알아서!

}

private static boolean isBankRegistered(Member member) {
return member.getAccountStatus() == AccountStatus.REGISTERED;
}

public MemberResponse(String email, String nickname, String pageName, String bio, String profileImage, boolean bankRegistered) {
public MemberResponse(String email, String nickname, String pageName, String bio,
String profileImage, long point, boolean bankRegistered) {
this.email = email;
this.nickname = nickname;
this.pageName = pageName;
this.bio = bio;
this.profileImage = profileImage;
this.point = point;
this.bankRegistered = bankRegistered;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
package com.example.tyfserver.member.exception;

import com.example.tyfserver.common.exception.BaseException;

public class NotEnoughPointException extends BaseException {

public static final String ERROR_CODE = "donation-010";
private static final String MESSAGE = "보유 포인트가 충분하지 않습니다.";

public NotEnoughPointException() {
super(ERROR_CODE, MESSAGE);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@
import com.example.tyfserver.auth.dto.LoginMember;
import com.example.tyfserver.auth.dto.VerifiedRefunder;
import com.example.tyfserver.payment.dto.*;
import com.example.tyfserver.payment.exception.PaymentCompleteRequestException;
import com.example.tyfserver.payment.exception.PaymentPendingRequestException;
import com.example.tyfserver.payment.exception.RefundVerificationException;
import com.example.tyfserver.payment.exception.RefundVerificationReadyException;
import com.example.tyfserver.payment.service.PaymentService;
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;
Expand All @@ -21,8 +23,7 @@ public class PaymentController {

private final PaymentService paymentService;

//todo: /payments 에서 /charge/ready 쪽으로 옮겨가야됨. PaymentController 네이밍이 ChargeController로 바뀔지도?
@PostMapping
@PostMapping("/charge/ready")
public ResponseEntity<PaymentPendingResponse> payment(@Valid @RequestBody PaymentPendingRequest paymentPendingRequest, BindingResult result,
LoginMember loginMember) {
if (result.hasErrors()) {
Expand All @@ -33,6 +34,16 @@ public ResponseEntity<PaymentPendingResponse> payment(@Valid @RequestBody Paymen
return ResponseEntity.ok(response);
}

@PostMapping("/charge")
public ResponseEntity<PaymentCompleteResponse> completePayment(@Valid @RequestBody PaymentCompleteRequest paymentCompleteRequest, BindingResult result) {
if (result.hasErrors()) {
throw new PaymentCompleteRequestException();
}

return ResponseEntity.status(HttpStatus.CREATED)
.body(paymentService.completePayment(paymentCompleteRequest));
}

@PostMapping("/refund/verification/ready")
public ResponseEntity<RefundVerificationReadyResponse> refundVerificationReady(@Valid @RequestBody RefundVerificationReadyRequest verificationReadyRequest, BindingResult result,
LoginMember loginMember) {
Copy link
Collaborator

Choose a reason for hiding this comment

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

여기서 LoginMember를 사용하지 않는데,
인터셉터에 걸리게만 해놓는건 어때?

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

이게... 처음에 토큰 필요한 애들이니깐 미리 LoginMember 써놔야지~! 했다가 안쓰는 애들이 많겠구나 싶어서 놔둔거였어 !! 테스트코드하면서 필요하면 추가하고 안쓰면 빼고 해주면 좋을 것 같어!

Copy link
Collaborator

@Rok93 Rok93 Sep 6, 2021

Choose a reason for hiding this comment

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

지금은 안쓰지만, 앞으로 변경 될 후원로직을 생각하면 LoginMember가 필요할거 같아서 굳이 안지워도 될 것 같어!
혹시라도 안쓴다면 나중에 제거해도 될 부분인거 같어 🤔

Copy link
Collaborator Author

Choose a reason for hiding this comment

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

테스트 짜면서 알아서들 지워주세요 허헣

Expand Down