From f10dc5148fae0ff8fa6cd7e8585b432f819961d6 Mon Sep 17 00:00:00 2001 From: makearmy Date: Sat, 27 Sep 2025 09:21:08 -0400 Subject: [PATCH] dropdown fixes --- app/my/rigs/RigBuilderClient.tsx | 197 +++++++++++++++---------------- 1 file changed, 98 insertions(+), 99 deletions(-) diff --git a/app/my/rigs/RigBuilderClient.tsx b/app/my/rigs/RigBuilderClient.tsx index 92bed195..037197d3 100644 --- a/app/my/rigs/RigBuilderClient.tsx +++ b/app/my/rigs/RigBuilderClient.tsx @@ -6,14 +6,14 @@ import { z } from "zod"; import { zodResolver } from "@hookform/resolvers/zod"; function handleAuthError(err: any): boolean { - const status = (err as any)?.status; - const code = (err as any)?.code; - if (status === 401 || code === "TOKEN_EXPIRED") { - const next = encodeURIComponent(window.location.pathname + window.location.search); - window.location.assign(`/auth/sign-in?next=${next}`); - return true; - } - return false; + const status = (err as any)?.status; + const code = (err as any)?.code; + if (status === 401 || code === "TOKEN_EXPIRED") { + const next = encodeURIComponent(window.location.pathname + window.location.search); + window.location.assign(`/auth/sign-in?next=${next}`); + return true; + } + return false; } import { useToast } from "@/hooks/use-toast"; @@ -47,40 +47,43 @@ type RigRow = { id: number; name: string; rig_type: number | string | null; - rig_type_name?: string; // convenience when our API includes name + rig_type_name?: string; }; // ───────────────────────────────────────────────────────────── // Helpers // ───────────────────────────────────────────────────────────── -const RIG_TARGET_MAP: Record = { - fiber: "settings_fiber", - uv: "settings_uv", - co2_galvo: "settings_co2gal", - co2_gantry: "settings_co2gan", -}; - - // Builder rig_type -> settings form target expected by options API const SETTINGS_TARGET_MAP: Record = { - fiber: "settings_fiber", - co2_gantry: "settings_co2gan", - co2_galvo: "settings_co2gal", - uv: "settings_uv", + fiber: "settings_fiber", + co2_gantry: "settings_co2gan", + co2_galvo: "settings_co2gal", + uv: "settings_uv", }; + async function apiJson(url: string, init?: RequestInit): Promise { const res = await fetch(url, { ...init, headers: { "Content-Type": "application/json", ...(init?.headers || {}) }, - cache: "no-store", - credentials: "include", + cache: "no-store", + credentials: "include", }); - if (!res.ok) { - const txt = await res.text(); - throw new Error(txt || res.statusText); + const txt = await res.text().catch(() => ""); + if (res.ok) { + try { return JSON.parse(txt) as T; } catch { return undefined as T; } } - return res.json() as Promise; + // try to unwrap nested error format + let body: any = undefined; + try { body = JSON.parse(txt); } catch {} + if (body && typeof body.error === "string") { + try { body = JSON.parse(body.error); } catch {} + } + const err: any = new Error(`HTTP ${res.status} for ${url}`); + err.status = res.status; + err.code = body?.errors?.[0]?.extensions?.code || body?.code; + err.body = body ?? txt; + throw err; } const schema = z.object({ @@ -88,7 +91,6 @@ const schema = z.object({ rig_type: z.string().min(1, "Pick a rig type"), laser_source: z.string().optional().nullable(), laser_software: z.string().optional().nullable(), - // exactly one of focus OR scan (by rig type). We let the form send nulls. laser_focus_lens: z.string().optional().nullable(), laser_scan_lens: z.string().optional().nullable(), laser_scan_lens_apt: z.string().optional().nullable(), @@ -112,6 +114,8 @@ export default function RigBuilderClient() { // Options that depend on rig type const [sourceOpts, setSourceOpts] = useState([]); const [softwareOpts, setSoftwareOpts] = useState([]); + const [scanLensOpts, setScanLensOpts] = useState([]); + const [focusLensOpts, setFocusLensOpts] = useState([]); // Load laser software list once (independent of rig type) useEffect(() => { @@ -124,14 +128,13 @@ export default function RigBuilderClient() { setSoftwareOpts(sw); } catch (e: any) { if (!handleAuthError(e)) { - console.error('[laser_software] load failed:', e); + console.error("[laser_software] load failed:", e); setSoftwareOpts([]); } } })(); }, []); - // Form const { register, @@ -156,10 +159,8 @@ export default function RigBuilderClient() { }); const rigTypeVal = watch("rig_type"); - const rigTarget = RIG_TARGET_MAP[rigTypeVal ?? ""] || ""; - - - const settingsTarget = SETTINGS_TARGET_MAP[rigTypeVal ?? ""] ?? "";const isGantry = rigTypeVal === "co2_gantry"; + const settingsTarget = SETTINGS_TARGET_MAP[rigTypeVal ?? ""] ?? ""; + const isGantry = rigTypeVal === "co2_gantry"; const isScan = rigTypeVal === "fiber" || rigTypeVal === "uv" || rigTypeVal === "co2_galvo"; // Initial loads @@ -167,23 +168,25 @@ export default function RigBuilderClient() { (async () => { try { const [typesRes, rigsRes] = await Promise.all([ - apiJson<{ data: { id: number; name: string }[] }>("/api/options/rig_type"), - apiJson<{ data: RigRow[] }>("/api/my/rigs"), + apiJson<{ data: { id: number; name: string }[] }>(`/api/options/rig_type`), + apiJson<{ data: RigRow[] }>(`/api/my/rigs`), ]); - setRigTypes(typesRes.data); - setRigs(rigsRes.data); + setRigTypes(typesRes.data ?? []); + setRigs(rigsRes.data ?? []); } catch (e: any) { - console.warn("[rigs] initial load failed:", e?.message || e); - toast({ - title: "Failed to load", - description: "Could not load your rigs or rig types.", - variant: "destructive", - }); + if (!handleAuthError(e)) { + console.warn("[rigs] initial load failed:", e?.message || e); + toast({ + title: "Failed to load", + description: "Could not load your rigs or rig types.", + variant: "destructive", + }); + } } })(); }, [toast]); - // Load static-ish options that depend on rig type + // Load options that depend on rig type useEffect(() => { // when rig type changes, clear type-specific fields setValue("laser_focus_lens", null); @@ -191,35 +194,33 @@ export default function RigBuilderClient() { setValue("laser_scan_lens_apt", null); setValue("laser_scan_lens_exp", null); - if (!rigTarget) { + if (!settingsTarget) { setSourceOpts([]); setScanLensOpts([]); + setFocusLensOpts([]); return; } (async () => { try { - // laser sources (by target) - const src = await apiJson<{ data: Option[] }>(`/api/options/laser_source?target=${settingsTarget}`); - setSourceOpts(src.data ?? []); - } catch { + // LASER sources by target (matches anonymous form targets) + const srcJson = await apiJson<{ data: Option[] }>( + `/api/options/laser_source?target=${encodeURIComponent(settingsTarget)}` + ); + setSourceOpts(srcJson.data ?? []); + } catch (e: any) { + if (!handleAuthError(e)) console.error("[laser_source] load failed:", e); setSourceOpts([]); } - try { - // software (generic list; if you have target-aware, swap the endpoint) - const soft = await apiJson<{ data: Option[] }>(`/api/options/laser_soft`); - setSoftwareOpts(soft.data ?? []); - } catch { - setSoftwareOpts([]); - } - if (isScan) { try { - const lenses = await apiJson<{ data: Option[] }>(`/api/options/lens?target=${settingsTarget}`); - // server already formats "110x110mm (F160)"; keep but ensure scroll - setScanLensOpts(lenses.data ?? []); - } catch { + const lensesJson = await apiJson<{ data: Option[] }>( + `/api/options/lens?target=${encodeURIComponent(settingsTarget)}` + ); + setScanLensOpts(lensesJson.data ?? []); + } catch (e: any) { + if (!handleAuthError(e)) console.error("[scan_lens] load failed:", e); setScanLensOpts([]); } } else { @@ -228,24 +229,23 @@ export default function RigBuilderClient() { if (isGantry) { try { - // focus lenses are just name strings - const focus = await apiJson<{ data: Option[] }>(`/api/options/laser_focus_lens`); - setFocusLensOpts(focus.data ?? []); - } catch { + const focusJson = await apiJson<{ data: Option[] }>(`/api/options/laser_focus_lens`); + setFocusLensOpts(focusJson.data ?? []); + } catch (e: any) { + if (!handleAuthError(e)) console.error("[focus_lens] load failed:", e); setFocusLensOpts([]); } } else { setFocusLensOpts([]); } })(); - }, [rigTarget, isScan, isGantry, setValue]); + }, [settingsTarget, isScan, isGantry, setValue]); async function onSubmit(values: FormValues) { try { - // shape for API const payload = { name: values.name, - rig_type: rigTypes.find((t) => String(t.name) === String(values.rig_type))?.id ?? values.rig_type, // allow id or name + rig_type: rigTypes.find((t) => String(t.name) === String(values.rig_type))?.id ?? values.rig_type, laser_source: values.laser_source || null, laser_software: values.laser_software || null, laser_focus_lens: isGantry ? values.laser_focus_lens || null : null, @@ -255,18 +255,16 @@ export default function RigBuilderClient() { notes: values.notes || null, }; - await apiJson("/api/my/rigs", { + await apiJson(`/api/my/rigs`, { method: "POST", body: JSON.stringify(payload), }); toast({ title: "Rig saved", description: "Your rig was added." }); - // refresh list - const rigsRes = await apiJson<{ data: RigRow[] }>("/api/my/rigs"); - setRigs(rigsRes.data); + const rigsRes = await apiJson<{ data: RigRow[] }>(`/api/my/rigs`); + setRigs(rigsRes.data ?? []); - // keep rig type but clear the rest so it's quick to add another reset({ name: "", rig_type: values.rig_type, @@ -279,10 +277,14 @@ export default function RigBuilderClient() { notes: "", }); } catch (e: any) { + if (handleAuthError(e)) return; const message = (() => { try { - const j = JSON.parse(e?.message || "{}"); - if (j?.errors) return `Directus error ${j.errors?.[0]?.extensions?.code || ""}: ${j.errors?.[0]?.message || "Failed"}`; + const j = typeof e?.body === "object" ? e.body : JSON.parse(e?.message || "{}"); + if (j?.errors) { + const first = j.errors[0]; + return `${first?.extensions?.code || "API"}: ${first?.message || "Failed"}`; + } } catch {} return e?.message || "Failed to save rig"; })(); @@ -301,6 +303,7 @@ export default function RigBuilderClient() { await apiJson(`/api/my/rigs/${id}`, { method: "DELETE" }); setRigs((prev) => prev.filter((r) => r.id !== id)); } catch (e: any) { + if (handleAuthError(e)) return; toast({ title: "Delete failed", description: e?.message || "Could not delete rig.", @@ -310,8 +313,12 @@ export default function RigBuilderClient() { } const rigTypeItems = useMemo( - () => rigTypes.map((t) => ({ value: String(t.name), label: String(t.name).replaceAll("_", " ") })), - [rigTypes] + () => + rigTypes.map((t) => ({ + value: String(t.name), + label: String(t.name).replaceAll("_", " "), + })), + [rigTypes] ); // ───────────────────────────────────────────────────────────── @@ -335,15 +342,11 @@ export default function RigBuilderClient() { {/* Rig type */}
- setValue("rig_type", v)}> - {/* add scroll so big lists are usable */} - + {rigTypeItems.map((rt) => ( {rt.label} @@ -353,7 +356,7 @@ export default function RigBuilderClient() {
- {/* Laser Source (optional) */} + {/* LASER Source (optional) */}
- {/* Laser Software (optional) */} + {/* LASER Software (optional) */}