Stripe Payment

This commit is contained in:
augmentedpotato
2026-04-09 22:27:03 -06:00
parent 559f3bc343
commit 4d91d8b331
26 changed files with 2022 additions and 33 deletions

View File

@@ -1,13 +1,13 @@
# Build
FROM maven:3.9-eclipse-temurin-17 AS build
FROM maven:3.9-eclipse-temurin-25-alpine AS build
WORKDIR /app
COPY pom.xml .
COPY src ./src
RUN mvn -q -DskipTests package
# Run
FROM eclipse-temurin:17-jre
FROM eclipse-temurin:25-jre
WORKDIR /app
COPY --from=build /app/target/*.jar app.jar
EXPOSE 8080
ENTRYPOINT ["java","-jar","app.jar"]
ENTRYPOINT ["java","-jar","app.jar"]

View File

@@ -26,6 +26,7 @@ services:
SPRING_DATASOURCE_PASSWORD: petshop
# Change this in real use (must be at least 32 characters)
JWT_SECRET: change_me_please_this_secret_key_is_long_enough_for_jwt_hmac_sha256
STRIPE_SECRET_KEY: sk_test_51TK18lFQ95OLlFb7XuwaVRxK2w9CNfeCJMhJt76mGvhRp84ddhX62wiJAcU7jMEP0GodH8aoFx0BZFI3tuf8tIiC00aaW1xQJT
ports:
- "8080:8080"
depends_on:

View File

@@ -90,6 +90,12 @@
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>com.stripe</groupId>
<artifactId>stripe-java</artifactId>
<version>25.3.0</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>

View File

@@ -0,0 +1,84 @@
package com.petshop.backend.controller;
import com.petshop.backend.dto.cart.*;
import com.petshop.backend.service.CartService;
import com.petshop.backend.util.AuthenticationHelper;
import jakarta.validation.Valid;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/v1/cart")
public class CartController {
private final CartService cartService;
public CartController(CartService cartService) {
this.cartService = cartService;
}
@GetMapping
@PreAuthorize("isAuthenticated()")
public ResponseEntity<CartResponse> getActiveCart(@RequestParam Long storeId) {
Long userId = AuthenticationHelper.getAuthenticatedUserId();
CartResponse cart = cartService.getActiveCart(userId, storeId);
if (cart == null) {
return ResponseEntity.noContent().build();
}
return ResponseEntity.ok(cart);
}
@PostMapping("/add")
@PreAuthorize("isAuthenticated()")
public ResponseEntity<CartResponse> addItem(@Valid @RequestBody AddToCartRequest request) {
Long userId = AuthenticationHelper.getAuthenticatedUserId();
return ResponseEntity.ok(cartService.addItem(userId, request));
}
@PutMapping("/update")
@PreAuthorize("isAuthenticated()")
public ResponseEntity<CartResponse> updateItem(@Valid @RequestBody UpdateCartItemRequest request) {
Long userId = AuthenticationHelper.getAuthenticatedUserId();
return ResponseEntity.ok(cartService.updateItem(userId, request));
}
@DeleteMapping("/remove/{cartItemId}")
@PreAuthorize("isAuthenticated()")
public ResponseEntity<CartResponse> removeItem(@PathVariable Long cartItemId) {
Long userId = AuthenticationHelper.getAuthenticatedUserId();
return ResponseEntity.ok(cartService.removeItem(userId, cartItemId));
}
@DeleteMapping("/clear")
@PreAuthorize("isAuthenticated()")
public ResponseEntity<Void> clearCart(@RequestParam Long storeId) {
Long userId = AuthenticationHelper.getAuthenticatedUserId();
cartService.clearCart(userId, storeId);
return ResponseEntity.noContent().build();
}
@PostMapping("/apply-coupon")
@PreAuthorize("isAuthenticated()")
public ResponseEntity<CartResponse> applyCoupon(
@RequestParam Long storeId,
@Valid @RequestBody ApplyCouponRequest request) {
Long userId = AuthenticationHelper.getAuthenticatedUserId();
return ResponseEntity.ok(cartService.applyCoupon(userId, storeId, request.getCouponCode()));
}
@PostMapping("/checkout")
@PreAuthorize("isAuthenticated()")
public ResponseEntity<CheckoutResponse> checkout(@Valid @RequestBody CheckoutRequest request) {
Long userId = AuthenticationHelper.getAuthenticatedUserId();
return ResponseEntity.ok(cartService.checkout(userId, request.getStoreId(), request.getPaymentMethodId()));}
}

View File

@@ -14,7 +14,6 @@ import org.springframework.web.bind.annotation.*;
@RestController
@RequestMapping("/api/v1/stores")
@PreAuthorize("hasRole('ADMIN')")
public class StoreController {
private final StoreService storeService;
@@ -24,6 +23,7 @@ public class StoreController {
}
@GetMapping
@PreAuthorize("isAuthenticated()")
public ResponseEntity<Page<StoreResponse>> getAllStores(
@RequestParam(required = false) String q,
Pageable pageable) {
@@ -31,6 +31,7 @@ public class StoreController {
}
@GetMapping("/{id}")
@PreAuthorize("isAuthenticated()")
public ResponseEntity<StoreResponse> getStoreById(@PathVariable Long id) {
return ResponseEntity.ok(storeService.getStoreById(id));
}

View File

@@ -0,0 +1,43 @@
package com.petshop.backend.dto.cart;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
public class AddToCartRequest {
@NotNull
private Long prodId;
@NotNull
private Long storeId;
@NotNull
@Min(1)
private Integer quantity;
public Long getProdId() {
return prodId;
}
public void setProdId(Long prodId) {
this.prodId = prodId;
}
public Long getStoreId() {
return storeId;
}
public void setStoreId(Long storeId) {
this.storeId = storeId;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
}

View File

@@ -0,0 +1,17 @@
package com.petshop.backend.dto.cart;
import jakarta.validation.constraints.NotBlank;
public class ApplyCouponRequest {
@NotBlank
private String couponCode;
public String getCouponCode() {
return couponCode;
}
public void setCouponCode(String couponCode) {
this.couponCode = couponCode;
}
}

View File

@@ -0,0 +1,90 @@
package com.petshop.backend.dto.cart;
import java.math.BigDecimal;
public class CartItemResponse {
private Long cartItemId;
private Long prodId;
private String prodName;
private String imageUrl;
private BigDecimal unitPrice;
private Integer quantity;
private BigDecimal lineTotal;
public CartItemResponse() {
}
public CartItemResponse(Long cartItemId, Long prodId, String prodName, String imageUrl,
BigDecimal unitPrice, Integer quantity, BigDecimal lineTotal) {
this.cartItemId = cartItemId;
this.prodId = prodId;
this.prodName = prodName;
this.imageUrl = imageUrl;
this.unitPrice = unitPrice;
this.quantity = quantity;
this.lineTotal = lineTotal;
}
public Long getCartItemId() {
return cartItemId;
}
public void setCartItemId(Long cartItemId) {
this.cartItemId = cartItemId;
}
public Long getProdId() {
return prodId;
}
public void setProdId(Long prodId) {
this.prodId = prodId;
}
public String getProdName() {
return prodName;
}
public void setProdName(String prodName) {
this.prodName = prodName;
}
public String getImageUrl() {
return imageUrl;
}
public void setImageUrl(String imageUrl) {
this.imageUrl = imageUrl;
}
public BigDecimal getUnitPrice() {
return unitPrice;
}
public void setUnitPrice(BigDecimal unitPrice) {
this.unitPrice = unitPrice;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
public BigDecimal getLineTotal() {
return lineTotal;
}
public void setLineTotal(BigDecimal lineTotal) {
this.lineTotal = lineTotal;
}
}

View File

@@ -0,0 +1,43 @@
package com.petshop.backend.dto.cart;
import java.math.BigDecimal;
import java.util.List;
public class CartResponse {
private Long cartId;
private Long storeId;
private String cartStatus;
private List<CartItemResponse> items;
private BigDecimal subtotalAmount;
private BigDecimal discountAmount;
private BigDecimal totalAmount;
private String couponCode;
public CartResponse() {
}
public Long getCartId() { return cartId; }
public void setCartId(Long cartId) { this.cartId = cartId; }
public Long getStoreId() { return storeId; }
public void setStoreId(Long storeId) { this.storeId = storeId; }
public String getCartStatus() { return cartStatus; }
public void setCartStatus(String cartStatus) { this.cartStatus = cartStatus; }
public List<CartItemResponse> getItems() { return items; }
public void setItems(List<CartItemResponse> items) { this.items = items; }
public BigDecimal getSubtotalAmount() { return subtotalAmount; }
public void setSubtotalAmount(BigDecimal subtotalAmount) { this.subtotalAmount = subtotalAmount; }
public BigDecimal getDiscountAmount() { return discountAmount; }
public void setDiscountAmount(BigDecimal discountAmount) { this.discountAmount = discountAmount; }
public BigDecimal getTotalAmount() { return totalAmount; }
public void setTotalAmount(BigDecimal totalAmount) { this.totalAmount = totalAmount; }
public String getCouponCode() { return couponCode; }
public void setCouponCode(String couponCode) { this.couponCode = couponCode; }
}

View File

@@ -0,0 +1,24 @@
package com.petshop.backend.dto.cart;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull;
public class CheckoutRequest {
@NotNull
private Long storeId;
@NotBlank
private String paymentMethodId;
public Long getStoreId() { return storeId; }
public void setStoreId(Long storeId) { this.storeId = storeId; }
public String getPaymentMethodId() {
return paymentMethodId;
}
public void setPaymentMethodId(String paymentMethodId) {
this.paymentMethodId = paymentMethodId;
}
}

View File

@@ -0,0 +1,57 @@
package com.petshop.backend.dto.cart;
import java.math.BigDecimal;
public class CheckoutResponse {
private Long cartId;
private String clientSecret;
private BigDecimal totalAmount;
private String status;
public CheckoutResponse() {
}
public CheckoutResponse(Long cartId, String clientSecret, BigDecimal totalAmount, String status) {
this.cartId = cartId;
this.clientSecret = clientSecret;
this.totalAmount = totalAmount;
this.status = status;
}
public Long getCartId() {
return cartId;
}
public void setCartId(Long cartId) {
this.cartId = cartId;
}
public String getClientSecret() {
return clientSecret;
}
public void setClientSecret(String clientSecret) {
this.clientSecret = clientSecret;
}
public BigDecimal getTotalAmount() {
return totalAmount;
}
public void setTotalAmount(BigDecimal totalAmount) {
this.totalAmount = totalAmount;
}
public String getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
}

View File

@@ -0,0 +1,32 @@
package com.petshop.backend.dto.cart;
import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotNull;
public class UpdateCartItemRequest {
@NotNull
private Long cartItemId;
@NotNull
@Min(1)
private Integer quantity;
public Long getCartItemId() {
return cartItemId;
}
public void setCartItemId(Long cartItemId) {
this.cartItemId = cartItemId;
}
public Integer getQuantity() {
return quantity;
}
public void setQuantity(Integer quantity) {
this.quantity = quantity;
}
}

View File

@@ -5,9 +5,14 @@ import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import java.util.List;
import java.util.Optional;
@Repository
public interface CartItemRepository extends JpaRepository<CartItem, Long> {
List<CartItem> findByCartCartId(Long cartId);
Optional<CartItem> findByCartCartIdAndProductProdId(Long cartId, Long prodId);
void deleteByCartCartId(Long cartId);
}

View File

@@ -2,6 +2,8 @@ package com.petshop.backend.repository;
import com.petshop.backend.entity.Cart;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;
import java.util.List;
@@ -13,4 +15,9 @@ public interface CartRepository extends JpaRepository<Cart, Long> {
List<Cart> findByUserId(Long userId);
Optional<Cart> findByUserIdAndCartStatus(Long userId, String cartStatus);
@Query("SELECT c FROM Cart c WHERE c.user.id = :userId AND c.store.storeId = :storeId AND c.cartStatus = :status")
Optional<Cart> findActiveCartByUserAndStore(@Param("userId") Long userId,
@Param("storeId") Long storeId,
@Param("status") String status);
}

View File

@@ -10,4 +10,6 @@ import java.util.Optional;
public interface CouponRepository extends JpaRepository<Coupon, Long> {
Optional<Coupon> findByCouponCode(String couponCode);
Optional<Coupon> findByCouponCodeIgnoreCase(String couponCode);
}

View File

@@ -0,0 +1,301 @@
package com.petshop.backend.service;
import com.petshop.backend.dto.cart.*;
import com.petshop.backend.entity.*;
import com.petshop.backend.exception.BusinessException;
import com.petshop.backend.exception.ResourceNotFoundException;
import com.petshop.backend.repository.*;
import com.stripe.Stripe;
import com.stripe.exception.StripeException;
import com.stripe.model.PaymentIntent;
import com.stripe.param.PaymentIntentCreateParams;
import jakarta.annotation.PostConstruct;
import jakarta.transaction.Transactional;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.util.List;
@Service
public class CartService {
private final CartRepository cartRepository;
private final CartItemRepository cartItemRepository;
private final UserRepository userRepository;
private final StoreRepository storeRepository;
private final ProductRepository productRepository;
private final CouponRepository couponRepository;
@Value("${stripe.secret-key:}")
private String stripeSecretKey;
public CartService(CartRepository cartRepository,
CartItemRepository cartItemRepository,
UserRepository userRepository,
StoreRepository storeRepository,
ProductRepository productRepository,
CouponRepository couponRepository) {
this.cartRepository = cartRepository;
this.cartItemRepository = cartItemRepository;
this.userRepository = userRepository;
this.storeRepository = storeRepository;
this.productRepository = productRepository;
this.couponRepository = couponRepository;
}
@PostConstruct
public void initStripe() {
if (stripeSecretKey != null && !stripeSecretKey.isBlank()) {
Stripe.apiKey = stripeSecretKey;
}
}
public CartResponse getActiveCart(Long userId, Long storeId) {
return cartRepository
.findActiveCartByUserAndStore(userId, storeId, "ACTIVE")
.map(this::toResponse)
.orElse(null);
}
@Transactional
public CartResponse addItem(Long userId, AddToCartRequest request) {
User user = userRepository.findById(userId).orElseThrow(() -> new ResourceNotFoundException("User not found"));
StoreLocation store = storeRepository.findById(request.getStoreId()).orElseThrow(() -> new ResourceNotFoundException("Store not found"));
Product product = productRepository.findById(request.getProdId()).orElseThrow(() -> new ResourceNotFoundException("Product not found"));
if (request.getQuantity() < 1) {
throw new BusinessException("Quantity must be at least 1");
}
Cart cart = cartRepository
.findActiveCartByUserAndStore(userId, request.getStoreId(), "ACTIVE")
.orElseGet(() -> {
Cart newCart = new Cart();
newCart.setUser(user);
newCart.setStore(store);
newCart.setCartStatus("ACTIVE");
return cartRepository.save(newCart);
});
cartItemRepository.findByCartCartIdAndProductProdId(cart.getCartId(), product.getProdId())
.ifPresentOrElse(
existing -> existing.setQuantity(existing.getQuantity() + request.getQuantity()),
() -> {
CartItem item = new CartItem();
item.setCart(cart);
item.setProduct(product);
item.setQuantity(request.getQuantity());
item.setUnitPrice(product.getProdPrice());
cartItemRepository.save(item);
}
);
recalculate(cart);
return toResponse(cart);
}
@Transactional
public CartResponse updateItem(Long userId, UpdateCartItemRequest request) {
CartItem item = cartItemRepository.findById(request.getCartItemId())
.orElseThrow(() -> new ResourceNotFoundException("Cart item not found"));
if (!item.getCart().getUser().getId().equals(userId)) {
throw new BusinessException("Access denied");
}
if (!item.getCart().getCartStatus().equals("ACTIVE")) {
throw new BusinessException("Cart is not active");
}
if (request.getQuantity() < 1) {
throw new BusinessException("Quantity must be at least 1");
}
item.setQuantity(request.getQuantity());
cartItemRepository.save(item);
recalculate(item.getCart());
return toResponse(item.getCart());
}
@Transactional
public CartResponse removeItem(Long userId, Long cartItemId) {
CartItem item = cartItemRepository.findById(cartItemId)
.orElseThrow(() -> new ResourceNotFoundException("Cart item not found"));
if (!item.getCart().getUser().getId().equals(userId)) {
throw new BusinessException("Access denied");
}
if (!item.getCart().getCartStatus().equals("ACTIVE")) {
throw new BusinessException("Cart is not active");
}
Cart cart = item.getCart();
cartItemRepository.delete(item);
recalculate(cart);
return toResponse(cart);
}
@Transactional
public void clearCart(Long userId, Long storeId) {
cartRepository.findActiveCartByUserAndStore(userId, storeId, "ACTIVE")
.ifPresent(cart -> {
cartItemRepository.deleteByCartCartId(cart.getCartId());
cart.setSubtotalAmount(BigDecimal.ZERO);
cart.setDiscountAmount(BigDecimal.ZERO);
cart.setTotalAmount(BigDecimal.ZERO);
cart.setCoupon(null);
cartRepository.save(cart);
});
}
@Transactional
public CartResponse applyCoupon(Long userId, Long storeId, String couponCode) {
Cart cart = cartRepository
.findActiveCartByUserAndStore(userId, storeId, "ACTIVE")
.orElseThrow(() -> new BusinessException("No active cart found"));
Coupon coupon = couponRepository.findByCouponCodeIgnoreCase(couponCode)
.orElseThrow(() -> new BusinessException("Invalid coupon code"));
LocalDateTime now = LocalDateTime.now();
if (!coupon.getActive()) {
throw new BusinessException("Coupon is no longer active");
}
if (coupon.getStartsAt() != null && now.isBefore(coupon.getStartsAt())) {
throw new BusinessException("Coupon is not yet valid");
}
if (coupon.getEndsAt() != null && now.isAfter(coupon.getEndsAt())) {
throw new BusinessException("Coupon has expired");
}
if (coupon.getMinOrderAmount() != null && cart.getSubtotalAmount().compareTo(coupon.getMinOrderAmount()) < 0) {
throw new BusinessException("Minimum order amount of $" + coupon.getMinOrderAmount() + " required");
}
cart.setCoupon(coupon);
recalculate(cart);
return toResponse(cart);
}
@Transactional
public CheckoutResponse checkout(Long userId, Long storeId, String paymentMethodId) {
Cart cart = cartRepository
.findActiveCartByUserAndStore(userId, storeId, "ACTIVE")
.orElseThrow(() -> new BusinessException("No active cart found"));
List<CartItem> items = cartItemRepository.findByCartCartId(cart.getCartId());
if (items.isEmpty()) {
throw new BusinessException("Cart is empty");
}
long amountInCents = cart.getTotalAmount()
.multiply(BigDecimal.valueOf(100))
.setScale(0, RoundingMode.HALF_UP)
.longValue();
if (amountInCents < 50) {
throw new BusinessException("Order total is too low to process payment");
}
try {
PaymentIntentCreateParams params = PaymentIntentCreateParams.builder()
.setAmount(amountInCents)
.setCurrency("usd")
.setPaymentMethod(paymentMethodId)
.setConfirm(true)
.setReturnUrl("http://localhost:3000/cart/confirmation")
.putMetadata("cartId", String.valueOf(cart.getCartId()))
.putMetadata("userId", String.valueOf(userId))
.build();
PaymentIntent intent = PaymentIntent.create(params);
if ("succeeded".equals(intent.getStatus())
|| "requires_action".equals(intent.getStatus())) {
cart.setCartStatus("CHECKED_OUT");
cartRepository.save(cart);
}
return new CheckoutResponse(
cart.getCartId(),
intent.getClientSecret(),
cart.getTotalAmount(),
intent.getStatus()
);
}
catch (StripeException e) {
throw new BusinessException("Payment processing failed: " + e.getMessage());
}
}
private void recalculate(Cart cart) {
List<CartItem> items = cartItemRepository.findByCartCartId(cart.getCartId());
BigDecimal subtotal = items.stream()
.map(i -> i.getUnitPrice().multiply(BigDecimal.valueOf(i.getQuantity())))
.reduce(BigDecimal.ZERO, BigDecimal::add);
cart.setSubtotalAmount(subtotal);
BigDecimal discount = BigDecimal.ZERO;
Coupon coupon = cart.getCoupon();
if (coupon != null) {
if ("PERCENTAGE".equalsIgnoreCase(coupon.getDiscountType())) {
discount = subtotal.multiply(coupon.getDiscountValue())
.divide(BigDecimal.valueOf(100), 2, RoundingMode.HALF_UP);
}
else if ("FIXED".equalsIgnoreCase(coupon.getDiscountType())) {
discount = coupon.getDiscountValue().min(subtotal);
}
}
discount = discount.max(BigDecimal.ZERO).min(subtotal);
cart.setDiscountAmount(discount);
cart.setTotalAmount(subtotal.subtract(discount).max(BigDecimal.ZERO));
cartRepository.save(cart);
}
private CartResponse toResponse(Cart cart) {
List<CartItemResponse> itemResponses = cartItemRepository
.findByCartCartId(cart.getCartId())
.stream()
.map(item -> new CartItemResponse(
item.getCartItemId(),
item.getProduct().getProdId(),
item.getProduct().getProdName(),
item.getProduct().getImageUrl(),
item.getUnitPrice(),
item.getQuantity(),
item.getUnitPrice().multiply(BigDecimal.valueOf(item.getQuantity()))
))
.toList();
CartResponse response = new CartResponse();
response.setCartId(cart.getCartId());
response.setStoreId(cart.getStore() != null ? cart.getStore().getStoreId() : null);
response.setCartStatus(cart.getCartStatus());
response.setItems(itemResponses);
response.setSubtotalAmount(cart.getSubtotalAmount());
response.setDiscountAmount(cart.getDiscountAmount());
response.setTotalAmount(cart.getTotalAmount());
response.setCouponCode(cart.getCoupon() != null ? cart.getCoupon().getCouponCode() : null);
return response;
}
}

View File

@@ -50,6 +50,9 @@ jwt:
secret: ${JWT_SECRET:change_me_please_make_this_at_least_32_characters_long_for_security}
expiration: ${JWT_EXPIRATION:86400000}
stripe:
secret-key: ${STRIPE_SECRET_KEY:}
logging:
level:
com.petshop: ${LOG_LEVEL:INFO}

356
web/app/cart/page.js Normal file
View File

@@ -0,0 +1,356 @@
"use client";
import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { useAuth } from "@/context/AuthContext";
import { useCart } from "@/context/CartContext";
import { loadStripe } from "@stripe/stripe-js";
import {
Elements,
PaymentElement,
useStripe,
useElements,
} from "@stripe/react-stripe-js";
const stripePromise = loadStripe(process.env.NEXT_PUBLIC_STRIPE_PUBLISHABLE_KEY || "");
function PaymentForm({ clientSecret, totalAmount, onSuccess, onCancel }) {
const stripe = useStripe();
const elements = useElements();
const [paying, setPaying] = useState(false);
const [payError, setPayError] = useState(null);
async function handlePay(e) {
e.preventDefault();
if (!stripe || !elements) return;
setPaying(true);
setPayError(null);
const { error } = await stripe.confirmPayment({
elements,
confirmParams: { return_url: window.location.origin + "/cart/confirmation" },
redirect: "if_required",
});
if (error) {
setPayError(error.message);
setPaying(false);
}
else {
onSuccess();
}
}
return (
<div className="cart-payment-form">
<h3 className="cart-payment-title">Payment Details</h3>
<p className="cart-payment-total">
Total to pay: <strong>${parseFloat(totalAmount).toFixed(2)}</strong>
</p>
<PaymentElement />
{payError && <p className="cart-error-msg">{payError}</p>}
<div className="cart-payment-actions">
<button
className="cart-pay-btn"
type="button"
onClick={handlePay}
disabled={paying || !stripe}
>
{paying ? "Processing…" : `Pay $${parseFloat(totalAmount).toFixed(2)}`}
</button>
<button className="cart-cancel-btn" type="button" onClick={onCancel}>
Cancel
</button>
</div>
</div>
);
}
export default function CartPage() {
const { user, loading: authLoading } = useAuth();
const {
cart,
cartLoading,
cartError,
selectedStoreId,
updateItem,
removeItem,
clearCart,
applyCoupon,
checkout,
} = useCart();
const router = useRouter();
const [couponInput, setCouponInput] = useState("");
const [couponError, setCouponError] = useState(null);
const [couponLoading, setCouponLoading] = useState(false);
const [checkoutLoading, setCheckoutLoading] = useState(false);
const [checkoutError, setCheckoutError] = useState(null);
const [clientSecret, setClientSecret] = useState(null);
const [checkoutTotal, setCheckoutTotal] = useState(null);
const [confirmed, setConfirmed] = useState(false);
const [localQuantities, setLocalQuantities] = useState({});
useEffect(() => {
if (!authLoading && !user) {
router.push("/login");
}
}, [authLoading, user, router]);
useEffect(() => {
if (cart?.items) {
const map = {};
cart.items.forEach((i) => (map[i.cartItemId] = i.quantity));
setLocalQuantities(map);
}
}, [cart]);
async function handleQuantityChange(cartItemId, newQty) {
if (newQty < 1) {
return;
}
setLocalQuantities((prev) => ({ ...prev, [cartItemId]: newQty }));
try {
await updateItem(cartItemId, newQty);
}
catch {
if (cart?.items) {
const original = cart.items.find((i) => i.cartItemId === cartItemId);
if (original) {
setLocalQuantities((prev) => ({ ...prev, [cartItemId]: original.quantity }));
}
}
}
}
async function handleRemove(cartItemId) {
try {
await removeItem(cartItemId);
}
catch {
}
}
async function handleApplyCoupon() {
if (!couponInput.trim()) return;
setCouponLoading(true);
setCouponError(null);
try {
await applyCoupon(couponInput.trim());
setCouponInput("");
}
catch (err) {
setCouponError(err.message);
}
finally {
setCouponLoading(false);
}
}
async function handleCheckout() {
if (!cart?.items?.length) return;
setCheckoutLoading(true);
setCheckoutError(null);
try {
const result = await checkout("pm_card_visa");
if (result?.clientSecret) {
setClientSecret(result.clientSecret);
setCheckoutTotal(result.totalAmount);
}
else if (result?.status === "succeeded") {
setConfirmed(true);
}
}
catch (err) {
setCheckoutError(err.message);
}
finally {
setCheckoutLoading(false);
}
}
if (authLoading || cartLoading) {
return <main className="cart-page"><p className="cart-status-msg">Loading</p></main>;
}
if (!user) return null;
if (confirmed) {
return (
<main className="cart-page">
<div className="cart-confirmation">
<div className="cart-confirmation-icon"></div>
<h2 className="cart-confirmation-title">Order Confirmed!</h2>
<p className="cart-confirmation-body">
Thank you for your purchase. Your order has been placed successfully.
</p>
<button className="cart-continue-btn" type="button" onClick={() => router.push("/products")}>
Continue Shopping
</button>
</div>
</main>
);
}
if (!selectedStoreId) {
return (
<main className="cart-page">
<p className="cart-status-msg">Please select a store from the navigation bar to view your cart.</p>
</main>
);
}
const items = cart?.items ?? [];
return (
<main className="cart-page">
<h1 className="cart-title">Your Cart</h1>
{cartError && <p className="cart-error-msg">{cartError}</p>}
{items.length === 0 && !cartError && (
<div className="cart-empty">
<p className="cart-empty-msg">Your cart is empty.</p>
<button className="cart-continue-btn" type="button" onClick={() => router.push("/products")}>
Browse Products
</button>
</div>
)}
{items.length > 0 && (
<div className="cart-layout">
<div className="cart-items-section">
{items.map((item) => (
<div key={item.cartItemId} className="cart-item-row">
<img
src={item.imageUrl || "/images/pet-placeholder.png"}
alt={item.prodName}
className="cart-item-img"
onError={(e) => {
e.currentTarget.onerror = null;
e.currentTarget.src = "/images/pet-placeholder.png";
}}
/>
<div className="cart-item-details">
<p className="cart-item-name">{item.prodName}</p>
<p className="cart-item-unit-price">${parseFloat(item.unitPrice).toFixed(2)} each</p>
</div>
<div className="cart-item-qty-controls">
<button
className="cart-qty-btn"
type="button"
onClick={() =>
handleQuantityChange(item.cartItemId, (localQuantities[item.cartItemId] ?? item.quantity) - 1)
}
>
</button>
<span className="cart-qty-val">{localQuantities[item.cartItemId] ?? item.quantity}</span>
<button
className="cart-qty-btn"
type="button"
onClick={() =>
handleQuantityChange(item.cartItemId, (localQuantities[item.cartItemId] ?? item.quantity) + 1)
}
>
+
</button>
</div>
<p className="cart-item-line-total">
${(parseFloat(item.unitPrice) * (localQuantities[item.cartItemId] ?? item.quantity)).toFixed(2)}
</p>
<button
className="cart-item-remove-btn"
type="button"
onClick={() => handleRemove(item.cartItemId)}
>
</button>
</div>
))}
<button className="cart-clear-btn" type="button" onClick={clearCart}>
Clear Cart
</button>
</div>
<aside className="cart-summary">
<h2 className="cart-summary-title">Order Summary</h2>
<div className="cart-summary-row">
<span>Subtotal</span>
<span>${parseFloat(cart.subtotalAmount ?? 0).toFixed(2)}</span>
</div>
{parseFloat(cart.discountAmount ?? 0) > 0 && (
<div className="cart-summary-row cart-summary-discount">
<span>Discount {cart.couponCode && `(${cart.couponCode})`}</span>
<span>${parseFloat(cart.discountAmount).toFixed(2)}</span>
</div>
)}
<div className="cart-summary-row cart-summary-total">
<span>Total</span>
<span>${parseFloat(cart.totalAmount ?? 0).toFixed(2)}</span>
</div>
<div className="cart-coupon-section">
<input
className="cart-coupon-input"
type="text"
placeholder="Coupon code"
value={couponInput}
onChange={(e) => setCouponInput(e.target.value)}
onKeyDown={(e) => e.key === "Enter" && handleApplyCoupon()}
/>
<button
className="cart-coupon-btn"
type="button"
onClick={handleApplyCoupon}
disabled={couponLoading}
>
{couponLoading ? "…" : "Apply"}
</button>
{couponError && <p className="cart-coupon-error">{couponError}</p>}
</div>
{checkoutError && <p className="cart-error-msg">{checkoutError}</p>}
{!clientSecret && (
<button
className="cart-checkout-btn"
type="button"
onClick={handleCheckout}
disabled={checkoutLoading || items.length === 0}
>
{checkoutLoading ? "Processing…" : "Checkout"}
</button>
)}
{clientSecret && (
<Elements stripe={stripePromise} options={{ clientSecret }}>
<PaymentForm
clientSecret={clientSecret}
totalAmount={checkoutTotal ?? cart.totalAmount}
onSuccess={() => {
setClientSecret(null);
setConfirmed(true);
}}
onCancel={() => setClientSecret(null)}
/>
</Elements>
)}
</aside>
</div>
)}
</main>
);
}

View File

@@ -1843,3 +1843,527 @@ body {
border-color: #999;
color: #333;
}
/* ── Store Selector ──────────────────────────────────────── */
.nav-store-select {
background: rgba(255, 255, 255, 0.15);
color: white;
border: 1px solid rgba(255, 255, 255, 0.4);
border-radius: 6px;
padding: 0.3rem 0.6rem;
font-size: 0.9rem;
cursor: pointer;
margin-right: 0.5rem;
outline: none;
transition: background 0.2s ease;
}
.nav-store-select option {
background: #333;
color: white;
}
.nav-store-select:hover {
background: rgba(255, 255, 255, 0.25);
}
/* ── Cart Badge ──────────────────────────────────────────── */
.nav-cart-btn {
position: relative;
display: inline-flex;
align-items: center;
font-size: 1.4rem;
text-decoration: none;
margin-right: 0.5rem;
padding: 0.2rem 0.4rem;
border-radius: 6px;
transition: background 0.2s ease;
}
.nav-cart-btn:hover {
background: rgba(255, 255, 255, 0.2);
}
.nav-cart-badge {
position: absolute;
top: -4px;
right: -6px;
background: #e53935;
color: white;
border-radius: 999px;
font-size: 0.65rem;
font-weight: 700;
min-width: 18px;
height: 18px;
display: flex;
align-items: center;
justify-content: center;
padding: 0 3px;
line-height: 1;
}
/* ProductCard Add-to-Cart */
.product-card-wrapper {
display: flex;
flex-direction: column;
text-decoration: none;
}
.product-card-link {
text-decoration: none;
color: inherit;
flex: 1;
}
.product-card-actions {
padding: 0.6rem 0.75rem 0.75rem;
display: flex;
flex-direction: column;
gap: 0.4rem;
}
.product-card-qty-row {
display: flex;
align-items: center;
gap: 0.5rem;
}
.product-card-qty-btn {
width: 28px;
height: 28px;
border: 1px solid #ddd;
border-radius: 6px;
background: white;
font-size: 1rem;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
transition: border-color 0.2s ease;
}
.product-card-qty-btn:hover:not(:disabled) {
border-color: orange;
}
.product-card-qty-val {
min-width: 24px;
text-align: center;
font-weight: 600;
font-size: 0.9rem;
}
.product-card-add-btn {
width: 100%;
padding: 0.45rem;
background: orange;
color: white;
border: none;
border-radius: 8px;
font-size: 0.88rem;
font-weight: 700;
cursor: pointer;
transition: background 0.2s ease;
}
.product-card-add-btn:hover:not(:disabled) {
background: #e69500;
}
.product-card-add-btn:disabled {
opacity: 0.6;
cursor: not-allowed;
}
.product-card-feedback {
font-size: 0.78rem;
color: #2e7d32;
margin: 0;
text-align: center;
}
/* Cart Page */
.cart-page {
max-width: 1100px;
margin: 2rem auto;
padding: 0 1.5rem 3rem;
}
.cart-title {
font-size: 2rem;
font-weight: 800;
color: #222;
margin-bottom: 1.5rem;
}
.cart-status-msg {
text-align: center;
color: #888;
margin-top: 3rem;
font-size: 1rem;
}
.cart-error-msg {
color: #c0392b;
font-size: 0.9rem;
margin: 0.5rem 0;
}
.cart-empty {
display: flex;
flex-direction: column;
align-items: center;
gap: 1rem;
margin-top: 4rem;
}
.cart-empty-msg {
font-size: 1.1rem;
color: #666;
}
.cart-continue-btn {
background: orange;
color: white;
border: none;
border-radius: 8px;
padding: 0.65rem 1.5rem;
font-size: 1rem;
font-weight: 700;
cursor: pointer;
transition: background 0.2s ease;
}
.cart-continue-btn:hover {
background: #e69500;
}
.cart-layout {
display: grid;
grid-template-columns: 1fr 340px;
gap: 2rem;
align-items: start;
}
@media (max-width: 800px) {
.cart-layout {
grid-template-columns: 1fr;
}
}
.cart-items-section {
display: flex;
flex-direction: column;
gap: 0;
}
.cart-item-row {
display: grid;
grid-template-columns: 72px 1fr auto auto auto;
align-items: center;
gap: 1rem;
padding: 1rem 0;
border-bottom: 1px solid #eee;
}
.cart-item-img {
width: 72px;
height: 72px;
object-fit: cover;
border-radius: 8px;
background: #f5f5f5;
}
.cart-item-details {
display: flex;
flex-direction: column;
gap: 0.2rem;
}
.cart-item-name {
font-weight: 700;
font-size: 0.95rem;
color: #222;
margin: 0;
}
.cart-item-unit-price {
font-size: 0.82rem;
color: #888;
margin: 0;
}
.cart-item-qty-controls {
display: flex;
align-items: center;
gap: 0.4rem;
}
.cart-qty-btn {
width: 28px;
height: 28px;
border: 1px solid #ddd;
border-radius: 6px;
background: white;
font-size: 1rem;
cursor: pointer;
display: flex;
align-items: center;
justify-content: center;
transition: border-color 0.2s ease;
}
.cart-qty-btn:hover {
border-color: orange;
}
.cart-qty-val {
min-width: 28px;
text-align: center;
font-weight: 600;
}
.cart-item-line-total {
font-weight: 700;
font-size: 0.95rem;
color: #222;
min-width: 60px;
text-align: right;
margin: 0;
}
.cart-item-remove-btn {
background: none;
border: none;
color: #bbb;
font-size: 1rem;
cursor: pointer;
padding: 0.2rem;
transition: color 0.2s ease;
}
.cart-item-remove-btn:hover {
color: #c0392b;
}
.cart-clear-btn {
align-self: flex-start;
margin-top: 1rem;
background: none;
border: 1px solid #ddd;
border-radius: 6px;
padding: 0.4rem 0.9rem;
font-size: 0.82rem;
color: #888;
cursor: pointer;
transition: all 0.2s ease;
}
.cart-clear-btn:hover {
border-color: #c0392b;
color: #c0392b;
}
.cart-summary {
background: #fafafa;
border: 1px solid #eee;
border-radius: 14px;
padding: 1.5rem;
display: flex;
flex-direction: column;
gap: 0.75rem;
position: sticky;
top: 84px;
}
.cart-summary-title {
font-size: 1.2rem;
font-weight: 800;
color: #222;
margin: 0 0 0.5rem;
}
.cart-summary-row {
display: flex;
justify-content: space-between;
font-size: 0.95rem;
color: #444;
}
.cart-summary-discount {
color: #2e7d32;
}
.cart-summary-total {
font-size: 1.1rem;
font-weight: 800;
color: #222;
border-top: 1px solid #eee;
padding-top: 0.75rem;
margin-top: 0.25rem;
}
.cart-coupon-section {
display: flex;
flex-wrap: wrap;
gap: 0.5rem;
margin-top: 0.25rem;
}
.cart-coupon-input {
flex: 1;
min-width: 0;
border: 1px solid #ddd;
border-radius: 7px;
padding: 0.5rem 0.75rem;
font-size: 0.88rem;
outline: none;
transition: border-color 0.2s ease;
}
.cart-coupon-input:focus {
border-color: orange;
}
.cart-coupon-btn {
background: #333;
color: white;
border: none;
border-radius: 7px;
padding: 0.5rem 0.9rem;
font-size: 0.88rem;
font-weight: 700;
cursor: pointer;
transition: background 0.2s ease;
}
.cart-coupon-btn:hover:not(:disabled) {
background: #111;
}
.cart-coupon-error {
width: 100%;
font-size: 0.8rem;
color: #c0392b;
margin: 0;
}
.cart-checkout-btn {
width: 100%;
padding: 0.85rem;
background: orange;
color: white;
border: none;
border-radius: 10px;
font-size: 1rem;
font-weight: 800;
cursor: pointer;
margin-top: 0.5rem;
transition: background 0.2s ease;
}
.cart-checkout-btn:hover:not(:disabled) {
background: #e69500;
}
.cart-checkout-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.cart-payment-form {
display: flex;
flex-direction: column;
gap: 0.75rem;
margin-top: 0.5rem;
}
.cart-payment-title {
font-size: 1rem;
font-weight: 700;
color: #222;
margin: 0;
}
.cart-payment-total {
font-size: 0.9rem;
color: #444;
margin: 0;
}
.cart-payment-actions {
display: flex;
flex-direction: column;
gap: 0.5rem;
}
.cart-pay-btn {
width: 100%;
padding: 0.75rem;
background: #1a56db;
color: white;
border: none;
border-radius: 8px;
font-size: 0.95rem;
font-weight: 700;
cursor: pointer;
transition: background 0.2s ease;
}
.cart-pay-btn:hover:not(:disabled) {
background: #1446c0;
}
.cart-pay-btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
.cart-cancel-btn {
width: 100%;
padding: 0.65rem;
background: white;
color: #666;
border: 1px solid #ddd;
border-radius: 8px;
font-size: 0.9rem;
font-weight: 600;
cursor: pointer;
transition: all 0.2s ease;
}
.cart-cancel-btn:hover {
border-color: #999;
color: #333;
}
.cart-confirmation {
display: flex;
flex-direction: column;
align-items: center;
gap: 1rem;
margin-top: 5rem;
text-align: center;
}
.cart-confirmation-icon {
font-size: 3.5rem;
}
.cart-confirmation-title {
font-size: 1.8rem;
font-weight: 800;
color: #222;
margin: 0;
}
.cart-confirmation-body {
font-size: 1rem;
color: #555;
max-width: 400px;
margin: 0;
}

