ui using new v1 api for products

This commit is contained in:
2025-12-18 19:18:15 -05:00
parent 463fd06a12
commit 7f3818f795
12 changed files with 153 additions and 74 deletions
+2 -2
View File
@@ -177,12 +177,12 @@ export default function BuildSummaryPage() {
setError(null); setError(null);
// scoped (platform) // scoped (platform)
const scopedUrl = `${API_BASE_URL}/api/products?platform=${encodeURIComponent( const scopedUrl = `${API_BASE_URL}/api/v1/products?platform=${encodeURIComponent(
platform platform
)}`; )}`;
// universal (optional) // universal (optional)
const universalUrl = `${API_BASE_URL}/api/products`; const universalUrl = `${API_BASE_URL}/api/v1/products`;
const [scopedRes, universalRes] = await Promise.all([ const [scopedRes, universalRes] = await Promise.all([
fetch(scopedUrl, { signal: controller.signal }), fetch(scopedUrl, { signal: controller.signal }),
+2 -2
View File
@@ -316,11 +316,11 @@ export default function GunbuilderPage() {
setLoading(true); setLoading(true);
setError(null); setError(null);
const scopedUrl = `${API_BASE_URL}/api/products?platform=${encodeURIComponent( const scopedUrl = `${API_BASE_URL}/api/v1/products?platform=${encodeURIComponent(
platform platform
)}`; )}`;
const universalUrl = `${API_BASE_URL}/api/products`; const universalUrl = `${API_BASE_URL}/api/v1/products`;
const [scopedRes, universalRes] = await Promise.all([ const [scopedRes, universalRes] = await Promise.all([
fetch(scopedUrl, { signal: controller.signal }), fetch(scopedUrl, { signal: controller.signal }),
+1 -1
View File
@@ -116,7 +116,7 @@ export default function BuildDetailsPage() {
setPartsError(null); setPartsError(null);
const res = await fetch( const res = await fetch(
`${API_BASE_URL}/api/products?platform=${encodeURIComponent(platform)}`, `${API_BASE_URL}/api/v1/products?platform=${encodeURIComponent(platform)}`,
{ signal: controller.signal }, { signal: controller.signal },
); );
@@ -122,7 +122,7 @@ export default function ProductDetailsPage() {
setLoading(true); setLoading(true);
setError(null); setError(null);
const url = `${API_BASE_URL}/api/products/${numericId}`; const url = `${API_BASE_URL}/api/v1/products/${numericId}`;
const res = await fetch(url, { signal: controller.signal }); const res = await fetch(url, { signal: controller.signal });
if (!res.ok) { if (!res.ok) {
@@ -56,13 +56,13 @@ export function getPricingHistory(
/** /**
* Get retailer offers for a part * Get retailer offers for a part
* Real implementation using Ballistic backend: * Real implementation using Ballistic backend:
* GET /api/products/{productId}/offers * GET /api/v1/products/{productId}/offers
*/ */
export async function getRetailerOffers( export async function getRetailerOffers(
productId: string, productId: string,
): Promise<RetailerOffer[]> { ): Promise<RetailerOffer[]> {
const res = await fetch( const res = await fetch(
`${API_BASE_URL}/api/products/${productId}/offers`, `${API_BASE_URL}/api/v1/products/${productId}/offers`,
{ {
// This will be called from the client detail page, // This will be called from the client detail page,
// so we *don't* use cache here. // so we *don't* use cache here.
@@ -135,7 +135,7 @@ export default function CategoryPage() {
search.append("partRoles", r); search.append("partRoles", r);
} }
const url = `${API_BASE_URL}/api/products?${search.toString()}`; const url = `${API_BASE_URL}/api/v1/products?${search.toString()}`;
const res = await fetch(url, { signal: controller.signal }); const res = await fetch(url, { signal: controller.signal });
@@ -172,7 +172,7 @@ export default function ProductDetailsPage() {
setLoading(true); setLoading(true);
setError(null); setError(null);
const url = `${API_BASE_URL}/api/products/${numericId}`; const url = `${API_BASE_URL}/api/v1/products/${numericId}`;
const res = await fetch(url, { signal: controller.signal }); const res = await fetch(url, { signal: controller.signal });
if (!res.ok) { if (!res.ok) {
+3 -3
View File
@@ -22,7 +22,7 @@ type PlatformOption = {
}; };
// Backend currently filters products by canonical platform strings like "AR-15". // Backend currently filters products by canonical platform strings like "AR-15".
// DB platform keys are like "AR15" / "AR9". Translate when calling /api/products. // DB platform keys are like "AR15" / "AR9". Translate when calling /api/v1/products.
const platformKeyToApiPlatform = (key: string) => { const platformKeyToApiPlatform = (key: string) => {
const k = (key ?? "").toUpperCase().trim(); const k = (key ?? "").toUpperCase().trim();
if (!k) return "AR-15"; if (!k) return "AR-15";
@@ -123,7 +123,7 @@ export default function AdminProductsPage() {
const apiPlatform = platformKeyToApiPlatform(platform); const apiPlatform = platformKeyToApiPlatform(platform);
// NOTE: backend endpoint expects `platform`, not `platformKey`. // NOTE: backend endpoint expects `platform`, not `platformKey`.
const url = `${API_BASE_URL}/api/products?platform=${encodeURIComponent( const url = `${API_BASE_URL}/api/v1/products?platform=${encodeURIComponent(
apiPlatform apiPlatform
)}`; )}`;
@@ -402,7 +402,7 @@ export default function AdminProductsPage() {
)} )}
<div className="mt-3 text-[0.7rem] text-zinc-500"> <div className="mt-3 text-[0.7rem] text-zinc-500">
Backend: <span className="font-mono text-zinc-400">{API_BASE_URL}</span> · Endpoint: <span className="font-mono text-zinc-400">/api/products?platform=...</span> · Page size: <span className="font-mono text-zinc-400">{pageSize}</span> Backend: <span className="font-mono text-zinc-400">{API_BASE_URL}</span> · Endpoint: <span className="font-mono text-zinc-400">/api/v1/products?platform=...</span> · Page size: <span className="font-mono text-zinc-400">{pageSize}</span>
</div> </div>
</section> </section>
</div> </div>
+130 -51
View File
@@ -1,5 +1,6 @@
"use client"; "use client";
import Link from "next/link";
/** /**
* PartsBrowseClient * PartsBrowseClient
* ----------------------------------------------------------------------------- * -----------------------------------------------------------------------------
@@ -20,7 +21,10 @@ import Pagination from "@/components/parts/Pagination";
import PlatformSwitcher from "@/components/parts/PlatformSwitcher"; import PlatformSwitcher from "@/components/parts/PlatformSwitcher";
import type { CategoryId } from "@/types/gunbuilder"; import type { CategoryId } from "@/types/gunbuilder";
import { PART_ROLE_TO_CATEGORY, normalizePartRole } from "@/lib/catalogMappings"; import {
PART_ROLE_TO_CATEGORY,
normalizePartRole,
} from "@/lib/catalogMappings";
type ViewMode = "card" | "list"; type ViewMode = "card" | "list";
type SortOption = "relevance" | "price-asc" | "price-desc" | "brand-asc"; type SortOption = "relevance" | "price-asc" | "price-desc" | "brand-asc";
@@ -49,7 +53,8 @@ type UiPart = {
inStock?: boolean; inStock?: boolean;
}; };
const API_BASE_URL = process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://localhost:8080"; const API_BASE_URL =
process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://localhost:8080";
const PAGE_SIZE = 24; const PAGE_SIZE = 24;
function normalizeId(id: string | number) { function normalizeId(id: string | number) {
@@ -70,9 +75,9 @@ function toSlug(s: string) {
*/ */
function buildDetailHref(platform: string, partRole: string, p: UiPart) { function buildDetailHref(platform: string, partRole: string, p: UiPart) {
const slug = toSlug(`${p.brand ?? ""} ${p.name ?? ""}`); const slug = toSlug(`${p.brand ?? ""} ${p.name ?? ""}`);
return `/parts/p/${encodeURIComponent(platform)}/${encodeURIComponent(partRole)}/${encodeURIComponent( return `/parts/p/${encodeURIComponent(platform)}/${encodeURIComponent(
`${p.id}-${slug}` partRole
)}`; )}/${encodeURIComponent(`${p.id}-${slug}`)}`;
} }
export default function PartsBrowseClient(props: { export default function PartsBrowseClient(props: {
@@ -84,7 +89,8 @@ export default function PartsBrowseClient(props: {
const router = useRouter(); const router = useRouter();
const searchParams = useSearchParams(); const searchParams = useSearchParams();
const effectivePlatform = props.platform ?? searchParams.get("platform") ?? "AR-15"; const effectivePlatform =
props.platform ?? searchParams.get("platform") ?? "AR-15";
const partRole = props.partRole; const partRole = props.partRole;
const [viewMode, setViewMode] = useState<ViewMode>("list"); const [viewMode, setViewMode] = useState<ViewMode>("list");
@@ -95,7 +101,10 @@ export default function PartsBrowseClient(props: {
const [brandFilter, setBrandFilter] = useState<string[]>([]); const [brandFilter, setBrandFilter] = useState<string[]>([]);
const [sortBy, setSortBy] = useState<SortOption>("relevance"); const [sortBy, setSortBy] = useState<SortOption>("relevance");
const [searchQuery, setSearchQuery] = useState<string>(""); const [searchQuery, setSearchQuery] = useState<string>("");
const [priceRange, setPriceRange] = useState<{ min: number | null; max: number | null }>({ const [priceRange, setPriceRange] = useState<{
min: number | null;
max: number | null;
}>({
min: null, min: null,
max: null, max: null,
}); });
@@ -116,7 +125,7 @@ export default function PartsBrowseClient(props: {
search.set("platform", effectivePlatform); search.set("platform", effectivePlatform);
search.append("partRoles", partRole); search.append("partRoles", partRole);
const url = `${API_BASE_URL}/api/products?${search.toString()}`; const url = `${API_BASE_URL}/api/v1/products?${search.toString()}`;
const res = await fetch(url, { signal: controller.signal }); const res = await fetch(url, { signal: controller.signal });
if (!res.ok) throw new Error(`Failed to load products (${res.status})`); if (!res.ok) throw new Error(`Failed to load products (${res.status})`);
@@ -150,7 +159,15 @@ export default function PartsBrowseClient(props: {
useEffect(() => { useEffect(() => {
setCurrentPage(1); setCurrentPage(1);
}, [partRole, effectivePlatform, brandFilter, sortBy, searchQuery, priceRange, inStockOnly]); }, [
partRole,
effectivePlatform,
brandFilter,
sortBy,
searchQuery,
priceRange,
inStockOnly,
]);
const availableBrands = useMemo( const availableBrands = useMemo(
() => () =>
@@ -161,7 +178,8 @@ export default function PartsBrowseClient(props: {
); );
const priceBounds = useMemo(() => { const priceBounds = useMemo(() => {
if (parts.length === 0) return { min: null as number | null, max: null as number | null }; if (parts.length === 0)
return { min: null as number | null, max: null as number | null };
let min = Number.POSITIVE_INFINITY; let min = Number.POSITIVE_INFINITY;
let max = Number.NEGATIVE_INFINITY; let max = Number.NEGATIVE_INFINITY;
@@ -198,7 +216,9 @@ export default function PartsBrowseClient(props: {
const effectiveMin = priceRange.min ?? priceBounds.min; const effectiveMin = priceRange.min ?? priceBounds.min;
const effectiveMax = priceRange.max ?? priceBounds.max; const effectiveMax = priceRange.max ?? priceBounds.max;
if (effectiveMin != null && effectiveMax != null) { if (effectiveMin != null && effectiveMax != null) {
result = result.filter((p) => p.price >= effectiveMin && p.price <= effectiveMax); result = result.filter(
(p) => p.price >= effectiveMin && p.price <= effectiveMax
);
} }
if (brandFilter.length > 0) { if (brandFilter.length > 0) {
@@ -234,10 +254,22 @@ export default function PartsBrowseClient(props: {
} }
return result; return result;
}, [parts, brandFilter, sortBy, searchQuery, priceRange, priceBounds.min, priceBounds.max, inStockOnly]); }, [
parts,
brandFilter,
sortBy,
searchQuery,
priceRange,
priceBounds.min,
priceBounds.max,
inStockOnly,
]);
const totalPages = useMemo( const totalPages = useMemo(
() => (filteredParts.length === 0 ? 1 : Math.ceil(filteredParts.length / PAGE_SIZE)), () =>
filteredParts.length === 0
? 1
: Math.ceil(filteredParts.length / PAGE_SIZE),
[filteredParts.length] [filteredParts.length]
); );
@@ -250,21 +282,30 @@ export default function PartsBrowseClient(props: {
const visibleRange = useMemo(() => { const visibleRange = useMemo(() => {
if (filteredParts.length === 0) return { start: 0, end: 0 }; if (filteredParts.length === 0) return { start: 0, end: 0 };
const start = (currentPage - 1) * PAGE_SIZE + 1; const start = (currentPage - 1) * PAGE_SIZE + 1;
const end = Math.min(start + paginatedParts.length - 1, filteredParts.length); const end = Math.min(
start + paginatedParts.length - 1,
filteredParts.length
);
return { start, end }; return { start, end };
}, [filteredParts.length, currentPage, paginatedParts.length]); }, [filteredParts.length, currentPage, paginatedParts.length]);
const headingTitle = props.title ?? `${partRole.replaceAll("-", " ")} parts`; const headingTitle = props.title ?? `${partRole.replaceAll("-", " ")} parts`;
const headingSubtitle = props.subtitle ?? "Browse available parts pulled from your Ballistic backend."; const headingSubtitle =
props.subtitle ??
"Browse available parts pulled from your Ballistic backend.";
// ✅ Add-to-build handler: deep-links into builders existing ?select= logic // ✅ Add-to-build handler: deep-links into builders existing ?select= logic
const handleAddToBuild = (p: UiPart) => { const handleAddToBuild = (p: UiPart) => {
const normalizedRole = normalizePartRole(partRole); const normalizedRole = normalizePartRole(partRole);
const categoryId: CategoryId | null = const categoryId: CategoryId | null =
PART_ROLE_TO_CATEGORY[partRole] ?? PART_ROLE_TO_CATEGORY[normalizedRole] ?? null; PART_ROLE_TO_CATEGORY[partRole] ??
PART_ROLE_TO_CATEGORY[normalizedRole] ??
null;
if (!categoryId) { if (!categoryId) {
alert(`No CategoryId mapping found for role "${partRole}". Add it to catalogMappings.`); alert(
`No CategoryId mapping found for role "${partRole}". Add it to catalogMappings.`
);
return; return;
} }
@@ -286,36 +327,63 @@ export default function PartsBrowseClient(props: {
</p> </p>
<h1 className="mt-1 text-2xl md:text-3xl font-semibold tracking-tight"> <h1 className="mt-1 text-2xl md:text-3xl font-semibold tracking-tight">
{headingTitle} <span className="text-amber-300">{effectivePlatform}</span> {headingTitle}{" "}
<span className="text-amber-300">{effectivePlatform}</span>
</h1> </h1>
<p className="mt-2 text-sm text-zinc-400 max-w-xl">{headingSubtitle}</p> <p className="mt-2 text-sm text-zinc-400 max-w-xl">
{headingSubtitle}
</p>
<div className="mt-3"> <div className="mt-3">
<PlatformSwitcher currentPlatform={effectivePlatform} partRole={partRole} preserveQuery /> <PlatformSwitcher
currentPlatform={effectivePlatform}
partRole={partRole}
preserveQuery
/>
</div> </div>
</div> </div>
{!loading && !error && parts.length > 0 && ( {!loading && !error && (
<div className="flex gap-2 border border-zinc-800 rounded-md p-1 bg-zinc-950/60"> <div className="flex items-center gap-2">
<button <Link
type="button" href={{
onClick={() => setViewMode("card")} pathname: "/builder",
className={`px-3 py-1.5 text-xs font-medium rounded transition-colors ${ query: effectivePlatform
viewMode === "card" ? "bg-zinc-800 text-zinc-50" : "text-zinc-400 hover:text-zinc-300" ? { platform: effectivePlatform }
}`} : {},
}}
className="rounded-md border border-zinc-700 bg-zinc-900/70 px-3 py-2 text-xs font-semibold text-zinc-200 hover:bg-zinc-800"
> >
Card Back to Build
</button> </Link>
<button
type="button" {parts.length > 0 && (
onClick={() => setViewMode("list")} <div className="flex gap-2 border border-zinc-800 rounded-md p-1 bg-zinc-950/60">
className={`px-3 py-1.5 text-xs font-medium rounded transition-colors ${ <button
viewMode === "list" ? "bg-zinc-800 text-zinc-50" : "text-zinc-400 hover:text-zinc-300" type="button"
}`} onClick={() => setViewMode("card")}
> className={`px-3 py-1.5 text-xs font-medium rounded transition-colors ${
List viewMode === "card"
</button> ? "bg-zinc-800 text-zinc-50"
: "text-zinc-400 hover:text-zinc-300"
}`}
>
Card
</button>
<button
type="button"
onClick={() => setViewMode("list")}
className={`px-3 py-1.5 text-xs font-medium rounded transition-colors ${
viewMode === "list"
? "bg-zinc-800 text-zinc-50"
: "text-zinc-400 hover:text-zinc-300"
}`}
>
List
</button>
</div>
)}
</div> </div>
)} )}
</div> </div>
@@ -352,35 +420,46 @@ export default function PartsBrowseClient(props: {
)} )}
{loading ? ( {loading ? (
<p className="py-8 text-center text-sm text-zinc-500">Loading</p> <p className="py-8 text-center text-sm text-zinc-500">
Loading
</p>
) : error ? ( ) : error ? (
<p className="py-8 text-center text-sm text-red-400"> <p className="py-8 text-center text-sm text-red-400">
{error} check that the Ballistic API is running. {error} check that the Ballistic API is running.
</p> </p>
) : filteredParts.length === 0 ? ( ) : filteredParts.length === 0 ? (
<p className="py-8 text-center text-sm text-zinc-500">No parts found for this role yet.</p> <p className="py-8 text-center text-sm text-zinc-500">
No parts found for this role yet.
</p>
) : ( ) : (
<PartsGrid <PartsGrid
viewMode={viewMode} viewMode={viewMode}
parts={paginatedParts} parts={paginatedParts}
buildDetailHref={(p) => buildDetailHref(effectivePlatform, partRole, p)} buildDetailHref={(p) =>
buildDetailHref(effectivePlatform, partRole, p)
}
onAddToBuild={handleAddToBuild} onAddToBuild={handleAddToBuild}
addLabel="Add to Build" addLabel="Add to Build"
/> />
)} )}
{!loading && !error && filteredParts.length > 0 && totalPages > 1 && ( {!loading &&
<Pagination !error &&
currentPage={currentPage} filteredParts.length > 0 &&
totalPages={totalPages} totalPages > 1 && (
onPrev={() => setCurrentPage((p) => Math.max(1, p - 1))} <Pagination
onNext={() => setCurrentPage((p) => Math.min(totalPages, p + 1))} currentPage={currentPage}
/> totalPages={totalPages}
)} onPrev={() => setCurrentPage((p) => Math.max(1, p - 1))}
onNext={() =>
setCurrentPage((p) => Math.min(totalPages, p + 1))
}
/>
)}
</div> </div>
</div> </div>
</section> </section>
</div> </div>
</main> </main>
); );
} }
+2 -2
View File
@@ -48,8 +48,8 @@ export default function PartsListPageClient(props: {
setError(null); setError(null);
// Your current list endpoint: // Your current list endpoint:
// GET /api/products?platform=AR-15&partRoles=upper-receiver // GET /api/v1/products?platform=AR-15&partRoles=upper-receiver
const url = `${API_BASE_URL}/api/products?platform=${encodeURIComponent(platform)}&partRoles=${encodeURIComponent(partRole)}`; const url = `${API_BASE_URL}/api/v1/products?platform=${encodeURIComponent(platform)}&partRoles=${encodeURIComponent(partRole)}`;
const res = await fetch(url, { headers: { Accept: "application/json" } }); const res = await fetch(url, { headers: { Accept: "application/json" } });
if (!res.ok) { if (!res.ok) {
+3 -3
View File
@@ -38,10 +38,10 @@ async function fetchProductDetail(params: {
if (!id) throw new Error(`Invalid product URL slug: '${productSlug}' (could not parse id)`); if (!id) throw new Error(`Invalid product URL slug: '${productSlug}' (could not parse id)`);
// ---- Preferred (if you add it): GET /api/products/{id} // ---- Preferred (if you add it): GET /api/v1/products/{id}
// If it 404s, we fall back. // If it 404s, we fall back.
try { try {
const res = await fetch(`${API_BASE_URL}/api/products/${encodeURIComponent(id)}`, { const res = await fetch(`${API_BASE_URL}/api/v1/products/${encodeURIComponent(id)}`, {
headers: { Accept: "application/json" }, headers: { Accept: "application/json" },
}); });
@@ -54,7 +54,7 @@ async function fetchProductDetail(params: {
// ---- Fallback: use list endpoint + find by id (works right now with your current API) // ---- Fallback: use list endpoint + find by id (works right now with your current API)
const listRes = await fetch( const listRes = await fetch(
`${API_BASE_URL}/api/products?platform=${encodeURIComponent(platform)}&partRoles=${encodeURIComponent(partRole)}`, `${API_BASE_URL}/api/v1/products?platform=${encodeURIComponent(platform)}&partRoles=${encodeURIComponent(partRole)}`,
{ headers: { Accept: "application/json" } } { headers: { Accept: "application/json" } }
); );
+5 -5
View File
@@ -42,7 +42,7 @@ export function slugify(input: string) {
/** /**
* Your existing list endpoint: * Your existing list endpoint:
* GET /api/products?platform=AR-15&partRoles=complete-upper * GET /api/v1/products?platform=AR-15&partRoles=complete-upper
*/ */
export async function fetchProducts(params: { export async function fetchProducts(params: {
platform: string; platform: string;
@@ -51,7 +51,7 @@ export async function fetchProducts(params: {
const { platform, partRole } = params; const { platform, partRole } = params;
const url = const url =
`${API_BASE_URL}/api/products?` + `${API_BASE_URL}/api/v1/products?` +
new URLSearchParams({ new URLSearchParams({
platform, platform,
partRoles: partRole, partRoles: partRole,
@@ -70,9 +70,9 @@ export async function fetchProducts(params: {
/** /**
* You likely have (or should add) a detail endpoint like: * You likely have (or should add) a detail endpoint like:
* GET /api/products/{id}?platform=AR-15 OR GET /api/products/{id} * GET /api/v1/products/{id}?platform=AR-15 OR GET /api/v1/products/{id}
* *
* We'll call /api/products/{id} and optionally include platform as a query param. * We'll call /api/v1/products/{id} and optionally include platform as a query param.
*/ */
export async function fetchProductById(params: { export async function fetchProductById(params: {
id: string; id: string;
@@ -81,7 +81,7 @@ export async function fetchProductById(params: {
const { id, platform } = params; const { id, platform } = params;
const url = const url =
`${API_BASE_URL}/api/products/${encodeURIComponent(id)}` + `${API_BASE_URL}/api/v1/products/${encodeURIComponent(id)}` +
(platform ? `?${new URLSearchParams({ platform })}` : ""); (platform ? `?${new URLSearchParams({ platform })}` : "");
const res = await fetch(url, { cache: "no-store" }); const res = await fetch(url, { cache: "no-store" });