pulling products from spring api. live data

This commit is contained in:
2025-11-30 09:24:00 -05:00
parent 2441542a90
commit d53a58e994
74 changed files with 1627 additions and 538 deletions
+171 -167
View File
@@ -1,59 +1,92 @@
"use client";
import { useMemo } from "react";
import { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { useParams } from "next/navigation";
import { CATEGORIES, PARTS } from "@/data/gunbuilderParts";
import { CATEGORIES } from "@/data/gunbuilderParts";
import type { CategoryId } from "@/types/gunbuilder";
import { getPricingHistory, getRetailerOffers } from "./data";
import { PricingHistoryGraph } from "@/components/PricingHistoryGraph";
import { RetailersList } from "@/components/RetailersList";
type GunbuilderProductFromApi = {
id: number;
uuid: string;
slug: string;
name: string;
brandName: string;
platform: string;
partRole: string;
price: number | null;
mainImageUrl: string | null;
buyUrl: string | null;
};
const API_BASE_URL =
process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://localhost:8080";
export default function PartDetailPage() {
const params = useParams();
const categoryId = params.categoryId as CategoryId;
const partId = params.partId as string;
const partId = params.partId as string; // this is the UUID we passed in the link
const [product, setProduct] = useState<GunbuilderProductFromApi | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const category = useMemo(
() => CATEGORIES.find((c) => c.id === categoryId),
[categoryId],
);
const part = useMemo(
() => PARTS.find((p) => p.id === partId && p.categoryId === categoryId),
[partId, categoryId],
);
useEffect(() => {
if (!partId) return;
// Get pricing history and retailer offers
// TODO: Replace with API calls when endpoints are ready
const pricingHistory = useMemo(
() => (part ? getPricingHistory(part.id, part.price) : []),
[part],
);
const controller = new AbortController();
const retailerOffers = useMemo(
() =>
part
? getRetailerOffers(part.id, part.price, part.affiliateUrl)
: [],
[part],
);
async function fetchProduct() {
try {
setLoading(true);
setError(null);
if (!category || !part) {
// For now, pull the full AR-15 list and find by UUID.
// We can optimize with a dedicated /api/products/gunbuilder/{uuid} later.
const url = `${API_BASE_URL}/api/products/gunbuilder?platform=AR-15`;
const res = await fetch(url, { signal: controller.signal });
if (!res.ok) {
throw new Error(`Failed to load product (${res.status})`);
}
const data: GunbuilderProductFromApi[] = await res.json();
const found = data.find((p) => p.uuid === partId) ?? null;
if (!found) {
setError("Product not found");
}
setProduct(found);
} catch (err: any) {
if (err.name === "AbortError") return;
setError(err.message ?? "Failed to load product");
} finally {
setLoading(false);
}
}
fetchProduct();
return () => controller.abort();
}, [partId]);
if (!category) {
return (
<main className="min-h-screen bg-black text-zinc-50">
<div className="mx-auto max-w-6xl px-4 py-6 lg:py-10">
<div className="text-center">
<h1 className="text-2xl font-semibold text-zinc-50 mb-4">
Product Not Found
</h1>
<Link
href="/gunbuilder"
className="text-amber-300 hover:text-amber-200 underline"
>
Return to Gunbuilder
</Link>
</div>
<h1 className="text-2xl font-semibold mb-4">Category Not Found</h1>
<Link
href="/gunbuilder"
className="text-amber-300 hover:text-amber-200 underline"
>
Return to Gunbuilder
</Link>
</div>
</main>
);
@@ -61,152 +94,123 @@ export default function PartDetailPage() {
return (
<main className="min-h-screen bg-black text-zinc-50">
<div className="mx-auto max-w-6xl px-4 py-6 lg:py-10">
{/* Header */}
<header className="mb-6">
<div className="mx-auto max-w-5xl px-4 py-6 lg:py-10">
{/* Breadcrumbs */}
<nav className="mb-4 text-xs text-zinc-500">
<Link
href="/gunbuilder"
className="hover:text-zinc-300 transition-colors"
>
Gunbuilder
</Link>
<span className="mx-1">/</span>
<Link
href={`/gunbuilder/${categoryId}`}
className="text-xs text-zinc-400 hover:text-zinc-300 mb-4 inline-block"
className="hover:text-zinc-300 transition-colors"
>
Back to {category.name}
{category.name}
</Link>
{product && (
<>
<span className="mx-1">/</span>
<span className="text-zinc-300">{product.name}</span>
</>
)}
</nav>
{loading ? (
<p className="text-sm text-zinc-500">Loading product</p>
) : error || !product ? (
<div>
<p className="text-xs font-semibold tracking-[0.2em] uppercase text-zinc-500">
Shadow Standard
</p>
<h1 className="mt-1 text-2xl md:text-3xl font-semibold tracking-tight">
{part.brand} <span className="text-amber-300">{part.name}</span>
</h1>
<p className="mt-2 text-sm text-zinc-400 max-w-xl">
{category.name} Product Details
<h1 className="text-xl font-semibold mb-2">Product Unavailable</h1>
<p className="text-sm text-zinc-500 mb-4">
{error ?? "We couldnt find this product."}
</p>
<Link
href={`/gunbuilder/${categoryId}`}
className="text-amber-300 hover:text-amber-200 underline text-sm"
>
Back to {category.name} parts
</Link>
</div>
</header>
{/* Product Details */}
<div className="grid gap-4 lg:grid-cols-[2fr,1fr]">
{/* Main Content */}
<section className="space-y-4">
{/* Product Information */}
<div className="rounded-lg border border-zinc-800 bg-zinc-950/60 p-4 md:p-6">
<div className="grid gap-6 md:grid-cols-[1fr,1fr]">
{/* Product Info */}
<div>
<div className="text-xs font-semibold tracking-[0.16em] uppercase text-zinc-400 mb-2">
Product Information
</div>
<div className="space-y-3">
<div>
<div className="text-xs text-zinc-500 uppercase tracking-wide mb-1">
Brand
</div>
<div className="text-lg font-semibold text-zinc-50">
{part.brand}
</div>
</div>
<div>
<div className="text-xs text-zinc-500 uppercase tracking-wide mb-1">
Model
</div>
<div className="text-lg font-semibold text-zinc-50">
{part.name}
</div>
</div>
<div>
<div className="text-xs text-zinc-500 uppercase tracking-wide mb-1">
Category
</div>
<div className="text-lg font-semibold text-zinc-50">
{category.name}
</div>
</div>
{part.notes && (
<div>
<div className="text-xs text-zinc-500 uppercase tracking-wide mb-1">
Details
</div>
<div className="text-sm text-zinc-300 leading-relaxed">
{part.notes}
</div>
</div>
)}
</div>
</div>
{/* Product Image */}
<div className="flex items-start justify-center">
<div className="w-full aspect-square max-w-md rounded-md border border-zinc-700 bg-zinc-900/50 flex items-center justify-center">
<div className="text-center p-8">
<svg
className="w-16 h-16 mx-auto text-zinc-600 mb-2"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
xmlns="http://www.w3.org/2000/svg"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={1.5}
d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"
/>
</svg>
<p className="text-xs text-zinc-500 uppercase tracking-wide">
Product Image
</p>
</div>
</div>
) : (
<div className="grid gap-6 md:grid-cols-[minmax(0,2fr)_minmax(0,1.3fr)] items-start">
{/* Left: image + meta */}
<div className="space-y-4">
{product.mainImageUrl && (
<div className="overflow-hidden rounded-lg border border-zinc-800 bg-zinc-950">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={product.mainImageUrl}
alt={product.name}
className="w-full object-contain max-h-80 bg-zinc-950"
/>
</div>
)}
<div className="text-xs font-semibold tracking-[0.2em] uppercase text-zinc-500">
{product.brandName}
</div>
<h1 className="text-2xl md:text-3xl font-semibold tracking-tight">
{product.name}
</h1>
<p className="text-xs text-zinc-500">
Platform: <span className="text-zinc-300">{product.platform}</span>
</p>
<p className="text-xs text-zinc-500">
Role: <span className="text-zinc-300">{product.partRole}</span>
</p>
</div>
{/* Retailers List */}
{retailerOffers.length > 0 && (
<div className="rounded-lg border border-zinc-800 bg-zinc-950/60 p-4 md:p-6">
<RetailersList retailers={retailerOffers} />
{/* Right: pricing + actions */}
<aside className="rounded-lg border border-zinc-800 bg-zinc-950/70 p-4 space-y-4">
<div>
<p className="text-xs uppercase tracking-[0.2em] text-zinc-500 mb-1">
Price
</p>
<p className="text-2xl font-semibold text-amber-300">
{product.price && product.price > 0
? `$${product.price.toFixed(2)}`
: "—"}
</p>
{!product.price && (
<p className="mt-1 text-xs text-zinc-500">
Pricing not available yet. Live pricing will appear once
offers are imported.
</p>
)}
</div>
)}
</section>
{/* Sidebar */}
<aside className="rounded-lg border border-zinc-800 bg-zinc-950/80 p-4 md:p-6 flex flex-col">
<div className="mb-4">
<div className="text-xs text-zinc-400 mb-2">Price</div>
<div className="text-3xl font-semibold text-amber-300">
${part.price.toFixed(2)}
<div className="space-y-2">
<Link
href={`/gunbuilder?select=${categoryId}:${product.uuid}`}
className="block w-full rounded-md bg-amber-400 text-black text-sm font-semibold text-center py-2.5 hover:bg-amber-300 transition-colors"
>
Add to Build
</Link>
{product.buyUrl ? (
<a
href={product.buyUrl}
target="_blank"
rel="noreferrer"
className="block w-full rounded-md border border-zinc-700 bg-zinc-900 text-xs font-medium text-zinc-200 text-center py-2 hover:bg-zinc-800 transition-colors"
>
View on Merchant Site
</a>
) : (
<button
type="button"
disabled
className="block w-full rounded-md border border-zinc-800 bg-zinc-900/60 text-xs font-medium text-zinc-500 text-center py-2 cursor-not-allowed"
>
External link coming soon
</button>
)}
</div>
</div>
{/* Pricing History */}
{pricingHistory.length > 0 && (
<div className="mb-6">
<PricingHistoryGraph
data={pricingHistory}
currentPrice={part.price}
/>
</div>
)}
<div className="mt-auto space-y-3">
<Link
href={`/gunbuilder?select=${categoryId}:${part.id}`}
className="block w-full rounded-md border border-amber-400/60 bg-amber-400/10 px-4 py-3 text-sm font-medium text-amber-200 hover:bg-amber-400/15 text-center transition-colors"
>
Add to Build
</Link>
<a
href={part.affiliateUrl}
target="_blank"
rel="noopener noreferrer"
className="block w-full rounded-md border border-zinc-700 bg-zinc-900/50 px-4 py-3 text-sm font-medium text-zinc-300 hover:bg-zinc-800 hover:border-zinc-600 text-center transition-colors"
>
View Retailer
</a>
</div>
</aside>
</div>
</aside>
</div>
)}
</div>
</main>
);
}
}
+106 -15
View File
@@ -1,27 +1,109 @@
"use client";
import { useMemo, useState } from "react";
import { useEffect, useMemo, useState } from "react";
import Link from "next/link";
import { useParams } from "next/navigation";
import { CATEGORIES, PARTS } from "@/data/gunbuilderParts";
import type { CategoryId } from "@/types/gunbuilder";
import { CATEGORIES } from "@/data/gunbuilderParts";
import type { CategoryId, Part } from "@/types/gunbuilder";
type ViewMode = "card" | "list";
type GunbuilderProductFromApi = {
id: number;
uuid: string;
slug: string;
name: string;
brandName: string;
platform: string;
partRole: string;
price: number | null;
mainImageUrl: string | null;
buyUrl: string | null;
};
const API_BASE_URL =
process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://localhost:8080";
/**
* Map from category id -> Ballistic partRole(s)
* Keep this in sync with whatever youre using on the main /gunbuilder page.
*/
const CATEGORY_TO_PART_ROLES: Record<CategoryId, string[]> = {
upper: ["upper-receiver"],
barrel: ["barrel"],
handguard: ["handguard"],
chargingHandle: ["charging-handle"],
buffer: ["buffer-kit"],
lowerParts: ["lower-parts-kit"],
sights: ["sight"],
};
export default function CategoryPage() {
const params = useParams();
const categoryId = params.categoryId as CategoryId;
const [viewMode, setViewMode] = useState<ViewMode>("list");
const [parts, setParts] = useState<Part[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const category = useMemo(
() => CATEGORIES.find((c) => c.id === categoryId),
[categoryId],
);
const parts = useMemo(
() => PARTS.filter((p) => p.categoryId === categoryId),
[categoryId],
);
useEffect(() => {
if (!categoryId) return;
const controller = new AbortController();
async function fetchCategoryParts() {
try {
setLoading(true);
setError(null);
const roles = CATEGORY_TO_PART_ROLES[categoryId] ?? [];
const search = new URLSearchParams();
search.set("platform", "AR-15");
roles.forEach((r) => search.append("partRoles", r));
const url = `${API_BASE_URL}/api/products/gunbuilder${
roles.length ? `?${search.toString()}` : ""
}`;
const res = await fetch(url, { signal: controller.signal });
if (!res.ok) {
throw new Error(`Failed to load products (${res.status})`);
}
const data: GunbuilderProductFromApi[] = await res.json();
const normalized: Part[] = data.map((p) => ({
id: p.uuid,
categoryId,
name: p.name,
brand: p.brandName,
price: p.price ?? 0,
// these fields exist in the Part type even if youre not using them yet
imageUrl: p.mainImageUrl ?? undefined,
url: p.buyUrl ?? undefined,
notes: undefined,
}));
setParts(normalized);
} catch (err: any) {
if (err.name === "AbortError") return;
setError(err.message ?? "Failed to load products");
} finally {
setLoading(false);
}
}
fetchCategoryParts();
return () => controller.abort();
}, [categoryId]);
if (!category) {
return (
@@ -63,11 +145,11 @@ export default function CategoryPage() {
{category.name} <span className="text-amber-300">Parts</span>
</h1>
<p className="mt-2 text-sm text-zinc-400 max-w-xl">
Browse all available {category.name.toLowerCase()} options for your
build.
Browse all available {category.name.toLowerCase()} options for
your build, pulled live from your Ballistic backend.
</p>
</div>
{parts.length > 0 && (
{!loading && !error && parts.length > 0 && (
<div className="flex gap-2 border border-zinc-800 rounded-md p-1 bg-zinc-950/60">
<button
type="button"
@@ -100,7 +182,15 @@ export default function CategoryPage() {
{/* Parts Grid/List */}
<section className="rounded-lg border border-zinc-800 bg-zinc-950/60 p-3 md:p-4">
{parts.length === 0 ? (
{loading ? (
<p className="text-sm text-zinc-500 text-center py-8">
Loading {category.name.toLowerCase()}
</p>
) : error ? (
<p className="text-sm text-red-400 text-center py-8">
{error} check that the Ballistic API is running.
</p>
) : parts.length === 0 ? (
<p className="text-sm text-zinc-500 text-center py-8">
No parts available for this category yet.
</p>
@@ -118,7 +208,8 @@ export default function CategoryPage() {
<div className="flex justify-between items-center gap-2 mb-3">
<div className="flex-1">
<div className="text-sm font-semibold text-zinc-50">
{part.brand} <span className="font-normal"> {part.name}</span>
{part.brand}{" "}
<span className="font-normal"> {part.name}</span>
</div>
{part.notes && (
<p className="mt-1 text-xs text-zinc-400 line-clamp-2">
@@ -160,7 +251,8 @@ export default function CategoryPage() {
className="block"
>
<div className="text-sm font-semibold text-zinc-50">
{part.brand} <span className="font-normal"> {part.name}</span>
{part.brand}{" "}
<span className="font-normal"> {part.name}</span>
</div>
{part.notes && (
<p className="mt-1 text-xs text-zinc-400 line-clamp-1">
@@ -195,5 +287,4 @@ export default function CategoryPage() {
</div>
</main>
);
}
}
+122 -26
View File
@@ -3,10 +3,38 @@
import { useMemo, useState, useEffect } from "react";
import Link from "next/link";
import { useSearchParams, useRouter } from "next/navigation";
import { CATEGORIES, PARTS } from "@/data/gunbuilderParts";
import { CATEGORIES } from "@/data/gunbuilderParts";
import type { CategoryId, Part } from "@/types/gunbuilder";
import { CategoryColumn } from "@/components/CategoryColumn";
type GunbuilderProductFromApi = {
id: number;
uuid: string;
slug: string;
name: string;
brandName: string;
platform: string;
partRole: string;
price: number | null;
mainImageUrl: string | null;
buyUrl: string | null;
};
const API_BASE_URL =
process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://localhost:8080";
// Map backend partRole to your existing CategoryId values.
// Make sure these string values match the `id` fields in CATEGORIES.
const PART_ROLE_TO_CATEGORY: Record<string, CategoryId> = {
"upper-receiver": "upper" as CategoryId,
barrel: "barrel" as CategoryId,
handguard: "handguard" as CategoryId,
"charging-handle": "chargingHandle" as CategoryId,
"buffer-kit": "buffer" as CategoryId,
"lower-parts-kit": "lowerParts" as CategoryId,
sight: "sights" as CategoryId,
};
type BuildState = Partial<Record<CategoryId, string>>; // categoryId -> partId
const STORAGE_KEY = "gunbuilder-build-state";
@@ -14,6 +42,9 @@ const STORAGE_KEY = "gunbuilder-build-state";
export default function GunbuilderPage() {
const searchParams = useSearchParams();
const router = useRouter();
const [parts, setParts] = useState<Part[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [build, setBuild] = useState<BuildState>(() => {
// Initialize from localStorage if available
if (typeof window !== "undefined") {
@@ -29,6 +60,60 @@ export default function GunbuilderPage() {
return {};
});
useEffect(() => {
const controller = new AbortController();
async function fetchProducts() {
try {
setLoading(true);
setError(null);
const res = await fetch(
`${API_BASE_URL}/api/products/gunbuilder?platform=AR-15`,
{ signal: controller.signal },
);
if (!res.ok) {
throw new Error(`Failed to load products (${res.status})`);
}
const data: GunbuilderProductFromApi[] = await res.json();
const normalized: Part[] = data
.map((p) => {
const categoryId = PART_ROLE_TO_CATEGORY[p.partRole];
if (!categoryId) {
// Skip any parts we don't know how to map yet
return null;
}
return {
// Use the backend UUID as the stable id for the UI
id: p.uuid,
categoryId,
name: p.name,
brand: p.brandName,
price: p.price ?? 0,
imageUrl: p.mainImageUrl ?? undefined,
url: p.buyUrl ?? undefined,
} as Part;
})
.filter(Boolean) as Part[];
setParts(normalized);
} catch (err: any) {
if (err.name === "AbortError") return;
setError(err.message ?? "Failed to load products");
} finally {
setLoading(false);
}
}
fetchProducts();
return () => controller.abort();
}, []);
// Handle URL query parameter for part selection
useEffect(() => {
const selectParam = searchParams.get("select");
@@ -60,20 +145,20 @@ export default function GunbuilderPage() {
const partsByCategory: Record<CategoryId, Part[]> = useMemo(() => {
const grouped = {} as Record<CategoryId, Part[]>;
for (const category of CATEGORIES) {
grouped[category.id] = PARTS.filter(
grouped[category.id] = parts.filter(
(p) => p.categoryId === category.id,
);
}
return grouped;
}, []);
}, [parts]);
const selectedParts: Part[] = useMemo(() => {
return Object.entries(build)
.map(([categoryId, partId]) =>
PARTS.find((p) => p.id === partId && p.categoryId === categoryId),
parts.find((p) => p.id === partId && p.categoryId === categoryId),
)
.filter(Boolean) as Part[];
}, [build]);
}, [build, parts]);
const totalPrice = useMemo(
() => selectedParts.reduce((sum, p) => sum + p.price, 0),
@@ -100,9 +185,9 @@ export default function GunbuilderPage() {
Gunbuilder <span className="text-amber-300">Prototype</span>
</h1>
<p className="mt-2 text-sm text-zinc-400 max-w-xl">
Choose one part per category to assemble an AR-15 build. Prices
and links are mock data for nowbut the flow is close to what
the real tool will be.
Choose one part per category to assemble an AR-15 build. Parts are
loaded from the live merchant feed (Aero Precision for now), using
your Ballistic backend API.
</p>
</div>
@@ -121,23 +206,34 @@ export default function GunbuilderPage() {
<div className="grid gap-4 lg:grid-cols-[3fr,1.25fr]">
{/* Categories/parts */}
<section className="rounded-lg border border-zinc-800 bg-zinc-950/60 p-3 md:p-4">
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
{CATEGORIES.map((category) => (
<div
key={category.id}
className="border border-zinc-800 rounded-md p-2 md:p-3 bg-zinc-950/60"
>
<CategoryColumn
category={category}
parts={partsByCategory[category.id]}
selectedPartId={build[category.id]}
onSelectPart={(partId) =>
handleSelectPart(category.id, partId)
}
/>
</div>
))}
</div>
{loading && (
<p className="text-sm text-zinc-500">Loading parts from backend</p>
)}
{error && !loading && (
<p className="text-sm text-red-400">
{error} check that the Ballistic API is running and CORS is
configured.
</p>
)}
{!loading && !error && (
<div className="grid gap-4 md:grid-cols-2 lg:grid-cols-3">
{CATEGORIES.map((category) => (
<div
key={category.id}
className="border border-zinc-800 rounded-md p-2 md:p-3 bg-zinc-950/60"
>
<CategoryColumn
category={category}
parts={partsByCategory[category.id]}
selectedPartId={build[category.id]}
onSelectPart={(partId) =>
handleSelectPart(category.id, partId)
}
/>
</div>
))}
</div>
)}
</section>
{/* Build Summary */}
@@ -156,7 +252,7 @@ export default function GunbuilderPage() {
<ul className="space-y-2">
{CATEGORIES.map((cat) => {
const selectedPartId = build[cat.id];
const part = PARTS.find(
const part = parts.find(
(p) => p.id === selectedPartId && p.categoryId === cat.id,
);
return (