View File

@@ -1,7 +1,12 @@
"use client";
import { AuthProvider } from "@/context/AuthContext";
import { CartProvider } from "@/context/CartContext";
export default function ClientProviders({children}) {
return <AuthProvider>{children}</AuthProvider>;
export default function ClientProviders({ children }) {
return (
<AuthProvider>
<CartProvider>{children}</CartProvider>
</AuthProvider>
);
}

View File

@@ -3,11 +3,25 @@
import Image from "next/image";
import Link from "next/link";
import { useRouter } from "next/navigation";
import { useEffect, useState } from "react";
import { useAuth } from "@/context/AuthContext";
import { useCart } from "@/context/CartContext";
export default function DisplayNav() {
const {user, logout, loading} = useAuth();
const { user, token, logout, loading } = useAuth();
const { itemCount, selectedStoreId, setStoreId } = useCart();
const router = useRouter();
const [stores, setStores] = useState([]);
useEffect(() => {
if (!token) return;
fetch("/api/v1/stores?size=100", {
headers: { Authorization: `Bearer ${token}` },
})
.then((r) => (r.ok ? r.json() : null))
.then((data) => { if (data) setStores(data.content ?? []); })
.catch(() => {});
}, [token]);
function handleLogout() {
logout();
@@ -16,12 +30,14 @@ export default function DisplayNav() {
return (
<nav className="navbar">
<Image className="mx-3"
<Image
className="mx-3"
src="/logo_simple.png"
alt="store_logo"
width={50}
height={50}
id="logo"/>
id="logo"
/>
<div className="nav-links">
<Link href="/" className="nav-link">Home</Link>
@@ -33,6 +49,30 @@ export default function DisplayNav() {
</div>
<div className="nav-auth">
{stores.length > 0 && (
<select
className="nav-store-select"
value={selectedStoreId ?? ""}
onChange={(e) => setStoreId(e.target.value || null)}
>
<option value="">Select Store</option>
{stores.map((s) => (
<option key={s.storeId} value={s.storeId}>
{s.storeName}
</option>
))}
</select>
)}
{user && (
<Link href="/cart" className="nav-cart-btn" aria-label="Cart">
🛒
{itemCount > 0 && (
<span className="nav-cart-badge">{itemCount > 99 ? "99+" : itemCount}</span>
)}
</Link>
)}
{loading ? null : user ? (
<>
<Link href="/profile" className="nav-link nav-greeting">

View File

@@ -1,26 +1,97 @@
"use client";
import Link from "next/link";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { useAuth } from "@/context/AuthContext";
import { useCart } from "@/context/CartContext";
export default function ProductCard({ prodId, prodName, categoryName, prodPrice, imageUrl }) {
const { user } = useAuth();
const { addItem, selectedStoreId } = useCart();
const router = useRouter();
const [quantity, setQuantity] = useState(1);
const [adding, setAdding] = useState(false);
const [feedback, setFeedback] = useState(null);
async function handleAddToCart(e) {
e.preventDefault();
if (!user) {
router.push("/login");
return;
}
if (!selectedStoreId) {
setFeedback("Please select a store first");
setTimeout(() => setFeedback(null), 2500);
return;
}
setAdding(true);
setFeedback(null);
try {
await addItem(prodId, quantity);
setFeedback("Added!");
setTimeout(() => setFeedback(null), 1500);
} catch (err) {
setFeedback(err.message || "Failed to add");
setTimeout(() => setFeedback(null), 2500);
} finally {
setAdding(false);
}
}
return (
<Link href={`/products/${prodId}`} className="pet-card">
<div className="pet-card-image-wrapper">
<img
src={imageUrl || "/images/pet-placeholder.png"}
alt={prodName}
className="pet-card-image"
onError={(e) => {
e.currentTarget.onerror = null;
e.currentTarget.src = "/images/pet-placeholder.png";
}}
/>
<div className="pet-card product-card-wrapper">
<Link href={`/products/${prodId}`} className="product-card-link">
<div className="pet-card-image-wrapper">
<img
src={imageUrl || "/images/pet-placeholder.png"}
alt={prodName}
className="pet-card-image"
onError={(e) => {
e.currentTarget.onerror = null;
e.currentTarget.src = "/images/pet-placeholder.png";
}}
/>
</div>
<div className="pet-card-body">
<h3 className="pet-card-name">{prodName}</h3>
<p className="pet-card-species">{categoryName}</p>
{prodPrice != null && (
<span className="product-card-price">${parseFloat(prodPrice).toFixed(2)}</span>
)}
</div>
</Link>
<div className="product-card-actions">
<div className="product-card-qty-row">
<button
className="product-card-qty-btn"
type="button"
onClick={() => setQuantity((q) => Math.max(1, q - 1))}
disabled={adding}
>
</button>
<span className="product-card-qty-val">{quantity}</span>
<button
className="product-card-qty-btn"
type="button"
onClick={() => setQuantity((q) => q + 1)}
disabled={adding}
>
+
</button>
</div>
<button
className="product-card-add-btn"
type="button"
onClick={handleAddToCart}
disabled={adding}
>
{adding ? "Adding…" : "Add to Cart"}
</button>
{feedback && <p className="product-card-feedback">{feedback}</p>}
</div>
<div className="pet-card-body">
<h3 className="pet-card-name">{prodName}</h3>
<p className="pet-card-species">{categoryName}</p>
{prodPrice != null && (
<span className="product-card-price">${parseFloat(prodPrice).toFixed(2)}</span>
)}
</div>
</Link>
</div>
);
}

171
web/context/CartContext.js Normal file
View File

@@ -0,0 +1,171 @@
"use client";
import { createContext, useContext, useState, useEffect, useCallback } from "react";
import { useAuth } from "@/context/AuthContext";
import {
fetchCart,
apiAddToCart,
apiUpdateCartItem,
apiRemoveCartItem,
apiClearCart,
apiApplyCoupon,
apiCheckout,
} from "@/lib/cartApi";
const CartContext = createContext(null);
const STORE_KEY = "selected_store_id";
export function CartProvider({ children }) {
const { user, token } = useAuth();
const [cart, setCart] = useState(null);
const [selectedStoreId, setSelectedStoreIdState] = useState(null);
const [cartLoading, setCartLoading] = useState(false);
const [cartError, setCartError] = useState(null);
const setStoreId = useCallback((id) => {
const parsed = id ? Number(id) : null;
setSelectedStoreIdState(parsed);
if (parsed) {
localStorage.setItem(STORE_KEY, String(parsed));
}
else {
localStorage.removeItem(STORE_KEY);
}
}, []);
useEffect(() => {
const stored = localStorage.getItem(STORE_KEY);
if (stored) {
setSelectedStoreIdState(Number(stored));
}
}, []);
const refreshCart = useCallback(async () => {
if (!token || !selectedStoreId) {
setCart(null);
return;
}
setCartLoading(true);
setCartError(null);
try {
const data = await fetchCart(token, selectedStoreId);
setCart(data);
}
catch (err) {
setCartError(err.message);
}
finally {
setCartLoading(false);
}
}, [token, selectedStoreId]);
useEffect(() => {
if (user && selectedStoreId) {
refreshCart();
}
else {
setCart(null);
}
}, [user, selectedStoreId, refreshCart]);
const addItem = useCallback(
async (prodId, quantity = 1) => {
if (!token || !selectedStoreId) throw new Error("Select a store first");
const updated = await apiAddToCart(token, { prodId, storeId: selectedStoreId, quantity });
setCart(updated);
return updated;
},
[token, selectedStoreId]
);
const updateItem = useCallback(
async (cartItemId, quantity) => {
if (!token) return;
const updated = await apiUpdateCartItem(token, { cartItemId, quantity });
setCart(updated);
return updated;
},
[token]
);
const removeItem = useCallback(
async (cartItemId) => {
if (!token) return;
const updated = await apiRemoveCartItem(token, cartItemId);
setCart(updated);
return updated;
},
[token]
);
const clearCart = useCallback(async () => {
if (!token || !selectedStoreId) return;
await apiClearCart(token, selectedStoreId);
setCart(null);
}, [token, selectedStoreId]);
const applyCoupon = useCallback(
async (couponCode) => {
if (!token || !selectedStoreId) throw new Error("Select a store first");
const updated = await apiApplyCoupon(token, selectedStoreId, couponCode);
setCart(updated);
return updated;
},
[token, selectedStoreId]
);
const checkout = useCallback(
async (paymentMethodId) => {
if (!token || !selectedStoreId) throw new Error("Select a store first");
const result = await apiCheckout(token, {
storeId: selectedStoreId,
paymentMethodId,
});
if (result?.status === "succeeded") {
setCart(null);
}
return result;
},
[token, selectedStoreId]
);
const itemCount = cart?.items?.reduce((sum, i) => sum + i.quantity, 0) ?? 0;
return (
<CartContext.Provider
value={{
cart,
cartLoading,
cartError,
itemCount,
selectedStoreId,
setStoreId,
addItem,
updateItem,
removeItem,
clearCart,
applyCoupon,
checkout,
refreshCart,
}}
>
{children}
</CartContext.Provider>
);
}
export function useCart() {
const ctx = useContext(CartContext);
if (!ctx) throw new Error("useCart must be used within a CartProvider");
return ctx;
}

84
web/lib/cartApi.js Normal file
View File

@@ -0,0 +1,84 @@
const BASE = "/api/v1/cart";
function authHeaders(token) {
return {
"Content-Type": "application/json",
Authorization: `Bearer ${token}`,
};
}
async function handleResponse(res) {
if (res.status === 204) return null;
const data = await res.json();
if (!res.ok) throw new Error(data.message || "Cart request failed");
return data;
}
export async function fetchCart(token, storeId) {
const res = await fetch(`${BASE}?storeId=${storeId}`, {
headers: authHeaders(token),
});
if (res.status === 204) return null;
const data = await res.json();
if (!res.ok) throw new Error(data.message || "Failed to fetch cart");
return data;
}
export async function apiAddToCart(token, { prodId, storeId, quantity }) {
const res = await fetch(`${BASE}/add`, {
method: "POST",
headers: authHeaders(token),
body: JSON.stringify({ prodId, storeId, quantity }),
});
return handleResponse(res);
}
export async function apiUpdateCartItem(token, { cartItemId, quantity }) {
const res = await fetch(`${BASE}/update`, {
method: "PUT",
headers: authHeaders(token),
body: JSON.stringify({ cartItemId, quantity }),
});
return handleResponse(res);
}
export async function apiRemoveCartItem(token, cartItemId) {
const res = await fetch(`${BASE}/remove/${cartItemId}`, {
method: "DELETE",
headers: authHeaders(token),
});
return handleResponse(res);
}
export async function apiClearCart(token, storeId) {
const res = await fetch(`${BASE}/clear?storeId=${storeId}`, {
method: "DELETE",
headers: authHeaders(token),
});
return handleResponse(res);
}
export async function apiApplyCoupon(token, storeId, couponCode) {
const res = await fetch(`${BASE}/apply-coupon?storeId=${storeId}`, {
method: "POST",
headers: authHeaders(token),
body: JSON.stringify({ couponCode }),
});
return handleResponse(res);
}
export async function apiCheckout(token, { storeId, paymentMethodId }) {
const res = await fetch(`${BASE}/checkout`, {
method: "POST",
headers: authHeaders(token),
body: JSON.stringify({ storeId, paymentMethodId }),
});
return handleResponse(res);
}

30
web/package-lock.json generated
View File

@@ -8,6 +8,8 @@
"name": "threaded-pets",
"version": "0.1.0",
"dependencies": {
"@stripe/react-stripe-js": "^3.1.1",
"@stripe/stripe-js": "^5.5.0",
"next": "^16.2.2",
"react": "19.2.3",
"react-dom": "19.2.3"
@@ -1230,6 +1232,29 @@
"dev": true,
"license": "MIT"
},
"node_modules/@stripe/react-stripe-js": {
"version": "3.10.0",
"resolved": "https://registry.npmjs.org/@stripe/react-stripe-js/-/react-stripe-js-3.10.0.tgz",
"integrity": "sha512-UPqHZwMwDzGSax0ZI7XlxR3tZSpgIiZdk3CiwjbTK978phwR/fFXeAXQcN/h8wTAjR4ZIAzdlI9DbOqJhuJdeg==",
"license": "MIT",
"dependencies": {
"prop-types": "^15.7.2"
},
"peerDependencies": {
"@stripe/stripe-js": ">=1.44.1 <8.0.0",
"react": ">=16.8.0 <20.0.0",
"react-dom": ">=16.8.0 <20.0.0"
}
},
"node_modules/@stripe/stripe-js": {
"version": "5.10.0",
"resolved": "https://registry.npmjs.org/@stripe/stripe-js/-/stripe-js-5.10.0.tgz",
"integrity": "sha512-PTigkxMdMUP6B5ISS7jMqJAKhgrhZwjprDqR1eATtFfh0OpKVNp110xiH+goeVdrJ29/4LeZJR4FaHHWstsu0A==",
"license": "MIT",
"engines": {
"node": ">=12.16"
}
},
"node_modules/@swc/helpers": {
"version": "0.5.15",
"resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.15.tgz",
@@ -4408,7 +4433,6 @@
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
"integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
"dev": true,
"license": "MIT"
},
"node_modules/js-yaml": {
@@ -4819,7 +4843,6 @@
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
"integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
"dev": true,
"license": "MIT",
"dependencies": {
"js-tokens": "^3.0.0 || ^4.0.0"
@@ -5064,7 +5087,6 @@
"version": "4.1.1",
"resolved": "https://registry.npmjs.org/object-assign/-/object-assign-4.1.1.tgz",
"integrity": "sha512-rJgTQnkUnH1sFw8yT6VSU3zD3sWmu6sZhIseY8VX+GRu3P6F7Fu+JNDoXfklElbLJSnc3FUQHVe4cU5hj+BcUg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=0.10.0"
@@ -5363,7 +5385,6 @@
"version": "15.8.1",
"resolved": "https://registry.npmjs.org/prop-types/-/prop-types-15.8.1.tgz",
"integrity": "sha512-oj87CgZICdulUohogVAR7AjlC0327U4el4L6eAvOqCeudMDVU0NThNaV+b9Df4dXgSP1gXMTnPdhfe/2qDH5cg==",
"dev": true,
"license": "MIT",
"dependencies": {
"loose-envify": "^1.4.0",
@@ -5427,7 +5448,6 @@
"version": "16.13.1",
"resolved": "https://registry.npmjs.org/react-is/-/react-is-16.13.1.tgz",
"integrity": "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ==",
"dev": true,
"license": "MIT"
},
"node_modules/reflect.getprototypeof": {

View File

@@ -9,6 +9,8 @@
"lint": "eslint"
},
"dependencies": {
"@stripe/react-stripe-js": "^3.1.1",
"@stripe/stripe-js": "^5.5.0",
"next": "^16.2.2",
"react": "19.2.3",
"react-dom": "19.2.3"