mad cleanup.
This commit is contained in:
@@ -0,0 +1,339 @@
|
||||
"use client";
|
||||
|
||||
import React, { useMemo, useState } from "react";
|
||||
|
||||
type Counts = Record<string, number>;
|
||||
|
||||
type DiffRow = {
|
||||
productId: number;
|
||||
name: string;
|
||||
platform: string | null;
|
||||
rawCategoryKey: string | null;
|
||||
|
||||
resolvedMerchantId: number | null;
|
||||
|
||||
existingPartRole: string | null;
|
||||
existingSource: string | null;
|
||||
partRoleLocked: boolean | null;
|
||||
platformLocked: boolean | null;
|
||||
|
||||
resolvedPartRole: string | null;
|
||||
resolvedSource: string | null;
|
||||
resolvedConfidence: number | null;
|
||||
resolvedReason: string | null;
|
||||
|
||||
status: string;
|
||||
meta?: Record<string, any>;
|
||||
};
|
||||
|
||||
type ReconcileResponse = {
|
||||
dryRun: boolean;
|
||||
scanned: number;
|
||||
counts: Counts;
|
||||
samples: DiffRow[];
|
||||
};
|
||||
|
||||
const DEFAULT_LIMIT = 500;
|
||||
const DEFAULT_PLATFORM = "AR-15";
|
||||
|
||||
// Update these if your admin mapping UI lives elsewhere.
|
||||
const MAPPING_UI_PATH = "/admin/mapping"; // <- change if needed
|
||||
const API_BASE = process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://localhost:8080";
|
||||
|
||||
const url = `${API_BASE}/admin/classification/reconcile?dryRun=true&limit=500&platform=AR-15&merchantId=4`;
|
||||
|
||||
|
||||
|
||||
export default function AdminClassificationReconcilePage() {
|
||||
const [merchantId, setMerchantId] = useState<string>("4"); // your current test merchant
|
||||
const [platform, setPlatform] = useState<string>(DEFAULT_PLATFORM);
|
||||
const [limit, setLimit] = useState<number>(DEFAULT_LIMIT);
|
||||
const [includeLocked, setIncludeLocked] = useState<boolean>(false);
|
||||
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [data, setData] = useState<ReconcileResponse | null>(null);
|
||||
|
||||
const [statusFilter, setStatusFilter] = useState<string>("ALL");
|
||||
|
||||
const filteredSamples = useMemo(() => {
|
||||
if (!data?.samples) return [];
|
||||
if (statusFilter === "ALL") return data.samples;
|
||||
return data.samples.filter((r) => r.status === statusFilter);
|
||||
}, [data, statusFilter]);
|
||||
|
||||
const uniqueStatuses = useMemo(() => {
|
||||
const set = new Set<string>();
|
||||
(data?.samples ?? []).forEach((r) => set.add(r.status));
|
||||
return ["ALL", ...Array.from(set.values()).sort()];
|
||||
}, [data]);
|
||||
|
||||
async function runReconcile() {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
const params = new URLSearchParams();
|
||||
params.set("dryRun", "true");
|
||||
params.set("limit", String(limit));
|
||||
if (platform?.trim()) params.set("platform", platform.trim());
|
||||
if (merchantId?.trim()) params.set("merchantId", merchantId.trim());
|
||||
if (includeLocked) params.set("includeLocked", "true");
|
||||
|
||||
const API_BASE = process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://localhost:8080";
|
||||
const url = `${API_BASE}/admin/classification/reconcile?${params.toString()}`;
|
||||
|
||||
const res = await fetch(url, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({}),
|
||||
cache: "no-store",
|
||||
});
|
||||
|
||||
// Helpful error body (also avoids the "<!DOCTYPE" confusion)
|
||||
const text = await res.text();
|
||||
if (!res.ok) throw new Error(text || `Request failed (${res.status})`);
|
||||
|
||||
const json = JSON.parse(text) as ReconcileResponse;
|
||||
setData(json);
|
||||
} catch (e: any) {
|
||||
setError(e?.message ?? "Unknown error");
|
||||
setData(null);
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
function mappingLink(row: DiffRow) {
|
||||
// Deep-link into existing mapping UI with prefilled values.
|
||||
// Adjust param names to match your mapping UI, if needed.
|
||||
const qs = new URLSearchParams();
|
||||
if (merchantId) qs.set("merchantId", merchantId);
|
||||
if (platform) qs.set("platform", platform);
|
||||
if (row.rawCategoryKey) qs.set("rawCategoryKey", row.rawCategoryKey);
|
||||
return `${MAPPING_UI_PATH}?${qs.toString()}`;
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="mx-auto max-w-6xl px-6 py-10">
|
||||
<div className="mb-8">
|
||||
<h1 className="text-2xl font-semibold tracking-tight">Classification Reconcile</h1>
|
||||
<p className="mt-2 text-sm text-zinc-400">
|
||||
Dry-run inspector for part-role classification. Finds <span className="text-zinc-200">UNMAPPED</span>,{" "}
|
||||
<span className="text-zinc-200">IGNORED</span>, rule hits, and drift. (No writes. No regrets.)
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Controls */}
|
||||
<div className="rounded-lg border border-zinc-800 bg-zinc-950/60 p-5">
|
||||
<div className="grid grid-cols-1 gap-4 md:grid-cols-5">
|
||||
<label className="block">
|
||||
<div className="text-xs text-zinc-400">Merchant ID</div>
|
||||
<input
|
||||
value={merchantId}
|
||||
onChange={(e) => setMerchantId(e.target.value)}
|
||||
className="mt-1 w-full rounded-md border border-zinc-800 bg-zinc-950 px-3 py-2 text-sm text-zinc-100"
|
||||
placeholder="4"
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="block">
|
||||
<div className="text-xs text-zinc-400">Platform</div>
|
||||
<select
|
||||
value={platform}
|
||||
onChange={(e) => setPlatform(e.target.value)}
|
||||
className="mt-1 w-full rounded-md border border-zinc-800 bg-zinc-950 px-3 py-2 text-sm text-zinc-100"
|
||||
>
|
||||
<option value="AR-15">AR-15</option>
|
||||
<option value="AR-10">AR-10</option>
|
||||
<option value="AR-9">AR-9</option>
|
||||
<option value="AK-47">AK-47</option>
|
||||
<option value="">(any)</option>
|
||||
</select>
|
||||
</label>
|
||||
|
||||
<label className="block">
|
||||
<div className="text-xs text-zinc-400">Limit</div>
|
||||
<input
|
||||
type="number"
|
||||
value={limit}
|
||||
onChange={(e) => setLimit(Number(e.target.value))}
|
||||
className="mt-1 w-full rounded-md border border-zinc-800 bg-zinc-950 px-3 py-2 text-sm text-zinc-100"
|
||||
min={1}
|
||||
max={20000}
|
||||
/>
|
||||
</label>
|
||||
|
||||
<label className="flex items-end gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={includeLocked}
|
||||
onChange={(e) => setIncludeLocked(e.target.checked)}
|
||||
className="h-4 w-4 accent-zinc-200"
|
||||
/>
|
||||
<span className="text-sm text-zinc-200">Include locked</span>
|
||||
</label>
|
||||
|
||||
<div className="flex items-end justify-end">
|
||||
<button
|
||||
onClick={runReconcile}
|
||||
disabled={loading}
|
||||
className="inline-flex w-full items-center justify-center rounded-md bg-zinc-100 px-4 py-2 text-sm font-medium text-zinc-900 hover:bg-white disabled:opacity-60 md:w-auto"
|
||||
>
|
||||
{loading ? "Running…" : "Run reconcile"}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<div className="mt-4 rounded-md border border-red-900/40 bg-red-950/30 px-4 py-3 text-sm text-red-200">
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Results */}
|
||||
{data && (
|
||||
<div className="mt-8 space-y-6">
|
||||
<div className="rounded-lg border border-zinc-800 bg-zinc-950/60 p-5">
|
||||
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||
<div className="text-sm text-zinc-300">
|
||||
Scanned: <span className="text-zinc-100 font-medium">{data.scanned}</span> • DryRun:{" "}
|
||||
<span className="text-zinc-100 font-medium">{String(data.dryRun)}</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs text-zinc-400">Filter</span>
|
||||
<select
|
||||
value={statusFilter}
|
||||
onChange={(e) => setStatusFilter(e.target.value)}
|
||||
className="rounded-md border border-zinc-800 bg-zinc-950 px-3 py-2 text-sm text-zinc-100"
|
||||
>
|
||||
{uniqueStatuses.map((s) => (
|
||||
<option key={s} value={s}>
|
||||
{s}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Counts */}
|
||||
<div className="mt-4 grid grid-cols-2 gap-3 md:grid-cols-7">
|
||||
{Object.entries(data.counts ?? {}).map(([k, v]) => (
|
||||
<div key={k} className="rounded-md border border-zinc-800 bg-zinc-950 px-3 py-2">
|
||||
<div className="text-[11px] uppercase tracking-wider text-zinc-500">{k}</div>
|
||||
<div className="text-lg font-semibold text-zinc-100">{v}</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Samples table */}
|
||||
<div className="rounded-lg border border-zinc-800 bg-zinc-950/60">
|
||||
<div className="flex items-center justify-between border-b border-zinc-800 px-5 py-4">
|
||||
<div>
|
||||
<div className="text-sm font-medium text-zinc-100">Samples</div>
|
||||
<div className="text-xs text-zinc-400">
|
||||
Showing up to 50 interesting rows (UNMAPPED / IGNORED / CONFLICT / WOULD_UPDATE + rule hits).
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<a
|
||||
href={MAPPING_UI_PATH}
|
||||
className="text-sm text-zinc-200 underline decoration-zinc-700 underline-offset-4 hover:text-white"
|
||||
>
|
||||
Go to mappings →
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<div className="overflow-auto">
|
||||
<table className="w-full text-left text-sm">
|
||||
<thead className="sticky top-0 bg-zinc-950">
|
||||
<tr className="border-b border-zinc-800 text-xs text-zinc-400">
|
||||
<th className="px-5 py-3">Status</th>
|
||||
<th className="px-5 py-3">Product</th>
|
||||
<th className="px-5 py-3">Raw Category</th>
|
||||
<th className="px-5 py-3">Existing Role</th>
|
||||
<th className="px-5 py-3">Resolved</th>
|
||||
<th className="px-5 py-3">Why</th>
|
||||
<th className="px-5 py-3"></th>
|
||||
</tr>
|
||||
</thead>
|
||||
|
||||
<tbody>
|
||||
{filteredSamples.length === 0 ? (
|
||||
<tr>
|
||||
<td colSpan={7} className="px-5 py-6 text-zinc-400">
|
||||
No rows match this filter.
|
||||
</td>
|
||||
</tr>
|
||||
) : (
|
||||
filteredSamples.map((r) => (
|
||||
<tr key={r.productId} className="border-b border-zinc-900 align-top">
|
||||
<td className="px-5 py-3">
|
||||
<span className="rounded-md border border-zinc-800 bg-zinc-950 px-2 py-1 text-xs text-zinc-200">
|
||||
{r.status}
|
||||
</span>
|
||||
{r.resolvedSource?.startsWith("rules_") && (
|
||||
<div className="mt-2 text-[11px] text-zinc-500">
|
||||
rule: <span className="text-zinc-300">{r.resolvedSource}</span>
|
||||
</div>
|
||||
)}
|
||||
</td>
|
||||
|
||||
<td className="px-5 py-3">
|
||||
<div className="text-zinc-100">{r.name}</div>
|
||||
<div className="mt-1 text-xs text-zinc-500">
|
||||
#{r.productId} • {r.platform ?? "—"} • merchantUsed: {r.resolvedMerchantId ?? "—"}
|
||||
</div>
|
||||
</td>
|
||||
|
||||
<td className="px-5 py-3">
|
||||
<div className="text-zinc-200">{r.rawCategoryKey ?? "—"}</div>
|
||||
</td>
|
||||
|
||||
<td className="px-5 py-3">
|
||||
<div className="text-zinc-200">{r.existingPartRole ?? "—"}</div>
|
||||
<div className="mt-1 text-xs text-zinc-500">
|
||||
src: {r.existingSource ?? "—"}
|
||||
{r.partRoleLocked ? " • locked" : ""}
|
||||
{r.platformLocked ? " • platformLocked" : ""}
|
||||
</div>
|
||||
</td>
|
||||
|
||||
<td className="px-5 py-3">
|
||||
<div className="text-zinc-100">{r.resolvedPartRole ?? "—"}</div>
|
||||
<div className="mt-1 text-xs text-zinc-500">
|
||||
src: {r.resolvedSource ?? "—"} • conf:{" "}
|
||||
{typeof r.resolvedConfidence === "number" ? r.resolvedConfidence.toFixed(2) : "—"}
|
||||
</div>
|
||||
</td>
|
||||
|
||||
<td className="px-5 py-3">
|
||||
<div className="text-zinc-300">{r.resolvedReason ?? "—"}</div>
|
||||
</td>
|
||||
|
||||
<td className="px-5 py-3 text-right">
|
||||
{r.status === "UNMAPPED" && r.rawCategoryKey ? (
|
||||
<a
|
||||
href={mappingLink(r)}
|
||||
className="rounded-md border border-zinc-800 bg-zinc-950 px-3 py-2 text-xs text-zinc-200 hover:text-white"
|
||||
>
|
||||
Map category →
|
||||
</a>
|
||||
) : (
|
||||
<span className="text-xs text-zinc-600">—</span>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))
|
||||
)}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
+540
-84
@@ -1,10 +1,21 @@
|
||||
"use client";
|
||||
|
||||
import { useEffect, useMemo, useState } from "react";
|
||||
import { useSearchParams, useRouter } from "next/navigation";
|
||||
|
||||
const API_BASE_URL =
|
||||
process.env.NEXT_PUBLIC_API_BASE_URL ?? "http://localhost:8080";
|
||||
|
||||
/**
|
||||
* Tabs:
|
||||
* - roles: map raw category -> canonical_part_role (builder slot)
|
||||
* - catalog: map raw category -> canonical_category_id (FK to canonical_categories)
|
||||
*/
|
||||
type TabKey = "roles" | "catalog";
|
||||
|
||||
/**
|
||||
* Existing (you already have this working)
|
||||
*/
|
||||
type PendingBucket = {
|
||||
merchantId: number;
|
||||
merchantName: string;
|
||||
@@ -14,8 +25,47 @@ type PendingBucket = {
|
||||
};
|
||||
|
||||
/**
|
||||
* Canonical part roles (kebab-case) — should match what the importer normalizes to.
|
||||
* Keep this list tight + intentional so mappings don't create junk roles in the DB.
|
||||
* New “raw categories” row (for the combined UI).
|
||||
* If your backend returns fewer fields at first, it’s fine—just keep the ones you have.
|
||||
*/
|
||||
type RawCategoryRow = {
|
||||
merchantId: number;
|
||||
merchantName?: string | null;
|
||||
platform?: string | null;
|
||||
|
||||
rawCategoryKey: string;
|
||||
productCount: number;
|
||||
|
||||
// current mapping state (merchant_category_map row)
|
||||
mcmId?: number | null;
|
||||
enabled?: boolean | null;
|
||||
|
||||
canonicalPartRole?: string | null;
|
||||
|
||||
canonicalCategoryId?: number | null;
|
||||
canonicalCategoryName?: string | null;
|
||||
};
|
||||
|
||||
type CanonicalCategoryOption = {
|
||||
id: number;
|
||||
name: string;
|
||||
slug?: string | null;
|
||||
};
|
||||
|
||||
type MerchantOption = {
|
||||
id: number;
|
||||
name: string;
|
||||
};
|
||||
|
||||
type MappingOptionsResponse = {
|
||||
merchants: MerchantOption[];
|
||||
canonicalCategories: CanonicalCategoryOption[];
|
||||
};
|
||||
|
||||
const DEFAULT_PLATFORM = "AR-15";
|
||||
|
||||
/**
|
||||
* Canonical part roles (kebab-case)
|
||||
*/
|
||||
const PART_ROLE_OPTIONS = [
|
||||
// Assemblies / receivers
|
||||
@@ -56,23 +106,62 @@ const PART_ROLE_OPTIONS = [
|
||||
"tools",
|
||||
] as const;
|
||||
|
||||
type PartRole = (typeof PART_ROLE_OPTIONS)[number];
|
||||
|
||||
function toLabel(role: string) {
|
||||
// "complete-upper" -> "Complete Upper"
|
||||
return role
|
||||
.split("-")
|
||||
.map((w) => w.charAt(0).toUpperCase() + w.slice(1))
|
||||
.join(" ");
|
||||
}
|
||||
|
||||
function normalizeRole(role: string) {
|
||||
return role.trim().toLowerCase().replace(/_/g, "-");
|
||||
}
|
||||
|
||||
function safeNum(v: any): number | null {
|
||||
if (v == null) return null;
|
||||
if (typeof v === "number") return Number.isFinite(v) ? v : null;
|
||||
if (typeof v === "string") {
|
||||
const n = Number(v);
|
||||
return Number.isFinite(n) ? n : null;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
export default function MappingAdminPage() {
|
||||
const [rows, setRows] = useState<PendingBucket[]>([]);
|
||||
const [loading, setLoading] = useState(true);
|
||||
const [savingKey, setSavingKey] = useState<string | null>(null);
|
||||
const searchParams = useSearchParams();
|
||||
const router = useRouter();
|
||||
|
||||
// URL-driven state
|
||||
const initialTab = (searchParams.get("tab") as TabKey) || "roles";
|
||||
const initialMerchantId = searchParams.get("merchantId") || "";
|
||||
const initialPlatform = searchParams.get("platform") || DEFAULT_PLATFORM;
|
||||
const initialQ = searchParams.get("q") || "";
|
||||
|
||||
const [tab, setTab] = useState<TabKey>(initialTab);
|
||||
|
||||
const [merchantId, setMerchantId] = useState<string>(initialMerchantId);
|
||||
const [platform, setPlatform] = useState<string>(initialPlatform);
|
||||
const [q, setQ] = useState<string>(initialQ);
|
||||
|
||||
const [loading, setLoading] = useState<boolean>(true);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
const options = useMemo(
|
||||
// Options (for catalog tab + merchant dropdown)
|
||||
const [optionsLoading, setOptionsLoading] = useState<boolean>(false);
|
||||
const [merchants, setMerchants] = useState<MerchantOption[]>([]);
|
||||
const [canonicalCategories, setCanonicalCategories] = useState<
|
||||
CanonicalCategoryOption[]
|
||||
>([]);
|
||||
|
||||
// Rows
|
||||
const [roleBuckets, setRoleBuckets] = useState<PendingBucket[]>([]);
|
||||
const [rawRows, setRawRows] = useState<RawCategoryRow[]>([]);
|
||||
|
||||
// Saving state
|
||||
const [savingKey, setSavingKey] = useState<string | null>(null);
|
||||
|
||||
// Part role dropdown options
|
||||
const roleOptions = useMemo(
|
||||
() =>
|
||||
PART_ROLE_OPTIONS.map((value) => ({
|
||||
value,
|
||||
@@ -81,16 +170,83 @@ export default function MappingAdminPage() {
|
||||
[]
|
||||
);
|
||||
|
||||
// Keep URL in sync (so reconcile can deep-link)
|
||||
function syncUrl(next: Partial<{ tab: TabKey; merchantId: string; platform: string; q: string }>) {
|
||||
const params = new URLSearchParams(searchParams.toString());
|
||||
if (next.tab) params.set("tab", next.tab);
|
||||
if (next.merchantId !== undefined) {
|
||||
if (next.merchantId) params.set("merchantId", next.merchantId);
|
||||
else params.delete("merchantId");
|
||||
}
|
||||
if (next.platform !== undefined) {
|
||||
if (next.platform) params.set("platform", next.platform);
|
||||
else params.delete("platform");
|
||||
}
|
||||
if (next.q !== undefined) {
|
||||
if (next.q) params.set("q", next.q);
|
||||
else params.delete("q");
|
||||
}
|
||||
router.replace(`/admin/mapping?${params.toString()}`);
|
||||
}
|
||||
|
||||
// Load merchants + canonical categories (needed for catalog tab, but also nice for filtering everywhere)
|
||||
useEffect(() => {
|
||||
async function load() {
|
||||
async function loadOptions() {
|
||||
setOptionsLoading(true);
|
||||
try {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
const res = await fetch(
|
||||
`${API_BASE_URL}/api/admin/mapping/pending-buckets`,
|
||||
{ headers: { Accept: "application/json" } }
|
||||
);
|
||||
// EXPECTED backend endpoint (new):
|
||||
// GET { merchants: [{id,name}], canonicalCategories: [{id,name,slug}] }
|
||||
const res = await fetch(`${API_BASE_URL}/api/admin/mapping/options`, {
|
||||
headers: { Accept: "application/json" },
|
||||
cache: "no-store",
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
// Don’t hard-fail the whole page if options aren’t wired yet.
|
||||
// Roles tab can still function using pending-buckets.
|
||||
const txt = await res.text().catch(() => "");
|
||||
console.warn("options endpoint not ready:", res.status, txt);
|
||||
return;
|
||||
}
|
||||
|
||||
const json = (await res.json()) as MappingOptionsResponse;
|
||||
setMerchants(json.merchants ?? []);
|
||||
setCanonicalCategories(json.canonicalCategories ?? []);
|
||||
} catch (e) {
|
||||
console.warn("Failed to load mapping options:", e);
|
||||
} finally {
|
||||
setOptionsLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
loadOptions();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, []);
|
||||
|
||||
// Default merchant if not provided and merchants list exists
|
||||
useEffect(() => {
|
||||
if (!merchantId && merchants.length > 0) {
|
||||
setMerchantId(String(merchants[0].id));
|
||||
syncUrl({ merchantId: String(merchants[0].id) });
|
||||
}
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [merchants]);
|
||||
|
||||
// Core loader: depends on tab
|
||||
async function load() {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
if (tab === "roles") {
|
||||
// Existing endpoint you already have:
|
||||
// GET /api/admin/mapping/pending-buckets
|
||||
const res = await fetch(`${API_BASE_URL}/api/admin/mapping/pending-buckets`, {
|
||||
headers: { Accept: "application/json" },
|
||||
cache: "no-store",
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const text = await res.text().catch(() => "");
|
||||
@@ -100,40 +256,71 @@ export default function MappingAdminPage() {
|
||||
}
|
||||
|
||||
const data: PendingBucket[] = await res.json();
|
||||
setRows(data);
|
||||
} catch (e: any) {
|
||||
console.error(e);
|
||||
setError(e.message ?? "Failed to load pending buckets");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
setRoleBuckets(data);
|
||||
setRawRows([]);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// tab === "catalog"
|
||||
// EXPECTED new endpoint:
|
||||
// GET /api/admin/mapping/raw-categories?merchantId=4&platform=AR-15&q=...
|
||||
// returns rows with productCount + mapping state including canonicalCategoryId
|
||||
if (!merchantId) {
|
||||
setRawRows([]);
|
||||
setError("Pick a merchant to view catalog mappings.");
|
||||
return;
|
||||
}
|
||||
|
||||
const params = new URLSearchParams();
|
||||
params.set("merchantId", merchantId);
|
||||
if (platform?.trim()) params.set("platform", platform.trim());
|
||||
if (q?.trim()) params.set("q", q.trim());
|
||||
|
||||
const res = await fetch(
|
||||
`${API_BASE_URL}/api/admin/mapping/raw-categories?${params.toString()}`,
|
||||
{ headers: { Accept: "application/json" }, cache: "no-store" }
|
||||
);
|
||||
|
||||
if (!res.ok) {
|
||||
const text = await res.text().catch(() => "");
|
||||
throw new Error(
|
||||
`Catalog mapping endpoint not ready (${res.status})${text ? `: ${text}` : ""}`
|
||||
);
|
||||
}
|
||||
|
||||
const data: RawCategoryRow[] = await res.json();
|
||||
setRawRows(data);
|
||||
setRoleBuckets([]);
|
||||
} catch (e: any) {
|
||||
console.error(e);
|
||||
setError(e?.message ?? "Failed to load mapping data");
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}
|
||||
|
||||
// Load on mount + when tab changes
|
||||
useEffect(() => {
|
||||
load();
|
||||
}, []);
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [tab]);
|
||||
|
||||
// ===== Roles tab actions =====
|
||||
|
||||
const handleChangeRole = (idx: number, value: string) => {
|
||||
// Always store normalized kebab-case (defensive)
|
||||
const normalized = value
|
||||
? value.trim().toLowerCase().replace(/_/g, "-")
|
||||
: "";
|
||||
|
||||
setRows((prev) => {
|
||||
const normalized = value ? normalizeRole(value) : "";
|
||||
setRoleBuckets((prev) => {
|
||||
const next = [...prev];
|
||||
next[idx] = { ...next[idx], mappedPartRole: normalized || null };
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const handleSave = async (row: PendingBucket) => {
|
||||
const handleSaveRole = async (row: PendingBucket) => {
|
||||
if (!row.mappedPartRole) return;
|
||||
|
||||
const mapped = row.mappedPartRole
|
||||
.trim()
|
||||
.toLowerCase()
|
||||
.replace(/_/g, "-");
|
||||
const mapped = normalizeRole(row.mappedPartRole);
|
||||
|
||||
// Basic guard: prevent saving random roles from stale data
|
||||
const allowed = new Set<string>(PART_ROLE_OPTIONS as readonly string[]);
|
||||
if (!allowed.has(mapped)) {
|
||||
setError(
|
||||
@@ -142,11 +329,13 @@ export default function MappingAdminPage() {
|
||||
return;
|
||||
}
|
||||
|
||||
const key = `${row.merchantId}-${row.rawCategoryKey}`;
|
||||
const key = `roles-${row.merchantId}-${row.rawCategoryKey}`;
|
||||
try {
|
||||
setSavingKey(key);
|
||||
setError(null);
|
||||
|
||||
// Existing endpoint you already have:
|
||||
// POST /api/admin/mapping/apply
|
||||
const res = await fetch(`${API_BASE_URL}/api/admin/mapping/apply`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
@@ -164,8 +353,7 @@ export default function MappingAdminPage() {
|
||||
);
|
||||
}
|
||||
|
||||
// After save, remove this bucket from the list
|
||||
setRows((prev) =>
|
||||
setRoleBuckets((prev) =>
|
||||
prev.filter(
|
||||
(r) =>
|
||||
!(
|
||||
@@ -176,46 +364,228 @@ export default function MappingAdminPage() {
|
||||
);
|
||||
} catch (e: any) {
|
||||
console.error(e);
|
||||
setError(e.message ?? "Failed to save mapping");
|
||||
setError(e?.message ?? "Failed to save mapping");
|
||||
} finally {
|
||||
setSavingKey(null);
|
||||
}
|
||||
};
|
||||
|
||||
// ===== Catalog tab actions =====
|
||||
|
||||
const updateRawRow = (idx: number, patch: Partial<RawCategoryRow>) => {
|
||||
setRawRows((prev) => {
|
||||
const next = [...prev];
|
||||
next[idx] = { ...next[idx], ...patch };
|
||||
return next;
|
||||
});
|
||||
};
|
||||
|
||||
const handleSaveCatalog = async (row: RawCategoryRow) => {
|
||||
if (!merchantId) return;
|
||||
|
||||
const key = `catalog-${row.merchantId}-${row.rawCategoryKey}`;
|
||||
try {
|
||||
setSavingKey(key);
|
||||
setError(null);
|
||||
|
||||
// EXPECTED new endpoint:
|
||||
// POST /api/admin/mapping/upsert
|
||||
const res = await fetch(`${API_BASE_URL}/api/admin/mapping/upsert`, {
|
||||
method: "POST",
|
||||
headers: { "Content-Type": "application/json" },
|
||||
body: JSON.stringify({
|
||||
merchantId: row.merchantId,
|
||||
platform: row.platform ?? platform ?? null,
|
||||
rawCategory: row.rawCategoryKey,
|
||||
enabled: row.enabled ?? true,
|
||||
canonicalCategoryId: row.canonicalCategoryId ?? null,
|
||||
// do NOT overwrite part role here; backend should merge/partial update
|
||||
canonicalPartRole: null,
|
||||
}),
|
||||
});
|
||||
|
||||
if (!res.ok) {
|
||||
const text = await res.text().catch(() => "");
|
||||
throw new Error(
|
||||
`Failed to save catalog mapping (${res.status})${text ? `: ${text}` : ""}`
|
||||
);
|
||||
}
|
||||
|
||||
// Reload after save so we reflect the server’s truth.
|
||||
await load();
|
||||
} catch (e: any) {
|
||||
console.error(e);
|
||||
setError(e?.message ?? "Failed to save catalog mapping");
|
||||
} finally {
|
||||
setSavingKey(null);
|
||||
}
|
||||
};
|
||||
|
||||
const totals = useMemo(() => {
|
||||
if (tab === "roles") {
|
||||
return {
|
||||
buckets: roleBuckets.length,
|
||||
products: roleBuckets.reduce((s, r) => s + (r.productCount ?? 0), 0),
|
||||
};
|
||||
}
|
||||
return {
|
||||
buckets: rawRows.length,
|
||||
products: rawRows.reduce((s, r) => s + (r.productCount ?? 0), 0),
|
||||
};
|
||||
}, [tab, roleBuckets, rawRows]);
|
||||
|
||||
return (
|
||||
<main className="min-h-screen bg-black text-zinc-50">
|
||||
<div className="mx-auto max-w-6xl px-4 py-6">
|
||||
<h1 className="text-xl font-semibold tracking-tight">
|
||||
Bulk Mapping – Pending Categories
|
||||
</h1>
|
||||
<p className="mt-1 text-sm text-zinc-400">
|
||||
Bucketed by merchant + raw category. Map each bucket to a part role to
|
||||
clean up the builder catalog.
|
||||
</p>
|
||||
<div className="flex flex-col gap-3 sm:flex-row sm:items-end sm:justify-between">
|
||||
<div>
|
||||
<h1 className="text-xl font-semibold tracking-tight">Admin Mapping</h1>
|
||||
<p className="mt-1 text-sm text-zinc-400">
|
||||
Manage <span className="text-zinc-200">builder part roles</span> and{" "}
|
||||
<span className="text-zinc-200">catalog categories</span> without
|
||||
blending worlds.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
onClick={() => load()}
|
||||
className="rounded-md border border-zinc-700 bg-zinc-950/60 px-3 py-1.5 text-xs font-semibold text-zinc-100 hover:bg-zinc-900/60"
|
||||
>
|
||||
Refresh
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Tabs */}
|
||||
<div className="mt-4 flex items-center gap-2">
|
||||
<button
|
||||
onClick={() => {
|
||||
setTab("roles");
|
||||
syncUrl({ tab: "roles" });
|
||||
}}
|
||||
className={[
|
||||
"rounded-md px-3 py-1.5 text-xs font-semibold",
|
||||
tab === "roles"
|
||||
? "bg-amber-400 text-black"
|
||||
: "border border-zinc-700 bg-zinc-950/60 text-zinc-100 hover:bg-zinc-900/60",
|
||||
].join(" ")}
|
||||
>
|
||||
Builder Part Roles
|
||||
</button>
|
||||
|
||||
<button
|
||||
onClick={() => {
|
||||
setTab("catalog");
|
||||
syncUrl({ tab: "catalog" });
|
||||
}}
|
||||
className={[
|
||||
"rounded-md px-3 py-1.5 text-xs font-semibold",
|
||||
tab === "catalog"
|
||||
? "bg-amber-400 text-black"
|
||||
: "border border-zinc-700 bg-zinc-950/60 text-zinc-100 hover:bg-zinc-900/60",
|
||||
].join(" ")}
|
||||
>
|
||||
Catalog Categories
|
||||
</button>
|
||||
|
||||
<span className="ml-auto text-xs text-zinc-400">
|
||||
{totals.buckets} rows • {totals.products} products
|
||||
</span>
|
||||
</div>
|
||||
|
||||
{/* Filters (catalog tab only) */}
|
||||
{tab === "catalog" && (
|
||||
<section className="mt-4 rounded-lg border border-zinc-800 bg-zinc-950/80 p-3">
|
||||
<div className="grid grid-cols-1 gap-3 sm:grid-cols-3">
|
||||
<div>
|
||||
<label className="block text-[0.7rem] font-semibold uppercase tracking-[0.14em] text-zinc-500">
|
||||
Merchant
|
||||
</label>
|
||||
<select
|
||||
className="mt-1 w-full rounded-md border border-zinc-700 bg-zinc-950/80 px-2 py-2 text-xs text-zinc-100 outline-none focus:border-amber-400"
|
||||
value={merchantId}
|
||||
onChange={(e) => {
|
||||
setMerchantId(e.target.value);
|
||||
syncUrl({ merchantId: e.target.value });
|
||||
}}
|
||||
>
|
||||
<option value="">Select merchant…</option>
|
||||
{merchants.map((m) => (
|
||||
<option key={m.id} value={String(m.id)}>
|
||||
{m.name} (#{m.id})
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
{optionsLoading && (
|
||||
<p className="mt-1 text-[0.7rem] text-zinc-500">Loading merchants…</p>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-[0.7rem] font-semibold uppercase tracking-[0.14em] text-zinc-500">
|
||||
Platform
|
||||
</label>
|
||||
<input
|
||||
className="mt-1 w-full rounded-md border border-zinc-700 bg-zinc-950/80 px-2 py-2 text-xs text-zinc-100 outline-none focus:border-amber-400"
|
||||
value={platform}
|
||||
onChange={(e) => {
|
||||
setPlatform(e.target.value);
|
||||
syncUrl({ platform: e.target.value });
|
||||
}}
|
||||
placeholder="AR-15"
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<label className="block text-[0.7rem] font-semibold uppercase tracking-[0.14em] text-zinc-500">
|
||||
Search raw categories
|
||||
</label>
|
||||
<div className="mt-1 flex gap-2">
|
||||
<input
|
||||
className="w-full rounded-md border border-zinc-700 bg-zinc-950/80 px-2 py-2 text-xs text-zinc-100 outline-none focus:border-amber-400"
|
||||
value={q}
|
||||
onChange={(e) => {
|
||||
setQ(e.target.value);
|
||||
syncUrl({ q: e.target.value });
|
||||
}}
|
||||
placeholder="e.g. Charging Handles"
|
||||
/>
|
||||
<button
|
||||
onClick={() => load()}
|
||||
className="rounded-md bg-emerald-500 px-3 py-2 text-xs font-semibold text-black"
|
||||
>
|
||||
Search
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{loading && (
|
||||
<p className="mt-4 text-sm text-zinc-400">Loading pending buckets…</p>
|
||||
<p className="mt-4 text-sm text-zinc-400">Loading…</p>
|
||||
)}
|
||||
|
||||
{error && (
|
||||
<p className="mt-4 text-sm text-red-400">Error: {error}</p>
|
||||
)}
|
||||
|
||||
{!loading && rows.length === 0 && !error && (
|
||||
{/* ROLES TAB TABLE */}
|
||||
{!loading && tab === "roles" && !error && roleBuckets.length === 0 && (
|
||||
<p className="mt-4 text-sm text-emerald-400">
|
||||
No pending mapping buckets 🎉
|
||||
No pending role buckets 🎉
|
||||
</p>
|
||||
)}
|
||||
|
||||
{!loading && rows.length > 0 && (
|
||||
{!loading && tab === "roles" && roleBuckets.length > 0 && (
|
||||
<section className="mt-4 rounded-lg border border-zinc-800 bg-zinc-950/80 p-3">
|
||||
<div className="mb-2 flex items-center justify-between">
|
||||
<h2 className="text-xs font-semibold uppercase tracking-[0.14em] text-zinc-500">
|
||||
Pending Buckets
|
||||
Pending Part Role Buckets
|
||||
</h2>
|
||||
<span className="text-xs text-zinc-400">
|
||||
{rows.length} buckets •{" "}
|
||||
{rows.reduce((s, r) => s + r.productCount, 0)} products
|
||||
{totals.buckets} buckets • {totals.products} products
|
||||
</span>
|
||||
</div>
|
||||
|
||||
@@ -223,26 +593,17 @@ export default function MappingAdminPage() {
|
||||
<table className="min-w-full text-xs">
|
||||
<thead>
|
||||
<tr className="border-b border-zinc-800 bg-zinc-900/60">
|
||||
<th className="px-2 py-1 text-left text-zinc-400">
|
||||
Merchant
|
||||
</th>
|
||||
<th className="px-2 py-1 text-left text-zinc-400">
|
||||
Raw Category
|
||||
</th>
|
||||
<th className="px-2 py-1 text-left text-zinc-400">
|
||||
Products
|
||||
</th>
|
||||
<th className="px-2 py-1 text-left text-zinc-400">
|
||||
Part Role
|
||||
</th>
|
||||
<th className="px-2 py-1 text-right text-zinc-400">
|
||||
Action
|
||||
</th>
|
||||
<th className="px-2 py-1 text-left text-zinc-400">Merchant</th>
|
||||
<th className="px-2 py-1 text-left text-zinc-400">Raw Category</th>
|
||||
<th className="px-2 py-1 text-left text-zinc-400">Products</th>
|
||||
<th className="px-2 py-1 text-left text-zinc-400">Part Role</th>
|
||||
<th className="px-2 py-1 text-right text-zinc-400">Action</th>
|
||||
</tr>
|
||||
</thead>
|
||||
|
||||
<tbody>
|
||||
{rows.map((row, idx) => {
|
||||
const rowKey = `${row.merchantId}-${row.rawCategoryKey}`;
|
||||
{roleBuckets.map((row, idx) => {
|
||||
const rowKey = `roles-${row.merchantId}-${row.rawCategoryKey}`;
|
||||
const isSaving = savingKey === rowKey;
|
||||
|
||||
return (
|
||||
@@ -250,25 +611,17 @@ export default function MappingAdminPage() {
|
||||
key={rowKey}
|
||||
className="border-b border-zinc-900 hover:bg-zinc-900/40"
|
||||
>
|
||||
<td className="px-2 py-1 text-zinc-100">
|
||||
{row.merchantName}
|
||||
</td>
|
||||
<td className="px-2 py-1 text-zinc-300">
|
||||
{row.rawCategoryKey}
|
||||
</td>
|
||||
<td className="px-2 py-1 text-zinc-200">
|
||||
{row.productCount}
|
||||
</td>
|
||||
<td className="px-2 py-1 text-zinc-100">{row.merchantName}</td>
|
||||
<td className="px-2 py-1 text-zinc-300">{row.rawCategoryKey}</td>
|
||||
<td className="px-2 py-1 text-zinc-200">{row.productCount}</td>
|
||||
<td className="px-2 py-1 text-zinc-100">
|
||||
<select
|
||||
className="w-full rounded-md border border-zinc-700 bg-zinc-950/80 px-2 py-1 text-xs text-zinc-100 outline-none focus:border-amber-400"
|
||||
value={row.mappedPartRole ?? ""}
|
||||
onChange={(e) =>
|
||||
handleChangeRole(idx, e.target.value)
|
||||
}
|
||||
onChange={(e) => handleChangeRole(idx, e.target.value)}
|
||||
>
|
||||
<option value="">Select part role…</option>
|
||||
{options.map((opt) => (
|
||||
{roleOptions.map((opt) => (
|
||||
<option key={opt.value} value={opt.value}>
|
||||
{opt.label} ({opt.value})
|
||||
</option>
|
||||
@@ -277,7 +630,7 @@ export default function MappingAdminPage() {
|
||||
</td>
|
||||
<td className="px-2 py-1 text-right">
|
||||
<button
|
||||
onClick={() => handleSave(row)}
|
||||
onClick={() => handleSaveRole(row)}
|
||||
disabled={!row.mappedPartRole || isSaving}
|
||||
className="rounded-md bg-emerald-500 px-3 py-1 text-[0.7rem] font-semibold text-black disabled:cursor-not-allowed disabled:bg-zinc-700"
|
||||
>
|
||||
@@ -292,6 +645,109 @@ export default function MappingAdminPage() {
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
|
||||
{/* CATALOG TAB TABLE */}
|
||||
{!loading && tab === "catalog" && !error && rawRows.length === 0 && (
|
||||
<p className="mt-4 text-sm text-zinc-400">
|
||||
No rows loaded. Pick a merchant + click Search.
|
||||
</p>
|
||||
)}
|
||||
|
||||
{!loading && tab === "catalog" && rawRows.length > 0 && (
|
||||
<section className="mt-4 rounded-lg border border-zinc-800 bg-zinc-950/80 p-3">
|
||||
<div className="mb-2 flex items-center justify-between">
|
||||
<h2 className="text-xs font-semibold uppercase tracking-[0.14em] text-zinc-500">
|
||||
Catalog Category Mapping
|
||||
</h2>
|
||||
<span className="text-xs text-zinc-400">
|
||||
{totals.buckets} rows • {totals.products} products
|
||||
</span>
|
||||
</div>
|
||||
|
||||
<div className="mt-1 overflow-x-auto">
|
||||
<table className="min-w-full text-xs">
|
||||
<thead>
|
||||
<tr className="border-b border-zinc-800 bg-zinc-900/60">
|
||||
<th className="px-2 py-1 text-left text-zinc-400">Raw Category</th>
|
||||
<th className="px-2 py-1 text-left text-zinc-400">Products</th>
|
||||
<th className="px-2 py-1 text-left text-zinc-400">Canonical Category</th>
|
||||
<th className="px-2 py-1 text-left text-zinc-400">Enabled</th>
|
||||
<th className="px-2 py-1 text-right text-zinc-400">Action</th>
|
||||
</tr>
|
||||
</thead>
|
||||
|
||||
<tbody>
|
||||
{rawRows.map((row, idx) => {
|
||||
const rowKey = `catalog-${row.merchantId}-${row.rawCategoryKey}`;
|
||||
const isSaving = savingKey === rowKey;
|
||||
|
||||
const currentCategoryId =
|
||||
row.canonicalCategoryId != null ? String(row.canonicalCategoryId) : "";
|
||||
|
||||
return (
|
||||
<tr
|
||||
key={rowKey}
|
||||
className="border-b border-zinc-900 hover:bg-zinc-900/40"
|
||||
>
|
||||
<td className="px-2 py-1 text-zinc-300">{row.rawCategoryKey}</td>
|
||||
<td className="px-2 py-1 text-zinc-200">{row.productCount}</td>
|
||||
|
||||
<td className="px-2 py-1 text-zinc-100">
|
||||
<select
|
||||
className="w-full rounded-md border border-zinc-700 bg-zinc-950/80 px-2 py-1 text-xs text-zinc-100 outline-none focus:border-amber-400"
|
||||
value={currentCategoryId}
|
||||
onChange={(e) => {
|
||||
const id = safeNum(e.target.value);
|
||||
const opt = canonicalCategories.find((c) => c.id === id);
|
||||
updateRawRow(idx, {
|
||||
canonicalCategoryId: id,
|
||||
canonicalCategoryName: opt?.name ?? null,
|
||||
});
|
||||
}}
|
||||
>
|
||||
<option value="">Select canonical category…</option>
|
||||
{canonicalCategories.map((c) => (
|
||||
<option key={c.id} value={String(c.id)}>
|
||||
{c.name}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
|
||||
{canonicalCategories.length === 0 && (
|
||||
<p className="mt-1 text-[0.7rem] text-zinc-500">
|
||||
No canonical categories loaded (options endpoint may not be wired yet).
|
||||
</p>
|
||||
)}
|
||||
</td>
|
||||
|
||||
<td className="px-2 py-1 text-zinc-100">
|
||||
<label className="inline-flex items-center gap-2">
|
||||
<input
|
||||
type="checkbox"
|
||||
checked={row.enabled ?? true}
|
||||
onChange={(e) => updateRawRow(idx, { enabled: e.target.checked })}
|
||||
/>
|
||||
<span className="text-zinc-300">Enabled</span>
|
||||
</label>
|
||||
</td>
|
||||
|
||||
<td className="px-2 py-1 text-right">
|
||||
<button
|
||||
onClick={() => handleSaveCatalog(row)}
|
||||
disabled={isSaving}
|
||||
className="rounded-md bg-emerald-500 px-3 py-1 text-[0.7rem] font-semibold text-black disabled:cursor-not-allowed disabled:bg-zinc-700"
|
||||
>
|
||||
{isSaving ? "Saving…" : "Save"}
|
||||
</button>
|
||||
</td>
|
||||
</tr>
|
||||
);
|
||||
})}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</section>
|
||||
)}
|
||||
</div>
|
||||
</main>
|
||||
);
|
||||
|
||||
Reference in New Issue
Block a user