added v2 RigSwitcher and Builder

This commit is contained in:
makearmy 2025-09-29 15:34:49 -04:00
parent 63ddd29393
commit 0cf4661264
5 changed files with 352 additions and 250 deletions

115
app/api/rigs/route.ts Normal file
View file

@ -0,0 +1,115 @@
// app/api/my/rigs/route.ts
import { NextResponse } from "next/server";
import { dxGET, dxPOST, dxDELETE } from "@/lib/directus";
import { requireBearer } from "@/app/api/_lib/auth";
export const runtime = "nodejs";
function bad(msg: string, code = 400) {
return NextResponse.json({ error: msg }, { status: code });
}
export async function GET(req: Request) {
try {
const bearer = requireBearer(req);
const me = await dxGET<{ id: string }>("/users/me?fields=id", bearer);
const q = new URL(req.url).searchParams;
const limit = Math.min(parseInt(q.get("limit") || "50", 10), 100);
const fields = [
"id",
"name",
"notes",
"rig_type.id",
"rig_type.name",
"laser_source.submission_id",
"laser_source.make",
"laser_source.model",
"laser_scan_lens.id",
"laser_scan_lens.field_size",
"laser_scan_lens.focal_length",
"laser_focus_lens.id",
"laser_focus_lens.name",
"laser_software.id",
"laser_software.name",
"date_created",
"date_updated",
].join(",");
const path =
`/items/user_rigs?filter[owner][_eq]=${encodeURIComponent(me.id)}` +
`&fields=${encodeURIComponent(fields)}&sort=-date_updated&limit=${limit}`;
const res = await dxGET<any>(path, bearer);
return NextResponse.json(res?.data ?? []);
} catch (e: any) {
return bad(e?.message || "Failed to load rigs", e?.status || 500);
}
}
export async function POST(req: Request) {
try {
const bearer = requireBearer(req);
const body = await req.json().catch(() => ({}));
const name = (body?.name || "").trim();
const rig_type = body?.rig_type; // id
const laser_source = body?.laser_source; // submission_id
const laser_scan_lens = body?.laser_scan_lens || null;
const laser_focus_lens = body?.laser_focus_lens || null;
const laser_software = body?.laser_software || null;
const notes = (body?.notes || "").trim();
if (!name) return bad("Missing: name");
if (!rig_type) return bad("Missing: rig_type");
if (!laser_source) return bad("Missing: laser_source");
// Derive owner from authd user; ignore any spoofed owner in body
const me = await dxGET<{ id: string }>("/users/me?fields=id", bearer);
// Only set one lens m2o depending on rig type on the client; server tolerates both null.
const payload: any = {
owner: me.id,
name,
rig_type,
laser_source,
laser_scan_lens,
laser_focus_lens,
laser_software,
notes,
};
const res = await dxPOST<{ data: { id: string } }>(
"/items/user_rigs",
bearer,
payload
);
return NextResponse.json({ ok: true, id: String(res?.data?.id) });
} catch (e: any) {
return bad(e?.message || "Failed to create rig", e?.status || 500);
}
}
export async function DELETE(req: Request) {
try {
const bearer = requireBearer(req);
const url = new URL(req.url);
const id = url.searchParams.get("id");
if (!id) return bad("Missing: id");
// Hard-guard: ensure the rig belongs to the current user
const me = await dxGET<{ id: string }>("/users/me?fields=id", bearer);
const rig = await dxGET<any>(
`/items/user_rigs/${encodeURIComponent(id)}?fields=id,owner`,
bearer
);
if (!rig || String(rig.owner) !== String(me.id)) {
return bad("Not your rig", 403);
}
await dxDELETE(`/items/user_rigs/${encodeURIComponent(id)}`, bearer);
return NextResponse.json({ ok: true });
} catch (e: any) {
return bad(e?.message || "Failed to delete rig", e?.status || 500);
}
}

View file

