full app is using live data now,
This commit is contained in:
@@ -1,6 +1,11 @@
|
||||
// app/gunbuilder/[categoryId]/[partId]/data.ts
|
||||
|
||||
// Simulated data functions - Replace these with API calls when ready
|
||||
// Example: export async function getPricingHistory(partId: string) { ... }
|
||||
|
||||
const API_BASE_URL =
|
||||
process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://localhost:8080";
|
||||
|
||||
export interface PriceHistoryPoint {
|
||||
date: string; // ISO date string
|
||||
price: number;
|
||||
@@ -19,6 +24,8 @@ export interface RetailerOffer {
|
||||
/**
|
||||
* Get pricing history for a part
|
||||
* TODO: Replace with API call: GET /api/parts/{partId}/pricing-history
|
||||
*
|
||||
* For now, we keep this simulated.
|
||||
*/
|
||||
export function getPricingHistory(
|
||||
partId: string,
|
||||
@@ -48,40 +55,62 @@ export function getPricingHistory(
|
||||
|
||||
/**
|
||||
* Get retailer offers for a part
|
||||
* TODO: Replace with API call: GET /api/parts/{partId}/retailers
|
||||
* Real implementation using Ballistic backend:
|
||||
* GET /api/products/{productId}/offers
|
||||
*/
|
||||
export function getRetailerOffers(
|
||||
partId: string,
|
||||
basePrice: number,
|
||||
baseAffiliateUrl: string,
|
||||
): RetailerOffer[] {
|
||||
const retailers = [
|
||||
"Primary Arms",
|
||||
"Brownells",
|
||||
"Optics Planet",
|
||||
"MidwayUSA",
|
||||
"Palmetto State Armory",
|
||||
];
|
||||
export async function getRetailerOffers(
|
||||
productId: string,
|
||||
): Promise<RetailerOffer[]> {
|
||||
const res = await fetch(
|
||||
`${API_BASE_URL}/api/products/${productId}/offers`,
|
||||
{
|
||||
// This will be called from the client detail page,
|
||||
// so we *don't* use cache here.
|
||||
cache: "no-store",
|
||||
},
|
||||
);
|
||||
|
||||
return retailers.map((retailer, index) => {
|
||||
// Simulate price variations between retailers
|
||||
const priceVariation = (Math.random() - 0.4) * 0.2; // -8% to +12%
|
||||
const price = basePrice * (1 + priceVariation);
|
||||
const hasSale = Math.random() > 0.6; // 40% chance of sale
|
||||
const originalPrice = hasSale ? price * 1.15 : undefined;
|
||||
const inStock = Math.random() > 0.2; // 80% chance in stock
|
||||
if (!res.ok) {
|
||||
throw new Error(
|
||||
`Failed to load retailer offers (${res.status}) for product ${productId}`,
|
||||
);
|
||||
}
|
||||
|
||||
return {
|
||||
id: `retailer-${index}`,
|
||||
retailerName: retailer,
|
||||
price: Math.round(price * 100) / 100,
|
||||
originalPrice: originalPrice
|
||||
? Math.round(originalPrice * 100) / 100
|
||||
: undefined,
|
||||
inStock,
|
||||
affiliateUrl: baseAffiliateUrl.replace("example.com", `${retailer.toLowerCase().replace(/\s+/g, "")}.com`),
|
||||
lastUpdated: new Date().toISOString(),
|
||||
};
|
||||
}).sort((a, b) => a.price - b.price); // Sort by price ascending
|
||||
}
|
||||
// Expected backend payload (example):
|
||||
// [
|
||||
// {
|
||||
// "id": "uuid-or-int",
|
||||
// "merchantName": "Aero Precision",
|
||||
// "price": 189.99,
|
||||
// "originalPrice": 210.0,
|
||||
// "inStock": true,
|
||||
// "buyUrl": "https://classic.avantlink.com/click.php?...",
|
||||
// "lastUpdated": "2025-11-30T15:22:00Z"
|
||||
// },
|
||||
// ...
|
||||
// ]
|
||||
const data: Array<{
|
||||
id: string | number;
|
||||
merchantName: string;
|
||||
price: number;
|
||||
originalPrice?: number | null;
|
||||
inStock: boolean;
|
||||
buyUrl: string;
|
||||
lastUpdated: string;
|
||||
}> = await res.json();
|
||||
|
||||
const offers: RetailerOffer[] = data
|
||||
.map((o) => ({
|
||||
id: String(o.id),
|
||||
retailerName: o.merchantName,
|
||||
price: o.price,
|
||||
originalPrice: o.originalPrice ?? undefined,
|
||||
inStock: o.inStock,
|
||||
affiliateUrl: o.buyUrl,
|
||||
lastUpdated: o.lastUpdated,
|
||||
}))
|
||||
// Sort by lowest price first
|
||||
.sort((a, b) => a.price - b.price);
|
||||
|
||||
return offers;
|
||||
}
|
||||
@@ -5,13 +5,15 @@ import Link from "next/link";
|
||||
import { useParams } from "next/navigation";
|
||||
import { CATEGORIES } from "@/data/gunbuilderParts";
|
||||
import type { CategoryId } from "@/types/gunbuilder";
|
||||
import {
|
||||
getRetailerOffers,
|
||||
type RetailerOffer,
|
||||
} from "./data";
|
||||
|
||||
type GunbuilderProductFromApi = {
|
||||
id: number;
|
||||
uuid: string;
|
||||
slug: string;
|
||||
id: string; // backend UUID string
|
||||
name: string;
|
||||
brandName: string;
|
||||
brand: string;
|
||||
platform: string;
|
||||
partRole: string;
|
||||
price: number | null;
|
||||
@@ -31,11 +33,16 @@ export default function PartDetailPage() {
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const [offers, setOffers] = useState<RetailerOffer[]>([]);
|
||||
const [offersLoading, setOffersLoading] = useState(true);
|
||||
const [offersError, setOffersError] = useState<string | null>(null);
|
||||
|
||||
const category = useMemo(
|
||||
() => CATEGORIES.find((c) => c.id === categoryId),
|
||||
[categoryId],
|
||||
);
|
||||
|
||||
// 1) Load product (same as before)
|
||||
useEffect(() => {
|
||||
if (!partId) return;
|
||||
|
||||
@@ -47,7 +54,7 @@ export default function PartDetailPage() {
|
||||
setError(null);
|
||||
|
||||
// For now, pull the full AR-15 list and find by UUID.
|
||||
// We can optimize with a dedicated /api/products/gunbuilder/{uuid} later.
|
||||
// We can optimize with a dedicated /api/products/{uuid} later.
|
||||
const url = `${API_BASE_URL}/api/products/gunbuilder?platform=AR-15`;
|
||||
const res = await fetch(url, { signal: controller.signal });
|
||||
|
||||
@@ -56,7 +63,7 @@ export default function PartDetailPage() {
|
||||
}
|
||||
|
||||
const data: GunbuilderProductFromApi[] = await res.json();
|
||||
const found = data.find((p) => p.uuid === partId) ?? null;
|
||||
const found = data.find((p) => p.id === partId) ?? null;
|
||||
|
||||
if (!found) {
|
||||
setError("Product not found");
|
||||
@@ -76,6 +83,48 @@ export default function PartDetailPage() {
|
||||
return () => controller.abort();
|
||||
}, [partId]);
|
||||
|
||||
// 2) Load offers for this product from Ballistic backend
|
||||
useEffect(() => {
|
||||
if (!partId) return;
|
||||
|
||||
let cancelled = false;
|
||||
|
||||
async function fetchOffers() {
|
||||
try {
|
||||
setOffersLoading(true);
|
||||
setOffersError(null);
|
||||
|
||||
const data = await getRetailerOffers(partId);
|
||||
|
||||
if (!cancelled) {
|
||||
setOffers(data);
|
||||
}
|
||||
} catch (err: any) {
|
||||
if (!cancelled) {
|
||||
setOffersError(err.message ?? "Failed to load retailer offers");
|
||||
}
|
||||
} finally {
|
||||
if (!cancelled) {
|
||||
setOffersLoading(false);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fetchOffers();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [partId]);
|
||||
|
||||
// Best price: prefer live offers, fall back to summary product.price
|
||||
const bestPrice = useMemo(() => {
|
||||
if (offers.length > 0) {
|
||||
return offers[0].price;
|
||||
}
|
||||
return product?.price ?? null;
|
||||
}, [offers, product]);
|
||||
|
||||
if (!category) {
|
||||
return (
|
||||
<main className="min-h-screen bg-black text-zinc-50">
|
||||
@@ -148,13 +197,14 @@ export default function PartDetailPage() {
|
||||
</div>
|
||||
)}
|
||||
<div className="text-xs font-semibold tracking-[0.2em] uppercase text-zinc-500">
|
||||
{product.brandName}
|
||||
{product.brand}
|
||||
</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>
|
||||
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>
|
||||
@@ -168,11 +218,11 @@ export default function PartDetailPage() {
|
||||
Price
|
||||
</p>
|
||||
<p className="text-2xl font-semibold text-amber-300">
|
||||
{product.price && product.price > 0
|
||||
? `$${product.price.toFixed(2)}`
|
||||
{bestPrice && bestPrice > 0
|
||||
? `$${bestPrice.toFixed(2)}`
|
||||
: "—"}
|
||||
</p>
|
||||
{!product.price && (
|
||||
{!bestPrice && (
|
||||
<p className="mt-1 text-xs text-zinc-500">
|
||||
Pricing not available yet. Live pricing will appear once
|
||||
offers are imported.
|
||||
@@ -180,9 +230,41 @@ export default function PartDetailPage() {
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Offers list */}
|
||||
<div className="space-y-2">
|
||||
{offersLoading && (
|
||||
<p className="text-xs text-zinc-500">Loading offers…</p>
|
||||
)}
|
||||
{offersError && (
|
||||
<p className="text-xs text-red-400">
|
||||
{offersError}
|
||||
</p>
|
||||
)}
|
||||
{!offersLoading && !offersError && offers.length > 0 && (
|
||||
<div className="space-y-1">
|
||||
{offers.map((offer) => (
|
||||
<a
|
||||
key={offer.id}
|
||||
href={offer.affiliateUrl}
|
||||
target="_blank"
|
||||
rel="noreferrer"
|
||||
className="flex items-center justify-between rounded-md border border-zinc-700 bg-zinc-900 px-3 py-1.5 text-xs hover:bg-zinc-800 transition-colors"
|
||||
>
|
||||
<span className="text-zinc-200">
|
||||
{offer.retailerName}
|
||||
</span>
|
||||
<span className="font-semibold text-amber-300">
|
||||
${offer.price.toFixed(2)}
|
||||
</span>
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<Link
|
||||
href={`/gunbuilder?select=${categoryId}:${product.uuid}`}
|
||||
href={`/gunbuilder?select=${categoryId}:${product.id}`}
|
||||
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
|
||||
|
||||
@@ -9,11 +9,9 @@ import type { CategoryId, Part } from "@/types/gunbuilder";
|
||||
type ViewMode = "card" | "list";
|
||||
|
||||
type GunbuilderProductFromApi = {
|
||||
id: number;
|
||||
uuid: string;
|
||||
slug: string;
|
||||
id: string; // backend UUID as string
|
||||
name: string;
|
||||
brandName: string;
|
||||
brand: string; // backend brand field
|
||||
platform: string;
|
||||
partRole: string;
|
||||
price: number | null;
|
||||
@@ -79,13 +77,13 @@ export default function CategoryPage() {
|
||||
|
||||
const data: GunbuilderProductFromApi[] = await res.json();
|
||||
|
||||
// 🔑 Normalize into your Part type using *id* and *brand*
|
||||
const normalized: Part[] = data.map((p) => ({
|
||||
id: p.uuid,
|
||||
id: p.id, // ✅ backend id (UUID string)
|
||||
categoryId,
|
||||
name: p.name,
|
||||
brand: p.brandName,
|
||||
brand: p.brand, // ✅ backend brand
|
||||
price: p.price ?? 0,
|
||||
// these fields exist in the Part type even if you’re not using them yet
|
||||
imageUrl: p.mainImageUrl ?? undefined,
|
||||
url: p.buyUrl ?? undefined,
|
||||
notes: undefined,
|
||||
|
||||
+128
-37
@@ -3,13 +3,37 @@
|
||||
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";
|
||||
|
||||
type BuildState = Partial<Record<CategoryId, string>>; // categoryId -> partId
|
||||
|
||||
const STORAGE_KEY = "gunbuilder-build-state";
|
||||
|
||||
const API_BASE_URL =
|
||||
process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://localhost:8080";
|
||||
|
||||
type GunbuilderProductFromApi = {
|
||||
id: string; // backend UUID string
|
||||
name: string;
|
||||
brand: string;
|
||||
platform: string;
|
||||
partRole: string;
|
||||
price: number | null;
|
||||
mainImageUrl: string | null;
|
||||
buyUrl: string | null;
|
||||
};
|
||||
|
||||
// Map backend partRole -> CategoryId (same as /gunbuilder page)
|
||||
const PART_ROLE_TO_CATEGORY: Record<string, CategoryId> = {
|
||||
"upper-receiver": "upper",
|
||||
barrel: "barrel",
|
||||
handguard: "handguard",
|
||||
"charging-handle": "chargingHandle",
|
||||
"buffer-kit": "buffer",
|
||||
"lower-parts-kit": "lowerParts",
|
||||
sight: "sights",
|
||||
};
|
||||
|
||||
// Encode build state to URL-friendly string
|
||||
function encodeBuildState(build: BuildState): string {
|
||||
const entries = Object.entries(build)
|
||||
@@ -39,10 +63,15 @@ function decodeBuildState(encoded: string): BuildState {
|
||||
export default function BuildDetailsPage() {
|
||||
const searchParams = useSearchParams();
|
||||
const router = useRouter();
|
||||
|
||||
const [build, setBuild] = useState<BuildState>({});
|
||||
const [shareUrl, setShareUrl] = useState<string>("");
|
||||
const [copied, setCopied] = useState(false);
|
||||
|
||||
const [parts, setParts] = useState<Part[]>([]);
|
||||
const [loadingParts, setLoadingParts] = useState(true);
|
||||
const [partsError, setPartsError] = useState<string | null>(null);
|
||||
|
||||
// Load build from URL params or localStorage
|
||||
useEffect(() => {
|
||||
const buildParam = searchParams.get("build");
|
||||
@@ -65,6 +94,58 @@ export default function BuildDetailsPage() {
|
||||
}
|
||||
}, [searchParams]);
|
||||
|
||||
// Fetch live parts from backend (same source as /gunbuilder)
|
||||
useEffect(() => {
|
||||
const controller = new AbortController();
|
||||
|
||||
async function fetchProducts() {
|
||||
try {
|
||||
setLoadingParts(true);
|
||||
setPartsError(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): Part | null => {
|
||||
const categoryId = PART_ROLE_TO_CATEGORY[p.partRole];
|
||||
if (!categoryId) return null;
|
||||
|
||||
return {
|
||||
id: p.id, // already a string UUID
|
||||
categoryId,
|
||||
name: p.name,
|
||||
brand: p.brand,
|
||||
price: p.price ?? 0,
|
||||
imageUrl: p.mainImageUrl ?? undefined,
|
||||
url: p.buyUrl ?? undefined,
|
||||
notes: undefined,
|
||||
};
|
||||
})
|
||||
.filter(Boolean) as Part[];
|
||||
|
||||
setParts(normalized);
|
||||
} catch (err: any) {
|
||||
if (err.name === "AbortError") return;
|
||||
setPartsError(err.message ?? "Failed to load products");
|
||||
} finally {
|
||||
setLoadingParts(false);
|
||||
}
|
||||
}
|
||||
|
||||
fetchProducts();
|
||||
|
||||
return () => controller.abort();
|
||||
}, []);
|
||||
|
||||
// Generate shareable URL
|
||||
useEffect(() => {
|
||||
if (typeof window !== "undefined" && Object.keys(build).length > 0) {
|
||||
@@ -75,12 +156,16 @@ export default function BuildDetailsPage() {
|
||||
}, [build]);
|
||||
|
||||
const selectedParts: Part[] = useMemo(() => {
|
||||
if (parts.length === 0) return [];
|
||||
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 as CategoryId),
|
||||
),
|
||||
)
|
||||
.filter(Boolean) as Part[];
|
||||
}, [build]);
|
||||
}, [build, parts]);
|
||||
|
||||
const totalPrice = useMemo(
|
||||
() => selectedParts.reduce((sum, p) => sum + p.price, 0),
|
||||
@@ -107,8 +192,7 @@ export default function BuildDetailsPage() {
|
||||
text: `Check out my AR-15 build: $${totalPrice.toFixed(2)}`,
|
||||
url: shareUrl,
|
||||
});
|
||||
} catch (err) {
|
||||
// User cancelled or share failed, fall back to copy
|
||||
} catch {
|
||||
handleCopyLink();
|
||||
}
|
||||
} else {
|
||||
@@ -116,7 +200,7 @@ export default function BuildDetailsPage() {
|
||||
}
|
||||
};
|
||||
|
||||
if (selectedParts.length === 0) {
|
||||
if (!loadingParts && selectedParts.length === 0) {
|
||||
return (
|
||||
<main className="min-h-screen bg-black text-zinc-50">
|
||||
<div className="mx-auto max-w-4xl px-4 py-6 lg:py-10">
|
||||
@@ -225,11 +309,22 @@ export default function BuildDetailsPage() {
|
||||
Selected Parts
|
||||
</h2>
|
||||
|
||||
{loadingParts && (
|
||||
<p className="text-sm text-zinc-500 mb-4">Loading parts…</p>
|
||||
)}
|
||||
{partsError && (
|
||||
<p className="text-sm text-red-400 mb-4">
|
||||
{partsError} — check the Ballistic API.
|
||||
</p>
|
||||
)}
|
||||
|
||||
<div className="space-y-4">
|
||||
{CATEGORIES.map((category) => {
|
||||
const selectedPartId = build[category.id];
|
||||
const part = PARTS.find(
|
||||
(p) => p.id === selectedPartId && p.categoryId === category.id,
|
||||
const part = parts.find(
|
||||
(p) =>
|
||||
p.id === selectedPartId &&
|
||||
p.categoryId === (category.id as CategoryId),
|
||||
);
|
||||
|
||||
return (
|
||||
@@ -248,33 +343,30 @@ export default function BuildDetailsPage() {
|
||||
<span className="text-zinc-400">{part.brand}</span>{" "}
|
||||
{part.name}
|
||||
</div>
|
||||
{part.notes && (
|
||||
<p className="text-sm text-zinc-400 mt-1">
|
||||
{part.notes}
|
||||
</p>
|
||||
)}
|
||||
<div className="mt-3 flex gap-2">
|
||||
<a
|
||||
href={part.affiliateUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-2 rounded-md border border-amber-400/60 bg-amber-400/10 px-4 py-2 text-sm font-medium text-amber-200 hover:bg-amber-400/15 transition-colors"
|
||||
>
|
||||
Purchase from Retailer
|
||||
<svg
|
||||
className="w-4 h-4"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
<div className="mt-3 flex gap-2 flex-wrap">
|
||||
{part.url && (
|
||||
<a
|
||||
href={part.url}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="inline-flex items-center gap-2 rounded-md border border-amber-400/60 bg-amber-400/10 px-4 py-2 text-sm font-medium text-amber-200 hover:bg-amber-400/15 transition-colors"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"
|
||||
/>
|
||||
</svg>
|
||||
</a>
|
||||
Purchase from Retailer
|
||||
<svg
|
||||
className="w-4 h-4"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
viewBox="0 0 24 24"
|
||||
>
|
||||
<path
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
strokeWidth={2}
|
||||
d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14"
|
||||
/>
|
||||
</svg>
|
||||
</a>
|
||||
)}
|
||||
<Link
|
||||
href={`/gunbuilder/${category.id}/${part.id}`}
|
||||
className="inline-flex items-center rounded-md border border-zinc-700 bg-zinc-900/50 px-4 py-2 text-sm font-medium text-zinc-300 hover:bg-zinc-800 hover:border-zinc-600 transition-colors"
|
||||
@@ -327,5 +419,4 @@ export default function BuildDetailsPage() {
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
|
||||
}
|
||||
+12
-17
@@ -8,11 +8,9 @@ import type { CategoryId, Part } from "@/types/gunbuilder";
|
||||
import { CategoryColumn } from "@/components/CategoryColumn";
|
||||
|
||||
type GunbuilderProductFromApi = {
|
||||
id: number;
|
||||
uuid: string;
|
||||
slug: string;
|
||||
id: number; // backend numeric id
|
||||
name: string;
|
||||
brandName: string;
|
||||
brand: string;
|
||||
platform: string;
|
||||
partRole: string;
|
||||
price: number | null;
|
||||
@@ -24,7 +22,6 @@ 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,
|
||||
@@ -46,7 +43,6 @@ export default function GunbuilderPage() {
|
||||
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") {
|
||||
const stored = localStorage.getItem(STORAGE_KEY);
|
||||
if (stored) {
|
||||
@@ -80,7 +76,7 @@ export default function GunbuilderPage() {
|
||||
const data: GunbuilderProductFromApi[] = await res.json();
|
||||
|
||||
const normalized: Part[] = data
|
||||
.map((p) => {
|
||||
.map((p): Part | null => {
|
||||
const categoryId = PART_ROLE_TO_CATEGORY[p.partRole];
|
||||
if (!categoryId) {
|
||||
// Skip any parts we don't know how to map yet
|
||||
@@ -88,17 +84,17 @@ export default function GunbuilderPage() {
|
||||
}
|
||||
|
||||
return {
|
||||
// Use the backend UUID as the stable id for the UI
|
||||
id: p.uuid,
|
||||
id: String(p.id), // <<< ALWAYS string
|
||||
categoryId,
|
||||
name: p.name,
|
||||
brand: p.brandName,
|
||||
brand: p.brand,
|
||||
price: p.price ?? 0,
|
||||
imageUrl: p.mainImageUrl ?? undefined,
|
||||
url: p.buyUrl ?? undefined,
|
||||
} as Part;
|
||||
notes: undefined,
|
||||
};
|
||||
})
|
||||
.filter(Boolean) as Part[];
|
||||
.filter((p): p is Part => p !== null);
|
||||
|
||||
setParts(normalized);
|
||||
} catch (err: any) {
|
||||
@@ -114,7 +110,7 @@ export default function GunbuilderPage() {
|
||||
return () => controller.abort();
|
||||
}, []);
|
||||
|
||||
// Handle URL query parameter for part selection
|
||||
// Handle URL query parameter for part selection (?select=upper:165)
|
||||
useEffect(() => {
|
||||
const selectParam = searchParams.get("select");
|
||||
if (selectParam) {
|
||||
@@ -123,13 +119,12 @@ export default function GunbuilderPage() {
|
||||
setBuild((prev) => {
|
||||
const updated = {
|
||||
...prev,
|
||||
[categoryId]: partId,
|
||||
[categoryId as CategoryId]: partId,
|
||||
};
|
||||
// Persist to localStorage
|
||||
localStorage.setItem(STORAGE_KEY, JSON.stringify(updated));
|
||||
return updated;
|
||||
});
|
||||
// Remove query param from URL
|
||||
|
||||
router.replace("/gunbuilder", { scroll: false });
|
||||
}
|
||||
}
|
||||
@@ -319,4 +314,4 @@ export default function GunbuilderPage() {
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user