Compare commits

..

17 commits

Author SHA1 Message Date
970730de20 Merge pull request 'v1.13.1-data: links/redirects, captions, partner picks, Plausible reports, migration baseline' (#28) from data into main 2026-10-06 10:10:56 +01:00
Zaldimmar
e996462231 v1.13.1-data: bump SITE_VERSION; drop comments from index.html
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-06 04:10:31 -05:00
Zaldimmar
5de3cae599 Redirects: still redirect when site.json can't be read
Only the Plausible report is skipped, with a warning, instead of the click failing with a 500.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 02:03:14 -05:00
Zaldimmar
0eea9ba13b Links/redirects: Copy link on a saved redirect
A manifest's idLink gives a saved record's own address, shown on its URL ID card with a Copy link button; redirects use it for the /go/ link.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 00:48:33 -05:00
Zaldimmar
e060153798 Newsletter: Pick a redirect on every link field
Link fields with redirects: true get a list of Data > Links/redirects that fills in the short link's full address; the newsletter turns it on for its blocks' links and their items' links.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 00:39:52 -05:00
Zaldimmar
6289e7203f Links/redirects: /go/ short links with click counts, Plausible and UTM tags (migration 068)
Data > Links/redirects (editors and up) makes short links on our
domain. GET /go/<id> counts the click, reports it to Plausible as a
pageview of /go/<id> (the visitor's browser and address, no key
needed), and redirects (302, no-store) with the link's UTM tags added
to the destination. Unknown ids fall through to the not-found page.
The editor can show a fixed lead-in in the URL ID box (idPrefix).
Vite proxies /go in dev. docs/redirects.md.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-05 00:37:26 -05:00
Zaldimmar
3fafd7f92c Docs: newsletter colors are pickers now
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 23:29:01 -05:00
Zaldimmar
f52a74a383 Newsletter: title color, and color pickers instead of palette dropdowns
Every part color (band, underline, card bar, line, divider, and now the title) is any hex color from a picker; blank is the default, typing none still means no color. Saved drafts keep their colors.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 23:28:52 -05:00
Zaldimmar
24450fba6c Newsletter: Save as a new draft beside Save draft when a draft is open
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 23:18:57 -05:00
Zaldimmar
ce6162d797 History decades: placeholder titles for 1970s to 2010s
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 23:07:31 -05:00
Zaldimmar
77ce5709ef Region pages: drop the raw domestic/international scope from the facts line
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 22:50:44 -05:00
Zaldimmar
fd7e1b6fc1 Organization cards: list partners, ministries or a hand-picked set (migration 067)
The Partners section's preset gets "Cards: list" (partners by default,
ministries, or both) and an optional hand-picked list
(page_section_orgs, partners or ministries only, enforced by trigger)
that replaces it in its own order. /organizations takes kind=ministry
and ids=; the plain list still leaves ministries out. Ministry cards
link to their website only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 22:40:24 -05:00
Zaldimmar
635dd21083 Consolidate migrations 023 to 066 into one baseline plus a minimal seed
066_schema.sql is generated from the live v66 schema (checked identical
to the old migrations' result: every object, every table's columns);
066_seed.sql holds only what pages need: the single rows, event scopes,
home sections, site pages and their sections, the Musicians tag. Sample
content (hero words, paths, stats, the Organization address) is no
longer seeded. Both share version 66, so a database at v66 skips them;
one below v66 is refused and has to be brought up by 33be618 first.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 22:01:55 -05:00
Zaldimmar
33be618331 Captions for uploaded videos (migration 066)
Video blocks get a Captions field and the hero a Video captions field,
each a WebVTT upload drawn as <track kind="captions" default> on a
video file. The media library takes .vtt (sniffed by its WEBVTT
header, kept as is, always in /uploads/captions/) with its own tab.
Newsletter parts leave the field out. nginx needs text/vtt in
mime.types: docs/media-uploads.md, step 5.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 21:55:05 -05:00
Zaldimmar
aaab1a945c Docs: setting up the Plausible reports to Discord
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 21:46:32 -05:00
Zaldimmar
636388730f Plausible analytics reports to Discord (migration 065)
Daily (yesterday) and weekly (Mondays, last 7 days vs the 7 before)
summaries: visitors, pageviews, bounce rate, visit length, top pages
and sources. Each has its own switch in Site settings > Reports; off
until PLAUSIBLE_API_KEY and DISCORD_WEBHOOK_URL are set. Sent at 8:00
REPORT_TZ (default America/Chicago); analytics_reports keeps one a day.
node src/analyticsReport.js daily|weekly sends one by hand.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 21:44:25 -05:00
Zaldimmar
b8012c75e9 Video frame stills for featured cards; newsletter Pick from fix
- Image fields take frameFrom/frameWhen: "Frame at" saves a still from
  the row's YouTube or Facebook link to /uploads/thumbnails/
  (POST /api/admin/video-frame, grabFrame in clips.js). Used on video
  featured cards.
- clock/parseClock moved to src/lib/clock.ts, shared with Video clips.
- Newsletter: new drafts no longer store source 'events' (the Pick from
  select's blank choice), which showed as "events no longer exists";
  older drafts load it as blank.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-04 21:35:08 -05:00
96 changed files with 1987 additions and 3431 deletions

View file

@ -32,7 +32,7 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu
- Debugging: check `journalctl -u ngu-api -n 40 --no-pager` first. Make sure rsync ran from the repo (not the deployed copy) before restarting the service. - Debugging: check `journalctl -u ngu-api -n 40 --no-pager` first. Make sure rsync ran from the repo (not the deployed copy) before restarting the service.
- Never run commands against the production server or database unless explicitly asked. - Never run commands against the production server or database unless explicitly asked.
- Uploaded media: `UPLOADS_DIR=/var/lib/ngu/uploads`, served by nginx at `/uploads/`. Setup and the nginx block are in `docs/media-uploads.md`. - Uploaded media: `UPLOADS_DIR=/var/lib/ngu/uploads`, served by nginx at `/uploads/`. Setup and the nginx block are in `docs/media-uploads.md`.
- Analytics: self-hosted Plausible, proxied by nginx at `/pa/`. The API adds its script to every page (`analyticsTag` in `server/src/pageMeta.js`), counting under the hostname of `site.json`'s `url`, so each deployment reports as itself. Nothing in `index.html` or the app. - Analytics: self-hosted Plausible, proxied by nginx at `/pa/`. The API adds its script to every page (`analyticsTag` in `server/src/pageMeta.js`), counting under the hostname of `site.json`'s `url`, so each deployment reports as itself. Nothing in `index.html` or the app. Daily and weekly reports go to Discord when Panel → Site settings → Reports turns them on and `PLAUSIBLE_API_KEY` and `DISCORD_WEBHOOK_URL` are set (`server/src/analyticsReport.js`): `docs/analytics-reports.md`. Short links `/go/<id>` (Data → Links/redirects, `server/src/routes/redirects.js`) count clicks, report each to Plausible as a pageview and add the link's UTM tags: `docs/redirects.md`.
- Page HTML goes through the API, which fills in each page's title, description, preview image and structured data (`server/src/pageMeta.js`), and serves `/sitemap.xml`. It reads `SITE_CONFIG` (site.json) and `SITE_INDEX` (the built index.html), with Panel → Site settings (the `site_settings` table) laid over site.json, and serves `/robots.txt` from the same merge. nginx setup: `docs/seo.md`. - Page HTML goes through the API, which fills in each page's title, description, preview image and structured data (`server/src/pageMeta.js`), and serves `/sitemap.xml`. It reads `SITE_CONFIG` (site.json) and `SITE_INDEX` (the built index.html), with Panel → Site settings (the `site_settings` table) laid over site.json, and serves `/robots.txt` from the same merge. nginx setup: `docs/seo.md`.
- Video clips (Tools, admins and up): yt-dlp downloads our YouTube/Facebook videos into `CLIPS_DIR`, ffmpeg cuts them; one job at a time, files swept after a day (`server/src/clips.js`). Needs yt-dlp and ffmpeg on the VPS: `docs/video-clips.md`. - Video clips (Tools, admins and up): yt-dlp downloads our YouTube/Facebook videos into `CLIPS_DIR`, ffmpeg cuts them; one job at a time, files swept after a day (`server/src/clips.js`). Needs yt-dlp and ffmpeg on the VPS: `docs/video-clips.md`.
- Newsletter countdown pictures: `/api/countdown/:id.png` (`server/src/routes/countdown.js`), drawn with sharp when an email is opened; it uses the VPS's fonts, so install Poppins there (eg. into `/usr/local/share/fonts`, then `fc-cache`) or it falls back to a plain sans. The social bar's icons are static files in `public/email/`. - Newsletter countdown pictures: `/api/countdown/:id.png` (`server/src/routes/countdown.js`), drawn with sharp when an email is opened; it uses the VPS's fonts, so install Poppins there (eg. into `/usr/local/share/fonts`, then `fc-cache`) or it falls back to a plain sans. The social bar's icons are static files in `public/email/`.
@ -64,7 +64,7 @@ In dev, Vite proxies `/api` to the target set in `vite.config.ts`, so the API mu
- `navConfig.ts` is the single source of truth for navigation, routes, and actions (header, footer, pages). - `navConfig.ts` is the single source of truth for navigation, routes, and actions (header, footer, pages).
- `api.ts` is the shared caching client used by frontend data hooks. - `api.ts` is the shared caching client used by frontend data hooks.
- `docs/updating-data-in-code.md`: where content that isn't in the database lives (admin dropdown labels, fixed value lists, nav, banner, decades, map grid) and how to change it. Keep it current when adding a dropdown or code-owned content. - `docs/updating-data-in-code.md`: where content that isn't in the database lives (admin dropdown labels, fixed value lists, nav, banner, decades, map grid) and how to change it. Keep it current when adding a dropdown or code-owned content.
- Images: every record image (logos, photos, backgrounds, block images) is an upload, in a folder by use: `/uploads/logos/`, `/uploads/images/`, `/uploads/thumbnails/` (saved previews); a logo or icon image field sets `folder: "logos"` (`docs/media-uploads.md`, Folders). A bare filename resolves to `/uploads/<file>` (`src/lib/media.ts`, and `server/src/pageMeta.js` for previews). Only the site's own chosen assets, the NGU logos in the nav, footer and admin, are bundled from `src/assets/logos/`. Logo images hide themselves on load error (`onError`). - Images: every record image (logos, photos, backgrounds, block images) is an upload, in a folder by use: `/uploads/logos/`, `/uploads/images/`, `/uploads/thumbnails/` (saved previews), `/uploads/captions/` (videos' .vtt files); a logo or icon image field sets `folder: "logos"` (`docs/media-uploads.md`, Folders). A bare filename resolves to `/uploads/<file>` (`src/lib/media.ts`, and `server/src/pageMeta.js` for previews). Only the site's own chosen assets, the NGU logos in the nav, footer and admin, are bundled from `src/assets/logos/`. Logo images hide themselves on load error (`onError`).
## Rules and gotchas ## Rules and gotchas
- **Role checks must use ladder comparisons, never equality.** Roles rank viewer → editor → admin → superadmin. Use the minimum-rank helpers from `src/lib/roles.ts` (`canWrite`, `canDelete`, `isSuper`, `atLeast`). Where a local variable shadows the name, import with an alias, e.g. `canWrite as roleCanWrite`. `role === "admin"` silently excludes higher roles and has caused repeated bugs. - **Role checks must use ladder comparisons, never equality.** Roles rank viewer → editor → admin → superadmin. Use the minimum-rank helpers from `src/lib/roles.ts` (`canWrite`, `canDelete`, `isSuper`, `atLeast`). Where a local variable shadows the name, import with an alias, e.g. `canWrite as roleCanWrite`. `role === "admin"` silently excludes higher roles and has caused repeated bugs.
@ -89,8 +89,8 @@ Descriptor-driven: `server/src/admin-crud.js` and `server/src/admin-schema/` (se
- `admin-cli.js` imports `ROLES` and `destroyAllSessionsFor` from `auth.js`. Keep it that way to prevent drift. - `admin-cli.js` imports `ROLES` and `destroyAllSessionsFor` from `auth.js`. Keep it that way to prevent drift.
## Migrations ## Migrations
- `server/src/migrations/023_schema.sql` is the baseline: the whole schema, consolidated from the old 001–023. It only runs on an empty database; the runner refuses a database between v1 and v22. It's the place to read the schema, not to change it: a database that already exists never re-runs it. - `server/src/migrations/066_schema.sql` is the baseline: the whole schema, consolidated on 2026-10-04 from the old 023–066 (generated from the live schema, so the comments are the ones inside each table). `066_seed.sql` runs right after it with the least a new database needs (single rows, event scopes, the site pages' sections, the Musicians tag); content is typed in through the admin. Both only run on an empty database; the runner refuses a database between v1 and v65 (bring it to v66 with a release from before the consolidation first). It's the place to read the schema, not to change it: a database that already exists never re-runs it.
- Changes go in new sequential files after it: `024_`, `025_`, ... - Changes go in new sequential files after it: `067_`, `068_`, ...
- The runner may drop statements after a `BEGIN...END` trigger body. Keep triggers last in a file, and put each `CREATE VIEW` before any trigger or in its own file. - The runner may drop statements after a `BEGIN...END` trigger body. Keep triggers last in a file, and put each `CREATE VIEW` before any trigger or in its own file.
- The runner turns foreign keys off around every migration (it can't be done inside the file's transaction) and runs `PRAGMA foreign_key_check` before committing, so a table rebuild needs no `PRAGMA foreign_keys` of its own. When views or triggers name the table being rebuilt, wrap the drop-and-rename in `PRAGMA legacy_alter_table = ON` ... `OFF`, then recreate the rebuilt table's own indexes and triggers. - The runner turns foreign keys off around every migration (it can't be done inside the file's transaction) and runs `PRAGMA foreign_key_check` before committing, so a table rebuild needs no `PRAGMA foreign_keys` of its own. When views or triggers name the table being rebuilt, wrap the drop-and-rename in `PRAGMA legacy_alter_table = ON` ... `OFF`, then recreate the rebuilt table's own indexes and triggers.

162
docs/analytics-reports.md Normal file
View file

@ -0,0 +1,162 @@
# Analytics reports to Discord
The API can post the site's Plausible numbers to a Discord channel
(`server/src/analyticsReport.js`, migration 065):
- **Daily**: yesterday's visitors, pageviews, bounce rate, visit length,
and the top 3 pages and sources.
- **Weekly**, on Mondays: the last 7 days (Monday to Sunday), each
total with its change from the week before, and the top 5 pages and
sources.
Each one has its own switch in Panel → Site settings → Reports, and both
are off until it's turned on. They go out at 8:00 in `REPORT_TZ`. If the
server is down then, they go out when it comes back up later that day.
A restart never posts the same report twice. Nothing else on the site
depends on this.
| Setting on the `ngu-api` service | What it is |
| --- | --- |
| `PLAUSIBLE_API_KEY` | A Plausible Stats API key (step 1) |
| `DISCORD_WEBHOOK_URL` | The channel's webhook address (step 2) |
| `PLAUSIBLE_URL` | Where the API can reach Plausible. Default `http://127.0.0.1:8000` |
| `REPORT_TZ` | The time zone for "yesterday" and 8:00. Default `America/Chicago` |
Without the first two, no reports are sent, whatever the switches say.
## 1. The Plausible API key
1. Sign in to Plausible (the self-hosted one behind `/pa/`) as an owner
of the site.
2. Account settings → API keys → New API key. Pick **Stats API** if it
asks for a type, and name it eg. `ngu-api reports`.
3. Copy the key now. Plausible shows it only once.
The site has to exist in Plausible under the same domain the pages count
under: the hostname of `site.json`'s `url`, eg. `nextgenerationofunity.org`
(not `www.` and not `https://`). It already does if the dashboard shows
visits.
The reports use the Stats API v2 (`/api/v2/query`), which needs
Plausible Community Edition 2.1 or later. Check Settings or the page
footer for the version, and upgrade an older one first.
### Where Plausible listens
`PLAUSIBLE_URL` is the address the API calls directly, not the public
`/pa/` path. nginx's proxy for `/pa/` already points at it:
```sh
grep proxy_pass /etc/nginx/snippets/plausible-proxy.conf
```
If that shows `http://127.0.0.1:8000`, leave `PLAUSIBLE_URL` unset.
Otherwise set it to that address, eg. `http://127.0.0.1:8001`, or
`https://plausible.io` for Plausible's own hosting.
## 2. The Discord webhook
1. In Discord, open the channel's settings (the gear by its name) →
Integrations → Webhooks → New Webhook.
2. Name it eg. `NGU analytics`, give it an avatar if you like, and check
that it posts to the right channel.
3. Copy Webhook URL. It looks like
`https://discord.com/api/webhooks/123456789/AbCdEf...`.
You need Manage Webhooks on the channel. Anyone who has the address can
post to the channel, so treat it as a password.
## 3. The service
Both values are secrets, so put them in a file only root can read
rather than in the unit itself (a `systemctl edit` override is readable
by every user on the box):
```sh
sudo mkdir -p /etc/ngu
sudo tee /etc/ngu/analytics-reports.env >/dev/null <<'EOF'
PLAUSIBLE_API_KEY=<the key from step 1>
DISCORD_WEBHOOK_URL=<the webhook address from step 2>
EOF
sudo chmod 600 /etc/ngu/analytics-reports.env
```
Add `PLAUSIBLE_URL=` or `REPORT_TZ=` lines to the same file if you need
them. Then point the service at it:
```sh
sudo systemctl edit ngu-api
```
```ini
[Service]
EnvironmentFile=/etc/ngu/analytics-reports.env
```
systemd reads the file as root before it starts the service, so the
service's own user doesn't need to be able to read it.
Back up the database first (migration 065 adds the switches and runs at
the next start), then:
```sh
sudo systemctl restart ngu-api
```
No nginx change is needed: the API calls Plausible and Discord itself.
## 4. Try it
Send one straight away, whatever the switches say, while the service is
running:
```sh
cd /srv/ngu-api
sudo bash -c 'set -a; . /etc/ngu/analytics-reports.env; set +a;
SITE_CONFIG=/srv/ngu-api/site.json DB_PATH=/var/lib/ngu/ngu.db \
node src/analyticsReport.js daily'
```
`Sent the daily report.` means it's in the channel. Use `weekly` for the
weekly one. Sending one by hand doesn't stop that day's scheduled
report.
## 5. Turn them on
Panel → Site settings → Reports: set **Daily analytics report** and/or
**Weekly analytics report** to On, and save. Set one back to Off (or
blank) to stop it. The change counts from the next check, within 15
minutes.
The switches are per database, so the dev server only posts if its own
database has them on and its own service has the settings. Leave the
settings off dev, or it reports as `dev.nextgenerationofunity.org`.
## Checking it
Every report is logged:
```sh
journalctl -u ngu-api --since today --no-pager | grep analytics
```
- `analytics daily report sent for 2026-10-05`: it went out.
- `Plausible answered 401`: the API key is wrong or was deleted. Make a
new one (step 1).
- `Plausible answered 400` or `404` naming the site: Plausible has no
site under that domain. Compare `site.json`'s `url` with the domain in
Plausible's site list.
- `Plausible answered 404` with no site named: Plausible is older than
2.1 and has no v2 API.
- `fetch failed` or `ECONNREFUSED`: Plausible isn't at `PLAUSIBLE_URL`
(see Where Plausible listens).
- `Discord answered 401` or `404`: the webhook was deleted or the
address is wrong. Make a new one (step 2).
- Nothing at all: check that both settings are in the service's
environment (`sudo systemctl show ngu-api -p EnvironmentFiles`), that
the switch is On, that it's past 8:00 in `REPORT_TZ`, and for the
weekly report, that it's Monday.
A failed report isn't retried that day, so a broken setup logs one line
a day, not one every 15 minutes. Fix the cause, then send it by hand
(step 4) if you still want it.

View file

@ -15,8 +15,10 @@ in the `media` table (`server/src/migrations/028_media.sql`).
- **Keep original** stores the file exactly as uploaded (up to 10 MB), - **Keep original** stores the file exactly as uploaded (up to 10 MB),
metadata and all. metadata and all.
- SVGs are always kept as they are. - SVGs are always kept as they are.
- Accepted types: JPEG, PNG, GIF, WebP, SVG. The type is read from the - Accepted types: JPEG, PNG, GIF, WebP, SVG, and WebVTT captions
file's contents, not its name. (`.vtt`, kept as they are, always in `captions/`). The type is read
from the file's contents, not its name: a captions file has to start
with `WEBVTT`.
- Editors and up can upload. Admins and up can delete. The Media page - Editors and up can upload. Admins and up can delete. The Media page
shows which tables still use a file before deleting it, because shows which tables still use a file before deleting it, because
nothing stops a file a record uses from being deleted. nothing stops a file a record uses from being deleted.
@ -33,6 +35,7 @@ Images are kept in folders by what they're for (`FOLDERS` in
| `logos/` | Uploads from logo and icon fields (organization, team, award and event logos, the favicon and home-screen icon): the fields with `folder: "logos"` in `src/lib/adminSchema/` | | `logos/` | Uploads from logo and icon fields (organization, team, award and event logos, the favicon and home-screen icon): the fields with `folder: "logos"` in `src/lib/adminSchema/` |
| `images/` | Every other upload: photos, backgrounds, covers, block images | | `images/` | Every other upload: photos, backgrounds, covers, block images |
| `thumbnails/` | Pictures the site saves by itself: link previews (Fetch preview) and Drive files' first pages | | `thumbnails/` | Pictures the site saves by itself: link previews (Fetch preview) and Drive files' first pages |
| `captions/` | WebVTT files for uploaded videos: the Captions field of video blocks and the hero's Video captions (migration 066). YouTube, Vimeo and Facebook videos show their own |
Each image's `-640.webp` small copy sits beside it. Video and audio Each image's `-640.webp` small copy sits beside it. Video and audio
clips (Tools → Video clips) stay in the root. The Media page and every clips (Tools → Video clips) stay in the root. The Media page and every
@ -100,3 +103,15 @@ which git ignores). The API serves `/uploads/` itself, and Vite proxies
4. `sharp` is a server dependency now: run `pnpm install` in 4. `sharp` is a server dependency now: run `pnpm install` in
`/srv/ngu-api` after the deploy. It ships prebuilt Linux binaries, `/srv/ngu-api` after the deploy. It ships prebuilt Linux binaries,
so no build tools are needed. so no build tools are needed.
5. Captions need nginx to send `.vtt` files as `text/vtt` (Firefox
won't show them otherwise, and `nosniff` stops guessing). Check:
```sh
grep vtt /etc/nginx/mime.types
```
If nothing comes back, add `text/vtt vtt;` inside the `types { }`
block of `/etc/nginx/mime.types`, then
`sudo nginx -t && sudo systemctl reload nginx`. Not in the site's
own file: a `types` block there replaces the whole list.

53
docs/redirects.md Normal file
View file

@ -0,0 +1,53 @@
# Links/redirects
Short links on our own domain, made in Admin → Data → Links/redirects
(editors and up), eg. `nextgenerationofunity.org/go/retreat-signup`. Use
them in the newsletter, or anywhere else, so each click is counted.
Each link has:
- **URL ID**: the part after `/go/`. Lowercase letters, numbers and
hyphens, and it can't be changed once made, since it's already been
sent out.
- **Goes to**: a web address (`https://...`) or a page on this site
(`/retreats`). This can be changed at any time, and every copy of the
link already sent follows it.
- **Note**: what it's for. Only we see it.
- **UTM tags** (source, medium, campaign): added to the destination's
address, eg. `?utm_source=newsletter&utm_medium=email&utm_campaign=october-2026`.
A tag the destination already has is left as it is.
## What a click does
`GET /go/<URL ID>` (`server/src/routes/redirects.js`, migration 068):
1. Adds one to the link's **Clicks** and sets **Last click** (both on
the list page). A save in the editor never changes them.
2. Tells Plausible, as a pageview of `/go/<URL ID>` with the visitor's
browser and address, so it appears in Top Pages (and in the Discord
reports) like any page. A redirect never loads the page script, so
the server reports it. It uses `PLAUSIBLE_URL`, the same as the
reports (`docs/analytics-reports.md`), and needs no API key. If
Plausible can't be reached, the redirect still works and the
problem is logged once.
3. Sends the visitor on with a 302. It's never cached, so every click
reaches the server.
An unknown URL ID shows the site's not-found page.
## Reading the numbers
- **Clicks** counts every request, including link checkers. Some email
security scanners open every link in a message before the reader
does, so a newsletter link can show a few clicks straight away.
Plausible leaves out known bots, so its count is usually lower and
closer to real readers.
- In Plausible, filter by page `/go/` to see every short link, or by a
UTM source or campaign to see what those visitors did once they
landed on our site.
## Setup
Nothing beyond the migration: nginx already sends `/go/...` to the API
through its catch-all page block (`nginx-dev`, `ngu-prod`). In
development, Vite proxies `/go` to the API (`vite.config.ts`).

View file

