From 976eaf7653e4bd1ae8abb0ea084cea8bcc541863 Mon Sep 17 00:00:00 2001 From: Tim Howitz Date: Mon, 2 Jun 2025 07:57:50 +0100 Subject: [PATCH] Fixed shop and added sending to api route --- src/app/shop/page.tsx | 227 +++++++++++++++++++++++++++++++++--------- 1 file changed, 179 insertions(+), 48 deletions(-) diff --git a/src/app/shop/page.tsx b/src/app/shop/page.tsx index aa72a7f..81494de 100644 --- a/src/app/shop/page.tsx +++ b/src/app/shop/page.tsx @@ -1,11 +1,12 @@ "use client"; -import Image from 'next/image'; -import { Dispatch, SetStateAction, useCallback, useEffect, useState } from 'react'; +import axios from "axios"; +import Image from "next/image"; +import { Dispatch, SetStateAction, useCallback, useEffect, useState } from "react"; -import { ExtendedArtefact } from '@appTypes/ApiTypes'; -import { Currency } from '@appTypes/StoreModel'; -import BottomFooter from '@components/BottomFooter'; -import { useStoreState } from '@hooks/store'; +import { ExtendedArtefact } from "@appTypes/ApiTypes"; +import { Currency } from "@appTypes/StoreModel"; +import BottomFooter from "@components/BottomFooter"; +import { useStoreState } from "@hooks/store"; interface SuperExtendedArtefact extends ExtendedArtefact { location: string; @@ -18,9 +19,12 @@ export default function Shop() { const [artefacts, setArtefacts] = useState([]); const [hiddenArtefactIds, setHiddenArtefactIds] = useState([]); const [loading, setLoading] = useState(true); + + const [cart, setCart] = useState([]); + const [showCartModal, setShowCartModal] = useState(false); + const user = useStoreState((state) => state.user); - // 3. Fetch from your API route and map data to fit your existing fields useEffect(() => { async function fetchArtefacts() { setLoading(true); @@ -50,6 +54,7 @@ export default function Shop() { const [selectedArtefact, setSelectedArtefact] = useState(null); const [showPaymentModal, setShowPaymentModal] = useState(false); const [artefactToBuy, setArtefactToBuy] = useState(null); + const [cartCheckout, setCartCheckout] = useState(false); // true = checkout cart (not single artefact) const [showThankYouModal, setShowThankYouModal] = useState(false); const [orderNumber, setOrderNumber] = useState(null); @@ -93,11 +98,14 @@ export default function Shop() { ); } + function Modal({ artefact }: { artefact: SuperExtendedArtefact }) { if (!artefact) return null; const handleOverlayClick = (e: React.MouseEvent) => { if (e.target === e.currentTarget) setSelectedArtefact(null); }; + const inCart = cart.some((a) => a.id === artefact.id); + return (
{artefact.earthquakeCode}

{artefact.type}

{artefact.dateReleased}

-
+
+
@@ -138,15 +162,99 @@ export default function Shop() { ); } - function PaymentModal({ artefact, onClose }: { artefact: SuperExtendedArtefact; onClose: () => void }) { + function CartModal() { + const total = cart.reduce((sum, art) => sum + art.price, 0); + + const handleOverlayClick = (e: React.MouseEvent) => { + if (e.target === e.currentTarget) setShowCartModal(false); + }; + + return ( +
+
+
+

Your Cart

+ +
+ {cart.length === 0 ? ( +

Your cart is empty.

+ ) : ( + <> +
    + {cart.map((art) => ( +
  • +
    + {art.name} +
    +
    +

    {art.name}

    +

    {art.location}

    +
    +

    + {currencyTickers[selectedCurrency]} + {convertPrice(art.price, selectedCurrency)} +

    + +
  • + ))} +
+
+ Total: + + {currencyTickers[selectedCurrency]} + {convertPrice(total, selectedCurrency)} + +
+
+ +
+ + )} +
+
+ ); + } + + function PaymentModal({ + artefact, + onClose, + cartItems, + }: { + artefact?: SuperExtendedArtefact; + onClose: () => void; + cartItems?: SuperExtendedArtefact[]; + }) { const [cardNumber, setCardNumber] = useState(""); const [expiry, setExpiry] = useState(""); const [cvc, setCvc] = useState(""); const [name, setName] = useState(""); - const [email, setEmail] = useState(""); + const [email, setEmail] = useState(user?.email || ""); const [remember, setRemember] = useState(false); const [error, setError] = useState(""); + const artefactsToBuy = artefact ? [artefact] : cartItems || []; + const total = artefactsToBuy.reduce((sum, art) => sum + art.price, 0); + function validateEmail(email: string) { return ( email.includes("@") && @@ -162,18 +270,13 @@ export default function Shop() { function validateExpiry(exp: string) { return /^\d{2}\/\d{2}$/.test(exp); } - function handlePay() { setError(""); - if (email || user?.email) { - if (!validateEmail(email)) { - setError("Please enter a valid email ending"); - return; - } - } else { + const paymentEmail = user?.email || email; + if (!validateEmail(paymentEmail)) { + setError("Please enter a valid email"); return; } - if (!validateCardNumber(cardNumber)) { setError("Card number must be 12-19 digits."); return; @@ -186,44 +289,61 @@ export default function Shop() { setError("CVC must be 3 or 4 digits."); return; } - - setHiddenArtefactIds((ids) => [...ids, artefact.id]); - - // todo!! create receiving api route - // todo!! handle sending to api route + // remove all artefacts that were bought (works for both cart and single) + setHiddenArtefactIds((ids) => [...ids, ...artefactsToBuy.map((a) => a.id)]); + //!! todo create receiving api route const genOrder = () => "#" + Math.random().toString(36).substring(2, 10).toUpperCase(); - setOrderNumber(genOrder()); - onClose(); - setShowThankYouModal(true); + const orderNum = genOrder(); + + // todo add display of error + (async () => { + try { + const response = await axios.post("/api/shop/purchase", artefactsToBuy); + setOrderNumber(orderNum); + onClose(); + setShowThankYouModal(true); + setCart((c) => c.filter((a) => !artefactsToBuy.map((x) => x.id).includes(a.id))); + } catch (error) { + console.error("Error posting artefacts:", error); + throw error; + } + })(); } const handleOverlayClick = (e: React.MouseEvent) => { if (e.target === e.currentTarget) onClose(); }; return (
-

Buy {artefact.name}

- {/* ...Image... */} +

+ Checkout {artefact ? artefact.name : artefactsToBuy.length + " item(s)"} + {!artefact && ({artefactsToBuy.map((x) => x.name).join(", ")})} +

{ e.preventDefault(); handlePay(); }} > - {!user ? ( - setEmail(e.target.value)} - type="email" - required - autoFocus - /> - ) : null} + {/* Email autofill */} + setEmail(e.target.value)} + type="email" + required + autoFocus + disabled={!!user?.email} + /> + {user?.email && ( +

+ Signed in as {user.email} +

+ )} {error &&

{error}

} +
+ Total: + + {currencyTickers[selectedCurrency]} + {convertPrice(total, selectedCurrency)} + +
{selectedArtefact && } - {artefactToBuy && showPaymentModal && ( + {showCartModal && } + {showPaymentModal && (cartCheckout || artefactToBuy) && ( { setShowPaymentModal(false); setArtefactToBuy(null); + setCartCheckout(false); }} /> )} {showThankYouModal && orderNumber && ( setShowThankYouModal(false)} /> )} - {!selectedArtefact && !showPaymentModal && !showThankYouModal && ( + {!selectedArtefact && !showPaymentModal && !showThankYouModal && !showCartModal && (