/* ═══════════════════════════════════════════════════════════════ ADMIN: FEEDBACK TRIAGE Reads /api/admin/feedback, writes status and notes back through PATCH, and deletes through DELETE. Deliberately a flat list rather than a table: the message is the content, and messages don't fit in a cell. Two capabilities, two ranks. Editors and above can change a status or leave a note; deleting is admin and above, matching requireRole on the server. Both come from the roles ladder rather than an equality check: a superadmin is not role === "admin", and reading it that way is what hid these controls. Every read passes ttl: 0. The api cache exists for public content that changes weekly; a triage queue two people are working at the same time is the opposite case. ═══════════════════════════════════════════════════════════════ */ import { useCallback, useEffect, useState } from "react"; import { Link, useNavigate } from "react-router-dom"; import { del, get, patch, post, ApiError } from "../../lib/api.ts"; import { isUnauthorized, useAuth } from "../../lib/auth.tsx"; import { canWrite as roleCanWrite, canDelete } from "../../lib/roles.ts"; import { feedbackTypeLabel } from "../../data/feedbackTypes.ts"; import { fromRequest, requestType, requestTypeLabel } from "../../data/requestTypes.ts"; const STATUSES = ["new", "read", "actioned", "archived", "spam"]; const STATUS_STYLE = { new: "bg-action text-white", read: "bg-tint text-link", // The brand green at a tint, as text in light mode and lifted in dark. actioned: "bg-[color-mix(in_srgb,#56733f_14%,transparent)] text-[color-mix(in_srgb,#56733f_var(--accent-text-mix),#ffffff)]", archived: "bg-muted/10 text-muted", spam: "bg-danger-tint text-danger", }; // created_at is UTC in 'YYYY-MM-DD HH:MM:SS' form, which Safari // won't parse without the T and the Z. function formatDate(value) { const date = new Date(`${value.replace(" ", "T")}Z`); return date.toLocaleString(undefined, { dateStyle: "medium", timeStyle: "short", }); } const sizeOf = (bytes) => (bytes < 1024 * 1024 ? `${Math.ceil(bytes / 1024)} KB` : `${(bytes / 1024 / 1024).toFixed(1)} MB`); /* A content request's files: each downloads from Drive through the server, and a Word document can become a draft blog post (the same import as Blog posts → Import from Word). */ function RequestFiles({ row, canWrite, canRemove }) { const navigate = useNavigate(); const [files, setFiles] = useState(row.files); const [busy, setBusy] = useState(null); const [confirming, setConfirming] = useState(null); const [error, setError] = useState(null); useEffect(() => setFiles(row.files), [row.files]); async function makePost(file) { setBusy(file.id); setError(null); try { const result = await post(`/admin/feedback/${row.id}/files/${file.id}/blog-post`, {}); navigate(`/admin/blog_posts/${result.id}`, { state: { imported: result.summary } }); } catch (err) { setError(err instanceof ApiError ? err.message : "Couldn't reach the server."); setBusy(null); } } async function remove(file) { setBusy(file.id); setError(null); try { await del(`/admin/feedback/${row.id}/files/${file.id}`); setFiles((current) => current.filter((f) => f.id !== file.id)); } catch (err) { setError(err instanceof ApiError ? err.message : "Couldn't remove it."); } finally { setBusy(null); setConfirming(null); } } if (files.length === 0) return null; const small = "rounded-full border px-3 py-0.5 text-xs font-semibold transition-colors disabled:opacity-60"; return (
    {files.map((file) => (
  • {file.missing ? ( // Deleted or moved out of Requests in Drive: nothing to open. {file.name} ) : ( {file.name} )} {sizeOf(file.size)} {file.missing && ( Missing from Drive )} {canWrite && !file.missing && /\.docx$/i.test(file.name) && ( )} {canRemove && (confirming === file.id ? ( <> ) : ( ))}
  • ))}
{error && (

{error}

)}
); } /* A content request's details (049), labeled from requestTypes.ts; keys it no longer knows are shown as they are. */ function RequestDetails({ row }) { const entries = Object.entries(row.details ?? {}); if (entries.length === 0) return null; const labels = new Map((requestType(row.category)?.fields ?? []).map((f) => [f.key, f.label])); return (
{entries.map(([key, value]) => (
{labels.get(key) ?? key.replace(/_/g, " ")}
{value as string}
))}
); } /* The record a request is about, in its editor: a new one filled in from the request, or, for an update, the existing one (picked here, the closest name first) with the requested values beside its own. Nothing is saved until Save in the editor. */ function RequestRecord({ row }) { const navigate = useNavigate(); const type = requestType(row.category); const [candidates, setCandidates] = useState(null); const [picked, setPicked] = useState(""); const [error, setError] = useState(null); if (!type) return null; const state = { fromRequest: fromRequest(row) }; const button = "rounded-full border border-link px-4 py-1.5 text-sm font-semibold text-link transition-colors hover:bg-tint disabled:opacity-60"; if (row.request_action === "new") { return (
); } async function find() { if (!type) return; setError(null); try { const params = new URLSearchParams({ limit: "500", ...(type.preset ?? {}) }); const { rows } = await get(`/admin/${type.entity}?${params}`, { ttl: 0 }); const wanted = String(row.subject ?? "").toLowerCase().trim(); const name = (r) => String(r[type.heading] ?? r.id); // The closest name first: exact, then containing, then the rest. const score = (r) => { const n = name(r).toLowerCase(); return n === wanted ? 0 : wanted && (n.includes(wanted) || wanted.includes(n)) ? 1 : 2; }; const sorted = [...rows].sort((a, b) => score(a) - score(b) || name(a).localeCompare(name(b))); setCandidates(sorted.map((r) => ({ id: r.id, name: name(r) }))); setPicked(sorted[0]?.id ?? ""); } catch (err) { setError(err instanceof ApiError ? err.message : "Couldn't load the list."); } } return (
{candidates === null ? ( ) : candidates.length === 0 ? ( No {type.label.toLowerCase()} records yet. ) : ( <> )} {error && {error}}
); } function locationOf(row) { if (!row.page_path) return "Not page-specific"; return row.section_id ? `${row.page_path} #${row.section_id}` : row.page_path; } /* ── One submission ──────────────────────────────────────────── */ function FeedbackCard({ row, onChange, onRemove, canWrite, canRemove }) { const [note, setNote] = useState(row.admin_note ?? ""); const [busy, setBusy] = useState(false); const [error, setError] = useState(null); const [confirming, setConfirming] = useState(false); const noteDirty = note !== (row.admin_note ?? ""); async function save(changes) { setBusy(true); setError(null); try { const data = await patch(`/admin/feedback/${row.id}`, changes); onChange(data.feedback); } catch (err) { setError(err instanceof ApiError ? err.message : "Couldn't save that."); } finally { setBusy(false); } } // On success this card unmounts, so there's no finally here: // busy only needs clearing on the path where the row survives. async function remove() { setBusy(true); setError(null); try { await del(`/admin/feedback/${row.id}`); onRemove(row); } catch (err) { setError(err instanceof ApiError ? err.message : "Couldn't delete that."); setConfirming(false); setBusy(false); } } return (
{row.feedback_type === "content" ? `${row.request_action === "update" ? "Update" : "New"} ${requestTypeLabel(row.category).toLowerCase()}` : feedbackTypeLabel(row.feedback_type)} {row.status} {row.feedback_type !== "content" && {locationOf(row)}} #{row.id} · {formatDate(row.created_at)}
{row.subject &&

{row.subject}

}

{row.message}

{row.feedback_type === "content" && } {row.files?.length > 0 && } {row.feedback_type === "content" && canWrite && }

{row.name || row.email ? ( <> {row.name && {row.name}} {row.name && row.email && " · "} {row.email && ( {row.email} )} ) : ( Sent anonymously )}

{canWrite && (