Cleanup of old-data fixes; an editor for the Organization page

Nothing before these changes was ever public, so the fixes kept for
older data go: the /leadership redirect (MOVED in routes/pages.js),
index.html's move of "ngu-" browser keys to "site-", the boot-time
sorting of images from before folders (media.js), and emoji path
icons (a path with no named icon shows a dot; migration 055 turns
the baseline's seeded emoji into their names).

Pages → Organization page (migration 055): a singleton with the
Mission, Vision & Values blocks, the Leadership blocks (a People
block per team, in order) with a heading and blurb, and Volunteering
(title, blurb, links). content_blocks gains the two owner kinds;
GET /organization-page serves it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Zaldimmar 2026-09-30 23:37:35 -05:00
parent 1da79c128b
commit 43797f38bc
14 changed files with 308 additions and 127 deletions

View file

@ -51,6 +51,7 @@ import { timeline } from "./admin-schema/timeline.js";
import { frontPage } from "./admin-schema/frontPage.js";
import { blogPosts, communityPage } from "./admin-schema/blog.js";
import { siteSettings } from "./admin-schema/siteSettings.js";
import { organizationPage } from "./admin-schema/organizationPage.js";
export const ENTITIES = {
organizations,
@ -62,6 +63,7 @@ export const ENTITIES = {
front_page: frontPage,
blog_posts: blogPosts,
community_page: communityPage,
organization_page: organizationPage,
site_settings: siteSettings,
};

View file

@ -0,0 +1,43 @@
/* The Organization page (/organization): one row, its blocks and its
volunteering links (055_organization_page.sql). Two block
collections, each its own owner kind, so the editor shows them
apart: the Mission, Vision & Values section, and the Leadership
section (a People block per team, in order). */
import { text, url, blocksChild } from "./columns.js";
export const organizationPage = {
key: "organization_page",
table: "organization_page",
idColumn: "id",
idKind: "slug",
singleton: "organization",
concurrency: "updated_at",
list: {
columns: ["id", "updated_at"],
filters: [],
search: [],
order: "id",
},
columns: [
text("mission_title"),
text("leadership_title"),
text("leadership_blurb"),
text("volunteer_title"),
text("volunteer_blurb"),
],
children: [
{ ...blocksChild("org_page_mission"), key: "mission_blocks" },
{ ...blocksChild("org_page_leadership"), key: "leadership_blocks" },
{
key: "volunteer_links",
table: "organization_page_links",
owner: { column: "page_id" },
order: "sort_order",
columns: [text("label", { required: true }), url("url", { required: true })],
},
],
};

View file

@ -26,6 +26,7 @@ import history from "./routes/history.js";
import home from "./routes/home.js";
import directory from "./routes/directory.js";
import blog from "./routes/blog.js";
import organizationPage from "./routes/organizationPage.js";
import pages from "./routes/pages.js";
import feedback from "./routes/feedback.js";
import requests from "./routes/requests.js";
@ -38,7 +39,7 @@ import clips from "./routes/clips.js";
import imports from "./routes/import.js";
import files from "./routes/files.js";
import { CLIPS_DIR, startClipWorker } from "./clips.js";
import { UPLOADS_DIR, sortIntoFolders, writeMissingThumbs } from "./media.js";
import { UPLOADS_DIR, writeMissingThumbs } from "./media.js";
import { logSafe, startSessionSweeper } from "./auth.js";
import { syncDescriptorsWithSchema } from "./admin-schema-sync.js";
import { startGroupSync } from "./accessGroups.js";
@ -57,9 +58,6 @@ syncDescriptorsWithSchema(db, ENTITIES);
console.log(`db ${DB_PATH} (${db.driverName}, schema v${version})`);
await mkdir(UPLOADS_DIR, { recursive: true });
console.log(`uploads ${UPLOADS_DIR}`);
// Once: images from before folders into logos/, images/, thumbnails/.
const sorted = await sortIntoFolders(db);
if (sorted) console.log(`uploads: moved ${sorted} image(s) into folders`);
// In the background: pages fall back to the full file until it's done.
writeMissingThumbs()
.then((made) => made && console.log(`uploads: made ${made} small copies`))
@ -172,6 +170,7 @@ app.route("/api", history);
app.route("/api", home);
app.route("/api", directory);
app.route("/api", blog);
app.route("/api", organizationPage);
// Tighter limit on the write path than anything else gets.
app.use("/api/feedback", rateLimit({ windowMs: 60_000, max: 5 }));

View file

@ -36,8 +36,7 @@
by itself (link previews, Drive files' first pages), images/ for
the rest. A stored name includes it: 'logos/3f9c….webp', served at
/uploads/logos/3f9c….webp. The small copy sits beside it. Clips
and files from before folders keep a bare name in the root.
sortIntoFolders() moves those older images once, at boot.
keep a bare name in the root.
── Files copied in by hand ──
A file put straight into UPLOADS_DIR has no media row, so the
@ -51,7 +50,6 @@
import { randomBytes } from "node:crypto";
import { tx } from "./db.js";
import { mkdir, readFile, readdir, rename, stat, unlink, writeFile } from "node:fs/promises";
import path from "node:path";
@ -373,83 +371,4 @@ export async function registerLooseFiles(db) {
// Columns that hold a logo or a site icon: an image one of these
// names goes in logos/.
const LOGO_COLUMNS = new Set(["logo", "org_logo", "event_logo", "favicon", "apple_touch_icon"]);
// Tables whose text never names an upload a page uses.
const NOT_CONTENT = new Set(["media", "admin_users", "sessions", "feedback", "feedback_files", "sqlite_sequence"]);
/* Every image still in the root from before folders, moved into the
folder its uses call for (logos/ if a logo or icon field names it,
thumbnails/ if the site saved it as a preview, else images/), with
every record that names it rewritten to the new path. The files
move first; the rows change in one transaction, and if that fails
the files move back. Returns how many moved; run at boot, and a
no-op once nothing is left in the root. */
export async function sortIntoFolders(db) {
const rows = db
.prepare(
`SELECT id, filename, original_name FROM media
WHERE instr(filename, '/') = 0 AND content_type LIKE 'image/%'`,
)
.all();
if (rows.length === 0) return 0;
const columns = [];
for (const { name: table } of db
.prepare(`SELECT name FROM sqlite_schema WHERE type = 'table' AND name NOT LIKE 'sqlite_%'`)
.all()) {
if (NOT_CONTENT.has(table)) continue;
for (const col of db.prepare(`SELECT name, type FROM pragma_table_info(?)`).all(table)) {
if (col.type.toUpperCase() === "TEXT") columns.push({ table, column: col.name });
}
}
const namesOf = (filename) => [
...new Set([`${PUBLIC_PREFIX}${filename}`, `${PUBLIC_PREFIX}${encodeURIComponent(filename)}`, filename]),
];
const holds = (table, column, values) =>
db
.prepare(`SELECT 1 FROM "${table}" WHERE "${column}" IN (${values.map(() => "?").join(", ")}) LIMIT 1`)
.get(...values);
const moved = [];
for (const row of rows) {
const values = namesOf(row.filename);
const folder = columns.some(({ table, column }) => LOGO_COLUMNS.has(column) && holds(table, column, values))
? "logos"
: /^preview |\(preview\)$/.test(row.original_name) || holds("drive_files", "preview", values)
? "thumbnails"
: "images";
const to = `${folder}/${row.filename}`;
try {
await mkdir(path.join(UPLOADS_DIR, folder), { recursive: true });
await rename(path.join(UPLOADS_DIR, row.filename), path.join(UPLOADS_DIR, to));
} catch (err) {
// Not on disk (deleted by hand): leave its row as it is.
if (err.code !== "ENOENT") console.warn(`media: couldn't move ${row.filename}: ${err.message}`);
continue;
}
await rename(path.join(UPLOADS_DIR, thumbName(row.filename)), path.join(UPLOADS_DIR, thumbName(to))).catch(() => {});
moved.push({ row, to, values });
}
try {
tx(db, () => {
for (const { row, to, values } of moved) {
db.prepare(`UPDATE media SET filename = ? WHERE id = ?`).run(to, row.id);
for (const { table, column } of columns) {
db.prepare(`UPDATE "${table}" SET "${column}" = ? WHERE "${column}" IN (${values.map(() => "?").join(", ")})`).run(
publicPath(to),
...values,
);
}
}
});
} catch (err) {
for (const { row, to } of moved) {
await rename(path.join(UPLOADS_DIR, to), path.join(UPLOADS_DIR, row.filename)).catch(() => {});
await rename(path.join(UPLOADS_DIR, thumbName(to)), path.join(UPLOADS_DIR, thumbName(row.filename))).catch(() => {});
}
throw err;
}
return moved.length;
}

View file

@ -0,0 +1,134 @@
-- ═══════════════════════════════════════════════════════════════
-- 055 THE ORGANIZATION PAGE'S OWN EDITOR, NAMED PATH ICONS
--
-- The Organization page (/organization) is edited in the admin like
-- the Community blog section (Pages → Organization page): a
-- singleton row, organization_page, with
--
-- mission blocks content_blocks owned 'org_page_mission':
-- the Mission, Vision & Values section
-- leadership blocks content_blocks owned 'org_page_leadership':
-- the Leadership section, eg. a heading and a
-- People block per team (Board of Trustees,
-- then the Retreat Team), in the order given
-- volunteering a title, a blurb and organization_page_links,
-- under the leadership
--
-- Two owner kinds rather than a slot, so each list is its own
-- collection in the editor. The owner_kind CHECK changes, so
-- content_blocks is rebuilt as 054 did, with its index and owner
-- trigger (which learns the new kinds) again.
--
-- And the front page's "Find your way in" paths: the baseline seeded
-- them with emoji, from before the named icon list
-- (src/data/pathIcons.ts). The site now draws only named icons, so
-- the seeded emoji become their names and any other non-name is
-- cleared (shown as a plain dot until one is picked).
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE organization_page (
id TEXT PRIMARY KEY CHECK (id = 'organization'),
mission_title TEXT, -- null → 'Mission, Vision & Values'
leadership_title TEXT, -- null → 'Leadership'
leadership_blurb TEXT,
volunteer_title TEXT, -- null → 'Volunteering'
volunteer_blurb TEXT,
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
) STRICT;
INSERT INTO organization_page (id) VALUES ('organization');
CREATE TABLE organization_page_links (
id INTEGER PRIMARY KEY AUTOINCREMENT,
page_id TEXT NOT NULL REFERENCES organization_page (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
label TEXT NOT NULL,
url TEXT NOT NULL
) STRICT;
CREATE INDEX organization_page_links_idx ON organization_page_links (page_id, sort_order);
-- ── Blocks for the page ────────────────────────────────────────
CREATE TABLE content_blocks_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
owner_kind TEXT NOT NULL
CHECK (owner_kind IN ('organization', 'event', 'person', 'team', 'blog_post',
'org_page_mission', 'org_page_leadership')),
owner_id TEXT NOT NULL,
slot TEXT NOT NULL DEFAULT 'body' CHECK (slot IN ('card', 'body')),
sort_order INTEGER NOT NULL DEFAULT 0,
type TEXT NOT NULL
CHECK (type IN ('heading', 'subheading', 'paragraph',
'list', 'links', 'quote', 'image', 'divider',
'video', 'button', 'callout', 'schedule', 'table', 'cards',
'people')),
text TEXT,
media TEXT,
href TEXT,
alt TEXT,
cite TEXT,
team_id TEXT REFERENCES teams (id) ON DELETE SET NULL
) STRICT;
INSERT INTO content_blocks_new
(id, owner_kind, owner_id, slot, sort_order, type, text, media, href, alt, cite, team_id)
SELECT id, owner_kind, owner_id, slot, sort_order, type, text, media, href, alt, cite, team_id
FROM content_blocks;
PRAGMA legacy_alter_table = ON;
DROP TABLE content_blocks;
ALTER TABLE content_blocks_new RENAME TO content_blocks;
PRAGMA legacy_alter_table = OFF;
CREATE INDEX content_blocks_owner_idx
ON content_blocks (owner_kind, owner_id, slot, sort_order);
-- ── Path icons ─────────────────────────────────────────────────
UPDATE front_page_paths SET icon = 'compass' WHERE icon = '🧭';
UPDATE front_page_paths SET icon = 'hands' WHERE icon = '🤲';
UPDATE front_page_paths SET icon = 'sparkle' WHERE icon = '🌱';
UPDATE front_page_paths SET icon = 'people' WHERE icon = '🤝';
UPDATE front_page_paths SET icon = NULL
WHERE icon IS NOT NULL
AND icon NOT IN ('heart', 'hands', 'people', 'calendar', 'tent', 'map', 'home', 'book',
'learn', 'chat', 'music', 'compass', 'sparkle', 'star');
-- ── Triggers last (see CLAUDE.md, Migrations) ──
CREATE TRIGGER organization_page_touch
AFTER UPDATE ON organization_page
FOR EACH ROW WHEN new.updated_at = old.updated_at
BEGIN
UPDATE organization_page SET updated_at = datetime('now') WHERE id = new.id;
END;
CREATE TRIGGER content_blocks_owner_exists
BEFORE INSERT ON content_blocks
BEGIN
SELECT CASE
WHEN new.owner_kind = 'event'
AND NOT EXISTS (SELECT 1 FROM events WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such event')
WHEN new.owner_kind = 'organization'
AND NOT EXISTS (SELECT 1 FROM organizations WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such organization')
WHEN new.owner_kind = 'person'
AND NOT EXISTS (SELECT 1 FROM people WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such person')
WHEN new.owner_kind = 'team'
AND NOT EXISTS (SELECT 1 FROM teams WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such team')
WHEN new.owner_kind = 'blog_post'
AND NOT EXISTS (SELECT 1 FROM blog_posts WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such blog post')
WHEN new.owner_kind IN ('org_page_mission', 'org_page_leadership')
AND NOT EXISTS (SELECT 1 FROM organization_page WHERE id = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such organization page')
END;
END;

View file

@ -0,0 +1,43 @@
/* ═══════════════════════════════════════════════════════════════
ORGANIZATION PAGE ROUTE: read-only, mounted under /api
GET /organization-page the Organization page's own content:
its section titles, the Mission and
Leadership blocks, and Volunteering
(title, blurb, links)
Edited in the admin as Pages → Organization page
(admin-schema/organizationPage.js). The blocks are shaped as on
any record page (loadBlocks), so ContentBlocks draws them.
═══════════════════════════════════════════════════════════════ */
import { Hono } from "hono";
import { json, loadBlocks } from "../shape.js";
const ID = "organization";
const organizationPage = new Hono();
organizationPage.get("/organization-page", (c) => {
const db = c.get("db");
const row = db.prepare(`SELECT * FROM organization_page WHERE id = ?`).get(ID) ?? {};
const links = db
.prepare(`SELECT label, url FROM organization_page_links WHERE page_id = ? ORDER BY sort_order, id`)
.all(ID);
return json(c, {
page: {
mission_title: row.mission_title ?? null,
mission_blocks: loadBlocks(db, "org_page_mission", [ID]).get(ID) ?? [],
leadership_title: row.leadership_title ?? null,
leadership_blurb: row.leadership_blurb ?? null,
leadership_blocks: loadBlocks(db, "org_page_leadership", [ID]).get(ID) ?? [],
volunteer: {
title: row.volunteer_title ?? null,
blurb: row.volunteer_blurb ?? null,
links,
},
},
});
});
export default organizationPage;

View file

@ -21,9 +21,6 @@
the app's own not-found page with a 404 status, so search engines
drop it.
A page that moved answers with a 301 to where it is now (MOVED),
so old links, QR codes and search results keep working.
If the metadata can't be built (no site.json at SITE_CONFIG, say),
the page is still served, as built, and the cause is logged once:
a preview is never worth a page that won't load.
@ -92,23 +89,12 @@ pages.get("/sitemap.xml", (c) => {
});
});
/* Pages that have moved: old path → new, query string kept. */
const MOVED = {
"/leadership": "/organization",
};
pages.get("*", (c, next) => {
const pathname = c.req.path;
// The API's own paths, and an upload that isn't there, stay plain
// 404s rather than becoming a page.
if (/^\/(api|uploads)(\/|$)/.test(pathname)) return next();
const moved = MOVED[pathname.replace(/(.)\/+$/, "$1")];
if (moved) {
const query = new URL(c.req.url).search;
return c.redirect(moved + query, 301);
}
let html;
try {
html = indexHtml();