Compare commits
3 Commits
4bca956cbb
...
dd650c6ba6
| Author | SHA1 | Date | |
|---|---|---|---|
| dd650c6ba6 | |||
| 128517b388 | |||
| bc78626a24 |
@ -2,20 +2,18 @@ import { NextResponse } from "next/server";
|
||||
import { prisma } from "@utils/prisma";
|
||||
|
||||
export async function POST(req: Request) {
|
||||
try {
|
||||
const { requestType, requestingUserId, scientistId, comment } = await req.json();
|
||||
const request = await prisma.request.create({
|
||||
data: {
|
||||
requestType,
|
||||
requestingUser: { connect: { id: requestingUserId } },
|
||||
outcome: "IN_PROGRESS",
|
||||
// Optionally you can connect to Scientist via an inline relation if you have a foreign key
|
||||
// If the model has comment or details fields, add it!
|
||||
},
|
||||
});
|
||||
return NextResponse.json({ request }, { status: 201 });
|
||||
} catch (error) {
|
||||
console.error("Request create error:", error);
|
||||
return NextResponse.json({ error: "Failed to create request" }, { status: 500 });
|
||||
}
|
||||
try {
|
||||
const { requestType, requestingUserId, scientistId, comment } = await req.json();
|
||||
const request = await prisma.request.create({
|
||||
data: {
|
||||
requestType,
|
||||
requestingUser: { connect: { id: requestingUserId } },
|
||||
outcome: "IN_PROGRESS",
|
||||
},
|
||||
});
|
||||
return NextResponse.json({ request }, { status: 201 });
|
||||
} catch (error) {
|
||||
console.error("Request create error:", error);
|
||||
return NextResponse.json({ error: "Failed to create request" }, { status: 500 });
|
||||
}
|
||||
}
|
||||
@ -13,8 +13,7 @@ export async function POST(req: Request) {
|
||||
if ("user" in authResult === false) return authResult;
|
||||
|
||||
const { user } = authResult;
|
||||
// todo handle requestedRole
|
||||
const { userId, email, name, password } = await req.json();
|
||||
const { userId, email, name, password, requestedRole } = await req.json();
|
||||
|
||||
// Trying to update a different user than themselves
|
||||
// Only available to admins
|
||||
@ -58,6 +57,12 @@ export async function POST(req: Request) {
|
||||
passwordHash = await bcryptjs.hash(password, 10);
|
||||
}
|
||||
|
||||
if (requestedRole && ["GUEST", "SCIENTIST", "ADMIN"].includes(requestedRole) && requestedRole !== user.role) {
|
||||
await prisma.request.create({
|
||||
data: { requestType: requestedRole, requestingUserId: userId || user.id },
|
||||
});
|
||||
}
|
||||
|
||||
const updatedUser = await prisma.user.update({
|
||||
where: { id: userId || user.id },
|
||||
data: {
|
||||
|
||||
@ -11,28 +11,6 @@ import EarthquakeSearchModal from "@components/EarthquakeSearchModal";
|
||||
import EarthquakeLogModal from "@components/EarthquakeLogModal"; // If you use a separate log modal
|
||||
import { useStoreState } from "@hooks/store";
|
||||
|
||||
// Optional: "No Access Modal" - as in your original
|
||||
function NoAccessModal({ open, onClose }) {
|
||||
if (!open) return null;
|
||||
return (
|
||||
<div className="fixed z-50 inset-0 bg-black/40 flex items-center justify-center">
|
||||
<div className="bg-white rounded-lg shadow-lg p-8 max-w-xs w-full text-center relative">
|
||||
<button onClick={onClose} className="absolute right-4 top-4 text-gray-500 hover:text-black text-lg" aria-label="Close">
|
||||
×
|
||||
</button>
|
||||
<h2 className="font-bold text-xl mb-4">Access Denied</h2>
|
||||
<p className="text-gray-600 mb-3">
|
||||
Sorry, you do not have access rights to Log an Earthquake. Please Log in here, or contact an Admin if you believe this
|
||||
is a mistake
|
||||
</p>
|
||||
<button onClick={onClose} className="bg-blue-600 text-white px-6 py-2 rounded hover:bg-blue-700 mt-2">
|
||||
OK
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function Earthquakes() {
|
||||
const [selectedEventId, setSelectedEventId] = useState("");
|
||||
const [hoveredEventId, setHoveredEventId] = useState("");
|
||||
@ -40,12 +18,9 @@ export default function Earthquakes() {
|
||||
const [logModalOpen, setLogModalOpen] = useState(false);
|
||||
const [noAccessModalOpen, setNoAccessModalOpen] = useState(false);
|
||||
|
||||
// Your user/role logic
|
||||
const user = useStoreState((state) => state.user);
|
||||
const role: "GUEST" | "SCIENTIST" | "ADMIN" = user?.role ?? "GUEST";
|
||||
const canLogEarthquake = role === "SCIENTIST" || role === "ADMIN";
|
||||
const canLogEarthquake = user?.role === "SCIENTIST" || user?.role === "ADMIN";
|
||||
|
||||
// Fetch earthquakes (10 days recent)
|
||||
const { data, error, isLoading, mutate } = useSWR("/api/earthquakes", createPoster({ rangeDaysPrev: 10 }));
|
||||
|
||||
// Shape for Map/Sidebar
|
||||
@ -80,6 +55,27 @@ export default function Earthquakes() {
|
||||
}
|
||||
};
|
||||
|
||||
function NoAccessModal({ open, onClose }: { open: typeof noAccessModalOpen; onClose: () => void }) {
|
||||
if (!open) return null;
|
||||
return (
|
||||
<div className="fixed z-50 inset-0 bg-black/40 flex items-center justify-center">
|
||||
<div className="bg-white rounded-lg shadow-lg p-8 max-w-xs w-full text-center relative">
|
||||
<button onClick={onClose} className="absolute right-4 top-4 text-gray-500 hover:text-black text-lg" aria-label="Close">
|
||||
×
|
||||
</button>
|
||||
<h2 className="font-bold text-xl mb-4">Access Denied</h2>
|
||||
<p className="text-gray-600 mb-3">
|
||||
Sorry, you do not have access rights to Log an Earthquake. Please Log in here, or contact an Admin if you believe this
|
||||
is a mistake
|
||||
</p>
|
||||
<button onClick={onClose} className="bg-blue-600 text-white px-6 py-2 rounded hover:bg-blue-700 mt-2">
|
||||
OK
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="flex h-[calc(100vh-3.5rem)] w-full overflow-hidden">
|
||||
<div className="flex-grow h-full">
|
||||
@ -107,15 +103,12 @@ export default function Earthquakes() {
|
||||
onButton2Click={() => setSearchModalOpen(true)}
|
||||
button1Disabled={!canLogEarthquake}
|
||||
/>
|
||||
{/* ---- SEARCH MODAL ---- */}
|
||||
<EarthquakeSearchModal
|
||||
open={searchModalOpen}
|
||||
onClose={() => setSearchModalOpen(false)}
|
||||
onSelect={(eq) => setSelectedEventId(eq.code)}
|
||||
/>
|
||||
{/* ---- LOGGING MODAL ---- */}
|
||||
<EarthquakeLogModal open={logModalOpen} onClose={() => setLogModalOpen(false)} onSuccess={() => mutate()} />
|
||||
{/* ---- NO ACCESS ---- */}
|
||||
<NoAccessModal open={noAccessModalOpen} onClose={() => setNoAccessModalOpen(false)} />
|
||||
</div>
|
||||
);
|
||||
|
||||
@ -229,6 +229,7 @@ export default function Profile() {
|
||||
}
|
||||
setIsDeleting(true);
|
||||
try {
|
||||
// todo add delete user route
|
||||
const res = await axios.post(
|
||||
"/api/delete-user",
|
||||
{ userId: user!.id },
|
||||
|
||||
@ -1,41 +1,43 @@
|
||||
"use client";
|
||||
import Image from "next/image";
|
||||
import { useCallback, useEffect, useState } from "react";
|
||||
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";
|
||||
|
||||
interface SuperExtendedArtefact extends ExtendedArtefact {
|
||||
location: string;
|
||||
dateReleased: string;
|
||||
image: string;
|
||||
price: number;
|
||||
}
|
||||
|
||||
export default function Shop() {
|
||||
const [artefacts, setArtefacts] = useState<ExtendedArtefact[]>([]);
|
||||
const [artefacts, setArtefacts] = useState<SuperExtendedArtefact[]>([]);
|
||||
const [hiddenArtefactIds, setHiddenArtefactIds] = useState<number[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
|
||||
const [cart, setCart] = useState<ExtendedArtefact[]>([]);
|
||||
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);
|
||||
try {
|
||||
const res = await fetch("/api/artefacts");
|
||||
const data = await res.json();
|
||||
const transformed = data.artefact.map((a: any) => ({
|
||||
id: a.id,
|
||||
name: a.name,
|
||||
description: a.description,
|
||||
location: a.warehouseArea,
|
||||
earthquakeID: a.earthquakeId?.toString() ?? "",
|
||||
observatory: a.type ?? "",
|
||||
const data: { artefact: ExtendedArtefact[] } = await res.json();
|
||||
|
||||
const transformed = data.artefact.map((a) => ({
|
||||
...a,
|
||||
location: a.warehouseArea, // your database
|
||||
dateReleased: a.createdAt ? new Date(a.createdAt).toLocaleDateString() : "",
|
||||
image: "/artefactImages/" + (a.imageName || "NoImageFound.PNG"),
|
||||
price: a.shopPrice ?? 100,
|
||||
price: a.shopPrice ?? 100, // fallback price if not in DB
|
||||
}));
|
||||
setArtefacts(transformed);
|
||||
} catch (e) {
|
||||
// Optionally handle error
|
||||
console.error("Failed to fetch artefacts", e);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
@ -45,10 +47,9 @@ export default function Shop() {
|
||||
}, []);
|
||||
|
||||
const [currentPage, setCurrentPage] = useState(1);
|
||||
const [selectedArtefact, setSelectedArtefact] = useState<ExtendedArtefact | null>(null);
|
||||
const [selectedArtefact, setSelectedArtefact] = useState<SuperExtendedArtefact | null>(null);
|
||||
const [showPaymentModal, setShowPaymentModal] = useState(false);
|
||||
const [artefactToBuy, setArtefactToBuy] = useState<ExtendedArtefact | null>(null);
|
||||
const [cartCheckout, setCartCheckout] = useState(false); // true = checkout cart (not single artefact)
|
||||
const [artefactToBuy, setArtefactToBuy] = useState<SuperExtendedArtefact | null>(null);
|
||||
const [showThankYouModal, setShowThankYouModal] = useState(false);
|
||||
const [orderNumber, setOrderNumber] = useState<string | null>(null);
|
||||
|
||||
@ -73,7 +74,7 @@ export default function Shop() {
|
||||
if (currentPage > 1) setCurrentPage((prev) => prev - 1);
|
||||
};
|
||||
|
||||
function ArtefactCard({ artefact }: { artefact: ExtendedArtefact }) {
|
||||
function ArtefactCard({ artefact }: { artefact: SuperExtendedArtefact }) {
|
||||
return (
|
||||
<div
|
||||
className="flex flex-col bg-white shadow-md rounded-md overflow-hidden cursor-pointer hover:scale-105 transition-transform"
|
||||
@ -83,7 +84,7 @@ export default function Shop() {
|
||||
<div className="p-4">
|
||||
<h3 className="text-lg font-semibold">{artefact.name}</h3>
|
||||
<p className="text-neutral-500 mb-2">{artefact.location}</p>
|
||||
<p className="text-neutral-500 mb-2">{artefact.earthquakeID}</p>
|
||||
<p className="text-neutral-500 mb-2">{artefact.earthquakeCode}</p>
|
||||
<p className="text-black font-bold text-md mt-2">
|
||||
{currencyTickers[selectedCurrency]}
|
||||
{convertPrice(artefact.price, selectedCurrency)}
|
||||
@ -92,14 +93,11 @@ export default function Shop() {
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function Modal({ artefact }: { artefact: ExtendedArtefact }) {
|
||||
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 (
|
||||
<div
|
||||
className="fixed inset-0 bg-neutral-900 bg-opacity-50 flex justify-center items-center z-50"
|
||||
@ -120,35 +118,19 @@ export default function Shop() {
|
||||
</p>
|
||||
<p className="text-neutral-600 mt-2">{artefact.description}</p>
|
||||
<p className="text-neutral-500 font-bold mt-1">Location: {artefact.location}</p>
|
||||
<p className="text-neutral-500 mb-2">{artefact.earthquakeID}</p>
|
||||
<p className="text-neutral-500 mb-2">{artefact.observatory}</p>
|
||||
<p className="text-neutral-500 mb-2">{artefact.earthquakeCode}</p>
|
||||
<p className="text-neutral-500 mb-2">{artefact.type}</p>
|
||||
<p className="text-neutral-500 mb-2">{artefact.dateReleased}</p>
|
||||
<div className="flex flex-col sm:flex-row justify-end gap-4 mt-4 mr-2">
|
||||
<div className="flex justify-end gap-4 mt-4 mr-2">
|
||||
<button
|
||||
onClick={() => {
|
||||
if (!inCart) setCart((cart) => [...cart, artefact]);
|
||||
setArtefactToBuy(artefact); // Set artefact for payment modal
|
||||
setShowPaymentModal(true); // Show payment modal
|
||||
setSelectedArtefact(null); // Close this modal
|
||||
}}
|
||||
disabled={inCart}
|
||||
className={`px-6 py-2 rounded-md font-bold border
|
||||
${
|
||||
inCart
|
||||
? "bg-gray-300 text-gray-400 cursor-not-allowed"
|
||||
: "bg-green-500 hover:bg-green-600 text-white"
|
||||
}
|
||||
`}
|
||||
className="px-10 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700"
|
||||
>
|
||||
{inCart ? "In Cart" : "Add to Cart"}
|
||||
</button>
|
||||
<button
|
||||
onClick={() => {
|
||||
setArtefactToBuy(artefact);
|
||||
setShowPaymentModal(true);
|
||||
setCartCheckout(false);
|
||||
setSelectedArtefact(null);
|
||||
}}
|
||||
className="px-8 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700"
|
||||
>
|
||||
Buy Now
|
||||
Buy
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
@ -156,99 +138,15 @@ export default function Shop() {
|
||||
);
|
||||
}
|
||||
|
||||
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 (
|
||||
<div
|
||||
className="fixed inset-0 bg-neutral-900 bg-opacity-60 flex justify-center items-center z-[999]"
|
||||
onClick={handleOverlayClick}
|
||||
>
|
||||
<div className="bg-white rounded-xl shadow-2xl max-w-2xl w-full p-8">
|
||||
<div className="flex justify-between items-center mb-4">
|
||||
<h2 className="text-2xl font-bold">Your Cart</h2>
|
||||
<button onClick={() => setShowCartModal(false)} className="text-xl font-bold px-2 py-1 rounded">
|
||||
✖
|
||||
</button>
|
||||
</div>
|
||||
{cart.length === 0 ? (
|
||||
<p className="text-neutral-500">Your cart is empty.</p>
|
||||
) : (
|
||||
<>
|
||||
<ul className="mb-4">
|
||||
{cart.map((art) => (
|
||||
<li key={art.id} className="flex items-center border-b py-2">
|
||||
<div className="flex-shrink-0 mr-3">
|
||||
<Image src={art.image} alt={art.name} width={60} height={40} className="rounded" />
|
||||
</div>
|
||||
<div className="flex-grow">
|
||||
<p className="font-bold">{art.name}</p>
|
||||
<p className="text-neutral-500 text-sm">{art.location}</p>
|
||||
</div>
|
||||
<p className="font-bold mr-2">
|
||||
{currencyTickers[selectedCurrency]}
|
||||
{convertPrice(art.price, selectedCurrency)}
|
||||
</p>
|
||||
<button
|
||||
className="px-3 py-1 bg-red-400 hover:bg-red-500 text-white rounded"
|
||||
onClick={() => setCart((c) => c.filter((a) => a.id !== art.id))}
|
||||
>
|
||||
Remove
|
||||
</button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<div className="flex justify-between items-center mb-2">
|
||||
<span className="font-bold">Total:</span>
|
||||
<span className="text-lg font-bold">
|
||||
{currencyTickers[selectedCurrency]}
|
||||
{convertPrice(total, selectedCurrency)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="text-right">
|
||||
<button
|
||||
className="px-8 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700"
|
||||
onClick={() => {
|
||||
setShowCartModal(false);
|
||||
setArtefactToBuy(null);
|
||||
setShowPaymentModal(true);
|
||||
setCartCheckout(true);
|
||||
}}
|
||||
>
|
||||
Checkout
|
||||
</button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PaymentModal({
|
||||
artefact,
|
||||
onClose,
|
||||
cartItems,
|
||||
}: {
|
||||
artefact?: ExtendedArtefact;
|
||||
onClose: () => void;
|
||||
cartItems?: ExtendedArtefact[];
|
||||
}) {
|
||||
function PaymentModal({ artefact, onClose }: { artefact: SuperExtendedArtefact; onClose: () => void }) {
|
||||
const [cardNumber, setCardNumber] = useState("");
|
||||
const [expiry, setExpiry] = useState("");
|
||||
const [cvc, setCvc] = useState("");
|
||||
const [name, setName] = useState("");
|
||||
const [email, setEmail] = useState(user?.email || "");
|
||||
const [email, setEmail] = useState("");
|
||||
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("@") &&
|
||||
@ -264,13 +162,18 @@ export default function Shop() {
|
||||
function validateExpiry(exp: string) {
|
||||
return /^\d{2}\/\d{2}$/.test(exp);
|
||||
}
|
||||
|
||||
function handlePay() {
|
||||
setError("");
|
||||
const paymentEmail = user?.email || email;
|
||||
if (!validateEmail(paymentEmail)) {
|
||||
setError("Please enter a valid email");
|
||||
if (email || user?.email) {
|
||||
if (!validateEmail(email)) {
|
||||
setError("Please enter a valid email ending");
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!validateCardNumber(cardNumber)) {
|
||||
setError("Card number must be 12-19 digits.");
|
||||
return;
|
||||
@ -283,51 +186,44 @@ export default function Shop() {
|
||||
setError("CVC must be 3 or 4 digits.");
|
||||
return;
|
||||
}
|
||||
// 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
|
||||
// todo handle sending to api route
|
||||
|
||||
setHiddenArtefactIds((ids) => [...ids, artefact.id]);
|
||||
|
||||
// todo!! create receiving api route
|
||||
// todo!! handle sending to api route
|
||||
const genOrder = () => "#" + Math.random().toString(36).substring(2, 10).toUpperCase();
|
||||
setOrderNumber(genOrder());
|
||||
onClose();
|
||||
setShowThankYouModal(true);
|
||||
setCart((c) => c.filter((a) => !artefactsToBuy.map((x) => x.id).includes(a.id)));
|
||||
}
|
||||
const handleOverlayClick = (e: React.MouseEvent) => {
|
||||
if (e.target === e.currentTarget) onClose();
|
||||
};
|
||||
return (
|
||||
<div
|
||||
className="fixed inset-0 bg-neutral-900 bg-opacity-60 flex justify-center items-center z-[12000]"
|
||||
className="fixed inset-0 bg-neutral-900 bg-opacity-60 flex justify-center items-center z-10"
|
||||
onClick={handleOverlayClick}
|
||||
>
|
||||
<div className="bg-white rounded-xl shadow-2xl max-w-md w-full p-6">
|
||||
<h2 className="text-2xl font-bold mb-4">
|
||||
Checkout {artefact ? artefact.name : artefactsToBuy.length + " item(s)"}
|
||||
{!artefact && <span className="ml-1">({artefactsToBuy.map((x) => x.name).join(", ")})</span>}
|
||||
</h2>
|
||||
<h2 className="text-2xl font-bold mb-4">Buy {artefact.name}</h2>
|
||||
{/* ...Image... */}
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
handlePay();
|
||||
}}
|
||||
>
|
||||
{/* Email autofill */}
|
||||
<input
|
||||
className="w-full mb-2 px-3 py-2 border rounded"
|
||||
placeholder="Email Address"
|
||||
value={user?.email ? user.email : email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
type="email"
|
||||
required
|
||||
autoFocus
|
||||
disabled={!!user?.email}
|
||||
/>
|
||||
{user?.email && (
|
||||
<p className="text-sm text-gray-500 mb-2">
|
||||
Signed in as <span className="font-bold">{user.email}</span>
|
||||
</p>
|
||||
)}
|
||||
{!user ? (
|
||||
<input
|
||||
className="w-full mb-2 px-3 py-2 border rounded"
|
||||
placeholder="Email Address"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
type="email"
|
||||
required
|
||||
autoFocus
|
||||
/>
|
||||
) : null}
|
||||
<input
|
||||
className="w-full mb-2 px-3 py-2 border rounded"
|
||||
placeholder="Cardholder Name"
|
||||
@ -370,13 +266,6 @@ export default function Shop() {
|
||||
Remember me
|
||||
</label>
|
||||
{error && <p className="text-red-600 mb-2">{error}</p>}
|
||||
<div className="flex justify-between items-center mb-2">
|
||||
<span className="font-bold">Total:</span>
|
||||
<span className="text-lg font-bold">
|
||||
{currencyTickers[selectedCurrency]}
|
||||
{convertPrice(total, selectedCurrency)}
|
||||
</span>
|
||||
</div>
|
||||
<div className="flex justify-end gap-2 mt-2">
|
||||
<button type="button" onClick={onClose} className="px-4 py-2 bg-gray-300 text-gray-700 rounded-md mr-2">
|
||||
Cancel
|
||||
@ -421,28 +310,6 @@ export default function Shop() {
|
||||
}}
|
||||
>
|
||||
<div className="absolute inset-0 bg-black bg-opacity-0 z-0"></div>
|
||||
{/* --- Cart Button fixed at top right --- */}
|
||||
<button
|
||||
className="absolute top-6 right-6 z-[11000] bg-white border border-blue-500 shadow-lg rounded-full p-3 hover:bg-blue-100 flex flex-row items-center"
|
||||
onClick={() => setShowCartModal(true)}
|
||||
aria-label="Open your cart"
|
||||
>
|
||||
<span className="mr-2 font-bold">{cart.length || ""}</span>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
className="w-7 h-7 text-blue-600"
|
||||
fill="none"
|
||||
viewBox="0 0 24 24"
|
||||
stroke="currentColor"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M3 3h2l.4 2M7 13h10l4-8H5.4M7 13l-1.35 2.7a1 1 0 00.9 1.45h12.2M7 13l1.2-2.4M3 3l.01 0"
|
||||
/>
|
||||
</svg>
|
||||
</button>
|
||||
<div className="relative z-10 flex flex-col items-center w-full px-2 py-12">
|
||||
<h1 className="text-4xl md:text-4xl font-bold text-center text-blue-300 mb-2 tracking-tight drop-shadow-lg">
|
||||
Artefact Shop
|
||||
@ -453,7 +320,7 @@ export default function Shop() {
|
||||
</p>
|
||||
<div className="w-full max-w-7xl grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-10 p-2">
|
||||
{currentArtefacts
|
||||
.filter((x) => !hiddenArtefactIds.includes(x.id))
|
||||
.filter((x) => !hiddenArtefactIds.includes(x.id) && x.isRequired === false)
|
||||
.map((artefact) => (
|
||||
<ArtefactCard key={artefact.id} artefact={artefact} />
|
||||
))}
|
||||
@ -481,22 +348,19 @@ export default function Shop() {
|
||||
</footer>
|
||||
</div>
|
||||
{selectedArtefact && <Modal artefact={selectedArtefact} />}
|
||||
{showCartModal && <CartModal />}
|
||||
{showPaymentModal && (cartCheckout || artefactToBuy) && (
|
||||
{artefactToBuy && showPaymentModal && (
|
||||
<PaymentModal
|
||||
artefact={cartCheckout ? undefined : artefactToBuy!}
|
||||
cartItems={cartCheckout ? cart : undefined}
|
||||
artefact={artefactToBuy}
|
||||
onClose={() => {
|
||||
setShowPaymentModal(false);
|
||||
setArtefactToBuy(null);
|
||||
setCartCheckout(false);
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{showThankYouModal && orderNumber && (
|
||||
<ThankYouModal orderNumber={orderNumber} onClose={() => setShowThankYouModal(false)} />
|
||||
)}
|
||||
{!selectedArtefact && !showPaymentModal && !showThankYouModal && !showCartModal && (
|
||||
{!selectedArtefact && !showPaymentModal && !showThankYouModal && (
|
||||
<div className="relative z-50">
|
||||
<BottomFooter />
|
||||
</div>
|
||||
|
||||
@ -95,6 +95,7 @@ function LogModal({ onClose }: { onClose: () => void }) {
|
||||
}
|
||||
setIsSubmitting(true);
|
||||
try {
|
||||
// todo!! add log api route
|
||||
await new Promise((resolve) => setTimeout(resolve, 500)); // Simulated API call
|
||||
alert(`Logged ${name} to storage: ${storageLocation}`);
|
||||
onClose();
|
||||
|
||||
@ -1,248 +1,245 @@
|
||||
"use client";
|
||||
import { useState } from "react";
|
||||
import { FormEvent, useState, useRef } from "react";
|
||||
import DatePicker from "react-datepicker";
|
||||
import "react-datepicker/dist/react-datepicker.css";
|
||||
|
||||
const typeOptions = [
|
||||
{ value: "volcanic", label: "Volcanic" },
|
||||
{ value: "tectonic", label: "Tectonic" },
|
||||
{ value: "collapse", label: "Collapse" },
|
||||
{ value: "explosion", label: "Explosion" }
|
||||
{ value: "volcanic", label: "Volcanic" },
|
||||
{ value: "tectonic", label: "Tectonic" },
|
||||
{ value: "collapse", label: "Collapse" },
|
||||
{ value: "explosion", label: "Explosion" },
|
||||
];
|
||||
|
||||
export default function EarthquakeLogModal({ open, onClose, onSuccess }) {
|
||||
const [date, setDate] = useState<Date | null>(new Date());
|
||||
const [magnitude, setMagnitude] = useState("");
|
||||
const [type, setType] = useState(typeOptions[0].value);
|
||||
const [city, setCity] = useState("");
|
||||
const [country, setCountry] = useState("");
|
||||
const [latitude, setLatitude] = useState("");
|
||||
const [longitude, setLongitude] = useState("");
|
||||
const [depth, setDepth] = useState("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [successCode, setSuccessCode] = useState<string | null>(null);
|
||||
export default function EarthquakeLogModal({
|
||||
open,
|
||||
onClose,
|
||||
onSuccess,
|
||||
}: {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
onSuccess: () => void;
|
||||
}) {
|
||||
const [date, setDate] = useState<Date | null>(new Date());
|
||||
const [magnitude, setMagnitude] = useState("");
|
||||
const [type, setType] = useState(typeOptions[0].value);
|
||||
const [city, setCity] = useState("");
|
||||
const [country, setCountry] = useState("");
|
||||
const [latitude, setLatitude] = useState("");
|
||||
const [longitude, setLongitude] = useState("");
|
||||
const [depth, setDepth] = useState("");
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [successCode, setSuccessCode] = useState<string | null>(null);
|
||||
const modalRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
async function handleLatLonChange(lat: string, lon: string) {
|
||||
setLatitude(lat);
|
||||
setLongitude(lon);
|
||||
if (/^-?\d+(\.\d+)?$/.test(lat) && /^-?\d+(\.\d+)?$/.test(lon)) {
|
||||
try {
|
||||
const resp = await fetch(
|
||||
`https://nominatim.openstreetmap.org/reverse?lat=${lat}&lon=${lon}&format=json&zoom=10`
|
||||
);
|
||||
if (resp.ok) {
|
||||
const data = await resp.json();
|
||||
setCity(
|
||||
data.address.city ||
|
||||
data.address.town ||
|
||||
data.address.village ||
|
||||
data.address.hamlet ||
|
||||
data.address.county ||
|
||||
data.address.state ||
|
||||
""
|
||||
);
|
||||
setCountry(data.address.country || "");
|
||||
}
|
||||
} catch (e) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
async function handleLatLonChange(lat: string, lon: string) {
|
||||
setLatitude(lat);
|
||||
setLongitude(lon);
|
||||
if (/^-?\d+(\.\d+)?$/.test(lat) && /^-?\d+(\.\d+)?$/.test(lon)) {
|
||||
try {
|
||||
const resp = await fetch(`https://nominatim.openstreetmap.org/reverse?lat=${lat}&lon=${lon}&format=json&zoom=10`);
|
||||
if (resp.ok) {
|
||||
const data = await resp.json();
|
||||
setCity(
|
||||
data.address.city ||
|
||||
data.address.town ||
|
||||
data.address.village ||
|
||||
data.address.hamlet ||
|
||||
data.address.county ||
|
||||
data.address.state ||
|
||||
""
|
||||
);
|
||||
setCountry(data.address.country || "");
|
||||
}
|
||||
} catch (e) {
|
||||
// ignore
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async function handleSubmit(e) {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
if (!date || !magnitude || !type || !city || !country || !latitude || !longitude || !depth) {
|
||||
alert("Please complete all fields.");
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const res = await fetch("/api/earthquakes/log", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
date,
|
||||
magnitude: parseFloat(magnitude),
|
||||
type,
|
||||
location: `${city.trim()}, ${country.trim()}`,
|
||||
country: country.trim(),
|
||||
latitude: parseFloat(latitude),
|
||||
longitude: parseFloat(longitude),
|
||||
depth
|
||||
})
|
||||
});
|
||||
if (res.ok) {
|
||||
const result = await res.json();
|
||||
setSuccessCode(result.code);
|
||||
setLoading(false);
|
||||
if (onSuccess) onSuccess();
|
||||
} else {
|
||||
const err = await res.json();
|
||||
alert("Failed to log earthquake! " + (err.error || ""));
|
||||
setLoading(false);
|
||||
}
|
||||
} catch (e: any) {
|
||||
alert("Failed to log. " + e.message);
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
async function handleSubmit(e: FormEvent) {
|
||||
e.preventDefault();
|
||||
setLoading(true);
|
||||
if (!date || !magnitude || !type || !city || !country || !latitude || !longitude || !depth) {
|
||||
alert("Please complete all fields.");
|
||||
setLoading(false);
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const res = await fetch("/api/earthquakes/log", {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
date,
|
||||
magnitude: parseFloat(magnitude),
|
||||
type,
|
||||
location: `${city.trim()}, ${country.trim()}`,
|
||||
country: country.trim(),
|
||||
latitude: parseFloat(latitude),
|
||||
longitude: parseFloat(longitude),
|
||||
depth,
|
||||
}),
|
||||
});
|
||||
if (res.ok) {
|
||||
const result = await res.json();
|
||||
setSuccessCode(result.code);
|
||||
setLoading(false);
|
||||
if (onSuccess) onSuccess();
|
||||
} else {
|
||||
const err = await res.json();
|
||||
alert("Failed to log earthquake! " + (err.error || ""));
|
||||
setLoading(false);
|
||||
}
|
||||
} catch (e: any) {
|
||||
alert("Failed to log. " + e.message);
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
if (!open) return null;
|
||||
function handleOutsideClick(e: React.MouseEvent<HTMLDivElement>) {
|
||||
if (modalRef.current && !modalRef.current.contains(e.target as Node)) {
|
||||
onClose();
|
||||
}
|
||||
}
|
||||
|
||||
// Success popup overlay
|
||||
if (successCode) {
|
||||
return (
|
||||
<div className="fixed z-50 inset-0 bg-black/40 flex items-center justify-center">
|
||||
<div className="bg-white rounded-lg px-8 py-8 max-w-md w-full relative shadow-lg">
|
||||
<button
|
||||
onClick={() => {
|
||||
setSuccessCode(null);
|
||||
onClose();
|
||||
}}
|
||||
className="absolute right-4 top-4 text-xl text-gray-400 hover:text-gray-700"
|
||||
aria-label="Close"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
<div className="text-center">
|
||||
<h2 className="text-xl font-semibold mb-3">
|
||||
Thank you for logging an earthquake!
|
||||
</h2>
|
||||
<div className="mb-0">The Earthquake Identifier is</div>
|
||||
<div className="font-mono text-lg mb-4 bg-slate-100 rounded px-2 py-1 inline-block text-blue-800">{successCode}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
if (!open) return null;
|
||||
|
||||
return (
|
||||
<div className="fixed z-50 inset-0 bg-black/40 flex items-center justify-center">
|
||||
<div className="bg-white rounded-lg shadow-lg p-6 max-w-lg w-full relative">
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="absolute right-4 top-4 text-gray-500 hover:text-black text-lg"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
<h2 className="font-bold text-xl mb-4">Log Earthquake</h2>
|
||||
<form onSubmit={handleSubmit} className="space-y-3">
|
||||
<div>
|
||||
<label className="block text-sm font-medium">Date</label>
|
||||
<DatePicker
|
||||
selected={date}
|
||||
onChange={date => setDate(date)}
|
||||
className="border rounded px-3 py-2 w-full"
|
||||
dateFormat="yyyy-MM-dd"
|
||||
maxDate={new Date()}
|
||||
showMonthDropdown
|
||||
showYearDropdown
|
||||
dropdownMode="select"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium">Magnitude</label>
|
||||
<input
|
||||
type="number"
|
||||
className="border rounded px-3 py-2 w-full"
|
||||
min="0"
|
||||
max="10"
|
||||
step="0.1"
|
||||
value={magnitude}
|
||||
onChange={e => {
|
||||
const val = e.target.value;
|
||||
if (parseFloat(val) > 10) return;
|
||||
setMagnitude(val);
|
||||
}}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium">Type</label>
|
||||
<select
|
||||
className="border rounded px-3 py-2 w-full"
|
||||
value={type}
|
||||
onChange={e => setType(e.target.value)}
|
||||
required
|
||||
>
|
||||
{typeOptions.map(opt => (
|
||||
<option key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium">City/Area</label>
|
||||
<span className="block text-xs text-gray-400">
|
||||
(Use Lat/Lon then press Enter for reverse lookup)
|
||||
</span>
|
||||
<input
|
||||
type="text"
|
||||
className="border rounded px-3 py-2 w-full"
|
||||
value={city}
|
||||
onChange={e => setCity(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium">Country</label>
|
||||
<input
|
||||
type="text"
|
||||
className="border rounded px-3 py-2 w-full"
|
||||
value={country}
|
||||
onChange={e => setCountry(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="flex space-x-2">
|
||||
<div className="flex-1">
|
||||
<label className="block text-sm font-medium">Latitude</label>
|
||||
<input
|
||||
type="number"
|
||||
className="border rounded px-3 py-2 w-full"
|
||||
value={latitude}
|
||||
onChange={e => handleLatLonChange(e.target.value, longitude)}
|
||||
placeholder="e.g. 36.12"
|
||||
step="any"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<label className="block text-sm font-medium">Longitude</label>
|
||||
<input
|
||||
type="number"
|
||||
className="border rounded px-3 py-2 w-full"
|
||||
value={longitude}
|
||||
onChange={e => handleLatLonChange(latitude, e.target.value)}
|
||||
placeholder="e.g. -115.17"
|
||||
step="any"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium">Depth</label>
|
||||
<input
|
||||
type="text"
|
||||
className="border rounded px-3 py-2 w-full"
|
||||
value={depth}
|
||||
onChange={e => setDepth(e.target.value)}
|
||||
placeholder="e.g. 10 km"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<button
|
||||
type="submit"
|
||||
className="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700 w-full"
|
||||
disabled={loading}
|
||||
>
|
||||
{loading ? "Logging..." : "Log Earthquake"}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
// Success popup overlay
|
||||
if (successCode) {
|
||||
return (
|
||||
<div className="fixed z-50 inset-0 bg-black/40 flex items-center justify-center" onClick={handleOutsideClick}>
|
||||
<div className="bg-white rounded-lg px-8 py-8 max-w-md w-full relative shadow-lg" ref={modalRef}>
|
||||
<button
|
||||
onClick={() => {
|
||||
setSuccessCode(null);
|
||||
onClose();
|
||||
}}
|
||||
className="absolute right-4 top-4 text-xl text-gray-400 hover:text-gray-700"
|
||||
aria-label="Close"
|
||||
>
|
||||
×
|
||||
</button>
|
||||
<div className="text-center">
|
||||
<h2 className="text-xl font-semibold mb-3">Thank you for logging an earthquake!</h2>
|
||||
<div className="mb-0">The Earthquake Identifier is</div>
|
||||
<div className="font-mono text-lg mb-4 bg-slate-100 rounded px-2 py-1 inline-block text-blue-800">{successCode}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="fixed z-50 inset-0 bg-black/40 flex items-center justify-center" onClick={handleOutsideClick}>
|
||||
<div className="bg-white rounded-lg shadow-lg p-6 max-w-lg w-full relative" ref={modalRef}>
|
||||
<button onClick={onClose} className="absolute right-4 top-4 text-gray-500 hover:text-black text-lg">
|
||||
×
|
||||
</button>
|
||||
<h2 className="font-bold text-xl mb-4">Log Earthquake</h2>
|
||||
<form onSubmit={handleSubmit} className="space-y-3">
|
||||
<div>
|
||||
<label className="block text-sm font-medium">Date</label>
|
||||
<DatePicker
|
||||
selected={date}
|
||||
onChange={(date) => setDate(date)}
|
||||
className="border rounded px-3 py-2 w-full"
|
||||
dateFormat="yyyy-MM-dd"
|
||||
maxDate={new Date()}
|
||||
showMonthDropdown
|
||||
showYearDropdown
|
||||
dropdownMode="select"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium">Magnitude</label>
|
||||
<input
|
||||
type="number"
|
||||
className="border rounded px-3 py-2 w-full"
|
||||
min="0"
|
||||
max="10"
|
||||
step="0.1"
|
||||
value={magnitude}
|
||||
onChange={(e) => {
|
||||
const val = e.target.value;
|
||||
if (parseFloat(val) > 10) return;
|
||||
setMagnitude(val);
|
||||
}}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium">Type</label>
|
||||
<select className="border rounded px-3 py-2 w-full" value={type} onChange={(e) => setType(e.target.value)} required>
|
||||
{typeOptions.map((opt) => (
|
||||
<option key={opt.value} value={opt.value}>
|
||||
{opt.label}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium">City/Area</label>
|
||||
<span className="block text-xs text-gray-400">(Use Lat/Lon then press Enter for reverse lookup)</span>
|
||||
<input
|
||||
type="text"
|
||||
className="border rounded px-3 py-2 w-full"
|
||||
value={city}
|
||||
onChange={(e) => setCity(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium">Country</label>
|
||||
<input
|
||||
type="text"
|
||||
className="border rounded px-3 py-2 w-full"
|
||||
value={country}
|
||||
onChange={(e) => setCountry(e.target.value)}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="flex space-x-2">
|
||||
<div className="flex-1">
|
||||
<label className="block text-sm font-medium">Latitude</label>
|
||||
<input
|
||||
type="number"
|
||||
className="border rounded px-3 py-2 w-full"
|
||||
value={latitude}
|
||||
onChange={(e) => handleLatLonChange(e.target.value, longitude)}
|
||||
placeholder="e.g. 36.12"
|
||||
step="any"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<label className="block text-sm font-medium">Longitude</label>
|
||||
<input
|
||||
type="number"
|
||||
className="border rounded px-3 py-2 w-full"
|
||||
value={longitude}
|
||||
onChange={(e) => handleLatLonChange(latitude, e.target.value)}
|
||||
placeholder="e.g. -115.17"
|
||||
step="any"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium">Depth</label>
|
||||
<input
|
||||
type="text"
|
||||
className="border rounded px-3 py-2 w-full"
|
||||
value={depth}
|
||||
onChange={(e) => setDepth(e.target.value)}
|
||||
placeholder="e.g. 10 km"
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
<button type="submit" className="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700 w-full" disabled={loading}>
|
||||
{loading ? "Logging..." : "Log Earthquake"}
|
||||
</button>
|
||||
</form>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@ -3,243 +3,233 @@ import { useState, useEffect, useMemo } from "react";
|
||||
import axios from "axios";
|
||||
|
||||
export type Earthquake = {
|
||||
id: string;
|
||||
code: string;
|
||||
magnitude: number;
|
||||
location: string;
|
||||
date: string;
|
||||
longitude: number;
|
||||
latitude: number;
|
||||
id: string;
|
||||
code: string;
|
||||
magnitude: number;
|
||||
location: string;
|
||||
date: string;
|
||||
longitude: number;
|
||||
latitude: number;
|
||||
};
|
||||
|
||||
function formatDate(iso: string) {
|
||||
return new Date(iso).toLocaleDateString();
|
||||
return new Date(iso).toLocaleDateString();
|
||||
}
|
||||
|
||||
const COLUMNS = [
|
||||
{ label: "Code", key: "code", className: "font-mono font-bold" },
|
||||
{ label: "Location", key: "location" },
|
||||
{ label: "Magnitude", key: "magnitude", numeric: true },
|
||||
{ label: "Date", key: "date" },
|
||||
{ label: "Code", key: "code", className: "font-mono font-bold" },
|
||||
{ label: "Location", key: "location" },
|
||||
{ label: "Magnitude", key: "magnitude", numeric: true },
|
||||
{ label: "Date", key: "date" },
|
||||
];
|
||||
|
||||
// todo modify slightly
|
||||
|
||||
export default function EarthquakeSearchModal({
|
||||
open,
|
||||
onClose,
|
||||
onSelect,
|
||||
open,
|
||||
onClose,
|
||||
onSelect,
|
||||
}: {
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
onSelect: (eq: Earthquake) => void;
|
||||
open: boolean;
|
||||
onClose: () => void;
|
||||
onSelect: (eq: Earthquake) => void;
|
||||
}) {
|
||||
const [search, setSearch] = useState<string>("");
|
||||
const [results, setResults] = useState<Earthquake[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string>("");
|
||||
const [search, setSearch] = useState<string>("");
|
||||
const [results, setResults] = useState<Earthquake[]>([]);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string>("");
|
||||
|
||||
// Filters per column
|
||||
const [filters, setFilters] = useState<{ [k: string]: string }>({
|
||||
code: "",
|
||||
location: "",
|
||||
magnitude: "",
|
||||
date: "",
|
||||
});
|
||||
// Sort state
|
||||
const [sort, setSort] = useState<{ key: keyof Earthquake; dir: "asc" | "desc" } | null>(null);
|
||||
// Filters per column
|
||||
const [filters, setFilters] = useState<{ [k: string]: string }>({
|
||||
code: "",
|
||||
location: "",
|
||||
magnitude: "",
|
||||
date: "",
|
||||
});
|
||||
// Sort state
|
||||
const [sort, setSort] = useState<{ key: keyof Earthquake; dir: "asc" | "desc" } | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
setSearch("");
|
||||
setResults([]);
|
||||
setFilters({ code: "", location: "", magnitude: "", date: "" });
|
||||
setError("");
|
||||
setSort(null);
|
||||
}
|
||||
}, [open]);
|
||||
useEffect(() => {
|
||||
if (!open) {
|
||||
setSearch("");
|
||||
setResults([]);
|
||||
setFilters({ code: "", location: "", magnitude: "", date: "" });
|
||||
setError("");
|
||||
setSort(null);
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
const doSearch = async (q = search) => {
|
||||
setLoading(true);
|
||||
setResults([]);
|
||||
setError("");
|
||||
try {
|
||||
const resp = await axios.post("/api/earthquakes/search", { query: q });
|
||||
setResults(resp.data.earthquakes || []);
|
||||
} catch (e: any) {
|
||||
setError("Failed to search earthquakes.");
|
||||
}
|
||||
setLoading(false);
|
||||
};
|
||||
const doSearch = async (q = search) => {
|
||||
setLoading(true);
|
||||
setResults([]);
|
||||
setError("");
|
||||
try {
|
||||
const resp = await axios.post("/api/earthquakes/search", { query: q });
|
||||
setResults(resp.data.earthquakes || []);
|
||||
} catch (e: any) {
|
||||
setError("Failed to search earthquakes.");
|
||||
}
|
||||
setLoading(false);
|
||||
};
|
||||
|
||||
// Filter logic
|
||||
const filteredRows = useMemo(() => {
|
||||
return results.filter((row) =>
|
||||
(!filters.code ||
|
||||
row.code.toLowerCase().includes(filters.code.toLowerCase())) &&
|
||||
(!filters.location ||
|
||||
(row.location || "").toLowerCase().includes(filters.location.toLowerCase())) &&
|
||||
(!filters.magnitude ||
|
||||
String(row.magnitude).startsWith(filters.magnitude)) &&
|
||||
(!filters.date ||
|
||||
row.date.slice(0, 10) === filters.date)
|
||||
);
|
||||
}, [results, filters]);
|
||||
// Filter logic
|
||||
const filteredRows = useMemo(() => {
|
||||
return results.filter(
|
||||
(row) =>
|
||||
(!filters.code || row.code.toLowerCase().includes(filters.code.toLowerCase())) &&
|
||||
(!filters.location || (row.location || "").toLowerCase().includes(filters.location.toLowerCase())) &&
|
||||
(!filters.magnitude || String(row.magnitude).startsWith(filters.magnitude)) &&
|
||||
(!filters.date || row.date.slice(0, 10) === filters.date)
|
||||
);
|
||||
}, [results, filters]);
|
||||
|
||||
// Sort logic
|
||||
const sortedRows = useMemo(() => {
|
||||
if (!sort) return filteredRows;
|
||||
const sorted = [...filteredRows].sort((a, b) => {
|
||||
let valA = a[sort.key];
|
||||
let valB = b[sort.key];
|
||||
if (sort.key === "magnitude") {
|
||||
valA = Number(valA);
|
||||
valB = Number(valB);
|
||||
} else if (sort.key === "date") {
|
||||
valA = a.date;
|
||||
valB = b.date;
|
||||
} else {
|
||||
valA = String(valA || "");
|
||||
valB = String(valB || "");
|
||||
}
|
||||
if (valA < valB) return sort.dir === "asc" ? -1 : 1;
|
||||
if (valA > valB) return sort.dir === "asc" ? 1 : -1;
|
||||
return 0;
|
||||
});
|
||||
return sorted;
|
||||
}, [filteredRows, sort]);
|
||||
// Sort logic
|
||||
const sortedRows = useMemo(() => {
|
||||
if (!sort) return filteredRows;
|
||||
const sorted = [...filteredRows].sort((a, b) => {
|
||||
let valA = a[sort.key];
|
||||
let valB = b[sort.key];
|
||||
if (sort.key === "magnitude") {
|
||||
valA = Number(valA);
|
||||
valB = Number(valB);
|
||||
} else if (sort.key === "date") {
|
||||
valA = a.date;
|
||||
valB = b.date;
|
||||
} else {
|
||||
valA = String(valA || "");
|
||||
valB = String(valB || "");
|
||||
}
|
||||
if (valA < valB) return sort.dir === "asc" ? -1 : 1;
|
||||
if (valA > valB) return sort.dir === "asc" ? 1 : -1;
|
||||
return 0;
|
||||
});
|
||||
return sorted;
|
||||
}, [filteredRows, sort]);
|
||||
|
||||
if (!open) return null;
|
||||
return (
|
||||
<div className="fixed z-50 inset-0 bg-black/40 flex items-center justify-center animate-fadein">
|
||||
<div className="bg-white rounded-lg shadow-xl p-6 w-full max-w-2xl relative">
|
||||
<button
|
||||
onClick={onClose}
|
||||
className="absolute right-4 top-4 text-2xl text-gray-400 hover:text-red-500 font-bold"
|
||||
>×</button>
|
||||
<h2 className="font-bold text-xl mb-4">Search Earthquakes</h2>
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
doSearch();
|
||||
}}
|
||||
className="flex gap-2 mb-3"
|
||||
>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="e.g. Mexico, EV-7.4-Mexico-00035"
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
className="flex-grow px-3 py-2 border rounded"
|
||||
disabled={loading}
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700 min-w-[6.5rem] flex items-center justify-center"
|
||||
>
|
||||
{loading ? (
|
||||
<>
|
||||
<svg className="animate-spin h-4 w-4 mr-2" viewBox="0 0 24 24">
|
||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8z"></path>
|
||||
</svg>
|
||||
Search...
|
||||
</>
|
||||
) : (
|
||||
<>Search</>
|
||||
)}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setSearch("");
|
||||
setResults([]);
|
||||
setFilters({ code: "", location: "", magnitude: "", date: "" });
|
||||
}}
|
||||
className="bg-gray-100 text-gray-600 px-3 py-2 rounded hover:bg-gray-200"
|
||||
>
|
||||
Clear
|
||||
</button>
|
||||
</form>
|
||||
{error && (
|
||||
<div className="text-red-600 font-medium mb-2">{error}</div>
|
||||
)}
|
||||
{/* Filter Row */}
|
||||
<div className="mb-2">
|
||||
<div className="flex gap-3">
|
||||
{COLUMNS.map((col) => (
|
||||
<input
|
||||
key={col.key}
|
||||
type={col.key === "magnitude" ? "number" : col.key === "date" ? "date" : "text"}
|
||||
value={filters[col.key] || ""}
|
||||
onChange={e =>
|
||||
setFilters(f => ({ ...f, [col.key]: e.target.value }))
|
||||
}
|
||||
className="border border-neutral-200 rounded px-2 py-1 text-xs"
|
||||
style={{
|
||||
width:
|
||||
col.key === "magnitude"
|
||||
? 70
|
||||
: col.key === "date"
|
||||
? 130
|
||||
: 120,
|
||||
}}
|
||||
placeholder={`Filter ${col.label}`}
|
||||
aria-label={`Filter ${col.label}`}
|
||||
disabled={loading || results.length === 0}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
{/* Results Table */}
|
||||
<div className="border rounded shadow-inner bg-white max-h-72 overflow-y-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="bg-neutral-100 border-b">
|
||||
{COLUMNS.map((col) => (
|
||||
<th
|
||||
key={col.key}
|
||||
className={`font-semibold px-3 py-2 cursor-pointer select-none text-left`}
|
||||
onClick={() =>
|
||||
setSort(sort && sort.key === col.key
|
||||
? { key: col.key as keyof Earthquake, dir: sort.dir === "asc" ? "desc" : "asc" }
|
||||
: { key: col.key as keyof Earthquake, dir: "asc" })
|
||||
}
|
||||
>
|
||||
{col.label}
|
||||
{sort?.key === col.key &&
|
||||
(sort.dir === "asc" ? " ↑" : " ↓")}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{sortedRows.length === 0 && !loading && (
|
||||
<tr>
|
||||
<td colSpan={COLUMNS.length} className="p-3 text-center text-gray-400">
|
||||
No results found.
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
{sortedRows.map(eq => (
|
||||
<tr
|
||||
key={eq.id}
|
||||
className="hover:bg-blue-50 cursor-pointer border-b"
|
||||
onClick={() => {
|
||||
onSelect(eq);
|
||||
onClose();
|
||||
}}
|
||||
tabIndex={0}
|
||||
>
|
||||
<td className="px-3 py-2 font-mono">{eq.code}</td>
|
||||
<td className="px-3 py-2">{eq.location}</td>
|
||||
<td className="px-3 py-2 font-bold">{eq.magnitude}</td>
|
||||
<td className="px-3 py-2">{formatDate(eq.date)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
if (!open) return null;
|
||||
return (
|
||||
<div className="fixed z-50 inset-0 bg-black/40 flex items-center justify-center animate-fadein">
|
||||
<div className="bg-white rounded-lg shadow-xl p-6 w-full max-w-2xl relative">
|
||||
<button onClick={onClose} className="absolute right-4 top-4 text-2xl text-gray-400 hover:text-red-500 font-bold">
|
||||
×
|
||||
</button>
|
||||
<h2 className="font-bold text-xl mb-4">Search Earthquakes</h2>
|
||||
<form
|
||||
onSubmit={(e) => {
|
||||
e.preventDefault();
|
||||
doSearch();
|
||||
}}
|
||||
className="flex gap-2 mb-3"
|
||||
>
|
||||
<input
|
||||
type="text"
|
||||
placeholder="e.g. Mexico, EV-7.4-Mexico-00035"
|
||||
value={search}
|
||||
onChange={(e) => setSearch(e.target.value)}
|
||||
className="flex-grow px-3 py-2 border rounded"
|
||||
disabled={loading}
|
||||
/>
|
||||
<button
|
||||
type="submit"
|
||||
disabled={loading}
|
||||
className="bg-blue-600 text-white px-4 py-2 rounded hover:bg-blue-700 min-w-[6.5rem] flex items-center justify-center"
|
||||
>
|
||||
{loading ? (
|
||||
<>
|
||||
<svg className="animate-spin h-4 w-4 mr-2" viewBox="0 0 24 24">
|
||||
<circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
|
||||
<path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8v8z"></path>
|
||||
</svg>
|
||||
Search...
|
||||
</>
|
||||
) : (
|
||||
<>Search</>
|
||||
)}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => {
|
||||
setSearch("");
|
||||
setResults([]);
|
||||
setFilters({ code: "", location: "", magnitude: "", date: "" });
|
||||
}}
|
||||
className="bg-gray-100 text-gray-600 px-3 py-2 rounded hover:bg-gray-200"
|
||||
>
|
||||
Clear
|
||||
</button>
|
||||
</form>
|
||||
{error && <div className="text-red-600 font-medium mb-2">{error}</div>}
|
||||
{/* Filter Row */}
|
||||
<div className="mb-2">
|
||||
<div className="flex gap-3">
|
||||
{COLUMNS.map((col) => (
|
||||
<input
|
||||
key={col.key}
|
||||
type={col.key === "magnitude" ? "number" : col.key === "date" ? "date" : "text"}
|
||||
value={filters[col.key] || ""}
|
||||
onChange={(e) => setFilters((f) => ({ ...f, [col.key]: e.target.value }))}
|
||||
className="border border-neutral-200 rounded px-2 py-1 text-xs"
|
||||
style={{
|
||||
width: col.key === "magnitude" ? 70 : col.key === "date" ? 130 : 120,
|
||||
}}
|
||||
placeholder={`Filter ${col.label}`}
|
||||
aria-label={`Filter ${col.label}`}
|
||||
disabled={loading || results.length === 0}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
{/* Results Table */}
|
||||
<div className="border rounded shadow-inner bg-white max-h-72 overflow-y-auto">
|
||||
<table className="w-full text-sm">
|
||||
<thead>
|
||||
<tr className="bg-neutral-100 border-b">
|
||||
{COLUMNS.map((col) => (
|
||||
<th
|
||||
key={col.key}
|
||||
className={`font-semibold px-3 py-2 cursor-pointer select-none text-left`}
|
||||
onClick={() =>
|
||||
setSort(
|
||||
sort && sort.key === col.key
|
||||
? { key: col.key as keyof Earthquake, dir: sort.dir === "asc" ? "desc" : "asc" }
|
||||
: { key: col.key as keyof Earthquake, dir: "asc" }
|
||||
)
|
||||
}
|
||||
>
|
||||
{col.label}
|
||||
{sort?.key === col.key && (sort.dir === "asc" ? " ↑" : " ↓")}
|
||||
</th>
|
||||
))}
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
{sortedRows.length === 0 && !loading && (
|
||||
<tr>
|
||||
<td colSpan={COLUMNS.length} className="p-3 text-center text-gray-400">
|
||||
No results found.
|
||||
</td>
|
||||
</tr>
|
||||
)}
|
||||
{sortedRows.map((eq) => (
|
||||
<tr
|
||||
key={eq.id}
|
||||
className="hover:bg-blue-50 cursor-pointer border-b"
|
||||
onClick={() => {
|
||||
onSelect(eq);
|
||||
onClose();
|
||||
}}
|
||||
tabIndex={0}
|
||||
>
|
||||
<td className="px-3 py-2 font-mono">{eq.code}</td>
|
||||
<td className="px-3 py-2">{eq.location}</td>
|
||||
<td className="px-3 py-2 font-bold">{eq.magnitude}</td>
|
||||
<td className="px-3 py-2">{formatDate(eq.date)}</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Loading…
x
Reference in New Issue
Block a user