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(