Skip to content

Commit

Permalink
feat: 팀 생성 기능 구현 (#24)
Browse files Browse the repository at this point in the history
* feat: 결제 기능 요구사항 반영

* feat: Team 도메인 수정 및 일급 컬렉션화 (#3)

* feat: 팀 생성 기능 구현 (#4)

* feat: Team 도메인 수정 및 일급 컬렉션화

* feat: 팀 생성 기능 구현
  • Loading branch information
LEEJaeHyeok97 authored Nov 18, 2024
1 parent 2c51360 commit a63a709
Show file tree
Hide file tree
Showing 12 changed files with 219 additions and 127 deletions.
Original file line number Diff line number Diff line change
@@ -1,16 +1,5 @@
package com.jangburich.domain.payment.application;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

import com.jangburich.domain.payment.domain.PaymentChargeStatus;
import com.jangburich.domain.payment.domain.TeamChargeHistory;
import com.jangburich.domain.payment.domain.repository.TeamChargeHistoryRepository;
Expand All @@ -20,114 +9,116 @@
import com.jangburich.domain.payment.exception.TeamNotFoundException;
import com.jangburich.domain.team.domain.Team;
import com.jangburich.domain.team.domain.repository.TeamRepository;

import java.util.HashMap;
import java.util.Map;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.client.RestTemplate;

@Service
@RequiredArgsConstructor
public class KakaopayService implements PaymentService {

private final TeamChargeHistoryRepository teamChargeHistoryRepository;
@Value("${kakaopay.secretKey}")
private String secretKey;

@Value("${kakaopay.approve-url}")
private String approvalUrl;

@Value("${kakaopay.cancel-url}")
private String cancelUrl;
private final TeamChargeHistoryRepository teamChargeHistoryRepository;
@Value("${kakaopay.secretKey}")
private String secretKey;

@Value("${kakaopay.fail-url}")
private String failUrl;
@Value("${kakaopay.approve-url}")
private String approvalUrl;

private final TeamRepository teamRepository;
@Value("${kakaopay.cancel-url}")
private String cancelUrl;

private ResponseEntity<ReadyResponse> readyResponseResponseEntity;
private String userId;
@Value("${kakaopay.fail-url}")
private String failUrl;

@Override
public String getType() {
return "kakao";
}
private final TeamRepository teamRepository;

@Transactional
@Override
public ReadyResponse payReady(Long userId, PayRequest payRequest) {
this.userId = String.valueOf(userId);
@Override
public String getType() {
return "kakao";
}

Map<String, String> parameters = new HashMap<>();
@Transactional
@Override
public ReadyResponse payReady(String userId, PayRequest payRequest) {
Map<String, String> parameters = new HashMap<>();

parameters.put("cid", "TC0ONETIME"); // 가맹점 코드(테스트용)
parameters.put("partner_order_id", "1234567890"); // 주문번호
parameters.put("partner_user_id", String.valueOf(userId)); // 회원 아이디
parameters.put("item_name", "ITEM_NAME"); // 상품명
parameters.put("quantity", "1"); // 상품 수량
parameters.put("total_amount", payRequest.totalAmount()); // 상품 총액
parameters.put("tax_free_amount", "0"); // 상품 비과세 금액
parameters.put("approval_url", approvalUrl); // 결제 성공 시 URL
parameters.put("cancel_url", cancelUrl); // 결제 취소 시 URL
parameters.put("fail_url", failUrl); // 결제 실패 시 URL
parameters.put("cid", "TC0ONETIME"); // 가맹점 코드(테스트용)
parameters.put("partner_order_id", "1234567890"); // 주문번호
parameters.put("partner_user_id", String.valueOf(userId)); // 회원 아이디
parameters.put("item_name", "ITEM_NAME"); // 상품명
parameters.put("quantity", "1"); // 상품 수량
parameters.put("total_amount", payRequest.totalAmount()); // 상품 총액
parameters.put("tax_free_amount", "0"); // 상품 비과세 금액
parameters.put("approval_url", approvalUrl); // 결제 성공 시 URL
parameters.put("cancel_url", cancelUrl); // 결제 취소 시 URL
parameters.put("fail_url", failUrl); // 결제 실패 시 URL

HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(parameters, this.getHeaders());
HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(parameters, this.getHeaders());

RestTemplate template = new RestTemplate();
String url = "https://open-api.kakaopay.com/online/v1/payment/ready";
RestTemplate template = new RestTemplate();
String url = "https://open-api.kakaopay.com/online/v1/payment/ready";

readyResponseResponseEntity = template.postForEntity(url, requestEntity,
ReadyResponse.class);
ResponseEntity<ReadyResponse> readyResponseResponseEntity = template.postForEntity(url, requestEntity,
ReadyResponse.class);

Team team = teamRepository.findById(payRequest.teamId())
.orElseThrow(() -> new TeamNotFoundException());
Team team = teamRepository.findById(payRequest.teamId())
.orElseThrow(() -> new TeamNotFoundException());

TeamChargeHistory teamChargeHistory = TeamChargeHistory.builder()
.transactionId(readyResponseResponseEntity.getBody().tid())
.paymentAmount(Integer.valueOf(payRequest.totalAmount()))
.paymentChargeStatus(PaymentChargeStatus.PENDING)
.team(team)
.build();
TeamChargeHistory teamChargeHistory = TeamChargeHistory.builder()
.transactionId(readyResponseResponseEntity.getBody().tid())
.paymentAmount(Integer.valueOf(payRequest.totalAmount()))
.paymentChargeStatus(PaymentChargeStatus.PENDING)
.team(team)
.build();

teamChargeHistoryRepository.save(teamChargeHistory);
teamChargeHistoryRepository.save(teamChargeHistory);

return readyResponseResponseEntity.getBody();
}
return readyResponseResponseEntity.getBody();
}

@Transactional
@Override
public ApproveResponse payApprove(String pgToken) {
Map<String, String> parameters = new HashMap<>();
parameters.put("cid", "TC0ONETIME"); // 가맹점 코드(테스트용)
parameters.put("tid", readyResponseResponseEntity.getBody().tid()); // 결제 고유번호
parameters.put("partner_order_id", "1234567890"); // 주문번호
parameters.put("partner_user_id", String.valueOf(userId)); // 회원 아이디
parameters.put("pg_token", pgToken); // 결제승인 요청을 인증하는 토큰
@Transactional
@Override
public ApproveResponse payApprove(String userId, String tid, String pgToken) {
Map<String, String> parameters = new HashMap<>();
parameters.put("cid", "TC0ONETIME"); // 가맹점 코드(테스트용)
parameters.put("tid", tid); // 결제 고유번호
parameters.put("partner_order_id", "1234567890"); // 주문번호
parameters.put("partner_user_id", String.valueOf(userId)); // 회원 아이디
parameters.put("pg_token", pgToken); // 결제승인 요청을 인증하는 토큰

HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(parameters, this.getHeaders());
HttpEntity<Map<String, String>> requestEntity = new HttpEntity<>(parameters, this.getHeaders());

RestTemplate template = new RestTemplate();
RestTemplate template = new RestTemplate();

String url = "https://open-api.kakaopay.com/online/v1/payment/approve";
ApproveResponse approveResponse = template.postForObject(url, requestEntity, ApproveResponse.class);
String url = "https://open-api.kakaopay.com/online/v1/payment/approve";
ApproveResponse approveResponse = template.postForObject(url, requestEntity, ApproveResponse.class);

TeamChargeHistory teamChargeHistory = teamChargeHistoryRepository.findByTransactionId(
readyResponseResponseEntity.getBody().tid())
.orElseThrow(() -> new NullPointerException());
TeamChargeHistory teamChargeHistory = teamChargeHistoryRepository.findByTransactionId(tid)
.orElseThrow(() -> new NullPointerException());

teamChargeHistory.completePaymentChargeStatus();
teamChargeHistory.completePaymentChargeStatus();

Team team = teamRepository.findById(teamChargeHistory.getTeam().getId())
.orElseThrow(() -> new TeamNotFoundException());
Team team = teamRepository.findById(teamChargeHistory.getTeam().getId())
.orElseThrow(() -> new TeamNotFoundException());

team.updatePoint(teamChargeHistory.getPaymentAmount());
team.updatePoint(teamChargeHistory.getPaymentAmount());

return approveResponse;
}
return approveResponse;
}

private HttpHeaders getHeaders() {
HttpHeaders headers = new HttpHeaders();
String auth = "SECRET_KEY " + secretKey;
headers.set("Authorization", auth);
headers.set("Content-type", "application/json");
private HttpHeaders getHeaders() {
HttpHeaders headers = new HttpHeaders();
String auth = "SECRET_KEY " + secretKey;
headers.set("Authorization", auth);
headers.set("Content-type", "application/json");

return headers;
}
return headers;
}
}
Original file line number Diff line number Diff line change
@@ -1,27 +1,25 @@
package com.jangburich.domain.payment.application;

import org.springframework.stereotype.Service;

import com.jangburich.domain.payment.application.strategy.PaymentServiceStrategy;
import com.jangburich.domain.payment.dto.request.PayRequest;
import com.jangburich.domain.payment.dto.response.ApproveResponse;
import com.jangburich.domain.payment.dto.response.ReadyResponse;

import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class PaymentProcessingService {

private final PaymentServiceStrategy paymentServiceStrategy;
private final PaymentServiceStrategy paymentServiceStrategy;

public ReadyResponse processPayment(Long userId, PayRequest payRequest) {
PaymentService paymentService = paymentServiceStrategy.getPaymentService(payRequest.paymentType());
return paymentService.payReady(userId, payRequest);
}
public ReadyResponse processPayment(String userId, PayRequest payRequest) {
PaymentService paymentService = paymentServiceStrategy.getPaymentService(payRequest.paymentType());
return paymentService.payReady(userId, payRequest);
}

public ApproveResponse processSuccess(String pgToken) {
PaymentService paymentService = paymentServiceStrategy.getPaymentService("kakao");
return paymentService.payApprove(pgToken);
}
public ApproveResponse processSuccess(String userId, String tid, String pgToken) {
PaymentService paymentService = paymentServiceStrategy.getPaymentService("kakao");
return paymentService.payApprove(userId, tid, pgToken);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,7 @@
import com.jangburich.domain.payment.dto.response.ReadyResponse;

public interface PaymentService {
String getType();

ReadyResponse payReady(Long userId, PayRequest payRequest);

ApproveResponse payApprove(String pgToken);
String getType();
ReadyResponse payReady(String userId, PayRequest payRequest);
ApproveResponse payApprove(String userId, String tid, String pgToken);
}
Original file line number Diff line number Diff line change
@@ -1,5 +1,15 @@
package com.jangburich.domain.team.application;

import com.jangburich.domain.team.domain.Team;
import com.jangburich.domain.team.domain.TeamLeader;
import com.jangburich.domain.team.domain.TeamType;
import com.jangburich.domain.team.domain.UserTeam;
import com.jangburich.domain.team.domain.repository.TeamRepository;
import com.jangburich.domain.team.domain.repository.UserTeamRepository;
import com.jangburich.domain.team.dto.request.RegisterTeamRequest;
import com.jangburich.domain.user.domain.User;
import com.jangburich.domain.user.domain.repository.UserRepository;
import com.jangburich.global.payload.Message;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
Expand All @@ -9,5 +19,35 @@
@RequiredArgsConstructor
public class TeamService {

private static final int ZERO = 0;

private final TeamRepository teamRepository;
private final UserRepository userRepository;
private final UserTeamRepository userTeamRepository;

@Transactional
public Message registerTeam(String userId, RegisterTeamRequest registerTeamRequest) {
User user = userRepository.findByProviderId(userId)
.orElseThrow(() -> new NullPointerException());

Team team = Team.builder()
.name(registerTeamRequest.teamName())
.description(registerTeamRequest.description())
.teamLeader(new TeamLeader(user.getUserId(), registerTeamRequest.teamLeaderAccountNumber(),
registerTeamRequest.bankName()))
.point(ZERO)
.memberLimit(registerTeamRequest.memberLimit())
.teamType(TeamType.valueOf(registerTeamRequest.teamType()))
.build();

System.out.println("222");
teamRepository.save(team);

UserTeam userTeam = UserTeam.of(user, team);
userTeamRepository.save(userTeam);

return Message.builder()
.message("팀 생성이 완료되었습니다.")
.build();
}
}
21 changes: 14 additions & 7 deletions src/main/java/com/jangburich/domain/team/domain/Team.java
Original file line number Diff line number Diff line change
Expand Up @@ -3,19 +3,16 @@
import jakarta.persistence.Embedded;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import java.util.HashSet;
import java.util.Set;

import com.jangburich.domain.common.BaseEntity;
import com.jangburich.domain.user.domain.User;

import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
import jakarta.persistence.Id;
import jakarta.persistence.ManyToMany;
import lombok.AccessLevel;
import lombok.Builder;
import lombok.Getter;
import lombok.NoArgsConstructor;

Expand Down Expand Up @@ -51,10 +48,20 @@ public class Team extends BaseEntity {
@Column(name = "team_type")
private TeamType teamType;

@ManyToMany(mappedBy = "teams")
private Set<User> users = new HashSet<>();

public void updatePoint(Integer point) {
this.point += point;
}


@Builder
public Team(String name, String description, String secretCode, TeamLeader teamLeader, Integer point,
Integer memberLimit, TeamType teamType) {
this.name = name;
this.description = description;
this.secretCode = secretCode;
this.teamLeader = teamLeader;
this.point = point;
this.memberLimit = memberLimit;
this.teamType = teamType;
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,12 @@
public class TeamLeader {
private Long user_id;
private String accountNumber;
private String bankName;

public TeamLeader(Long user_id, String accountNumber) {
public TeamLeader(Long user_id, String accountNumber, String bankName) {
this.user_id = user_id;
this.accountNumber = accountNumber;
this.bankName = bankName;
}

public boolean isSameLeader(Long userId) {
Expand Down
Loading

0 comments on commit a63a709

Please sign in to comment.