schema improvements

This commit is contained in:
makearmy 2025-10-05 17:09:39 -04:00
parent eb962b8283
commit 4ef3160515
2 changed files with 158 additions and 112 deletions

View file

@ -1,6 +1,6 @@
// app/api/submit/settings/route.ts
import { NextResponse } from "next/server";
import { uploadFile, bytesFromMB, dxGET, dxPATCH, dxPOST } from "@/lib/directus";
import { uploadFile, createSettingsItem, bytesFromMB, dxGET, dxPATCH } from "@/lib/directus";
import { requireBearer } from "@/app/api/_lib/auth";
/**
@ -18,7 +18,7 @@ import { requireBearer } from "@/app/api/_lib/auth";
* - settings_co2gal
* - settings_uv
*
* Edit:
* Also supports editing:
* Body must include { mode: "edit", submission_id: string|number }
* We PATCH via filter[submission_id][_eq] and owner = current user.
* */
@ -53,7 +53,7 @@ function num(v: any, fallback: number | null = null) {
}
type ReadResult = {
mode: "json" | "multipart";
mode: "json" | "multipart"; // transport mode, not create/edit
body: any;
photoFile: File | null;
screenFile: File | null;
@ -140,8 +140,7 @@ export async function POST(req: Request) {
}
// Create vs Edit
const op: "create" | "edit" =
body?.mode === "edit" ? "edit" : "create";
const op: "create" | "edit" = body?.mode === "edit" ? "edit" : "create";
// Required basics
const setting_title = String(body?.setting_title || "").trim();
@ -174,18 +173,17 @@ export async function POST(req: Request) {
const mat_thickness = num(body?.mat_thickness, null);
const source = body?.source ?? null;
const lens = body?.lens ?? null;
// CO₂ galvo extras (relations)
const lens_conf = body?.lens_conf ?? null;
const lens_apt = body?.lens_apt ?? null;
const lens_exp = body?.lens_exp ?? null;
const focus = num(body?.focus, null);
const setting_notes = String(body?.setting_notes || "").trim();
// Shared string fields
const laser_soft = body?.laser_soft ?? null;
const repeat_all = num(body?.repeat_all, null);
const laser_soft = body?.laser_soft ?? null; // exact key: 'laser_soft'
const repeat_all = num(body?.repeat_all, null); // universally applicable
// CO2 lens extras (may be null on non-co2)
const lens_conf = body?.lens_conf ?? null;
const lens_apt = body?.lens_apt ?? null;
const lens_exp = body?.lens_exp ?? null;
// Upload / accept existing file ids
let photo_id: string | null = body?.photo ?? null;
@ -248,7 +246,6 @@ export async function POST(req: Request) {
laser_soft,
repeat_all,
// material / optics
mat,
mat_coat,
mat_color,
@ -256,15 +253,13 @@ export async function POST(req: Request) {
mat_thickness,
source,
lens,
focus,
// CO₂ galvo extras
// CO2-specific lens extras
lens_conf,
lens_apt,
lens_exp,
focus,
// repeaters
fill_settings: fills,
line_settings: lines,
raster_settings: rasters,
@ -273,37 +268,6 @@ export async function POST(req: Request) {
last_modified_date: nowIso,
};
// ── Per-target requireds (server-side enforcement) ─────────
if (target === "settings_co2gal") {
const missing: string[] = [];
const req = {
setting_title,
uploader,
photo: op === "create" ? photo_id : true, // on edit, can be omitted
source,
lens,
lens_conf,
lens_apt,
lens_exp,
focus: Number.isFinite(focus as number),
mat,
mat_coat,
mat_color,
mat_opacity,
laser_soft,
repeat_all: Number.isFinite(repeat_all as number),
};
for (const [k, v] of Object.entries(req)) {
if (!v) missing.push(k);
}
if (missing.length) {
return NextResponse.json(
{ error: `Missing required: ${missing.join(", ")}` },
{ status: 400 }
);
}
}
if (op === "create") {
// Create-only fields
basePayload.photo = photo_id;
@ -312,14 +276,9 @@ export async function POST(req: Request) {
basePayload.submitted_via = "makearmy-app";
basePayload.submitted_at = nowIso;
// 🔑 Directus requires { data: {...} }
const res = await dxPOST<{ data: { id: string | number } }>(
`/items/${target}`,
bearer,
{ data: basePayload }
);
return NextResponse.json({ ok: true, id: res?.data?.id });
// Helper is expected to wrap as { data: … } internally
const { data } = await createSettingsItem(target, basePayload, bearer);
return NextResponse.json({ ok: true, id: data.id });
}
// EDIT mode
@ -342,10 +301,11 @@ export async function POST(req: Request) {
// enforce owner matches current user (works whether owner is id or M2O)
qs.set("filter[_and][1][owner][_eq]", String(meId));
// ⬇⬇⬇ Directus expects { data: {...} } here (this fixes the 400 "data is required")
const res = await dxPATCH<{ data: any[] }>(
`/items/${target}?${qs.toString()}`,
bearer,
editPayload
{ data: editPayload }
);
const updatedCount = Array.isArray(res?.data) ? res.data.length : 0;

View file

@ -27,6 +27,11 @@ type Rec = {
laser_soft?: { id?: string | number; name?: string | null } | string | number | null;
repeat_all?: number | null;
// CO₂ Galvo extras (M2O)
lens_conf?: { id?: string | number; name?: string | null } | null;
lens_apt?: { id?: string | number; name?: string | null } | null;
lens_exp?: { id?: string | number; name?: string | null } | null;
fill_settings?: any[] | null;
line_settings?: any[] | null;
raster_settings?: any[] | null;
@ -39,7 +44,11 @@ type Rec = {
async function readJson(res: Response) {
const text = await res.text();
try { return text ? JSON.parse(text) : null; } catch { throw new Error(`Unexpected response (HTTP ${res.status})`); }
try {
return text ? JSON.parse(text) : null;
} catch {
throw new Error(`Unexpected response (HTTP ${res.status})`);
}
}
function ownerLabel(o: Rec["owner"]) {
@ -65,7 +74,9 @@ function ZoomableSquareImage(props: { src: string; alt: string; onOpen: () => vo
className="w-full h-full object-cover cursor-zoom-in"
loading="lazy"
onClick={onOpen}
onError={(e) => { (e.currentTarget as HTMLImageElement).style.display = "none"; }}
onError={(e) => {
(e.currentTarget as HTMLImageElement).style.display = "none";
}}
/>
</div>
);
@ -104,15 +115,21 @@ export default function CO2GalvoDetail({
const j = await readJson(r);
const id = j?.data?.id ?? j?.id ?? null;
if (!dead) setMeId(id ? String(id) : null);
} catch { /* ignore */ }
} catch {
/* ignore */
}
})();
return () => { dead = true; };
return () => {
dead = true;
};
}, []);
// lightbox
const [viewerSrc, setViewerSrc] = useState<string | null>(null);
useEffect(() => {
const onKey = (e: KeyboardEvent) => { if (e.key === "Escape") setViewerSrc(null); };
const onKey = (e: KeyboardEvent) => {
if (e.key === "Escape") setViewerSrc(null);
};
if (viewerSrc) window.addEventListener("keydown", onKey);
return () => window.removeEventListener("keydown", onKey);
}, [viewerSrc]);
@ -153,6 +170,14 @@ export default function CO2GalvoDetail({
"lens.field_size",
"lens.focal_length",
// CO₂ Galvo extras
"lens_conf.id",
"lens_conf.name",
"lens_apt.id",
"lens_apt.name",
"lens_exp.id",
"lens_exp.name",
"focus",
"laser_soft.id",
"laser_soft.name",
@ -168,9 +193,9 @@ export default function CO2GalvoDetail({
"last_modified_date",
].join(",");
const url = `/api/dx/items/settings_co2gal?fields=${encodeURIComponent(fields)}&filter[submission_id][_eq]=${encodeURIComponent(
String(id)
)}&limit=1`;
const url = `/api/dx/items/settings_co2gal?fields=${encodeURIComponent(
fields
)}&filter[submission_id][_eq]=${encodeURIComponent(String(id))}&limit=1`;
const r = await fetch(url, { cache: "no-store", credentials: "include" });
if (!r.ok) {
@ -188,25 +213,34 @@ export default function CO2GalvoDetail({
}
})();
return () => { dead = true; };
return () => {
dead = true;
};
}, [id]);
const initialValues = useMemo(() => {
if (!rec) return null;
const toId = (v: any) => (v == null ? null : (typeof v === "object" ? (v.id ?? v.submission_id ?? null) : v));
const toId = (v: any) => (v == null ? null : typeof v === "object" ? v.id ?? v.submission_id ?? null : v);
const photoId = typeof rec.photo === "string" || typeof rec.photo === "number" ? String(rec.photo) : rec.photo?.id ?? null;
const screenId = typeof rec.screen === "string" || typeof rec.screen === "number" ? String(rec.screen) : rec.screen?.id ?? null;
const screenId =
typeof rec.screen === "string" || typeof rec.screen === "number" ? String(rec.screen) : rec.screen?.id ?? null;
const matId = toId(rec.mat);
const coatId = toId(rec.mat_coat);
const colorId = toId(rec.mat_color);
const opacityId = toId(rec.mat_opacity);
const lensId = toId(rec.lens);
const sourceId = rec.source && typeof rec.source === "object" ? rec.source.submission_id ?? null : (rec.source as any) ?? null;
const sourceId =
rec.source && typeof rec.source === "object" ? rec.source.submission_id ?? null : (rec.source as any) ?? null;
// CO₂ Galvo M2O ids
const lensConfId = toId(rec.lens_conf);
const lensAptId = toId(rec.lens_apt);
const lensExpId = toId(rec.lens_exp);
return {
submission_id: rec.submission_id, // ★ include for type parity
submission_id: rec.submission_id, // keep for edit mode parity
setting_title: rec.setting_title ?? "",
setting_notes: rec.setting_notes ?? "",
@ -226,6 +260,11 @@ export default function CO2GalvoDetail({
laser_soft: (typeof rec.laser_soft === "object" ? rec.laser_soft?.id : (rec.laser_soft as any)) ?? null,
repeat_all: rec.repeat_all ?? null,
// pass through for prefill
lens_conf: lensConfId != null ? String(lensConfId) : null,
lens_apt: lensAptId != null ? String(lensAptId) : null,
lens_exp: lensExpId != null ? String(lensExpId) : null,
fill_settings: rec.fill_settings ?? [],
line_settings: rec.line_settings ?? [],
raster_settings: rec.raster_settings ?? [],
@ -239,7 +278,8 @@ export default function CO2GalvoDetail({
}
if (loading) return <p className="p-6">Loading setting</p>;
if (err) return (
if (err)
return (
<div className="p-6">
<div className="rounded-md border border-red-300 bg-red-50 px-3 py-2 text-sm text-red-700">{err}</div>
</div>
@ -252,7 +292,9 @@ export default function CO2GalvoDetail({
<main className="space-y-4">
<div className="flex items-center justify-between">
<h1 className="text-xl lg:text-2xl font-semibold">Edit CO Galvo Setting</h1>
<button className="px-2 py-1 border rounded" onClick={() => (onBack ? onBack() : clearEditParam())}>Cancel</button>
<button className="px-2 py-1 border rounded" onClick={() => (onBack ? onBack() : clearEditParam())}>
Cancel
</button>
</div>
<SettingsSubmit
mode="edit"
@ -266,7 +308,14 @@ export default function CO2GalvoDetail({
// ── VIEW MODE (readable) ───────────────────────────────────
const ownerDisplay = ownerLabel(rec.owner);
const ownerId = typeof rec.owner === "object" ? (rec.owner?.id != null ? String(rec.owner.id) : null) : (rec.owner != null ? String(rec.owner) : null);
const ownerId =
typeof rec.owner === "object"
? rec.owner?.id != null
? String(rec.owner.id)
: null
: rec.owner != null
? String(rec.owner)
: null;
const isMine = meId && ownerId ? meId === ownerId : false;
const photoId = typeof rec.photo === "object" ? rec.photo?.id : (rec.photo as any);
@ -275,7 +324,7 @@ export default function CO2GalvoDetail({
const photoSrc = photoId ? fileUrl(String(photoId)) : "";
const screenSrc = screenId ? fileUrl(String(screenId)) : "";
const softName = typeof rec.laser_soft === "object" ? (rec.laser_soft?.name ?? "—") : "—";
const softName = typeof rec.laser_soft === "object" ? rec.laser_soft?.name ?? "—" : "—";
function openEdit() {
const q = new URLSearchParams(sp.toString());
@ -293,18 +342,45 @@ export default function CO2GalvoDetail({
<section className="grid md:grid-cols-2 gap-6">
<div className="space-y-2">
<div className="text-sm">
<div><span className="font-medium">Owner:</span> {ownerDisplay}</div>
<div><span className="font-medium">Uploader:</span> {rec.uploader || "—"}</div>
<div><span className="font-medium">Material:</span> {rec.mat?.name || "—"}</div>
<div><span className="font-medium">Coating:</span> {rec.mat_coat?.name || "—"}</div>
<div><span className="font-medium">Color:</span> {rec.mat_color?.name || "—"}</div>
<div><span className="font-medium">Opacity:</span> {rec.mat_opacity?.opacity ?? "—"}</div>
<div><span className="font-medium">Thickness (mm):</span> {rec.mat_thickness ?? "—"}</div>
<div><span className="font-medium">Laser Source:</span> {[rec.source?.make, rec.source?.model].filter(Boolean).join(" ") || "—"}{rec.source?.nm ? ` (${rec.source.nm})` : ""}</div>
<div><span className="font-medium">Scan Lens:</span> {rec.lens?.field_size || "—"}{rec.lens?.focal_length ? ` / ${rec.lens.focal_length} mm` : ""}</div>
<div><span className="font-medium">Focus (mm):</span> {rec.focus ?? "—"}</div>
<div><span className="font-medium">Software:</span> {softName}</div>
<div><span className="font-medium">Repeat All:</span> {rec.repeat_all ?? "—"}</div>
<div>
<span className="font-medium">Owner:</span> {ownerDisplay}
</div>
<div>
<span className="font-medium">Uploader:</span> {rec.uploader || "—"}
</div>
<div>
<span className="font-medium">Material:</span> {rec.mat?.name || "—"}
</div>
<div>
<span className="font-medium">Coating:</span> {rec.mat_coat?.name || "—"}
</div>
<div>
<span className="font-medium">Color:</span> {rec.mat_color?.name || "—"}
</div>
<div>
<span className="font-medium">Opacity:</span> {rec.mat_opacity?.opacity ?? "—"}
</div>
<div>
<span className="font-medium">Thickness (mm):</span> {rec.mat_thickness ?? "—"}
</div>
<div>
<span className="font-medium">Laser Source:</span>{" "}
{[rec.source?.make, rec.source?.model].filter(Boolean).join(" ") || "—"}
{rec.source?.nm ? ` (${rec.source.nm})` : ""}
</div>
<div>
<span className="font-medium">Scan Lens:</span> {rec.lens?.field_size || "—"}
{rec.lens?.focal_length ? ` / ${rec.lens.focal_length} mm` : ""}
</div>
<div>
<span className="font-medium">Focus (mm):</span> {rec.focus ?? "—"}
</div>
<div>
<span className="font-medium">Software:</span> {softName}
</div>
<div>
<span className="font-medium">Repeat All:</span> {rec.repeat_all ?? "—"}
</div>
</div>
{rec.setting_notes ? (
@ -316,7 +392,9 @@ export default function CO2GalvoDetail({
{showOwnerEdit && isMine && (
<div className="pt-2">
<button onClick={openEdit} className="px-2 py-1 border rounded text-sm">Edit</button>
<button onClick={openEdit} className="px-2 py-1 border rounded text-sm">
Edit
</button>
</div>
)}
</div>
@ -444,8 +522,16 @@ export default function CO2GalvoDetail({
)}
{viewerSrc && (
<div className="fixed inset-0 z-50 bg-black/80 p-4 flex items-center justify-center" onClick={() => setViewerSrc(null)}>
<img src={viewerSrc} alt="" className="max-w-full max-h-full cursor-zoom-out" onClick={(e) => e.stopPropagation()} />
<div
className="fixed inset-0 z-50 bg-black/80 p-4 flex items-center justify-center"
onClick={() => setViewerSrc(null)}
>
<img
src={viewerSrc}
alt=""
className="max-w-full max-h-full cursor-zoom-out"
onClick={(e) => e.stopPropagation()}
/>
</div>
)}
</div>