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
+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 (