Manage request files: mark missing ones, remove them, list them all

Forms → Content requests and a new Tools → Media → Requests tab (by
type folder, each linked to its request) mark a file Drive no longer
has under Requests as Missing from Drive. Remove (admins and up)
trashes a file and takes it off its request. Drive is asked at most
every 30 seconds, and folder lookups now cache every level walked.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Zaldimmar 2026-09-29 23:25:58 -05:00
parent 9ff1cd6e99
commit e1542d8d87
6 changed files with 292 additions and 32 deletions

View file

@ -81,6 +81,14 @@ matches the one in Forms → Content requests. Deleting a request in the
admin deletes its files from Drive too. Request files from before the admin deletes its files from Drive too. Request files from before the
per-type folders stay where they are, in `Requests` itself. per-type folders stay where they are, in `Requests` itself.
Tools → Media → **Requests** lists every request file by its type folder,
each with its request; Forms → Content requests lists a request's own.
Both say **Missing from Drive** for a file Drive no longer has under
`Requests` (deleted, or moved out, by hand): it can't be downloaded or
made into a post, but can be taken off the request. **Remove** (admins
and up) trashes a file in Drive and takes it off its request; the
request itself stays.
**Deleting means Drive's trash.** Whatever the admin deletes (a **Deleting means Drive's trash.** Whatever the admin deletes (a
request's files, a file, an empty folder) goes to the shared drive's request's files, a file, an empty folder) goes to the shared drive's
trash, which keeps it 30 days; restore it from there if needed. A trash, which keeps it 30 days; restore it from there if needed. A

View file

@ -143,7 +143,12 @@ export function forgetFolders(path) {
async function findOrMakeFolder(path) { async function findOrMakeFolder(path) {
const drive = process.env.GOOGLE_SHARED_DRIVE; const drive = process.env.GOOGLE_SHARED_DRIVE;
let parent = drive; let parent = drive;
const walked = [];
for (const name of path.split("/").filter(Boolean)) { for (const name of path.split("/").filter(Boolean)) {
// Each level on the way is known too: "Requests" once
// "Requests/Chapters" has been found.
if (walked.length && !folders.has(walked.join("/"))) folders.set(walked.join("/"), Promise.resolve(parent));
walked.push(name);
const quoted = name.replace(/\\/g, "\\\\").replace(/'/g, "\\'"); const quoted = name.replace(/\\/g, "\\\\").replace(/'/g, "\\'");
const query = new URLSearchParams({ const query = new URLSearchParams({
q: `name = '${quoted}' and mimeType = '${FOLDER}' and '${parent}' in parents and trashed = false`, q: `name = '${quoted}' and mimeType = '${FOLDER}' and '${parent}' in parents and trashed = false`,

View file

@ -11,7 +11,8 @@
import { Hono } from "hono"; import { Hono } from "hono";
import { requireAuth, requireRole } from "../auth.js"; import { requireAuth, requireRole } from "../auth.js";
import { NO_STORE } from "../shape.js"; import { NO_STORE } from "../shape.js";
import { driveDelete, driveDownload } from "../googleService.js"; import { driveDelete, driveDownload, driveReady, driveTree } from "../googleService.js";
import { DRIVE_FOLDER, TYPE_FOLDERS } from "./requests.js";
import { HttpError } from "../admin-crud.js"; import { HttpError } from "../admin-crud.js";
import { importDocx } from "./import.js"; import { importDocx } from "./import.js";
@ -32,12 +33,31 @@ const KIND_WHERE = {
const COLUMNS = `id, created_at, feedback_type, message, name, email, page_path, section_id, const COLUMNS = `id, created_at, feedback_type, message, name, email, page_path, section_id,
status, admin_note, category, request_action, subject, details`; status, admin_note, category, request_action, subject, details`;
/* Each row with its files (content requests), in one query. */ /* The ids of every file under Requests in Drive (any type folder),
function withFiles(db, rows) { looked up at most every 30 seconds; null when Drive isn't set up or
didn't answer, which marks nothing missing. A file someone deleted
or moved out of Requests in Drive is then "missing". */
let inDrive = { at: 0, ids: null };
async function requestFilesInDrive() {
if (!driveReady()) return null;
if (Date.now() - inDrive.at < 30_000) return inDrive.ids;
try {
const tree = await driveTree(DRIVE_FOLDER, 2);
inDrive = { at: Date.now(), ids: new Set(tree.files.map((f) => f.id)) };
} catch (err) {
console.warn(`feedback: couldn't list ${DRIVE_FOLDER} in Drive: ${err.message}`);
inDrive = { at: Date.now(), ids: null };
}
return inDrive.ids;
}
/* Each row with its files (content requests), in one query. `ids`
(requestFilesInDrive) says which are still in Drive. */
function withFiles(db, rows, ids = null) {
if (rows.length === 0) return rows; if (rows.length === 0) return rows;
const files = db const files = db
.prepare( .prepare(
`SELECT id, feedback_id, name, mime, size FROM feedback_files `SELECT id, feedback_id, drive_id, name, mime, size FROM feedback_files
WHERE feedback_id IN (${rows.map(() => "?").join(",")}) ORDER BY id`, WHERE feedback_id IN (${rows.map(() => "?").join(",")}) ORDER BY id`,
) )
.all(...rows.map((r) => r.id)); .all(...rows.map((r) => r.id));
@ -45,7 +65,9 @@ function withFiles(db, rows) {
...row, ...row,
// Stored as JSON text (049); the admin wants the object. // Stored as JSON text (049); the admin wants the object.
details: row.details ? JSON.parse(row.details) : null, details: row.details ? JSON.parse(row.details) : null,
files: files.filter((f) => f.feedback_id === row.id).map(({ feedback_id, ...f }) => f), files: files
.filter((f) => f.feedback_id === row.id)
.map(({ feedback_id, drive_id, ...f }) => ({ ...f, missing: ids ? !ids.has(drive_id) : false })),
})); }));
} }
const MAX_LIMIT = 200; const MAX_LIMIT = 200;
@ -62,7 +84,7 @@ const NOTE_LIMIT = 2000;
?limit=50 ?limit=50
───────────────────────────────────────────────────────────── */ ───────────────────────────────────────────────────────────── */
admin.get("/feedback", (c) => { admin.get("/feedback", async (c) => {
const db = c.get("db"); const db = c.get("db");
const { status, type, kind, q, before, limit } = c.req.query(); const { status, type, kind, q, before, limit } = c.req.query();
@ -102,7 +124,7 @@ admin.get("/feedback", (c) => {
.all(...params, take + 1); // one extra to detect a next page .all(...params, take + 1); // one extra to detect a next page
const hasMore = rows.length > take; const hasMore = rows.length > take;
const page = withFiles(db, hasMore ? rows.slice(0, take) : rows); const page = withFiles(db, hasMore ? rows.slice(0, take) : rows, kind === "content" ? await requestFilesInDrive() : null);
// Status counts cover this queue (kind) but ignore the other // Status counts cover this queue (kind) but ignore the other
// filters: the tabs show what's waiting, not what's left after a // filters: the tabs show what's waiting, not what's left after a
@ -172,7 +194,7 @@ admin.patch("/feedback/:id", requireRole("editor"), async (c) => {
if (sets.length === 0) return c.json({ error: "Nothing to change." }, 400); if (sets.length === 0) return c.json({ error: "Nothing to change." }, 400);
const result = db_update(c.get("db"), id, sets, params); const result = db_update(c.get("db"), id, sets, params, await requestFilesInDrive());
if (!result) return c.json({ error: "No such feedback." }, 404); if (!result) return c.json({ error: "No such feedback." }, 404);
console.log(`feedback #${id} updated by ${c.get("user").email}`); console.log(`feedback #${id} updated by ${c.get("user").email}`);
@ -180,14 +202,14 @@ admin.patch("/feedback/:id", requireRole("editor"), async (c) => {
return c.json({ feedback: result }, 200, NO_STORE); return c.json({ feedback: result }, 200, NO_STORE);
}); });
function db_update(db, id, sets, params) { function db_update(db, id, sets, params, ids) {
const changed = db const changed = db
.prepare(`UPDATE feedback SET ${sets.join(", ")} WHERE id = ?`) .prepare(`UPDATE feedback SET ${sets.join(", ")} WHERE id = ?`)
.run(...params, id); .run(...params, id);
if (changed.changes === 0) return null; if (changed.changes === 0) return null;
return withFiles(db, [db.prepare(`SELECT ${COLUMNS} FROM feedback WHERE id = ?`).get(id)])[0]; return withFiles(db, [db.prepare(`SELECT ${COLUMNS} FROM feedback WHERE id = ?`).get(id)], ids)[0];
} }
/* ── DELETE /api/admin/feedback/:id ────────────────────────────── /* ── DELETE /api/admin/feedback/:id ──────────────────────────────
@ -221,9 +243,13 @@ admin.delete("/feedback/:id", requireRole("admin"), async (c) => {
}); });
/* ── A content request's files ─────────────────────────────────── /* ── A content request's files ───────────────────────────────────
GET /feedback/:id/files/:file download, from Drive GET /feedback/:id/files/:file download, from Drive
POST /feedback/:id/files/:file/blog-post a .docx as a new POST /feedback/:id/files/:file/blog-post a .docx as a new
unpublished blog post (import.js), editors and up unpublished blog post (import.js), editors and up
DELETE /feedback/:id/files/:file into Drive's trash and
off the request, admins and up
GET /request-files every request's files,
by type folder, for Tools → Media → Requests
───────────────────────────────────────────────────────────── */ ───────────────────────────────────────────────────────────── */
function fileOf(c) { function fileOf(c) {
@ -270,4 +296,45 @@ admin.post("/feedback/:id/files/:file/blog-post", requireRole("editor"), async (
} }
}); });
admin.delete("/feedback/:id/files/:file", requireRole("admin"), async (c) => {
const file = fileOf(c);
if (!file) return c.json({ error: "No such file." }, 404);
try {
await driveDelete(file.drive_id);
} catch (err) {
// Already gone from Drive: the row goes anyway.
if (!/^404 /.test(err.message)) return c.json({ error: `Google Drive didn't delete it: ${err.message}` }, 502);
}
c.get("db").prepare(`DELETE FROM feedback_files WHERE id = ?`).run(file.id);
inDrive.ids?.delete(file.drive_id);
console.log(`feedback #${c.req.param("id")}: file ${file.name} removed by ${c.get("user").email}`);
return c.body(null, 204);
});
admin.get("/request-files", async (c) => {
const db = c.get("db");
const ids = await requestFilesInDrive();
const rows = db
.prepare(
`SELECT f.id, f.feedback_id, f.drive_id, f.name, f.mime, f.size,
r.category, r.subject, r.request_action, r.status, r.created_at
FROM feedback_files f JOIN feedback r ON r.id = f.feedback_id
ORDER BY r.id DESC, f.id`,
)
.all();
return c.json(
{
files: rows.map(({ drive_id, ...row }) => ({
...row,
folder: TYPE_FOLDERS[row.category] ?? "",
missing: ids ? !ids.has(drive_id) : false,
})),
folders: Object.values(TYPE_FOLDERS),
checked: ids !== null,
},
200,
NO_STORE,
);
});
export default admin; export default admin;

View file

@ -65,8 +65,8 @@ export function cleanDetails(raw) {
const MIN_MESSAGE = 10; const MIN_MESSAGE = 10;
// Where in the shared drive the files go (googleService.js): a // Where in the shared drive the files go (googleService.js): a
// folder per type under Requests, eg. Requests/Chapters. // folder per type under Requests, eg. Requests/Chapters.
const DRIVE_FOLDER = "Requests"; export const DRIVE_FOLDER = "Requests";
const TYPE_FOLDERS = { export const TYPE_FOLDERS = {
blog: "Blog Posts", blog: "Blog Posts",
event: "Events", event: "Events",
chapter: "Chapters", chapter: "Chapters",

View file

@ -52,10 +52,13 @@ const sizeOf = (bytes) => (bytes < 1024 * 1024 ? `${Math.ceil(bytes / 1024)} KB`
/* A content request's files: each downloads from Drive through the /* A content request's files: each downloads from Drive through the
server, and a Word document can become a draft blog post server, and a Word document can become a draft blog post
(the same import as Blog posts → Import from Word). */ (the same import as Blog posts → Import from Word). */
function RequestFiles({ row, canWrite }) { function RequestFiles({ row, canWrite, canRemove }) {
const navigate = useNavigate(); const navigate = useNavigate();
const [files, setFiles] = useState<any[]>(row.files);
const [busy, setBusy] = useState<number | null>(null); const [busy, setBusy] = useState<number | null>(null);
const [confirming, setConfirming] = useState<number | null>(null);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
useEffect(() => setFiles(row.files), [row.files]);
async function makePost(file) { async function makePost(file) {
setBusy(file.id); setBusy(file.id);
@ -69,29 +72,81 @@ function RequestFiles({ row, canWrite }) {
} }
} }
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 ( return (
<div className="mt-4"> <div className="mt-4">
<ul className="space-y-2"> <ul className="space-y-2">
{row.files.map((file) => ( {files.map((file) => (
<li key={file.id} className="flex flex-wrap items-center gap-x-3 gap-y-1 text-sm"> <li key={file.id} className="flex flex-wrap items-center gap-x-3 gap-y-1 text-sm">
<a {file.missing ? (
href={`/api/admin/feedback/${row.id}/files/${file.id}`} // Deleted or moved out of Requests in Drive: nothing to open.
download={file.name} <span className="font-medium text-muted line-through">{file.name}</span>
className="font-medium text-link underline underline-offset-2" ) : (
> <a
{file.name} href={`/api/admin/feedback/${row.id}/files/${file.id}`}
</a> download={file.name}
className="font-medium text-link underline underline-offset-2"
>
{file.name}
</a>
)}
<span className="text-xs text-muted">{sizeOf(file.size)}</span> <span className="text-xs text-muted">{sizeOf(file.size)}</span>
{canWrite && /\.docx$/i.test(file.name) && ( {file.missing && (
<span className="rounded-full bg-danger-tint px-2 py-0.5 text-xs font-medium text-danger">
Missing from Drive
</span>
)}
{canWrite && !file.missing && /\.docx$/i.test(file.name) && (
<button <button
type="button" type="button"
disabled={busy !== null} disabled={busy !== null}
onClick={() => makePost(file)} onClick={() => makePost(file)}
className="rounded-full border border-link px-3 py-0.5 text-xs font-semibold text-link transition-colors hover:bg-tint disabled:opacity-60" className={`${small} border-link text-link hover:bg-tint`}
> >
{busy === file.id ? "Making the post…" : "Make a blog post from it"} {busy === file.id ? "Making the post…" : "Make a blog post from it"}
</button> </button>
)} )}
{canRemove &&
(confirming === file.id ? (
<>
<button
type="button"
disabled={busy !== null}
onClick={() => remove(file)}
className={`${small} border-danger bg-danger text-white`}
>
{busy === file.id ? "Removing…" : "Remove it"}
</button>
<button type="button" onClick={() => setConfirming(null)} className="text-xs text-muted hover:underline">
Keep it
</button>
</>
) : (
<button
type="button"
disabled={busy !== null}
onClick={() => setConfirming(file.id)}
className="text-xs text-muted hover:text-danger"
title={file.missing ? "Take it off this request" : "Into Drive's trash, and off this request"}
>
Remove
</button>
))}
</li> </li>
))} ))}
</ul> </ul>
@ -276,7 +331,7 @@ function FeedbackCard({ row, onChange, onRemove, canWrite, canRemove }) {
{row.subject && <h2 className="mt-4 text-lg font-semibold text-body">{row.subject}</h2>} {row.subject && <h2 className="mt-4 text-lg font-semibold text-body">{row.subject}</h2>}
<p className={`${row.subject ? "mt-2" : "mt-4"} whitespace-pre-wrap text-body`}>{row.message}</p> <p className={`${row.subject ? "mt-2" : "mt-4"} whitespace-pre-wrap text-body`}>{row.message}</p>
{row.feedback_type === "content" && <RequestDetails row={row} />} {row.feedback_type === "content" && <RequestDetails row={row} />}
{row.files?.length > 0 && <RequestFiles row={row} canWrite={canWrite} />} {row.files?.length > 0 && <RequestFiles row={row} canWrite={canWrite} canRemove={canRemove} />}
{row.feedback_type === "content" && canWrite && <RequestRecord row={row} />} {row.feedback_type === "content" && canWrite && <RequestRecord row={row} />}
<p className="mt-4 text-sm text-muted"> <p className="mt-4 text-sm text-muted">

View file

@ -7,7 +7,9 @@
(MediaLibrary.tsx), so this is housekeeping rather than the way (MediaLibrary.tsx), so this is housekeeping rather than the way
images get in. Files: documents, audio and zips in the shared images get in. Files: documents, audio and zips in the shared
Google Drive, for pages to link to (DriveFiles.tsx); link fields' Google Drive, for pages to link to (DriveFiles.tsx); link fields'
"Choose a file" picks from them. "Choose a file" picks from them. Requests: every file sent with
the Request form, by type folder in Drive, each with its request;
a file Drive no longer has is marked missing.
Two ranks, as on the server: editors and up upload, admins and Two ranks, as on the server: editors and up upload, admins and
up delete. A delete first asks the server which records still up delete. A delete first asks the server which records still
@ -15,7 +17,8 @@
a page (an image field stores the path, not a foreign key). a page (an image field stores the path, not a foreign key).
═══════════════════════════════════════════════════════════════ */ ═══════════════════════════════════════════════════════════════ */
import { useState } from "react"; import { useEffect, useState } from "react";
import { Link } from "react-router-dom";
import { ApiError, del, get, patch, post } from "../../lib/api.ts"; import { ApiError, del, get, patch, post } from "../../lib/api.ts";
import { useAuth } from "../../lib/auth.tsx"; import { useAuth } from "../../lib/auth.tsx";
@ -33,6 +36,7 @@ import {
} from "../../components/admin/DriveFiles.tsx"; } from "../../components/admin/DriveFiles.tsx";
import { import {
FolderTabs, FolderTabs,
formatBytes,
MediaGrid, MediaGrid,
UPLOAD_HELP, UPLOAD_HELP,
UploadButton, UploadButton,
@ -356,14 +360,131 @@ function FilesTab() {
); );
} }
/* Request form files, by their type's folder in Drive (Requests/…). */
function RequestFilesTab() {
const { user } = useAuth();
const [data, setData] = useState<any>(null);
const [error, setError] = useState<string | null>(null);
const [folder, setFolder] = useState("*");
const [confirming, setConfirming] = useState<number | null>(null);
const [busy, setBusy] = useState(false);
useEffect(() => {
get("/admin/request-files", { ttl: 0 })
.then(setData)
.catch((err) => setError(err instanceof ApiError ? err.message : "Couldn't load the request files."));
}, []);
async function remove(file) {
setBusy(true);
setError(null);
try {
await del(`/admin/feedback/${file.feedback_id}/files/${file.id}`);
setData((current) => ({ ...current, files: current.files.filter((f) => f.id !== file.id) }));
} catch (err) {
setError(err instanceof ApiError ? err.message : "Couldn't remove it.");
} finally {
setBusy(false);
setConfirming(null);
}
}
if (error && !data) return <p className="mt-6 text-sm text-danger">{error}</p>;
if (!data) return <p className="mt-6 text-sm text-muted">Loading…</p>;
const counts = new Map<string, number>();
for (const f of data.files) counts.set(f.folder, (counts.get(f.folder) ?? 0) + 1);
const shown = folder === "*" ? data.files : data.files.filter((f) => f.folder === folder);
return (
<div className="mt-6">
<div role="tablist" aria-label="Request folders" className="flex flex-wrap gap-1">
{[["*", "All"], ...data.folders.map((f) => [f, f])].map(([id, label]) => (
<button
key={id}
type="button"
role="tab"
aria-selected={folder === id}
onClick={() => setFolder(id)}
className={
"rounded-full px-3 py-1 text-sm transition-colors " +
(folder === id ? "bg-action font-semibold text-white" : "border border-muted/25 text-muted hover:border-brand/50")
}
>
{label}
{id !== "*" && counts.get(id) ? ` (${counts.get(id)})` : ""}
</button>
))}
</div>
{!data.checked && (
<p className="mt-3 text-sm text-muted">Drive couldn't be asked just now, so missing files aren't marked.</p>
)}
{error && <p className="mt-3 text-sm text-danger">{error}</p>}
{shown.length === 0 ? (
<p className="mt-6 text-sm text-muted">No request files here.</p>
) : (
<ul className="mt-6 divide-y divide-brand/10 rounded-2xl border border-brand/20 bg-surface">
{shown.map((file) => (
<li key={file.id} className="flex flex-wrap items-center gap-x-4 gap-y-1 px-4 py-3 text-sm">
{file.missing ? (
<span className="font-medium text-muted line-through">{file.name}</span>
) : (
<a
href={`/api/admin/feedback/${file.feedback_id}/files/${file.id}`}
download={file.name}
className="font-medium text-link underline underline-offset-2"
>
{file.name}
</a>
)}
<span className="text-xs text-muted">{formatBytes(file.size)}</span>
{file.missing && (
<span className="rounded-full bg-danger-tint px-2 py-0.5 text-xs font-medium text-danger">Missing from Drive</span>
)}
<Link to="/admin/requests" className="text-xs text-muted hover:text-link hover:underline">
Request #{file.feedback_id}
{file.subject ? `: ${file.subject}` : ""} ({file.status})
</Link>
{canDelete(user) && (
<span className="ml-auto">
{confirming === file.id ? (
<>
<button
type="button"
disabled={busy}
onClick={() => remove(file)}
className="rounded-full bg-danger px-3 py-0.5 text-xs font-semibold text-white disabled:opacity-60"
>
{busy ? "Removing…" : "Remove it"}
</button>{" "}
<button type="button" onClick={() => setConfirming(null)} className="text-xs text-muted hover:underline">
Keep it
</button>
</>
) : (
<button type="button" onClick={() => setConfirming(file.id)} className="text-xs text-muted hover:text-danger">
Remove
</button>
)}
</span>
)}
</li>
))}
</ul>
)}
</div>
);
}
const TABS = [ const TABS = [
["images", "Images"], ["images", "Images"],
["files", "Files"], ["files", "Files"],
["requests", "Requests"],
] as const; ] as const;
export default function AdminMedia() { export default function AdminMedia() {
const { user } = useAuth(); const { user } = useAuth();
const [tab, setTab] = useState<"images" | "files">("images"); const [tab, setTab] = useState<(typeof TABS)[number][0]>("images");
// The image folder showing; "" is all of them, clips included. // The image folder showing; "" is all of them, clips included.
const [folder, setFolder] = useState(""); const [folder, setFolder] = useState("");
const [query, setQuery] = useState(""); const [query, setQuery] = useState("");
@ -376,7 +497,9 @@ export default function AdminMedia() {
<p className="text-sm text-muted"> <p className="text-sm text-muted">
{tab === "images" {tab === "images"
? "Uploaded images. Image fields in every editor pick from here." ? "Uploaded images. Image fields in every editor pick from here."
: "Files in the shared Google Drive's Media folder, for pages to link to, including any put there in Drive itself. Link fields pick from here with Choose a file."} : tab === "files"
? "Files in the shared Google Drive's Media folder, for pages to link to, including any put there in Drive itself. Link fields pick from here with Choose a file."
: "Files sent with the Request form, in the shared Google Drive's Requests folder. Removing one takes it off its request too."}
</p> </p>
</div> </div>
@ -397,7 +520,9 @@ export default function AdminMedia() {
))} ))}
</nav> </nav>
{tab === "files" ? ( {tab === "requests" ? (
<RequestFilesTab />
) : tab === "files" ? (
<FilesTab /> <FilesTab />
) : ( ) : (
<> <>