Stripe Payment

This commit is contained in:
augmentedpotato
2026-04-09 22:27:03 -06:00
parent a7ba0fb4b4
commit 1010d57b79
26 changed files with 2022 additions and 33 deletions

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"