@ -1,140 +1,215 @@
// app/rigs/RigsListClient.tsx
"use client";
import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { useToast } from "@/hooks/use-toast";
import { useEffect, useMemo, useState } from "react";
import { useRouter } from "next/navigation";
type RigRow = {
id: number | string;
name: string;
rig_type_name?: string | null;
};
type Opt = { id: string | number; label: string };
async function apiJson<T>(url: string, init?: RequestInit): Promise<T> {
const res = await fetch(url, {
...init,
headers: {
Accept: "application/json",
...(init?.headers || {}),
},
credentials: "include",
cache: "no-store",
});
const API = (process.env.NEXT_PUBLIC_API_BASE_URL || "").replace(/\/$/, "");
const txt = await res.text().catch(() => "");
if (res.ok) {
try {
return (txt ? JSON.parse(txt) : ({} as any)) as T;
} catch {
return {} as T;
}
}
function useOptions(kind: "user_rig_type" | "laser_software" | "laser_source" | "lens", targetKey?: string) {
const [opts, setOpts] = useState<Opt[]>([]);
const [loading, setLoading] = useState(false);
let body: any = null;
try { body = txt ? JSON.parse(txt) : null; } catch {}
const message = body?.error || body?.message || txt || `HTTP ${res.status} for ${url}`;
useEffect(() => {
let alive = true;
setLoading(true);
// If unauthorized, send to sign-in (new flow always lands on /portal)
if (res.status === 401 && typeof window !== "undefined") {
window.location.assign("/auth/sign-in");
}
(async () => {
let url = "";
let normalize = (rows: any[]): Opt[] => rows.map(r => ({ id: String(r.id ?? r.submission_id), label: String(r.name ?? r.label ?? r.title ?? r.model ?? r.id) }));
if (kind === "user_rig_type") {
url = `${API}/items/user_rig_type?fields=id,name&sort=sort`;
} else if (kind === "laser_software") {
url = `${API}/items/laser_software?fields=id,name&limit=1000&sort=name`;
} else if (kind === "laser_source") {
// fetch all sources; client filter by nm band from targetKey
url = `${API}/items/laser_source?fields=submission_id,make,model,nm&limit=2000&sort=make,model`;
const parseNum = (v: any) => {
if (v == null) return null;
const m = String(v).match(/(\d+(\.\d+)?)/);
return m ? Number(m[1]) : null;
};
const nmRange = (t?: string | null): [number, number] | null => {
if (!t) return null;
const s = t.toLowerCase();
if (s.includes("fiber")) return [1000, 9000];
if (s.includes("uv")) return [300, 400];
if (s.includes("gantry") || s.includes("co2 gantry") || s.includes("co₂ gantry")) return [10000, 11000];
if (s.includes("galvo") || s.includes("co2 galvo") || s.includes("co₂ galvo")) return [10000, 11000];
return null;
};
const range = nmRange(targetKey);
normalize = (rows) => {
const filtered = range
? rows.filter((r: any) => {
const nm = parseNum(r.nm);
return nm != null && nm >= range[0] && nm <= range[1];
})
: rows;
return filtered.map((r: any) => ({
id: String(r.submission_id),
label: [r.make, r.model].filter(Boolean).join(" ") || String(r.submission_id),
}));
};
} else if (kind === "lens") {
if (targetKey && targetKey.toLowerCase().includes("gantry")) {
url = `${API}/items/laser_focus_lens?fields=id,name&limit=1000&sort=name`;
} else {
url = `${API}/items/laser_scan_lens?fields=id,field_size,focal_length&limit=1000`;
normalize = (rows) => {
const toNum = (v: any) => {
const m = String(v ?? "").match(/-?\d+(\.\d+)?/);
return m ? parseFloat(m[0]) : Number.POSITIVE_INFINITY;
};
return [...rows]
.sort((a, b) => toNum(a.focal_length) - toNum(b.focal_length))
.map((r) => ({
id: String(r.id),
label: [r.field_size && `${r.field_size} mm`, r.focal_length && `${r.focal_length} mm`].filter(Boolean).join(" — ") || String(r.id),
}));
};
}
}
const err: any = new Error(message);
err.status = res.status;
err.body = body ?? txt;
throw err;
const res = await fetch(url, { credentials: "include", cache: "no-store" });
const json = await res.json();
const rows = json?.data ?? [];
const mapped = normalize(rows);
if (alive) setOpts(mapped);
})()
.catch(() => alive && setOpts([]))
.finally(() => alive && setLoading(false));
return () => {
alive = false;
};
}, [kind, targetKey]);
return { opts, loading };
}
export default function RigsListClient() {
const { toast } = useToast();
const [rigs, setRigs] = useState<RigRow[] | null>(null);
const [loading, setLoading] = useState<boolean>(true);
const [err, setErr] = useState<string | null>(null);
const [deleting, setDeleting] = useState<Record<string | number, boolean>>({});
export default function RigBuilderClient() {
const router = useRouter();
const [name, setName] = useState("");
const [notes, setNotes] = useState("");
const [rigType, setRigType] = useState<string>("");
const [laserSource, setLaserSource] = useState<string>("");
const [scanLens, setScanLens] = useState<string>("");
const [focusLens, setFocusLens] = useState<string>("");
const [software, setSoftware] = useState<string>("");
// Load all rigs for the current user
useEffect(() => {
(async () => {
try {
setLoading(true);
setErr(null);
const j = await apiJson<{ data: RigRow[] }>("/api/my/rigs");
setRigs(j?.data ?? []);
} catch (e: any) {
setErr(e?.message || "Failed to load rigs");
} finally {
setLoading(false);
}
})();
}, []);
const rigTypes = useOptions("user_rig_type");
const targetKey = useMemo(() => {
const rt = rigTypes.opts.find(o => String(o.id) === String(rigType))?.label || "";
return rt;
}, [rigTypes.opts, rigType]);
async function onDelete(id: string | number) {
if (!confirm("Delete this rig?")) return;
try {
setDeleting((d) => ({ ...d, [id]: true }));
await apiJson(`/api/my/rigs/${id}`, { method: "DELETE" });
setRigs((prev) => (prev ? prev.filter((r) => r.id !== id) : prev));
toast({ title: "Rig deleted" });
} catch (e: any) {
toast({
title: "Delete failed",
description: e?.message || "Could not delete rig.",
variant: "destructive",
});
} finally {
setDeleting((d) => {
const copy = { ...d };
delete copy[id];
return copy;
});
const sources = useOptions("laser_source", targetKey);
const lens = useOptions("lens", targetKey);
const softwares = useOptions("laser_software");
const isGantry = (targetKey || "").toLowerCase().includes("gantry");
async function onSubmit(e: React.FormEvent) {
e.preventDefault();
const body: any = {
name,
rig_type: rigType ? Number(rigType) : null,
laser_source: laserSource ? Number(laserSource) : null,
notes: notes || "",
laser_software: software ? Number(software) : null,
};
if (isGantry) {
body.laser_focus_lens = focusLens ? Number(focusLens) : null;
body.laser_scan_lens = null;
} else {
body.laser_scan_lens = scanLens ? Number(scanLens) : null;
body.laser_focus_lens = null;
}
}
if (loading) {
return (
<div className="rounded-md border p-4 text-sm opacity-70">
Loading your rigs
</div>
);
}
if (err) {
return (
<div className="rounded-md border border-red-300 bg-red-50 p-4 text-sm text-red-700">
{err}
</div>
);
const res = await fetch("/api/my/rigs", {
method: "POST",
headers: { "Content-Type": "application/json" },
credentials: "include",
body: JSON.stringify(body),
});
const j = await res.json().catch(() => ({}));
if (!res.ok) {
alert(j?.error || "Failed to create rig");
return;
}
// Go back to list tab
router.replace("/portal/rigs?t=my", { scroll: false });
router.refresh();
}
return (
<div className="space-y-3">
<div className="divide-y divide-border rounded-md border">
{(!rigs || rigs.length === 0) && (
<div className="p-4 text-sm opacity-70">No rigs yet.</div>
<form onSubmit={onSubmit} className="space-y-4 max-w-xl">
<div>
<label className="block text-sm mb-1">
Rig Name <span className="text-red-600">*</span>
</label>
<input className="w-full border rounded px-2 py-1" value={name} onChange={e => setName(e.target.value)} required />
</div>
<div className="grid sm:grid-cols-2 gap-3">
<div>
<label className="block text-sm mb-1">
Rig Type <span className="text-red-600">*</span>
</label>
<select className="w-full border rounded px-2 py-1" value={rigType} onChange={e => setRigType(e.target.value)} required>
<option value="">{rigTypes.loading ? "Loading…" : "—"}</option>
{rigTypes.opts.map(o => <option key={o.id} value={o.id}>{o.label}</option>)}
</select>
</div>
<div>
<label className="block text-sm mb-1">
Laser Source <span className="text-red-600">*</span>
</label>
<select className="w-full border rounded px-2 py-1" value={laserSource} onChange={e => setLaserSource(e.target.value)} required>
<option value="">{sources.loading ? "Loading…" : "—"}</option>
{sources.opts.map(o => <option key={o.id} value={o.id}>{o.label}</option>)}
</select>
</div>
</div>
{/* Lens (focus for gantry, scan for others) */}
{isGantry ? (
<div>
<label className="block text-sm mb-1">Focus Lens</label>
<select className="w-full border rounded px-2 py-1" value={focusLens} onChange={e => setFocusLens(e.target.value)}>
<option value="">{lens.loading ? "Loading…" : "—"}</option>
{lens.opts.map(o => <option key={o.id} value={o.id}>{o.label}</option>)}
</select>
</div>
) : (
<div>
<label className="block text-sm mb-1">Scan Lens</label>
<select className="w-full border rounded px-2 py-1" value={scanLens} onChange={e => setScanLens(e.target.value)}>
<option value="">{lens.loading ? "Loading…" : "—"}</option>
{lens.opts.map(o => <option key={o.id} value={o.id}>{o.label}</option>)}
</select>
</div>
)}
{rigs?.map((r) => (
<div key={r.id} className="flex items-center justify-between p-4">
<div className="flex items-center gap-3">
<div className="font-medium">{r.name}</div>
{r.rig_type_name && (
<Badge variant="secondary">{r.rig_type_name}</Badge>
)}
</div>
<div>
<label className="block text-sm mb-1">Software</label>
<select className="w-full border rounded px-2 py-1" value={software} onChange={e => setSoftware(e.target.value)}>
<option value="">{softwares.loading ? "Loading…" : "—"}</option>
{softwares.opts.map(o => <option key={o.id} value={o.id}>{o.label}</option>)}
</select>
</div>
<Button
variant="destructive"
size="sm"
onClick={() => onDelete(r.id)}
disabled={!!deleting[r.id]}
>
{deleting[r.id] ? "Deleting…" : "Delete"}
</Button>
</div>
))}
</div>
<div>
<label className="block text-sm mb-1">Notes</label>
<textarea rows={4} className="w-full border rounded px-2 py-1" value={notes} onChange={e => setNotes(e.target.value)} />
</div>
<button className="px-3 py-2 border rounded bg-accent text-background hover:opacity-90">
Create Rig
</button>
</form>
);
}

View file

@ -1,139 +1,63 @@
// app/rigs/RigsListClient.tsx
"use client";
import { useEffect, useState } from "react";
import { Button } from "@/components/ui/button";
import { Badge } from "@/components/ui/badge";
import { useToast } from "@/hooks/use-toast";
type RigRow = {
id: number | string;
type Rig = {
id: string | number;
name: string;
rig_type_name?: string | null;
notes?: string;
rig_type?: { id: number; name: string };
laser_source?: { submission_id: number; make?: string; model?: string };
laser_scan_lens?: { id: number; field_size?: string; focal_length?: string };
laser_focus_lens?: { id: number; name?: string };
laser_software?: { id: number; name?: string };
};
async function apiJson<T>(url: string, init?: RequestInit): Promise<T> {
const res = await fetch(url, {
...init,
headers: {
Accept: "application/json",
...(init?.headers || {}),
},
credentials: "include",
cache: "no-store",
});
const txt = await res.text().catch(() => "");
if (res.ok) {
try {
return (txt ? JSON.parse(txt) : ({} as any)) as T;
} catch {
return {} as T;
}
}
let body: any = null;
try { body = txt ? JSON.parse(txt) : null; } catch {}
const message = body?.error || body?.message || txt || `HTTP ${res.status} for ${url}`;
// If unauthorized, send to sign-in (our flow always lands on /portal)
if (res.status === 401 && typeof window !== "undefined") {
window.location.assign("/auth/sign-in");
}
const err: any = new Error(message);
err.status = res.status;
err.body = body ?? txt;
throw err;
}
export default function RigsListClient() {
const { toast } = useToast();
const [rigs, setRigs] = useState<RigRow[] | null>(null);
const [loading, setLoading] = useState<boolean>(true);
const [err, setErr] = useState<string | null>(null);
const [deleting, setDeleting] = useState<Record<string | number, boolean>>({});
const [rows, setRows] = useState<Rig[]>([]);
const [loading, setLoading] = useState(false);
useEffect(() => {
(async () => {
try {
setLoading(true);
setErr(null);
const j = await apiJson<{ data: RigRow[] }>("/api/my/rigs");
setRigs(j?.data ?? []);
} catch (e: any) {
setErr(e?.message || "Failed to load rigs");
} finally {
setLoading(false);
}
})();
}, []);
async function onDelete(id: string | number) {
if (!confirm("Delete this rig?")) return;
async function load() {
setLoading(true);
try {
setDeleting((d) => ({ ...d, [id]: true }));
await apiJson(`/api/my/rigs/${id}`, { method: "DELETE" });
setRigs((prev) => (prev ? prev.filter((r) => r.id !== id) : prev));
toast({ title: "Rig deleted" });
} catch (e: any) {
toast({
title: "Delete failed",
description: e?.message || "Could not delete rig.",
variant: "destructive",
});
const res = await fetch("/api/my/rigs", { credentials: "include", cache: "no-store" });
const data = await res.json();
setRows(Array.isArray(data) ? data : []);
} finally {
setDeleting((d) => {
const copy = { ...d };
delete copy[id];
return copy;
});
setLoading(false);
}
}
if (loading) {
return (
<div className="rounded-md border p-4 text-sm opacity-70">
Loading your rigs
</div>
);
useEffect(() => { load(); }, []);
async function remove(id: string | number) {
if (!confirm("Delete this rig?")) return;
const res = await fetch(`/api/my/rigs?id=${encodeURIComponent(String(id))}`, { method: "DELETE", credentials: "include" });
if (res.ok) load();
else alert("Failed to delete");
}
if (err) {
return (
<div className="rounded-md border border-red-300 bg-red-50 p-4 text-sm text-red-700">
{err}
</div>
);
}
if (loading) return <div className="text-sm opacity-70">Loading</div>;
if (!rows.length) return <div className="text-sm opacity-70">No rigs yet.</div>;
return (
<div className="space-y-3">
<div className="divide-y divide-border rounded-md border">
{(!rigs || rigs.length === 0) && (
<div className="p-4 text-sm opacity-70">No rigs yet.</div>
)}
{rigs?.map((r) => (
<div key={r.id} className="flex items-center justify-between p-4">
<div className="flex items-center gap-3">
{rows.map((r) => (
<div key={r.id} className="rounded border p-3">
<div className="flex items-center justify-between gap-3">
<div className="font-medium">{r.name}</div>
{r.rig_type_name && (
<Badge variant="secondary">{r.rig_type_name}</Badge>
)}
<button onClick={() => remove(r.id)} className="text-sm px-2 py-1 border rounded hover:bg-muted">Delete</button>
</div>
<Button
variant="destructive"
size="sm"
onClick={() => onDelete(r.id)}
disabled={!!deleting[r.id]}
>
{deleting[r.id] ? "Deleting…" : "Delete"}
</Button>
<div className="text-sm text-muted-foreground mt-1">
{r.rig_type?.name ? <>Type: {r.rig_type.name}. </> : null}
{r.laser_source ? <>Source: {[r.laser_source.make, r.laser_source.model].filter(Boolean).join(" ") || r.laser_source.submission_id}. </> : null}
{r.laser_focus_lens?.name ? <>Focus Lens: {r.laser_focus_lens.name}. </> : null}
{r.laser_scan_lens ? <>Scan Lens: {[r.laser_scan_lens.field_size && `${r.laser_scan_lens.field_size}mm`, r.laser_scan_lens.focal_length && `${r.laser_scan_lens.focal_length}mm`].filter(Boolean).join(" / ")}. </> : null}
{r.laser_software?.name ? <>Software: {r.laser_software.name}. </> : null}
</div>
{r.notes ? <div className="text-sm mt-2">{r.notes}</div> : null}
</div>
))}
</div>
</div>
);
}

View file

@ -1,13 +1,8 @@
// app/rigs/page.tsx
import RigsListClient from "./RigsListClient";
export const metadata = { title: "Rigs" };
export default async function RigsPage() {
export default function Page() {
return (
<main className="mx-auto max-w-5xl px-6 py-10">
<h1 className="mb-6 text-3xl font-bold tracking-tight">Your Rigs</h1>
<RigsListClient />
</main>
<div className="p-4">
<h1 className="text-2xl font-bold mb-3">Rigs</h1>
<p className="text-sm text-muted-foreground">Manage rigs used when submitting settings.</p>
</div>
);
}

View file

@ -4,6 +4,7 @@
import { useRouter, useSearchParams } from "next/navigation";
import { cn } from "@/lib/utils";
import RigsListClient from "@/app/rigs/RigsListClient";
import RigBuilderClient from "@/app/rigs/RigBuilderClient";
const TABS = [
{ key: "my", label: "My Rigs" },
@ -19,17 +20,9 @@ function Panel({ tab }: { tab: string }) {
</div>
);
case "add":
// Placeholder: well retrofit the builder (or a minimal create form) next sprint
return (
<div className="rounded-md border p-4 space-y-3">
<div className="text-sm opacity-70">
Add Rig form will go here. Well wire to <code>POST /api/my/rigs</code> with user auth.
</div>
<ul className="text-sm list-disc pl-5 opacity-70">
<li>Fields: name (required), rig_type (required), optional notes</li>
<li>Use <code>/api/options/user_rig_type</code> for types</li>
<li>On success: refresh list tab</li>
</ul>
<div className="rounded-md border p-4">
<RigBuilderClient />
</div>
);
default: