248 lines
8 KiB
TypeScript
248 lines
8 KiB
TypeScript
// app/settings/co2-galvo/page.tsx
|
|
"use client";
|
|
|
|
import { useEffect, useState, useMemo } from "react";
|
|
import Link from "next/link";
|
|
import { useSearchParams } from "next/navigation";
|
|
|
|
type Owner =
|
|
| string
|
|
| number
|
|
| { id?: string | number; username?: string | null; first_name?: string | null; last_name?: string | null; email?: string | null }
|
|
| null
|
|
| undefined;
|
|
|
|
type SettingsRow = {
|
|
submission_id: string | number;
|
|
setting_title?: string | null;
|
|
uploader?: string | null;
|
|
owner?: Owner;
|
|
mat?: { name?: string | null } | null;
|
|
mat_coat?: { name?: string | null } | null;
|
|
source?: { model?: string | null } | null;
|
|
lens?: { field_size?: string | number | null } | null;
|
|
};
|
|
|
|
export default function CO2GalvoSettingsPage() {
|
|
const searchParams = useSearchParams();
|
|
const initialQuery = searchParams.get("query") || "";
|
|
|
|
const [query, setQuery] = useState(initialQuery);
|
|
const [debouncedQuery, setDebouncedQuery] = useState(initialQuery);
|
|
const [settings, setSettings] = useState<SettingsRow[]>([]);
|
|
const [ownerMap, setOwnerMap] = useState<Record<string, string>>({}); // id -> username
|
|
const [loading, setLoading] = useState(true);
|
|
const [resolvingOwners, setResolvingOwners] = useState(false);
|
|
|
|
// Debounce search box
|
|
useEffect(() => {
|
|
const t = setTimeout(() => setDebouncedQuery(query), 300);
|
|
return () => clearTimeout(t);
|
|
}, [query]);
|
|
|
|
// Safe JSON reader (so HTML 404s don't blow up)
|
|
async function readJson(res: Response) {
|
|
const text = await res.text();
|
|
try {
|
|
return text ? JSON.parse(text) : null;
|
|
} catch {
|
|
throw new Error(`Unexpected response (status ${res.status})`);
|
|
}
|
|
}
|
|
|
|
useEffect(() => {
|
|
// ✅ include parent field `owner` AND subfields; use auth proxy
|
|
const fields = [
|
|
"submission_id",
|
|
"setting_title",
|
|
"uploader",
|
|
"owner", // ← add comma here
|
|
"owner.id",
|
|
"owner.username",
|
|
"photo.id",
|
|
"photo.title",
|
|
"mat.name",
|
|
"mat_coat.name",
|
|
"source.model",
|
|
"lens.field_size",
|
|
].join(",");
|
|
|
|
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 readJson(res).catch(() => null);
|
|
const msg = (j as any)?.errors?.[0]?.message || `HTTP ${res.status}`;
|
|
throw new Error(msg);
|
|
}
|
|
return readJson(res);
|
|
})
|
|
.then((json: any) => setSettings(Array.isArray(json?.data) ? json.data : []))
|
|
.catch((e) => {
|
|
console.error("CO2 Galvo list fetch failed:", e);
|
|
setSettings([]);
|
|
})
|
|
.finally(() => setLoading(false));
|
|
}, []);
|
|
|
|
// After settings load, resolve owner usernames directly via /api/dx/users using the user token
|
|
useEffect(() => {
|
|
if (!settings.length) return;
|
|
|
|
// Collect IDs needing resolution (owner is raw id OR object without username)
|
|
const ids = new Set<string>();
|
|
for (const s of settings) {
|
|
const o = s.owner;
|
|
if (!o) continue;
|
|
|
|
if (typeof o === "string" || typeof o === "number") {
|
|
const k = String(o);
|
|
if (!ownerMap[k]) ids.add(k);
|
|
} else {
|
|
// object with maybe id/username
|
|
const id = o.id != null ? String(o.id) : "";
|
|
const hasUsername = !!o.username;
|
|
if (id && !hasUsername && !ownerMap[id]) ids.add(id);
|
|
}
|
|
}
|
|
|
|
if (!ids.size) return;
|
|
|
|
const all = Array.from(ids);
|
|
const chunk = 100; // Directus handles big _in, but chunk to be safe
|
|
setResolvingOwners(true);
|
|
|
|
(async () => {
|
|
const updates: Record<string, string> = {};
|
|
for (let i = 0; i < all.length; i += chunk) {
|
|
const slice = all.slice(i, i + chunk);
|
|
const qs = new URLSearchParams();
|
|
qs.set("fields", "id,username");
|
|
qs.set("limit", String(slice.length));
|
|
// filter[id][_in]=a,b,c
|
|
qs.set("filter[id][_in]", slice.join(","));
|
|
|
|
try {
|
|
const r = await fetch(`/api/dx/users?${qs.toString()}`, {
|
|
credentials: "include",
|
|
cache: "no-store",
|
|
});
|
|
if (!r.ok) {
|
|
const j = await readJson(r).catch(() => null);
|
|
const msg = (j as any)?.errors?.[0]?.message || `HTTP ${r.status}`;
|
|
console.warn("Owner lookup failed:", msg);
|
|
// If 403/401, perms don't allow reading other users; stop trying further
|
|
if (r.status === 401 || r.status === 403) break;
|
|
continue;
|
|
}
|
|
const j = await readJson(r);
|
|
const rows: Array<{ id: string; username?: string | null }> = j?.data || [];
|
|
for (const row of rows) {
|
|
updates[String(row.id)] = row.username || String(row.id);
|
|
}
|
|
} catch (e) {
|
|
console.warn("Owner lookup error:", e);
|
|
break;
|
|
}
|
|
}
|
|
|
|
if (Object.keys(updates).length) {
|
|
setOwnerMap((prev) => ({ ...prev, ...updates }));
|
|
}
|
|
setResolvingOwners(false);
|
|
})();
|
|
}, [settings, ownerMap]);
|
|
|
|
const ownerLabel = (o: Owner) => {
|
|
if (!o) return "—";
|
|
|
|
if (typeof o === "string" || typeof o === "number") {
|
|
const id = String(o);
|
|
return ownerMap[id] || id; // prefer resolved username, fall back to id
|
|
}
|
|
|
|
// object
|
|
return (
|
|
o.username ||
|
|
[o.first_name, o.last_name].filter(Boolean).join(" ").trim() ||
|
|
o.email ||
|
|
(o.id != null ? String(o.id) : "—")
|
|
);
|
|
};
|
|
|
|
const highlight = (text?: string) => {
|
|
if (!debouncedQuery) return text || "";
|
|
const regex = new RegExp(`(${debouncedQuery.replace(/[.*+?^${}()|[\\]\\\\]/g, "\\$&")})`, "gi");
|
|
return (text || "").replace(regex, "<mark>$1</mark>");
|
|
};
|
|
|
|
const filtered = useMemo(() => {
|
|
const q = debouncedQuery.toLowerCase();
|
|
return settings.filter((entry) => {
|
|
const fieldsToSearch = [
|
|
entry.setting_title,
|
|
ownerLabel(entry.owner),
|
|
entry.uploader,
|
|
entry.mat?.name,
|
|
entry.mat_coat?.name,
|
|
entry.source?.model,
|
|
entry.lens?.field_size as any,
|
|
];
|
|
return fieldsToSearch
|
|
.filter(Boolean)
|
|
.some((field: string) => String(field).toLowerCase().includes(q));
|
|
});
|
|
}, [settings, debouncedQuery, ownerMap]);
|
|
|
|
return (
|
|
<div className="p-6 max-w-7xl mx-auto">
|
|
<div className="mb-4">
|
|
<input
|
|
value={query}
|
|
onChange={(e) => setQuery(e.currentTarget.value)}
|
|
placeholder="Search by title, owner, material, model…"
|
|
className="w-full max-w-lg border rounded px-3 py-2"
|
|
/>
|
|
</div>
|
|
|
|
{loading ? (
|
|
<p>Loading…</p>
|
|
) : (
|
|
<div className="overflow-x-auto">
|
|
<table className="min-w-full text-sm">
|
|
<thead>
|
|
<tr className="bg-muted">
|
|
<th className="px-2 py-2 text-left">Title</th>
|
|
<th className="px-2 py-2 text-left">Owner {resolvingOwners ? "…resolving" : ""}</th>
|
|
<th className="px-2 py-2 text-left">Material</th>
|
|
<th className="px-2 py-2 text-left">Coating</th>
|
|
<th className="px-2 py-2 text-left">Model</th>
|
|
<th className="px-2 py-2 text-left">Field</th>
|
|
</tr>
|
|
</thead>
|
|
<tbody>
|
|
{filtered.map((s) => (
|
|
<tr key={s.submission_id} className="border-b hover:bg-muted/30">
|
|
<td className="px-2 py-2 whitespace-nowrap">
|
|
<Link href={`/settings/co2-galvo/${s.submission_id}`} className="underline">
|
|
<span dangerouslySetInnerHTML={{ __html: highlight(s.setting_title || "Untitled") }} />
|
|
</Link>
|
|
</td>
|
|
<td
|
|
className="px-2 py-2 whitespace-nowrap"
|
|
dangerouslySetInnerHTML={{ __html: highlight(ownerLabel(s.owner)) }}
|
|
/>
|
|
<td className="px-2 py-2 whitespace-nowrap">{s.mat?.name || "—"}</td>
|
|
<td className="px-2 py-2 whitespace-nowrap">{s.mat_coat?.name || "—"}</td>
|
|
<td className="px-2 py-2 whitespace-nowrap">{s.source?.model || "—"}</td>
|
|
<td className="px-2 py-2 whitespace-nowrap">{s.lens?.field_size || "—"}</td>
|
|
</tr>
|
|
))}
|
|
</tbody>
|
|
</table>
|
|
</div>
|
|
)}
|
|
</div>
|
|
);
|
|
}
|