|
------------------------카트서비스
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import cohttp://m.shoppingmall.item.Item;
import cohttp://m.shoppingmall.item.ItemService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
@Service
public class CartService {
@Autowired
private CartRepository cartRepository;
@Autowired
private ItemService itemService;
public void createCart(Long usersid) {
if (usersid == null) throw new NullPointerException("usersid should not be null");
cartRepository.save(new Cart(usersid));
}
public boolean hasUserCart(Long usersid) {
if (usersid == null) throw new NullPointerException("usersid should not be null");
for (Cart c : cartRepository.findAll()) {
if (c.getUsersid().equals(usersid))
return true;
}
return false;
}
public Optional<Cart> getUserCart(Long usersid) {
if (usersid == null) throw new NullPointerException("UserId should not be null");
return cartRepository.findById(usersid);
}
public void addItemToCart(Long usersid, Long itemid, Long quantity, HttpServletRequest request, HttpServletResponse response) {
if (request == null) {
throw new IllegalArgumentException("HttpServletRequest should not be null");
}
String contextPath = request.getContextPath();
if (usersid == null) {
throw new NullPointerException("usersid should not be null");
}
if (itemid == null) {
throw new NullPointerException("itemid should not be null");
}
Optional<Cart> cartOptional = getUserCart(usersid);
if (cartOptional.isEmpty()) {
// 로그인하지 않은 사용자가 장바구니에 접근하려고 할 때 로그인 페이지로 리디렉션
try {
response.sendRedirect(contextPath + "/login"); // 로그인 페이지 URL로 수정
} catch (IOException e) {
// 처리할 예외 상황
e.printStackTrace();
}
return;
}
Cart cart = cartOptional.get();
cart.getCartitem().put(itemid, quantity);
cartRepository.save(cart);
}
// @Autowired
public void removeItemFromCart(Long usersid, Long itemid, HttpServletRequest request, HttpServletResponse response) {
if (request == null) {
throw new IllegalArgumentException("HttpServletRequest should not be null");
}
String contextPath = request.getContextPath();
if (usersid == null) throw new NullPointerException("UserId should not be null");
if (itemid == null) throw new NullPointerException("itemId should not be null");
Optional<Cart> cartOptional = getUserCart(usersid);
if (cartOptional.isEmpty())
throw new NullPointerException("Cart is empty");
Cart cart = cartOptional.get();
cart.getCartitem().remove(itemid);
cartRepository.save(cart);
}
public void removeItemFromStock(Long cartid) {
if (cartid == null) throw new NullPointerException("cartId should not be null");
Map<Item, Long> cartitem = getItemsFromCart(cartid);
for (Item i : cartitem.keySet()) {
i.setStock((int) (i.getStock() - cartitem.get(i)));
itemService.save(i);
}
resetCart(cartid);
}
// @Autowired
public void resetCart(Long cartid) {
if (cartid == null) throw new NullPointerException("cartId should not be null");
Optional<Cart> cartOptional = cartRepository.findById(cartid);
Cart cart = cartOptional.get();
cart.setCartitem(new HashMap<>());
cartRepository.save(cart);
}
public Map<Item, Long> getItemsFromCart(Long cartid) {
if (cartid == null) throw new NullPointerException("cartId should not be null");
Map<Item, Long> cartitem = new HashMap<>();
Optional<Cart> cartOptional = cartRepository.findById(cartid);
if (cartOptional.isEmpty()) {
throw new NullPointerException("CartOptional should not be null");
}
Cart cart = cartOptional.get();
for (Long id : cart.getCartitem().keySet()) {
Optional<Item> itemOptional = itemService.findItemById(id);
if (itemOptional.isPresent()) {
Item item = itemOptional.get();
cartitem.put(item, cart.getCartitem().get(id));
} else {
// Handle the case when the item does not exist in the database
// For instance: log an error or skip adding it to the cartitem map
}
}
return cartitem;
}
public Long calculateTotalPrice(Map<Item, Long> cartitem) {
long price = 0L;
for (Item i : cartitem.keySet()) {
price += i.getPrice() *cartitem.get(i);
}
return price;
}
public void updateCartItemQuantity(Long cartid, Long itemid, Long newQuantity) {
System.out.println("++++++++++++++++++++++++++++++++++++++++++ " + cartid + "," +itemid + "," + newQuantity);
// Load the cart by cartId from the repository
Optional<Cart> cartOptional = cartRepository.findById(cartid);
cartOptional.ifPresent(cart -> {
Map<Long, Long> cartitem = cart.getCartitem();
if (cartitem.containsKey(itemid)) {
cartitem.put(itemid, newQuantity);
cart.setCartitem(cartitem);
System.out.println(cart.toString());
cartRepository.save(cart);// 디비갱신
}
});
}
}
----------------------------------카트컨트롤러
import java.util.Map;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import cohttp://m.shoppingmall.item.Item;
import cohttp://m.shoppingmall.item.ItemService;
import cohttp://m.shoppingmall.users.Users;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
@Controller
public class CartController {
@Autowired
private CartService cartService;
@Autowired
private ItemService itemService;
// @RequestMapping("/addItem")
// public String addItemToCart(@RequestParam Long usersid, @RequestParam Long itemid, @RequestParam Long quantity, HttpSession session,HttpServletRequest request) {
// // 이메일로 사용자 확인하는 부분을 가정
// if (session.getAttribute("loggedInUserEmail") == null) {
// return "redirect:/login"; // 로그인 페이지로 리다이렉트
// }
//
// // 로그인한 사용자에게만 카트 아이템 추가
// cartService.addItemToCart(usersid, itemid, quantity, null, null);
//
// return "redirect:/cart"; // 카트 페이지로 리다이렉트
// }
@GetMapping("/cart")//카트 아이디를 가져와 보도록 할것 // 이 코드가 최근
public String showCart(Model model, HttpSession session, @RequestParam("itemid") Optional<Long> itemid,HttpServletRequest request, HttpServletResponse response) {
System.out.println("start");
String contextPath = request.getContextPath();
Users loggedInUser = (Users) session.getAttribute("loggedInUser");
if (loggedInUser == null) {
return "redirect:/login";
}
Cart cart = null;
if (itemid.isEmpty()) {
if (cartService.hasUserCart(loggedInUser.getUsersid())) {
cart = cartService.getUserCart(loggedInUser.getUsersid()).get();
Map<Item, Long> cartitem = cartService.getItemsFromCart(cart.getCartid());
model.addAttribute("cartitem", cartitem);
model.addAttribute("total", cartService.calculateTotalPrice(cartitem));
model.addAttribute("cartid", cart.getCartid());
} else {
cartService.createCart(loggedInUser.getUsersid());
cart = cartService.getUserCart(loggedInUser.getUsersid()).get();
Map<Item, Long> cartitem = cartService.getItemsFromCart(cart.getCartid());
model.addAttribute("cartitem", cartitem);
model.addAttribute("total", cartService.calculateTotalPrice(cartitem));
model.addAttribute("cartid", cart.getCartid());
}
} else {
if (cartService.hasUserCart(loggedInUser.getUsersid())) {
cartService.addItemToCart(loggedInUser.getUsersid(), itemid.get(), 1L, request, response);
cart = cartService.getUserCart(loggedInUser.getUsersid()).get();
Map<Item, Long> cartitem = cartService.getItemsFromCart(cart.getCartid());
model.addAttribute("cartitem", cartitem);
model.addAttribute("total", cartService.calculateTotalPrice(cartitem));
model.addAttribute("cartid", cart.getCartid());
} else {
cartService.createCart(loggedInUser.getUsersid());
cartService.addItemToCart(loggedInUser.getUsersid(), itemid.get(), 1L, request, response);
cart = cartService.getUserCart(loggedInUser.getUsersid()).get();
Map<Item, Long> cartitem = cartService.getItemsFromCart(cart.getCartid());
model.addAttribute("cartitem", cartitem);
model.addAttribute("total", cartService.calculateTotalPrice(cartitem));
model.addAttribute("cartid", cart.getCartid());
}
}
//model.addAttribute("users", users);
return "cart/cartitem";
}
@GetMapping("/payment")
public String showPayment(Model model, Users users, @RequestParam("cartid") Optional<Long> cartid) {
model.addAttribute("users", users);
cartid.ifPresent(aLong -> cartService.removeItemFromStock(aLong));
return "order/payment";
}
@GetMapping("/removeFromCart")
public String removeFromCart(Model model, HttpSession session, @RequestParam("itemid") Optional<Long> itemid,HttpServletRequest request, HttpServletResponse response) {
System.out.println("delete");
String contextPath = request.getContextPath();
Users loggedInUser = (Users) session.getAttribute("loggedInUser");
if (loggedInUser == null) {
return "redirect:/login";
}
if (itemid.isEmpty())
return "redirect:/cart";
cartService.removeItemFromCart(loggedInUser.getUsersid(), itemid.get(),request, response); // 'removeItemToCart' -> 'removeItemFromCart'
return "redirect:/cart";
}
@PostMapping("/updateQuantity")
public String updateCartItemQuantity(@RequestParam String cartid, @RequestParam String itemid, @RequestParam String newQuantity, RedirectAttributes attributes) {
try {
cartService.updateCartItemQuantity(Long.parseLong(cartid), Long.parseLong(itemid), Long.parseLong(newQuantity));
attributes.addFlashAttribute("message", "Cart item quantity updated successfully");
} catch (Exception e) {
attributes.addFlashAttribute("error", "Error updating cart item quantity");
}
// 다시 원래 페이지로 리디렉션
return "redirect:/cart"; // 여기서 "yourPreviousPageURL"은 실제 이전 페이지의 URL로 대체되어야 합니다.
}
}