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

Update/#62/update apis #68

Merged
merged 5 commits into from
Aug 1, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions src/main/java/com/habday/server/classes/Common.java
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,9 @@ public class Common {
@Autowired
public FundingMemberRepository fundingMemberRepository;

@Autowired
public MemberRepository memberRepository;

@Autowired
public PaymentRepository paymentRepository;

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ public enum ExceptionCode {
FUNDING_CONFIRM_NOT_NEEDED(INTERNAL_SERVER_ERROR, "펀딩 실패한 경우 인증이 필요하지 않습니다."),
FUNDING_CONFIRM_NOT_YET(INTERNAL_SERVER_ERROR, "완료되지 않은 펀딩은 인증을 진행할 수 없습니다."),
FUNDING_ALREADY_CONFIRMED(INTERNAL_SERVER_ERROR, "이미 인증된 펀딩입니다."),
NO_CONFIRMATION_EXIST(INTERNAL_SERVER_ERROR,"존재하지 않는 인증 번호 입니다."),
NO_CONFIRMATION_EXIST(INTERNAL_SERVER_ERROR,"펀딩 인증이 존재하지 않습니다."),
DELETE_FUNDING_UNAVAILABLE(INTERNAL_SERVER_ERROR, "마감한 펀딩에 대해서는 펀딩 삭제가 불가합니다."),
DELETE_PARTICIPATE_UNAVAILABLE(INTERNAL_SERVER_ERROR,"마감한 펀딩에 대해서는 참여 취소가 불가합니다."),
PAYMENT_VALIDATION_FAIL(INTERNAL_SERVER_ERROR, "결제 수단이 사용자 정보와 일치하지 않습니다."),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -67,11 +67,11 @@ public ResponseEntity<CommonResponse> confirm(@RequestHeader("") String accessTo
return CommonResponse.toResponse(FUNDING_CONFIRMATION_SUCCESS, null);
}

@GetMapping(value = {"/showConfirmation", "/showConfirmation/{confirmationId}"})
public ResponseEntity<CommonResponse> showConfirmation(@PathVariable Optional<Long> confirmationId){
@GetMapping(value = {"/showConfirmation", "/showConfirmation/{fundingItemId}"})
public ResponseEntity<CommonResponse> showConfirmation(@PathVariable Optional<Long> fundingItemId){

ShowConfirmationResponseDto response = fundingService.showConfirmation(confirmationId.orElseThrow(() ->
new CustomException(NO_CONFIRMATION_EXIST)));
ShowConfirmationResponseDto response = fundingService.showConfirmation(fundingItemId.orElseThrow(() ->
new CustomException(NO_FUNDING_ITEM_ID)));
return CommonResponse.toResponse(SHOW_FUNDING_CONFIRM_SUCCESS, response);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -86,8 +86,14 @@ public FundingItem updatePricePercentage(BigDecimal totalPrice, int percentage){
this.percentage = percentage;
return this;
}
public FundingItem updateFundingState(FundingState status){
this.status = status;

public FundingItem updateFundingSuccess(){
this.status = FundingState.SUCCESS;
return this;
}

public FundingItem updateFundingFail(){
this.status = FundingState.FAIL;
return this;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -104,22 +104,22 @@ public static FundingMember of(ParticipateFundingRequest fundingRequestDto, Sche
.build();
}

public FundingMember updateCancel(BigDecimal cancelAmount, String reason, ScheduledPayState payment_status, LocalDate cancelDate){
public FundingMember updateCancel(BigDecimal cancelAmount, String reason, LocalDate cancelDate){
this.cancelAmount = cancelAmount;
this.reason = reason;
this.payment_status = payment_status;
this.payment_status = ScheduledPayState.cancel;
this.cancelDate = cancelDate;
return this;
}

public FundingMember updateWebhookFail(ScheduledPayState payment_status, String fail_reason){
this.payment_status = payment_status;
public FundingMember updateWebhookFail(String fail_reason){
this.payment_status = ScheduledPayState.fail;
this.fail_reason = fail_reason;
return this;
}

public FundingMember updateWebhookSuccess(ScheduledPayState payment_status){
this.payment_status = payment_status;
public FundingMember updateWebhookSuccess(){
this.payment_status = ScheduledPayState.paid;
return this;
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import lombok.Getter;
import lombok.NoArgsConstructor;

import java.math.BigDecimal;
import java.time.LocalDateTime;

@Getter
Expand All @@ -12,10 +13,12 @@ public class ShowConfirmationResponseDto {
private String confirmationImg;
private String message;
private LocalDateTime createdDate;
public ShowConfirmationResponseDto(Confirmation confirmation){
BigDecimal totalPrice;
public ShowConfirmationResponseDto(Confirmation confirmation, BigDecimal totalPrice){
this.title = confirmation.getTitle();
this.confirmationImg = confirmation.getConfirmationImg();
this.message = confirmation.getMessage();
this.createdDate = confirmation.getCreatedDate();
this.totalPrice = totalPrice;
}
}
41 changes: 30 additions & 11 deletions src/main/java/com/habday/server/service/FundingCloseService.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
import com.google.gson.Gson;
import com.habday.server.classes.Common;
import com.habday.server.config.email.EmailFormats;
import com.habday.server.constants.CustomException;
import com.habday.server.constants.code.ExceptionCode;
import com.habday.server.constants.state.FundingState;
import com.habday.server.domain.fundingItem.FundingItem;
import com.habday.server.domain.fundingMember.FundingMember;
Expand All @@ -19,6 +21,8 @@
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;

import static com.habday.server.constants.state.ScheduledPayState.fail;
import static com.habday.server.constants.state.ScheduledPayState.paid;

Expand All @@ -41,25 +45,39 @@ public class FundingCloseService extends Common {
* - 펀딩 성공 메일 보내기
* */
@Transactional
public void checkFundingSuccess(FundingItem fundingItem) {
public void checkFundingSuccess(FundingItem fundingItem) {//성공한 아이템이 들어오게
BigDecimal goalPercent = fundingItem.getGoalPrice().divide(fundingItem.getItemPrice(), BigDecimal.ROUND_DOWN); //최소목표퍼센트
BigDecimal realPercent = fundingItem.getTotalPrice().divide(fundingItem.getItemPrice(), BigDecimal.ROUND_DOWN); // 실제달성퍼센트

log.info("itemId: " + fundingItem.getId() + " goalPercent^^ " + goalPercent + " realPercent^^ " + realPercent);
log.info("itemId: " +fundingItem.getId() + " realPercent.compareTo(goalPercent)^^ : " + realPercent.compareTo(goalPercent));

if (realPercent.compareTo(goalPercent) == 0 || realPercent.compareTo(goalPercent) == 1) { // 펀딩 최소 목표 퍼센트에 달성함
fundingItem.updateFundingState(FundingState.SUCCESS);
fundingItem.updateFundingSuccess();
log.info("최소 목표퍼센트 이상 달성함");
emailFormats.sendFundingSuccessEmail(fundingItem);
} else { // 펀딩 최소 목표 퍼센트에 달성 못함
log.info("최소 목표퍼센트 이상 달성 실패");
fundingItem.updateFundingState(FundingState.FAIL);
fundingItem.updateFundingFail();
payService.unscheduleAll(fundingItem);
emailFormats.sendFundingFailEmail(fundingItem);//throw new CustomException(FAIL_FINISH_FUNDING);
}
}

@Transactional
public void fundingSuccess(FundingItem fundingItem){
log.info("최소 목표퍼센트 이상 달성함");
emailFormats.sendFundingSuccessEmail(fundingItem);
}

@Transactional
public void fundingFail(FundingItem fundingItem){
log.info("최소 목표퍼센트 이상 달성 실패");
fundingItem.updateFundingFail();
payService.unscheduleAll(fundingItem);
emailFormats.sendFundingFailEmail(fundingItem);//throw new CustomException(FAIL_FINISH_FUNDING);
}


/*
<웹훅>
Expand All @@ -75,34 +93,35 @@ public void callbackSchedule(CallbackScheduleRequestDto callbackRequestDto, Http
String[] ips = {"52.78.100.19", "52.78.48.223", "52.78.5.241"};
List<String> ipLists = new ArrayList<>(Arrays.asList(ips));

FundingMember fundingMember = fundingMemberRepository.findByMerchantId(callbackRequestDto.getMerchant_uid());
FundingItem fundingItem = fundingMember.getFundingItem();
BigDecimal amount = fundingMember.getAmount();
Optional<FundingMember> fundingMember = Optional.ofNullable(fundingMemberRepository.findByMerchantId(callbackRequestDto.getMerchant_uid()));
FundingItem fundingItem = fundingMember.orElseThrow(()->
new CustomException(ExceptionCode.NO_FUNDING_MEMBER_ID)).getFundingItem();
BigDecimal amount = fundingMember.get().getAmount();

IamportResponse<Payment> response = iamportService.paymentByImpUid(callbackRequestDto.getImp_uid());
log.info("response: " + new Gson().toJson(response));

if (!ipLists.contains(clientIp)){
fundingMember.updateWebhookFail(fail, "ip주소가 맞지 않음");
fundingMember.get().updateWebhookFail("ip주소가 맞지 않음");
log.info("callbackSchedule() ip 주소 안맞음");
return;//throw new CustomException(UNAUTHORIZED_IP);
//exception 날리면 트랜잭션이 롤백되어버려 영속성컨텍스트 flush 안됨
}

if(amount.compareTo(response.getResponse().getAmount()) !=0){
fundingMember.updateWebhookFail(fail, "결제 금액이 맞지 않음");
fundingMember.get().updateWebhookFail("결제 금액이 맞지 않음");
log.info("callbackSchedule(): member-amount : " + amount);
log.info("callbackSchedule() 결제 금액 안맞음 " + response.getResponse().getMerchantUid());
return;//throw new CustomException(NO_CORRESPONDING_AMOUNT);
}
String[] receiver = {fundingMember.getMember().getEmail()};
String[] receiver = {fundingMember.get().getMember().getEmail()};

if(callbackRequestDto.getStatus().equals(paid.getMsg())){
fundingMember.updateWebhookSuccess(paid);
fundingMember.get().updateWebhookSuccess();
log.info("callbackSchedule() paid로 update" + response.getResponse().getMerchantUid());
emailFormats.sendPaymentSuccessEmail(fundingItem, receiver, amount);
}else{
fundingMember.updateWebhookFail(fail, response.getResponse().getFailReason());
fundingMember.get().updateWebhookFail(response.getResponse().getFailReason());
log.info("callbackSchedule() fail로 update" + response.getResponse().getMerchantUid());
emailFormats.sendPaymentFailEmail(fundingItem, receiver);
}
Expand Down
21 changes: 9 additions & 12 deletions src/main/java/com/habday/server/service/FundingService.java
Original file line number Diff line number Diff line change
Expand Up @@ -57,8 +57,6 @@ public class FundingService extends Common {
private final S3Uploader s3Uploader;
private final EmailFormats emailFormats;
private final PayService payService;
private final MemberRepository memberRepository;
private final FundingItemRepository fundingItemRepository;


@Transactional//예외 발생 시 롤백해줌
Expand Down Expand Up @@ -99,21 +97,19 @@ public ParticipateFundingResponseDto participateFunding(ParticipateFundingReques
fundingItem.updatePricePercentage(totalPrice, percentage);

// 펀딩 금액 달성시, SUCCESS로 상태 변경
if(fundingItem.getTotalPrice() == fundingItem.getGoalPrice()) {
fundingItem.updateFundingState(FundingState.SUCCESS);
if(fundingItem.getTotalPrice().compareTo(fundingItem.getGoalPrice()) >=0) {
fundingItem.updateFundingSuccess();
}
return ParticipateFundingResponseDto.of(scheduleResult.getCode(), scheduleResult.getMessage());
}

public ShowFundingContentResponseDto showFundingContent(Long fundingItemId) {
FundingItem fundingItem = fundingItemRepository.findById(fundingItemId)
.orElseThrow(() -> new CustomException(NO_FUNDING_ITEM_ID));
Member member = fundingItem.getMember();
if (member == null)
throw new CustomException(NO_MEMBER_ID_SAVED);
Confirmation confirmation = confirmationRepository.findByFundingItem(fundingItem);
Member member = Optional.ofNullable(fundingItem.getMember()).orElseThrow(()-> new CustomException(NO_MEMBER_ID_SAVED));
Optional<Confirmation> confirmation = Optional.ofNullable(confirmationRepository.findByFundingItem(fundingItem));
return ShowFundingContentResponseDto.of(fundingItem, member, getParticipantList(fundingItem),
confirmation == null ? null : confirmation.getId());
confirmation.orElseGet(null).getId());
}

public List<FundingParticipantList> getParticipantList(FundingItem fundingItem) {
Expand Down Expand Up @@ -214,9 +210,10 @@ public void confirm(MultipartFile img, ConfirmationRequest request, Long funding
fundingItem.updateIsConfirmTrue();
}

public ShowConfirmationResponseDto showConfirmation(Long confirmationId){
Confirmation confirmation = confirmationRepository.findById(confirmationId).orElseThrow(() -> new CustomException(NO_CONFIRMATION_EXIST));
return new ShowConfirmationResponseDto(confirmation);
public ShowConfirmationResponseDto showConfirmation(Long fundingItemId){
FundingItem fundingItem = fundingItemRepository.findById(fundingItemId).orElseThrow(() -> new CustomException(NO_FUNDING_ITEM_ID));
Confirmation confirmation = Optional.ofNullable(confirmationRepository.findByFundingItem(fundingItem)).orElseThrow(() -> new CustomException(NO_CONFIRMATION_EXIST));
return new ShowConfirmationResponseDto(confirmation, fundingItem.getTotalPrice());
}

@Transactional
Expand Down
1 change: 0 additions & 1 deletion src/main/java/com/habday/server/service/MemberService.java
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
@Service
@RequiredArgsConstructor
public class MemberService extends Common {
private final MemberRepository memberRepository;
@Transactional
public void updateMemberProfile(Long memberId, MemberProfileRequestDto requestDto) {
Member member = memberRepository.findById(memberId)
Expand Down
6 changes: 2 additions & 4 deletions src/main/java/com/habday/server/service/PayService.java
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,6 @@
public class PayService extends Common {
private final IamportService iamportService;
private final UIDCreation uidCreation;
private final MemberRepository memberRepository;
private final FundingItemRepository fundingItemRepository;

@Transactional
public GetBillingKeyResponseDto getBillingKey(NoneAuthPayBillingKeyRequestDto billingKeyRequest, Long memberId){
Expand Down Expand Up @@ -132,7 +130,7 @@ public UnscheduleResponseDto noneAuthPayUnschedule(NoneAuthPayUnscheduleRequestD
throw new CustomExceptionWithMessage(PAY_SCHEDULING_INTERNAL_ERROR, iamportResponse.getMessage());
}
LocalDate cancelDate = LocalDate.now();
fundingMember.updateCancel(fundingMember.getAmount(), unscheduleRequestDto.getReason(), cancel, cancelDate);
fundingMember.updateCancel(fundingMember.getAmount(), unscheduleRequestDto.getReason(), cancelDate);

return UnscheduleResponseDto.builder()
.merchant_uid(fundingMember.getMerchantId())
Expand All @@ -149,7 +147,7 @@ public void unscheduleAll(FundingItem fundingItem){
NoneAuthPayUnscheduleRequestDto request = new NoneAuthPayUnscheduleRequestDto(id, "목표 달성 실패로 인한 결제 취소");
try {
UnscheduleResponseDto respone = noneAuthPayUnschedule(request);
log.info("unschedulePayment response: " + new Gson().toJson(respone));
//log.info("unschedulePayment response: " + new Gson().toJson(respone));
} catch(RuntimeException e){
log.info("unschedule Payment 서비스 내 오류: " + e);
}
Expand Down
24 changes: 12 additions & 12 deletions src/main/java/com/habday/server/service/ScheduleService.java
Original file line number Diff line number Diff line change
Expand Up @@ -29,18 +29,23 @@
@RequiredArgsConstructor
@Service
public class ScheduleService extends Common {
private final MemberRepository memberRepository;
private final Calculation calculation;
private final FundingCloseService closeService;

@Transactional
@Scheduled(cron = scheduleCron) // "0 5 0 * * *" 매일 밤 0시 5분에 실행
public void checkFundingState() {
log.info("schedule 시작");
List<FundingItem> overdatedFundings = fundingItemRepository.findByStatusAndFinishDate(FundingState.PROGRESS, LocalDate.now());
overdatedFundings.forEach(fundingItem -> {
log.info("오늘 마감 fundingItem: " + fundingItem.getId());
closeService.checkFundingSuccess(fundingItem);
List<FundingItem> successFunding = fundingItemRepository.findByStatusAndFinishDate(FundingState.SUCCESS, LocalDate.now());
List<FundingItem> failFunding = fundingItemRepository.findByStatusAndFinishDate(FundingState.PROGRESS, LocalDate.now());

successFunding.forEach(fundingItem -> {
log.info("오늘 마감 성공 fundingItem: " + fundingItem.getId());
closeService.fundingSuccess(fundingItem);
});

failFunding.forEach(fundingItem -> {
log.info("오늘 마감 실패 fundingItem: " + fundingItem.getId());
closeService.fundingFail(fundingItem);
});
log.info("schedule 끝");
}
Expand All @@ -52,6 +57,7 @@ public void checkFundingState() {
@Transactional
@Scheduled(cron = memberStateCron)//매일 밤 12시
public void checkMemberState(){
log.info("member cron 돌아감");
List<FundingItem> fundingItems = //now > finishDate + 14 == now - 14 > finishDate
fundingItemRepository.findByIsConfirmAndStatusAndFinishDateLessThan(FundingConfirmState.FALSE,
FundingState.SUCCESS, LocalDate.now().minusDays(CmnConst.confirmLimitDate));//데이터 많아지면 검색 범위를 지정해도 되지 않을까 너무 옛날꺼는 검색하지 않는다던지
Expand All @@ -62,12 +68,6 @@ public void checkMemberState(){
if(member != null && member.getStatus().equals(MemberState.AVAILABLE))
member.updateStatusSuspended();
item.updateIsConfirmDone();//false로 있으면 조건문에 걸릴 수 있으니
// if (calculation.isAfterTwoWeek(item)){//afterTwoWeek >= LocalDate.now()이면 pass
// Member member = item.getMember();
// member.updateStatusSuspended();
// log.info("checkMemberState(): memberId: " + member.getId() + " itemId: " + item.getId() + " 기간 만료");
// item.updateIsConfirmDone();
// }
}));
}
}