From e1542d8d878cb44c472aa20fb22378553be69686 Mon Sep 17 00:00:00 2001 From: Zaldimmar Date: Tue, 29 Sep 2026 23:25:58 -0500 Subject: [PATCH] Manage request files: mark missing ones, remove them, list them all MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 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 --- docs/google-drive-and-mail.md | 8 ++ server/src/googleService.js | 5 ++ server/src/routes/admin.js | 93 +++++++++++++++++--- server/src/routes/requests.js | 4 +- src/pages/admin/AdminFeedback.tsx | 79 ++++++++++++++--- src/pages/admin/AdminMedia.tsx | 135 ++++++++++++++++++++++++++++-- 6 files changed, 292 insertions(+), 32 deletions(-) diff --git a/docs/google-drive-and-mail.md b/docs/google-drive-and-mail.md index f045dbb..2789404 100644 --- a/docs/google-drive-and-mail.md +++ b/docs/google-drive-and-mail.md @@ -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 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 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 diff --git a/server/src/googleService.js b/server/src/googleService.js index 31bf976..e1234d2 100644 --- a/server/src/googleService.js +++ b/server/src/googleService.js @@ -143,7 +143,12 @@ export function forgetFolders(path) { async function findOrMakeFolder(path) { const drive = process.env.GOOGLE_SHARED_DRIVE; let parent = drive; + const walked = []; 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 query = new URLSearchParams({ q: `name = '${quoted}' and mimeType = '${FOLDER}' and '${parent}' in parents and trashed = false`, diff --git a/server/src/routes/admin.js b/server/src/routes/admin.js index 85ec0ff..47cc1a1 100644 --- a/server/src/routes/admin.js +++ b/server/src/routes/admin.js @@ -11,7 +11,8 @@ import { Hono } from "hono"; import { requireAuth, requireRole } from "../auth.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 { 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, status, admin_note, category, request_action, subject, details`; -/* Each row with its files (content requests), in one query. */ -function withFiles(db, rows) { +/* The ids of every file under Requests in Drive (any type folder), + 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; const files = db .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`, ) .all(...rows.map((r) => r.id)); @@ -45,7 +65,9 @@ function withFiles(db, rows) { ...row, // Stored as JSON text (049); the admin wants the object. 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; @@ -62,7 +84,7 @@ const NOTE_LIMIT = 2000; ?limit=50 ───────────────────────────────────────────────────────────── */ -admin.get("/feedback", (c) => { +admin.get("/feedback", async (c) => { const db = c.get("db"); 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 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 // 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); - 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); 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); }); -function db_update(db, id, sets, params) { +function db_update(db, id, sets, params, ids) { const changed = db .prepare(`UPDATE feedback SET ${sets.join(", ")} WHERE id = ?`) .run(...params, id); 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 ────────────────────────────── @@ -221,9 +243,13 @@ admin.delete("/feedback/:id", requireRole("admin"), async (c) => { }); /* ── A content request's files ─────────────────────────────────── - GET /feedback/:id/files/:file download, from Drive - POST /feedback/:id/files/:file/blog-post a .docx as a new - unpublished blog post (import.js), editors and up + GET /feedback/:id/files/:file download, from Drive + POST /feedback/:id/files/:file/blog-post a .docx as a new + 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) { @@ -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; diff --git a/server/src/routes/requests.js b/server/src/routes/requests.js index cca84a6..f64872d 100644 --- a/server/src/routes/requests.js +++ b/server/src/routes/requests.js @@ -65,8 +65,8 @@ export function cleanDetails(raw) { const MIN_MESSAGE = 10; // Where in the shared drive the files go (googleService.js): a // folder per type under Requests, eg. Requests/Chapters. -const DRIVE_FOLDER = "Requests"; -const TYPE_FOLDERS = { +export const DRIVE_FOLDER = "Requests"; +export const TYPE_FOLDERS = { blog: "Blog Posts", event: "Events", chapter: "Chapters", diff --git a/src/pages/admin/AdminFeedback.tsx b/src/pages/admin/AdminFeedback.tsx index 83b2129..705e8fe 100644 --- a/src/pages/admin/AdminFeedback.tsx +++ b/src/pages/admin/AdminFeedback.tsx @@ -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 server, and a Word document can become a draft blog post (the same import as Blog posts → Import from Word). */ -function RequestFiles({ row, canWrite }) { +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); @@ -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 (
    - {row.files.map((file) => ( + {files.map((file) => (
  • - - {file.name} - + {file.missing ? ( + // Deleted or moved out of Requests in Drive: nothing to open. + {file.name} + ) : ( + + {file.name} + + )} {sizeOf(file.size)} - {canWrite && /\.docx$/i.test(file.name) && ( + {file.missing && ( + + Missing from Drive + + )} + {canWrite && !file.missing && /\.docx$/i.test(file.name) && ( )} + {canRemove && + (confirming === file.id ? ( + <> + + + + ) : ( + + ))}
  • ))}
@@ -276,7 +331,7 @@ function FeedbackCard({ row, onChange, onRemove, canWrite, canRemove }) { {row.subject &&

{row.subject}

}

{row.message}

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

diff --git a/src/pages/admin/AdminMedia.tsx b/src/pages/admin/AdminMedia.tsx index 2f91851..f16c784 100644 --- a/src/pages/admin/AdminMedia.tsx +++ b/src/pages/admin/AdminMedia.tsx @@ -7,7 +7,9 @@ (MediaLibrary.tsx), so this is housekeeping rather than the way images get in. Files: documents, audio and zips in the shared 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 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). ═══════════════════════════════════════════════════════════════ */ -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 { useAuth } from "../../lib/auth.tsx"; @@ -33,6 +36,7 @@ import { } from "../../components/admin/DriveFiles.tsx"; import { FolderTabs, + formatBytes, MediaGrid, UPLOAD_HELP, 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(null); + const [error, setError] = useState(null); + const [folder, setFolder] = useState("*"); + const [confirming, setConfirming] = useState(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

{error}

; + if (!data) return

Loading…

; + const counts = new Map(); + 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 ( +
+
+ {[["*", "All"], ...data.folders.map((f) => [f, f])].map(([id, label]) => ( + + ))} +
+ {!data.checked && ( +

Drive couldn't be asked just now, so missing files aren't marked.

+ )} + {error &&

{error}

} + + {shown.length === 0 ? ( +

No request files here.

+ ) : ( +
    + {shown.map((file) => ( +
  • + {file.missing ? ( + {file.name} + ) : ( + + {file.name} + + )} + {formatBytes(file.size)} + {file.missing && ( + Missing from Drive + )} + + Request #{file.feedback_id} + {file.subject ? `: ${file.subject}` : ""} ({file.status}) + + {canDelete(user) && ( + + {confirming === file.id ? ( + <> + {" "} + + + ) : ( + + )} + + )} +
  • + ))} +
+ )} +
+ ); +} + const TABS = [ ["images", "Images"], ["files", "Files"], + ["requests", "Requests"], ] as const; export default function AdminMedia() { 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. const [folder, setFolder] = useState(""); const [query, setQuery] = useState(""); @@ -376,7 +497,9 @@ export default function AdminMedia() {

{tab === "images" ? "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."}

@@ -397,7 +520,9 @@ export default function AdminMedia() { ))} - {tab === "files" ? ( + {tab === "requests" ? ( + + ) : tab === "files" ? ( ) : ( <>