co2 galvo owner test

This commit is contained in:
makearmy 2025-10-01 20:00:26 -04:00
parent 715be11ff9
commit a38aa4c2f9
5 changed files with 254 additions and 236 deletions

View file

@ -81,26 +81,36 @@ async function readJsonOrMultipart(req: Request): Promise<ReadResult> {
return { mode: "json", body, photoFile: null, screenFile: null };
}
// map to your Directus folder paths
function folderPathFor(target: Target, kind: "photo" | "screen") {
switch (target) {
case "settings_fiber":
return kind === "photo"
? "le_fiber_settings/le_fiber_settings_photos"
: "le_fiber_settings/le_fiber_settings_screenshots";
case "settings_co2gan":
return kind === "photo"
? "le_co2gan_settings/le_co2gan_settings_photos"
: "le_co2gan_settings/le_co2gan_settings_screenshots";
case "settings_co2gal":
return kind === "photo"
? "le_co2gal_settings/le_co2gal_settings_photos"
: "le_co2gal_settings/le_co2gal_settings_screenshots";
case "settings_uv":
return kind === "photo"
? "le_uv_settings/le_uv_settings_photos"
: "le_uv_settings/le_uv_settings_screenshots";
}
/** Env-based folder IDs (no folder browsing) */
function folderIdFor(
target: Target,
kind: "photo" | "screen" | "notes"
): string | undefined {
const E = process.env;
const map = {
settings_co2gal: {
photo: E.DX_FOLDER_GALVO_PHOTOS,
screen: E.DX_FOLDER_GALVO_SCREENS,
notes: E.DX_FOLDER_GALVO_NOTES,
},
settings_co2gan: {
photo: E.DX_FOLDER_GANTRY_PHOTOS,
screen: E.DX_FOLDER_GANTRY_SCREENS,
notes: E.DX_FOLDER_GANTRY_NOTES,
},
settings_fiber: {
photo: E.DX_FOLDER_FIBER_PHOTOS,
screen: E.DX_FOLDER_FIBER_SCREENS,
notes: E.DX_FOLDER_FIBER_NOTES,
},
settings_uv: {
photo: E.DX_FOLDER_UV_PHOTOS,
screen: E.DX_FOLDER_UV_SCREENS,
notes: E.DX_FOLDER_UV_NOTES,
},
} as const;
// @ts-expect-error narrow map index
return map[target]?.[kind];
}
export async function POST(req: Request) {
@ -109,152 +119,141 @@ export async function POST(req: Request) {
const ip =
(req.headers.get("x-forwarded-for")?.split(",")[0]?.trim() as string) ||
"0.0.0.0";
if (!rateLimitOk(ip)) {
return NextResponse.json({ error: "Rate limited" }, { status: 429 });
}
if (!rateLimitOk(ip)) {
return NextResponse.json({ error: "Rate limited" }, { status: 429 });
}
// Enforce user auth
const bearer = requireBearer(req);
// Enforce user auth (everything uses the user's token)
const bearer = requireBearer(req);
const { mode, body, photoFile, screenFile } = await readJsonOrMultipart(req);
const { mode, body, photoFile, screenFile } = await readJsonOrMultipart(req);
const target: Target = body?.target;
if (
!target ||
!["settings_fiber", "settings_co2gan", "settings_co2gal", "settings_uv"].includes(target)
) {
return NextResponse.json({ error: "Invalid target" }, { status: 400 });
}
const target: Target = body?.target;
if (
!target ||
!["settings_fiber", "settings_co2gan", "settings_co2gal", "settings_uv"].includes(target)
) {
return NextResponse.json({ error: "Invalid target" }, { status: 400 });
}
// Required basics
const setting_title = String(body?.setting_title || "").trim();
if (!setting_title)
return NextResponse.json(
{ error: "Missing required: setting_title" },
{ status: 400 }
);
// Required basics
const setting_title = String(body?.setting_title || "").trim();
if (!setting_title) {
return NextResponse.json(
{ error: "Missing required: setting_title" },
{ status: 400 }
);
}
// ── Current user (handle both shapes from dxGET) ─────────────
const meRes = await dxGET<any>("/users/me?fields=id,username", bearer);
const meId = meRes?.data?.id ?? meRes?.id ?? null;
const meUsername = meRes?.data?.username ?? meRes?.username ?? null;
// Current user (handle both {data:{...}} and {...} shapes)
const meRes = await dxGET<any>("/users/me?fields=id,username", bearer);
const meId = meRes?.data?.id ?? meRes?.id ?? null;
const meUsername = meRes?.data?.username ?? meRes?.username ?? null;
// Derive uploader from the authenticated user (server-trusted)
const uploader = meUsername || "user";
// Attribution
const uploader = meUsername || "user"; // string field mirrors owner.username
// Relations & numerics
const mat = body?.mat ?? null;
const mat_coat = body?.mat_coat ?? null;
const mat_color = body?.mat_color ?? null;
const mat_opacity = body?.mat_opacity ?? null;
const mat_thickness = num(body?.mat_thickness, null);
const source = body?.source ?? null;
const lens = body?.lens ?? null;
const focus = num(body?.focus, null);
const setting_notes = String(body?.setting_notes || "").trim();
// Relations & numerics
const mat = body?.mat ?? null;
const mat_coat = body?.mat_coat ?? null;
const mat_color = body?.mat_color ?? null;
const mat_opacity = body?.mat_opacity ?? null;
const mat_thickness = num(body?.mat_thickness, null);
const source = body?.source ?? null;
const lens = body?.lens ?? null;
const focus = num(body?.focus, null);
const setting_notes = String(body?.setting_notes || "").trim();
// Fiber-only / shared string
const laser_soft = body?.laser_soft ?? null; // string
const repeat_all =
target === "settings_fiber" ? num(body?.repeat_all, null) : undefined;
// Shared string fields
const laser_soft = body?.laser_soft ?? null; // exact key: 'laser_soft'
const repeat_all = num(body?.repeat_all, null); // ← universally applicable now
// Upload / accept existing file ids
let photo_id: string | null = body?.photo ?? null;
let screen_id: string | null = body?.screen ?? null;
// Upload / accept existing file ids
let photo_id: string | null = body?.photo ?? null;
let screen_id: string | null = body?.screen ?? null;
// photo is required: if no id on body, require file
if (!photo_id && photoFile) {
if (photoFile.size > MAX_BYTES)
return NextResponse.json(
{ error: `Photo exceeds ${MAX_MB} MB` },
{ status: 400 }
);
const up = await uploadFile(
photoFile,
(photoFile as File).name,
bearer,
{
folderNamePath: folderPathFor(target, "photo"),
title: setting_title,
// NOTE: do NOT include `owner` here; uploadFile options don't accept it.
}
);
photo_id = up.id;
}
if (!photo_id) {
return NextResponse.json(
{ error: "Missing required: photo" },
{ status: 400 }
);
}
// photo is required: if no id on body, require file
if (!photo_id && photoFile) {
if (photoFile.size > MAX_BYTES) {
return NextResponse.json(
{ error: `Photo exceeds ${MAX_MB} MB` },
{ status: 400 }
);
}
const up = await uploadFile(photoFile, (photoFile as File).name, bearer, {
folderId: folderIdFor(target, "photo"),
title: setting_title,
});
photo_id = up.id;
}
if (!photo_id) {
return NextResponse.json(
{ error: "Missing required: photo" },
{ status: 400 }
);
}
if (!screen_id && screenFile) {
if (screenFile.size > MAX_BYTES)
return NextResponse.json(
{ error: `Screenshot exceeds ${MAX_MB} MB` },
{ status: 400 }
);
const up = await uploadFile(
screenFile,
(screenFile as File).name,
bearer,
{
folderNamePath: folderPathFor(target, "screen"),
title: `${setting_title} (screen)`,
}
);
screen_id = up.id;
}
if (!screen_id && screenFile) {
if (screenFile.size > MAX_BYTES) {
return NextResponse.json(
{ error: `Screenshot exceeds ${MAX_MB} MB` },
{ status: 400 }
);
}
const up = await uploadFile(screenFile, (screenFile as File).name, bearer, {
folderId: folderIdFor(target, "screen"),
title: `${setting_title} (screen)`,
});
screen_id = up.id;
}
// Repeaters (pass through; UI already coerces numbers/bools)
const fills = Array.isArray(body?.fill_settings) ? body.fill_settings : [];
const lines = Array.isArray(body?.line_settings) ? body.line_settings : [];
const rasters = Array.isArray(body?.raster_settings) ? body.raster_settings : [];
// Repeaters (pass-through; UI coerces numbers/bools)
const fills = Array.isArray(body?.fill_settings) ? body.fill_settings : [];
const lines = Array.isArray(body?.line_settings) ? body.line_settings : [];
const rasters = Array.isArray(body?.raster_settings) ? body.raster_settings : [];
// timestamps for required fields
const nowIso = new Date().toISOString();
// timestamps
const nowIso = new Date().toISOString();
const payload: Record<string, any> = {
setting_title,
// Ownership & attribution
owner: meId || null, // ✅ M2O to directus_users
uploader, // ✅ mirror username into string field
const payload: Record<string, any> = {
setting_title,
setting_notes,
// Ownership & attribution
owner: meId || null, // M2O to directus_users
uploader, // string mirror of username
submission_date: nowIso, // if required by schema
last_modified_date: nowIso, // keep in sync
setting_notes,
photo: photo_id,
screen: screen_id ?? null,
submission_date: nowIso,
last_modified_date: nowIso,
// ✅ exact key (string)
laser_soft,
photo: photo_id,
screen: screen_id ?? null,
mat,
mat_coat,
mat_color,
mat_opacity,
mat_thickness,
source,
lens,
focus,
// exact keys
laser_soft,
repeat_all, // ← always included
fill_settings: fills,
line_settings: lines,
raster_settings: rasters,
mat,
mat_coat,
mat_color,
mat_opacity,
mat_thickness,
source,
lens,
focus,
status: "pending",
submitted_via: "makearmy-app",
submitted_at: nowIso,
};
fill_settings: fills,
line_settings: lines,
raster_settings: rasters,
if (target === "settings_fiber") {
payload.repeat_all = repeat_all ?? null;
}
status: "pending",
submitted_via: "makearmy-app",
submitted_at: nowIso,
};
const { data } = await createSettingsItem(target, payload, bearer);
return NextResponse.json({ ok: true, id: data.id });
const { data } = await createSettingsItem(target, payload, bearer);
return NextResponse.json({ ok: true, id: data.id });
} catch (err: any) {
console.error("[submit/settings] error", err?.message || err);
return NextResponse.json(

View file

@ -20,7 +20,6 @@ export default function CO2GalvoSettingDetailPage() {
"submission_id",
"setting_title",
"uploader",
// make sure owner expands
"owner.id",
"owner.username",
"setting_notes",
@ -41,7 +40,6 @@ export default function CO2GalvoSettingDetailPage() {
"lens_apt.name",
"lens_exp.name",
"focus",
// string-or-relation
"laser_soft",
"laser_soft.name",
"repeat_all",
@ -50,7 +48,8 @@ export default function CO2GalvoSettingDetailPage() {
"raster_settings",
].join(",");
const url = `/api/dx/items/settings_co2gal/${encodeURIComponent(String(id))}` +
const url =
`/api/dx/items/settings_co2gal/${encodeURIComponent(String(id))}` +
`?fields=${encodeURIComponent(fields)}`;
setLoading(true);
@ -73,7 +72,6 @@ export default function CO2GalvoSettingDetailPage() {
if (loading) return <p className="p-6">Loading setting...</p>;
if (!setting) return <p className="p-6">Setting not found.</p>;
// ---- display helpers ----
const ownerDisplay: string =
typeof setting?.owner === "object"
? (setting.owner?.username ?? setting.owner?.id ?? "—")

View file

@ -8,7 +8,6 @@ import Image from "next/image";
type Owner = {
id?: string | number;
username?: string | null;
// keep extras harmlessly if API returns them
first_name?: string | null;
last_name?: string | null;
email?: string | null;
@ -31,32 +30,31 @@ export default function CO2GalvoSettingsPage() {
}, [query]);
useEffect(() => {
const url =
`${process.env.NEXT_PUBLIC_API_BASE_URL}/items/settings_co2gal` +
`?fields=` +
[
const fields = [
"submission_id",
"setting_title",
"uploader",
// owner (M2O) ensure username is requested
"owner.id",
"owner.username",
// assets / denorms
"photo.id",
"photo.title",
"mat.name",
"mat_coat.name",
"source.model",
"lens.field_size",
].join(",") +
`&limit=-1`;
].join(",");
fetch(url, { cache: "no-store" })
.then((res) => {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const url = `/api/dx/items/settings_co2gal?fields=${encodeURIComponent(fields)}&limit=-1`;
fetch(url, { cache: "no-store", credentials: "include" })
.then(async (res) => {
if (!res.ok) {
const j = await res.json().catch(() => ({}));
throw new Error(j?.errors?.[0]?.message || `HTTP ${res.status}`);
}
return res.json();
})
.then((data) => setSettings(data?.data || []))
.then((json) => setSettings(json?.data || []))
.catch((e) => {
console.error("CO2 Galvo settings fetch failed:", e);
setSettings([]);