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

cart 요청 변경 후 preorder만들기 #205

Merged
merged 1 commit into from
Nov 14, 2024
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
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@
public class UserDetailsServiceImpl implements UserDetailsService {

private final MemberRepository memberRepository;

public UserDetailsServiceImpl(MemberRepository memberRepository) {
this.memberRepository = memberRepository;
}
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
package poomasi.domain.order.dto.request;

import jdk.jfr.Description;

@Description("cart에서 상품 정보 넘어오는 정보")
public record CartOrderRequest(
Long cartId,
Integer count
) {

}
Original file line number Diff line number Diff line change
@@ -1,6 +1,11 @@
package poomasi.domain.order.dto.request;

public record ProductOrderRegisterRequest(String destinationAddress,
String destinationAddressDetail,
String deliveryRequest) {
import java.util.List;

public record ProductOrderRegisterRequest(
List<CartOrderRequest> carts,
String destinationAddress,
String destinationAddressDetail,
String deliveryRequest)
{
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
import jakarta.persistence.CascadeType;
import jakarta.persistence.Column;
import jakarta.persistence.Entity;
import jakarta.persistence.EnumType;
import jakarta.persistence.Enumerated;
import jakarta.persistence.FetchType;
import jakarta.persistence.GeneratedValue;
import jakarta.persistence.GenerationType;
Expand Down Expand Up @@ -70,7 +72,8 @@ public class OrderedProduct implements Serializable {
@Column(name = "invoice_number", nullable = true)
private String invoiceNumber;

private OrderedProductStatus orderedProductStatus = OrderedProductStatus.PENDING_SELLER_APPROVAL;
@Enumerated(EnumType.STRING)
private OrderedProductStatus orderedProductStatus;

@Description("TODO : product의 delivery fee를 참조해야 한다.")
private BigDecimal deliveryFee;
Expand All @@ -96,15 +99,17 @@ public class OrderedProduct implements Serializable {
// 배송 상태 적절히 변경해야 함

@Builder
public OrderedProduct(Product product, ProductOrder productOrder, String productDescription,
String productName, BigDecimal price, Integer count) {
public OrderedProduct(Product product, ProductOrder productOrder, OrderedProductStatus orderedProductStatus, String productDescription,
BigDecimal deliveryFee, String productName, BigDecimal price, Integer count) {
this.product = product;
this.productOrder = productOrder;
this.productDescription = productDescription;
this.productName = productName;
this.price = price;
this.count = count;
this.review = null;
this.orderedProductStatus = orderedProductStatus;
this.deliveryFee = deliveryFee;
}

public void setInvoiceNumber(String invoiceNumber) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@


import jakarta.persistence.*;
import java.util.ArrayList;
import jdk.jfr.Description;
import lombok.Builder;
import lombok.Getter;
Expand All @@ -25,13 +26,13 @@ public class ProductOrder extends AbstractOrder {

@Column(name = "merchant_uid")
@Description("서버 내부 주문 id(아임포트 id)")
private String merchantUid = "p" + new Date().getTime();
private String merchantUid;

@Column(name = "ordered_products_id")
@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
private List<OrderedProduct> orderedProducts;
private List<OrderedProduct> orderedProducts = new ArrayList<>();

@OneToOne
@OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)
@JoinColumn(name = "product_order_details_id") // 외래 키 지정
@Description("상품 배송지, 요청 사항")
private ProductOrderDetails productOrderDetails;
Expand All @@ -41,7 +42,7 @@ public ProductOrder(){
}

public void addOrderedProduct(OrderedProduct orderedProduct) {
this.orderedProducts.add(orderedProduct);
orderedProducts.add(orderedProduct);
}

public void setMerchantUid(String merchantUid) {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package poomasi.domain.order.repository;

import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.web.bind.annotation.RequestMapping;
import poomasi.domain.order.entity._product.ProductOrderDetails;

@RequestMapping
public interface ProductOrderDetailsRepository extends JpaRepository<ProductOrderDetails,Long> {

}
51 changes: 36 additions & 15 deletions src/main/java/poomasi/domain/order/service/ProductOrderService.java
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
package poomasi.domain.order.service;

import java.util.ArrayList;
import java.util.Date;
import jdk.jfr.Description;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
Expand All @@ -9,27 +11,33 @@
import org.springframework.transaction.annotation.Transactional;
import poomasi.domain.auth.security.userdetail.UserDetailsImpl;
import poomasi.domain.member.entity.Member;
import poomasi.domain.order.dto.request.CartOrderRequest;
import poomasi.domain.order.dto.request.ProductOrderRegisterRequest;
import poomasi.domain.order.dto.response.OrderDetailsResponse;
import poomasi.domain.order.dto.response.OrderProductDetailsResponse;
import poomasi.domain.order.dto.response.OrderResponse;
import poomasi.domain.order.entity.PaymentStatus;
import poomasi.domain.order.entity._product.OrderedProduct;
import poomasi.domain.order.entity._product.OrderedProductStatus;
import poomasi.domain.order.entity._product.ProductOrder;
import poomasi.domain.order.entity._product.ProductOrderDetails;
import poomasi.domain.order.repository.OrderedProductRepository;
import poomasi.domain.order.repository.ProductOrderDetailsRepository;
import poomasi.domain.order.repository.ProductOrderRepository;
import poomasi.domain.product._cart.entity.Cart;
import poomasi.domain.product._cart.repository.CartRepository;
import poomasi.domain.product._cart.service.CartService;
import poomasi.domain.product.entity.Product;
import poomasi.domain.product.repository.ProductRepository;
import poomasi.global.error.ApplicationException;
import poomasi.global.error.BusinessError;
import poomasi.global.error.BusinessException;
import poomasi.payment.dto.request.PaymentPreRegisterRequest;

import java.math.BigDecimal;
import java.util.List;
import java.util.stream.Collectors;
import poomasi.payment.entity.Payment;

import static poomasi.global.error.ApplicationError.PAYMENT_NOT_FOUND;
import static poomasi.global.error.BusinessError.*;
Expand All @@ -41,68 +49,79 @@
public class ProductOrderService {

private final ProductOrderRepository productOrderRepository;
private final CartRepository cartRepository;
private final CartService cartService;
private final ProductRepository productRepository;
private final OrderedProductRepository orderedProductRepository;
private final ProductOrderDetailsRepository productOrderDetailsRepository;

@Transactional
public PaymentPreRegisterRequest productPreOrderRegister(ProductOrderRegisterRequest productOrderRegisterRequest) {
Member member = getMember();
Long memberId = member.getId();
List<Cart> cartList = cartRepository.findByMemberIdAndSelected(memberId);
List<Long> idList = productOrderRegisterRequest.carts().stream().map(CartOrderRequest::cartId).toList();
List<Cart> cartList = cartService.getCartsByIdList(idList);

String destinationAddress = productOrderRegisterRequest.destinationAddress();
String destinationAddressDetail = productOrderRegisterRequest.destinationAddressDetail();
String deliveryRequest = productOrderRegisterRequest.deliveryRequest();

ProductOrder productOrder = new ProductOrder()
ProductOrder productOrder = ProductOrder
.builder()
.merchantUid("p" + new Date().getTime())
.payment(new Payment())
.totalAmount(BigDecimal.ZERO)
.member(member)
.orderedProducts(new ArrayList<>())
.build();
productOrderRepository.save(productOrder);

ProductOrderDetails productOrderDetails = new ProductOrderDetails()
ProductOrderDetails productOrderDetails = ProductOrderDetails
.builder()
.productOrder(productOrder)
.destinationAddress(destinationAddress)
.destinationAddressDetail(destinationAddressDetail)
.deliveryRequest(deliveryRequest)
.build();

productOrderDetailsRepository.save(productOrderDetails);

productOrder.setProductOrderDetails(productOrderDetails);

//cart에 있는 총 가격 계산하기
BigDecimal totalPrice = BigDecimal.ZERO;

// cart 돌면서 productOrder details 추가
for (Cart cart : cartList) {
Long productId = cart.getProductId();
Product product = productRepository.findById(productId)
.orElseThrow(() -> new BusinessException(PRODUCT_NOT_FOUND));
for (int i=0 ; i<cartList.size() ; i++) {
Product product = cartList.get(i).getProduct();
if(product == null)
throw new BusinessException(PRODUCT_NOT_FOUND);
//Cart cart = cartList.get(i);

Integer productStock = product.getStock();
Integer quantityInCart = cart.getCount();
Integer quantityInCart = productOrderRegisterRequest.carts().get(i).count();

// 현재 남아있는 재고보다 더 많이 요청하면
// pending 상태로 저장이 안 됨.
//현재 남아있는 재고보다 더 많이 요청하면
//pending 상태로 저장이 안 됨.
if (quantityInCart > productStock) {
throw new BusinessException(PRODUCT_STOCK_ZERO);
}

String productDescription = product.getDescription();
Integer count = cart.getCount();
String productName = product.getName();
BigDecimal price = product.getPrice();
BigDecimal price = product.getPrice().multiply(BigDecimal.valueOf((long) quantityInCart));

//TODO : Store store = product.getStore();

OrderedProduct orderedProduct = OrderedProduct
.builder()
.product(product)
.orderedProductStatus(OrderedProductStatus.PENDING_SELLER_APPROVAL)
.deliveryFee(product.getShippingFee())
.productOrder(productOrder)
//.store(store)
.productDescription(productDescription)
.productName(productName)
.price(price)
.count(count)
.count(quantityInCart)
.build();

productOrder.addOrderedProduct(orderedProduct);
Expand All @@ -112,6 +131,8 @@ public PaymentPreRegisterRequest productPreOrderRegister(ProductOrderRegisterReq
productOrder.setCheckSum(totalPrice);
productOrderRepository.save(productOrder);

productOrder.setProductOrderDetails(productOrderDetails);

String merchantUid = productOrder.getMerchantUid();
return new PaymentPreRegisterRequest(merchantUid, totalPrice);
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,83 +4,61 @@
import lombok.RequiredArgsConstructor;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PatchMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import poomasi.domain.product._cart.dto.CartRegisterRequest;
import poomasi.domain.product._cart.dto.CartRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import poomasi.domain.auth.security.userdetail.UserDetailsImpl;
import poomasi.domain.member.entity.Member;
import poomasi.domain.product._cart.dto.CartResponse;
import poomasi.domain.product._cart.service.CartService;

@Controller
@RequiredArgsConstructor
@RequestMapping("/api/cart")
public class CartController {

private final CartService cartService;

//장바구니 정보
@GetMapping("/api/cart")
public ResponseEntity<?> getCart() {
List<CartResponse> cart = cartService.getCart();
//장바구니 모든 정보
@GetMapping("")
public ResponseEntity<?> getCart(@AuthenticationPrincipal UserDetailsImpl userDetails) {
Member member = userDetails.getMember();
List<CartResponse> cart = cartService.getCart(member);
return ResponseEntity.ok().body(cart);
}

//장바구니 선택한거만 가격
@GetMapping("/api/cart/price")
public ResponseEntity<?> getPrice() {
Integer price = cartService.getPrice();
return ResponseEntity.ok().body(price);
}

//장바구니 추가
@PostMapping("/api/cart")
public ResponseEntity<?> addCart(@RequestBody CartRegisterRequest cartRequest) {
Long cartId = cartService.addCart(cartRequest);
@PostMapping("/{productId}")
public ResponseEntity<?> addCart(
@AuthenticationPrincipal UserDetailsImpl userDetails,
@PathVariable Long productId) {
Member member = userDetails.getMember();
Long cartId = cartService.addCart(member, productId);
return new ResponseEntity<>(cartId, HttpStatus.CREATED);
}

//장바구니 선택/해제
@PostMapping("/api/cart/select")
public ResponseEntity<?> changeSelect(@RequestBody CartRequest cartRequest) {
cartService.changeSelect(cartRequest);
return ResponseEntity.ok().build();
}

//장바구니 삭제
@DeleteMapping("/api/cart")
public ResponseEntity<?> removeCart(@RequestBody CartRequest cartRequest) {
cartService.deleteCart(cartRequest);
return ResponseEntity.ok().build();
}

//장바구니 선택된거 삭제
@DeleteMapping("/api/cart/selected")
public ResponseEntity<?> removeSelected() {
cartService.removeSelected();
@DeleteMapping("/{cartId}")
public ResponseEntity<?> removeCart(
@AuthenticationPrincipal UserDetailsImpl userDetails,
@PathVariable Long cartId) {
Member member = userDetails.getMember();
cartService.deleteCart(member, cartId);
return ResponseEntity.ok().build();
}

//장바구니 전부 삭제
@DeleteMapping("/api/cart/all")
public ResponseEntity<?> removeAllCart() {
cartService.deleteAll();
return ResponseEntity.ok().build();
}

//장바구니 물건 개수 추가
@PatchMapping("/api/cart/add")
public ResponseEntity<?> addCount(@RequestBody CartRequest cartRequest) {
cartService.addCount(cartRequest);
@DeleteMapping("/all")
public ResponseEntity<?> removeAllCart(@AuthenticationPrincipal UserDetailsImpl userDetails) {
Member member = userDetails.getMember();
cartService.deleteAll(member);
return ResponseEntity.ok().build();
}

//장바구니 물건 개수 감소
@PatchMapping("/api/cart/sub")
public ResponseEntity<?> subCount(@RequestBody CartRequest cartRequest) {
cartService.subCount(cartRequest);
return ResponseEntity.ok().build();
}
}

This file was deleted.

Loading
Loading