@ -56,7 +56,7 @@ each entity:
And the database itself holds the final word: most fixed lists are a And the database itself holds the final word: most fixed lists are a
`CHECK (... IN (...))` constraint on the column (read them in `CHECK (... IN (...))` constraint on the column (read them in
`server/src/migrations/023_schema.sql` and any later migration). `server/src/migrations/066_schema.sql` and any later migration).
### Two kinds of dropdown ### Two kinds of dropdown
@ -167,7 +167,7 @@ also in `server/src/admin-schema/` and a CHECK):
| Entity → field | Stored values | Labeled? | Also used on the public site by | | Entity → field | Stored values | Labeled? | Also used on the public site by |
| --- | --- | --- | --- | | --- | --- | --- | --- |
| Organizations → Kind (+ list filter) | national, region, group, partner, ministry | no, shows values | `ORG_BASE` in `src/lib/hrefs.ts` (the route each kind uses). A ministry has no page or list on the public site (the public routes, `pageMeta.js` and the sitemap leave it out, `ORG_KINDS` in `server/src/routes/content.js` doesn't take it); only its groups name it. `KINDS` in `src/components/admin/NewsletterRecipients.tsx` (the export's filter) lists every kind too. | | Organizations → Kind (+ list filter) | national, region, group, partner, ministry | no, shows values | `ORG_BASE` in `src/lib/hrefs.ts` (the route each kind uses). A ministry has no page on the public site (the public routes, `pageMeta.js` and the sitemap leave it out); its groups name it, and an organization cards section lists it when asked to (below). `/organizations` returns ministries only when asked by kind or id. `KINDS` in `src/components/admin/NewsletterRecipients.tsx` (the export's filter) lists every kind too. |
| Organizations → Region → Scope | domestic, international, virtual | no | the Community page groups regions by it | | Organizations → Region → Scope | domestic, international, virtual | no | the Community page groups regions by it |
| Organizations → Region areas → Edge | top, bottom | no | the group map (`OrgList-Map.tsx`) | | Organizations → Region areas → Edge | top, bottom | no | the group map (`OrgList-Map.tsx`) |
| Events → Type (+ list filter) | retreat, class, workshop, meeting, other | no | `EVENT_TYPES` in `src/lib/eventTypes.ts` (public labels and plurals) | | Events → Type (+ list filter) | retreat, class, workshop, meeting, other | no | `EVENT_TYPES` in `src/lib/eventTypes.ts` (public labels and plurals) |
@ -190,6 +190,7 @@ also in `server/src/admin-schema/` and a CHECK):
| Front page → Featured cards → Card type (Community → Community blog: pinned community posts offers link and video only) | record, link, video | **yes**, `FEATURED_KINDS` | `FeaturedCards.tsx` (how each kind draws), `loadFeaturedCards` in `server/src/shape.js` | | Front page → Featured cards → Card type (Community → Community blog: pinned community posts offers link and video only) | record, link, video | **yes**, `FEATURED_KINDS` | `FeaturedCards.tsx` (how each kind draws), `loadFeaturedCards` in `server/src/shape.js` |
| Front page → Featured cards → Record type | event, organization, person, team, award | no | `FEATURED_REFS` in `server/src/shape.js` (what each fills the card with); the triggers in `030_featured_cards.sql` | | Front page → Featured cards → Record type | event, organization, person, team, award | no | `FEATURED_REFS` in `server/src/shape.js` (what each fills the card with); the triggers in `030_featured_cards.sql` |
| Pages → Sections → Preset | community_blog, group_map, region_list, partner_list, events, timeline, people_directory | **yes**, `PRESETS` in `src/lib/adminSchema/sitePages.ts` (which pages offer which, the list passed to each `sitePage`) | `PRESETS` in `src/pages/SitePage.tsx`. A People directory shows its tag's first `DIRECTORY_PREVIEW` people (`src/pages/sections/PeopleDirectory.tsx`), linking to `/directory/<tag>`. | | Pages → Sections → Preset | community_blog, group_map, region_list, partner_list, events, timeline, people_directory | **yes**, `PRESETS` in `src/lib/adminSchema/sitePages.ts` (which pages offer which, the list passed to each `sitePage`) | `PRESETS` in `src/pages/SitePage.tsx`. A People directory shows its tag's first `DIRECTORY_PREVIEW` people (`src/pages/sections/PeopleDirectory.tsx`), linking to `/directory/<tag>`. |
| Pages → Sections → Cards: list (organization cards preset, 067) | partner, ministry, partner,ministry | **yes**, inline in `src/lib/adminSchema/sitePages.ts` | `partner_list` in `PRESETS` in `src/pages/SitePage.tsx` passes it as the kind to `OrgListCards`; a section's hand-picked Cards: organizations (`page_section_orgs`) replace it |
| Every list → Published / Listed / Featured filter | 1, 0 | **yes** | n/a | | Every list → Published / Listed / Featured filter | 1, 0 | **yes** | n/a |
"No, shows values" means the dropdown currently shows the raw value, "No, shows values" means the dropdown currently shows the raw value,
@ -284,14 +285,14 @@ The numbers band's "Number Source" dropdown works the same way:
| The icons a Front page "Find your way in" path can pick | `src/data/pathIcons.ts` (keys and labels) **and** `ICONS` in `src/pages/sections/home/Pathfinder.tsx` (the Phosphor icon for each key) | Add a line to both. A path saved with an emoji from before the list shows it as it is. | | The icons a Front page "Find your way in" path can pick | `src/data/pathIcons.ts` (keys and labels) **and** `ICONS` in `src/pages/sections/home/Pathfinder.tsx` (the Phosphor icon for each key) | Add a line to both. A path saved with an emoji from before the list shows it as it is. |
| A page section's accent color | `BRAND` and `ACCENTS` in `src/lib/color.ts` | Pages pick from these (`accent: ACCENTS.green`); add a color there, not a hex in a page. Each is readable as text on white and the tints. | | A page section's accent color | `BRAND` and `ACCENTS` in `src/lib/color.ts` | Pages pick from these (`accent: ACCENTS.green`); add a color there, not a hex in a page. Each is readable as text on white and the tints. |
| The palette (the 16-color grid the theme is drawn from) | `PALETTE` in `src/lib/color.ts` | Four families, a column each. `PALETTE_LIGHT` / `PALETTE_DARK` are the fills things colored by data use (a person's initials tile, `paletteFill`); the page background's layers (how many circles, their sizes and parallax speeds) are `LAYERS` in `src/components/PageBackdrop.tsx` and its shades are in `PageBackdrop.css`; the admin home's two alternating group colors are `BLOCK_COLORS` in `src/pages/admin/AdminHome.tsx`. | | The palette (the 16-color grid the theme is drawn from) | `PALETTE` in `src/lib/color.ts` | Four families, a column each. `PALETTE_LIGHT` / `PALETTE_DARK` are the fills things colored by data use (a person's initials tile, `paletteFill`); the page background's layers (how many circles, their sizes and parallax speeds) are `LAYERS` in `src/components/PageBackdrop.tsx` and its shades are in `PageBackdrop.css`; the admin home's two alternating group colors are `BLOCK_COLORS` in `src/pages/admin/AdminHome.tsx`. |
| The accessibility panel's choices (bottom right of every public page) | `SETTINGS` in `src/components/AccessibilityPanel.tsx`; the color blind modes are `VISIONS` and `SWAPS` in `src/lib/color.ts` | Each choice is an attribute on `<html>` styled in `src/index.css`, and `index.html` sets it again before the first paint, so a new one goes in all three. A color blind mode replaces all three color families, teal, green and amber (`SWAPS`, picked by simulating each type: see the comment there), in code, in data colors as they load (`src/lib/api.ts`, never under /admin), in CSS (the `--pal-*` variables in `src/index.css`, which hold the same values as `SWAPS`: change both) and in the theme tokens drawn from them. A palette hex in a component or CSS file should be `var(--pal-<family>-<shade>)` (eg. `var(--pal-amber-2)`), or a color blind mode won't reach it. Reading mode is `src/components/ReaderView.tsx`, which reads the hidden page and writes out its headings, paragraphs, links and described pictures. A part it can't read well (a carousel, tabs, details behind a click, a map) draws its own text version when `useReadingMode()` (`src/lib/readingMode.ts`) is on: the hero, pathfinder, stats, history rail, event lists, calendar (the next six weeks), featured cards, org lists and groups map, history timeline, schedule, people tiles and video player; the countdown draws nothing. A new component with any of those should do the same. Something saved or sent (the newsletter's colors) uses `STORED_PALETTE`, which is never swapped. | | The accessibility panel's choices (bottom right of every public page) | `SETTINGS` in `src/components/AccessibilityPanel.tsx`; the color blind modes are `VISIONS` and `SWAPS` in `src/lib/color.ts` | Each choice is an attribute on `<html>` styled in `src/index.css`, and `index.html` sets it again before the first paint, so a new one goes in all three. A color blind mode replaces all three color families, teal, green and amber (`SWAPS`, picked by simulating each type: see the comment there), in code, in data colors as they load (`src/lib/api.ts`, never under /admin), in CSS (the `--pal-*` variables in `src/index.css`, which hold the same values as `SWAPS`: change both) and in the theme tokens drawn from them. A palette hex in a component or CSS file should be `var(--pal-<family>-<shade>)` (eg. `var(--pal-amber-2)`), or a color blind mode won't reach it. Reading mode is `src/components/ReaderView.tsx`, which reads the hidden page and writes out its headings, paragraphs, links and described pictures. A part it can't read well (a carousel, tabs, details behind a click, a map) draws its own text version when `useReadingMode()` (`src/lib/readingMode.ts`) is on: the hero, pathfinder, stats, history rail, event lists, calendar (the next six weeks), featured cards, org lists and groups map, history timeline, schedule, people tiles and video player; the countdown draws nothing. A new component with any of those should do the same. Something saved or sent (the newsletter's colors) is a stored hex, which is never swapped. |
| Privacy Policy and Terms wording | `src/pages/Privacy.tsx`, `src/pages/Terms.tsx` | The `PARTS` list, and `LAST_UPDATED` whenever the wording changes. The Privacy page must stay true of the code: what the feedback form stores, what the browser keeps, which embeds wait for a click. | | Privacy Policy and Terms wording | `src/pages/Privacy.tsx`, `src/pages/Terms.tsx` | The `PARTS` list, and `LAST_UPDATED` whenever the wording changes. The Privacy page must stay true of the code: what the feedback form stores, what the browser keeps, which embeds wait for a click. |
| Event type labels and plurals (public site) | `src/lib/eventTypes.ts` | Also the order of the type filter chips. | | Event type labels and plurals (public site) | `src/lib/eventTypes.ts` | Also the order of the type filter chips. |
| Event and person role labels (public site) | `ROLE_LABEL` in `src/pages/EventDetail.tsx` and `src/pages/PersonDetail.tsx` | | | Event and person role labels (public site) | `ROLE_LABEL` in `src/pages/EventDetail.tsx` and `src/pages/PersonDetail.tsx` | |
| Organization kind labels ("Region", "Group") | the Kind options in `src/lib/adminSchema/organizations.ts` (admin) | | | Organization kind labels ("Region", "Group") | the Kind options in `src/lib/adminSchema/organizations.ts` (admin) | |
| Admin account roles | `src/lib/roles.ts` (labels, notes) and `ROLES` in `server/src/auth.js` | Adding a role is also a CHECK change on `admin_users.role`. | | Admin account roles | `src/lib/roles.ts` (labels, notes) and `ROLES` in `server/src/auth.js` | Adding a role is also a CHECK change on `admin_users.role`. |
| Admin navigation | `src/pages/admin/adminNav.ts` | | | Admin navigation | `src/pages/admin/adminNav.ts` | |
| Newsletter parts and their defaults (Tools → Newsletter) | `PARTS_SPEC`, `PART_TYPES` and `STARTER` in `src/pages/admin/AdminNewsletter.tsx`; `PICK_DEFAULTS`, `DEFAULT_TITLE` and `COLOR` in `src/lib/newsletter.ts` | A draft is one JSON list of parts (`newsletters.layout`, 060), so adding a part or a setting needs no migration: a field in `PARTS_SPEC` and its drawing in `newsletter.ts`. The color choices are `PALETTE`; `COLOR` holds the defaults as hex, since an inbox has no theme tokens. `STARTER` is what a new draft starts with. The social bar's icons are PNGs in `public/email/` (Gmail and Outlook don't show SVG), made from `PlatformIcon.tsx` by `node scripts/email-icons.mjs`: run it again after adding a platform. A social bar with no links shows the footer's, `SOCIAL_LINKS` in `src/data/socialLinks.ts`. The countdown picture is `server/src/routes/countdown.js`, counting to local midnight in its `TIME_ZONE` (America/Chicago). | | Newsletter parts and their defaults (Tools → Newsletter) | `PARTS_SPEC`, `PART_TYPES` and `STARTER` in `src/pages/admin/AdminNewsletter.tsx`; `PICK_DEFAULTS`, `DEFAULT_TITLE` and `EMAIL_COLOR` in `src/lib/newsletter.ts` | A draft is one JSON list of parts (`newsletters.layout`, 060), so adding a part or a setting needs no migration: a field in `PARTS_SPEC` and its drawing in `newsletter.ts`. Part colors (the title, bands, lines, card bars) are color pickers taking any hex, or the word none; `EMAIL_COLOR` holds the defaults as hex, since an inbox has no theme tokens. `STARTER` is what a new draft starts with. The social bar's icons are PNGs in `public/email/` (Gmail and Outlook don't show SVG), made from `PlatformIcon.tsx` by `node scripts/email-icons.mjs`: run it again after adding a platform. A social bar with no links shows the footer's, `SOCIAL_LINKS` in `src/data/socialLinks.ts`. The countdown picture is `server/src/routes/countdown.js`, counting to local midnight in its `TIME_ZONE` (America/Chicago). |
| The live site's address (used by QR codes) | `SITE_ORIGIN` in `src/lib/site.ts` | | | The live site's address (used by QR codes) | `SITE_ORIGIN` in `src/lib/site.ts` | |
| Version shown on the admin home page | `src/lib/version.ts` | | | Version shown on the admin home page | `src/lib/version.ts` | |
| Image directories (where logos and photos are looked up) | `src/lib/media.ts` | | | Image directories (where logos and photos are looked up) | `src/lib/media.ts` | |

View file

@ -14,6 +14,12 @@ it: **Save to library** and **Save to Drive** on the download itself.
It stays on the server to cut clips from either way (until the day's It stays on the server to cut clips from either way (until the day's
sweep). sweep).
The same tools take stills: a video featured card's Image field has
**Frame at** (editors and up), which saves the frame at a typed time to
`/uploads/thumbnails/` (`grabFrame` in `server/src/clips.js`). It
downloads only that frame, outside the queue. A link's own `t=` (eg.
`?t=83`) fills in the time.
Clips queue and run one at a time. A finished clip is deleted from the Clips queue and run one at a time. A finished clip is deleted from the
server once it's downloaded, unless **Save to library** is pressed first, server once it's downloaded, unless **Save to library** is pressed first,
which puts it in the media library as an upload (usable as a featured which puts it in the media library as an upload (usable as a featured

View file

@ -5,20 +5,13 @@
<meta charset="UTF-8" /> <meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title><!-- site:title --></title> <title><!-- site:title --></title>
<!-- The browser chrome around the page, for each mode. -->
<meta name="theme-color" content="#073d4a" media="(prefers-color-scheme: light)" /> <meta name="theme-color" content="#073d4a" media="(prefers-color-scheme: light)" />
<meta name="theme-color" content="#0c1d21" media="(prefers-color-scheme: dark)" /> <meta name="theme-color" content="#0c1d21" media="(prefers-color-scheme: dark)" />
<!-- Theme before first paint, so a dark visitor never sees a white
flash: this browser's choice (ThemeToggle), else the system;
and the accessibility choices, for the same reason. -->
<script> <script>
try { try {
var t = localStorage.getItem("site-theme"); var t = localStorage.getItem("site-theme");
document.documentElement.dataset.theme = document.documentElement.dataset.theme =
t === "dark" || t === "light" ? t : matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light"; t === "dark" || t === "light" ? t : matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light";
// The accessibility panel's choices (AccessibilityPanel.tsx).
// Reading and color blind modes are for the public pages: the
// admin edits colors and layout, which they would hide.
if (localStorage.getItem("site-font") === "dyslexic") document.documentElement.dataset.font = "dyslexic"; if (localStorage.getItem("site-font") === "dyslexic") document.documentElement.dataset.font = "dyslexic";
if (!location.pathname.startsWith("/admin")) { if (!location.pathname.startsWith("/admin")) {
if (localStorage.getItem("site-reading") === "on") document.documentElement.dataset.reading = "on"; if (localStorage.getItem("site-reading") === "on") document.documentElement.dataset.reading = "on";

View file

@ -56,6 +56,7 @@ import { siteSettings } from "./admin-schema/siteSettings.js";
import { newsletters } from "./admin-schema/newsletters.js"; import { newsletters } from "./admin-schema/newsletters.js";
import { personTagTypes } from "./admin-schema/personTags.js"; import { personTagTypes } from "./admin-schema/personTags.js";
import { contactTypes } from "./admin-schema/contactTypes.js"; import { contactTypes } from "./admin-schema/contactTypes.js";
import { redirects } from "./admin-schema/redirects.js";
import { import {
communityPage, communityPage,
retreatsPage, retreatsPage,
@ -70,6 +71,7 @@ export const ENTITIES = {
people, people,
person_tag_types: personTagTypes, person_tag_types: personTagTypes,
contact_types: contactTypes, contact_types: contactTypes,
redirects,
teams, teams,
awards, awards,
timeline, timeline,
@ -96,11 +98,16 @@ export const OPTION_QUERIES = {
"SELECT id, name AS label FROM organizations WHERE kind = 'region' ORDER BY name", "SELECT id, name AS label FROM organizations WHERE kind = 'region' ORDER BY name",
ministries: ministries:
"SELECT id, name AS label FROM organizations WHERE kind = 'ministry' ORDER BY name", "SELECT id, name AS label FROM organizations WHERE kind = 'ministry' ORDER BY name",
// What an organization cards section can hand-pick (067).
card_orgs:
"SELECT id, name || ' (' || kind || ')' AS label FROM organizations WHERE kind IN ('partner', 'ministry') ORDER BY kind, name",
event_scopes: "SELECT id, name AS label FROM event_scopes ORDER BY sort_order", event_scopes: "SELECT id, name AS label FROM event_scopes ORDER BY sort_order",
events: "SELECT id, title AS label FROM events ORDER BY starts_on DESC, title", events: "SELECT id, title AS label FROM events ORDER BY starts_on DESC, title",
people: "SELECT id, display_name AS label FROM people ORDER BY sort_name, display_name", people: "SELECT id, display_name AS label FROM people ORDER BY sort_name, display_name",
person_tag_types: "SELECT id, name AS label FROM person_tag_types ORDER BY sort_order, name", person_tag_types: "SELECT id, name AS label FROM person_tag_types ORDER BY sort_order, name",
contact_types: "SELECT id, name AS label FROM contact_types ORDER BY sort_order, name", contact_types: "SELECT id, name AS label FROM contact_types ORDER BY sort_order, name",
// Link fields with `redirects: true` pick from these (068).
redirects: "SELECT id, id || ' (' || target_url || ')' AS label FROM redirects ORDER BY id",
blog_posts: "SELECT id, title AS label FROM blog_posts ORDER BY published_on DESC, title", blog_posts: "SELECT id, title AS label FROM blog_posts ORDER BY published_on DESC, title",
// org_id rides along so the affiliation row can filter the list // org_id rides along so the affiliation row can filter the list

View file

@ -159,6 +159,8 @@ export const blocksChild = (ownerKind) => ({
url("href"), url("href"),
text("alt"), text("alt"),
text("cite"), text("cite"),
// Video blocks only (066): an uploaded video's WebVTT file.
text("captions"),
// People blocks only (054): whose team's tiles to show. // People blocks only (054): whose team's tiles to show.
text("team_id"), text("team_id"),
], ],

View file

@ -44,6 +44,7 @@ export const frontPage = {
text("livestream_title"), text("livestream_title"),
url("video_url"), url("video_url"),
text("video_title"), text("video_title"),
text("video_captions"),
text("countdown_event_id"), text("countdown_event_id"),
text("countdown_scope_id"), text("countdown_scope_id"),
enumeration("countdown_event_type", ["retreat", "class", "workshop", "meeting", "other"]), enumeration("countdown_event_type", ["retreat", "class", "workshop", "meeting", "other"]),

View file

@ -0,0 +1,30 @@
import { text, url } from "./columns.js";
/* ── Links/redirects (068_redirects.sql) ─────────────────────────
Short links on our domain, /go/<id>, answered by
routes/redirects.js. clicks and last_clicked_at are the route's,
so they're listed but never written from here: a save can't reset
a count. */
export const redirects = {
key: "redirects",
table: "redirects",
idColumn: "id",
idKind: "slug",
list: {
columns: ["id", "target_url", "clicks", "last_clicked_at"],
filters: [],
search: ["id", "target_url", "note", "utm_campaign"],
order: "id",
},
columns: [
url("target_url", { required: true }),
text("note"),
text("utm_source"),
text("utm_medium"),
text("utm_campaign"),
],
};

View file

@ -36,8 +36,20 @@ const sectionsChild = {
enumeration("event_type", ["retreat", "class", "workshop", "meeting", "other"]), enumeration("event_type", ["retreat", "class", "workshop", "meeting", "other"]),
enumeration("view", ["carousel", "grid", "map"]), enumeration("view", ["carousel", "grid", "map"]),
text("tag_id"), text("tag_id"),
// Organization cards (067): the kinds listed by themselves.
enumeration("org_kinds", ["partner", "ministry", "partner,ministry"]),
],
children: [
blocksChild("page_section"),
{
// Organization cards (067): a hand-picked list, shown instead.
key: "orgs",
table: "page_section_orgs",
owner: { column: "section_id" },
order: "sort_order",
columns: [text("org_id", { required: true })],
},
], ],
children: [blocksChild("page_section")],
}; };
const sitePage = (id, more = {}) => ({ const sitePage = (id, more = {}) => ({

View file

@ -34,6 +34,8 @@ export const siteSettings = {
text("access_group_viewer"), text("access_group_viewer"),
text("access_group_editor"), text("access_group_editor"),
text("access_group_admin"), text("access_group_admin"),
enumeration("report_daily", ["on", "off"]),
enumeration("report_weekly", ["on", "off"]),
], ],
children: [ children: [

View file

@ -0,0 +1,205 @@
/* ═══════════════════════════════════════════════════════════════
ANALYTICS REPORTS
Plausible's numbers for this site, posted to a Discord channel:
daily yesterday: visitors, pageviews, bounce rate, visit
length, top pages and sources
weekly Mondays: the last 7 days, with the change from the 7
before
Each is switched on in Panel → Site settings → Reports. Both go
out at SEND_HOUR in REPORT_TZ, or as soon after as the server is
up that day; analytics_reports (065) keeps it to one a day.
── Configuration (the ngu-api service environment) ──
PLAUSIBLE_API_KEY a Stats API key (Plausible → Account
settings → API keys)
DISCORD_WEBHOOK_URL the channel's webhook (Discord → channel
settings → Integrations → Webhooks)
PLAUSIBLE_URL default http://127.0.0.1:8000, where the
self-hosted Plausible listens
REPORT_TZ default America/Chicago
Off until the first two are set. The site counted is the hostname
of site.json's url, as in pageMeta.js's analyticsTag.
To send one now (eg. to try the setup), whatever the switches say:
DB_PATH=/var/lib/ngu/ngu.db node src/analyticsReport.js daily|weekly
Setup: docs/analytics-reports.md.
═══════════════════════════════════════════════════════════════ */
import { pathToFileURL } from "node:url";
import { siteFor } from "./pageMeta.js";
export const PLAUSIBLE_URL = (process.env.PLAUSIBLE_URL || "http://127.0.0.1:8000").replace(/\/$/, "");
const PLAUSIBLE_API_KEY = process.env.PLAUSIBLE_API_KEY || null;
const DISCORD_WEBHOOK_URL = process.env.DISCORD_WEBHOOK_URL || null;
const REPORT_TZ = process.env.REPORT_TZ || "America/Chicago";
const SEND_HOUR = 8;
const TICK_MS = 15 * 60 * 1000;
const KINDS = ["daily", "weekly"];
export const reportsReady = () => Boolean(PLAUSIBLE_API_KEY && DISCORD_WEBHOOK_URL);
/* Today's date and the hour in REPORT_TZ, and whether it's Monday. */
function localNow(now = new Date()) {
const parts = Object.fromEntries(
new Intl.DateTimeFormat("en-US", {
timeZone: REPORT_TZ,
year: "numeric",
month: "2-digit",
day: "2-digit",
hour: "2-digit",
hourCycle: "h23",
weekday: "short",
})
.formatToParts(now)
.map((part) => [part.type, part.value]),
);
return { date: `${parts.year}-${parts.month}-${parts.day}`, hour: Number(parts.hour), monday: parts.weekday === "Mon" };
}
/* "2026-10-04" moved by `days`. */
function shift(date, days) {
const d = new Date(`${date}T00:00:00Z`);
d.setUTCDate(d.getUTCDate() + days);
return d.toISOString().slice(0, 10);
}
/* ── Plausible ─────────────────────────────────────────────── */
async function query(siteId, body) {
const res = await fetch(`${PLAUSIBLE_URL}/api/v2/query`, {
method: "POST",
headers: { Authorization: `Bearer ${PLAUSIBLE_API_KEY}`, "Content-Type": "application/json" },
body: JSON.stringify({ site_id: siteId, ...body }),
signal: AbortSignal.timeout(20_000),
});
if (!res.ok) throw new Error(`Plausible answered ${res.status}: ${(await res.text()).slice(0, 200)}`);
return (await res.json()).results ?? [];
}
const METRICS = ["visitors", "pageviews", "bounce_rate", "visit_duration"];
async function totals(siteId, range) {
const [row] = await query(siteId, { metrics: METRICS, date_range: range });
return Object.fromEntries(METRICS.map((metric, i) => [metric, row?.metrics[i] ?? 0]));
}
async function top(siteId, dimension, range, limit) {
const rows = await query(siteId, {
metrics: ["visitors"],
dimensions: [dimension],
date_range: range,
order_by: [["visitors", "desc"]],
pagination: { limit },
});
return rows.length ? rows.map((r) => `${r.dimensions[0]}: ${r.metrics[0]}`).join("\n") : "-";
}
/* ── The message ───────────────────────────────────────────── */
const duration = (seconds) => `${Math.floor(seconds / 60)}m ${Math.round(seconds % 60)}s`;
function change(now, before) {
if (!before) return now ? " (new)" : "";
const percent = Math.round(((now - before) / before) * 100);
return ` (${percent >= 0 ? "+" : ""}${percent}%)`;
}
/* The Discord message for `kind` as of `today` (a REPORT_TZ date):
yesterday, or the 7 days ending yesterday. */
export async function buildReport(db, kind, today) {
const siteId = new URL(siteFor(db).url).hostname;
const to = shift(today, -1);
const from = kind === "weekly" ? shift(to, -6) : to;
const range = [from, to];
const limit = kind === "weekly" ? 5 : 3;
const [now, before, pages, sources] = await Promise.all([
totals(siteId, range),
kind === "weekly" ? totals(siteId, [shift(from, -7), shift(to, -7)]) : null,
top(siteId, "event:page", range, limit),
top(siteId, "visit:source", range, limit),
]);
const vs = (metric) => (before ? change(now[metric], before[metric]) : "");
return {
embeds: [
{
title: kind === "weekly" ? `${siteId}: week of ${from} to ${to}` : `${siteId}: ${to}`,
fields: [
{ name: "Visitors", value: `${now.visitors}${vs("visitors")}`, inline: true },
{ name: "Pageviews", value: `${now.pageviews}${vs("pageviews")}`, inline: true },
{ name: "Bounce rate", value: `${now.bounce_rate}%`, inline: true },
{ name: "Visit length", value: duration(now.visit_duration), inline: true },
{ name: "Top pages", value: pages },
{ name: "Top sources", value: sources },
],
},
],
};
}
export async function sendReport(db, kind, today = localNow().date) {
const res = await fetch(DISCORD_WEBHOOK_URL, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(await buildReport(db, kind, today)),
signal: AbortSignal.timeout(20_000),
});
if (!res.ok) throw new Error(`Discord answered ${res.status}: ${(await res.text()).slice(0, 200)}`);
}
/* ── Schedule ──────────────────────────────────────────────── */
export function startAnalyticsReports(db) {
if (!reportsReady()) return;
let running = false;
const tick = async () => {
const { date, hour, monday } = localNow();
if (running || hour < SEND_HOUR) return;
running = true;
try {
const settings = db.prepare(`SELECT report_daily, report_weekly FROM site_settings WHERE id = 'site'`).get() ?? {};
for (const kind of KINDS) {
if (settings[`report_${kind}`] !== "on" || (kind === "weekly" && !monday)) continue;
if (db.prepare(`SELECT 1 FROM analytics_reports WHERE kind = ? AND sent_for = ?`).get(kind, date)) continue;
// Marked before sending: a Plausible or Discord failure is
// logged once that day, not every tick.
db.prepare(
`INSERT INTO analytics_reports (kind, sent_for) VALUES (?, ?)
ON CONFLICT (kind) DO UPDATE SET sent_for = excluded.sent_for`,
).run(kind, date);
try {
await sendReport(db, kind, date);
console.log(`analytics ${kind} report sent for ${date}`);
} catch (err) {
console.error(`analytics ${kind} report failed: ${err.message}`);
}
}
} finally {
running = false;
}
};
tick();
setInterval(tick, TICK_MS).unref();
}
/* ── By hand ───────────────────────────────────────────────── */
if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) {
const kind = process.argv[2];
if (!KINDS.includes(kind)) {
console.error("usage: node src/analyticsReport.js daily|weekly");
process.exit(1);
}
if (!reportsReady()) {
console.error("Set PLAUSIBLE_API_KEY and DISCORD_WEBHOOK_URL first.");
process.exit(1);
}
const { openDatabase } = await import("./db.js");
const db = await openDatabase(process.env.DB_PATH ?? "./ngu.db");
await sendReport(db, kind);
console.log(`Sent the ${kind} report.`);
}

View file

@ -49,7 +49,7 @@
import { spawn } from "node:child_process"; import { spawn } from "node:child_process";
import { randomBytes } from "node:crypto"; import { randomBytes } from "node:crypto";
import { access, constants, copyFile, mkdir, readdir, rm, stat } from "node:fs/promises"; import { access, constants, copyFile, mkdir, readFile, readdir, rm, stat } from "node:fs/promises";
import path from "node:path"; import path from "node:path";
import { UPLOADS_DIR, PUBLIC_PREFIX } from "./media.js"; import { UPLOADS_DIR, PUBLIC_PREFIX } from "./media.js";
@ -446,6 +446,63 @@ async function cut(db, job) {
}); });
} }
/* ── A single frame ──────────────────────────────────────── */
/* One frame of a YouTube or Facebook video as a JPEG, for a card's
picture. yt-dlp only finds the stream's address and ffmpeg seeks
in it, so nothing is downloaded but that frame; light enough to
run in the request, outside the queue. */
export async function grabFrame(sourceUrl, seconds) {
const link = checkSourceUrl(sourceUrl);
if (!Number.isFinite(seconds) || seconds < 0 || seconds > MAX_SOURCE_SECONDS) {
throw new ClipError(400, "That isn't a time in the video.");
}
await mkdir(CLIPS_DIR, { recursive: true });
const id = `frame-${randomBytes(6).toString("hex")}`;
const out = path.join(CLIPS_DIR, `${id}.jpg`);
const cookies = await cookieArgs(id);
let stream = null;
try {
await run(
YTDLP,
[
"--ignore-config",
...cookies.args,
"--js-runtimes",
`node:${process.execPath}`,
"--no-playlist",
"-f",
"bv*[height<=1080]/b[height<=1080]/b",
"--get-url",
"--",
link,
],
{ onLine: (line) => (stream ??= /^https:\/\//.test(line.trim()) ? line.trim() : null) },
);
} catch (err) {
if (err instanceof ClipError) throw err;
console.error(`frame ${link}: ${err.message}`);
throw new ClipError(422, "The video couldn't be opened. It may be private or removed.");
} finally {
await cookies.cleanup();
}
if (!stream) throw new ClipError(422, "The video couldn't be opened. It may be private or removed.");
try {
// -ss before -i seeks in the stream instead of reading up to it.
await run(FFMPEG, ["-hide_banner", "-loglevel", "error", "-ss", String(seconds), "-i", stream, "-frames:v", "1", "-q:v", "2", "-y", out]);
return await readFile(out);
} catch (err) {
// Past the end, ffmpeg finishes without writing anything.
if (err.code === "ENOENT") throw new ClipError(422, "The video doesn't run that long.");
if (err instanceof ClipError) throw err;
console.error(`frame ${link} at ${seconds}: ${err.message}`);
throw new ClipError(422, "The frame couldn't be taken from the video.");
} finally {
await rm(out, { force: true });
}
}
let running = false; let running = false;
let dbRef = null; let dbRef = null;

View file

@ -84,6 +84,9 @@ export function tx(db, fn) {
baseline was built by those older files and has to be brought baseline was built by those older files and has to be brought
up by a release that still has them; running the baseline over up by a release that still has them; running the baseline over
it would fail halfway on CREATE TABLE, so this refuses first. it would fail halfway on CREATE TABLE, so this refuses first.
The baseline's seed shares its version (066_schema.sql, then
066_seed.sql): `current` is read once, so an empty database
runs both and one already at that version skips both.
───────────────────────────────────────────────────────────── */ ───────────────────────────────────────────────────────────── */
export function migrate(db, { log = console.log } = {}) { export function migrate(db, { log = console.log } = {}) {

View file

@ -40,11 +40,13 @@ import clips from "./routes/clips.js";
import imports from "./routes/import.js"; import imports from "./routes/import.js";
import files from "./routes/files.js"; import files from "./routes/files.js";
import countdown from "./routes/countdown.js"; import countdown from "./routes/countdown.js";
import redirects from "./routes/redirects.js";
import { CLIPS_DIR, startClipWorker } from "./clips.js"; import { CLIPS_DIR, startClipWorker } from "./clips.js";
import { UPLOADS_DIR, writeMissingThumbs } from "./media.js"; import { UPLOADS_DIR, writeMissingThumbs } from "./media.js";
import { logSafe, startSessionSweeper } from "./auth.js"; import { logSafe, startSessionSweeper } from "./auth.js";
import { syncDescriptorsWithSchema } from "./admin-schema-sync.js"; import { syncDescriptorsWithSchema } from "./admin-schema-sync.js";
import { startGroupSync } from "./accessGroups.js"; import { startGroupSync } from "./accessGroups.js";
import { startAnalyticsReports } from "./analyticsReport.js";
import { ENTITIES } from "./admin-schema.js"; import { ENTITIES } from "./admin-schema.js";
const HOST = process.env.HOST ?? "127.0.0.1"; const HOST = process.env.HOST ?? "127.0.0.1";
@ -234,6 +236,10 @@ app.use(
}), }),
); );
// Short links, /go/<id> (routes/redirects.js); an unknown one falls
// through to the pages below.
app.route("/", redirects);
// Last: every other GET that isn't /api is a page of the site, sent // Last: every other GET that isn't /api is a page of the site, sent
// with its metadata filled in (routes/pages.js). // with its metadata filled in (routes/pages.js).
app.route("/", pages); app.route("/", pages);
@ -241,6 +247,7 @@ app.route("/", pages);
startSessionSweeper(db); startSessionSweeper(db);
startGroupSync(db); startGroupSync(db);
startClipWorker(db); startClipWorker(db);
startAnalyticsReports(db);
console.log(`clips ${CLIPS_DIR}`); console.log(`clips ${CLIPS_DIR}`);
app.notFound((c) => c.json({ error: "Not found" }, 404)); app.notFound((c) => c.json({ error: "Not found" }, 404));

View file

@ -15,8 +15,9 @@
── What ── ── What ──
The type is read from the file's first bytes, never from its The type is read from the file's first bytes, never from its
name or the browser's Content-Type, both of which the uploader name or the browser's Content-Type, both of which the uploader
controls. JPEG, PNG, GIF, WebP and SVG are accepted; anything controls. JPEG, PNG, GIF, WebP and SVG are accepted, and WebVTT
else is refused. captions (a text file starting "WEBVTT"); anything else is
refused.
── Processing ── ── Processing ──
By default a raster image is turned upright (EXIF orientation), By default a raster image is turned upright (EXIF orientation),
@ -25,7 +26,7 @@
`keepOriginal` stores the bytes exactly as uploaded instead, `keepOriginal` stores the bytes exactly as uploaded instead,
under the tighter KEEP_MAX_BYTES. An SVG is always kept as it under the tighter KEEP_MAX_BYTES. An SVG is always kept as it
is: it's already small, and rasterizing it would lose the point is: it's already small, and rasterizing it would lose the point
of it. of it. So is a WebVTT file, always into captions/.
Names are random, so two uploads of "logo.png" can't collide Names are random, so two uploads of "logo.png" can't collide
and a filename says nothing about what's in it. and a filename says nothing about what's in it.
@ -33,8 +34,8 @@
── Folders ── ── Folders ──
Each upload goes in a folder by what it's for (FOLDERS): logos/ Each upload goes in a folder by what it's for (FOLDERS): logos/
for logo and icon fields, thumbnails/ for pictures the site saves for logo and icon fields, thumbnails/ for pictures the site saves
by itself (link previews, Drive files' first pages), images/ for by itself (link previews, Drive files' first pages), captions/
the rest. A stored name includes it: 'logos/3f9c….webp', served at for videos' WebVTT files, 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 /uploads/logos/3f9c….webp. The small copy sits beside it. Clips
keep a bare name in the root. keep a bare name in the root.
@ -66,7 +67,7 @@ const MB = 1024 * 1024;
/* The largest file accepted at all, before processing: room for a /* The largest file accepted at all, before processing: room for a
full-size phone photo. */ full-size phone photo. */
/* Where an upload goes, by what it's for (see Folders above). */ /* Where an upload goes, by what it's for (see Folders above). */
export const FOLDERS = ["logos", "images", "thumbnails"]; export const FOLDERS = ["logos", "images", "thumbnails", "captions"];
export const folderOf = (value) => (FOLDERS.includes(value) ? value : "images"); export const folderOf = (value) => (FOLDERS.includes(value) ? value : "images");
/* A name this library stores: a bare name in the root, or one inside /* A name this library stores: a bare name in the root, or one inside
@ -131,8 +132,12 @@ const TYPES = {
gif: { mime: "image/gif", ext: ".gif" }, gif: { mime: "image/gif", ext: ".gif" },
webp: { mime: "image/webp", ext: ".webp" }, webp: { mime: "image/webp", ext: ".webp" },
svg: { mime: "image/svg+xml", ext: ".svg" }, svg: { mime: "image/svg+xml", ext: ".svg" },
vtt: { mime: "text/vtt", ext: ".vtt" },
}; };
/* Kinds stored exactly as uploaded, with no small copy: text, not pixels. */
const AS_IS = new Set(["svg", "vtt"]);
function startsWith(buf, bytes, offset = 0) { function startsWith(buf, bytes, offset = 0) {
return bytes.every((byte, i) => buf[offset + i] === byte); return bytes.every((byte, i) => buf[offset + i] === byte);
} }
@ -151,6 +156,7 @@ function sniff(buf) {
if (/^(<\?xml[\s\S]*?\?>\s*)?(<!--[\s\S]*?-->\s*|<!DOCTYPE[^>]*>\s*)*<svg[\s>]/i.test(head)) { if (/^(<\?xml[\s\S]*?\?>\s*)?(<!--[\s\S]*?-->\s*|<!DOCTYPE[^>]*>\s*)*<svg[\s>]/i.test(head)) {
return "svg"; return "svg";
} }
if (/^WEBVTT(\s|$)/.test(head)) return "vtt";
return null; return null;
} }
@ -169,10 +175,10 @@ export async function store(buf, { keepOriginal = false, folder } = {}) {
const kind = sniff(buf); const kind = sniff(buf);
if (!kind) { if (!kind) {
throw new MediaError(415, "Only JPEG, PNG, GIF, WebP and SVG images can be uploaded."); throw new MediaError(415, "Only JPEG, PNG, GIF, WebP and SVG images, and WebVTT (.vtt) captions, can be uploaded.");
} }
const convert = kind !== "svg" && !keepOriginal; const convert = !AS_IS.has(kind) && !keepOriginal;
if (!convert && buf.length > KEEP_MAX_BYTES) { if (!convert && buf.length > KEEP_MAX_BYTES) {
throw new MediaError( throw new MediaError(
@ -200,7 +206,7 @@ export async function store(buf, { keepOriginal = false, folder } = {}) {
width = info.width; width = info.width;
// An animated image reports the whole strip's height. // An animated image reports the whole strip's height.
height = info.pageHeight ?? info.height; height = info.pageHeight ?? info.height;
} else if (kind !== "svg") { } else if (!AS_IS.has(kind)) {
const meta = await sharp(buf, { limitInputPixels: MAX_INPUT_PIXELS }).metadata(); const meta = await sharp(buf, { limitInputPixels: MAX_INPUT_PIXELS }).metadata();
width = meta.width ?? null; width = meta.width ?? null;
height = meta.pageHeight ?? meta.height ?? null; height = meta.pageHeight ?? meta.height ?? null;
@ -209,7 +215,7 @@ export async function store(buf, { keepOriginal = false, folder } = {}) {
throw new MediaError(415, "That image couldn't be read. It may be damaged."); throw new MediaError(415, "That image couldn't be read. It may be damaged.");
} }
const dir = folderOf(folder); const dir = kind === "vtt" ? "captions" : folderOf(folder);
const base = `${randomBytes(12).toString("hex")}${type.ext}`; const base = `${randomBytes(12).toString("hex")}${type.ext}`;
const filename = `${dir}/${base}`; const filename = `${dir}/${base}`;
@ -219,7 +225,7 @@ export async function store(buf, { keepOriginal = false, folder } = {}) {
const tmp = path.join(UPLOADS_DIR, dir, `.${base}.tmp`); const tmp = path.join(UPLOADS_DIR, dir, `.${base}.tmp`);
await writeFile(tmp, out); await writeFile(tmp, out);
await rename(tmp, path.join(UPLOADS_DIR, filename)); await rename(tmp, path.join(UPLOADS_DIR, filename));
if (kind !== "svg") await writeThumb(filename, out); if (!AS_IS.has(kind)) await writeThumb(filename, out);
return { return {
filename, filename,
@ -269,10 +275,10 @@ export async function writeMissingThumbs() {
const present = new Set(names); const present = new Set(names);
let made = 0; let made = 0;
for (const name of names) { for (const name of names) {
if (THUMB.test(name) || /\.svg$/i.test(name)) continue; if (THUMB.test(name) || /\.(svg|vtt)$/i.test(name)) continue;
if (present.has(thumbName(name))) continue; if (present.has(thumbName(name))) continue;
const buf = await readFile(path.join(UPLOADS_DIR, name)).catch(() => null); const buf = await readFile(path.join(UPLOADS_DIR, name)).catch(() => null);
if (!buf || !sniff(buf) || sniff(buf) === "svg") continue; if (!buf || !sniff(buf) || AS_IS.has(sniff(buf))) continue;
await writeThumb(name, buf); await writeThumb(name, buf);
made += 1; made += 1;
} }
@ -309,7 +315,7 @@ async function describe(filename) {
let width = null; let width = null;
let height = null; let height = null;
if (kind !== "svg") { if (!AS_IS.has(kind)) {
try { try {
const meta = await sharp(buf, { limitInputPixels: MAX_INPUT_PIXELS }).metadata(); const meta = await sharp(buf, { limitInputPixels: MAX_INPUT_PIXELS }).metadata();
width = meta.width ?? null; width = meta.width ?? null;

View file

@ -1,79 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 024 FRONT PAGE: FEATURED VIDEO
--
-- A fourth hero mode, 'video': a recorded video beside the words,
-- the way 'livestream' puts a stream there, but without the LIVE
-- badge and without autoplay: a visitor presses play.
--
-- Its own two columns rather than reusing the livestream's, so a
-- featured video and a stream can both be set up ahead of time and
-- the mode switches between them, as photos and livestream already
-- can.
--
-- video_url a YouTube, Vimeo or Facebook link (turned into an
-- embed), or a video file: a filename in
-- public/front-page/, a /path, or an https URL ending
-- in .mp4, .webm, .m4v, .mov or .ogv, which plays in
-- the browser's own player
-- video_title shown after "Featured video" above the headline
--
-- hero_mode's CHECK can't be altered in place, so front_page is
-- rebuilt. Its children (slides, sections, stats, paths) reference
-- it by name; the runner has foreign keys off, so the DROP leaves
-- them alone and the rename puts front_page back underneath them.
-- No view or other table's trigger names front_page, so the rename
-- needs no legacy_alter_table. front_page_touch goes with the old
-- table and is recreated last.
--
-- PRAGMA user_version; -- reads 23 before this file
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE front_page_new (
id TEXT PRIMARY KEY CHECK (id = 'home'),
hero_mode TEXT NOT NULL DEFAULT 'brand'
CHECK (hero_mode IN ('brand', 'photos', 'livestream', 'video')),
eyebrow TEXT,
headline TEXT NOT NULL DEFAULT 'Next Generation of Unity',
subhead TEXT,
primary_label TEXT,
primary_url TEXT,
secondary_label TEXT,
secondary_url TEXT,
slide_seconds INTEGER NOT NULL DEFAULT 7
CHECK (slide_seconds BETWEEN 3 AND 60),
livestream_url TEXT,
livestream_title TEXT,
video_url TEXT,
video_title TEXT,
countdown_event_id TEXT REFERENCES events (id) ON DELETE SET NULL,
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
) STRICT;
INSERT INTO front_page_new
(id, hero_mode, eyebrow, headline, subhead,
primary_label, primary_url, secondary_label, secondary_url,
slide_seconds, livestream_url, livestream_title,
countdown_event_id, updated_at)
SELECT
id, hero_mode, eyebrow, headline, subhead,
primary_label, primary_url, secondary_label, secondary_url,
slide_seconds, livestream_url, livestream_title,
countdown_event_id, updated_at
FROM front_page;
DROP TABLE front_page;
ALTER TABLE front_page_new RENAME TO front_page;
CREATE TRIGGER front_page_touch
AFTER UPDATE ON front_page
FOR EACH ROW WHEN new.updated_at = old.updated_at
BEGIN
UPDATE front_page SET updated_at = datetime('now') WHERE id = new.id;
END;

View file

@ -1,40 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 025 HERO: BACKDROP AND FEATURE ARE SEPARATE CHOICES
--
-- hero_mode answered two questions with one value: what fills the
-- background (the brand animation or the photo slideshow) and what
-- sits beside the words (nothing, a livestream or a featured
-- video). A stream or a video could only ever sit on the brand
-- backdrop. Split, any backdrop goes with any feature.
--
-- hero_backdrop 'brand' | 'photos'
-- hero_feature 'none' | 'livestream' | 'video'
--
-- Today's modes map across exactly: photos → photos + none;
-- livestream and video → brand + that feature; brand → brand +
-- none. Photos mode still falls back to brand on the page when
-- there are no photos, as before.
--
-- ADD COLUMN takes a constant DEFAULT and a CHECK, and DROP COLUMN
-- allows a column whose only constraint is its own CHECK, so no
-- rebuild: front_page's children and its touch trigger are never
-- touched.
--
-- PRAGMA user_version; -- reads 24 before this file
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE front_page ADD COLUMN hero_backdrop TEXT NOT NULL DEFAULT 'brand'
CHECK (hero_backdrop IN ('brand', 'photos'));
ALTER TABLE front_page ADD COLUMN hero_feature TEXT NOT NULL DEFAULT 'none'
CHECK (hero_feature IN ('none', 'livestream', 'video'));
UPDATE front_page
SET hero_backdrop = CASE hero_mode WHEN 'photos' THEN 'photos' ELSE 'brand' END,
hero_feature = CASE hero_mode
WHEN 'livestream' THEN 'livestream'
WHEN 'video' THEN 'video'
ELSE 'none'
END;
ALTER TABLE front_page DROP COLUMN hero_mode;

View file

@ -1,29 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 026 COUNTDOWN: FILTER BY SCOPE AND TYPE
--
-- The countdown counts to the pinned event, or else to the next
-- published event that hasn't ended. These two narrow "the next
-- event": National + Retreat counts down to the next national
-- retreat and skips a regional class that happens sooner. Either or
-- both can be left null, meaning any. A pinned event still wins
-- whatever they say; the admin chose it by name.
--
-- countdown_scope_id an event_scopes id. A real foreign key,
-- so it can't name a scope that doesn't
-- exist; ON DELETE SET NULL puts it back to
-- "any" if a scope is ever removed.
-- countdown_event_type the same values as events.event_type.
-- Adding an event type now means widening
-- this CHECK too.
--
-- Plain ADD COLUMN: a REFERENCES column is allowed when its default
-- is NULL, and a CHECK is allowed on any. No rebuild.
--
-- PRAGMA user_version; -- reads 25 before this file
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE front_page ADD COLUMN countdown_scope_id TEXT
REFERENCES event_scopes (id) ON DELETE SET NULL;
ALTER TABLE front_page ADD COLUMN countdown_event_type TEXT
CHECK (countdown_event_type IN ('retreat', 'class', 'workshop', 'meeting', 'other'));

View file

@ -1,43 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 027 LISTED: PUBLISHED BUT ONLY BY LINK
--
-- is_published stays the hard gate: 0 is a draft (or, for people,
-- private), off the site entirely and a 404 at its own URL.
-- is_listed only means anything on a published row. 0 keeps the
-- record's own page working but leaves it out of every list the
-- site gathers by itself:
--
-- the /events, /organizations, /teams and /awards lists (and so
-- every band, calendar, map and card grid built on them), a
-- region's chapters, an organization's events, teams and awards,
-- the /directory the QR page reads, and the front page's counts
-- and next-event countdown.
--
-- It still appears wherever someone attached it by hand: rosters,
-- billed people, hosts, award recipients, timeline entries, and a
-- countdown pinned to it by name. Each of those rows has its own
-- is_public (or is_published) to hide it there.
--
-- Defaults to 1, so every existing row stays listed.
--
-- Plain ADD COLUMN: NOT NULL with a constant default and a CHECK is
-- allowed without a rebuild, STRICT tables included. v_events reads
-- e.*, so it picks the column up with no change of its own.
--
-- PRAGMA user_version; -- reads 26 before this file
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE organizations ADD COLUMN is_listed INTEGER NOT NULL DEFAULT 1
CHECK (is_listed IN (0, 1));
ALTER TABLE events ADD COLUMN is_listed INTEGER NOT NULL DEFAULT 1
CHECK (is_listed IN (0, 1));
ALTER TABLE people ADD COLUMN is_listed INTEGER NOT NULL DEFAULT 1
CHECK (is_listed IN (0, 1));
ALTER TABLE teams ADD COLUMN is_listed INTEGER NOT NULL DEFAULT 1
CHECK (is_listed IN (0, 1));
ALTER TABLE awards ADD COLUMN is_listed INTEGER NOT NULL DEFAULT 1
CHECK (is_listed IN (0, 1));

View file

@ -1,41 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 028 MEDIA: UPLOADED IMAGES
--
-- One row per file in UPLOADS_DIR (/var/lib/ngu/uploads in
-- production, outside the deployed app so an rsync can't touch
-- it). nginx serves the directory at /uploads/; the API only
-- writes and deletes.
--
-- An image field stores the file's public path, '/uploads/<file>',
-- not this row's id. That keeps every image column a plain TEXT
-- that also takes a filename in public/ or a full URL, as before,
-- and means media.ts needs no lookup. The cost is no foreign key:
-- deleting a file a record still names leaves that record showing
-- nothing (the <Logo> and <img> fallbacks already handle a missing
-- file), so the Media page warns before a delete.
--
-- filename the stored name: random, so it can't collide or
-- be guessed from the original. '3f9c…e1.webp'
-- original_name what the uploader's file was called, for the
-- library's search and display
-- processed 1 when resized and converted to WebP, 0 when
-- kept as uploaded
-- width, height null for an SVG, which has no pixel size
--
-- PRAGMA user_version; -- reads 27 before this file
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE media (
id INTEGER PRIMARY KEY AUTOINCREMENT,
filename TEXT NOT NULL UNIQUE,
original_name TEXT NOT NULL,
content_type TEXT NOT NULL,
bytes INTEGER NOT NULL CHECK (bytes >= 0),
width INTEGER,
height INTEGER,
processed INTEGER NOT NULL DEFAULT 1 CHECK (processed IN (0, 1)),
uploaded_by INTEGER REFERENCES admin_users (id) ON DELETE SET NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
) STRICT;
CREATE INDEX media_created_idx ON media (created_at DESC);

View file

@ -1,15 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 029 EVENTS: CARD BACKGROUND IMAGE
--
-- A photo behind an event's card. The card keeps its size and its
-- layout; the image covers it, under a light veil (CARD_IMAGE_VEIL
-- in EventList-Cards.tsx) so the text on top stays readable.
--
-- Like every image column, it holds a path: '/uploads/<file>' from
-- the media library, a bare filename in public/event-backgrounds/,
-- or a full URL. Null draws the card as before.
--
-- PRAGMA user_version; -- reads 28 before this file
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE events ADD COLUMN card_image TEXT;

View file

@ -1,167 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 030 FEATURED CARDS
--
-- A row of cards that point somewhere: the front page's new
-- 'featured' band first, and the Community page's blog posts next.
-- One table for both, owned polymorphically like links and
-- content_blocks, so the card's shape and the code that draws it
-- are written once. owner_kind only allows 'front_page' today;
-- adding an owner is a rebuild of this table, which nothing
-- references, so it's a cheap one.
--
-- A card is one of three kinds:
--
-- record points at an event, organization, person, team or
-- award. Title, image and link come from that record at
-- read time, so renaming the event renames the card.
-- Any of title, blurb and image filled in here overrides.
-- link any URL, on the site or off it. Title and image are
-- the card's own (the editor can fetch them from the
-- page's preview tags).
-- video a YouTube, Vimeo or Facebook link, or a video file.
-- Drawn as a thumbnail that swaps in the player when
-- pressed. image overrides the thumbnail.
--
-- ref_kind + ref_id is checked by the triggers below, the same way
-- timeline_entries' is, and a deleted record takes its cards with
-- it. An unpublished record's card is left out when read.
--
-- Also: 'featured' joins front_page_sections.section. A CHECK can't
-- be altered in place, so that table is rebuilt. No view or trigger
-- names it, and nothing references it.
--
-- PRAGMA user_version; -- reads 29 before this file
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE front_page_sections_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
page_id TEXT NOT NULL REFERENCES front_page (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
section TEXT NOT NULL
CHECK (section IN ('countdown', 'retreats', 'calendar', 'stats',
'timeline', 'connect', 'featured')),
title TEXT,
blurb TEXT,
is_hidden INTEGER NOT NULL DEFAULT 0 CHECK (is_hidden IN (0, 1)),
UNIQUE (page_id, section)
) STRICT;
INSERT INTO front_page_sections_new (id, page_id, sort_order, section, title, blurb, is_hidden)
SELECT id, page_id, sort_order, section, title, blurb, is_hidden
FROM front_page_sections;
DROP TABLE front_page_sections;
ALTER TABLE front_page_sections_new RENAME TO front_page_sections;
CREATE TABLE featured_cards (
id INTEGER PRIMARY KEY AUTOINCREMENT,
owner_kind TEXT NOT NULL CHECK (owner_kind IN ('front_page')),
owner_id TEXT NOT NULL,
sort_order INTEGER NOT NULL DEFAULT 0,
kind TEXT NOT NULL DEFAULT 'link'
CHECK (kind IN ('record', 'link', 'video')),
ref_kind TEXT CHECK (ref_kind IN ('event', 'organization', 'person', 'team', 'award')),
ref_id TEXT,
url TEXT,
eyebrow TEXT, -- 'Article', 'Watch'
title TEXT,
blurb TEXT,
image TEXT, -- '/uploads/…', a filename, or a URL
CHECK ((ref_kind IS NULL) = (ref_id IS NULL)),
-- A record card needs its record; the other two need somewhere to
-- go. Named as sentences: the admin shows a sentence-shaped
-- constraint name as the error (wrapDbErrors in admin-crud.js).
CONSTRAINT "A record card needs a record to point at."
CHECK (kind != 'record' OR ref_kind IS NOT NULL),
CONSTRAINT "A link or video card needs a URL."
CHECK (kind = 'record' OR url IS NOT NULL)
) STRICT;
CREATE INDEX featured_cards_owner_idx ON featured_cards (owner_kind, owner_id, sort_order);
-- ── Triggers last (see CLAUDE.md, Migrations) ──
CREATE TRIGGER featured_cards_ref_exists
BEFORE INSERT ON featured_cards
BEGIN
SELECT CASE
WHEN new.ref_kind = 'event'
AND NOT EXISTS (SELECT 1 FROM events WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such event')
WHEN new.ref_kind = 'organization'
AND NOT EXISTS (SELECT 1 FROM organizations WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such organization')
WHEN new.ref_kind = 'person'
AND NOT EXISTS (SELECT 1 FROM people WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such person')
WHEN new.ref_kind = 'team'
AND NOT EXISTS (SELECT 1 FROM teams WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such team')
WHEN new.ref_kind = 'award'
AND NOT EXISTS (SELECT 1 FROM awards WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such award')
END;
END;
CREATE TRIGGER featured_cards_ref_exists_update
BEFORE UPDATE OF ref_kind, ref_id ON featured_cards
BEGIN
SELECT CASE
WHEN new.ref_kind = 'event'
AND NOT EXISTS (SELECT 1 FROM events WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such event')
WHEN new.ref_kind = 'organization'
AND NOT EXISTS (SELECT 1 FROM organizations WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such organization')
WHEN new.ref_kind = 'person'
AND NOT EXISTS (SELECT 1 FROM people WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such person')
WHEN new.ref_kind = 'team'
AND NOT EXISTS (SELECT 1 FROM teams WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such team')
WHEN new.ref_kind = 'award'
AND NOT EXISTS (SELECT 1 FROM awards WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such award')
END;
END;
-- A deleted record takes the cards that point at it. Separate
-- triggers rather than additions to the existing *_cleanup ones, so
-- this file doesn't have to drop and restate those.
CREATE TRIGGER events_featured_cleanup
AFTER DELETE ON events
BEGIN
DELETE FROM featured_cards WHERE ref_kind = 'event' AND ref_id = old.id;
END;
CREATE TRIGGER organizations_featured_cleanup
AFTER DELETE ON organizations
BEGIN
DELETE FROM featured_cards WHERE ref_kind = 'organization' AND ref_id = old.id;
END;
CREATE TRIGGER people_featured_cleanup
AFTER DELETE ON people
BEGIN
DELETE FROM featured_cards WHERE ref_kind = 'person' AND ref_id = old.id;
END;
CREATE TRIGGER teams_featured_cleanup
AFTER DELETE ON teams
BEGIN
DELETE FROM featured_cards WHERE ref_kind = 'team' AND ref_id = old.id;
END;
CREATE TRIGGER awards_featured_cleanup
AFTER DELETE ON awards
BEGIN
DELETE FROM featured_cards WHERE ref_kind = 'award' AND ref_id = old.id;
END;

View file

@ -1,254 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 031 BLOG
--
-- Posts of our own, at /blog/<id>, and the Community page's blog
-- section, which shows two subsections:
--
-- Our posts pinned blog_posts first, then the newest
-- published, listed ones, up to internal_slots
-- Community posts pinned featured_cards (owner 'community_page')
-- first, then the newest items from the RSS or
-- Atom feeds in community_page_feeds, up to
-- external_slots
--
-- blog_posts
-- A draft until published (is_published defaults to 0, as for
-- people): a half-written post shouldn't go live by accident.
-- is_listed works as it does everywhere (027): unticked, the post
-- is left out of "newest" but its page works and it can be pinned.
-- The body is content_blocks with owner_kind 'blog_post', slot
-- 'body'. Authors are people (blog_post_authors), or a guest named
-- on the post itself, or both. tags is a comma-separated list, eg.
-- 'Reflection, Event recap'; it is only displayed, never joined on.
--
-- content_blocks gains 'blog_post' as an owner. A CHECK can't be
-- altered in place, so the table is rebuilt; the *_cleanup triggers
-- on other tables name it, hence legacy_alter_table around the
-- rename. Its own index and owner trigger are recreated below.
--
-- featured_cards gains 'community_page' as an owner, the same way.
-- Nothing names it but its own triggers, recreated below.
--
-- community_page is a singleton like front_page: one row, made
-- here, which the admin edits and can't delete.
--
-- PRAGMA user_version; -- reads 30 before this file
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE blog_posts (
id TEXT PRIMARY KEY, -- slug: 'finding-unity-at-camp'
title TEXT NOT NULL,
excerpt TEXT, -- the card's text; else the body's start
cover_image TEXT, -- '/uploads/…', a filename, or a URL
published_on TEXT, -- 'YYYY-MM-DD'; newest first
tags TEXT, -- 'Reflection, Event recap'
guest_author TEXT, -- someone with no people row
guest_photo TEXT,
is_published INTEGER NOT NULL DEFAULT 0 CHECK (is_published IN (0, 1)),
is_listed INTEGER NOT NULL DEFAULT 1 CHECK (is_listed IN (0, 1)),
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
) STRICT;
CREATE INDEX blog_posts_newest_idx ON blog_posts (is_published, is_listed, published_on DESC);
CREATE TABLE blog_post_authors (
post_id TEXT NOT NULL REFERENCES blog_posts (id) ON DELETE CASCADE,
person_id TEXT NOT NULL REFERENCES people (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (post_id, person_id)
) STRICT;
CREATE INDEX blog_post_authors_person_idx ON blog_post_authors (person_id);
CREATE TABLE community_page (
id TEXT PRIMARY KEY CHECK (id = 'community'),
blog_title TEXT, -- null → 'Community Blog'
blog_blurb TEXT,
internal_title TEXT, -- null → 'From NGU'
internal_slots INTEGER NOT NULL DEFAULT 3 CHECK (internal_slots BETWEEN 0 AND 12),
external_title TEXT, -- null → 'From our community'
external_slots INTEGER NOT NULL DEFAULT 3 CHECK (external_slots BETWEEN 0 AND 12),
external_url TEXT, -- the Substack home, for its button
external_label TEXT, -- null → 'Read more on Substack'
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
) STRICT;
INSERT INTO community_page (id) VALUES ('community');
CREATE TABLE community_page_pinned_posts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
page_id TEXT NOT NULL REFERENCES community_page (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
post_id TEXT NOT NULL REFERENCES blog_posts (id) ON DELETE CASCADE,
UNIQUE (page_id, post_id)
) STRICT;
CREATE TABLE community_page_feeds (
id INTEGER PRIMARY KEY AUTOINCREMENT,
page_id TEXT NOT NULL REFERENCES community_page (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
url TEXT NOT NULL, -- 'https://ngu.substack.com/feed'
label TEXT -- shown on its items; else the feed's own title
) STRICT;
-- ── content_blocks: add 'blog_post' ───────────────────────────
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')),
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')),
text TEXT,
media TEXT,
href TEXT
) STRICT;
INSERT INTO content_blocks_new (id, owner_kind, owner_id, slot, sort_order, type, text, media, href)
SELECT id, owner_kind, owner_id, slot, sort_order, type, text, media, href
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);
-- ── featured_cards: add 'community_page' ──────────────────────
CREATE TABLE featured_cards_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
owner_kind TEXT NOT NULL CHECK (owner_kind IN ('front_page', 'community_page')),
owner_id TEXT NOT NULL,
sort_order INTEGER NOT NULL DEFAULT 0,
kind TEXT NOT NULL DEFAULT 'link'
CHECK (kind IN ('record', 'link', 'video')),
ref_kind TEXT CHECK (ref_kind IN ('event', 'organization', 'person', 'team', 'award')),
ref_id TEXT,
url TEXT,
eyebrow TEXT,
title TEXT,
blurb TEXT,
image TEXT,
CHECK ((ref_kind IS NULL) = (ref_id IS NULL)),
CONSTRAINT "A record card needs a record to point at."
CHECK (kind != 'record' OR ref_kind IS NOT NULL),
CONSTRAINT "A link or video card needs a URL."
CHECK (kind = 'record' OR url IS NOT NULL)
) STRICT;
INSERT INTO featured_cards_new
(id, owner_kind, owner_id, sort_order, kind, ref_kind, ref_id, url, eyebrow, title, blurb, image)
SELECT id, owner_kind, owner_id, sort_order, kind, ref_kind, ref_id, url, eyebrow, title, blurb, image
FROM featured_cards;
PRAGMA legacy_alter_table = ON;
DROP TABLE featured_cards;
ALTER TABLE featured_cards_new RENAME TO featured_cards;
PRAGMA legacy_alter_table = OFF;
CREATE INDEX featured_cards_owner_idx ON featured_cards (owner_kind, owner_id, sort_order);
-- ── Triggers last (see CLAUDE.md, Migrations) ──
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')
END;
END;
CREATE TRIGGER featured_cards_ref_exists
BEFORE INSERT ON featured_cards
BEGIN
SELECT CASE
WHEN new.ref_kind = 'event'
AND NOT EXISTS (SELECT 1 FROM events WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such event')
WHEN new.ref_kind = 'organization'
AND NOT EXISTS (SELECT 1 FROM organizations WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such organization')
WHEN new.ref_kind = 'person'
AND NOT EXISTS (SELECT 1 FROM people WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such person')
WHEN new.ref_kind = 'team'
AND NOT EXISTS (SELECT 1 FROM teams WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such team')
WHEN new.ref_kind = 'award'
AND NOT EXISTS (SELECT 1 FROM awards WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such award')
END;
END;
CREATE TRIGGER featured_cards_ref_exists_update
BEFORE UPDATE OF ref_kind, ref_id ON featured_cards
BEGIN
SELECT CASE
WHEN new.ref_kind = 'event'
AND NOT EXISTS (SELECT 1 FROM events WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such event')
WHEN new.ref_kind = 'organization'
AND NOT EXISTS (SELECT 1 FROM organizations WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such organization')
WHEN new.ref_kind = 'person'
AND NOT EXISTS (SELECT 1 FROM people WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such person')
WHEN new.ref_kind = 'team'
AND NOT EXISTS (SELECT 1 FROM teams WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such team')
WHEN new.ref_kind = 'award'
AND NOT EXISTS (SELECT 1 FROM awards WHERE id = new.ref_id)
THEN RAISE(ABORT, 'featured_cards: no such award')
END;
END;
CREATE TRIGGER blog_posts_cleanup
AFTER DELETE ON blog_posts
BEGIN
DELETE FROM content_blocks WHERE owner_kind = 'blog_post' AND owner_id = old.id;
END;
CREATE TRIGGER blog_posts_touch
AFTER UPDATE ON blog_posts
FOR EACH ROW WHEN new.updated_at = old.updated_at
BEGIN
UPDATE blog_posts SET updated_at = datetime('now') WHERE id = new.id;
END;
CREATE TRIGGER community_page_touch
AFTER UPDATE ON community_page
FOR EACH ROW WHEN new.updated_at = old.updated_at
BEGIN
UPDATE community_page SET updated_at = datetime('now') WHERE id = new.id;
END;

View file

@ -1,80 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 032 CONTENT BLOCKS: VIDEO, BUTTON, CALLOUT, ALT TEXT, ATTRIBUTION
--
-- Three new block types, and two columns for types that had to
-- borrow one:
--
-- video href is the link (YouTube, Vimeo, Facebook) or a
-- video file; text is the caption; media an optional
-- still. Drawn click-to-play, like a featured card.
-- button text is the label, href where it goes.
-- callout text in a tinted box, for a note or announcement.
--
-- alt an image's alt text. text stays its caption: a
-- caption describes the moment, alt describes the
-- picture to someone who can't see it.
-- cite who a quote is by.
--
-- The type list is a CHECK, so the table is rebuilt, the same way
-- 031 did (see its header): legacy_alter_table around the rename,
-- because the *_cleanup triggers on other tables name it, then the
-- index and the owner trigger again.
--
-- PRAGMA user_version; -- reads 31 before this file
-- ═══════════════════════════════════════════════════════════════
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')),
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')),
text TEXT,
media TEXT,
href TEXT,
alt TEXT,
cite TEXT
) STRICT;
INSERT INTO content_blocks_new (id, owner_kind, owner_id, slot, sort_order, type, text, media, href)
SELECT id, owner_kind, owner_id, slot, sort_order, type, text, media, href
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);
-- ── Triggers last (see CLAUDE.md, Migrations) ──
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')
END;
END;

View file

@ -1,34 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 033 HERO: A FEATURED EVENT
--
-- A fourth hero feature, 'event': an event's card beside the
-- headline, over whichever backdrop is chosen.
--
-- hero_event_id the event to feature. Null means the event the
-- countdown shows (its pin, or the next one that
-- hasn't ended, narrowed by its scope and type),
-- so the hero and the countdown can't disagree.
-- A pinned event that is over, unpublished or
-- deleted falls back the same way; ON DELETE SET
-- NULL does the last one.
--
-- hero_feature's CHECK gains 'event'. A CHECK can't be altered in
-- place, so the column is replaced the way 025 did it: a new column
-- with the new CHECK, the values copied across, the old one dropped
-- and the new one renamed into its place. Nothing else names the
-- column, so front_page itself needn't be rebuilt.
--
-- PRAGMA user_version; -- reads 32 before this file
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE front_page ADD COLUMN hero_feature_new TEXT NOT NULL DEFAULT 'none'
CHECK (hero_feature_new IN ('none', 'livestream', 'video', 'event'));
UPDATE front_page SET hero_feature_new = hero_feature;
ALTER TABLE front_page DROP COLUMN hero_feature;
ALTER TABLE front_page RENAME COLUMN hero_feature_new TO hero_feature;
ALTER TABLE front_page ADD COLUMN hero_event_id TEXT
REFERENCES events (id) ON DELETE SET NULL;

View file

@ -1,99 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 034 CONTENT BLOCKS: SCHEDULE
--
-- A 'schedule' block: the block's items are its entries, grouped
-- into one tab per day. Each entry says when, what and where, and
-- folds out for more. The block's own text is an optional intro.
--
-- content_block_items gains the entry's fields. A list or link-row
-- block leaves them empty:
--
-- day the tab it sits under, eg. 'Friday'. Tabs follow
-- the order entries are in; blank means one untitled
-- day, and a schedule of one day draws no tabs
-- time '7:00pm', '9:00 to 10:30am': shown as typed
-- location where it happens, eg. 'Main Hall'
-- person_id who hosts or speaks: a people row, drawn with its
-- photo and linked to its page. ON DELETE SET NULL,
-- and an unpublished person isn't shown
-- description the fold-out text, formatted like a paragraph
-- media a graphic in the fold-out: '/uploads/…' or a URL
-- map a place or address to show on a Google map in the
-- fold-out, eg. 'Camp Hebron, Halifax PA'
--
-- text is the entry's title, detail a line under it, url a link on
-- the title, as for list items.
--
-- The type list is a CHECK, so content_blocks is rebuilt the way
-- 031 and 032 did it (legacy_alter_table around the rename, then
-- the index and the owner trigger again). The item columns are
-- plain ADD COLUMNs.
--
-- PRAGMA user_version; -- reads 33 before this file
-- ═══════════════════════════════════════════════════════════════
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')),
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')),
text TEXT,
media TEXT,
href TEXT,
alt TEXT,
cite TEXT
) STRICT;
INSERT INTO content_blocks_new
(id, owner_kind, owner_id, slot, sort_order, type, text, media, href, alt, cite)
SELECT id, owner_kind, owner_id, slot, sort_order, type, text, media, href, alt, cite
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);
ALTER TABLE content_block_items ADD COLUMN day TEXT;
ALTER TABLE content_block_items ADD COLUMN time TEXT;
ALTER TABLE content_block_items ADD COLUMN location TEXT;
ALTER TABLE content_block_items ADD COLUMN person_id TEXT
REFERENCES people (id) ON DELETE SET NULL;
ALTER TABLE content_block_items ADD COLUMN description TEXT;
ALTER TABLE content_block_items ADD COLUMN media TEXT;
ALTER TABLE content_block_items ADD COLUMN map TEXT;
-- ── Triggers last (see CLAUDE.md, Migrations) ──
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')
END;
END;

View file

@ -1,62 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 035 SITE SETTINGS
--
-- What the site says about itself, editable in the admin (Panel →
-- Site settings, superadmins only) instead of only in site.json.
-- Every column is an override: null means "whatever site.json
-- says", so a fresh database behaves exactly as before and the
-- built index.html (made from site.json) stays a true fallback for
-- when the API is down.
--
-- site_name the site's name, in every title
-- description the default search description
-- preview_image the default link-preview image
-- favicon the browser-tab icon ('/uploads/…', PNG or SVG)
-- apple_touch_icon the home-screen icon on iPhones (PNG, 180px)
-- indexing 'on' or 'off': whether search engines may list
-- the site. Per database, so the dev server can
-- say off while production says on, from one
-- build. Null follows site.json's robots.index.
--
-- site_setting_pages overrides a static page's title and intro
-- (site.json's "pages"), one row per page that differs. The path
-- must be one of site.json's pages; the admin only offers those.
--
-- A singleton like front_page: one row, made here, which the admin
-- edits and can't delete.
--
-- PRAGMA user_version; -- reads 34 before this file
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE site_settings (
id TEXT PRIMARY KEY CHECK (id = 'site'),
site_name TEXT,
description TEXT,
preview_image TEXT,
favicon TEXT,
apple_touch_icon TEXT,
indexing TEXT CHECK (indexing IN ('on', 'off')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
) STRICT;
INSERT INTO site_settings (id) VALUES ('site');
CREATE TABLE site_setting_pages (
id INTEGER PRIMARY KEY AUTOINCREMENT,
settings_id TEXT NOT NULL REFERENCES site_settings (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
path TEXT NOT NULL, -- '/retreats'
title TEXT,
description TEXT,
UNIQUE (settings_id, path)
) STRICT;
-- ── Triggers last (see CLAUDE.md, Migrations) ──
CREATE TRIGGER site_settings_touch
AFTER UPDATE ON site_settings
FOR EACH ROW WHEN new.updated_at = old.updated_at
BEGIN
UPDATE site_settings SET updated_at = datetime('now') WHERE id = new.id;
END;

View file

@ -1,53 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 036 VIDEO CLIPS
--
-- The admin's video clip tool (Tools → Video clips): download one of
-- our videos from YouTube or Facebook, cut clips from it, and take
-- them away as MP4 or MP3. One row per job, of two kinds:
--
-- source a download (yt-dlp) of source_url. When done, file is
-- the video in CLIPS_DIR and title/duration describe it.
-- clip a cut (ffmpeg) of a source: params holds the JSON
-- { start, end, shape, focus, format }. When done, file
-- is the clip in CLIPS_DIR.
--
-- Jobs run one at a time, oldest queued first (server/src/clips.js).
-- A job left 'running' by a restart is marked failed at boot.
--
-- Files are temporary. A clip's file is deleted once it has been
-- downloaded, unless it was saved to the media library first
-- (saved_media_id), and anything older than a day is swept, sources
-- included. Deleting a source deletes its clips.
--
-- PRAGMA user_version; -- reads 35 before this file
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE clip_jobs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
kind TEXT NOT NULL CHECK (kind IN ('source', 'clip')),
status TEXT NOT NULL DEFAULT 'queued'
CHECK (status IN ('queued', 'running', 'done', 'failed')),
progress REAL NOT NULL DEFAULT 0 CHECK (progress BETWEEN 0 AND 1),
source_url TEXT, -- kind 'source'
source_id INTEGER REFERENCES clip_jobs (id) ON DELETE CASCADE, -- kind 'clip'
params TEXT, -- kind 'clip': JSON
title TEXT,
duration REAL, -- seconds
file TEXT, -- a name in CLIPS_DIR, once done
bytes INTEGER,
error TEXT,
saved_media_id INTEGER REFERENCES media (id) ON DELETE SET NULL,
downloaded_at TEXT, -- a clip's file went out, and was deleted
created_by INTEGER REFERENCES admin_users (id) ON DELETE SET NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
finished_at TEXT,
CHECK ((kind = 'source') = (source_url IS NOT NULL)),
CHECK ((kind = 'clip') = (source_id IS NOT NULL))
) STRICT;
CREATE INDEX clip_jobs_queue_idx ON clip_jobs (status, id);
CREATE INDEX clip_jobs_source_idx ON clip_jobs (source_id);

View file

@ -1,39 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 037 LEADERSHIP VIEW: PUBLISHED HOME ORGS ONLY
--
-- v_org_leadership named a person's primary organization even when
-- that organization was unpublished, so a draft org's name could
-- show on a public leadership list. It now joins published ones
-- only; an unpublished one reads as no primary org.
-- ═══════════════════════════════════════════════════════════════
DROP VIEW v_org_leadership;
CREATE VIEW v_org_leadership AS
SELECT
a.org_id,
a.team_id,
t.name AS team_name,
t.sort_order AS team_sort_order,
a.person_id,
a.title,
a.role,
a.is_owner,
a.sort_order,
p.display_name,
p.sort_name,
p.pronouns,
p.tagline,
p.photo,
p.public_email,
p.location_label,
p.bio,
o.id AS primary_org_id,
o.name AS primary_org_name
FROM affiliations a
JOIN people p ON p.id = a.person_id AND p.is_published = 1
LEFT JOIN teams t ON t.id = a.team_id
LEFT JOIN organizations o ON o.id = p.primary_org_id AND o.is_published = 1
WHERE a.is_public = 1
AND a.ended_on IS NULL
ORDER BY a.org_id, a.is_owner DESC, a.sort_order, p.sort_name;

View file

@ -1,13 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 038 ALT TEXT FOR BLOG COVERS AND SCHEDULE GRAPHICS
--
-- Both images can carry information (a flyer, a site map, a cover
-- photo that sets the scene), so each gets its own description for
-- screen readers. Blank means decorative: the image is skipped.
--
-- blog_posts.cover_alt the cover image's description
-- content_block_items.media_alt a schedule entry graphic's
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE blog_posts ADD COLUMN cover_alt TEXT;
ALTER TABLE content_block_items ADD COLUMN media_alt TEXT;

View file

@ -1,11 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 039 PRIVACY CONTACT
--
-- The address the Privacy page gives for privacy questions and data
-- requests (Panel → Site settings). Null falls back to site.json's
-- privacyEmail; blank in both, the page points to its request form
-- only. Data requests themselves are feedback rows of type
-- 'privacy' (routes/feedback.js), triaged in Admin → Feedback.
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE site_settings ADD COLUMN privacy_email TEXT;

View file

@ -1,12 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 040 NO MORE CARD GRADIENTS
--
-- An event card is its photo (card_image) under a light veil, or a
-- plain card, always with the event's colour as its border. The
-- gradient layer went over the photo and hid it, and gradients are
-- leaving the design, so the column goes. Any gradient saved on an
-- event is dropped with it; the card falls back to its photo or the
-- plain surface.
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE events DROP COLUMN gradient;

View file

@ -1,28 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 041 SITE COLOURS
--
-- The admin's palette (Panel → Site settings → Colours): one row per
-- colour token that differs from the site's own (src/index.css), with
-- a light and a dark value. Blank keeps that mode's default. The
-- server writes them into every page (server/src/theme.js) and
-- refuses a save that would make text hard to read.
--
-- token one of the tokens in THEME_DEFAULTS (theme.js), which
-- the admin's dropdown offers
-- light '#rrggbb', or null for the default
-- dark '#rrggbb', or null for the default
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE site_setting_colors (
id INTEGER PRIMARY KEY AUTOINCREMENT,
settings_id TEXT NOT NULL REFERENCES site_settings (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
token TEXT NOT NULL CHECK (token IN (
'ink', 'body', 'muted', 'link', 'brand', 'action', 'action-hover',
'surface', 'tint', 'tint-soft', 'danger', 'danger-tint')),
light TEXT CONSTRAINT "A colour must be written #rrggbb, eg. #0f7183."
CHECK (light IS NULL OR (length(light) = 7 AND light GLOB '#[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]')),
dark TEXT CONSTRAINT "A dark colour must be written #rrggbb, eg. #5ccbdc."
CHECK (dark IS NULL OR (length(dark) = 7 AND dark GLOB '#[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]')),
UNIQUE (settings_id, token)
) STRICT;

View file

@ -1,10 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 042 AWARD RECIPIENTS BY AWARD
--
-- person_awards is read by award (an award's page lists its
-- recipients, an organization counts them), but its only index
-- starts with person_id, so those reads scan the table. Tiny today;
-- this keeps it from mattering later.
-- ═══════════════════════════════════════════════════════════════
CREATE INDEX person_awards_award_idx ON person_awards (award_id);

View file

@ -1,10 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 043 A POST'S TABLE OF CONTENTS
--
-- Blog posts → "Show contents": list the post's headings beside it
-- (a fold-out on phones), the one being read lit. Off unless an
-- editor turns it on, since a short post doesn't need one.
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE blog_posts ADD COLUMN show_contents INTEGER NOT NULL DEFAULT 0
CHECK (show_contents IN (0, 1));

View file

@ -1,72 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 044 TABLE BLOCKS
--
-- A content block of type 'table': a grid of text, for comparison
-- charts and the like (a blog post imported from Word, say). The
-- grid is the block's text, one row per line, cells split by "|",
-- the first row the header; cells take the same inline formatting as
-- a paragraph (**bold**, *italic*, [link](url)). ContentBlocks.tsx
-- draws it.
--
-- Only the type's CHECK changes, and SQLite can't alter a CHECK, so
-- the table is rebuilt the way 031, 032 and 034 did it
-- (legacy_alter_table around the rename, then its index and owner
-- trigger again).
-- ═══════════════════════════════════════════════════════════════
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')),
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')),
text TEXT,
media TEXT,
href TEXT,
alt TEXT,
cite TEXT
) STRICT;
INSERT INTO content_blocks_new
(id, owner_kind, owner_id, slot, sort_order, type, text, media, href, alt, cite)
SELECT id, owner_kind, owner_id, slot, sort_order, type, text, media, href, alt, cite
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);
-- ── Triggers last (see CLAUDE.md, Migrations) ──
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')
END;
END;

View file

@ -1,70 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 045 LINK CARD BLOCKS
--
-- A content block of type 'cards': link cards, one per item, like a
-- link shared in a chat. The item's text is the title, detail the
-- description, url the link and media the picture (the item columns
-- there already are); Fetch preview in the admin fills them.
-- ContentBlocks.tsx draws it.
--
-- Only the type's CHECK changes, so the table is rebuilt as 044 did
-- (legacy_alter_table around the rename, then its index and owner
-- trigger again).
-- ═══════════════════════════════════════════════════════════════
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')),
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')),
text TEXT,
media TEXT,
href TEXT,
alt TEXT,
cite TEXT
) STRICT;
INSERT INTO content_blocks_new
(id, owner_kind, owner_id, slot, sort_order, type, text, media, href, alt, cite)
SELECT id, owner_kind, owner_id, slot, sort_order, type, text, media, href, alt, cite
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);
-- ── Triggers last (see CLAUDE.md, Migrations) ──
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')
END;
END;

View file

@ -1,39 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 046 CONTENT REQUESTS
--
-- The Request form (/request): someone asks for a blog post, an
-- event, or a new or updated chapter, region, partner, team, award
-- or person, and can attach files (a .docx to fill in, photos).
-- Requests are feedback rows of type 'content', so they share the
-- admin's triage (Forms → Content requests): status, notes, delete.
--
-- category what it's about (REQUEST_TYPES in
-- src/data/requestTypes.ts)
-- request_action 'new' or 'update'
-- subject the title or name, or which record to update
--
-- The files themselves live in Google Drive (googleService.js);
-- feedback_files keeps Drive's id for each, and goes with its row.
--
-- site_settings.notify_emails: who gets an email for each new
-- content or data request (Panel → Site settings), comma separated.
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE feedback ADD COLUMN category TEXT
CHECK (category IN ('blog', 'event', 'chapter', 'region', 'partner', 'team', 'award', 'person'));
ALTER TABLE feedback ADD COLUMN request_action TEXT
CHECK (request_action IN ('new', 'update'));
ALTER TABLE feedback ADD COLUMN subject TEXT;
CREATE TABLE feedback_files (
id INTEGER PRIMARY KEY AUTOINCREMENT,
feedback_id INTEGER NOT NULL REFERENCES feedback (id) ON DELETE CASCADE,
drive_id TEXT NOT NULL,
name TEXT NOT NULL,
mime TEXT NOT NULL,
size INTEGER NOT NULL
) STRICT;
CREATE INDEX feedback_files_owner_idx ON feedback_files (feedback_id);
ALTER TABLE site_settings ADD COLUMN notify_emails TEXT;

View file

@ -1,29 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 047 ACCESS BY GOOGLE GROUP
--
-- Admin access from Google Workspace groups (accessGroups.js).
-- Panel → Site settings → Access names a group for each of viewer,
-- editor and admin. Someone in one of them who signs in with Google
-- gets an account with the highest of those roles, and keeps it only
-- while they're in the group. Superadmins and admin-cli accounts are
-- never touched.
--
-- admin_users.access_source 'manual' (admin-cli, the Panel) or
-- 'group' (made by a group sign-in;
-- Google only, role follows the group)
-- admin_users.group_disabled 1 when a group check turned it off
-- (back in a group turns it on again);
-- a superadmin's Disable sets 0, and
-- that one sticks
-- admin_users.groups_checked_at the last group check, UTC
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE admin_users ADD COLUMN access_source TEXT NOT NULL DEFAULT 'manual'
CHECK (access_source IN ('manual', 'group'));
ALTER TABLE admin_users ADD COLUMN group_disabled INTEGER NOT NULL DEFAULT 0
CHECK (group_disabled IN (0, 1));
ALTER TABLE admin_users ADD COLUMN groups_checked_at TEXT;
ALTER TABLE site_settings ADD COLUMN access_group_viewer TEXT;
ALTER TABLE site_settings ADD COLUMN access_group_editor TEXT;
ALTER TABLE site_settings ADD COLUMN access_group_admin TEXT;

View file

@ -1,28 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 048 FILES IN GOOGLE DRIVE
--
-- Files for the public site to link to (a handout, slides, a talk's
-- audio, a brand kit), uploaded from Tools → Media → Files into the
-- shared drive's "Blog" folder (routes/files.js) and shared as
-- "anyone with the link can view". Content blocks link to `url`,
-- Drive's page for the file.
--
-- preview /uploads/... of Drive's picture of the first page, in
-- the media library, once Drive has drawn one (PDFs and
-- Office files); a link card to the file takes it as its
-- picture
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE drive_files (
id INTEGER PRIMARY KEY AUTOINCREMENT,
drive_id TEXT NOT NULL UNIQUE,
name TEXT NOT NULL,
mime TEXT NOT NULL,
bytes INTEGER NOT NULL CHECK (bytes >= 0),
url TEXT NOT NULL,
preview TEXT,
uploaded_by INTEGER REFERENCES admin_users (id) ON DELETE SET NULL,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
) STRICT;
CREATE INDEX drive_files_created_idx ON drive_files (created_at DESC);

View file

@ -1,12 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 049 REQUEST DETAILS
--
-- The Request form's details for the record it's about (a chapter's
-- city, website and meeting time, an event's dates...), as one JSON
-- object of strings: { "city": "Kansas City", "meets": "..." }. Which
-- keys there are is src/data/requestTypes.ts's business; the server
-- only checks the shape (routes/requests.js). Forms → Content
-- requests shows them and opens the record's editor filled in.
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE feedback ADD COLUMN details TEXT CHECK (details IS NULL OR json_valid(details));

View file

@ -1,10 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 050 FOLDERS FOR DRIVE FILES
--
-- The folder a file is in, under the shared drive's Media folder:
-- '' for Media itself, 'Slides' or 'Slides/2026' below it. Made,
-- renamed and deleted from Tools → Media → Files (routes/files.js);
-- a file moved in Drive by hand is followed on the next look.
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE drive_files ADD COLUMN folder TEXT NOT NULL DEFAULT '';

View file

@ -1,10 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 051 CLIPS SAVED TO DRIVE
--
-- Tools → Video clips → Save to Drive puts a finished clip in a folder
-- under the shared drive's Media folder, as a Files entry
-- (drive_files, 048). The job keeps which one, as it keeps its media
-- library copy in saved_media_id; a clip can be in both.
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE clip_jobs ADD COLUMN saved_drive_file_id INTEGER REFERENCES drive_files (id) ON DELETE SET NULL;

View file

@ -1,219 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 052 CHAPTERS BECOME GROUPS
--
-- Local chapters are called groups now, everywhere: the kind value,
-- the side table, the front page count, the Request form's type, the
-- pages (/groups/<id>, the Community page's #groups section).
--
-- organizations.kind 'chapter' → 'group' (CHECK changes, so
-- the table is rebuilt as 045 did, then
-- its indexes and triggers again)
-- chapters renamed groups, its index with it
-- front_page_stats.source 'chapters' → 'groups' (rebuilt), and
-- the seeded "Chapters" label
-- feedback.category 'chapter' → 'group' (a column CHECK
-- only, so a new column replaces it)
-- links in records the site's own /chapters/ and
-- #chapters links, in link columns and
-- [text](url) formatting
--
-- Names and prose written in the admin (an organization called
-- "Lynnwood Chapter", a post's paragraph) are left as written.
-- ═══════════════════════════════════════════════════════════════
-- ── organizations.kind ─────────────────────────────────────────
CREATE TABLE organizations_new (
id TEXT PRIMARY KEY, -- slug: 'northwest', 'lynnwood'
kind TEXT NOT NULL
CHECK (kind IN ('national', 'region', 'group', 'partner')),
name TEXT NOT NULL,
short_name TEXT,
tagline TEXT, -- one line, for the card
color TEXT,
logo TEXT, -- an upload's filename
venue TEXT,
address TEXT,
locality TEXT,
state_code TEXT, -- US only
country TEXT NOT NULL DEFAULT 'US',
location_label TEXT,
latitude REAL,
longitude REAL,
is_online INTEGER NOT NULL DEFAULT 0 CHECK (is_online IN (0, 1)),
is_published INTEGER NOT NULL DEFAULT 1 CHECK (is_published IN (0, 1)),
sort_order INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
in_timeline INTEGER NOT NULL DEFAULT 0 CHECK (in_timeline IN (0, 1)),
is_listed INTEGER NOT NULL DEFAULT 1 CHECK (is_listed IN (0, 1))
) STRICT;
INSERT INTO organizations_new
(id, kind, name, short_name, tagline, color, logo,
venue, address, locality, state_code, country, location_label,
latitude, longitude, is_online,
is_published, sort_order, created_at, updated_at, in_timeline, is_listed)
SELECT id, CASE kind WHEN 'chapter' THEN 'group' ELSE kind END,
name, short_name, tagline, color, logo,
venue, address, locality, state_code, country, location_label,
latitude, longitude, is_online,
is_published, sort_order, created_at, updated_at, in_timeline, is_listed
FROM organizations;
PRAGMA legacy_alter_table = ON;
DROP TABLE organizations;
ALTER TABLE organizations_new RENAME TO organizations;
PRAGMA legacy_alter_table = OFF;
CREATE INDEX organizations_kind_idx ON organizations (kind, is_published, sort_order);
CREATE INDEX organizations_state_idx ON organizations (state_code);
-- ── chapters → groups ──────────────────────────────────────────
ALTER TABLE chapters RENAME TO groups;
DROP INDEX chapters_region_idx;
CREATE INDEX groups_region_idx ON groups (region_id);
-- ── front_page_stats.source ────────────────────────────────────
CREATE TABLE front_page_stats_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
page_id TEXT NOT NULL REFERENCES front_page (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
label TEXT NOT NULL,
source TEXT NOT NULL DEFAULT 'manual'
CHECK (source IN ('manual', 'years_since', 'regions', 'groups',
'partners', 'events_held', 'retreats_held',
'people', 'awards_given')),
value TEXT,
suffix TEXT, -- '+', 'k', ' states'
note TEXT
) STRICT;
INSERT INTO front_page_stats_new
(id, page_id, sort_order, label, source, value, suffix, note)
SELECT id, page_id, sort_order,
CASE label WHEN 'Chapters' THEN 'Groups' ELSE label END,
CASE source WHEN 'chapters' THEN 'groups' ELSE source END,
value, suffix, note
FROM front_page_stats;
PRAGMA legacy_alter_table = ON;
DROP TABLE front_page_stats;
ALTER TABLE front_page_stats_new RENAME TO front_page_stats;
PRAGMA legacy_alter_table = OFF;
-- ── feedback.category ──────────────────────────────────────────
ALTER TABLE feedback ADD COLUMN category_new TEXT
CHECK (category_new IN ('blog', 'event', 'group', 'region', 'partner', 'team', 'award', 'person'));
UPDATE feedback SET category_new = CASE category WHEN 'chapter' THEN 'group' ELSE category END;
ALTER TABLE feedback DROP COLUMN category;
ALTER TABLE feedback RENAME COLUMN category_new TO category;
UPDATE feedback SET section_id = 'groups' WHERE section_id = 'chapters';
UPDATE feedback SET page_path = '/groups/' || substr(page_path, 11)
WHERE page_path LIKE '/chapters/%';
-- ── Seeded text ────────────────────────────────────────────────
UPDATE front_page_path_actions SET description = 'Groups and regions across the country.'
WHERE description = 'Chapters and regions across the country.';
UPDATE affiliations SET title = replace(replace(title, 'Chapter', 'Group'), 'chapter', 'group')
WHERE title LIKE '%chapter%';
-- ── The site's own links ───────────────────────────────────────
-- A link to one of our group pages or the Community page's section:
-- '/chapters/<id>', '/community#chapters', or either on our domain.
-- Someone else's site with a /chapters/ path is left alone.
UPDATE links SET url = replace(replace(url, '/chapters/', '/groups/'), '#chapters', '#groups')
WHERE url LIKE '/chapters/%' OR url LIKE '%nextgenerationofunity.org/chapters/%'
OR url LIKE '%/community#chapters' OR url = '#chapters';
UPDATE content_block_items SET url = replace(replace(url, '/chapters/', '/groups/'), '#chapters', '#groups')
WHERE url LIKE '/chapters/%' OR url LIKE '%nextgenerationofunity.org/chapters/%'
OR url LIKE '%/community#chapters' OR url = '#chapters';
UPDATE content_blocks SET href = replace(replace(href, '/chapters/', '/groups/'), '#chapters', '#groups')
WHERE href LIKE '/chapters/%' OR href LIKE '%nextgenerationofunity.org/chapters/%'
OR href LIKE '%/community#chapters' OR href = '#chapters';
UPDATE featured_cards SET url = replace(replace(url, '/chapters/', '/groups/'), '#chapters', '#groups')
WHERE url LIKE '/chapters/%' OR url LIKE '%nextgenerationofunity.org/chapters/%'
OR url LIKE '%/community#chapters' OR url = '#chapters';
UPDATE timeline_entries SET link_url = replace(replace(link_url, '/chapters/', '/groups/'), '#chapters', '#groups')
WHERE link_url LIKE '/chapters/%' OR link_url LIKE '%nextgenerationofunity.org/chapters/%'
OR link_url LIKE '%/community#chapters' OR link_url = '#chapters';
UPDATE front_page_slides SET link_url = replace(replace(link_url, '/chapters/', '/groups/'), '#chapters', '#groups')
WHERE link_url LIKE '/chapters/%' OR link_url LIKE '%nextgenerationofunity.org/chapters/%'
OR link_url LIKE '%/community#chapters' OR link_url = '#chapters';
UPDATE front_page_path_actions SET url = replace(replace(url, '/chapters/', '/groups/'), '#chapters', '#groups')
WHERE url LIKE '/chapters/%' OR url LIKE '%nextgenerationofunity.org/chapters/%'
OR url LIKE '%/community#chapters' OR url = '#chapters';
UPDATE front_page SET primary_url = replace(replace(primary_url, '/chapters/', '/groups/'), '#chapters', '#groups')
WHERE primary_url LIKE '/chapters/%' OR primary_url LIKE '%nextgenerationofunity.org/chapters/%'
OR primary_url LIKE '%/community#chapters' OR primary_url = '#chapters';
UPDATE front_page SET secondary_url = replace(replace(secondary_url, '/chapters/', '/groups/'), '#chapters', '#groups')
WHERE secondary_url LIKE '/chapters/%' OR secondary_url LIKE '%nextgenerationofunity.org/chapters/%'
OR secondary_url LIKE '%/community#chapters' OR secondary_url = '#chapters';
-- [text](url) formatting in block and item text.
UPDATE content_blocks
SET text = replace(replace(replace(text, '](/chapters/', '](/groups/'),
'](/community#chapters)', '](/community#groups)'),
'nextgenerationofunity.org/chapters/', 'nextgenerationofunity.org/groups/')
WHERE text LIKE '%](/chapters/%' OR text LIKE '%](/community#chapters)%'
OR text LIKE '%nextgenerationofunity.org/chapters/%';
UPDATE content_block_items
SET text = replace(replace(replace(text, '](/chapters/', '](/groups/'),
'](/community#chapters)', '](/community#groups)'),
'nextgenerationofunity.org/chapters/', 'nextgenerationofunity.org/groups/')
WHERE text LIKE '%](/chapters/%' OR text LIKE '%](/community#chapters)%'
OR text LIKE '%nextgenerationofunity.org/chapters/%';
-- ── Triggers last (see CLAUDE.md, Migrations) ──
-- Dropping organizations took its own triggers with it.
CREATE TRIGGER organizations_cleanup
AFTER DELETE ON organizations
BEGIN
DELETE FROM content_blocks WHERE owner_kind = 'organization' AND owner_id = old.id;
DELETE FROM links WHERE owner_kind = 'organization' AND owner_id = old.id;
END;
CREATE TRIGGER timeline_organizations_cleanup
AFTER DELETE ON organizations
BEGIN
DELETE FROM timeline_entries WHERE ref_kind = 'organization' AND ref_id = old.id;
END;
CREATE TRIGGER organizations_featured_cleanup
AFTER DELETE ON organizations
BEGIN
DELETE FROM featured_cards WHERE ref_kind = 'organization' AND ref_id = old.id;
END;
CREATE TRIGGER organizations_touch
AFTER UPDATE ON organizations
FOR EACH ROW WHEN new.updated_at = old.updated_at
BEGIN
UPDATE organizations SET updated_at = datetime('now') WHERE id = new.id;
END;

View file

@ -1,34 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 053 US SPELLING IN MESSAGES
--
-- The site is written in US English now. Two of 041's CHECKs are
-- named with the sentence the admin shows when a save breaks them
-- (admin-crud.js), and those said "colour"; the table is rebuilt to
-- rename them, the same columns and rows as before.
--
-- events.status keeps the value 'cancelled': it's stored data, and
-- the admin and the pages show it as "canceled".
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE site_setting_colors_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
settings_id TEXT NOT NULL REFERENCES site_settings (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
token TEXT NOT NULL CHECK (token IN (
'ink', 'body', 'muted', 'link', 'brand', 'action', 'action-hover',
'surface', 'tint', 'tint-soft', 'danger', 'danger-tint')),
light TEXT CONSTRAINT "A color must be written #rrggbb, eg. #0f7183."
CHECK (light IS NULL OR (length(light) = 7 AND light GLOB '#[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]')),
dark TEXT CONSTRAINT "A dark color must be written #rrggbb, eg. #5ccbdc."
CHECK (dark IS NULL OR (length(dark) = 7 AND dark GLOB '#[0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F][0-9a-fA-F]')),
UNIQUE (settings_id, token)
) STRICT;
INSERT INTO site_setting_colors_new (id, settings_id, sort_order, token, light, dark)
SELECT id, settings_id, sort_order, token, light, dark
FROM site_setting_colors;
PRAGMA legacy_alter_table = ON;
DROP TABLE site_setting_colors;
ALTER TABLE site_setting_colors_new RENAME TO site_setting_colors;
PRAGMA legacy_alter_table = OFF;

View file

@ -1,140 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 054 PEOPLE BLOCKS, HOST TEAMS, THE ORGANIZATION PAGE
--
-- A content block of type 'people': a team's people tiles, people
-- picked one by one (items, each with a title), or both. The team
-- is a new column, content_blocks.team_id; a picked person rides on
-- the item's person_id, as a schedule entry's does. ContentBlocks.tsx
-- draws it with PeopleTiles. The type CHECK changes, so the table is
-- rebuilt as 045 did (legacy_alter_table around the rename, then its
-- index and owner trigger again).
--
-- An event's organization host can name a team to show instead:
-- event_hosts.team_id, any organization's team. The event page then
-- reads "Hosted by <team>" linked to the team's page. v_event_hosts
-- carries it (and v_events, which reads v_event_hosts, is made again
-- around it, unchanged).
--
-- The Leadership page is now the Organization page, at /organization:
-- a page title or intro saved for /leadership in Site settings moves
-- with it.
-- ═══════════════════════════════════════════════════════════════
-- ── Host teams ─────────────────────────────────────────────────
ALTER TABLE event_hosts ADD COLUMN team_id TEXT REFERENCES teams (id) ON DELETE SET NULL;
DROP VIEW v_events;
DROP VIEW v_event_hosts;
CREATE VIEW v_event_hosts AS
SELECT
eh.id,
eh.event_id,
eh.sort_order,
CASE WHEN eh.person_id IS NULL THEN 'organization' ELSE 'person' END
AS host_kind,
COALESCE(eh.org_id, eh.person_id) AS host_id,
COALESCE(o.name, p.display_name) AS host_name,
o.kind AS host_org_kind,
o.logo AS host_logo,
o.color AS host_color,
p.photo AS host_photo,
COALESCE(o.is_published, p.is_published) AS host_is_published,
t.id AS host_team_id,
t.name AS host_team_name
FROM event_hosts eh
LEFT JOIN organizations o ON o.id = eh.org_id
LEFT JOIN people p ON p.id = eh.person_id
LEFT JOIN teams t ON t.id = eh.team_id AND eh.org_id IS NOT NULL AND t.is_published = 1;
CREATE VIEW v_events AS
SELECT
e.*,
h.host_kind,
h.host_id,
h.host_name,
h.host_org_kind,
COALESCE(e.org_logo, h.host_logo) AS effective_org_logo,
COALESCE(e.color, h.host_color) AS effective_color,
COALESCE(
e.status,
CASE WHEN e.ends_on IS NOT NULL AND e.ends_on < date('now')
THEN 'past' ELSE 'upcoming' END
) AS effective_status
FROM events e
LEFT JOIN v_event_hosts h
ON h.id = (
SELECT x.id
FROM v_event_hosts x
WHERE x.event_id = e.id
ORDER BY x.sort_order, x.id
LIMIT 1
);
-- ── People blocks ──────────────────────────────────────────────
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')),
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)
SELECT id, owner_kind, owner_id, slot, sort_order, type, text, media, href, alt, cite
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);
-- ── The Organization page ──────────────────────────────────────
UPDATE site_setting_pages SET path = '/organization' WHERE path = '/leadership';
-- ── Triggers last (see CLAUDE.md, Migrations) ──
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')
END;
END;

View file

@ -1,134 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 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

@ -1,221 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 056 PAGE EDITORS: SECTIONS FOR THE SITE'S OWN PAGES
--
-- Community, Retreats, Resources, Organization and History are
-- built in the admin (Pages → each page) as a list of sections. A
-- section is its title (30 characters at most: it's listed in the
-- page's side nav), an optional blurb, an accent and the anchor it
-- sits at, and then either
--
-- its own content blocks content_blocks owned 'page_section',
-- owner_id the section's id
-- a preset a prebuilt part of the site, drawn by
-- the page (SitePage.tsx): the Community
-- blog, the group map, the region list,
-- the partner cards, an event list (scope,
-- type and the view it opens in), the
-- timeline, NGU's address and tax details
--
-- Every page's sections are seeded as the code drew them, so nothing
-- moves on the site. Organization takes what 055's editor held: its
-- Mission and Leadership blocks, with the Volunteering title, blurb
-- and links appended to the Leadership section as a heading, a
-- paragraph and link buttons; 055's tables go.
--
-- The Community blog's own settings (its slots, pinned posts, feeds)
-- stay in community_page, now edited inside the Community page
-- editor; its heading and blurb become the blog section's own, so
-- community_page loses blog_title and blog_blurb.
--
-- content_blocks is rebuilt for its owner_kind CHECK (as 055 did),
-- moving 055's blocks across on the way. A section deleted (every
-- save rewrites them) takes its blocks with it, by trigger, since
-- the owner is polymorphic and can't be a foreign key.
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE site_pages (
id TEXT PRIMARY KEY
CHECK (id IN ('community', 'retreats', 'resources', 'organization', 'history')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
) STRICT;
INSERT INTO site_pages (id) VALUES ('community'), ('retreats'), ('resources'), ('organization'), ('history');
CREATE TABLE page_sections (
id INTEGER PRIMARY KEY AUTOINCREMENT,
page_id TEXT NOT NULL REFERENCES site_pages (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
anchor TEXT NOT NULL
CONSTRAINT "A section's URL ID can use only lowercase letters, numbers and hyphens, eg. leadership."
CHECK (anchor <> '' AND anchor NOT GLOB '*[^a-z0-9-]*'),
title TEXT NOT NULL
CONSTRAINT "A section title can be 30 characters at most (it's listed in the page's side nav)."
CHECK (length(title) <= 30),
blurb TEXT,
accent TEXT CHECK (accent IN ('teal', 'deep', 'green', 'amber')),
preset TEXT CHECK (preset IN ('community_blog', 'group_map', 'region_list', 'partner_list',
'events', 'timeline', 'organization_details')),
-- An events preset's filter and first view.
scope_id TEXT REFERENCES event_scopes (id) ON DELETE SET NULL,
event_type TEXT CHECK (event_type IN ('retreat', 'class', 'workshop', 'meeting', 'other')),
view TEXT CHECK (view IN ('carousel', 'grid', 'map')),
UNIQUE (page_id, anchor)
) STRICT;
CREATE INDEX page_sections_page_idx ON page_sections (page_id, sort_order);
INSERT INTO page_sections (page_id, sort_order, anchor, title, blurb, accent, preset, scope_id, event_type, view)
SELECT 'community', 0, 'blog', COALESCE(blog_title, 'Community Blog'), blog_blurb, 'teal', 'community_blog', NULL, NULL, NULL
FROM community_page WHERE id = 'community';
INSERT INTO page_sections (page_id, sort_order, anchor, title, blurb, accent, preset, scope_id, event_type, view) VALUES
('community', 1, 'groups', 'Local Groups',
'Young adult groups meeting in person and online across the movement.', 'teal', 'group_map', NULL, NULL, 'map'),
('community', 2, 'regions', 'Unity Regions',
'The regional organizations that support groups and host their own gatherings.', 'deep', 'region_list', NULL, NULL, NULL),
('community', 3, 'partners', 'Partner Organizations',
'Organizations we collaborate with across the Unity movement and beyond.', 'amber', 'partner_list', NULL, NULL, NULL),
('retreats', 0, 'national', 'National Retreats',
'Our flagship gatherings, open to young adults across the country.', 'teal', 'events', 'national', 'retreat', 'carousel'),
('retreats', 1, 'regional', 'Regional Retreats',
'Smaller gatherings hosted by regions throughout the year.', 'green', 'events', 'regional', 'retreat', 'grid'),
('retreats', 2, 'partner', 'Partner Events',
'Retreats hosted by organizations we collaborate with.', 'amber', 'events', 'partner', 'retreat', 'grid'),
('resources', 0, 'unity', 'Unity Teachings',
'Core principles, readings, and study material from the Unity movement.', 'teal', NULL, NULL, NULL, NULL),
('resources', 1, 'branding', 'Branding & Marketing',
'Logos, colors, templates, and guidelines for representing NGU.', 'green', NULL, NULL, NULL, NULL),
('resources', 2, 'partner', 'Partner Resources',
'Material for the organizations we collaborate with.', 'amber', NULL, NULL, NULL, NULL),
('history', 0, 'timeline', 'NGU Timeline', 'Open a year to see what happened.', 'teal', 'timeline', NULL, NULL, NULL),
('organization', 2, 'contact', 'Details & Contact', NULL, 'deep', 'organization_details', NULL, NULL, NULL);
INSERT INTO page_sections (page_id, sort_order, anchor, title, blurb, accent)
SELECT 'organization', 0, 'mission', substr(COALESCE(mission_title, 'Mission, Vision & Values'), 1, 30), NULL, 'teal'
FROM organization_page WHERE id = 'organization';
INSERT INTO page_sections (page_id, sort_order, anchor, title, blurb, accent)
SELECT 'organization', 1, 'leadership', substr(COALESCE(leadership_title, 'Leadership'), 1, 30), leadership_blurb, 'green'
FROM organization_page WHERE id = 'organization';
ALTER TABLE community_page DROP COLUMN blog_title;
ALTER TABLE community_page DROP COLUMN blog_blurb;
-- ── Blocks: the new owner kind, 055's blocks moved across ──────
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', 'page_section')),
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 b.id,
CASE WHEN b.owner_kind IN ('org_page_mission', 'org_page_leadership') THEN 'page_section' ELSE b.owner_kind END,
CASE b.owner_kind
WHEN 'org_page_mission' THEN
(SELECT CAST(s.id AS TEXT) FROM page_sections s WHERE s.page_id = 'organization' AND s.anchor = 'mission')
WHEN 'org_page_leadership' THEN
(SELECT CAST(s.id AS TEXT) FROM page_sections s WHERE s.page_id = 'organization' AND s.anchor = 'leadership')
ELSE b.owner_id
END,
b.slot, b.sort_order, b.type, b.text, b.media, b.href, b.alt, b.cite, b.team_id
FROM content_blocks b;
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);
-- Volunteering, appended to the Leadership section where 055 had it.
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text)
SELECT 'page_section', CAST(s.id AS TEXT), 'body', 1000, 'heading', COALESCE(p.volunteer_title, 'Volunteering')
FROM organization_page p
JOIN page_sections s ON s.page_id = 'organization' AND s.anchor = 'leadership'
WHERE p.volunteer_title IS NOT NULL OR p.volunteer_blurb IS NOT NULL
OR EXISTS (SELECT 1 FROM organization_page_links);
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text)
SELECT 'page_section', CAST(s.id AS TEXT), 'body', 1001, 'paragraph', p.volunteer_blurb
FROM organization_page p
JOIN page_sections s ON s.page_id = 'organization' AND s.anchor = 'leadership'
WHERE p.volunteer_blurb IS NOT NULL;
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type)
SELECT 'page_section', CAST(s.id AS TEXT), 'body', 1002, 'links'
FROM page_sections s
WHERE s.page_id = 'organization' AND s.anchor = 'leadership'
AND EXISTS (SELECT 1 FROM organization_page_links);
INSERT INTO content_block_items (block_id, sort_order, text, url)
SELECT b.id, l.sort_order, l.label, l.url
FROM organization_page_links l
JOIN content_blocks b ON b.owner_kind = 'page_section' AND b.type = 'links' AND b.sort_order = 1002;
DROP TABLE organization_page_links;
DROP TABLE organization_page;
-- ── Triggers last (see CLAUDE.md, Migrations) ──
CREATE TRIGGER site_pages_touch
AFTER UPDATE ON site_pages
FOR EACH ROW WHEN new.updated_at = old.updated_at
BEGIN
UPDATE site_pages SET updated_at = datetime('now') WHERE id = new.id;
END;
CREATE TRIGGER page_sections_cleanup
AFTER DELETE ON page_sections
BEGIN
DELETE FROM content_blocks WHERE owner_kind = 'page_section' AND owner_id = CAST(old.id AS TEXT);
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 = 'page_section'
AND NOT EXISTS (SELECT 1 FROM page_sections WHERE CAST(id AS TEXT) = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such page section')
END;
END;

View file

@ -1,111 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 057 NEWSLETTER DRAFTS
--
-- Tools → Newsletter saves what it builds as a draft, to come back
-- to, copy into Mailchimp again, or post as a blog post:
--
-- title, intro the email's heading and opening lines
-- footer the closing lines (blank: the site's name and
-- address); no unsubscribe link, since Mailchimp
-- adds its own
-- picks what's ticked, as JSON: event ids, blog post
-- ids, and the front page cards by their link
-- ({"events": [...], "posts": [...], "cards": [...]})
-- blocks content_blocks owned 'newsletter': whatever is
-- written for this issue, under the intro
--
-- content_blocks is rebuilt for its owner_kind CHECK (as 056 did). A
-- draft deleted takes its blocks with it, by trigger.
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE newsletters (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT,
intro TEXT,
footer TEXT,
picks TEXT NOT NULL DEFAULT '{}' CHECK (json_valid(picks)),
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
) STRICT;
-- ── Blocks: the new owner kind ─────────────────────────────────
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', 'page_section',
'newsletter')),
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);
-- ── Triggers last (see CLAUDE.md, Migrations) ──
CREATE TRIGGER newsletters_touch
AFTER UPDATE ON newsletters
FOR EACH ROW WHEN new.updated_at = old.updated_at
BEGIN
UPDATE newsletters SET updated_at = datetime('now') WHERE id = new.id;
END;
CREATE TRIGGER newsletters_cleanup
AFTER DELETE ON newsletters
BEGIN
DELETE FROM content_blocks WHERE owner_kind = 'newsletter' AND owner_id = CAST(old.id AS TEXT);
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 = 'page_section'
AND NOT EXISTS (SELECT 1 FROM page_sections WHERE CAST(id AS TEXT) = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such page section')
WHEN new.owner_kind = 'newsletter'
AND NOT EXISTS (SELECT 1 FROM newsletters WHERE CAST(id AS TEXT) = new.owner_id)
THEN RAISE(ABORT, 'content_blocks: no such newsletter')
END;
END;

View file

@ -1,73 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 058 DETAILS & CONTACT AS BLOCKS
--
-- The Organization page's Details & Contact section was a preset
-- (organization_details) drawing NGU's address, tax ID and email
-- from code. It's ordinary content now, edited like any section's:
-- each section that used the preset gets those details as blocks
-- (the address, the nonprofit line with the tax ID, an email
-- button), and the preset leaves page_sections' CHECK.
--
-- page_sections is rebuilt for that CHECK, keeping its ids (its
-- blocks are owned by them), with its index and cleanup trigger.
-- ═══════════════════════════════════════════════════════════════
INSERT INTO content_blocks (owner_kind, owner_id, slot, sort_order, type, text, href)
SELECT 'page_section', CAST(s.id AS TEXT), 'body', b.sort_order, b.type, b.text, b.href
FROM page_sections s
CROSS JOIN (
SELECT 1000 AS sort_order, 'paragraph' AS type,
'1901 NW Blue Parkway' || char(10) || 'Unity Village, MO 64065' || char(10) ||
'*(Physical address, not for mail)*' AS text,
NULL AS href
UNION ALL
SELECT 1001, 'paragraph',
'Next Generation of Unity is a qualified 501(c)(3) nonprofit organization. Tax ID: 33-2819320.', NULL
UNION ALL
SELECT 1002, 'button', 'info@nextgenerationofunity.org', 'mailto:info@nextgenerationofunity.org'
) b
WHERE s.preset = 'organization_details';
UPDATE page_sections SET preset = NULL WHERE preset = 'organization_details';
CREATE TABLE page_sections_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
page_id TEXT NOT NULL REFERENCES site_pages (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
anchor TEXT NOT NULL
CONSTRAINT "A section's URL ID can use only lowercase letters, numbers and hyphens, eg. leadership."
CHECK (anchor <> '' AND anchor NOT GLOB '*[^a-z0-9-]*'),
title TEXT NOT NULL
CONSTRAINT "A section title can be 30 characters at most (it's listed in the page's side nav)."
CHECK (length(title) <= 30),
blurb TEXT,
accent TEXT CHECK (accent IN ('teal', 'deep', 'green', 'amber')),
preset TEXT CHECK (preset IN ('community_blog', 'group_map', 'region_list', 'partner_list',
'events', 'timeline')),
-- An events preset's filter and first view.
scope_id TEXT REFERENCES event_scopes (id) ON DELETE SET NULL,
event_type TEXT CHECK (event_type IN ('retreat', 'class', 'workshop', 'meeting', 'other')),
view TEXT CHECK (view IN ('carousel', 'grid', 'map')),
UNIQUE (page_id, anchor)
) STRICT;
INSERT INTO page_sections_new
(id, page_id, sort_order, anchor, title, blurb, accent, preset, scope_id, event_type, view)
SELECT id, page_id, sort_order, anchor, title, blurb, accent, preset, scope_id, event_type, view
FROM page_sections;
PRAGMA legacy_alter_table = ON;
DROP TABLE page_sections;
ALTER TABLE page_sections_new RENAME TO page_sections;
PRAGMA legacy_alter_table = OFF;
CREATE INDEX page_sections_page_idx ON page_sections (page_id, sort_order);
-- ── Triggers last (see CLAUDE.md, Migrations) ──
CREATE TRIGGER page_sections_cleanup
AFTER DELETE ON page_sections
BEGIN
DELETE FROM content_blocks WHERE owner_kind = 'page_section' AND owner_id = CAST(old.id AS TEXT);
END;

View file

@ -1,50 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 059 EVENTS VIEW: FIRST PUBLISHED HOST, READ DIRECTLY
--
-- v_events took its host (name, logo, color) from the first row of
-- v_event_hosts, published or not, so a draft partner hosting a
-- published event showed in its page's structured data and preview
-- image. It now takes the first published host, as loadHosts does.
--
-- It also joins event_hosts, organizations and people itself:
-- through the v_event_hosts view, SQLite built every host of every
-- event for each lookup, even one event's page. Same columns.
--
-- person_awards gets the index its event_id lookups (an event's
-- awards, and the SET NULL when an event is deleted) were missing.
-- ═══════════════════════════════════════════════════════════════
DROP VIEW v_events;
CREATE VIEW v_events AS
SELECT
e.*,
CASE WHEN eh.id IS NULL THEN NULL
WHEN eh.person_id IS NULL THEN 'organization' ELSE 'person' END
AS host_kind,
COALESCE(eh.org_id, eh.person_id) AS host_id,
COALESCE(o.name, p.display_name) AS host_name,
o.kind AS host_org_kind,
COALESCE(e.org_logo, o.logo) AS effective_org_logo,
COALESCE(e.color, o.color) AS effective_color,
COALESCE(
e.status,
CASE WHEN e.ends_on IS NOT NULL AND e.ends_on < date('now')
THEN 'past' ELSE 'upcoming' END
) AS effective_status
FROM events e
LEFT JOIN event_hosts eh
ON eh.id = (
SELECT x.id
FROM event_hosts x
LEFT JOIN organizations xo ON xo.id = x.org_id
LEFT JOIN people xp ON xp.id = x.person_id
WHERE x.event_id = e.id
AND COALESCE(xo.is_published, xp.is_published) = 1
ORDER BY x.sort_order, x.id
LIMIT 1
)
LEFT JOIN organizations o ON o.id = eh.org_id
LEFT JOIN people p ON p.id = eh.person_id;
CREATE INDEX person_awards_event_idx ON person_awards (event_id);

View file

@ -1,47 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 060 NEWSLETTER LAYOUT
--
-- A newsletter is one ordered list of parts now, each movable and
-- each with its own settings (src/lib/newsletter.ts reads them):
-- the header band, the title, any email block, a section of picked
-- events, posts or front page cards, and the footer. It's kept as
-- JSON in `layout`, the builder's only editor.
--
-- That replaces 057's fixed fields (intro, footer, picks) and the
-- drafts' content_blocks. 057 never reached a live database, so
-- there are no drafts to carry over: the table is rebuilt keeping
-- each row's id, title and dates, and its blocks are deleted.
-- `title` stays as its own column, for the list of drafts.
-- ═══════════════════════════════════════════════════════════════
DELETE FROM content_blocks WHERE owner_kind = 'newsletter';
DROP TRIGGER newsletters_touch;
DROP TRIGGER newsletters_cleanup;
CREATE TABLE newsletters_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
title TEXT,
layout TEXT NOT NULL DEFAULT '[]' CHECK (json_valid(layout) AND json_type(layout) = 'array'),
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now'))
) STRICT;
INSERT INTO newsletters_new (id, title, created_at, updated_at)
SELECT id, title, created_at, updated_at FROM newsletters;
-- content_blocks_owner_exists names this table.
PRAGMA legacy_alter_table = ON;
DROP TABLE newsletters;
ALTER TABLE newsletters_new RENAME TO newsletters;
PRAGMA legacy_alter_table = OFF;
-- ── Triggers last (see CLAUDE.md, Migrations) ──
CREATE TRIGGER newsletters_touch
AFTER UPDATE ON newsletters
FOR EACH ROW WHEN new.updated_at = old.updated_at
BEGIN
UPDATE newsletters SET updated_at = datetime('now') WHERE id = new.id;
END;

View file

@ -1,20 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 061 EVENTS: EVENT PHOTO
--
-- An event's own 16:9 photo, shown whole: at the top of its page, as
-- the front page's featured event, on featured cards, in newsletter
-- picks and as its page's share preview. photo_alt says what it
-- shows, for screen readers (blank: decoration).
--
-- card_image (029) goes back to being only the faded background of
-- the event's card, which crops it to the card's shape. Until now it
-- did both jobs, so each event's photo starts as its card
-- background, to keep the front page and previews as they were.
--
-- v_events selects e.*, so it carries the new columns as it is.
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE events ADD COLUMN photo TEXT;
ALTER TABLE events ADD COLUMN photo_alt TEXT;
UPDATE events SET photo = card_image WHERE card_image IS NOT NULL;

View file

@ -1,89 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 062 PEOPLE TAGS AND THE PEOPLE DIRECTORY
--
-- A tag marks people for a directory, rather than making a team of
-- them: Musician first, more (Speakers, Teachers) added in the admin
-- (Data → People tags) with no code.
--
-- person_tag_types the tags: a name, the full directory page's
-- intro (/directory/<id>) and their order
-- person_tags which people carry which tags; a person's
-- own repeater, so deleting a tag takes its
-- rows with it (cascade)
-- people.specialty one line shown in a directory, eg. "Vocals,
-- piano · Gospel, folk"
-- page_sections a 'people_directory' preset drawing one tag's
-- people (tag_id), a short list linking to the
-- full page; rebuilt for the preset CHECK as 058
-- did, then its index and trigger again
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE person_tag_types (
id TEXT PRIMARY KEY
CONSTRAINT "A tag's URL ID can use only lowercase letters, numbers and hyphens, eg. musician."
CHECK (id <> '' AND id NOT GLOB '*[^a-z0-9-]*'),
name TEXT NOT NULL, -- 'Musicians', the directory's title
blurb TEXT, -- the full directory page's intro
sort_order INTEGER NOT NULL DEFAULT 0
) STRICT;
INSERT INTO person_tag_types (id, name, blurb, sort_order) VALUES
('musician', 'Musicians', 'Musicians in the NGU community, for services, retreats and events.', 0);
CREATE TABLE person_tags (
person_id TEXT NOT NULL REFERENCES people (id) ON DELETE CASCADE,
tag_id TEXT NOT NULL REFERENCES person_tag_types (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY (person_id, tag_id)
) STRICT;
CREATE INDEX person_tags_tag_idx ON person_tags (tag_id);
ALTER TABLE people ADD COLUMN specialty TEXT;
-- ── page_sections: the directory preset ────────────────────────
CREATE TABLE page_sections_new (
id INTEGER PRIMARY KEY AUTOINCREMENT,
page_id TEXT NOT NULL REFERENCES site_pages (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
anchor TEXT NOT NULL
CONSTRAINT "A section's URL ID can use only lowercase letters, numbers and hyphens, eg. leadership."
CHECK (anchor <> '' AND anchor NOT GLOB '*[^a-z0-9-]*'),
title TEXT NOT NULL
CONSTRAINT "A section title can be 30 characters at most (it's listed in the page's side nav)."
CHECK (length(title) <= 30),
blurb TEXT,
accent TEXT CHECK (accent IN ('teal', 'deep', 'green', 'amber')),
preset TEXT CHECK (preset IN ('community_blog', 'group_map', 'region_list', 'partner_list',
'events', 'timeline', 'people_directory')),
-- An events preset's filter and first view.
scope_id TEXT REFERENCES event_scopes (id) ON DELETE SET NULL,
event_type TEXT CHECK (event_type IN ('retreat', 'class', 'workshop', 'meeting', 'other')),
view TEXT CHECK (view IN ('carousel', 'grid', 'map')),
-- A people_directory preset's tag.
tag_id TEXT REFERENCES person_tag_types (id) ON DELETE SET NULL,
UNIQUE (page_id, anchor)
) STRICT;
INSERT INTO page_sections_new
(id, page_id, sort_order, anchor, title, blurb, accent, preset, scope_id, event_type, view)
SELECT id, page_id, sort_order, anchor, title, blurb, accent, preset, scope_id, event_type, view
FROM page_sections;
PRAGMA legacy_alter_table = ON;
DROP TABLE page_sections;
ALTER TABLE page_sections_new RENAME TO page_sections;
PRAGMA legacy_alter_table = OFF;
CREATE INDEX page_sections_page_idx ON page_sections (page_id, sort_order);
-- ── Triggers last (see CLAUDE.md, Migrations) ──
CREATE TRIGGER page_sections_cleanup
AFTER DELETE ON page_sections
BEGIN
DELETE FROM content_blocks WHERE owner_kind = 'page_section' AND owner_id = CAST(old.id AS TEXT);
END;

View file

@ -1,114 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 063 MINISTRIES
--
-- A Unity ministry (a church) is an organization of its own kind, so
-- the list of them is kept here and an NGU group can name the one it
-- belongs to. Ministries have no page and no list on the public site:
-- a group's page says "Ministry: <name>", linked to the ministry's
-- website when it has one.
--
-- organizations.kind gains 'ministry' (the CHECK changes, so the
-- table is rebuilt as 052 did, then its indexes
-- and triggers again)
-- groups.ministry_id the group's ministry, cleared if the ministry
-- is deleted; the trigger below keeps it to
-- ministries
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE organizations_new (
id TEXT PRIMARY KEY, -- slug: 'northwest', 'lynnwood'
kind TEXT NOT NULL
CHECK (kind IN ('national', 'region', 'group', 'partner', 'ministry')),
name TEXT NOT NULL,
short_name TEXT,
tagline TEXT, -- one line, for the card
color TEXT,
logo TEXT, -- an upload's filename
venue TEXT,
address TEXT,
locality TEXT,
state_code TEXT, -- US only
country TEXT NOT NULL DEFAULT 'US',
location_label TEXT,
latitude REAL,
longitude REAL,
is_online INTEGER NOT NULL DEFAULT 0 CHECK (is_online IN (0, 1)),
is_published INTEGER NOT NULL DEFAULT 1 CHECK (is_published IN (0, 1)),
sort_order INTEGER NOT NULL DEFAULT 0,
created_at TEXT NOT NULL DEFAULT (datetime('now')),
updated_at TEXT NOT NULL DEFAULT (datetime('now')),
in_timeline INTEGER NOT NULL DEFAULT 0 CHECK (in_timeline IN (0, 1)),
is_listed INTEGER NOT NULL DEFAULT 1 CHECK (is_listed IN (0, 1))
) STRICT;
INSERT INTO organizations_new
(id, kind, name, short_name, tagline, color, logo,
venue, address, locality, state_code, country, location_label,
latitude, longitude, is_online,
is_published, sort_order, created_at, updated_at, in_timeline, is_listed)
SELECT id, kind, name, short_name, tagline, color, logo,
venue, address, locality, state_code, country, location_label,
latitude, longitude, is_online,
is_published, sort_order, created_at, updated_at, in_timeline, is_listed
FROM organizations;
PRAGMA legacy_alter_table = ON;
DROP TABLE organizations;
ALTER TABLE organizations_new RENAME TO organizations;
PRAGMA legacy_alter_table = OFF;
CREATE INDEX organizations_kind_idx ON organizations (kind, is_published, sort_order);
CREATE INDEX organizations_state_idx ON organizations (state_code);
-- ── groups.ministry_id ─────────────────────────────────────────
ALTER TABLE groups ADD COLUMN ministry_id TEXT REFERENCES organizations (id) ON DELETE SET NULL;
-- ── Triggers last (see CLAUDE.md, Migrations) ──
CREATE TRIGGER organizations_cleanup
AFTER DELETE ON organizations
BEGIN
DELETE FROM content_blocks WHERE owner_kind = 'organization' AND owner_id = old.id;
DELETE FROM links WHERE owner_kind = 'organization' AND owner_id = old.id;
END;
CREATE TRIGGER timeline_organizations_cleanup
AFTER DELETE ON organizations
BEGIN
DELETE FROM timeline_entries WHERE ref_kind = 'organization' AND ref_id = old.id;
END;
CREATE TRIGGER organizations_featured_cleanup
AFTER DELETE ON organizations
BEGIN
DELETE FROM featured_cards WHERE ref_kind = 'organization' AND ref_id = old.id;
END;
CREATE TRIGGER organizations_touch
AFTER UPDATE ON organizations
FOR EACH ROW WHEN new.updated_at = old.updated_at
BEGIN
UPDATE organizations SET updated_at = datetime('now') WHERE id = new.id;
END;
CREATE TRIGGER groups_ministry_kind
BEFORE INSERT ON groups
FOR EACH ROW WHEN new.ministry_id IS NOT NULL
AND (SELECT kind FROM organizations WHERE id = new.ministry_id) IS NOT 'ministry'
BEGIN
SELECT RAISE(ABORT, 'A group''s ministry must be a ministry.');
END;
CREATE TRIGGER groups_ministry_kind_update
BEFORE UPDATE OF ministry_id ON groups
FOR EACH ROW WHEN new.ministry_id IS NOT NULL
AND (SELECT kind FROM organizations WHERE id = new.ministry_id) IS NOT 'ministry'
BEGIN
SELECT RAISE(ABORT, 'A group''s ministry must be a ministry.');
END;

View file

@ -1,38 +0,0 @@
-- ═══════════════════════════════════════════════════════════════
-- 064 ORGANIZATION CONTACTS
--
-- Who to write to at an organization, by role, so a mailing list can
-- be exported (Tools → Newsletter → Recipients) filtered by role,
-- kind and region. Private: never sent to the public site.
--
-- contact_types the roles, made in the admin (Data →
-- Contact types), eg. Minister, General
-- info; none are seeded
-- organization_contacts an organization's contacts, each with a
-- role; its own repeater on the organization.
-- A role still in use can't be deleted (the
-- foreign key refuses it)
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE contact_types (
id TEXT PRIMARY KEY
CONSTRAINT "A contact type's URL ID can use only lowercase letters, numbers and hyphens, eg. minister."
CHECK (id <> '' AND id NOT GLOB '*[^a-z0-9-]*'),
name TEXT NOT NULL, -- 'Minister'
sort_order INTEGER NOT NULL DEFAULT 0
) STRICT;
CREATE TABLE organization_contacts (
id INTEGER PRIMARY KEY AUTOINCREMENT,
org_id TEXT NOT NULL REFERENCES organizations (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
type_id TEXT NOT NULL REFERENCES contact_types (id),
name TEXT,
email TEXT,
phone TEXT,
CONSTRAINT "A contact needs an email or a phone number."
CHECK (email IS NOT NULL OR phone IS NOT NULL)
) STRICT;
CREATE INDEX organization_contacts_org_idx ON organization_contacts (org_id, sort_order);
CREATE INDEX organization_contacts_type_idx ON organization_contacts (type_id);

View file

@ -0,0 +1,66 @@
-- ═══════════════════════════════════════════════════════════════
-- 066 SEED (with the baseline)
--
-- The least a new database needs for every page to work. Runs right
-- after 066_schema.sql, on an empty database only.
--
-- meta, site_settings, the single rows the site reads and the
-- front_page, admin edits in place, each left at its
-- community_page defaults (blank means "use site.json"
-- or the built-in default)
-- event_scopes the fixed scopes events and Retreats
-- sections filter by
-- front_page_sections the home page's sections, in order
-- site_pages, page_sections the Community, Retreats, Resources,
-- Organization and History pages and
-- their sections (presets: map, lists,
-- events, timeline)
-- person_tag_types Musicians, the directory the people
-- section and /directory/musician show
--
-- Not seeded: content an editor types in (the hero's words, paths,
-- stats, the Organization page's address and tax ID). Fill those in
-- through the admin.
-- ═══════════════════════════════════════════════════════════════
INSERT INTO meta (key, value) VALUES ('created_at', datetime('now'));
INSERT INTO site_settings (id) VALUES ('site');
INSERT INTO front_page (id) VALUES ('home');
INSERT INTO community_page (id) VALUES ('community');
INSERT INTO event_scopes (id, name, sort_order) VALUES ('national', 'National', 10);
INSERT INTO event_scopes (id, name, sort_order) VALUES ('regional', 'Regional', 20);
INSERT INTO event_scopes (id, name, sort_order) VALUES ('local', 'Local', 30);
INSERT INTO event_scopes (id, name, sort_order) VALUES ('international', 'International', 40);
INSERT INTO event_scopes (id, name, sort_order) VALUES ('partner', 'Partner', 50);
INSERT INTO event_scopes (id, name, sort_order) VALUES ('other', 'Other', 60);
INSERT INTO front_page_sections (page_id, sort_order, section, is_hidden) VALUES ('home', 0, 'countdown', 0);
INSERT INTO front_page_sections (page_id, sort_order, section, title, blurb, is_hidden) VALUES ('home', 1, 'retreats', 'National Retreats', 'Our flagship gatherings, open to young adults across the country.', 0);
INSERT INTO front_page_sections (page_id, sort_order, section, title, blurb, is_hidden) VALUES ('home', 2, 'calendar', 'What''s on', 'Every gathering, class and meeting in one place.', 0);
INSERT INTO front_page_sections (page_id, sort_order, section, title, is_hidden) VALUES ('home', 3, 'stats', 'NGU by the numbers', 0);
INSERT INTO front_page_sections (page_id, sort_order, section, title, blurb, is_hidden) VALUES ('home', 4, 'timeline', 'Moments that shaped us', 'Highlights from our history.', 0);
INSERT INTO front_page_sections (page_id, sort_order, section, title, blurb, is_hidden) VALUES ('home', 5, 'connect', 'Find your way in', 'Tell us what you''re looking for.', 0);
INSERT INTO site_pages (id) VALUES ('community');
INSERT INTO site_pages (id) VALUES ('retreats');
INSERT INTO site_pages (id) VALUES ('resources');
INSERT INTO site_pages (id) VALUES ('organization');
INSERT INTO site_pages (id) VALUES ('history');
INSERT INTO page_sections (page_id, sort_order, anchor, title, accent, preset) VALUES ('community', 0, 'blog', 'Community Blog', 'teal', 'community_blog');
INSERT INTO page_sections (page_id, sort_order, anchor, title, blurb, accent, preset, view) VALUES ('community', 1, 'groups', 'Local Groups', 'Young adult groups meeting in person and online across the movement.', 'teal', 'group_map', 'map');
INSERT INTO page_sections (page_id, sort_order, anchor, title, blurb, accent, preset) VALUES ('community', 2, 'regions', 'Unity Regions', 'The regional organizations that support groups and host their own gatherings.', 'deep', 'region_list');
INSERT INTO page_sections (page_id, sort_order, anchor, title, blurb, accent, preset) VALUES ('community', 3, 'partners', 'Partner Organizations', 'Organizations we collaborate with across the Unity movement and beyond.', 'amber', 'partner_list');
INSERT INTO page_sections (page_id, sort_order, anchor, title, blurb, accent, preset, scope_id, event_type, view) VALUES ('retreats', 0, 'national', 'National Retreats', 'Our flagship gatherings, open to young adults across the country.', 'teal', 'events', 'national', 'retreat', 'carousel');
INSERT INTO page_sections (page_id, sort_order, anchor, title, blurb, accent, preset, scope_id, event_type, view) VALUES ('retreats', 1, 'regional', 'Regional Retreats', 'Smaller gatherings hosted by regions throughout the year.', 'green', 'events', 'regional', 'retreat', 'grid');
INSERT INTO page_sections (page_id, sort_order, anchor, title, blurb, accent, preset, scope_id, event_type, view) VALUES ('retreats', 2, 'partner', 'Partner Events', 'Retreats hosted by organizations we collaborate with.', 'amber', 'events', 'partner', 'retreat', 'grid');
INSERT INTO page_sections (page_id, sort_order, anchor, title, blurb, accent) VALUES ('resources', 0, 'unity', 'Unity Teachings', 'Core principles, readings, and study material from the Unity movement.', 'teal');
INSERT INTO page_sections (page_id, sort_order, anchor, title, blurb, accent) VALUES ('resources', 1, 'branding', 'Branding & Marketing', 'Logos, colors, templates, and guidelines for representing NGU.', 'green');
INSERT INTO page_sections (page_id, sort_order, anchor, title, blurb, accent) VALUES ('resources', 2, 'partner', 'Partner Resources', 'Material for the organizations we collaborate with.', 'amber');
INSERT INTO page_sections (page_id, sort_order, anchor, title, blurb, accent, preset) VALUES ('history', 0, 'timeline', 'NGU Timeline', 'Open a year to see what happened.', 'teal', 'timeline');
INSERT INTO page_sections (page_id, sort_order, anchor, title, accent) VALUES ('organization', 2, 'contact', 'Details & Contact', 'deep');
INSERT INTO page_sections (page_id, sort_order, anchor, title, accent) VALUES ('organization', 0, 'mission', 'Mission, Vision & Values', 'teal');
INSERT INTO page_sections (page_id, sort_order, anchor, title, accent) VALUES ('organization', 1, 'leadership', 'Leadership', 'green');
INSERT INTO person_tag_types (id, name, blurb, sort_order) VALUES ('musician', 'Musicians', 'Musicians in the NGU community, for services, retreats and events.', 0);

View file

@ -0,0 +1,42 @@
-- ═══════════════════════════════════════════════════════════════
-- 067 ORGANIZATION CARDS: WHICH ORGANIZATIONS
--
-- The organization cards preset (page_sections.preset 'partner_list',
-- the Community page's Partners) can list ministries as well as
-- partners, chosen two ways:
--
-- page_sections.org_kinds which kinds it lists by itself, every
-- published, listed one by name:
-- 'partner', 'ministry' or both
-- ('partner,ministry'). Blank: partners
-- page_section_orgs a hand-picked list, in order; when a
-- section has any, it shows those instead
-- (published ones, listed or not). Only
-- partners and ministries (triggers below)
-- ═══════════════════════════════════════════════════════════════
ALTER TABLE page_sections ADD COLUMN org_kinds TEXT
CHECK (org_kinds IN ('partner', 'ministry', 'partner,ministry'));
CREATE TABLE page_section_orgs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
section_id INTEGER NOT NULL REFERENCES page_sections (id) ON DELETE CASCADE,
sort_order INTEGER NOT NULL DEFAULT 0,
org_id TEXT NOT NULL REFERENCES organizations (id) ON DELETE CASCADE
) STRICT;
CREATE INDEX page_section_orgs_section_idx ON page_section_orgs (section_id, sort_order);
CREATE TRIGGER page_section_orgs_kind
BEFORE INSERT ON page_section_orgs
FOR EACH ROW WHEN (SELECT kind FROM organizations WHERE id = new.org_id) NOT IN ('partner', 'ministry')
BEGIN
SELECT RAISE(ABORT, 'Organization cards can list partners and ministries only.');
END;
CREATE TRIGGER page_section_orgs_kind_update
BEFORE UPDATE OF org_id ON page_section_orgs
FOR EACH ROW WHEN (SELECT kind FROM organizations WHERE id = new.org_id) NOT IN ('partner', 'ministry')
BEGIN
SELECT RAISE(ABORT, 'Organization cards can list partners and ministries only.');
END;

View file

@ -0,0 +1,32 @@
-- ═══════════════════════════════════════════════════════════════
-- 068 REDIRECTS
--
-- Short links on our own domain (Data → Links/redirects), eg.
-- /go/retreat-signup, for the newsletter and anywhere else a link
-- should be counted. routes/redirects.js answers /go/<id>: it counts
-- the click here, tells Plausible about it, and sends the visitor on
-- with the link's UTM tags added.
--
-- target_url where it goes: a web address, or a path on this
-- site starting with /
-- utm_* added to the destination's query, when set
-- clicks, kept by the redirect route, not the editor
-- last_clicked_at
-- ═══════════════════════════════════════════════════════════════
CREATE TABLE redirects (
id TEXT PRIMARY KEY
CONSTRAINT "A redirect's URL ID can use only lowercase letters, numbers and hyphens, eg. retreat-signup."
CHECK (id <> '' AND id NOT GLOB '*[^a-z0-9-]*'),
target_url TEXT NOT NULL
CONSTRAINT "A redirect goes to a web address (https://...) or a path on this site starting with /."
CHECK (target_url GLOB 'https://?*' OR target_url GLOB 'http://?*'
OR (target_url GLOB '/*' AND target_url NOT GLOB '//*')),
note TEXT, -- what it's for, admin only
utm_source TEXT, -- 'newsletter'
utm_medium TEXT, -- 'email'
utm_campaign TEXT, -- 'october-2026'
clicks INTEGER NOT NULL DEFAULT 0,
last_clicked_at TEXT,
created_at TEXT NOT NULL DEFAULT (datetime('now'))
) STRICT;

View file

@ -72,7 +72,7 @@ const content = new Hono();
// Kinds with a public page. A ministry (063_ministries.sql) has none: // Kinds with a public page. A ministry (063_ministries.sql) has none:
// it's only named on its groups' pages, so no route here serves one. // it's only named on its groups' pages, so no route here serves one.
const ORG_KINDS = ["national", "region", "group", "partner"]; const ORG_KINDS = ["national", "region", "group", "partner", "ministry"];
/* ── Loaders ───────────────────────────────────────────────── */ /* ── Loaders ───────────────────────────────────────────────── */
@ -597,6 +597,11 @@ content.get("/events/:id", (c) => {
GET /organizations every published, listed org GET /organizations every published, listed org
GET /organizations?kind=region one kind GET /organizations?kind=region one kind
GET /organizations?kind=region,group GET /organizations?kind=region,group
GET /organizations?ids=a,b these, published, listed or
not (a hand-picked list, 067)
Ministries come only when asked for, by kind or id: they have no
page, so the plain list leaves them out.
Whatever the kind, the common card fields are in the same Whatever the kind, the common card fields are in the same
places, so a list component reads `name`, `color`, `logo` and places, so a list component reads `name`, `color`, `logo` and
@ -616,19 +621,21 @@ content.get("/organizations", (c) => {
return c.json({ error: `kind must be one of ${ORG_KINDS.join(", ")}` }, 400); return c.json({ error: `kind must be one of ${ORG_KINDS.join(", ")}` }, 400);
} }
const filter = kinds.length > 0 ? `AND kind IN (${marks(kinds.length)})` : ""; const ids = (c.req.query("ids") ?? "").split(",").map((id) => id.trim()).filter(Boolean).slice(0, 100);
const [where, params] =
ids.length > 0
? [`id IN (${marks(ids.length)})`, ids]
: kinds.length > 0
? [`is_listed = 1 AND kind IN (${marks(kinds.length)})`, kinds]
: [`is_listed = 1 AND kind <> 'ministry'`, []];
const rows = db const rows = db
.prepare( .prepare(`SELECT * FROM organizations WHERE is_published = 1 AND ${where} ORDER BY kind, sort_order, name`)
`SELECT * FROM organizations .all(...params);
WHERE is_published = 1 AND is_listed = 1 AND kind <> 'ministry' ${filter}
ORDER BY kind, sort_order, name`,
)
.all(...kinds);
const ids = rows.map((row) => row.id); const found = rows.map((row) => row.id);
const links = loadLinks(db, "organization", ids); const links = loadLinks(db, "organization", found);
const cards = loadBlocks(db, "organization", ids, "card"); const cards = loadBlocks(db, "organization", found, "card");
// No body blocks or leadership: they grow with every organization // No body blocks or leadership: they grow with every organization
// and only a group's own detail panel or page shows them, which // and only a group's own detail panel or page shows them, which

View file

@ -225,7 +225,7 @@ home.get("/front-page", (c) => {
? { url: page.livestream_url, title: page.livestream_title } ? { url: page.livestream_url, title: page.livestream_title }
: null, : null,
video: page.video_url video: page.video_url
? { url: page.video_url, title: page.video_title } ? { url: page.video_url, title: page.video_title, captions: page.video_captions }
: null, : null,
event: shapeHeroEvent(db, heroEvent), event: shapeHeroEvent(db, heroEvent),
}, },

View file

@ -3,12 +3,12 @@
GET /media the library, newest first, ?q=name, GET /media the library, newest first, ?q=name,
?type=image|video|audio, ?type=image|video|audio,
?folder=logos|images|thumbnails. ?folder=logos|images|thumbnails|captions.
Picks up images copied into the Picks up images copied into the
uploads folder by hand first uploads folder by hand first
(registerLooseFiles, at most every (registerLooseFiles, at most every
SCAN_EVERY_MS) SCAN_EVERY_MS)
POST /media upload one image (multipart: file, POST /media upload one image or .vtt (multipart: file,
keep_original, folder: FOLDERS in keep_original, folder: FOLDERS in
media.js, default images) media.js, default images)
GET /media/:id/uses which records name this file GET /media/:id/uses which records name this file
@ -41,6 +41,7 @@ import {
store, store,
} from "../media.js"; } from "../media.js";
import { fetchImage, previewLink } from "../linkPreview.js"; import { fetchImage, previewLink } from "../linkPreview.js";
import { ClipError, grabFrame } from "../clips.js";
import { NO_STORE } from "../shape.js"; import { NO_STORE } from "../shape.js";
const media = new Hono(); const media = new Hono();
@ -204,6 +205,26 @@ media.post("/link-preview", requireRole("editor"), async (c) => {
); );
}); });
/* A frame of a YouTube or Facebook video at `seconds`, saved as a
thumbnail for a video card's picture. */
media.post("/video-frame", requireRole("editor"), async (c) => {
const user = c.get("user");
let body;
try {
body = (await c.req.json()) ?? {};
} catch {
return c.json({ error: "Expected a JSON body." }, 400);
}
const row = await addToLibrary(c.get("db"), await grabFrame(body.url, Number(body.seconds)), {
originalName: `video frame ${Math.floor(Number(body.seconds))}s`,
folder: "thumbnails",
keepOriginal: false,
userId: user.id,
});
console.log(`video frame ${String(body.url).slice(0, 200)} at ${body.seconds}s by ${user.email}`);
return c.json({ media: shape(row) }, 201, NO_STORE);
});
/* Every TEXT column of every content table, searched for any of the /* Every TEXT column of every content table, searched for any of the
exact values a record can use to name the file: its /uploads/ exact values a record can use to name the file: its /uploads/
path, that path escaped, or (for a file copied in by hand and path, that path escaped, or (for a file copied in by hand and
@ -273,7 +294,7 @@ media.delete("/media/:id", requireRole("admin"), async (c) => {
}); });
media.onError((err, c) => { media.onError((err, c) => {
if (err instanceof MediaError) return c.json({ error: err.message }, err.status, NO_STORE); if (err instanceof MediaError || err instanceof ClipError) return c.json({ error: err.message }, err.status, NO_STORE);
console.error(err); console.error(err);
return c.json({ error: "Something went wrong." }, 500); return c.json({ error: "Something went wrong." }, 500);
}); });

View file

@ -0,0 +1,97 @@
/* ═══════════════════════════════════════════════════════════════
REDIRECTS: GET /go/:id
A short link from Data → Links/redirects (068). Each visit:
1. adds one to the link's clicks (shown in the admin list)
2. tells Plausible, as a pageview of /go/<id> with the visitor's
browser and address, since a redirect never loads the page
script; it shows under Top Pages like any page
3. sends the visitor on (302) to the destination, with the link's
UTM tags added to its query, so a click that lands on a
tracked site is credited to the newsletter
Never cached, so every click reaches here. An unknown id falls
through to the page route, which shows the site's not-found page.
Plausible is at PLAUSIBLE_URL (analyticsReport.js); if it can't
be reached the redirect still happens, and that's logged once.
Mounted before routes/pages.js. In production nginx sends /go/
here through its catch-all page block; in development Vite
proxies /go (vite.config.ts).
═══════════════════════════════════════════════════════════════ */
import { Hono } from "hono";
import { PLAUSIBLE_URL } from "../analyticsReport.js";
import { clientIp } from "../auth.js";
import { siteFor } from "../pageMeta.js";
import { NO_STORE } from "../shape.js";
const UTM = ["utm_source", "utm_medium", "utm_campaign"];
/* The destination with the link's UTM tags, any it already carries
kept. A path on this site stays a path. */
export function destination(row, origin) {
const local = row.target_url.startsWith("/");
const url = new URL(row.target_url, origin);
for (const key of UTM) {
if (row[key] && !url.searchParams.has(key)) url.searchParams.set(key, row[key]);
}
return local ? `${url.pathname}${url.search}${url.hash}` : url.href;
}
let plausibleWarned = false;
function tellPlausible(c, site, id) {
let domain;
try {
domain = new URL(site.url).hostname;
} catch {
return; // no site url, nothing to count under
}
const ip = clientIp(c);
fetch(`${PLAUSIBLE_URL}/api/event`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"User-Agent": c.req.header("user-agent") ?? "",
...(ip ? { "X-Forwarded-For": ip } : {}),
},
body: JSON.stringify({
name: "pageview",
domain,
url: `${site.url.replace(/\/$/, "")}/go/${id}`,
referrer: c.req.header("referer") ?? null,
}),
signal: AbortSignal.timeout(5_000),
}).catch((err) => {
if (plausibleWarned) return;
plausibleWarned = true;
console.warn(`redirects: couldn't reach Plausible at ${PLAUSIBLE_URL} (${err.message}); clicks are still counted`);
});
}
const redirects = new Hono();
redirects.get("/go/:id", (c, next) => {
const db = c.get("db");
const row = db.prepare(`SELECT * FROM redirects WHERE id = ?`).get(c.req.param("id").toLowerCase());
if (!row) return next();
db.prepare(`UPDATE redirects SET clicks = clicks + 1, last_clicked_at = datetime('now') WHERE id = ?`).run(row.id);
// site.json gives Plausible's domain and an origin to resolve paths
// against. Without it (SITE_CONFIG missing) the visitor still goes
// on; only the Plausible report is skipped.
let site = {};
try {
site = siteFor(db);
} catch (err) {
console.warn(`redirects: /go/${row.id} without site.json (${err.message}); not reported to Plausible`);
}
if (site.url) tellPlausible(c, site, row.id);
for (const [name, value] of Object.entries(NO_STORE)) c.header(name, value);
return c.redirect(destination(row, site.url || "http://localhost"), 302);
});
export default redirects;

View file

@ -37,11 +37,21 @@ sitePages.get("/site-pages/:id", (c) => {
const rows = db const rows = db
.prepare( .prepare(
`SELECT id, anchor, title, blurb, accent, preset, scope_id, event_type, view, tag_id `SELECT id, anchor, title, blurb, accent, preset, scope_id, event_type, view, tag_id, org_kinds
FROM page_sections WHERE page_id = ? ORDER BY sort_order, id`, FROM page_sections WHERE page_id = ? ORDER BY sort_order, id`,
) )
.all(id); .all(id);
const blocks = loadBlocks(db, "page_section", rows.map((row) => String(row.id))); const blocks = loadBlocks(db, "page_section", rows.map((row) => String(row.id)));
const picked = new Map();
for (const { section_id, org_id } of db
.prepare(
`SELECT o.section_id, o.org_id FROM page_section_orgs o
JOIN page_sections s ON s.id = o.section_id
WHERE s.page_id = ? ORDER BY o.section_id, o.sort_order, o.id`,
)
.all(id)) {
picked.set(section_id, [...(picked.get(section_id) ?? []), org_id]);
}
return json(c, { return json(c, {
page: { page: {
@ -49,6 +59,7 @@ sitePages.get("/site-pages/:id", (c) => {
sections: rows.map(({ id: sectionId, ...section }) => ({ sections: rows.map(({ id: sectionId, ...section }) => ({
...section, ...section,
blocks: blocks.get(String(sectionId)) ?? [], blocks: blocks.get(String(sectionId)) ?? [],
org_ids: picked.get(sectionId) ?? [],
})), })),
}, },
}); });

View file

@ -66,7 +66,7 @@ export function loadBlocks(db, ownerKind, ids, slot = "body") {
const blockRows = db const blockRows = db
.prepare( .prepare(
`SELECT id, owner_id, type, text, media, href, alt, cite, team_id `SELECT id, owner_id, type, text, media, href, alt, cite, captions, team_id
FROM content_blocks FROM content_blocks
WHERE owner_kind = ? AND slot = ? AND owner_id IN (${placeholders(ids.length)}) WHERE owner_kind = ? AND slot = ? AND owner_id IN (${placeholders(ids.length)})
ORDER BY owner_id, sort_order`, ORDER BY owner_id, sort_order`,
@ -85,6 +85,7 @@ export function loadBlocks(db, ownerKind, ids, slot = "body") {
href: row.href, href: row.href,
alt: row.alt, alt: row.alt,
cite: row.cite, cite: row.cite,
captions: row.captions,
team_id: row.team_id, team_id: row.team_id,
items: [], items: [],
}; };

View file

@ -351,7 +351,7 @@ function Block({
return ( return (
<figure> <figure>
<div className="overflow-hidden"> <div className="overflow-hidden">
<VideoPlayer url={block.href} still={mediaUrl(block.media)} title={text || null} /> <VideoPlayer url={block.href} still={mediaUrl(block.media)} captions={mediaUrl(block.captions)} title={text || null} />
</div> </div>
{!reading && <Caption text={text} />} {!reading && <Caption text={text} />}
</figure> </figure>

View file

@ -33,11 +33,14 @@ export default function VideoPlayer({
url, url,
still, still,
title, title,
captions,
className = '', className = '',
}: { }: {
url?: string | null url?: string | null
/** An image URL to show before it plays. */ /** An image URL to show before it plays. */
still?: string | null still?: string | null
/** A WebVTT file's URL, for an uploaded video; embeds bring their own. */
captions?: string | null
title?: string | null title?: string | null
className?: string className?: string
}) { }) {
@ -66,7 +69,9 @@ export default function VideoPlayer({
playsInline playsInline
aria-label={title || 'Video'} aria-label={title || 'Video'}
className={`aspect-video w-full rounded-md bg-black ${className}`} className={`aspect-video w-full rounded-md bg-black ${className}`}
/> >
{captions && <track kind="captions" src={captions} srcLang="en" label="Captions" default />}
</video>
) : ( ) : (
<iframe <iframe
ref={focusOnMount} ref={focusOnMount}

View file

@ -37,13 +37,14 @@
cached list would lie. cached list would lie.
═══════════════════════════════════════════════════════════════ */ ═══════════════════════════════════════════════════════════════ */
import { FileAudio, X } from "@phosphor-icons/react"; import { ClosedCaptioning, FileAudio, X } from "@phosphor-icons/react";
import { useCallback, useEffect, useId, useRef, useState, type ReactNode } from "react"; import { useCallback, useEffect, useId, useRef, useState, type ReactNode } from "react";
import { useLocation } from "react-router-dom"; import { useLocation } from "react-router-dom";
import { ApiError, get, post, upload } from "../../lib/api.ts"; import { ApiError, get, post, upload } from "../../lib/api.ts";
import { useAuth } from "../../lib/auth.tsx"; import { useAuth } from "../../lib/auth.tsx";
import { clock, parseClock } from "../../lib/clock.ts";
import { canWrite as roleCanWrite } from "../../lib/roles.ts"; import { canWrite as roleCanWrite } from "../../lib/roles.ts";
import { useSmallImage } from "../../lib/useSmallImage.ts"; import { useSmallImage } from "../../lib/useSmallImage.ts";
@ -58,7 +59,7 @@ export type MediaItem = {
processed: boolean; processed: boolean;
uploaded_by: string | null; uploaded_by: string | null;
created_at: string; created_at: string;
/** logos, images or thumbnails; null for clips and older files in the root. */ /** logos, images, thumbnails or captions; null for clips and older files in the root. */
folder: string | null; folder: string | null;
}; };
@ -68,6 +69,7 @@ export const IMAGE_FOLDERS = [
["logos", "Logos"], ["logos", "Logos"],
["images", "Images"], ["images", "Images"],
["thumbnails", "Previews"], ["thumbnails", "Previews"],
["captions", "Captions"],
] as const; ] as const;
export type ImageFolder = (typeof IMAGE_FOLDERS)[number][0]; export type ImageFolder = (typeof IMAGE_FOLDERS)[number][0];
@ -197,6 +199,8 @@ export function UploadButton({
const [keepOriginal, setKeepOriginal] = useState(false); const [keepOriginal, setKeepOriginal] = useState(false);
const [busy, setBusy] = useState(false); const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null); const [error, setError] = useState<string | null>(null);
// Captions are kept as they are, so there's no original to keep.
const captions = folder === "captions";
async function send(files: FileList | null) { async function send(files: FileList | null) {
if (!files || files.length === 0) return; if (!files || files.length === 0) return;
@ -234,11 +238,12 @@ export function UploadButton({
<input <input
ref={inputRef} ref={inputRef}
type="file" type="file"
accept="image/jpeg,image/png,image/gif,image/webp,image/svg+xml" accept={captions ? ".vtt,text/vtt" : "image/jpeg,image/png,image/gif,image/webp,image/svg+xml"}
multiple={multiple} multiple={multiple}
className="hidden" className="hidden"
onChange={(e) => send(e.target.files)} onChange={(e) => send(e.target.files)}
/> />
{!captions && (
<label htmlFor={keepId} className="flex items-center gap-1.5 text-xs text-muted"> <label htmlFor={keepId} className="flex items-center gap-1.5 text-xs text-muted">
<input <input
id={keepId} id={keepId}
@ -249,6 +254,7 @@ export function UploadButton({
/> />
Keep original Keep original
</label> </label>
)}
</div> </div>
{error && <p className="mt-1 text-xs text-danger">{error}</p>} {error && <p className="mt-1 text-xs text-danger">{error}</p>}
</div> </div>
@ -292,6 +298,10 @@ export function MediaGrid({
<div className="flex h-full w-full items-center justify-center bg-tint" aria-hidden="true"> <div className="flex h-full w-full items-center justify-center bg-tint" aria-hidden="true">
<FileAudio weight="bold" className="h-10 w-10 text-link" /> <FileAudio weight="bold" className="h-10 w-10 text-link" />
</div> </div>
) : item.content_type === "text/vtt" ? (
<div className="flex h-full w-full items-center justify-center bg-tint" aria-hidden="true">
<ClosedCaptioning weight="bold" className="h-10 w-10 text-link" />
</div>
) : ( ) : (
<Thumb url={item.url} /> <Thumb url={item.url} />
)} )}
@ -428,7 +438,7 @@ export function MediaPicker({
const [query, setQuery] = useState(""); const [query, setQuery] = useState("");
const [tab, setTab] = useState<string>(folder); const [tab, setTab] = useState<string>(folder);
const fromRequests = tab === REQUESTS_TAB; const fromRequests = tab === REQUESTS_TAB;
const { items, error, setItems } = useMediaLibrary(query, "image", fromRequests ? undefined : tab); const { items, error, setItems } = useMediaLibrary(query, tab === "captions" ? undefined : "image", fromRequests ? undefined : tab);
const dialogRef = useRef<HTMLDialogElement>(null); const dialogRef = useRef<HTMLDialogElement>(null);
// showModal gives focus trapping, Escape and the backdrop for free. // showModal gives focus trapping, Escape and the backdrop for free.
@ -524,6 +534,7 @@ export function ImageInput({
value, value,
resolve, resolve,
folder, folder,
videoUrl,
locked, locked,
className, className,
onChange, onChange,
@ -533,6 +544,8 @@ export function ImageInput({
resolve?: (file?: string | null) => string | null; resolve?: (file?: string | null) => string | null;
/** The field's `folder` (logos for logo fields); default images. */ /** The field's `folder` (logos for logo fields); default images. */
folder?: string; folder?: string;
/** A video link to take a frame from (the field's `frameFrom`). */
videoUrl?: string | null;
locked: boolean; locked: boolean;
className: string; className: string;
onChange: (value: string) => void; onChange: (value: string) => void;
@ -552,11 +565,13 @@ export function ImageInput({
className="flex h-20 w-20 shrink-0 items-center justify-center overflow-hidden border border-muted/20" className="flex h-20 w-20 shrink-0 items-center justify-center overflow-hidden border border-muted/20"
style={CHECKER} style={CHECKER}
> >
{src && !broken ? ( {folder === "captions" && src ? (
<ClosedCaptioning weight="bold" className="h-8 w-8 text-link" aria-label="Captions file" />
) : src && !broken ? (
<img src={src} alt="" className="h-full w-full object-contain" onError={() => setBroken(true)} /> <img src={src} alt="" className="h-full w-full object-contain" onError={() => setBroken(true)} />
) : ( ) : (
<span className="px-1 text-center text-[10px] text-muted/70"> <span className="px-1 text-center text-[10px] text-muted/70">
{src ? "Not found" : "No image"} {src ? "Not found" : folder === "captions" ? "No file" : "No image"}
</span> </span>
)} )}
</div> </div>
@ -587,6 +602,7 @@ export function ImageInput({
)} )}
</div> </div>
)} )}
{editable && videoUrl && <FrameFromVideo url={videoUrl} className={className} onSaved={onChange} />}
</div> </div>
{picking && ( {picking && (
@ -601,6 +617,55 @@ export function ImageInput({
); );
} }
/* ── Frame from a video ──────────────────────────────────────── */
/* A link's own start time (YouTube's t=83 or t=83s), so a link
copied at the moment wanted starts the picker there. */
function startOf(url: string): number {
try {
const t = new URL(url).searchParams.get("t") ?? "";
return /^\d+s?$/.test(t) ? parseInt(t, 10) : 0;
} catch {
return 0;
}
}
function FrameFromVideo({ url, className, onSaved }: { url: string; className: string; onSaved: (value: string) => void }) {
const [text, setText] = useState(() => clock(startOf(url)));
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const timeId = useId();
const seconds = parseClock(text);
async function take() {
setBusy(true);
setError(null);
try {
const { media } = await post("/admin/video-frame", { url, seconds });
onSaved(media.url);
} catch (err) {
setError(err instanceof ApiError ? err.message : "Couldn't take that frame.");
} finally {
setBusy(false);
}
}
return (
<div className="flex flex-wrap items-center gap-2">
<label htmlFor={timeId} className="text-sm text-muted">
Frame at
</label>
<div className="w-24">
<input id={timeId} type="text" value={text} onChange={(e) => setText(e.target.value)} placeholder="eg. 1:23" className={className} />
</div>
<button type="button" className={button} disabled={busy || seconds == null} onClick={take}>
{busy ? "Taking…" : "Use this frame"}
</button>
{error && <span className="text-xs text-danger">{error}</span>}
</div>
);
}
/* ── Link preview field ──────────────────────────────────────── */ /* ── Link preview field ──────────────────────────────────────── */
/* Fills only what's empty: a title somebody already typed is theirs, /* Fills only what's empty: a title somebody already typed is theirs,

View file

@ -62,6 +62,10 @@
the file's name and first-page preview. `filesWhen` limits it to the file's name and first-page preview. `filesWhen` limits it to
rows that match, as `when` does for the field. rows that match, as `when` does for the field.
`redirects: true` on a link field adds "Pick a redirect": a list of
Data → Links/redirects (the `redirects` options) that fills the
field with the short link's full address, <site>/go/<URL ID>.
`widget: "testNotice"` is a text box of email addresses with a `widget: "testNotice"` is a text box of email addresses with a
"Send a test notice" button (TestNoticeInput below), for Site "Send a test notice" button (TestNoticeInput below), for Site
settings → Notices. settings → Notices.
@ -71,7 +75,9 @@
`resolve` option is the media.ts helper for the field's public/ `resolve` option is the media.ts helper for the field's public/
directory, so a bare filename previews from the right place. Its directory, so a bare filename previews from the right place. Its
`folder` ("logos" for logo and icon fields) is where uploads go and `folder` ("logos" for logo and icon fields) is where uploads go and
the tab the library opens on. the tab the library opens on. `frameFrom` names the row's video
link field and adds "Frame at" (a still at a typed time, saved to
thumbnails/); `frameWhen` limits it to rows that match.
Two options change the box itself rather than what goes in it: Two options change the box itself rather than what goes in it:
@ -95,6 +101,7 @@ import ContentBlocks from "../ContentBlocks.tsx";
import { FILTER_FROM, OptionFilter, narrow } from "../OptionFilter.tsx"; import { FILTER_FROM, OptionFilter, narrow } from "../OptionFilter.tsx";
import { ImageInput, LinkPreviewInput } from "./MediaLibrary.tsx"; import { ImageInput, LinkPreviewInput } from "./MediaLibrary.tsx";
import { ChooseFileButton } from "./DriveFiles.tsx"; import { ChooseFileButton } from "./DriveFiles.tsx";
import { siteUrl } from "../../lib/site.ts";
/* Live previews a collection can name with `preview`. Each gets the /* Live previews a collection can name with `preview`. Each gets the
row as the form holds it, which is the API's shape. */ row as the form holds it, which is the API's shape. */
@ -383,6 +390,7 @@ export function Field({ field, value, row, options, error, onChange, onPatch }:
value={value} value={value}
resolve={field.resolve} resolve={field.resolve}
folder={field.folder} folder={field.folder}
videoUrl={field.frameFrom && fieldShown({ when: field.frameWhen }, row) ? getPath(row, field.frameFrom) : null}
locked={locked} locked={locked}
className={locked ? inputLocked : common.className} className={locked ? inputLocked : common.className}
onChange={onChange} onChange={onChange}
@ -431,6 +439,21 @@ export function Field({ field, value, row, options, error, onChange, onPatch }:
<ChooseFileButton value={value} onPick={pickFile} /> <ChooseFileButton value={value} onPick={pickFile} />
</div> </div>
)} )}
{field.redirects && !locked && options?.redirects?.length > 0 && (
<select
value=""
onChange={(e) => e.target.value && onChange(siteUrl(`/go/${e.target.value}`))}
aria-label={`${typeof field.label === "function" ? field.label(row) : field.label}: pick a redirect`}
className={`mt-2 ${common.className}`}
>
<option value="">Pick a redirect (Data → Links/redirects)</option>
{options.redirects.map((option) => (
<option key={option.id} value={option.id}>
{option.label}
</option>
))}
</select>
)}
</div> </div>
{error ? ( {error ? (

View file

@ -24,7 +24,7 @@ export const HISTORY_DECADES: DecadeMeta[] = [
}, },
{ {
decade: 2010, decade: 2010,
title: 'Millennials run the show', title: 'Decade Title TBD',
tagline: 'A time of something', tagline: 'A time of something',
blurb: blurb:
'Need to update what happened here, mostly documented on facebook we asumme', 'Need to update what happened here, mostly documented on facebook we asumme',
@ -38,7 +38,7 @@ export const HISTORY_DECADES: DecadeMeta[] = [
}, },
{ {
decade: 1990, decade: 1990,
title: 'Before NGU there was YAU', title: 'Decade Title TBD',
tagline: 'Young adult ministry existed', tagline: 'Young adult ministry existed',
preProgram: true, preProgram: true,
blurb: blurb:
@ -46,7 +46,7 @@ export const HISTORY_DECADES: DecadeMeta[] = [
}, },
{ {
decade: 1980, decade: 1980,
title: 'YAU?', title: 'Decade Title TBD',
tagline: 'Young adult ministry existed', tagline: 'Young adult ministry existed',
preProgram: true, preProgram: true,
blurb: blurb:
@ -54,7 +54,7 @@ export const HISTORY_DECADES: DecadeMeta[] = [
}, },
{ {
decade: 1970, decade: 1970,
title: 'YAU?', title: 'Decade Title TBD',
tagline: 'Young adult ministry existed', tagline: 'Young adult ministry existed',
preProgram: true, preProgram: true,
blurb: blurb:

View file

@ -29,6 +29,7 @@ import { blogPosts } from "./adminSchema/blog.ts";
import { siteSettings } from "./adminSchema/siteSettings.ts"; import { siteSettings } from "./adminSchema/siteSettings.ts";
import { personTagTypes } from "./adminSchema/personTags.ts"; import { personTagTypes } from "./adminSchema/personTags.ts";
import { contactTypes } from "./adminSchema/contactTypes.ts"; import { contactTypes } from "./adminSchema/contactTypes.ts";
import { redirects } from "./adminSchema/redirects.ts";
import { import {
communityPage, communityPage,
retreatsPage, retreatsPage,
@ -43,6 +44,7 @@ export const ADMIN_ENTITIES: Record<string, any> = {
people, people,
person_tag_types: personTagTypes, person_tag_types: personTagTypes,
contact_types: contactTypes, contact_types: contactTypes,
redirects,
teams, teams,
awards, awards,
timeline, timeline,

View file

@ -107,6 +107,15 @@ export const frontPage = {
"A YouTube, Vimeo or Facebook link, or a video file: a filename in " + "A YouTube, Vimeo or Facebook link, or a video file: a filename in " +
"the uploads folder, or a link ending in .mp4 or .webm", "the uploads folder, or a link ending in .mp4 or .webm",
}, },
{
path: "video_captions",
label: "Video captions",
widget: "image",
folder: "captions",
resolve: mediaUrl,
full: true,
help: "A WebVTT (.vtt) file, for a video file; YouTube, Vimeo and Facebook show their own. Default: none.",
},
{ path: "video_title", label: "Video title", full: true, help: "Shown after \"Featured video\" above the headline" }, { path: "video_title", label: "Video title", full: true, help: "Shown after \"Featured video\" above the headline" },
{ {
path: "hero_event_id", path: "hero_event_id",

View file

@ -0,0 +1,55 @@
/* ── Links/redirects (068_redirects.sql) ─────────────────────────
Data → Links/redirects: short links on our own domain, /go/<URL ID>,
for the newsletter and anywhere a link should be counted. Each
click is counted here, sent to Plausible as a pageview of
/go/<URL ID>, and passed on with the link's UTM tags. Server side:
server/src/admin-schema/redirects.js and routes/redirects.js. */
import { SITE_ORIGIN, siteUrl } from "../site.ts";
const GO = `${SITE_ORIGIN.replace(/^https?:\/\//, "").replace(/\/$/, "")}/go/`;
export const redirects = {
key: "redirects",
label: "Links/redirects",
singular: "redirect",
idLabel: "URL ID",
idPrefix: GO,
// The address to share, copied from the saved redirect's page.
idLink: (id: string) => siteUrl(`/go/${id}`),
list: {
columns: [
{ key: "id", label: "Link", primary: true },
{ key: "target_url", label: "Goes to" },
{ key: "clicks", label: "Clicks" },
{ key: "last_clicked_at", label: "Last click" },
],
filters: [],
},
groups: [
{
legend: "Redirect",
fields: [
{
path: "target_url",
label: "Goes to",
required: true,
full: true,
help: "A web address, eg. https://ngu.churchcenter.com/registrations/events/123, or a page on this site, eg. /retreats",
},
{ path: "note", label: "Note", full: true, help: "What it's for, for us only. eg. October newsletter, retreat button" },
],
},
{
legend: "Tracking (UTM tags)",
note: "Added to the destination, so a click that lands on our site (or another one with analytics) is credited to where the link was shared. Clicks are counted either way.",
fields: [
{ path: "utm_source", label: "Source", help: "eg. newsletter. Default: none" },
{ path: "utm_medium", label: "Medium", help: "eg. email. Default: none" },
{ path: "utm_campaign", label: "Campaign", help: "eg. october-2026. Default: none" },
],
},
],
};

View file

@ -191,7 +191,9 @@ export const featuredCardsChild = {
widget: "image", widget: "image",
resolve: mediaUrl, resolve: mediaUrl,
full: true, full: true,
help: "Default: the record's own picture, or for a YouTube video, its thumbnail.", frameFrom: "url",
frameWhen: { path: "kind", value: "video" },
help: "Default: the record's own picture, or for a YouTube video, its thumbnail. For a video, Frame at takes a still from it instead.",
}, },
], ],
}; };
@ -394,6 +396,16 @@ export const blocksChild = {
help: (row) => help: (row) =>
row?.type === "video" ? "Still shown before it plays. Default: YouTube's own thumbnail." : undefined, row?.type === "video" ? "Still shown before it plays. Default: YouTube's own thumbnail." : undefined,
}, },
{
path: "captions",
label: "Captions",
widget: "image",
folder: "captions",
resolve: mediaUrl,
full: true,
when: { path: "type", value: "video" },
help: "A WebVTT (.vtt) file, for an uploaded video; YouTube, Vimeo and Facebook show their own. Default: none.",
},
{ {
path: "alt", path: "alt",
label: "Alt text", label: "Alt text",

View file

@ -15,7 +15,7 @@ const PRESETS = {
community_blog: "Community blog (its settings are below)", community_blog: "Community blog (its settings are below)",
group_map: "Local groups map", group_map: "Local groups map",
region_list: "Unity Regions list", region_list: "Unity Regions list",
partner_list: "Partner organization cards", partner_list: "Organization cards (partners, ministries)",
events: "Event carousel or grid", events: "Event carousel or grid",
timeline: "Timeline", timeline: "Timeline",
people_directory: "People directory (a tag's people)", people_directory: "People directory (a tag's people)",
@ -37,6 +37,7 @@ const EVENT_TYPES = [
]; ];
const EVENTS = { path: "preset", value: "events" }; const EVENTS = { path: "preset", value: "events" };
const CARDS = { path: "preset", value: "partner_list" };
const sectionsChild = (presets: string[]) => ({ const sectionsChild = (presets: string[]) => ({
key: "sections", key: "sections",
@ -113,6 +114,23 @@ const sectionsChild = (presets: string[]) => ({
}, },
] ]
: []), : []),
...(presets.includes("partner_list")
? [
{
path: "org_kinds",
label: "Cards: list",
widget: "select",
options: [
["partner", "Partners"],
["ministry", "Ministries"],
["partner,ministry", "Partners and ministries"],
],
blankLabel: "Default: Partners",
help: "Every published, listed one, by name. Organizations picked below replace this list.",
when: CARDS,
},
]
: []),
...(presets.includes("group_map") ...(presets.includes("group_map")
? [ ? [
{ {
@ -127,6 +145,16 @@ const sectionsChild = (presets: string[]) => ({
: []), : []),
], ],
children: [ children: [
{
key: "orgs",
label: "Cards: organizations",
note: "Picked here, these show instead of the list above, in this order: partners or ministries, published ones, listed or not.",
addLabel: "Add organization",
when: CARDS,
title: (row, options) => options?.card_orgs?.find((o) => o.id === row.org_id)?.label ?? "New organization",
blank: { org_id: "" },
fields: [{ path: "org_id", label: "Organization", widget: "select", optionsFrom: "card_orgs", required: true }],
},
{ {
...blocksChild, ...blocksChild,
label: "Blocks", label: "Blocks",

View file

@ -145,6 +145,33 @@ export const siteSettings = {
}, },
], ],
}, },
{
legend: "Reports",
fields: [
{
path: "report_daily",
label: "Daily analytics report",
widget: "select",
options: [
["on", "On"],
["off", "Off"],
],
blankLabel: "Default: off",
help: "Yesterday's visitors, pageviews and top pages from Plausible, posted to Discord each morning. Needs PLAUSIBLE_API_KEY and DISCORD_WEBHOOK_URL on the server (server/src/analyticsReport.js).",
},
{
path: "report_weekly",
label: "Weekly analytics report",
widget: "select",
options: [
["on", "On"],
["off", "Off"],
],
blankLabel: "Default: off",
help: "The last 7 days, with the change from the week before, posted to Discord each Monday morning.",
},
],
},
{ {
legend: "Notices", legend: "Notices",
fields: [ fields: [

21
src/lib/clock.ts Normal file
View file

@ -0,0 +1,21 @@
/* Times in a video, as typed and shown: Tools → Video clips and the
image field's frame picker. */
/* 83.5 → "1:23.5"; 3723 → "1:02:03". */
export function clock(seconds: number | null | undefined): string {
if (seconds == null || !Number.isFinite(seconds)) return "-";
const whole = Math.floor(seconds);
const tenths = Math.round((seconds - whole) * 10);
const h = Math.floor(whole / 3600);
const m = Math.floor((whole % 3600) / 60);
const s = whole % 60;
const ss = `${String(s).padStart(2, "0")}${tenths ? `.${tenths % 10}` : ""}`;
return h ? `${h}:${String(m).padStart(2, "0")}:${ss}` : `${m}:${ss}`;
}
/* "1:23.5", "83.5" or "1:02:03" → seconds; null when it isn't a time. */
export function parseClock(text: string): number | null {
const parts = text.trim().split(":");
if (!parts.length || parts.some((p) => !/^\d+(\.\d+)?$/.test(p))) return null;
return parts.reduce((total, part) => total * 60 + Number(part), 0);
}

View file

@ -26,8 +26,8 @@
cards and dividers (with their color, thickness and cards and dividers (with their color, thickness and
spacing); a video is its still linked to the video spacing); a video is its still linked to the video
Colors are the site's palette (STORED_PALETTE) or "none"; blank is the Colors are any hex color, picked in the builder, or "none"; blank
default. No unsubscribe link: Mailchimp adds its own to every send. is the default (EMAIL_COLOR). No unsubscribe link: Mailchimp adds its own to every send.
Email clients ignore stylesheets, CSS variables and most layout, Email clients ignore stylesheets, CSS variables and most layout,
so the HTML is tables with inline styles at 600px, images with so the HTML is tables with inline styles at 600px, images with
@ -104,7 +104,7 @@ export type Newsletter = {
} }
/* The palette as an inbox needs it. */ /* The palette as an inbox needs it. */
const COLOR = { export const EMAIL_COLOR = {
ink: '#001011', ink: '#001011',
body: '#003a45', body: '#003a45',
muted: '#3b5456', muted: '#3b5456',
@ -113,6 +113,7 @@ const COLOR = {
card: '#ffffff', card: '#ffffff',
rule: '#d6f5fa', rule: '#d6f5fa',
} }
const COLOR = EMAIL_COLOR
/* What each picks section is called and says on its buttons, unless /* What each picks section is called and says on its buttons, unless
the part says otherwise. */ the part says otherwise. */
@ -368,7 +369,7 @@ function partHtml(part: NewsletterPart, n: Newsletter): string {
case 'header': case 'header':
return headerHtml(part, n) return headerHtml(part, n)
case 'title': case 'title':
return `<tr><td style="padding:28px 24px 0;text-align:${alignOf(part)};"><h1 style="margin:0;font-family:${FONT};font-size:28px;line-height:34px;font-weight:700;color:${COLOR.ink};">${escape(part.text?.trim() || DEFAULT_TITLE(n.siteName))}</h1></td></tr>` return `<tr><td style="padding:28px 24px 0;text-align:${alignOf(part)};"><h1 style="margin:0;font-family:${FONT};font-size:28px;line-height:34px;font-weight:700;color:${colorOf(part.color, COLOR.ink) ?? COLOR.ink};">${escape(part.text?.trim() || DEFAULT_TITLE(n.siteName))}</h1></td></tr>`
case 'picks': case 'picks':
return picksHtml(part, n) return picksHtml(part, n)
case 'footer': case 'footer':

View file

@ -27,8 +27,11 @@ import { isBadId, orgHref } from "./hrefs.ts";
import { useResource } from "./useResource.ts"; import { useResource } from "./useResource.ts";
export function useOrganizations(kind) { /* `ids` (a hand-picked list) wins over `kind`. */
const path = kind export function useOrganizations(kind, ids?: string[]) {
const path = ids?.length
? `/organizations?ids=${ids.map(encodeURIComponent).join(",")}`
: kind
? `/organizations?kind=${encodeURIComponent(kind)}` ? `/organizations?kind=${encodeURIComponent(kind)}`
: "/organizations"; : "/organizations";

View file

@ -48,6 +48,8 @@ export type ContentBlock = {
team_id?: string | null team_id?: string | null
/** Who a quote is by. */ /** Who a quote is by. */
cite?: string | null cite?: string | null
/** A video block's WebVTT file, for an uploaded video (066). */
captions?: string | null
items?: ContentBlockItem[] items?: ContentBlockItem[]
} }

View file

@ -51,7 +51,7 @@ export type Hero = {
slides: HeroSlide[] slides: HeroSlide[]
livestream: { url: string; title?: string | null } | null livestream: { url: string; title?: string | null } | null
/** A link to embed or a video file; see videoSource in embeds.ts. */ /** A link to embed or a video file; see videoSource in embeds.ts. */
video: { url: string; title?: string | null } | null video: { url: string; title?: string | null; captions?: string | null } | null
/** With the 'event' feature: the pinned event, else the countdown's. */ /** With the 'event' feature: the pinned event, else the countdown's. */
event: HeroEvent | null event: HeroEvent | null
} }

View file

@ -17,6 +17,10 @@ export type SitePageSection = {
view?: string | null view?: string | null
/** A people_directory preset's tag (Data → People tags). */ /** A people_directory preset's tag (Data → People tags). */
tag_id?: string | null tag_id?: string | null
/** Organization cards: the kinds listed ('partner', 'ministry' or both, comma separated). */
org_kinds?: string | null
/** Organization cards: a hand-picked list, in order, shown instead. */
org_ids: string[]
blocks: ContentBlock[] blocks: ContentBlock[]
} }

View file

@ -7,4 +7,4 @@
box or a build banner can read the same value later. box or a build banner can read the same value later.
═══════════════════════════════════════════════════════════════ */ ═══════════════════════════════════════════════════════════════ */
export const SITE_VERSION = "NGU-Web.v1.13.0-data"; export const SITE_VERSION = "NGU-Web.v1.13.1-data";

View file

@ -234,10 +234,6 @@ function Facts({
<div className="flex flex-wrap items-center gap-x-6 gap-y-3 text-sm"> <div className="flex flex-wrap items-center gap-x-6 gap-y-3 text-sm">
{where && <span style={{ color: BODY }}>{where}</span>} {where && <span style={{ color: BODY }}>{where}</span>}
{org.kind === 'region' && org.details.scope && (
<span style={{ color: BODY }}>{org.details.scope}</span>
)}
{org.kind === 'group' && org.details.region_id && ( {org.kind === 'group' && org.details.region_id && (
<span style={{ color: BODY }}> <span style={{ color: BODY }}>
Part of{' '} Part of{' '}

View file

@ -66,10 +66,15 @@ const PRESETS: Record<string, (section: SitePageSection) => Record<string, any>>
], ],
}, },
}), }),
partner_list: () => ({ partner_list: (section) => ({
Component: OrgListCards, Component: OrgListCards,
request: { type: 'partner', label: 'Request a partner listing' }, request: { type: 'partner', label: 'Request a partner listing' },
props: { kind: 'partner', pageLabel: 'Partner page', empty: '· Partner organizations coming soon ·' }, props: {
kind: section.org_kinds || 'partner',
ids: section.org_ids,
pageLabel: 'Partner page',
empty: '· Organizations coming soon ·',
},
}), }),
events: (section) => ({ events: (section) => ({
Component: EventListCards, Component: EventListCards,

View file

@ -18,6 +18,7 @@ import { useCallback, useEffect, useRef, useState, type ReactNode } from "react"
import { Link } from "react-router-dom"; import { Link } from "react-router-dom";
import { ApiError, del, get, post } from "../../lib/api.ts"; import { ApiError, del, get, post } from "../../lib/api.ts";
import { clock, parseClock } from "../../lib/clock.ts";
import { accentText, BRAND } from '../../lib/color.ts' import { accentText, BRAND } from '../../lib/color.ts'
const MUTED = "var(--color-muted)"; const MUTED = "var(--color-muted)";
@ -56,25 +57,6 @@ const SHAPES: Array<[string, string, number | null]> = [
["vertical", "Vertical 9:16 (Reels, Shorts, TikTok)", 9 / 16], ["vertical", "Vertical 9:16 (Reels, Shorts, TikTok)", 9 / 16],
]; ];
/* 83.5 → "1:23.5"; 3723 → "1:02:03". */
function clock(seconds: number | null | undefined): string {
if (seconds == null || !Number.isFinite(seconds)) return "-";
const whole = Math.floor(seconds);
const tenths = Math.round((seconds - whole) * 10);
const h = Math.floor(whole / 3600);
const m = Math.floor((whole % 3600) / 60);
const s = whole % 60;
const ss = `${String(s).padStart(2, "0")}${tenths ? `.${tenths % 10}` : ""}`;
return h ? `${h}:${String(m).padStart(2, "0")}:${ss}` : `${m}:${ss}`;
}
/* "1:23.5", "83.5" or "1:02:03" → seconds; null when it isn't a time. */
function parseClock(text: string): number | null {
const parts = text.trim().split(":");
if (!parts.length || parts.some((p) => !/^\d+(\.\d+)?$/.test(p))) return null;
return parts.reduce((total, part) => total * 60 + Number(part), 0);
}
function sizeOf(bytes: number | null): string { function sizeOf(bytes: number | null): string {
if (!bytes) return ""; if (!bytes) return "";
return bytes > 1024 * 1024 * 1024 return bytes > 1024 * 1024 * 1024

View file

@ -42,11 +42,11 @@ import { mediaUrl } from '../../lib/media.ts'
import { SITE_NAME, SITE_ORIGIN, siteUrl } from '../../lib/site.ts' import { SITE_NAME, SITE_ORIGIN, siteUrl } from '../../lib/site.ts'
import { seriesLabel } from '../../lib/eventSeries.ts' import { seriesLabel } from '../../lib/eventSeries.ts'
import { useWideAdminPage } from '../../lib/adminWidth.tsx' import { useWideAdminPage } from '../../lib/adminWidth.tsx'
import { STORED_PALETTE } from '../../lib/color.ts'
import { PLATFORMS } from '../../lib/platforms.ts' import { PLATFORMS } from '../../lib/platforms.ts'
import { SOCIAL_LINKS } from '../../data/socialLinks.ts' import { SOCIAL_LINKS } from '../../data/socialLinks.ts'
import { import {
DEFAULT_TITLE, DEFAULT_TITLE,
EMAIL_COLOR,
newsletterHtml, newsletterHtml,
newsletterText, newsletterText,
newsletterTitle, newsletterTitle,
@ -85,18 +85,14 @@ const PART_TYPES: Array<[string, string, string]> = [
] ]
const partLabel = (type: string) => PART_TYPES.find(([value]) => value === type)?.[1] ?? type const partLabel = (type: string) => PART_TYPES.find(([value]) => value === type)?.[1] ?? type
/* The site's palette as choices; an inbox needs the hex itself, and /* A color picker: any hex color, which is what an inbox needs. Blank
the one stored, not a color blind mode's swap (color.ts). */ is `fallback`; `none` (where given) is typed as the word none. */
const SHADES = ['', ', darkest', ', light', ', lightest'] const colorField = (path: string, label: string, fallback: string, none: string | null, types: string[]) => ({
const PALETTE_OPTIONS = Object.entries(STORED_PALETTE).flatMap(([family, shades]) =>
shades.map((hex, i) => [hex, `${family[0].toUpperCase()}${family.slice(1)}${SHADES[i]}`]),
)
const colorField = (path: string, label: string, fallback: string, none: string, types: string[]) => ({
path, path,
label, label,
widget: 'select', widget: 'color',
options: [['none', none], ...PALETTE_OPTIONS], placeholder: fallback,
blankLabel: `Default: ${fallback}`, help: `Default: ${fallback}${none ? `. Type none for ${none}` : ''}`,
when: { path: 'type', value: types }, when: { path: 'type', value: types },
}) })
@ -107,7 +103,18 @@ const sourceOf = (part: NewsletterPart): PickSource => (SOURCES.includes(part.so
/* Every part is a row: one editor for blocks and the email's own /* Every part is a row: one editor for blocks and the email's own
parts, so any of them can be moved, copied or removed. */ parts, so any of them can be moved, copied or removed. */
const blockFields = blocksChild.fields.filter((field) => !['slot', 'team_id', 'type'].includes(field.path)) /* Every link a block or its items carry can be a short link
(Data → Links/redirects), so its clicks are counted. */
const LINK_PATHS = ['href', 'url']
const withRedirects = (field: any) => (LINK_PATHS.includes(field.path) ? { ...field, redirects: true } : field)
const withRedirectsChild = (child: any) => ({
...child,
fields: child.fields.map(withRedirects),
children: child.children?.map(withRedirectsChild),
})
const blockFields = blocksChild.fields
.filter((field) => !['slot', 'team_id', 'type', 'captions'].includes(field.path))
.map(withRedirects)
const PARTS_SPEC = { const PARTS_SPEC = {
key: 'parts', key: 'parts',
label: 'Parts', label: 'Parts',
@ -142,7 +149,7 @@ const PARTS_SPEC = {
when: { path: 'type', value: 'header' }, when: { path: 'type', value: 'header' },
help: "A PNG or JPEG: Gmail and Outlook don't show SVG. Default: none, the words alone", help: "A PNG or JPEG: Gmail and Outlook don't show SVG. Default: none, the words alone",
}, },
colorField('color', 'Band color', 'Teal, darkest', 'None: no band', ['header', 'social', 'countdown']), colorField('color', 'Band color', EMAIL_COLOR.body, 'no band', ['header', 'social', 'countdown']),
{ {
path: 'event', path: 'event',
label: 'Event', label: 'Event',
@ -154,6 +161,7 @@ const PARTS_SPEC = {
}, },
{ path: 'text', label: 'Words above', when: { path: 'type', value: 'countdown' }, help: "Default: the event's title" }, { path: 'text', label: 'Words above', when: { path: 'type', value: 'countdown' }, help: "Default: the event's title" },
{ path: 'text', label: 'Title', full: true, when: { path: 'type', value: 'title' }, help: `Default: ${DEFAULT_TITLE(SITE_NAME)}` }, { path: 'text', label: 'Title', full: true, when: { path: 'type', value: 'title' }, help: `Default: ${DEFAULT_TITLE(SITE_NAME)}` },
colorField('color', 'Title color', EMAIL_COLOR.ink, null, ['title']),
{ {
path: 'source', path: 'source',
label: 'Pick from', label: 'Pick from',
@ -174,8 +182,8 @@ const PARTS_SPEC = {
when: { path: 'type', value: 'picks' }, when: { path: 'type', value: 'picks' },
help: (row: NewsletterPart) => `On each card. Default: ${PICK_DEFAULTS[sourceOf(row)].cta}`, help: (row: NewsletterPart) => `On each card. Default: ${PICK_DEFAULTS[sourceOf(row)].cta}`,
}, },
colorField('rule', 'Heading underline', 'Teal, lightest', 'None: no line', ['picks']), colorField('rule', 'Heading underline', EMAIL_COLOR.rule, 'no line', ['picks']),
colorField('bar', 'Card bar', 'Teal', 'None: no bar', ['picks']), colorField('bar', 'Card bar', EMAIL_COLOR.teal, 'no bar', ['picks']),
{ {
path: 'text', path: 'text',
label: 'Footer', label: 'Footer',
@ -184,14 +192,14 @@ const PARTS_SPEC = {
when: { path: 'type', value: 'footer' }, when: { path: 'type', value: 'footer' },
help: `Default: ${SITE_NAME} and ${SITE_ORIGIN}`, help: `Default: ${SITE_NAME} and ${SITE_ORIGIN}`,
}, },
colorField('rule', 'Line above', 'Teal, lightest', 'None: no line', ['footer']), colorField('rule', 'Line above', EMAIL_COLOR.rule, 'no line', ['footer']),
...blockFields, ...blockFields,
colorField('color', 'Line color', 'Teal, lightest', 'None: space only', ['divider']), colorField('color', 'Line color', EMAIL_COLOR.rule, 'space only', ['divider']),
{ path: 'size', label: 'Thickness', widget: 'number', when: { path: 'type', value: 'divider' }, help: 'In pixels, 1 to 8. Default: 2' }, { path: 'size', label: 'Thickness', widget: 'number', when: { path: 'type', value: 'divider' }, help: 'In pixels, 1 to 8. Default: 2' },
{ path: 'space', label: 'Space above', widget: 'number', when: { path: 'type', value: 'divider' }, help: 'In pixels, 0 to 64. Default: 24' }, { path: 'space', label: 'Space above', widget: 'number', when: { path: 'type', value: 'divider' }, help: 'In pixels, 0 to 64. Default: 24' },
], ],
children: [ children: [
...(blocksChild.children ?? []), ...(blocksChild.children ?? []).map(withRedirectsChild),
{ {
key: 'socials', key: 'socials',
label: 'Links', label: 'Links',
@ -230,7 +238,7 @@ const STARTER: NewsletterPart[] = [
{ type: 'header' }, { type: 'header' },
{ type: 'title', text: '' }, { type: 'title', text: '' },
{ type: 'paragraph', text: '' }, { type: 'paragraph', text: '' },
{ type: 'picks', source: 'events', picked: [] }, { type: 'picks', picked: [] },
{ type: 'picks', source: 'posts', picked: [] }, { type: 'picks', source: 'posts', picked: [] },
{ type: 'picks', source: 'cards', picked: [] }, { type: 'picks', source: 'cards', picked: [] },
{ type: 'footer' }, { type: 'footer' },
@ -257,6 +265,7 @@ export default function AdminNewsletter() {
const [posts, setPosts] = useState<PostRow[] | null>(null) const [posts, setPosts] = useState<PostRow[] | null>(null)
const [postDetails, setPostDetails] = useState<Record<string, BlogPostRecord>>({}) const [postDetails, setPostDetails] = useState<Record<string, BlogPostRecord>>({})
const [copied, setCopied] = useState<'html' | 'text' | null>(null) const [copied, setCopied] = useState<'html' | 'text' | null>(null)
const [redirects, setRedirects] = useState<{ id: string; label: string }[]>([])
// The draft being edited: null is a new one, not saved yet. // The draft being edited: null is a new one, not saved yet.
const [drafts, setDrafts] = useState<DraftRow[]>([]) const [drafts, setDrafts] = useState<DraftRow[]>([])
@ -272,6 +281,9 @@ export default function AdminNewsletter() {
get('/admin/blog_posts?is_published=1&is_listed=1&limit=200', { ttl: 0 }) get('/admin/blog_posts?is_published=1&is_listed=1&limit=200', { ttl: 0 })
.then((data: { rows: PostRow[] }) => setPosts(data.rows)) .then((data: { rows: PostRow[] }) => setPosts(data.rows))
.catch(() => setPosts([])) .catch(() => setPosts([]))
get('/admin/options?only=redirects', { ttl: 0 })
.then((data: { options: { redirects: { id: string; label: string }[] } }) => setRedirects(data.options.redirects))
.catch(() => setRedirects([]))
}, []) }, [])
const loadDrafts = () => const loadDrafts = () =>
@ -287,7 +299,8 @@ export default function AdminNewsletter() {
if (row) { if (row) {
try { try {
const parsed = JSON.parse(row.layout || '[]') const parsed = JSON.parse(row.layout || '[]')
layout = Array.isArray(parsed) ? parsed : [] // Events is the blank choice of Pick from, so an older draft's 'events' reads as blank.
layout = Array.isArray(parsed) ? parsed.map((part) => (part.source === 'events' ? { ...part, source: '' } : part)) : []
} catch { } catch {
// A hand-edited draft: start its parts over. // A hand-edited draft: start its parts over.
} }
@ -307,7 +320,9 @@ export default function AdminNewsletter() {
} }
} }
async function save() { /* Over the open draft, or (`asNew`, or nothing open) as a new one,
leaving the open draft as it was last saved. */
async function save(asNew = false) {
setBusy(true) setBusy(true)
setMessage(null) setMessage(null)
const payload = { const payload = {
@ -315,12 +330,13 @@ export default function AdminNewsletter() {
layout: JSON.stringify(parts), layout: JSON.stringify(parts),
} }
try { try {
const data = draft const data =
draft && !asNew
? await patch(`/admin/newsletters/${draft.id}`, { ...payload, updated_at: draft.updated_at }) ? await patch(`/admin/newsletters/${draft.id}`, { ...payload, updated_at: draft.updated_at })
: await post('/admin/newsletters', payload) : await post('/admin/newsletters', payload)
fill(data.row) fill(data.row)
loadDrafts() loadDrafts()
setMessage({ tone: 'ok', text: 'Draft saved.' }) setMessage({ tone: 'ok', text: draft && asNew ? 'Saved as a new draft, now open.' : 'Draft saved.' })
} catch (err) { } catch (err) {
const fields = err instanceof ApiError && err.fields ? Object.values(err.fields).filter(Boolean).join(' ') : '' const fields = err instanceof ApiError && err.fields ? Object.values(err.fields).filter(Boolean).join(' ') : ''
setMessage({ tone: 'error', text: [err instanceof Error ? err.message : 'Couldn’t save.', fields].filter(Boolean).join(' ') }) setMessage({ tone: 'error', text: [err instanceof Error ? err.message : 'Couldn’t save.', fields].filter(Boolean).join(' ') })
@ -410,8 +426,9 @@ export default function AdminNewsletter() {
countdownEvents: events countdownEvents: events
.filter((event) => !event.is_series && event.starts_on) .filter((event) => !event.is_series && event.starts_on)
.map((event) => ({ id: event.id, label: [event.title, event.date_label].filter(Boolean).join(', ') })), .map((event) => ({ id: event.id, label: [event.title, event.date_label].filter(Boolean).join(', ') })),
redirects,
}), }),
[events, posts, cards], [events, posts, cards, redirects],
) )
const newsletter = useMemo(() => { const newsletter = useMemo(() => {
@ -526,10 +543,16 @@ export default function AdminNewsletter() {
</label> </label>
{canWrite(user) && ( {canWrite(user) && (
<> <>
<button type="button" onClick={save} className={button} disabled={busy}> <button type="button" onClick={() => save()} className={button} disabled={busy}>
<FloppyDisk weight="bold" aria-hidden="true" /> <FloppyDisk weight="bold" aria-hidden="true" />
{draft ? 'Save draft' : 'Save as a new draft'} {draft ? 'Save draft' : 'Save as a new draft'}
</button> </button>
{draft && (
<button type="button" onClick={() => save(true)} className={button} disabled={busy}>
<Copy weight="bold" aria-hidden="true" />
Save as a new draft
</button>
)}
<button type="button" onClick={postAsBlog} className={button} disabled={busy || empty}> <button type="button" onClick={postAsBlog} className={button} disabled={busy || empty}>
<Article weight="bold" aria-hidden="true" /> <Article weight="bold" aria-hidden="true" />
Post as blog post Post as blog post

View file

@ -46,7 +46,7 @@
why the array form exists and teams uses it. why the array form exists and teams uses it.
═══════════════════════════════════════════════════════════════ */ ═══════════════════════════════════════════════════════════════ */
import { ArrowLeft } from "@phosphor-icons/react"; import { ArrowLeft, Check, Copy } from "@phosphor-icons/react";
import { useCallback, useEffect, useMemo, useRef, useState } from "react"; import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import { useLocation, useNavigate, useParams } from "react-router-dom"; import { useLocation, useNavigate, useParams } from "react-router-dom";
@ -431,8 +431,10 @@ export default function EntityEdit() {
field={{ field={{
path: "id", path: "id",
label: manifest.idLabel, label: manifest.idLabel,
prefix: isNew && qualifierPaths.length ? prefixOf(form) || prefixHint : undefined, // A fixed lead-in shown in the box (redirects' domain/go/), or
prefixPending: isNew && !prefixOf(form), // the qualifiers' prefix as it fills in.
prefix: isNew ? (qualifierPaths.length ? prefixOf(form) || prefixHint : manifest.idPrefix) : undefined,
prefixPending: isNew && qualifierPaths.length > 0 && !prefixOf(form),
placeholder: isNew && qualifierPaths.length ? "board" : undefined, placeholder: isNew && qualifierPaths.length ? "board" : undefined,
readOnly: !isNew, readOnly: !isNew,
help: !isNew help: !isNew
@ -448,6 +450,7 @@ export default function EntityEdit() {
change("id", `${prefixOf(form)}${slugify(value)}`); change("id", `${prefixOf(form)}${slugify(value)}`);
}} }}
/> />
{!isNew && manifest.idLink && <CopyLink url={manifest.idLink(form.id)} />}
{!isNew && form.updated_at && ( {!isNew && form.updated_at && (
<p className="mt-2 text-xs text-muted"> <p className="mt-2 text-xs text-muted">
Last saved {form.updated_at} Last saved {form.updated_at}
@ -647,3 +650,26 @@ function RequestedChanges({ request, isNew, form, onUse, onAdd }: any) {
); );
} }
/* A saved record's own link (the manifest's `idLink`, eg. a redirect's
/go/ address), with a button to copy it. */
function CopyLink({ url }: { url: string }) {
const [copied, setCopied] = useState(false);
return (
<div className="mt-3 flex flex-wrap items-center gap-3">
<code className="break-all text-sm text-body">{url}</code>
<button
type="button"
onClick={() =>
navigator.clipboard?.writeText(url).then(() => {
setCopied(true);
setTimeout(() => setCopied(false), 1500);
})
}
className="btn inline-flex items-center gap-1.5 border border-link px-3 py-1 text-sm text-link transition-colors hover:bg-tint"
>
{copied ? <Check weight="bold" aria-hidden="true" /> : <Copy weight="bold" aria-hidden="true" />}
{copied ? "Copied" : "Copy link"}
</button>
</div>
);
}

View file

@ -85,6 +85,11 @@ export const DATA_NAV = {
label: "People tags", label: "People tags",
blurb: "Directories people can be tagged into, eg. Musicians. Who carries a tag is edited on the person.", blurb: "Directories people can be tagged into, eg. Musicians. Who carries a tag is edited on the person.",
}, },
{
to: "/admin/redirects",
label: "Links/redirects",
blurb: "Short /go/ links for the newsletter, with click counts, Plausible and UTM tracking.",
},
{ {
to: "/admin/blog_posts", to: "/admin/blog_posts",
label: "Blog posts", label: "Blog posts",

View file

@ -18,6 +18,7 @@ import { useReadingMode } from '../../lib/readingMode.ts'
page manifest and gets no control in its heading. page manifest and gets no control in its heading.
<OrgListCards kind="partner" pageLabel="Partner page" /> <OrgListCards kind="partner" pageLabel="Partner page" />
<OrgListCards ids={["unity-worldwide", "unity-of-x"]} /> in that order
Where the vertical list expands in place, a card links out. The Where the vertical list expands in place, a card links out. The
card carries as much as fits at a glance and the organization's card carries as much as fits at a glance and the organization's
@ -152,6 +153,7 @@ function Block({ title, orgs, accent, pageLabel, siteLabel }) {
export default function OrgListCards({ export default function OrgListCards({
kind, kind,
ids,
title, title,
groups, groups,
groupBy, groupBy,
@ -161,7 +163,7 @@ export default function OrgListCards({
sort = byName, sort = byName,
empty = "Nothing to show here yet.", empty = "Nothing to show here yet.",
}) { }) {
const { organizations, loading, error } = useOrganizations(kind); const { organizations, loading, error } = useOrganizations(kind, ids);
const shell = children => ( const shell = children => (
<div className="mx-auto px-8 md:px-12" style={{ maxWidth: GRID_MAX }}> <div className="mx-auto px-8 md:px-12" style={{ maxWidth: GRID_MAX }}>
@ -191,7 +193,12 @@ export default function OrgListCards({
); );
} }
const sorted = sort ? [...organizations].sort(sort) : organizations; // A hand-picked list keeps its order; anything else is sorted.
const sorted = ids?.length
? ids.flatMap((id) => organizations.filter((org) => org.id === id))
: sort
? [...organizations].sort(sort)
: organizations;
// No groups given means one undivided grid. // No groups given means one undivided grid.
if (!groups || !groupBy) { if (!groups || !groupBy) {

View file

@ -113,7 +113,7 @@ export default function HeroStage({ hero }: { hero: Hero | null }) {
{feature === 'video' && hero?.video && ( {feature === 'video' && hero?.video && (
<div className="lg:col-span-7"> <div className="lg:col-span-7">
<VideoFrame source={video} url={hero.video.url} title={hero.video.title} /> <VideoFrame source={video} url={hero.video.url} title={hero.video.title} captions={mediaUrl(hero.video.captions)} />
</div> </div>
)} )}
@ -498,10 +498,13 @@ function VideoFrame({
source, source,
url, url,
title, title,
captions,
}: { }: {
source: VideoSource | null source: VideoSource | null
url: string url: string
title?: string | null title?: string | null
/** A WebVTT file's URL; only a file plays it, an embed has its own. */
captions?: string | null
}) { }) {
return ( return (
<div <div
@ -517,7 +520,9 @@ function VideoFrame({
controls controls
playsInline playsInline
preload="metadata" preload="metadata"
/> >
{captions && <track kind="captions" src={captions} srcLang="en" label="Captions" default />}
</video>
) : source?.kind === 'embed' ? ( ) : source?.kind === 'embed' ? (
<VideoPlayer url={url} title={title || 'Featured video'} className="h-full" /> <VideoPlayer url={url} title={title || 'Featured video'} className="h-full" />
) : ( ) : (

View file

@ -22,6 +22,13 @@ export default defineConfig({
changeOrigin: false, changeOrigin: false,
xfwd: true, xfwd: true,
}, },
// Short links (server/src/routes/redirects.js): in production
// nginx's page block sends them to the API.
"/go": {
target: "http://127.0.0.1:3001",
changeOrigin: false,
xfwd: true,
},
// Uploaded images. nginx serves these in production; in dev // Uploaded images. nginx serves these in production; in dev
// the API does, so they go to the same place as /api. // the API does, so they go to the same place as /api.
"/uploads": { "/uploads": {