Compare commits
9 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| b42700a943 | |||
| f71952f838 | |||
| ade21425d4 | |||
| aaa3fd9ed1 | |||
| 7bad1e8293 | |||
| 55239ef1e9 | |||
| f75178de69 | |||
| fac9b96cca | |||
| ebe0c77f7e |
+8
-4
@@ -94,12 +94,16 @@ NFS_ADDR=
|
|||||||
NFS_EXPORT=
|
NFS_EXPORT=
|
||||||
NFS_VERSION=4
|
NFS_VERSION=4
|
||||||
|
|
||||||
# Advanced editor bridge (optional). LUMENROOM_URL is the base URL of the
|
# Advanced editor bridge (optional). LUMENROOM_URL is the browser-facing base
|
||||||
# separate Lumenroom deployment, e.g. http://edit.local:8787. BRIDGE_SECRET is a
|
# URL of Lumenroom, e.g. http://<lan-ip>:8787 or https://edit.example.org.
|
||||||
# long random string shared with that deployment; without both the "Advanced"
|
# BRIDGE_SECRET is a long random string shared by both containers; without both
|
||||||
# button reports that the editor is not configured.
|
# the "Advanced" button reports that the editor is not configured.
|
||||||
LUMENROOM_URL=
|
LUMENROOM_URL=
|
||||||
BRIDGE_SECRET=
|
BRIDGE_SECRET=
|
||||||
|
# Compose-only host publishing for the Lumenroom container. Bind it to loopback
|
||||||
|
# when a reverse proxy in front of it terminates TLS.
|
||||||
|
LUMENROOM_PORT=8787
|
||||||
|
LUMENROOM_BIND=0.0.0.0
|
||||||
|
|
||||||
# Observability (declared; no Sentry integration is wired yet)
|
# Observability (declared; no Sentry integration is wired yet)
|
||||||
SENTRY_DSN=
|
SENTRY_DSN=
|
||||||
|
|||||||
+2
-2
@@ -10,7 +10,7 @@ ENV NODE_ENV=production
|
|||||||
# ImageMagick's LibRaw delegate decodes camera RAW files for the in-app editor;
|
# ImageMagick's LibRaw delegate decodes camera RAW files for the in-app editor;
|
||||||
# sharp does the tone rendering and JPEG encode. The Postgres client provides
|
# sharp does the tone rendering and JPEG encode. The Postgres client provides
|
||||||
# pg_dump/psql for admin backups and restores; unzip reads restore packages.
|
# pg_dump/psql for admin backups and restores; unzip reads restore packages.
|
||||||
RUN apk add --no-cache imagemagick libraw ffmpeg postgresql16-client unzip
|
RUN apk add --no-cache imagemagick libraw ffmpeg exiv2 postgresql16-client unzip
|
||||||
# pnpm is how this project is built (see package.json scripts).
|
# pnpm is how this project is built (see package.json scripts).
|
||||||
RUN npm install -g pnpm@9.15.0
|
RUN npm install -g pnpm@9.15.0
|
||||||
|
|
||||||
@@ -29,7 +29,7 @@ RUN pnpm build
|
|||||||
# ---------------------------------------------------------------------------
|
# ---------------------------------------------------------------------------
|
||||||
FROM builder AS tools
|
FROM builder AS tools
|
||||||
ENV NODE_ENV=development
|
ENV NODE_ENV=development
|
||||||
CMD ["sh", "-c", "pnpm db:migrate && pnpm db:seed"]
|
CMD ["pnpm", "db:migrate"]
|
||||||
|
|
||||||
FROM base AS runner
|
FROM base AS runner
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
|
|||||||
@@ -13,6 +13,7 @@ Built with Next.js 15, React 19, TypeScript, PostgreSQL 16, and Drizzle ORM. It
|
|||||||
- [Features](#features)
|
- [Features](#features)
|
||||||
- [Stack](#stack)
|
- [Stack](#stack)
|
||||||
- [Quick start (Docker)](#quick-start-docker)
|
- [Quick start (Docker)](#quick-start-docker)
|
||||||
|
- [Deploying the combined stack on another system](#deploying-the-combined-stack-on-another-system)
|
||||||
- [Local development](#local-development)
|
- [Local development](#local-development)
|
||||||
- [Configuration](#configuration)
|
- [Configuration](#configuration)
|
||||||
- [Email delivery](#email-delivery)
|
- [Email delivery](#email-delivery)
|
||||||
@@ -67,9 +68,9 @@ Built with Next.js 15, React 19, TypeScript, PostgreSQL 16, and Drizzle ORM. It
|
|||||||
|
|
||||||
### Events and media
|
### Events and media
|
||||||
|
|
||||||
- One-off events with a shot brief, location, times, photographer/editor assignments, and per-event shared folders.
|
- One-off events with a shot brief, location, times, photographer/editor assignments, and a single shared photo gallery per event.
|
||||||
- RAW and JPEG uploads streamed to disk, SHA-256 dedupe per folder, authenticated downloads, and manager-only event deletion with file cleanup.
|
- RAW and JPEG uploads streamed to disk, SHA-256 dedupe per event, authenticated downloads, and manager-only event deletion with file cleanup.
|
||||||
- Photo gallery with cached grid thumbnails (RAW included), preview, non-destructive adjustments/presets, export, per-folder or whole-event ZIP download, and filing a finished event into a dated delivery folder with a manifest. Every photo and video byte lives on the configured media storage share — never in container-local storage.
|
- Photo gallery with cached grid thumbnails (RAW included), preview, non-destructive adjustments/presets, export, whole-event or edited-only ZIP download, and filing a finished event into a dated delivery folder with a manifest. Every photo and video byte lives on the configured media storage share — never in container-local storage.
|
||||||
- Video upload with FFmpeg probe/transcode to web H.264/AAC, generated poster, non-destructive trim re-render, and retry after a failed encode.
|
- Video upload with FFmpeg probe/transcode to web H.264/AAC, generated poster, non-destructive trim re-render, and retry after a failed encode.
|
||||||
- Media visibility: team-only, unlisted link, or public. Ready public videos get `/watch/<id>`, a minimal `/embed/<id>` iframe, and an oEmbed endpoint.
|
- Media visibility: team-only, unlisted link, or public. Ready public videos get `/watch/<id>`, a minimal `/embed/<id>` iframe, and an oEmbed endpoint.
|
||||||
- Announcements feed with draft/publish/delete for coordinators and admins.
|
- Announcements feed with draft/publish/delete for coordinators and admins.
|
||||||
@@ -108,12 +109,21 @@ cp .env.example .env
|
|||||||
docker compose up -d db
|
docker compose up -d db
|
||||||
docker compose --profile tools build migrate
|
docker compose --profile tools build migrate
|
||||||
docker compose --profile tools run --rm migrate # migrations + seed
|
docker compose --profile tools run --rm migrate # migrations + seed
|
||||||
docker compose up -d --build app
|
docker compose up -d --build app lumenroom
|
||||||
```
|
```
|
||||||
|
|
||||||
Open <http://localhost:3000>. The app publishes on host port `3000`; Postgres is published on `5433` but bound to `127.0.0.1` by default (set `POSTGRES_BIND=0.0.0.0` only if another host must reach it).
|
Open <http://localhost:3000>. The advanced photo editor (Lumenroom) is the
|
||||||
|
vendored second container and publishes on <http://localhost:8787>; it is
|
||||||
|
optional, and the **Advanced** button stays disabled until `BRIDGE_SECRET` and
|
||||||
|
`LUMENROOM_URL` are set in `.env` (see [step 15](#15-advanced-photo-editor-bridge-optional)).
|
||||||
|
The app publishes on host port `3000`; Postgres is published on `5433` but bound to `127.0.0.1` by default (set `POSTGRES_BIND=0.0.0.0` only if another host must reach it).
|
||||||
|
|
||||||
With the default local configuration (`MAGIC_LINK_DEV_TRANSPORT=true`), requesting a sign-in link shows it in the browser and prints it in the app log:
|
```bash
|
||||||
|
curl -fsS http://localhost:3000/api/health # dashboard
|
||||||
|
curl -fsS http://localhost:8787/api/health # advanced editor
|
||||||
|
```
|
||||||
|
|
||||||
|
With the default local configuration (`MAGIC_LINK_DEV_TRANSPORT=true`), requesting a sign-in link prints it in the app log:
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
docker compose logs -f app
|
docker compose logs -f app
|
||||||
@@ -123,6 +133,93 @@ Sign in with the seeded admin, `admin@glenloch.local`. Other seeded accounts: `c
|
|||||||
|
|
||||||
Migrations are **not** run automatically by `docker compose up`. Re-run the `migrate` command after pulling schema changes. The seed is idempotent.
|
Migrations are **not** run automatically by `docker compose up`. Re-run the `migrate` command after pulling schema changes. The seed is idempotent.
|
||||||
|
|
||||||
|
## Deploying the combined stack on another system
|
||||||
|
|
||||||
|
One clone deploys everything: the dashboard (`app`), the advanced photo editor
|
||||||
|
(`lumenroom`, vendored under `lumenroom/`) and PostgreSQL (`db`). The detailed
|
||||||
|
Ubuntu walkthrough below covers each step; this is the short version for moving
|
||||||
|
the stack to a new host.
|
||||||
|
|
||||||
|
**What the target host needs**
|
||||||
|
|
||||||
|
- Docker Engine 24+ with Compose v2, and sudo access.
|
||||||
|
- A DNS name per app (for example `media.example.org` and `edit.example.org`),
|
||||||
|
or the host's LAN IP if it is not exposed to the internet.
|
||||||
|
- Inbound TCP 80 and 443 only. Ports 3000, 5433 and 8787 stay on the private
|
||||||
|
interface (`APP_BIND`, `POSTGRES_BIND`, `LUMENROOM_BIND` = `127.0.0.1`).
|
||||||
|
- The media export mounted on the host for original photos and videos
|
||||||
|
([step 9](#9-media-storage-on-nfs-or-a-local-path-required-for-event-media)).
|
||||||
|
|
||||||
|
**Get the code and secrets**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
git clone <repository-url> /opt/glenloch-media
|
||||||
|
cd /opt/glenloch-media
|
||||||
|
cp .env.example .env
|
||||||
|
chmod 600 .env
|
||||||
|
|
||||||
|
openssl rand -base64 32 # NEXTAUTH_SECRET
|
||||||
|
openssl rand -hex 32 # CRON_SECRET
|
||||||
|
openssl rand -hex 24 # POSTGRES_PASSWORD (hex avoids URL encoding)
|
||||||
|
openssl rand -hex 32 # BRIDGE_SECRET, shared by app and lumenroom
|
||||||
|
```
|
||||||
|
|
||||||
|
Minimum `.env` for both containers:
|
||||||
|
|
||||||
|
```dotenv
|
||||||
|
NEXTAUTH_URL=https://media.example.org
|
||||||
|
NEXTAUTH_SECRET=<base64 value>
|
||||||
|
PUBLIC_ORIGIN=https://media.example.org
|
||||||
|
APP_ORIGIN=https://media.example.org
|
||||||
|
APP_BIND=127.0.0.1
|
||||||
|
POSTGRES_BIND=127.0.0.1
|
||||||
|
POSTGRES_USER=media
|
||||||
|
POSTGRES_PASSWORD=<hex value>
|
||||||
|
POSTGRES_DB=media
|
||||||
|
DATABASE_URL=postgres://media:<hex value>@localhost:5433/media
|
||||||
|
CRON_SECRET=<hex value>
|
||||||
|
MEDIA_ARCHIVE_DIR=/mnt/glenloch-media
|
||||||
|
|
||||||
|
# Advanced editor bridge
|
||||||
|
LUMENROOM_URL=https://edit.example.org
|
||||||
|
LUMENROOM_BIND=127.0.0.1
|
||||||
|
BRIDGE_SECRET=<hex value>
|
||||||
|
```
|
||||||
|
|
||||||
|
`BRIDGE_SECRET` is passed to both services from this one value; they must match.
|
||||||
|
`LUMENROOM_URL` is the browser-facing editor address, while the app reaches
|
||||||
|
Lumenroom inside the Compose network by service name.
|
||||||
|
|
||||||
|
**Build, migrate, start**
|
||||||
|
|
||||||
|
```bash
|
||||||
|
docker compose config --quiet
|
||||||
|
docker compose up -d db
|
||||||
|
docker compose --profile tools build migrate
|
||||||
|
docker compose --profile tools run --rm migrate
|
||||||
|
docker compose up -d --build app lumenroom
|
||||||
|
docker compose ps
|
||||||
|
curl -fsS http://127.0.0.1:3000/api/health
|
||||||
|
curl -fsS http://127.0.0.1:8787/api/health
|
||||||
|
```
|
||||||
|
|
||||||
|
Both `app` and `lumenroom` must be `healthy`. `docker compose up -d --build`
|
||||||
|
without a service name also works and builds both images; naming them is just an
|
||||||
|
explicit version of the same command.
|
||||||
|
|
||||||
|
**Finish and verify**
|
||||||
|
|
||||||
|
1. Complete first sign-in and admin bootstrap ([step 5](#5-first-sign-in-and-admin-bootstrap)).
|
||||||
|
2. Save the media share in Settings → Media storage ([step 9](#9-media-storage-on-nfs-or-a-local-path-required-for-event-media)).
|
||||||
|
3. Put both hostnames in the reverse proxy ([step 6](#6-reverse-proxy-and-tls-with-caddy)) and reload Caddy.
|
||||||
|
4. Open an event photo and click **Advanced**: the editor should open in a new tab, already signed in, with a banner showing **Save to event**. If it reports the editor is not configured, `BRIDGE_SECRET` or `LUMENROOM_URL` is missing or the two secrets differ.
|
||||||
|
|
||||||
|
**Moving an existing installation.** Run Admin → Backup & restore on the old
|
||||||
|
host, copy the ZIP and `.env` (especially `NEXTAUTH_SECRET`) to the new host,
|
||||||
|
bring the stack up as above, then restore through the same admin panel. Original
|
||||||
|
media comes from the ZIP or the share itself. The `lumenroom-data` volume holds
|
||||||
|
only temporary bridge data and does not need to move.
|
||||||
|
|
||||||
## Local development
|
## Local development
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
@@ -168,7 +265,7 @@ Copy `.env.example` to `.env`; never commit real secrets (`.env*` is ignored, `.
|
|||||||
| `APP_ORIGIN` | Fallback application origin. |
|
| `APP_ORIGIN` | Fallback application origin. |
|
||||||
| `CHURCH_TIMEZONE` | Display timezone; scheduling itself stores UTC instants and local dates. Defaults to `America/New_York`. |
|
| `CHURCH_TIMEZONE` | Display timezone; scheduling itself stores UTC instants and local dates. Defaults to `America/New_York`. |
|
||||||
| `AUTO_ACTIVATE_NEW_USERS` | `false` (default) sends unknown emails to `pending_approval`; `true` is for dev/test only. |
|
| `AUTO_ACTIVATE_NEW_USERS` | `false` (default) sends unknown emails to `pending_approval`; `true` is for dev/test only. |
|
||||||
| `MAGIC_LINK_DEV_TRANSPORT` | Shows/prints the sign-in link instead of emailing it. Defaults on outside production; compose sets `true` for first login. |
|
| `MAGIC_LINK_DEV_TRANSPORT` | Returns/prints the sign-in link instead of emailing it; the login page never displays it. Defaults on outside production; compose sets `true` for first login. |
|
||||||
| `ALLOW_DEV_RESET` | Enables the destructive `POST /api/dev/reset` endpoint. Must stay `false` in real deployments. |
|
| `ALLOW_DEV_RESET` | Enables the destructive `POST /api/dev/reset` endpoint. Must stay `false` in real deployments. |
|
||||||
| `CRON_SECRET` | Bearer/query secret for the cron HTTP routes. Empty means session-only. |
|
| `CRON_SECRET` | Bearer/query secret for the cron HTTP routes. Empty means session-only. |
|
||||||
| `POSTMARK_SERVER_TOKEN`, `POSTMARK_FROM` | Optional Postmark fallback and default sender. Admin email settings take precedence. |
|
| `POSTMARK_SERVER_TOKEN`, `POSTMARK_FROM` | Optional Postmark fallback and default sender. Admin email settings take precedence. |
|
||||||
@@ -176,6 +273,8 @@ Copy `.env.example` to `.env`; never commit real secrets (`.env*` is ignored, `.
|
|||||||
| `UPLOAD_DIR` | Training attachments only (`/tmp/uploads` in compose). Event photos and videos never live here. |
|
| `UPLOAD_DIR` | Training attachments only (`/tmp/uploads` in compose). Event photos and videos never live here. |
|
||||||
| `ARCHIVE_DIR`, `NFS_SHARE`, `ARCHIVE_FOLDER` | Mount path inside the container, the reported share, and the default folder. This is the primary storage for original event photos and videos; a named share plus a writable path is required or uploads and photo editing stay disabled. |
|
| `ARCHIVE_DIR`, `NFS_SHARE`, `ARCHIVE_FOLDER` | Mount path inside the container, the reported share, and the default folder. This is the primary storage for original event photos and videos; a named share plus a writable path is required or uploads and photo editing stay disabled. |
|
||||||
| `MEDIA_ARCHIVE_DIR` | **Compose-only host path** mounted at `/archive` for the NFS export. |
|
| `MEDIA_ARCHIVE_DIR` | **Compose-only host path** mounted at `/archive` for the NFS export. |
|
||||||
|
| `LUMENROOM_URL`, `BRIDGE_SECRET` | Advanced editor bridge: the browser-facing address of the Lumenroom container and the shared token secret. Both are required for the **Advanced** button; leave empty to run without the editor. |
|
||||||
|
| `LUMENROOM_PORT`, `LUMENROOM_BIND` | **Compose-only** host publishing for Lumenroom. Default `8787` on all interfaces; set `127.0.0.1` behind a reverse proxy. |
|
||||||
| `SENTRY_DSN` | Declared but not wired to any integration. |
|
| `SENTRY_DSN` | Declared but not wired to any integration. |
|
||||||
|
|
||||||
Volumes in Compose: `pgdata`, `outbox-data`, `uploads-data`, and either `archive-data` or the host `MEDIA_ARCHIVE_DIR` bind mount (the latter is what holds original photos and videos). Back these up together.
|
Volumes in Compose: `pgdata`, `outbox-data`, `uploads-data`, and either `archive-data` or the host `MEDIA_ARCHIVE_DIR` bind mount (the latter is what holds original photos and videos). Back these up together.
|
||||||
@@ -327,6 +426,11 @@ MAGIC_LINK_DEV_TRANSPORT=true
|
|||||||
CRON_SECRET=<hex value>
|
CRON_SECRET=<hex value>
|
||||||
POSTMARK_FROM=media@example.org
|
POSTMARK_FROM=media@example.org
|
||||||
# POSTMARK_SERVER_TOKEN=... # optional; Gmail can be configured in Admin instead
|
# POSTMARK_SERVER_TOKEN=... # optional; Gmail can be configured in Admin instead
|
||||||
|
|
||||||
|
# Advanced photo editor (optional; omit to run without it)
|
||||||
|
LUMENROOM_URL=https://edit.example.org
|
||||||
|
LUMENROOM_BIND=127.0.0.1
|
||||||
|
BRIDGE_SECRET=<hex value>
|
||||||
```
|
```
|
||||||
|
|
||||||
Notes:
|
Notes:
|
||||||
@@ -348,9 +452,10 @@ docker compose config --quiet
|
|||||||
docker compose up -d db
|
docker compose up -d db
|
||||||
docker compose --profile tools build migrate
|
docker compose --profile tools build migrate
|
||||||
docker compose --profile tools run --rm migrate
|
docker compose --profile tools run --rm migrate
|
||||||
docker compose up -d --build app
|
docker compose up -d --build app lumenroom
|
||||||
docker compose ps
|
docker compose ps
|
||||||
curl -fsS http://127.0.0.1:3000/api/health
|
curl -fsS http://127.0.0.1:3000/api/health
|
||||||
|
curl -fsS http://127.0.0.1:8787/api/health
|
||||||
```
|
```
|
||||||
|
|
||||||
Rebuild `migrate` as shown; `docker compose run` reuses the last built tools image, so without the build step an update can run stale seed code against a newer schema.
|
Rebuild `migrate` as shown; `docker compose run` reuses the last built tools image, so without the build step an update can run stale seed code against a newer schema.
|
||||||
@@ -365,7 +470,7 @@ Keep the app on loopback and use an SSH tunnel for this step:
|
|||||||
ssh -L 3000:127.0.0.1:3000 you@media.example.org
|
ssh -L 3000:127.0.0.1:3000 you@media.example.org
|
||||||
```
|
```
|
||||||
|
|
||||||
Open `http://localhost:3000/login`, request a link for `admin@glenloch.local`, and read it from the page or from `docker compose logs app`. Then:
|
Open `http://localhost:3000/login`, request a link for `admin@glenloch.local`, and read it from `docker compose logs app`. Then:
|
||||||
|
|
||||||
1. Admin → People: change the admin name and email to the real person, and create real accounts.
|
1. Admin → People: change the admin name and email to the real person, and create real accounts.
|
||||||
2. Admin → Services: set real service times, roles, and headcounts.
|
2. Admin → Services: set real service times, roles, and headcounts.
|
||||||
@@ -378,7 +483,7 @@ Only after that, set `MAGIC_LINK_DEV_TRANSPORT=false` in `.env` and restart:
|
|||||||
docker compose up -d app
|
docker compose up -d app
|
||||||
```
|
```
|
||||||
|
|
||||||
**Do not expose the app publicly while the dev transport is on:** it displays sign-in links in the browser. Keep `APP_BIND=127.0.0.1` until bootstrap is finished.
|
**Do not expose the app publicly while the dev transport is on:** it can return and log sign-in links during bootstrap. Keep `APP_BIND=127.0.0.1` until bootstrap is finished.
|
||||||
|
|
||||||
### 6. Reverse proxy and TLS with Caddy
|
### 6. Reverse proxy and TLS with Caddy
|
||||||
|
|
||||||
@@ -401,8 +506,18 @@ media.example.org {
|
|||||||
encode zstd gzip
|
encode zstd gzip
|
||||||
reverse_proxy 127.0.0.1:3000
|
reverse_proxy 127.0.0.1:3000
|
||||||
}
|
}
|
||||||
|
|
||||||
|
edit.example.org {
|
||||||
|
reverse_proxy 127.0.0.1:8787
|
||||||
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
|
The second site is the advanced editor. Give it the same pattern as the app:
|
||||||
|
set `LUMENROOM_BIND=127.0.0.1` and `LUMENROOM_URL=https://edit.example.org`, and
|
||||||
|
point DNS for that hostname at the server too. If you leave the editor out,
|
||||||
|
remove its site block and set no `BRIDGE_SECRET`; the **Advanced** button then
|
||||||
|
reports that the editor is not configured.
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
sudo caddy validate --config /etc/caddy/Caddyfile
|
sudo caddy validate --config /etc/caddy/Caddyfile
|
||||||
sudo systemctl reload caddy
|
sudo systemctl reload caddy
|
||||||
@@ -421,7 +536,7 @@ sudo ufw enable
|
|||||||
sudo ufw status
|
sudo ufw status
|
||||||
```
|
```
|
||||||
|
|
||||||
`APP_BIND=127.0.0.1` and `POSTGRES_BIND=127.0.0.1` keep the app and database off the public interface.
|
`APP_BIND=127.0.0.1`, `LUMENROOM_BIND=127.0.0.1` and `POSTGRES_BIND=127.0.0.1` keep the app, the editor and the database off the public interface; only Caddy listens on 80/443.
|
||||||
|
|
||||||
### 8. Background jobs (cron)
|
### 8. Background jobs (cron)
|
||||||
|
|
||||||
@@ -541,6 +656,10 @@ Use Admin → Backup & restore to download a ZIP of the database dump, uploads,
|
|||||||
|
|
||||||
At minimum, back up after every schedule/training/media milestone and before every upgrade. The database, uploads, and archive volumes live under Docker's volume directory; the application-level ZIP is the supported portable backup.
|
At minimum, back up after every schedule/training/media milestone and before every upgrade. The database, uploads, and archive volumes live under Docker's volume directory; the application-level ZIP is the supported portable backup.
|
||||||
|
|
||||||
|
The `lumenroom-data` volume is different: it holds only Lumenroom's temporary
|
||||||
|
bridge catalog, cached previews and thumbnails, so it can be left out of backups
|
||||||
|
and rebuilt by opening events again.
|
||||||
|
|
||||||
### 12. Updating the deployment
|
### 12. Updating the deployment
|
||||||
|
|
||||||
Take a backup, then:
|
Take a backup, then:
|
||||||
@@ -550,9 +669,10 @@ cd /opt/glenloch-media
|
|||||||
git pull --ff-only
|
git pull --ff-only
|
||||||
docker compose --profile tools build migrate
|
docker compose --profile tools build migrate
|
||||||
docker compose --profile tools run --rm migrate
|
docker compose --profile tools run --rm migrate
|
||||||
docker compose up -d --build app
|
docker compose up -d --build app lumenroom
|
||||||
docker compose ps
|
docker compose ps
|
||||||
curl -fsS http://127.0.0.1:3000/api/health
|
curl -fsS http://127.0.0.1:3000/api/health
|
||||||
|
curl -fsS http://127.0.0.1:8787/api/health
|
||||||
```
|
```
|
||||||
|
|
||||||
`migrate` is idempotent and also runs the seed, which does not duplicate authored lessons or existing rows. If a release is bad, rebuild the previous commit:
|
`migrate` is idempotent and also runs the seed, which does not duplicate authored lessons or existing rows. If a release is bad, rebuild the previous commit:
|
||||||
@@ -560,7 +680,7 @@ curl -fsS http://127.0.0.1:3000/api/health
|
|||||||
```bash
|
```bash
|
||||||
git log --oneline -5
|
git log --oneline -5
|
||||||
git checkout <previous-commit>
|
git checkout <previous-commit>
|
||||||
docker compose up -d --build app
|
docker compose up -d --build app lumenroom
|
||||||
# after fixing:
|
# after fixing:
|
||||||
git switch main
|
git switch main
|
||||||
```
|
```
|
||||||
@@ -578,6 +698,8 @@ git switch main
|
|||||||
| Uploads/editing are disabled | Settings → Media storage needs a share name and a mounted path that UID 100 can write to; the banner states the exact failure. |
|
| Uploads/editing are disabled | Settings → Media storage needs a share name and a mounted path that UID 100 can write to; the banner states the exact failure. |
|
||||||
| Uploads are blocked with "not a network mount" | The export is not actually mounted: either add `docker-compose.nfs.yml` (`NFS_ADDR`/`NFS_EXPORT`) or mount it on the host and point `MEDIA_ARCHIVE_DIR` at that mount. `docker compose exec app grep ' /archive ' /proc/self/mounts` shows what the container really has. |
|
| Uploads are blocked with "not a network mount" | The export is not actually mounted: either add `docker-compose.nfs.yml` (`NFS_ADDR`/`NFS_EXPORT`) or mount it on the host and point `MEDIA_ARCHIVE_DIR` at that mount. `docker compose exec app grep ' /archive ' /proc/self/mounts` shows what the container really has. |
|
||||||
| Cron returns 401 | `CRON_SECRET` is set in `.env` and matches the value read by `/usr/local/bin/media-hub-cron`. |
|
| Cron returns 401 | `CRON_SECRET` is set in `.env` and matches the value read by `/usr/local/bin/media-hub-cron`. |
|
||||||
|
| **Advanced** reports the editor is not configured | `LUMENROOM_URL` and `BRIDGE_SECRET` are set in the app's environment, and Lumenroom has the same `BRIDGE_SECRET`. Restart both: `docker compose up -d app lumenroom`. |
|
||||||
|
| Advanced opens but the editor fails to load or is blank | `docker compose ps` should show `lumenroom` as `healthy`; `curl -fsS http://127.0.0.1:8787/api/health`; check `LUMENROOM_URL` is reachable from users' browsers and the proxy forwards `edit.example.org` to `127.0.0.1:8787`. |
|
||||||
| Disk filling up | Docker log rotation is capped at 10 MB × 3 per service; remove old backups, exports, and unused media. |
|
| Disk filling up | Docker log rotation is capped at 10 MB × 3 per service; remove old backups, exports, and unused media. |
|
||||||
|
|
||||||
### 14. Production checklist
|
### 14. Production checklist
|
||||||
@@ -592,6 +714,8 @@ git switch main
|
|||||||
- [ ] Cron jobs installed and returning success.
|
- [ ] Cron jobs installed and returning success.
|
||||||
- [ ] Backup downloaded, stored off-host, and restore tested once.
|
- [ ] Backup downloaded, stored off-host, and restore tested once.
|
||||||
- [ ] Media storage share configured in Settings → Media storage and writable (required for event photos and videos).
|
- [ ] Media storage share configured in Settings → Media storage and writable (required for event photos and videos).
|
||||||
|
- [ ] `LUMENROOM_BIND=127.0.0.1`, `LUMENROOM_URL` set to the editor's HTTPS origin, and `BRIDGE_SECRET` identical in both containers.
|
||||||
|
- [ ] `edit.example.org` (or the chosen editor hostname) proxies to `127.0.0.1:8787`, and **Advanced** opens the editor signed in.
|
||||||
- [ ] The `/api/dev/*` prefix is historical: the guards, not the URL, are the security boundary.
|
- [ ] The `/api/dev/*` prefix is historical: the guards, not the URL, are the security boundary.
|
||||||
|
|
||||||
### 15. Advanced photo editor bridge (optional)
|
### 15. Advanced photo editor bridge (optional)
|
||||||
@@ -610,12 +734,16 @@ that bridge session expires (12 hours by default).
|
|||||||
|
|
||||||
**One deployment.** Lumenroom is vendored under `lumenroom/`, and
|
**One deployment.** Lumenroom is vendored under `lumenroom/`, and
|
||||||
`docker-compose.yml` builds it as a second service next to the app. One clone
|
`docker-compose.yml` builds it as a second service next to the app. One clone
|
||||||
and one command deploy both:
|
and one command deploy both (add `--build` when the sources changed):
|
||||||
|
|
||||||
```bash
|
```bash
|
||||||
docker compose up -d --build
|
docker compose up -d --build app lumenroom
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Deployment steps are in [Deploying the combined stack on another
|
||||||
|
system](#deploying-the-combined-stack-on-another-system); the editor only needs
|
||||||
|
the extra `LUMENROOM_*` and `BRIDGE_SECRET` values shown there.
|
||||||
|
|
||||||
Values in `.env` (all optional except the secret):
|
Values in `.env` (all optional except the secret):
|
||||||
|
|
||||||
```dotenv
|
```dotenv
|
||||||
@@ -692,7 +820,7 @@ that the gallery shows.
|
|||||||
│ ├── domain/ Pure, unit-tested business rules
|
│ ├── domain/ Pure, unit-tested business rules
|
||||||
│ └── lib/ Timezone, tokens, email, storage, media, backup helpers
|
│ └── lib/ Timezone, tokens, email, storage, media, backup helpers
|
||||||
├── Dockerfile Multi-stage build; tools stage for migrations
|
├── Dockerfile Multi-stage build; tools stage for migrations
|
||||||
├── docker-compose.yml App + Postgres + one-shot migrate/seed
|
├── docker-compose.yml App + Lumenroom + Postgres + one-shot migrate/seed
|
||||||
├── drizzle.config.ts
|
├── drizzle.config.ts
|
||||||
├── next.config.ts
|
├── next.config.ts
|
||||||
├── playwright.config.ts
|
├── playwright.config.ts
|
||||||
@@ -709,7 +837,7 @@ that the gallery shows.
|
|||||||
| `/schedule/print`, `/run-sheet/[instanceId]` | Printable roster and editable run sheet |
|
| `/schedule/print`, `/run-sheet/[instanceId]` | Printable roster and editable run sheet |
|
||||||
| `/availability` | Personal and team blackout management |
|
| `/availability` | Personal and team blackout management |
|
||||||
| `/coverage` | Swap/release requests and public intake |
|
| `/coverage` | Swap/release requests and public intake |
|
||||||
| `/events`, `/events/[id]` | One-off events, briefs, photographers, folders |
|
| `/events`, `/events/[id]` | One-off events, briefs, photographers, photo gallery |
|
||||||
| `/media`, `/media/[id]` | Photo/video library and public video page |
|
| `/media`, `/media/[id]` | Photo/video library and public video page |
|
||||||
| `/training`, `/training/guides/*` | Lessons, attachments, role guides |
|
| `/training`, `/training/guides/*` | Lessons, attachments, role guides |
|
||||||
| `/announcements` | Team feed |
|
| `/announcements` | Team feed |
|
||||||
|
|||||||
+24
-2
@@ -91,6 +91,25 @@ services:
|
|||||||
max-file: "3"
|
max-file: "3"
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
|
||||||
|
# Notification dispatcher. The app only queues mail in the outbox; this loop
|
||||||
|
# drains it through the CRON_SECRET endpoint, so assignment, publish and
|
||||||
|
# reminder emails go out without anyone pressing a button.
|
||||||
|
cron:
|
||||||
|
image: curlimages/curl:8.10.1
|
||||||
|
environment:
|
||||||
|
CRON_SECRET: ${CRON_SECRET:-}
|
||||||
|
depends_on:
|
||||||
|
app:
|
||||||
|
condition: service_healthy
|
||||||
|
entrypoint: ["sh", "-c"]
|
||||||
|
command:
|
||||||
|
- 'while true; do echo "cron tick"; curl -fsS --max-time 30 -H "Authorization: Bearer $$CRON_SECRET" http://app:3000/api/dev/cron/notifications || echo "notification tick failed"; echo; sleep 60; done'
|
||||||
|
restart: unless-stopped
|
||||||
|
logging:
|
||||||
|
options:
|
||||||
|
max-size: "10m"
|
||||||
|
max-file: "3"
|
||||||
|
|
||||||
# Advanced photo editor (Lumenroom), vendored under ./lumenroom so one clone
|
# Advanced photo editor (Lumenroom), vendored under ./lumenroom so one clone
|
||||||
# and one `docker compose up -d --build` deploys both apps. Its catalog is
|
# and one `docker compose up -d --build` deploys both apps. Its catalog is
|
||||||
# temporary bridge data; originals stay on the app's media storage.
|
# temporary bridge data; originals stay on the app's media storage.
|
||||||
@@ -140,14 +159,17 @@ services:
|
|||||||
retries: 10
|
retries: 10
|
||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
|
|
||||||
# One-shot migrations + seed. Run on demand:
|
# One-shot migrations. Run on demand:
|
||||||
# docker compose --profile tools run --rm migrate
|
# docker compose --profile tools run --rm migrate
|
||||||
|
# Seed is intentionally separate: it inserts demo users/services and rewrites
|
||||||
|
# assignments, so it must never run as part of a production deploy. On a
|
||||||
|
# fresh install run: docker compose --profile tools run --rm migrate pnpm db:seed
|
||||||
migrate:
|
migrate:
|
||||||
build:
|
build:
|
||||||
context: .
|
context: .
|
||||||
dockerfile: Dockerfile
|
dockerfile: Dockerfile
|
||||||
target: tools
|
target: tools
|
||||||
command: ["sh", "-c", "pnpm db:migrate && pnpm db:seed"]
|
command: ["pnpm", "db:migrate"]
|
||||||
environment:
|
environment:
|
||||||
DATABASE_URL: postgres://${POSTGRES_USER:-media}:${POSTGRES_PASSWORD:-media}@db:5432/${POSTGRES_DB:-media}
|
DATABASE_URL: postgres://${POSTGRES_USER:-media}:${POSTGRES_PASSWORD:-media}@db:5432/${POSTGRES_DB:-media}
|
||||||
depends_on:
|
depends_on:
|
||||||
|
|||||||
@@ -0,0 +1,15 @@
|
|||||||
|
CREATE TABLE "assignment_proposals" (
|
||||||
|
"id" text PRIMARY KEY NOT NULL,
|
||||||
|
"assignment_id" text NOT NULL,
|
||||||
|
"user_id" text NOT NULL,
|
||||||
|
"proposed_instance_id" text NOT NULL,
|
||||||
|
"note" text,
|
||||||
|
"status" text DEFAULT 'pending' NOT NULL,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
ALTER TABLE "assignment_proposals" ADD CONSTRAINT "assignment_proposals_assignment_id_assignments_id_fk" FOREIGN KEY ("assignment_id") REFERENCES "public"."assignments"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "assignment_proposals" ADD CONSTRAINT "assignment_proposals_user_id_users_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."users"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "assignment_proposals" ADD CONSTRAINT "assignment_proposals_proposed_instance_id_service_instances_id_fk" FOREIGN KEY ("proposed_instance_id") REFERENCES "public"."service_instances"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint
|
||||||
|
CREATE UNIQUE INDEX "assignment_proposals_pending_assignment_idx" ON "assignment_proposals" USING btree ("assignment_id") WHERE "assignment_proposals"."status" = 'pending';--> statement-breakpoint
|
||||||
|
CREATE INDEX "assignment_proposals_status_idx" ON "assignment_proposals" USING btree ("status","created_at");
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -162,6 +162,13 @@
|
|||||||
"when": 1795223283100,
|
"when": 1795223283100,
|
||||||
"tag": "0022_fixed_squadron_supreme",
|
"tag": "0022_fixed_squadron_supreme",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 23,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1795274972891,
|
||||||
|
"tag": "0023_assignment_proposals",
|
||||||
|
"breakpoints": true
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
+11
-22
@@ -4,8 +4,8 @@ import { signInAs, resetDb, BASE } from "./dev";
|
|||||||
|
|
||||||
/**
|
/**
|
||||||
* Event photography (J/K slice): a coordinator creates an event and assigns two
|
* Event photography (J/K slice): a coordinator creates an event and assigns two
|
||||||
* photographers; the first creates a folder and uploads an edited JPEG plus a
|
* photographers; the first uploads a JPEG and a RAW original straight onto the
|
||||||
* RAW original; the second — not the uploader — downloads the untouched bytes.
|
* event page; the second — not the uploader — downloads the untouched bytes.
|
||||||
* An unassigned volunteer cannot open the event at all.
|
* An unassigned volunteer cannot open the event at all.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
@@ -56,17 +56,13 @@ test.describe("event photo sharing", () => {
|
|||||||
await expect(page.getByText("Sam Okafor").first()).toBeVisible();
|
await expect(page.getByText("Sam Okafor").first()).toBeVisible();
|
||||||
});
|
});
|
||||||
|
|
||||||
test("an assigned photographer creates a folder and uploads files", async ({
|
test("an assigned photographer uploads files on the event page", async ({
|
||||||
page,
|
page,
|
||||||
}) => {
|
}) => {
|
||||||
await page.setViewportSize({ width: 1200, height: 900 });
|
await page.setViewportSize({ width: 1200, height: 900 });
|
||||||
await signInAs(page, "avery@glenloch.local");
|
await signInAs(page, "avery@glenloch.local");
|
||||||
await page.goto(eventUrl);
|
await page.goto(eventUrl);
|
||||||
|
|
||||||
await page.getByLabel("New folder").fill("Originals");
|
|
||||||
await page.getByRole("button", { name: "Create folder" }).click();
|
|
||||||
await page.getByRole("link", { name: /Originals/ }).click();
|
|
||||||
|
|
||||||
await page.getByLabel("Choose photos to upload").setInputFiles([
|
await page.getByLabel("Choose photos to upload").setInputFiles([
|
||||||
{ name: PHOTO_NAME, mimeType: "image/jpeg", buffer: PHOTO },
|
{ name: PHOTO_NAME, mimeType: "image/jpeg", buffer: PHOTO },
|
||||||
{ name: "raw.CR3", mimeType: "application/octet-stream", buffer: RAW },
|
{ name: "raw.CR3", mimeType: "application/octet-stream", buffer: RAW },
|
||||||
@@ -84,11 +80,9 @@ test.describe("event photo sharing", () => {
|
|||||||
await page.setViewportSize({ width: 1200, height: 900 });
|
await page.setViewportSize({ width: 1200, height: 900 });
|
||||||
await signInAs(page, "sam@glenloch.local");
|
await signInAs(page, "sam@glenloch.local");
|
||||||
await page.goto(eventUrl);
|
await page.goto(eventUrl);
|
||||||
await page.getByRole("link", { name: /Originals/ }).click();
|
|
||||||
|
|
||||||
const [download] = await Promise.all([
|
const [download] = await Promise.all([
|
||||||
page.waitForEvent("download"),
|
page.waitForEvent("download"),
|
||||||
// Exact: the folder header also offers "Download folder (n)".
|
|
||||||
page.getByRole("link", { name: "Download", exact: true }).first().click(),
|
page.getByRole("link", { name: "Download", exact: true }).first().click(),
|
||||||
]);
|
]);
|
||||||
const downloadPath = await download.path();
|
const downloadPath = await download.path();
|
||||||
@@ -112,11 +106,11 @@ test.describe("event photo sharing", () => {
|
|||||||
|
|
||||||
const zip = await readFile(downloadPath!);
|
const zip = await readFile(downloadPath!);
|
||||||
expect(zip.subarray(0, 4).toString("binary")).toBe("PK\x03\x04");
|
expect(zip.subarray(0, 4).toString("binary")).toBe("PK\x03\x04");
|
||||||
// Store-only entries keep the original bytes and folder paths in the ZIP.
|
// Store-only entries keep the original bytes; uploads share one folder.
|
||||||
expect(zip.includes(PHOTO)).toBe(true);
|
expect(zip.includes(PHOTO)).toBe(true);
|
||||||
expect(zip.includes(RAW)).toBe(true);
|
expect(zip.includes(RAW)).toBe(true);
|
||||||
expect(zip.includes(Buffer.from(`Originals/${PHOTO_NAME}`))).toBe(true);
|
expect(zip.includes(Buffer.from(`Photos/${PHOTO_NAME}`))).toBe(true);
|
||||||
expect(zip.includes(Buffer.from("Originals/raw.CR3"))).toBe(true);
|
expect(zip.includes(Buffer.from("Photos/raw.CR3"))).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("a photographer views a photo and saves a full-resolution edited JPEG", async ({
|
test("a photographer views a photo and saves a full-resolution edited JPEG", async ({
|
||||||
@@ -125,7 +119,6 @@ test.describe("event photo sharing", () => {
|
|||||||
await page.setViewportSize({ width: 1200, height: 900 });
|
await page.setViewportSize({ width: 1200, height: 900 });
|
||||||
await signInAs(page, "sam@glenloch.local");
|
await signInAs(page, "sam@glenloch.local");
|
||||||
await page.goto(eventUrl);
|
await page.goto(eventUrl);
|
||||||
await page.getByRole("link", { name: /Originals/ }).click();
|
|
||||||
|
|
||||||
await page
|
await page
|
||||||
.getByRole("button", { name: `View and edit ${PHOTO_NAME}` })
|
.getByRole("button", { name: `View and edit ${PHOTO_NAME}` })
|
||||||
@@ -136,21 +129,18 @@ test.describe("event photo sharing", () => {
|
|||||||
await page.getByLabel("Exposure").focus();
|
await page.getByLabel("Exposure").focus();
|
||||||
await page.getByLabel("Exposure").press("ArrowRight");
|
await page.getByLabel("Exposure").press("ArrowRight");
|
||||||
await page.getByRole("button", { name: "Save edited JPEG" }).click();
|
await page.getByRole("button", { name: "Save edited JPEG" }).click();
|
||||||
await expect(page.getByText("Full-resolution JPEG saved.")).toBeVisible({
|
// A successful save closes the editor and returns to the refreshed gallery.
|
||||||
timeout: 30_000,
|
await expect(page.getByRole("dialog")).toBeHidden({ timeout: 30_000 });
|
||||||
});
|
await expect(page.getByText("Edited", { exact: true })).toBeVisible();
|
||||||
|
|
||||||
const [download] = await Promise.all([
|
const [download] = await Promise.all([
|
||||||
page.waitForEvent("download"),
|
page.waitForEvent("download"),
|
||||||
page.getByRole("link", { name: "Download edited JPEG" }).click(),
|
page.getByRole("link", { name: "Download edited" }).click(),
|
||||||
]);
|
]);
|
||||||
expect(download.suggestedFilename()).toBe("photo-edited.jpg");
|
expect(download.suggestedFilename()).toBe("photo-edited.jpg");
|
||||||
const edited = await readFile((await download.path())!);
|
const edited = await readFile((await download.path())!);
|
||||||
expect(edited.subarray(0, 3).toString("hex")).toBe("ffd8ff");
|
expect(edited.subarray(0, 3).toString("hex")).toBe("ffd8ff");
|
||||||
expect(edited.equals(PHOTO)).toBe(false);
|
expect(edited.equals(PHOTO)).toBe(false);
|
||||||
|
|
||||||
await page.getByRole("button", { name: "Close photo editor" }).click();
|
|
||||||
await expect(page.getByText("Edited", { exact: true })).toBeVisible();
|
|
||||||
await expect(page.locator(`img[alt="${PHOTO_NAME}"]`)).toHaveAttribute(
|
await expect(page.locator(`img[alt="${PHOTO_NAME}"]`)).toHaveAttribute(
|
||||||
"src",
|
"src",
|
||||||
/variant=edited/,
|
/variant=edited/,
|
||||||
@@ -164,7 +154,7 @@ test.describe("event photo sharing", () => {
|
|||||||
]);
|
]);
|
||||||
const zip = await readFile((await zipDownload.path())!);
|
const zip = await readFile((await zipDownload.path())!);
|
||||||
expect(zip.includes(edited)).toBe(true);
|
expect(zip.includes(edited)).toBe(true);
|
||||||
expect(zip.includes(Buffer.from("Originals/photo-edited.jpg"))).toBe(true);
|
expect(zip.includes(Buffer.from("Photos/photo-edited.jpg"))).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
test("an unassigned volunteer cannot open the event", async ({ page }) => {
|
test("an unassigned volunteer cannot open the event", async ({ page }) => {
|
||||||
@@ -178,7 +168,6 @@ test.describe("event photo sharing", () => {
|
|||||||
await page.setViewportSize({ width: 1200, height: 900 });
|
await page.setViewportSize({ width: 1200, height: 900 });
|
||||||
await signInAs(page, "admin@glenloch.local");
|
await signInAs(page, "admin@glenloch.local");
|
||||||
await page.goto(eventUrl);
|
await page.goto(eventUrl);
|
||||||
await page.getByRole("link", { name: /Originals/ }).click();
|
|
||||||
const photoHref = await page
|
const photoHref = await page
|
||||||
.getByRole("link", { name: "Download", exact: true })
|
.getByRole("link", { name: "Download", exact: true })
|
||||||
.first()
|
.first()
|
||||||
|
|||||||
@@ -158,14 +158,11 @@ test.describe("growth goals and maintenance", () => {
|
|||||||
"No media storage share",
|
"No media storage share",
|
||||||
);
|
);
|
||||||
|
|
||||||
await page.goto(`${BASE}/events/${eventId}/folders/${folderId}`);
|
|
||||||
await expect(page.getByRole("alert").first()).toContainText(
|
|
||||||
"Photo uploads and editing are disabled",
|
|
||||||
);
|
|
||||||
await page.goto(`${BASE}/events/${eventId}`);
|
await page.goto(`${BASE}/events/${eventId}`);
|
||||||
await expect(page.getByRole("alert").first()).toContainText(
|
await expect(
|
||||||
"Photo and video uploads are disabled",
|
page.getByText("Photo uploads and editing are disabled"),
|
||||||
);
|
).toBeVisible();
|
||||||
|
await expect(page.getByText("Photo and video uploads are disabled")).toBeVisible();
|
||||||
|
|
||||||
// A share name that reads like `host:/export` while the path is a local
|
// A share name that reads like `host:/export` while the path is a local
|
||||||
// directory must block writes: media would silently land on local disk.
|
// directory must block writes: media would silently land on local disk.
|
||||||
|
|||||||
@@ -9,7 +9,7 @@
|
|||||||
|
|
||||||
import crypto from 'node:crypto';
|
import crypto from 'node:crypto';
|
||||||
import { BRIDGE_SECRET, BRIDGE_TTL_HOURS, GLENLOCH_URL } from './config.mjs';
|
import { BRIDGE_SECRET, BRIDGE_TTL_HOURS, GLENLOCH_URL } from './config.mjs';
|
||||||
import { db, removeEvent, removePhoto, saveEvent, savePhoto } from './db.mjs';
|
import { db, getPhoto, removeEvent, removePhoto, saveEvent, savePhoto } from './db.mjs';
|
||||||
import { removeAsset } from './storage.mjs';
|
import { removeAsset } from './storage.mjs';
|
||||||
|
|
||||||
const VERSION = 'g1';
|
const VERSION = 'g1';
|
||||||
@@ -173,11 +173,17 @@ function photoRecordFrom(photo, eventId, sessionId, index) {
|
|||||||
meta: {},
|
meta: {},
|
||||||
thumb: '',
|
thumb: '',
|
||||||
thumbUrl: `/api/photos/${id}/thumb`,
|
thumbUrl: `/api/photos/${id}/thumb`,
|
||||||
|
// Thumbnail of the saved edit; the timestamp keeps the browser from reusing
|
||||||
|
// a thumbnail rendered before the edit was saved.
|
||||||
|
thumbVersion: photo.editedAt ? Date.parse(photo.editedAt) || undefined : undefined,
|
||||||
rating: 0,
|
rating: 0,
|
||||||
flag: 'none',
|
flag: 'none',
|
||||||
color: '',
|
color: '',
|
||||||
keywords: [],
|
keywords: [],
|
||||||
edits: {},
|
// The dashboard sends back the recipe saved for this photo, so reopening
|
||||||
|
// the advanced editor starts from the sliders the user left it with.
|
||||||
|
edits:
|
||||||
|
photo.edits && typeof photo.edits === 'object' ? photo.edits : {},
|
||||||
history: [],
|
history: [],
|
||||||
raw,
|
raw,
|
||||||
previewUrl: raw ? `/api/photos/${id}/preview` : undefined,
|
previewUrl: raw ? `/api/photos/${id}/preview` : undefined,
|
||||||
@@ -189,7 +195,7 @@ function photoRecordFrom(photo, eventId, sessionId, index) {
|
|||||||
* Mirrors one event into the local catalog. The photo bytes stay on the
|
* Mirrors one event into the local catalog. The photo bytes stay on the
|
||||||
* dashboard; only metadata, previews and thumbnails are temporary here.
|
* dashboard; only metadata, previews and thumbnails are temporary here.
|
||||||
*/
|
*/
|
||||||
export async function importBridgeEvent({ serviceToken, sessionId }) {
|
export async function importBridgeEvent({ serviceToken, sessionId, returnUrl }) {
|
||||||
const expiresAt =
|
const expiresAt =
|
||||||
Date.now() + Math.max(1, BRIDGE_TTL_HOURS) * 60 * 60 * 1000;
|
Date.now() + Math.max(1, BRIDGE_TTL_HOURS) * 60 * 60 * 1000;
|
||||||
|
|
||||||
@@ -198,12 +204,35 @@ export async function importBridgeEvent({ serviceToken, sessionId }) {
|
|||||||
serviceToken,
|
serviceToken,
|
||||||
);
|
);
|
||||||
const eventId = bridgeEventId(listing.event.id);
|
const eventId = bridgeEventId(listing.event.id);
|
||||||
|
// Preserve anything still unsaved locally before the import replaces rows, so
|
||||||
|
// reopening the editor never discards work in progress.
|
||||||
|
const localEdits = new Map();
|
||||||
|
for (const row of photosForEvent.all(eventId)) {
|
||||||
|
const record = getPhoto(row.id);
|
||||||
|
if (record?.edits && Object.keys(record.edits).length > 0) {
|
||||||
|
localEdits.set(row.id, record);
|
||||||
|
}
|
||||||
|
}
|
||||||
dropBridgeEvent(eventId);
|
dropBridgeEvent(eventId);
|
||||||
|
|
||||||
const returnUrl = listing.editor?.returnUrl ?? null;
|
// The exchange hands back the dashboard address the browser actually used;
|
||||||
saveEvent(eventRecordFrom(listing, eventId, sessionId, returnUrl, expiresAt), 0);
|
// the listing's value is a fallback derived from server configuration and may
|
||||||
|
// point at localhost in a LAN deployment.
|
||||||
|
const dashboardReturn =
|
||||||
|
typeof returnUrl === 'string' && /^https?:\/\//i.test(returnUrl)
|
||||||
|
? returnUrl
|
||||||
|
: listing.editor?.returnUrl ?? null;
|
||||||
|
saveEvent(eventRecordFrom(listing, eventId, sessionId, dashboardReturn, expiresAt), 0);
|
||||||
listing.photos.forEach((photo, index) => {
|
listing.photos.forEach((photo, index) => {
|
||||||
savePhoto(photoRecordFrom(photo, eventId, sessionId, index));
|
const record = photoRecordFrom(photo, eventId, sessionId, index);
|
||||||
|
const local = localEdits.get(record.id);
|
||||||
|
if (local) {
|
||||||
|
record.edits = local.edits;
|
||||||
|
if (Array.isArray(local.history) && local.history.length > 0) {
|
||||||
|
record.history = local.history;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
savePhoto(record);
|
||||||
});
|
});
|
||||||
bridgeInsert.run(
|
bridgeInsert.run(
|
||||||
eventId,
|
eventId,
|
||||||
@@ -211,7 +240,7 @@ export async function importBridgeEvent({ serviceToken, sessionId }) {
|
|||||||
serviceToken,
|
serviceToken,
|
||||||
GLENLOCH_URL,
|
GLENLOCH_URL,
|
||||||
listing.event.id,
|
listing.event.id,
|
||||||
returnUrl,
|
dashboardReturn,
|
||||||
expiresAt,
|
expiresAt,
|
||||||
Date.now(),
|
Date.now(),
|
||||||
);
|
);
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ import {
|
|||||||
findPreview,
|
findPreview,
|
||||||
findThumb,
|
findThumb,
|
||||||
removeAsset,
|
removeAsset,
|
||||||
|
removeThumb,
|
||||||
storageBytes,
|
storageBytes,
|
||||||
writeOriginal,
|
writeOriginal,
|
||||||
writePreview,
|
writePreview,
|
||||||
@@ -302,6 +303,7 @@ route('GET', '/api/bridge/login', async ({ req, res, url }) => {
|
|||||||
const imported = await importBridgeEvent({
|
const imported = await importBridgeEvent({
|
||||||
serviceToken: service.token,
|
serviceToken: service.token,
|
||||||
sessionId: payload.sid,
|
sessionId: payload.sid,
|
||||||
|
returnUrl: service.returnUrl,
|
||||||
});
|
});
|
||||||
const sessionToken = createSession(row.id);
|
const sessionToken = createSession(row.id);
|
||||||
res.writeHead(302, {
|
res.writeHead(302, {
|
||||||
@@ -459,7 +461,17 @@ route('POST', '/api/bridge/export', async ({ req, res }) => {
|
|||||||
if (result.status >= 400) {
|
if (result.status >= 400) {
|
||||||
return error(res, result.status, result.body?.error || 'The edit could not be saved to the event');
|
return error(res, result.status, result.body?.error || 'The edit could not be saved to the event');
|
||||||
}
|
}
|
||||||
return json(res, 200, result.body ?? { ok: true });
|
|
||||||
|
// The grid now shows the dashboard's thumbnail of this render, so drop the
|
||||||
|
// cached copy and bump the URL the browser asks for.
|
||||||
|
await removeThumb(body.photoId).catch(() => undefined);
|
||||||
|
const thumbVersion = Date.now();
|
||||||
|
const stored = getPhoto(body.photoId);
|
||||||
|
if (stored) {
|
||||||
|
stored.thumbVersion = thumbVersion;
|
||||||
|
savePhoto(stored);
|
||||||
|
}
|
||||||
|
return json(res, 200, { ...(result.body ?? { ok: true }), thumbVersion });
|
||||||
});
|
});
|
||||||
|
|
||||||
route('PUT', '/api/photos/:id', async ({ req, res, params }) => {
|
route('PUT', '/api/photos/:id', async ({ req, res, params }) => {
|
||||||
|
|||||||
@@ -70,6 +70,12 @@ export function findThumb(id) {
|
|||||||
return fs.existsSync(p) ? p : null;
|
return fs.existsSync(p) ? p : null;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** Drops the cached grid thumbnail so the next request refetches it. */
|
||||||
|
export async function removeThumb(id) {
|
||||||
|
const thumb = findThumb(id);
|
||||||
|
if (thumb) await fsp.rm(thumb, { force: true });
|
||||||
|
}
|
||||||
|
|
||||||
export async function removeAsset(id) {
|
export async function removeAsset(id) {
|
||||||
const files = [findOriginal(id), findPreview(id), findThumb(id)];
|
const files = [findOriginal(id), findPreview(id), findThumb(id)];
|
||||||
await Promise.all(files.map((f) => (f ? fsp.rm(f, { force: true }) : Promise.resolve())));
|
await Promise.all(files.map((f) => (f ? fsp.rm(f, { force: true }) : Promise.resolve())));
|
||||||
|
|||||||
@@ -653,15 +653,22 @@ export default function App() {
|
|||||||
height: activePhoto.height,
|
height: activePhoto.height,
|
||||||
}),
|
}),
|
||||||
});
|
});
|
||||||
const data = (await res.json().catch(() => ({}))) as { error?: string };
|
const data = (await res.json().catch(() => ({}))) as {
|
||||||
|
error?: string;
|
||||||
|
thumbVersion?: number;
|
||||||
|
};
|
||||||
if (!res.ok) throw new Error(data.error || 'The photo could not be saved');
|
if (!res.ok) throw new Error(data.error || 'The photo could not be saved');
|
||||||
|
if (typeof data.thumbVersion === 'number') {
|
||||||
|
// Refresh the grid thumbnail so it shows this render, not the original.
|
||||||
|
updatePhoto(activePhoto.id, { thumbVersion: data.thumbVersion });
|
||||||
|
}
|
||||||
setToast(`Saved ${activePhoto.name} to the event`);
|
setToast(`Saved ${activePhoto.name} to the event`);
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
setToast(err instanceof Error ? err.message : 'The photo could not be saved');
|
setToast(err instanceof Error ? err.message : 'The photo could not be saved');
|
||||||
} finally {
|
} finally {
|
||||||
setBridgeBusy(false);
|
setBridgeBusy(false);
|
||||||
}
|
}
|
||||||
}, [activePhoto, bridgeEvent]);
|
}, [activePhoto, bridgeEvent, updatePhoto]);
|
||||||
|
|
||||||
const handleCloudLogin = useCallback(
|
const handleCloudLogin = useCallback(
|
||||||
async (email: string, password: string) => {
|
async (email: string, password: string) => {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
import { useCallback, useEffect, useMemo, useRef, useState } from 'react';
|
||||||
import { ASPECTS, defaultEdits, thumbTransform } from '../lib/edits';
|
import { ASPECTS, defaultEdits, thumbTransform } from '../lib/edits';
|
||||||
import { getBitmap } from '../lib/images';
|
import { getBitmap, thumbSrc } from '../lib/images';
|
||||||
import { rotatedBounds, Renderer } from '../gl/renderer';
|
import { rotatedBounds, Renderer } from '../gl/renderer';
|
||||||
import type { Edits, EventRecord, PhotoRecord, Preset } from '../types';
|
import type { Edits, EventRecord, PhotoRecord, Preset } from '../types';
|
||||||
import ContextMenu, { type MenuEntry } from './ContextMenu';
|
import ContextMenu, { type MenuEntry } from './ContextMenu';
|
||||||
@@ -703,7 +703,7 @@ export default function Develop({
|
|||||||
title={p.name}
|
title={p.name}
|
||||||
>
|
>
|
||||||
<img
|
<img
|
||||||
src={p.thumbUrl ?? p.thumb}
|
src={thumbSrc(p)}
|
||||||
alt={p.name}
|
alt={p.name}
|
||||||
loading="lazy"
|
loading="lazy"
|
||||||
draggable={false}
|
draggable={false}
|
||||||
|
|||||||
@@ -1,6 +1,7 @@
|
|||||||
import { useRef, useState } from 'react';
|
import { useRef, useState } from 'react';
|
||||||
import { COLOR_LABELS, isEdited, thumbTransform } from '../lib/edits';
|
import { COLOR_LABELS, isEdited, thumbTransform } from '../lib/edits';
|
||||||
import { draggedPhotoIds, endDrag, PHOTO_DRAG, startPhotoDrag } from '../lib/drag';
|
import { draggedPhotoIds, endDrag, PHOTO_DRAG, startPhotoDrag } from '../lib/drag';
|
||||||
|
import { thumbSrc } from '../lib/images';
|
||||||
import type { ColorLabel, Flag, PhotoRecord } from '../types';
|
import type { ColorLabel, Flag, PhotoRecord } from '../types';
|
||||||
import Stars, { ColorSwatches, FlagButtons } from './Stars';
|
import Stars, { ColorSwatches, FlagButtons } from './Stars';
|
||||||
|
|
||||||
@@ -312,7 +313,7 @@ export default function LibraryGrid({
|
|||||||
>
|
>
|
||||||
<div className="card-thumb">
|
<div className="card-thumb">
|
||||||
<img
|
<img
|
||||||
src={p.thumbUrl ?? p.thumb}
|
src={thumbSrc(p)}
|
||||||
alt={p.name}
|
alt={p.name}
|
||||||
loading="lazy"
|
loading="lazy"
|
||||||
draggable={false}
|
draggable={false}
|
||||||
|
|||||||
@@ -4,7 +4,7 @@ import { computeAutoEdits } from '../lib/auto';
|
|||||||
import { clamp } from '../lib/curves';
|
import { clamp } from '../lib/curves';
|
||||||
import type { CurveChannel, Edits, EventRecord, HistoryEntry, PhotoRecord, Preset } from '../types';
|
import type { CurveChannel, Edits, EventRecord, HistoryEntry, PhotoRecord, Preset } from '../types';
|
||||||
import CurveEditor from './CurveEditor';
|
import CurveEditor from './CurveEditor';
|
||||||
import { getBitmap } from '../lib/images';
|
import { getBitmap, thumbSrc } from '../lib/images';
|
||||||
import { grainSampleWindow, rotatedBounds, Renderer } from '../gl/renderer';
|
import { grainSampleWindow, rotatedBounds, Renderer } from '../gl/renderer';
|
||||||
import { applyFilmVariant, FILM_VARIANTS, type FilmVariant } from '../lib/presets';
|
import { applyFilmVariant, FILM_VARIANTS, type FilmVariant } from '../lib/presets';
|
||||||
import { usePresetThumbs } from './PresetThumbs';
|
import { usePresetThumbs } from './PresetThumbs';
|
||||||
@@ -653,7 +653,7 @@ export function NavigatorPanel({ photo }: { photo: PhotoRecord }) {
|
|||||||
</div>
|
</div>
|
||||||
<div className="navigator-thumb">
|
<div className="navigator-thumb">
|
||||||
<img
|
<img
|
||||||
src={photo.thumbUrl ?? photo.thumb}
|
src={thumbSrc(photo)}
|
||||||
alt={photo.name}
|
alt={photo.name}
|
||||||
style={{ transform: thumbTransform(photo) }}
|
style={{ transform: thumbTransform(photo) }}
|
||||||
/>
|
/>
|
||||||
|
|||||||
@@ -266,6 +266,7 @@ export function normalizePhoto(input: Partial<PhotoRecord> & { id: string }): Ph
|
|||||||
decode: input.decode,
|
decode: input.decode,
|
||||||
previewUrl: input.previewUrl,
|
previewUrl: input.previewUrl,
|
||||||
thumbUrl: input.thumbUrl,
|
thumbUrl: input.thumbUrl,
|
||||||
|
thumbVersion: input.thumbVersion,
|
||||||
name: input.name ?? 'Untitled',
|
name: input.name ?? 'Untitled',
|
||||||
width: input.width ?? 0,
|
width: input.width ?? 0,
|
||||||
height: input.height ?? 0,
|
height: input.height ?? 0,
|
||||||
|
|||||||
@@ -4,6 +4,17 @@ import { getAsset, putAsset } from './db';
|
|||||||
const CACHE_LIMIT = 6;
|
const CACHE_LIMIT = 6;
|
||||||
const cache = new Map<string, ImageBitmap>();
|
const cache = new Map<string, ImageBitmap>();
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Grid/filmstrip thumbnail URL. The version stamp changes when the saved edit is
|
||||||
|
* re-rendered, so the browser does not keep showing the pre-edit thumbnail.
|
||||||
|
*/
|
||||||
|
export function thumbSrc(photo: PhotoRecord): string {
|
||||||
|
if (!photo.thumbUrl) return photo.thumb;
|
||||||
|
return photo.thumbVersion
|
||||||
|
? `${photo.thumbUrl}?v=${photo.thumbVersion}`
|
||||||
|
: photo.thumbUrl;
|
||||||
|
}
|
||||||
|
|
||||||
/** Where to fetch the original (or raw proxy) when it is not cached on this device. */
|
/** Where to fetch the original (or raw proxy) when it is not cached on this device. */
|
||||||
export function remoteAssetUrl(photo: PhotoRecord): string {
|
export function remoteAssetUrl(photo: PhotoRecord): string {
|
||||||
if (photo.raw) return photo.previewUrl || `/api/photos/${encodeURIComponent(photo.id)}/preview`;
|
if (photo.raw) return photo.previewUrl || `/api/photos/${encodeURIComponent(photo.id)}/preview`;
|
||||||
|
|||||||
@@ -562,6 +562,9 @@ img {
|
|||||||
overflow-y: auto;
|
overflow-y: auto;
|
||||||
display: grid;
|
display: grid;
|
||||||
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
|
grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
|
||||||
|
/* Keep every row at its natural height. Without this, a large library makes
|
||||||
|
the auto rows shrink to fit the viewport and the thumbnails collapse. */
|
||||||
|
grid-auto-rows: max-content;
|
||||||
gap: 12px;
|
gap: 12px;
|
||||||
padding: 14px;
|
padding: 14px;
|
||||||
align-content: start;
|
align-content: start;
|
||||||
|
|||||||
@@ -103,6 +103,8 @@ export interface PhotoRecord {
|
|||||||
previewUrl?: string;
|
previewUrl?: string;
|
||||||
/** server URL for the grid thumbnail */
|
/** server URL for the grid thumbnail */
|
||||||
thumbUrl?: string;
|
thumbUrl?: string;
|
||||||
|
/** bumps the thumbnail URL whenever the saved edit is re-rendered */
|
||||||
|
thumbVersion?: number;
|
||||||
/** Set when the photo is proxied from a dashboard bridge session. */
|
/** Set when the photo is proxied from a dashboard bridge session. */
|
||||||
bridgeSource?: { sessionId: string; sourceId: string };
|
bridgeSource?: { sessionId: string; sourceId: string };
|
||||||
}
|
}
|
||||||
|
|||||||
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -6,6 +6,7 @@ import { listUsersForAdmin } from "@/db/users";
|
|||||||
import { listSkillsMatrix } from "@/db/assessments";
|
import { listSkillsMatrix } from "@/db/assessments";
|
||||||
import { getPositionSkills, listPositions, listSkills } from "@/db/positions";
|
import { getPositionSkills, listPositions, listSkills } from "@/db/positions";
|
||||||
import { listServices } from "@/db/services";
|
import { listServices } from "@/db/services";
|
||||||
|
import { SPECIAL_SERVICE_NAME } from "@/db/specials";
|
||||||
import { listNotifications } from "@/db/outbox";
|
import { listNotifications } from "@/db/outbox";
|
||||||
import { listRules } from "@/db/reminders";
|
import { listRules } from "@/db/reminders";
|
||||||
import { getEmailSettings } from "@/db/settings";
|
import { getEmailSettings } from "@/db/settings";
|
||||||
@@ -270,7 +271,10 @@ export default async function AdminPage() {
|
|||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<ServicesPanel
|
<ServicesPanel
|
||||||
services={services.map((service) => ({
|
services={services
|
||||||
|
// The one-off parent is plumbing, not a template to manage.
|
||||||
|
.filter((service) => service.name !== SPECIAL_SERVICE_NAME)
|
||||||
|
.map((service) => ({
|
||||||
id: service.id,
|
id: service.id,
|
||||||
name: service.name,
|
name: service.name,
|
||||||
startTimeLocal: service.startTimeLocal,
|
startTimeLocal: service.startTimeLocal,
|
||||||
|
|||||||
@@ -4,7 +4,11 @@ import { Download, Printer } from "lucide-react";
|
|||||||
import { auth } from "@/auth/config";
|
import { auth } from "@/auth/config";
|
||||||
import { hasPermission } from "@/auth/permissions";
|
import { hasPermission } from "@/auth/permissions";
|
||||||
import type { SystemRole } from "@/auth/roles";
|
import type { SystemRole } from "@/auth/roles";
|
||||||
import { listPendingCoverageRequests } from "@/db/coverage";
|
import {
|
||||||
|
listPendingAlternativeProposals,
|
||||||
|
listPendingCoverageRequests,
|
||||||
|
} from "@/db/coverage";
|
||||||
|
import { CHURCH_TIMEZONE, formatInTimezone } from "@/lib/tz";
|
||||||
import { listCoverageIntakes } from "@/db/intake";
|
import { listCoverageIntakes } from "@/db/intake";
|
||||||
import { rankedCandidatesForSlot } from "@/db/rankedCandidates";
|
import { rankedCandidatesForSlot } from "@/db/rankedCandidates";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
@@ -24,9 +28,10 @@ export default async function CoveragePage() {
|
|||||||
if (!user?.id) return null;
|
if (!user?.id) return null;
|
||||||
if (!hasPermission(user.systemRole, "schedule.publish")) redirect("/home");
|
if (!hasPermission(user.systemRole, "schedule.publish")) redirect("/home");
|
||||||
|
|
||||||
const [requests, intakes] = await Promise.all([
|
const [requests, intakes, alternatives] = await Promise.all([
|
||||||
listPendingCoverageRequests(),
|
listPendingCoverageRequests(),
|
||||||
listCoverageIntakes("new"),
|
listCoverageIntakes("new"),
|
||||||
|
listPendingAlternativeProposals(),
|
||||||
]);
|
]);
|
||||||
|
|
||||||
const views: CoverageRequestView[] = await Promise.all(
|
const views: CoverageRequestView[] = await Promise.all(
|
||||||
@@ -96,6 +101,60 @@ export default async function CoveragePage() {
|
|||||||
|
|
||||||
<CoverageBoard requests={views} intakes={intakeViews} />
|
<CoverageBoard requests={views} intakes={intakeViews} />
|
||||||
|
|
||||||
|
{alternatives.length > 0 && (
|
||||||
|
<section className="rounded-md border border-border">
|
||||||
|
<div className="border-b border-border bg-muted/30 px-3 py-2">
|
||||||
|
<h2 className="text-sm font-semibold">Proposed another Sunday</h2>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
These volunteers cannot serve their proposed date but offered an
|
||||||
|
alternative. Reassign them from the schedule, then clear the seat.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<ul className="divide-y divide-border">
|
||||||
|
{alternatives.map((proposal) => (
|
||||||
|
<li key={proposal.id} className="space-y-1 px-3 py-2 text-sm">
|
||||||
|
<p>
|
||||||
|
<span className="font-medium">{proposal.requesterName}</span>{" "}
|
||||||
|
({proposal.roleName}) can serve{" "}
|
||||||
|
<span className="font-medium">
|
||||||
|
{formatInTimezone(
|
||||||
|
proposal.proposedStartsAt,
|
||||||
|
CHURCH_TIMEZONE,
|
||||||
|
{
|
||||||
|
timeZone: CHURCH_TIMEZONE,
|
||||||
|
weekday: "short",
|
||||||
|
month: "short",
|
||||||
|
day: "numeric",
|
||||||
|
},
|
||||||
|
)}
|
||||||
|
</span>{" "}
|
||||||
|
instead of{" "}
|
||||||
|
{formatInTimezone(
|
||||||
|
proposal.currentStartsAt,
|
||||||
|
CHURCH_TIMEZONE,
|
||||||
|
{
|
||||||
|
timeZone: CHURCH_TIMEZONE,
|
||||||
|
weekday: "short",
|
||||||
|
month: "short",
|
||||||
|
day: "numeric",
|
||||||
|
},
|
||||||
|
)}
|
||||||
|
.
|
||||||
|
</p>
|
||||||
|
{proposal.note && (
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
“{proposal.note}”
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
{proposal.requesterEmail}
|
||||||
|
</p>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
|
)}
|
||||||
|
|
||||||
<p className="text-xs text-muted-foreground">
|
<p className="text-xs text-muted-foreground">
|
||||||
Share the public request form at{" "}
|
Share the public request form at{" "}
|
||||||
<Link href="/request-coverage" className="font-medium underline">
|
<Link href="/request-coverage" className="font-medium underline">
|
||||||
|
|||||||
@@ -1,126 +0,0 @@
|
|||||||
import Link from "next/link";
|
|
||||||
import { notFound, redirect } from "next/navigation";
|
|
||||||
import { ArrowLeft, Download } from "lucide-react";
|
|
||||||
import { auth } from "@/auth/config";
|
|
||||||
import type { SystemRole } from "@/auth/roles";
|
|
||||||
import { getFolderDetail } from "@/db/events";
|
|
||||||
import {
|
|
||||||
isBrowserRenderablePhoto,
|
|
||||||
isEditableEventPhoto,
|
|
||||||
} from "@/lib/event-photos";
|
|
||||||
import { mediaStorage } from "@/lib/media-storage";
|
|
||||||
import { parseStoredPhotoAdjustments } from "@/lib/photo-adjustments";
|
|
||||||
import { Badge } from "@/components/ui/badge";
|
|
||||||
import { Button } from "@/components/ui/button";
|
|
||||||
import {
|
|
||||||
PhotoGallery,
|
|
||||||
type GalleryPhoto,
|
|
||||||
} from "@/components/app/events/photo-gallery";
|
|
||||||
|
|
||||||
const KIND_LABELS: Record<string, string> = {
|
|
||||||
originals: "RAW / originals",
|
|
||||||
edited: "Edited exports",
|
|
||||||
mixed: "Mixed",
|
|
||||||
};
|
|
||||||
|
|
||||||
function sizeLabel(bytes: number): string {
|
|
||||||
if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
|
|
||||||
if (bytes < 1024 * 1024 * 1024) {
|
|
||||||
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
|
||||||
}
|
|
||||||
return `${(bytes / (1024 * 1024 * 1024)).toFixed(2)} GB`;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* A folder's gallery. Every assigned photographer can see and download every
|
|
||||||
* file; only the uploader or an event manager can delete one.
|
|
||||||
*/
|
|
||||||
export default async function EventFolderPage({
|
|
||||||
params,
|
|
||||||
}: {
|
|
||||||
params: Promise<{ id: string; folderId: string }>;
|
|
||||||
}) {
|
|
||||||
const session = await auth();
|
|
||||||
const user = session?.user as
|
|
||||||
| { id?: string; systemRole?: SystemRole }
|
|
||||||
| undefined;
|
|
||||||
if (!user?.id) redirect("/login");
|
|
||||||
|
|
||||||
const { id, folderId } = await params;
|
|
||||||
const detail = await getFolderDetail(folderId, user.id, user.systemRole);
|
|
||||||
if (!detail || detail.event.id !== id) notFound();
|
|
||||||
|
|
||||||
// Photos live only on the configured media storage share, so the uploader and
|
|
||||||
// editor stay disabled (with the reason) until that destination is ready.
|
|
||||||
const storage = await mediaStorage();
|
|
||||||
|
|
||||||
const photos: GalleryPhoto[] = detail.photos.map((photo) => ({
|
|
||||||
id: photo.id,
|
|
||||||
filename: photo.filename,
|
|
||||||
sizeBytes: photo.sizeBytes,
|
|
||||||
kind: photo.kind,
|
|
||||||
uploaderId: photo.uploaderId,
|
|
||||||
uploaderName: photo.uploaderName,
|
|
||||||
previewable: isBrowserRenderablePhoto(photo.filename),
|
|
||||||
editable: isEditableEventPhoto(photo.filename),
|
|
||||||
adjustments: parseStoredPhotoAdjustments(photo.editJson),
|
|
||||||
editedAt: photo.editedAt ? photo.editedAt.toISOString() : null,
|
|
||||||
editedSizeBytes: photo.editedSizeBytes,
|
|
||||||
}));
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="space-y-5">
|
|
||||||
<div>
|
|
||||||
<Link
|
|
||||||
href={`/events/${detail.event.id}`}
|
|
||||||
className="inline-flex items-center gap-1 text-sm text-muted-foreground hover:text-foreground"
|
|
||||||
>
|
|
||||||
<ArrowLeft className="h-3.5 w-3.5" aria-hidden="true" />
|
|
||||||
{detail.event.title}
|
|
||||||
</Link>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<div className="flex flex-wrap items-start justify-between gap-3">
|
|
||||||
<div>
|
|
||||||
<h1 className="text-xl font-semibold tracking-tight">
|
|
||||||
{detail.folder.name}
|
|
||||||
</h1>
|
|
||||||
<p className="text-sm text-muted-foreground">
|
|
||||||
{detail.photos.length} photo{detail.photos.length === 1 ? "" : "s"}{" "}
|
|
||||||
· {sizeLabel(detail.folder.totalBytes)}
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<div className="flex flex-wrap items-center gap-2">
|
|
||||||
<Badge variant="secondary">
|
|
||||||
{KIND_LABELS[detail.folder.kind] ?? detail.folder.kind}
|
|
||||||
</Badge>
|
|
||||||
{detail.photos.length > 0 && (
|
|
||||||
<Button asChild variant="outline" size="sm">
|
|
||||||
<a
|
|
||||||
href={`/api/events/${detail.event.id}/download?folderId=${detail.folder.id}`}
|
|
||||||
>
|
|
||||||
<Download className="h-3.5 w-3.5" aria-hidden="true" />
|
|
||||||
Download folder ({detail.photos.length})
|
|
||||||
</a>
|
|
||||||
</Button>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<PhotoGallery
|
|
||||||
eventId={detail.event.id}
|
|
||||||
folderId={detail.folder.id}
|
|
||||||
photos={photos}
|
|
||||||
canContribute={detail.canContribute}
|
|
||||||
canManage={detail.canManage}
|
|
||||||
currentUserId={user.id}
|
|
||||||
storageReady={storage.ok}
|
|
||||||
storageMessage={
|
|
||||||
storage.ok
|
|
||||||
? ""
|
|
||||||
: storage.message
|
|
||||||
}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -1,10 +1,23 @@
|
|||||||
import Link from "next/link";
|
import Link from "next/link";
|
||||||
import { notFound, redirect } from "next/navigation";
|
import { notFound, redirect } from "next/navigation";
|
||||||
import { ArrowLeft, Camera, Download, Film, FolderOpen, MapPin, Play } from "lucide-react";
|
import {
|
||||||
|
ArrowLeft,
|
||||||
|
Camera,
|
||||||
|
Download,
|
||||||
|
Film,
|
||||||
|
Image as ImageIcon,
|
||||||
|
MapPin,
|
||||||
|
Play,
|
||||||
|
} from "lucide-react";
|
||||||
import { auth } from "@/auth/config";
|
import { auth } from "@/auth/config";
|
||||||
import type { SystemRole } from "@/auth/roles";
|
import type { SystemRole } from "@/auth/roles";
|
||||||
import { getEventDetail, listAssignableUsers } from "@/db/events";
|
import {
|
||||||
|
getEventDetail,
|
||||||
|
listAssignableUsers,
|
||||||
|
listEventPhotos,
|
||||||
|
} from "@/db/events";
|
||||||
import { listEventVideos } from "@/db/videos";
|
import { listEventVideos } from "@/db/videos";
|
||||||
|
import { bridgeConfigured } from "@/lib/bridge";
|
||||||
import { formatVideoDuration } from "@/lib/event-videos";
|
import { formatVideoDuration } from "@/lib/event-videos";
|
||||||
import { getStorageSettings } from "@/db/storage-settings";
|
import { getStorageSettings } from "@/db/storage-settings";
|
||||||
import { mediaStorage } from "@/lib/media-storage";
|
import { mediaStorage } from "@/lib/media-storage";
|
||||||
@@ -15,17 +28,21 @@ import {
|
|||||||
PhotographerPanel,
|
PhotographerPanel,
|
||||||
type EventPhotographer,
|
type EventPhotographer,
|
||||||
} from "@/components/app/events/photographer-panel";
|
} from "@/components/app/events/photographer-panel";
|
||||||
import { FolderCreateForm } from "@/components/app/events/folder-create-form";
|
|
||||||
import { DeleteEventButton } from "@/components/app/events/delete-event-button";
|
import { DeleteEventButton } from "@/components/app/events/delete-event-button";
|
||||||
|
import { AdvancedEditorButton } from "@/components/app/events/advanced-editor-button";
|
||||||
import { ArchiveEventButton } from "@/components/app/events/archive-event-button";
|
import { ArchiveEventButton } from "@/components/app/events/archive-event-button";
|
||||||
import { VideoUploadForm } from "@/components/app/media/video-upload-form";
|
import { VideoUploadForm } from "@/components/app/media/video-upload-form";
|
||||||
import { Button } from "@/components/ui/button";
|
import { Button } from "@/components/ui/button";
|
||||||
|
import {
|
||||||
const KIND_LABELS: Record<string, string> = {
|
PhotoGallery,
|
||||||
originals: "RAW / originals",
|
type GalleryPhoto,
|
||||||
edited: "Edited exports",
|
} from "@/components/app/events/photo-gallery";
|
||||||
mixed: "Mixed",
|
import {
|
||||||
};
|
isBrowserRenderablePhoto,
|
||||||
|
isEditableEventPhoto,
|
||||||
|
} from "@/lib/event-photos";
|
||||||
|
import { parseStoredPhotoAdjustments } from "@/lib/photo-adjustments";
|
||||||
|
import { advancedEditViewFor } from "@/lib/advanced-edit";
|
||||||
|
|
||||||
function when(date: Date): string {
|
function when(date: Date): string {
|
||||||
return formatInTimezone(date, CHURCH_TIMEZONE, {
|
return formatInTimezone(date, CHURCH_TIMEZONE, {
|
||||||
@@ -48,9 +65,9 @@ function sizeLabel(bytes: number): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* One event: brief, assigned photographers, and the shared folders. Managers
|
* One event: brief, assigned photographers, and every photo in a single
|
||||||
* assign people; any assignee can create folders. Folder pages own uploads;
|
* gallery. Managers assign people; any assignee can upload here. The header
|
||||||
* the event header downloads every photo as one ZIP.
|
* downloads every photo (or only the edited ones) as one ZIP.
|
||||||
*/
|
*/
|
||||||
export default async function EventDetailPage({
|
export default async function EventDetailPage({
|
||||||
params,
|
params,
|
||||||
@@ -79,6 +96,25 @@ export default async function EventDetailPage({
|
|||||||
role: person.role,
|
role: person.role,
|
||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
const photos: GalleryPhoto[] = (await listEventPhotos(event.event.id)).map(
|
||||||
|
(photo) => ({
|
||||||
|
id: photo.id,
|
||||||
|
folderId: photo.folderId,
|
||||||
|
filename: photo.filename,
|
||||||
|
sizeBytes: photo.sizeBytes,
|
||||||
|
kind: photo.kind,
|
||||||
|
uploaderId: photo.uploaderId,
|
||||||
|
uploaderName: photo.uploaderName,
|
||||||
|
previewable: isBrowserRenderablePhoto(photo.filename),
|
||||||
|
editable: isEditableEventPhoto(photo.filename),
|
||||||
|
adjustments: parseStoredPhotoAdjustments(photo.editJson),
|
||||||
|
advancedEdit: Boolean(photo.advancedEditJson),
|
||||||
|
advancedSummary: advancedEditViewFor(photo.advancedEditJson),
|
||||||
|
editedAt: photo.editedAt ? photo.editedAt.toISOString() : null,
|
||||||
|
editedSizeBytes: photo.editedSizeBytes,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
const editedCount = photos.filter((photo) => photo.editedAt).length;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-6">
|
<div className="space-y-6">
|
||||||
@@ -99,6 +135,9 @@ export default async function EventDetailPage({
|
|||||||
</h1>
|
</h1>
|
||||||
<Badge variant="outline">{event.event.eventType}</Badge>
|
<Badge variant="outline">{event.event.eventType}</Badge>
|
||||||
<div className="ml-auto flex flex-wrap items-center justify-end gap-2">
|
<div className="ml-auto flex flex-wrap items-center justify-end gap-2">
|
||||||
|
{bridgeConfigured() && (
|
||||||
|
<AdvancedEditorButton eventId={event.event.id} />
|
||||||
|
)}
|
||||||
{event.event.photoCount > 0 && (
|
{event.event.photoCount > 0 && (
|
||||||
<Button asChild variant="outline" size="sm">
|
<Button asChild variant="outline" size="sm">
|
||||||
<a href={`/api/events/${event.event.id}/download`}>
|
<a href={`/api/events/${event.event.id}/download`}>
|
||||||
@@ -107,6 +146,17 @@ export default async function EventDetailPage({
|
|||||||
</a>
|
</a>
|
||||||
</Button>
|
</Button>
|
||||||
)}
|
)}
|
||||||
|
{editedCount > 0 && (
|
||||||
|
<Button asChild variant="outline" size="sm">
|
||||||
|
<a
|
||||||
|
href={`/api/events/${event.event.id}/download?edited=1`}
|
||||||
|
title="Download only the photos with a saved edit, as full-resolution JPEGs"
|
||||||
|
>
|
||||||
|
<Download className="h-3.5 w-3.5" aria-hidden="true" />
|
||||||
|
Download edited ({editedCount})
|
||||||
|
</a>
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
{event.canManage && archiveStatus.ok && (
|
{event.canManage && archiveStatus.ok && (
|
||||||
<ArchiveEventButton
|
<ArchiveEventButton
|
||||||
eventId={event.event.id}
|
eventId={event.event.id}
|
||||||
@@ -175,50 +225,26 @@ export default async function EventDetailPage({
|
|||||||
<Card>
|
<Card>
|
||||||
<CardHeader className="pb-3">
|
<CardHeader className="pb-3">
|
||||||
<CardTitle className="flex items-center gap-2 text-base">
|
<CardTitle className="flex items-center gap-2 text-base">
|
||||||
<FolderOpen className="h-4 w-4" aria-hidden="true" />
|
<ImageIcon className="h-4 w-4" aria-hidden="true" />
|
||||||
Folders
|
Photos
|
||||||
|
{photos.length > 0 && (
|
||||||
|
<span className="text-sm font-normal text-muted-foreground">
|
||||||
|
{photos.length}
|
||||||
|
{editedCount > 0 ? ` · ${editedCount} edited` : ""}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
</CardTitle>
|
</CardTitle>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent className="space-y-3">
|
<CardContent>
|
||||||
{event.folders.length === 0 ? (
|
<PhotoGallery
|
||||||
<p className="text-sm text-muted-foreground">
|
eventId={event.event.id}
|
||||||
No folders yet. Create one for originals, dumps, or edited selects.
|
photos={photos}
|
||||||
</p>
|
canContribute={event.canContribute}
|
||||||
) : (
|
canManage={event.canManage}
|
||||||
<ul className="grid gap-3 sm:grid-cols-2">
|
currentUserId={user.id}
|
||||||
{event.folders.map((folder) => (
|
storageReady={archiveStatus.ok}
|
||||||
<li key={folder.id}>
|
storageMessage={archiveStatus.ok ? "" : archiveStatus.message}
|
||||||
<Link
|
/>
|
||||||
href={`/events/${event.event.id}/folders/${folder.id}`}
|
|
||||||
className="block rounded-md border border-border p-3 transition-colors hover:border-primary/60 hover:bg-muted/30"
|
|
||||||
>
|
|
||||||
<div className="flex items-start justify-between gap-2">
|
|
||||||
<p className="truncate text-sm font-medium">
|
|
||||||
{folder.name}
|
|
||||||
</p>
|
|
||||||
<Badge variant="secondary">
|
|
||||||
{KIND_LABELS[folder.kind] ?? folder.kind}
|
|
||||||
</Badge>
|
|
||||||
</div>
|
|
||||||
<p className="mt-1 text-xs text-muted-foreground">
|
|
||||||
{folder.photoCount} photo
|
|
||||||
{folder.photoCount === 1 ? "" : "s"} ·{" "}
|
|
||||||
{sizeLabel(folder.totalBytes)}
|
|
||||||
</p>
|
|
||||||
</Link>
|
|
||||||
</li>
|
|
||||||
))}
|
|
||||||
</ul>
|
|
||||||
)}
|
|
||||||
|
|
||||||
{event.canContribute ? (
|
|
||||||
<FolderCreateForm eventId={event.event.id} />
|
|
||||||
) : (
|
|
||||||
<p className="text-xs text-muted-foreground">
|
|
||||||
Only assigned photographers, coordinators and admins can add
|
|
||||||
folders or upload.
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
|
|
||||||
|
|||||||
@@ -235,8 +235,8 @@ export default async function MediaPage() {
|
|||||||
Photos
|
Photos
|
||||||
</h2>
|
</h2>
|
||||||
<p className="text-xs text-muted-foreground">
|
<p className="text-xs text-muted-foreground">
|
||||||
Every photo in the event folders you can open. Download originals
|
Every photo in the events you can open. Download originals from
|
||||||
from the event folder.
|
the event page.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<span className="text-xs text-muted-foreground">
|
<span className="text-xs text-muted-foreground">
|
||||||
@@ -264,7 +264,7 @@ export default async function MediaPage() {
|
|||||||
return (
|
return (
|
||||||
<Link
|
<Link
|
||||||
key={photo.id}
|
key={photo.id}
|
||||||
href={`/events/${photo.eventId}/folders/${photo.folderId}`}
|
href={`/events/${photo.eventId}`}
|
||||||
className="group overflow-hidden rounded-md border border-border bg-background transition-colors hover:border-primary/60"
|
className="group overflow-hidden rounded-md border border-border bg-background transition-colors hover:border-primary/60"
|
||||||
>
|
>
|
||||||
<div className="flex aspect-square items-center justify-center bg-muted/40">
|
<div className="flex aspect-square items-center justify-center bg-muted/40">
|
||||||
@@ -292,7 +292,7 @@ export default async function MediaPage() {
|
|||||||
{photo.filename}
|
{photo.filename}
|
||||||
</p>
|
</p>
|
||||||
<p className="truncate text-[11px] text-muted-foreground">
|
<p className="truncate text-[11px] text-muted-foreground">
|
||||||
{photo.eventTitle} · {photo.folderName}
|
{photo.eventTitle}
|
||||||
</p>
|
</p>
|
||||||
<p className="text-[10px] text-muted-foreground">
|
<p className="text-[10px] text-muted-foreground">
|
||||||
{bytesLabel(photo.sizeBytes)}
|
{bytesLabel(photo.sizeBytes)}
|
||||||
|
|||||||
@@ -5,6 +5,8 @@ import { WeekNav } from "@/components/app/week-nav";
|
|||||||
import { ScheduleAdminBar } from "@/components/app/schedule-admin-bar";
|
import { ScheduleAdminBar } from "@/components/app/schedule-admin-bar";
|
||||||
import { ScheduleGrid } from "@/components/app/schedule-grid";
|
import { ScheduleGrid } from "@/components/app/schedule-grid";
|
||||||
import { ScheduleGridEditor } from "@/components/app/schedule-grid-editor";
|
import { ScheduleGridEditor } from "@/components/app/schedule-grid-editor";
|
||||||
|
import { SpecialServiceForm } from "@/components/app/special-service-form";
|
||||||
|
import { listPositions } from "@/db/positions";
|
||||||
import {
|
import {
|
||||||
MonthNav,
|
MonthNav,
|
||||||
ScheduleViewToggle,
|
ScheduleViewToggle,
|
||||||
@@ -119,12 +121,25 @@ export default async function SchedulePage({
|
|||||||
}
|
}
|
||||||
|
|
||||||
const week = await gridForWeek(weekStart);
|
const week = await gridForWeek(weekStart);
|
||||||
|
const [roles, volunteers] = canEdit
|
||||||
|
? await Promise.all([listPositions({ active: true }), activeVolunteers(db)])
|
||||||
|
: [[], []];
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="space-y-4">
|
<div className="space-y-4">
|
||||||
{header}
|
{header}
|
||||||
{toggle}
|
{toggle}
|
||||||
<WeekNav weekStart={weekStart} />
|
<WeekNav weekStart={weekStart} />
|
||||||
|
{canEdit && (
|
||||||
|
<SpecialServiceForm
|
||||||
|
roles={roles.map((role) => ({ id: role.id, name: role.name }))}
|
||||||
|
volunteers={volunteers.map((person) => ({
|
||||||
|
id: person.id,
|
||||||
|
displayName: person.displayName,
|
||||||
|
}))}
|
||||||
|
defaultDate={weekStart}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
{canEdit && (
|
{canEdit && (
|
||||||
<ScheduleAdminBar
|
<ScheduleAdminBar
|
||||||
instances={week.instances.map((inst) => ({
|
instances={week.instances.map((inst) => ({
|
||||||
@@ -135,7 +150,7 @@ export default async function SchedulePage({
|
|||||||
/>
|
/>
|
||||||
)}
|
)}
|
||||||
{canEdit ? (
|
{canEdit ? (
|
||||||
<ScheduleGridEditor week={week} volunteers={await activeVolunteers(db)} />
|
<ScheduleGridEditor week={week} volunteers={volunteers} />
|
||||||
) : (
|
) : (
|
||||||
<ScheduleGrid week={week} />
|
<ScheduleGrid week={week} />
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -109,10 +109,13 @@ export default function AdminGuidePage() {
|
|||||||
/>
|
/>
|
||||||
<GuideCallout title="Draft versus published" tone="note">
|
<GuideCallout title="Draft versus published" tone="note">
|
||||||
<p>
|
<p>
|
||||||
New service instances start as drafts. Volunteers only see the
|
New service instances start as drafts, and volunteers do not see a
|
||||||
week, and only receive assignment email, after you publish it. A
|
draft on their schedule. Assigning a seat still sends the proposed
|
||||||
draft is safe to edit; a published week should be changed carefully
|
email immediately so the volunteer can accept, decline, or propose
|
||||||
because people have already been told about it.
|
another Sunday. Publishing makes the week visible and queues the
|
||||||
|
published/reminder mail for every live assignment. A draft is safe
|
||||||
|
to edit; a published week should be changed carefully because people
|
||||||
|
have already been told about it.
|
||||||
</p>
|
</p>
|
||||||
</GuideCallout>
|
</GuideCallout>
|
||||||
</GuideSection>
|
</GuideSection>
|
||||||
@@ -374,7 +377,9 @@ export default function AdminGuidePage() {
|
|||||||
</GuideStep>
|
</GuideStep>
|
||||||
<GuideStep>
|
<GuideStep>
|
||||||
Press <strong>Publish</strong> when the week is ready. Publishing
|
Press <strong>Publish</strong> when the week is ready. Publishing
|
||||||
queues assignment email and reminder rules for that instance.
|
makes the week visible and queues the published/reminder mail for
|
||||||
|
live assignments. Assignments made later still send their proposed
|
||||||
|
email immediately.
|
||||||
</GuideStep>
|
</GuideStep>
|
||||||
<GuideStep>
|
<GuideStep>
|
||||||
Unpublish only when you intend to withdraw the week; volunteers may
|
Unpublish only when you intend to withdraw the week; volunteers may
|
||||||
@@ -443,6 +448,20 @@ export default function AdminGuidePage() {
|
|||||||
</p>
|
</p>
|
||||||
</GuideCallout>
|
</GuideCallout>
|
||||||
|
|
||||||
|
<h3 className="pt-2 text-base font-semibold">
|
||||||
|
Volunteers who propose another Sunday
|
||||||
|
</h3>
|
||||||
|
<p className="text-sm leading-6">
|
||||||
|
The proposed email also offers <strong>Propose another Sunday</strong>.
|
||||||
|
That link records a pending proposal for a coordinator but leaves the
|
||||||
|
original assignment live, so the seat remains covered while you
|
||||||
|
decide. Pending proposals appear on <strong>Coverage</strong> under{" "}
|
||||||
|
<strong>Proposed another Sunday</strong>. This queue is read-only for
|
||||||
|
now: review the date and note, then change the schedule yourself
|
||||||
|
(assign a replacement or clear the seat) and confirm the change with
|
||||||
|
the volunteer.
|
||||||
|
</p>
|
||||||
|
|
||||||
<h3 className="pt-2 text-base font-semibold">Requests from outside the team</h3>
|
<h3 className="pt-2 text-base font-semibold">Requests from outside the team</h3>
|
||||||
<p className="text-sm leading-6">
|
<p className="text-sm leading-6">
|
||||||
Ministry leaders can submit the public form at{" "}
|
Ministry leaders can submit the public form at{" "}
|
||||||
@@ -450,7 +469,7 @@ export default function AdminGuidePage() {
|
|||||||
rate-limited and appear under Coverage as new requests. Read the brief,
|
rate-limited and appear under Coverage as new requests. Read the brief,
|
||||||
then either <strong>Create event</strong> (which opens an event with
|
then either <strong>Create event</strong> (which opens an event with
|
||||||
the requester and ministry attached) or <strong>Decline</strong>. The
|
the requester and ministry attached) or <strong>Decline</strong>. The
|
||||||
event is where you assign photographers and folders.
|
event page is where you assign photographers and upload photos.
|
||||||
</p>
|
</p>
|
||||||
</GuideSection>
|
</GuideSection>
|
||||||
|
|
||||||
@@ -704,12 +723,14 @@ export default function AdminGuidePage() {
|
|||||||
admins can remove them.
|
admins can remove them.
|
||||||
</GuideStep>
|
</GuideStep>
|
||||||
</GuideSteps>
|
</GuideSteps>
|
||||||
<GuideCallout title="The two long guides are built in" tone="tip">
|
<GuideCallout title="Role guides are built in" tone="tip">
|
||||||
<p>
|
<p>
|
||||||
The Platform administration guide and the Volunteer guide appear at
|
Training shows the guide for the signed-in role: the Platform
|
||||||
the top of Training as web pages with screenshots and as downloadable
|
administration guide for admins, the Coordinator guide for
|
||||||
PDFs. They are documentation for this deployment, not editable
|
coordinators, and the Volunteer guide for volunteers and trainees.
|
||||||
lessons, so they stay consistent for every admin.
|
The admin and volunteer guides also have downloadable PDFs. These
|
||||||
|
are documentation for this deployment, not editable lessons, so they
|
||||||
|
stay consistent for everyone.
|
||||||
</p>
|
</p>
|
||||||
</GuideCallout>
|
</GuideCallout>
|
||||||
</GuideSection>
|
</GuideSection>
|
||||||
|
|||||||
@@ -0,0 +1,393 @@
|
|||||||
|
import type { Metadata } from "next";
|
||||||
|
import {
|
||||||
|
GuideCallout,
|
||||||
|
GuideFields,
|
||||||
|
GuideFigure,
|
||||||
|
GuideSection,
|
||||||
|
GuideShell,
|
||||||
|
GuideStep,
|
||||||
|
GuideSteps,
|
||||||
|
} from "@/components/app/training/guide";
|
||||||
|
|
||||||
|
export const metadata: Metadata = {
|
||||||
|
title: "Coordinator guide",
|
||||||
|
};
|
||||||
|
|
||||||
|
const SECTIONS = [
|
||||||
|
{ id: "role", title: "Your coordinator role" },
|
||||||
|
{ id: "week", title: "Build and publish a week" },
|
||||||
|
{ id: "replies", title: "Assignment emails and replies" },
|
||||||
|
{ id: "coverage", title: "Coverage and swaps" },
|
||||||
|
{ id: "run-sheets", title: "Run sheets" },
|
||||||
|
{ id: "events", title: "Events and media" },
|
||||||
|
{ id: "announcements", title: "Announcements and training" },
|
||||||
|
{ id: "exports", title: "Print and CSV exports" },
|
||||||
|
{ id: "troubleshooting", title: "Troubleshooting" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export default function CoordinatorGuidePage() {
|
||||||
|
return (
|
||||||
|
<GuideShell
|
||||||
|
title="Coordinator guide"
|
||||||
|
audience="Coordinators"
|
||||||
|
intro="The working guide for coordinating the media team: building and publishing the schedule, responding to assignment replies, resolving coverage, preparing run sheets, keeping events moving, and getting the week onto paper or into a spreadsheet."
|
||||||
|
pdfHref="/training/media-team-coordinator-guide.pdf"
|
||||||
|
pdfLabel="Download coordinator PDF"
|
||||||
|
sections={SECTIONS}
|
||||||
|
>
|
||||||
|
<GuideSection id="role" title="1. Your coordinator role">
|
||||||
|
<p className="text-sm leading-6">
|
||||||
|
Coordinators run the week. You can edit and publish the schedule,
|
||||||
|
handle coverage and swaps, edit run sheets, manage events, author
|
||||||
|
announcements, and use the print and CSV exports. You do not need the
|
||||||
|
Admin tab for any of that.
|
||||||
|
</p>
|
||||||
|
<GuideFields
|
||||||
|
rows={[
|
||||||
|
{
|
||||||
|
label: "You can",
|
||||||
|
value:
|
||||||
|
"Dashboard, Coverage, schedule assignment and publishing, auto-fill, run sheets, events and media, announcements, training viewing, print, and schedule/history CSV downloads.",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: "Admins handle",
|
||||||
|
value:
|
||||||
|
"People and access, skill verification, positions and requirements, service templates, email credentials, reminder rules, backups, and training authoring. Ask an admin when one of those needs to change.",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: "Everyone serves",
|
||||||
|
value:
|
||||||
|
"Coordinators can hold a seat too. Your own assignment, availability, profile, and notification settings work exactly like a volunteer’s.",
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
<GuideFigure
|
||||||
|
src="/training/screens/admin-dashboard.png"
|
||||||
|
alt="Coverage dashboard with filled and open seats and the next service summary"
|
||||||
|
caption="Open Dashboard before planning a week: it shows open seats and unconfirmed assignments at a glance."
|
||||||
|
/>
|
||||||
|
</GuideSection>
|
||||||
|
|
||||||
|
<GuideSection id="week" title="2. Build and publish a week">
|
||||||
|
<p className="text-sm leading-6">
|
||||||
|
The week view is the only editable schedule lens. Month and year are
|
||||||
|
read-only overviews. A week starts as a draft; publishing makes it
|
||||||
|
visible to volunteers and starts the published/reminder mail.
|
||||||
|
</p>
|
||||||
|
<GuideFigure
|
||||||
|
src="/training/screens/admin-schedule.png"
|
||||||
|
alt="Week schedule grid with position columns and assignment controls"
|
||||||
|
caption="Each column is a position and each row is a service. Press an empty seat to assign someone."
|
||||||
|
/>
|
||||||
|
<GuideSteps>
|
||||||
|
<GuideStep>
|
||||||
|
Open <strong>Schedule</strong> and use the arrows to reach the week
|
||||||
|
you are building.
|
||||||
|
</GuideStep>
|
||||||
|
<GuideStep>
|
||||||
|
Press an empty seat and choose a volunteer. The candidate list is
|
||||||
|
ranked by skills, availability, and conflicts.
|
||||||
|
</GuideStep>
|
||||||
|
<GuideStep>
|
||||||
|
Use <strong>Auto-fill</strong> for a first pass over open seats, then
|
||||||
|
review every suggestion. The ranking does not know the relational
|
||||||
|
context or the last-minute holiday.
|
||||||
|
</GuideStep>
|
||||||
|
<GuideStep>
|
||||||
|
Read any conflict before saving. A hard conflict blocks the
|
||||||
|
assignment; a soft warning, such as exceeding a monthly cap, can be
|
||||||
|
overridden.
|
||||||
|
</GuideStep>
|
||||||
|
<GuideStep>
|
||||||
|
Press <strong>Publish</strong> when the week is ready. Publishing
|
||||||
|
makes the schedule visible and queues the published/reminder mail for
|
||||||
|
the people already on it.
|
||||||
|
</GuideStep>
|
||||||
|
</GuideSteps>
|
||||||
|
<GuideCallout title="Assigning sends mail before publish" tone="note">
|
||||||
|
<p>
|
||||||
|
A proposed assignment sends its “Can you serve on …?” email as soon
|
||||||
|
as you create it, even while the week is still a draft. Publishing
|
||||||
|
does not send that email again; it adds the published/reminder mail
|
||||||
|
for seats that are already filled. Draft weeks stay hidden from the
|
||||||
|
volunteer schedule until you publish.
|
||||||
|
</p>
|
||||||
|
</GuideCallout>
|
||||||
|
</GuideSection>
|
||||||
|
|
||||||
|
<GuideSection id="replies" title="3. Assignment emails and replies">
|
||||||
|
<p className="text-sm leading-6">
|
||||||
|
Every proposed seat gets an email with three single-use links. The
|
||||||
|
volunteer does not need an account or a login to use them.
|
||||||
|
</p>
|
||||||
|
<GuideFields
|
||||||
|
rows={[
|
||||||
|
{
|
||||||
|
label: "Confirm",
|
||||||
|
value:
|
||||||
|
"The volunteer accepts the seat. The assignment moves to confirmed and the schedule shows it immediately.",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: "Can’t make it",
|
||||||
|
value:
|
||||||
|
"The volunteer declines. The seat needs a replacement; use the schedule or Coverage to fill it.",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: "Propose another Sunday",
|
||||||
|
value:
|
||||||
|
"Records a pending request for a different date. It does not release the original seat or change the assignment by itself.",
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
<p className="text-sm leading-6">
|
||||||
|
Links are good for 14 days and work once. If a volunteer says the link
|
||||||
|
expired or was already used, do not forward someone else’s link; ask an
|
||||||
|
admin to help with the account or create the assignment again.
|
||||||
|
</p>
|
||||||
|
<GuideCallout title="What the volunteer sees" tone="tip">
|
||||||
|
<p>
|
||||||
|
The subject reads “Can you serve on [position] — [date]?” and the
|
||||||
|
body shows the service, call time, and location, followed by the
|
||||||
|
three buttons. The same reply buttons also appear on the{" "}
|
||||||
|
<code>/respond</code> page the link opens.
|
||||||
|
</p>
|
||||||
|
</GuideCallout>
|
||||||
|
</GuideSection>
|
||||||
|
|
||||||
|
<GuideSection id="coverage" title="4. Coverage and swaps">
|
||||||
|
<p className="text-sm leading-6">
|
||||||
|
Coverage is the working queue for changes. A pending request never
|
||||||
|
removes the volunteer: they stay responsible until you approve a
|
||||||
|
replacement or release the seat.
|
||||||
|
</p>
|
||||||
|
<GuideFigure
|
||||||
|
src="/training/screens/admin-coverage.png"
|
||||||
|
alt="Coverage page with pending swap requests and ranked replacements"
|
||||||
|
caption="Approve with a replacement, approve and release the seat, or decline and leave the volunteer in place."
|
||||||
|
/>
|
||||||
|
<h3 className="pt-2 text-base font-semibold">Handle a swap request</h3>
|
||||||
|
<GuideSteps>
|
||||||
|
<GuideStep>
|
||||||
|
Open <strong>Coverage</strong> and read the volunteer, seat, date,
|
||||||
|
and reason.
|
||||||
|
</GuideStep>
|
||||||
|
<GuideStep>
|
||||||
|
Review the ranked replacements and their warnings. Pick someone who
|
||||||
|
fits the skills and availability, not just the top score.
|
||||||
|
</GuideStep>
|
||||||
|
<GuideStep>
|
||||||
|
Choose <strong>Approve with replacement</strong> to cancel the
|
||||||
|
original assignment and place the replacement as proposed. The new
|
||||||
|
person receives the same accept/decline/propose email.
|
||||||
|
</GuideStep>
|
||||||
|
<GuideStep>
|
||||||
|
Choose <strong>Approve and release</strong> when nobody can take it.
|
||||||
|
The seat becomes open and the original assignment is kept in history.
|
||||||
|
</GuideStep>
|
||||||
|
<GuideStep>
|
||||||
|
Choose <strong>Decline</strong> when the request should not be
|
||||||
|
granted; the original volunteer stays on the seat.
|
||||||
|
</GuideStep>
|
||||||
|
</GuideSteps>
|
||||||
|
|
||||||
|
<h3 className="pt-2 text-base font-semibold">
|
||||||
|
Volunteers who propose another Sunday
|
||||||
|
</h3>
|
||||||
|
<p className="text-sm leading-6">
|
||||||
|
Proposals from the assignment email appear on Coverage under{" "}
|
||||||
|
<strong>Proposed another Sunday</strong>. The queue is read-only: it
|
||||||
|
records the volunteer, the current date, the proposed date, and any
|
||||||
|
note. Review it, then make the change yourself — assign a replacement,
|
||||||
|
move the seat, or clear it — and confirm the arrangement with the
|
||||||
|
volunteer. The original assignment stays live until you do.
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<h3 className="pt-2 text-base font-semibold">
|
||||||
|
Requests from outside the team
|
||||||
|
</h3>
|
||||||
|
<p className="text-sm leading-6">
|
||||||
|
Ministry leaders can submit the public form at{" "}
|
||||||
|
<code>/request-coverage</code> without an account. Accepted requests
|
||||||
|
become events: choose <strong>Create event</strong> to open one with
|
||||||
|
the requester and ministry attached, or <strong>Decline</strong> if it
|
||||||
|
is not a fit.
|
||||||
|
</p>
|
||||||
|
</GuideSection>
|
||||||
|
|
||||||
|
<GuideSection id="run-sheets" title="5. Run sheets">
|
||||||
|
<p className="text-sm leading-6">
|
||||||
|
Every service instance has one run sheet: speaker, message title,
|
||||||
|
stream and slides links, team notes, an ordered cue list, and a
|
||||||
|
pre/post checklist. Coordinators edit the details and cues; every
|
||||||
|
signed-in volunteer can tick checklist items.
|
||||||
|
</p>
|
||||||
|
<GuideFigure
|
||||||
|
src="/training/screens/admin-run-sheet.png"
|
||||||
|
alt="Run sheet editor with service details, cue list, and checklist"
|
||||||
|
caption="Prepare the sheet before the weekend, then let the team tick items as the service runs."
|
||||||
|
/>
|
||||||
|
<GuideSteps>
|
||||||
|
<GuideStep>
|
||||||
|
Open the run sheet from the schedule, Dashboard, or your own
|
||||||
|
next-serve card.
|
||||||
|
</GuideStep>
|
||||||
|
<GuideStep>
|
||||||
|
Fill in speaker, message title, stream link, slides link, and team
|
||||||
|
notes, then press <strong>Save details</strong>.
|
||||||
|
</GuideStep>
|
||||||
|
<GuideStep>
|
||||||
|
Edit cues inline and save each row. Add a cue at the bottom when the
|
||||||
|
service needs one.
|
||||||
|
</GuideStep>
|
||||||
|
<GuideStep>
|
||||||
|
Add pre-service or post-service checklist items for this service.
|
||||||
|
Defaults are seeded only once, so your edits stick.
|
||||||
|
</GuideStep>
|
||||||
|
<GuideStep>
|
||||||
|
Press <strong>Print</strong> for a clean booth copy.
|
||||||
|
</GuideStep>
|
||||||
|
</GuideSteps>
|
||||||
|
</GuideSection>
|
||||||
|
|
||||||
|
<GuideSection id="events" title="6. Events and media">
|
||||||
|
<p className="text-sm leading-6">
|
||||||
|
Events cover photoshoots, weddings, outreach nights, and other
|
||||||
|
coverage outside the weekly services. As a coordinator you see every
|
||||||
|
event and can assign photographers and editors; assigned volunteers see
|
||||||
|
only their events.
|
||||||
|
</p>
|
||||||
|
<GuideFigure
|
||||||
|
src="/training/screens/user-events.png"
|
||||||
|
alt="Events list with upcoming event cards and assignment counts"
|
||||||
|
caption="Open an event to see its brief, team, folders, and files."
|
||||||
|
/>
|
||||||
|
<GuideSteps>
|
||||||
|
<GuideStep>
|
||||||
|
Create the event with its date, time, location, and brief, or create
|
||||||
|
one from an accepted outside coverage request.
|
||||||
|
</GuideStep>
|
||||||
|
<GuideStep>
|
||||||
|
Assign the photographers and editors. Only assigned people and
|
||||||
|
managers can open the event and its files.
|
||||||
|
</GuideStep>
|
||||||
|
<GuideStep>
|
||||||
|
Create folders for originals and edited exports so the handoff is
|
||||||
|
obvious.
|
||||||
|
</GuideStep>
|
||||||
|
<GuideStep>
|
||||||
|
After the event, confirm the selects are uploaded and the folder is
|
||||||
|
ready. Archive the event when the work is finished; archived events
|
||||||
|
stay readable but stop accepting uploads.
|
||||||
|
</GuideStep>
|
||||||
|
</GuideSteps>
|
||||||
|
<GuideCallout title="Original files live on the media share" tone="note">
|
||||||
|
<p>
|
||||||
|
Event originals are stored on the configured church media share, not
|
||||||
|
in the database. The Media page is a convenience view and still
|
||||||
|
follows event assignment, so do not treat a copied link as public.
|
||||||
|
</p>
|
||||||
|
</GuideCallout>
|
||||||
|
</GuideSection>
|
||||||
|
|
||||||
|
<GuideSection id="announcements" title="7. Announcements and training">
|
||||||
|
<p className="text-sm leading-6">
|
||||||
|
Coordinators can write announcements. Training lessons are authored by
|
||||||
|
admins, but everyone can read the published lessons and the guide for
|
||||||
|
their role.
|
||||||
|
</p>
|
||||||
|
<GuideSteps>
|
||||||
|
<GuideStep>
|
||||||
|
Open <strong>Announcements</strong> and write a title and plain-text
|
||||||
|
message.
|
||||||
|
</GuideStep>
|
||||||
|
<GuideStep>
|
||||||
|
Keep <strong>Published</strong> ticked, or untick it to save a draft.
|
||||||
|
</GuideStep>
|
||||||
|
<GuideStep>
|
||||||
|
Use the row actions to publish, unpublish, or delete a post.
|
||||||
|
</GuideStep>
|
||||||
|
<GuideStep>
|
||||||
|
Open <strong>Training</strong> to read the coordinator guide and the
|
||||||
|
published lessons. If a lesson needs a correction, ask an admin.
|
||||||
|
</GuideStep>
|
||||||
|
</GuideSteps>
|
||||||
|
<GuideCallout title="Your guide is selected automatically" tone="tip">
|
||||||
|
<p>
|
||||||
|
Training shows the guide for your role. Admins see the Platform
|
||||||
|
administration guide, coordinators see this guide, and volunteers and
|
||||||
|
trainees see the Volunteer guide.
|
||||||
|
</p>
|
||||||
|
</GuideCallout>
|
||||||
|
</GuideSection>
|
||||||
|
|
||||||
|
<GuideSection id="exports" title="8. Print and CSV exports">
|
||||||
|
<GuideFields
|
||||||
|
rows={[
|
||||||
|
{
|
||||||
|
label: "Printable roster",
|
||||||
|
value:
|
||||||
|
"Open /schedule/print from Dashboard or Coverage. It prints the current week by service with call times and confirmation state, without the app navigation.",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: "Schedule CSV",
|
||||||
|
value:
|
||||||
|
"GET /api/export/schedule downloads assignments for a date range (four weeks by default).",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: "Serving history CSV",
|
||||||
|
value:
|
||||||
|
"GET /api/export/history downloads completed and no-show assignments for reviews and fairness checks.",
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
<GuideFigure
|
||||||
|
src="/training/screens/admin-print.png"
|
||||||
|
alt="Printable weekly roster with services, roles, and call times"
|
||||||
|
caption="The print view is deliberately plain: no navigation, no controls, just the roster."
|
||||||
|
/>
|
||||||
|
</GuideSection>
|
||||||
|
|
||||||
|
<GuideSection id="troubleshooting" title="9. Troubleshooting">
|
||||||
|
<GuideFields
|
||||||
|
rows={[
|
||||||
|
{
|
||||||
|
label: "A volunteer did not get the assignment email",
|
||||||
|
value:
|
||||||
|
"Ask them to check spam and confirm the address on their profile. Ask an admin to check the notification log; failed messages show the provider error and can be retried after the cause is fixed.",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: "A confirmation link does not work",
|
||||||
|
value:
|
||||||
|
"The links are single-use and expire after 14 days. Do not forward another person’s link; ask an admin for help with the account, or recreate the assignment.",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: "A seat will not accept an assignment",
|
||||||
|
value:
|
||||||
|
"Read the conflict. A blackout, duplicate service assignment, or missing core skill is a hard block. A monthly cap is a soft warning you may override.",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: "A volunteer cannot see the week",
|
||||||
|
value:
|
||||||
|
"Confirm the instance is published. Draft weeks are hidden from the volunteer schedule, even though the proposed email may already have gone out.",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: "A proposed Sunday is not on the schedule",
|
||||||
|
value:
|
||||||
|
"The proposal queue is read-only. Review it on Coverage, then change the schedule yourself and confirm the new arrangement with the volunteer.",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
label: "A coverage request disappeared",
|
||||||
|
value:
|
||||||
|
"Check whether the seat was cleared directly from the schedule. Approval keeps the cancelled assignment in history; a direct clear removes it.",
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
/>
|
||||||
|
<p className="text-sm leading-6">
|
||||||
|
When something looks wrong, note the date and service, take a
|
||||||
|
screenshot, and include the exact error text. That is far more useful
|
||||||
|
than “it didn’t work”.
|
||||||
|
</p>
|
||||||
|
</GuideSection>
|
||||||
|
</GuideShell>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
import { redirect } from "next/navigation";
|
||||||
|
import { auth } from "@/auth/config";
|
||||||
|
import type { SystemRole } from "@/auth/roles";
|
||||||
|
import { trainingGuideForRole } from "@/lib/training-guides";
|
||||||
|
|
||||||
|
/** `/training/guides` opens the guide for the signed-in person's role. */
|
||||||
|
export default async function TrainingGuidesPage() {
|
||||||
|
const session = await auth();
|
||||||
|
const role = (session?.user as { systemRole?: SystemRole } | undefined)
|
||||||
|
?.systemRole;
|
||||||
|
redirect(trainingGuideForRole(role).href);
|
||||||
|
}
|
||||||
@@ -128,6 +128,15 @@ export default function VolunteerGuidePage() {
|
|||||||
the top for the two things volunteers change most often.
|
the top for the two things volunteers change most often.
|
||||||
</GuideStep>
|
</GuideStep>
|
||||||
</GuideSteps>
|
</GuideSteps>
|
||||||
|
<GuideCallout title="Replying from email" tone="tip">
|
||||||
|
<p>
|
||||||
|
A proposed seat arrives by email with three links:{" "}
|
||||||
|
<strong>Confirm</strong>, <strong>Can’t make it</strong>, and{" "}
|
||||||
|
<strong>Propose another Sunday</strong>. No login is needed and each
|
||||||
|
link works once. If you propose another Sunday, the coordinator sees
|
||||||
|
the request but the seat stays yours until they change it.
|
||||||
|
</p>
|
||||||
|
</GuideCallout>
|
||||||
<GuideFigure
|
<GuideFigure
|
||||||
src="/training/screens/user-home-mobile.png"
|
src="/training/screens/user-home-mobile.png"
|
||||||
alt="Home page at phone width with the scrollable tab bar"
|
alt="Home page at phone width with the scrollable tab bar"
|
||||||
@@ -171,9 +180,11 @@ export default function VolunteerGuidePage() {
|
|||||||
/>
|
/>
|
||||||
<GuideCallout title="Draft weeks are invisible" tone="note">
|
<GuideCallout title="Draft weeks are invisible" tone="note">
|
||||||
<p>
|
<p>
|
||||||
A week that has not been published does not appear on your schedule
|
A week that has not been published does not appear on your schedule.
|
||||||
and does not generate assignment email. If you expected a date and
|
Assigning a seat can still send you a proposed email while the week
|
||||||
cannot see it, the week is probably still a draft.
|
is a draft, so reply to that email even if the date is not on the
|
||||||
|
schedule yet. Publishing is what makes the week visible and triggers
|
||||||
|
the published and reminder mail.
|
||||||
</p>
|
</p>
|
||||||
</GuideCallout>
|
</GuideCallout>
|
||||||
</GuideSection>
|
</GuideSection>
|
||||||
@@ -258,6 +269,14 @@ export default function VolunteerGuidePage() {
|
|||||||
You will see the change on Home once it is resolved.
|
You will see the change on Home once it is resolved.
|
||||||
</p>
|
</p>
|
||||||
</GuideCallout>
|
</GuideCallout>
|
||||||
|
<h3 className="pt-2 text-base font-semibold">Propose another Sunday</h3>
|
||||||
|
<p className="text-sm leading-6">
|
||||||
|
If you cannot serve the date but could serve a different Sunday, use{" "}
|
||||||
|
<strong>Propose another Sunday</strong> in the assignment email (or the
|
||||||
|
alternative link on the respond page). Tell the coordinator which date
|
||||||
|
works and why. This does not release the original seat: it stays yours
|
||||||
|
until a coordinator acts on the proposal and confirms the change.
|
||||||
|
</p>
|
||||||
<p className="text-sm leading-6">
|
<p className="text-sm leading-6">
|
||||||
Ministry leaders outside the team can request coverage through the
|
Ministry leaders outside the team can request coverage through the
|
||||||
public form at <code>/request-coverage</code>. If you are asked to
|
public form at <code>/request-coverage</code>. If you are asked to
|
||||||
@@ -395,24 +414,24 @@ export default function VolunteerGuidePage() {
|
|||||||
</p>
|
</p>
|
||||||
<GuideFigure
|
<GuideFigure
|
||||||
src="/training/screens/user-training.png"
|
src="/training/screens/user-training.png"
|
||||||
alt="Training page with the two full guides at the top and published lessons below"
|
alt="Training page with the guide for your role at the top and published lessons below"
|
||||||
caption="Start with the two full guides, then use the shorter lessons for specific skills."
|
caption="The guide for your role is at the top; use the shorter lessons for specific skills."
|
||||||
/>
|
/>
|
||||||
<GuideSteps>
|
<GuideSteps>
|
||||||
<GuideStep>
|
<GuideStep>
|
||||||
Open <strong>Training</strong> from the navigation.
|
Open <strong>Training</strong> from the navigation.
|
||||||
</GuideStep>
|
</GuideStep>
|
||||||
<GuideStep>
|
<GuideStep>
|
||||||
Read the <strong>Volunteer guide</strong> once end to end; it covers
|
Read the guide at the top of the page once end to end; it is chosen
|
||||||
every screen in this app.
|
for your role and covers every screen you can use.
|
||||||
</GuideStep>
|
</GuideStep>
|
||||||
<GuideStep>
|
<GuideStep>
|
||||||
Open an attachment to read or download it. Links open in a new tab so
|
Open an attachment to read or download it. Links open in a new tab so
|
||||||
you do not lose your place.
|
you do not lose your place.
|
||||||
</GuideStep>
|
</GuideStep>
|
||||||
<GuideStep>
|
<GuideStep>
|
||||||
Use the PDF download on either guide for an offline copy you can keep
|
Use the PDF download when the guide offers one, or print the page for
|
||||||
on your phone.
|
an offline copy you can keep on your phone.
|
||||||
</GuideStep>
|
</GuideStep>
|
||||||
</GuideSteps>
|
</GuideSteps>
|
||||||
<GuideCallout title="Read the run sheet lesson before your first serve" tone="tip">
|
<GuideCallout title="Read the run sheet lesson before your first serve" tone="tip">
|
||||||
|
|||||||
@@ -4,20 +4,36 @@ import { hasPermission } from "@/auth/permissions";
|
|||||||
import type { SystemRole } from "@/auth/roles";
|
import type { SystemRole } from "@/auth/roles";
|
||||||
import { listLessons } from "@/db/training";
|
import { listLessons } from "@/db/training";
|
||||||
import { trainingBodyToHtml } from "@/lib/rich-text";
|
import { trainingBodyToHtml } from "@/lib/rich-text";
|
||||||
|
import { trainingGuideForRole } from "@/lib/training-guides";
|
||||||
import { TrainingPanel } from "@/components/app/training-panel";
|
import { TrainingPanel } from "@/components/app/training-panel";
|
||||||
import { BookOpenCheck, Download, ShieldCheck, UserRound } from "lucide-react";
|
import {
|
||||||
|
BookOpenCheck,
|
||||||
|
ClipboardList,
|
||||||
|
Download,
|
||||||
|
ShieldCheck,
|
||||||
|
UserRound,
|
||||||
|
} from "lucide-react";
|
||||||
|
|
||||||
export const metadata = { title: "Training" };
|
export const metadata = { title: "Training" };
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Training content. Volunteers see published lessons and attachments; admins
|
* Training content. Volunteers see published lessons and attachments; admins
|
||||||
* can author, publish, upload, and delete. Content is stored in Postgres and
|
* can author, publish, upload, and delete. The full guide shown at the top is
|
||||||
|
* chosen from the signed-in person's role. Content is stored in Postgres and
|
||||||
* attachments under the uploads volume, so it is editable with no deploy.
|
* attachments under the uploads volume, so it is editable with no deploy.
|
||||||
*/
|
*/
|
||||||
export default async function TrainingPage() {
|
export default async function TrainingPage() {
|
||||||
const session = await auth();
|
const session = await auth();
|
||||||
const role = (session?.user as { systemRole?: SystemRole } | undefined)?.systemRole;
|
const role = (session?.user as { systemRole?: SystemRole } | undefined)
|
||||||
|
?.systemRole;
|
||||||
const canEdit = hasPermission(role, "training.author");
|
const canEdit = hasPermission(role, "training.author");
|
||||||
|
const guide = trainingGuideForRole(role);
|
||||||
|
const GuideIcon =
|
||||||
|
guide.key === "admin"
|
||||||
|
? ShieldCheck
|
||||||
|
: guide.key === "coordinator"
|
||||||
|
? ClipboardList
|
||||||
|
: UserRound;
|
||||||
const lessons = (await listLessons({ includeUnpublished: canEdit })).map(
|
const lessons = (await listLessons({ includeUnpublished: canEdit })).map(
|
||||||
(lesson) => ({
|
(lesson) => ({
|
||||||
...lesson,
|
...lesson,
|
||||||
@@ -36,67 +52,37 @@ export default async function TrainingPage() {
|
|||||||
<section aria-labelledby="full-guides" className="space-y-3">
|
<section aria-labelledby="full-guides" className="space-y-3">
|
||||||
<div>
|
<div>
|
||||||
<h2 id="full-guides" className="text-base font-semibold tracking-tight">
|
<h2 id="full-guides" className="text-base font-semibold tracking-tight">
|
||||||
Full guides
|
Your guide
|
||||||
</h2>
|
</h2>
|
||||||
<p className="text-sm text-muted-foreground">
|
<p className="text-sm text-muted-foreground">
|
||||||
Complete, illustrated walkthroughs with screenshots. Read them here
|
The complete, illustrated walkthrough for your role. Read it here or
|
||||||
or download the PDF for printing and offline use.
|
download the PDF where one is available.
|
||||||
</p>
|
</p>
|
||||||
</div>
|
</div>
|
||||||
<div className="grid gap-3 md:grid-cols-2">
|
<div className="rounded-md border border-border p-4">
|
||||||
<div className="flex flex-col rounded-md border border-border p-4">
|
<div className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
|
||||||
<div className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
|
<GuideIcon className="h-4 w-4" aria-hidden="true" />
|
||||||
<ShieldCheck className="h-4 w-4" aria-hidden="true" />
|
{guide.audience}
|
||||||
Admins
|
|
||||||
</div>
|
|
||||||
<h3 className="mt-2 text-base font-semibold">
|
|
||||||
Platform administration guide
|
|
||||||
</h3>
|
|
||||||
<p className="mt-1 flex-1 text-sm leading-6 text-muted-foreground">
|
|
||||||
People and access, skill verification, positions, services and
|
|
||||||
publishing, coverage, run sheets, email, notifications, backups,
|
|
||||||
and exports.
|
|
||||||
</p>
|
|
||||||
<div className="mt-3 flex flex-wrap items-center gap-4 text-sm font-medium">
|
|
||||||
<Link href="/training/guides/admin" className="text-primary underline">
|
|
||||||
<BookOpenCheck className="mr-1 inline h-4 w-4" aria-hidden="true" />
|
|
||||||
Read the guide
|
|
||||||
</Link>
|
|
||||||
<a
|
|
||||||
href="/training/media-team-admin-guide.pdf"
|
|
||||||
download
|
|
||||||
className="inline-flex items-center gap-1 text-primary underline"
|
|
||||||
>
|
|
||||||
<Download className="h-4 w-4" aria-hidden="true" />
|
|
||||||
Download PDF
|
|
||||||
</a>
|
|
||||||
</div>
|
|
||||||
</div>
|
</div>
|
||||||
|
<h3 className="mt-2 text-base font-semibold">{guide.title}</h3>
|
||||||
<div className="flex flex-col rounded-md border border-border p-4">
|
<p className="mt-1 text-sm leading-6 text-muted-foreground">
|
||||||
<div className="flex items-center gap-2 text-xs font-semibold uppercase tracking-wide text-muted-foreground">
|
{guide.description}
|
||||||
<UserRound className="h-4 w-4" aria-hidden="true" />
|
</p>
|
||||||
Volunteers & trainees
|
<div className="mt-3 flex flex-wrap items-center gap-4 text-sm font-medium">
|
||||||
</div>
|
<Link href={guide.href} className="text-primary underline">
|
||||||
<h3 className="mt-2 text-base font-semibold">Volunteer guide</h3>
|
<BookOpenCheck className="mr-1 inline h-4 w-4" aria-hidden="true" />
|
||||||
<p className="mt-1 flex-1 text-sm leading-6 text-muted-foreground">
|
Read your guide
|
||||||
Signing in, your next serve, the schedule, availability, swaps,
|
</Link>
|
||||||
run sheets, events and media, training, profile, and reminders.
|
{guide.pdfHref && guide.pdfLabel ? (
|
||||||
</p>
|
|
||||||
<div className="mt-3 flex flex-wrap items-center gap-4 text-sm font-medium">
|
|
||||||
<Link href="/training/guides/user" className="text-primary underline">
|
|
||||||
<BookOpenCheck className="mr-1 inline h-4 w-4" aria-hidden="true" />
|
|
||||||
Read the guide
|
|
||||||
</Link>
|
|
||||||
<a
|
<a
|
||||||
href="/training/media-team-user-guide.pdf"
|
href={guide.pdfHref}
|
||||||
download
|
download
|
||||||
className="inline-flex items-center gap-1 text-primary underline"
|
className="inline-flex items-center gap-1 text-primary underline"
|
||||||
>
|
>
|
||||||
<Download className="h-4 w-4" aria-hidden="true" />
|
<Download className="h-4 w-4" aria-hidden="true" />
|
||||||
Download PDF
|
{guide.pdfLabel}
|
||||||
</a>
|
</a>
|
||||||
</div>
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
</section>
|
</section>
|
||||||
|
|||||||
@@ -8,11 +8,13 @@ const bodySchema = z.object({ action: z.enum(["confirm", "decline"]) });
|
|||||||
function errorStatus(code: RespondError["code"]): number {
|
function errorStatus(code: RespondError["code"]): number {
|
||||||
switch (code) {
|
switch (code) {
|
||||||
case "unknown_assignment":
|
case "unknown_assignment":
|
||||||
|
case "unknown_instance":
|
||||||
return 404;
|
return 404;
|
||||||
case "wrong_volunteer":
|
case "wrong_volunteer":
|
||||||
return 403;
|
return 403;
|
||||||
case "not_actionable":
|
case "not_actionable":
|
||||||
case "already_used":
|
case "already_used":
|
||||||
|
case "invalid_alternative":
|
||||||
return 409;
|
return 409;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { NextRequest } from "next/server";
|
|||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { and, eq, inArray } from "drizzle-orm";
|
import { and, eq, inArray } from "drizzle-orm";
|
||||||
import { auth } from "@/auth/config";
|
import { auth } from "@/auth/config";
|
||||||
|
import { requestOrigin } from "@/auth/magic-link";
|
||||||
import { AuthError, requirePermission } from "@/auth/permissions";
|
import { AuthError, requirePermission } from "@/auth/permissions";
|
||||||
import type { SystemRole } from "@/auth/roles";
|
import type { SystemRole } from "@/auth/roles";
|
||||||
import { db } from "@/db";
|
import { db } from "@/db";
|
||||||
@@ -16,8 +17,10 @@ import {
|
|||||||
AssignFactError,
|
AssignFactError,
|
||||||
resolveAssignFacts,
|
resolveAssignFacts,
|
||||||
} from "@/db/assignments";
|
} from "@/db/assignments";
|
||||||
import { cancelAssignmentNotifications } from "@/db/outbox";
|
import {
|
||||||
import { enqueuePublishNotifications } from "@/db/outbox";
|
cancelAssignmentNotifications,
|
||||||
|
enqueueAssignmentProposed,
|
||||||
|
} from "@/db/outbox";
|
||||||
import { enqueueRemindersForInstance } from "@/db/reminders";
|
import { enqueueRemindersForInstance } from "@/db/reminders";
|
||||||
import { classifyConflicts, hardConflicts } from "@/domain/conflicts";
|
import { classifyConflicts, hardConflicts } from "@/domain/conflicts";
|
||||||
import { uuidv7 } from "@/lib/uuid";
|
import { uuidv7 } from "@/lib/uuid";
|
||||||
@@ -195,6 +198,8 @@ export const POST = async (req: NextRequest) => {
|
|||||||
.limit(1);
|
.limit(1);
|
||||||
|
|
||||||
const assignmentId = uuidv7();
|
const assignmentId = uuidv7();
|
||||||
|
const now = new Date();
|
||||||
|
const appOrigin = requestOrigin(req);
|
||||||
await db.transaction(async (tx) => {
|
await db.transaction(async (tx) => {
|
||||||
await tx.insert(assignments).values({
|
await tx.insert(assignments).values({
|
||||||
id: assignmentId,
|
id: assignmentId,
|
||||||
@@ -203,7 +208,7 @@ export const POST = async (req: NextRequest) => {
|
|||||||
status: "proposed",
|
status: "proposed",
|
||||||
source: "manual",
|
source: "manual",
|
||||||
assignedBy: actorId,
|
assignedBy: actorId,
|
||||||
assignedAt: new Date(),
|
assignedAt: now,
|
||||||
});
|
});
|
||||||
await tx
|
await tx
|
||||||
.update(slots)
|
.update(slots)
|
||||||
@@ -224,12 +229,12 @@ export const POST = async (req: NextRequest) => {
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
// A published week's mail is written at publish time; a seat added later
|
// The proposed email always goes out, whether the week is draft or
|
||||||
// would otherwise never be announced. Both enqueues are idempotent on
|
// published: the volunteer has to accept, decline, or propose another
|
||||||
// dedupe_key, so existing rows are untouched.
|
// Sunday. On a published week only the reminders need topping up.
|
||||||
|
await enqueueAssignmentProposed(tx, assignmentId, { now, appOrigin });
|
||||||
if (instance?.status === "published") {
|
if (instance?.status === "published") {
|
||||||
await enqueuePublishNotifications(tx, instance.id, { now: new Date() });
|
await enqueueRemindersForInstance(tx, instance.id, { now, appOrigin });
|
||||||
await enqueueRemindersForInstance(tx, instance.id, { now: new Date() });
|
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -2,6 +2,7 @@ import { NextRequest } from "next/server";
|
|||||||
import { authenticateBridge } from "@/db/bridge";
|
import { authenticateBridge } from "@/db/bridge";
|
||||||
import {
|
import {
|
||||||
BRIDGE_SESSION_TTL_SECONDS,
|
BRIDGE_SESSION_TTL_SECONDS,
|
||||||
|
bridgeReturnUrl,
|
||||||
signBridgeToken,
|
signBridgeToken,
|
||||||
} from "@/lib/bridge";
|
} from "@/lib/bridge";
|
||||||
import { errorResponse, jsonResponse } from "@/lib/http";
|
import { errorResponse, jsonResponse } from "@/lib/http";
|
||||||
@@ -36,5 +37,9 @@ export const POST = async (
|
|||||||
sessionId: auth.session.id,
|
sessionId: auth.session.id,
|
||||||
eventId: auth.session.eventId,
|
eventId: auth.session.eventId,
|
||||||
expiresAt: auth.session.expiresAt,
|
expiresAt: auth.session.expiresAt,
|
||||||
|
// Carried from the browser-facing request that opened the editor so the
|
||||||
|
// editor can link back to the address the user actually reached.
|
||||||
|
returnUrl:
|
||||||
|
auth.payload.ret ?? bridgeReturnUrl(auth.session.eventId) ?? null,
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -4,11 +4,17 @@ import { mkdir, rename, unlink, writeFile } from "node:fs/promises";
|
|||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { authenticateBridge, getBridgePhoto, saveBridgeRender } from "@/db/bridge";
|
import { authenticateBridge, getBridgePhoto, saveBridgeRender } from "@/db/bridge";
|
||||||
import {
|
import {
|
||||||
|
advancedStoredNameForEventPhoto,
|
||||||
editedStoredNameForEventPhoto,
|
editedStoredNameForEventPhoto,
|
||||||
eventPhotoPath,
|
eventPhotoPath,
|
||||||
} from "@/lib/event-photos";
|
} from "@/lib/event-photos";
|
||||||
import { errorResponse, jsonResponse } from "@/lib/http";
|
import { errorResponse, jsonResponse } from "@/lib/http";
|
||||||
import { mediaStorage } from "@/lib/media-storage";
|
import { mediaStorage } from "@/lib/media-storage";
|
||||||
|
import {
|
||||||
|
defaultPhotoAdjustments,
|
||||||
|
parseStoredPhotoAdjustments,
|
||||||
|
} from "@/lib/photo-adjustments";
|
||||||
|
import { renderPhotoJpeg } from "@/lib/photo-render";
|
||||||
|
|
||||||
const MAX_BODY_BYTES = 64 * 1024 * 1024;
|
const MAX_BODY_BYTES = 64 * 1024 * 1024;
|
||||||
const MAX_RECIPE_BYTES = 512 * 1024;
|
const MAX_RECIPE_BYTES = 512 * 1024;
|
||||||
@@ -19,9 +25,10 @@ const MAX_JPEG_BYTES = 48 * 1024 * 1024;
|
|||||||
* Body: { jpeg: <base64>, edits: <advanced recipe>, width, height }
|
* Body: { jpeg: <base64>, edits: <advanced recipe>, width, height }
|
||||||
*
|
*
|
||||||
* The advanced editor renders in the browser, so the server only has to store
|
* The advanced editor renders in the browser, so the server only has to store
|
||||||
* the result. The JPEG becomes the photo's edited version (used by the gallery,
|
* the result. The JPEG is kept as the photo's advanced render (its own file, so
|
||||||
* thumbnails and delivery exports) and the recipe is kept so the editor can be
|
* the simple editor can layer on top) and the recipe is kept so the editor can
|
||||||
* reopened with its sliders intact.
|
* be reopened with its sliders intact. Any simple-editor layer is rebuilt on
|
||||||
|
* top of the new render, so the two editors never disagree.
|
||||||
*/
|
*/
|
||||||
export const POST = async (
|
export const POST = async (
|
||||||
req: NextRequest,
|
req: NextRequest,
|
||||||
@@ -70,11 +77,11 @@ export const POST = async (
|
|||||||
const storage = await mediaStorage();
|
const storage = await mediaStorage();
|
||||||
if (!storage.ok) return errorResponse(503, storage.message);
|
if (!storage.ok) return errorResponse(503, storage.message);
|
||||||
|
|
||||||
const storedName = editedStoredNameForEventPhoto(
|
const advancedStoredName = advancedStoredNameForEventPhoto(
|
||||||
auth.session.eventId,
|
auth.session.eventId,
|
||||||
photo.id,
|
photo.id,
|
||||||
);
|
);
|
||||||
const target = eventPhotoPath(storage.root, storedName);
|
const target = eventPhotoPath(storage.root, advancedStoredName);
|
||||||
const temporary = `${target}.${randomUUID()}.tmp`;
|
const temporary = `${target}.${randomUUID()}.tmp`;
|
||||||
try {
|
try {
|
||||||
await mkdir(path.dirname(target), { recursive: true });
|
await mkdir(path.dirname(target), { recursive: true });
|
||||||
@@ -85,10 +92,40 @@ export const POST = async (
|
|||||||
return errorResponse(500, "the edited image could not be saved");
|
return errorResponse(500, "the edited image could not be saved");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// A photo the simple editor also adjusted keeps that layer: re-render it on
|
||||||
|
// the new advanced render so the saved JPEG still shows both recipes.
|
||||||
|
const quick = parseStoredPhotoAdjustments(photo.editJson);
|
||||||
|
const hasQuickLayer =
|
||||||
|
JSON.stringify(quick) !== JSON.stringify(defaultPhotoAdjustments());
|
||||||
|
let editedStoredName = advancedStoredName;
|
||||||
|
let editedSizeBytes = data.byteLength;
|
||||||
|
if (hasQuickLayer) {
|
||||||
|
editedStoredName = editedStoredNameForEventPhoto(auth.session.eventId, photo.id);
|
||||||
|
const layered = eventPhotoPath(storage.root, editedStoredName);
|
||||||
|
try {
|
||||||
|
const rendered = await renderPhotoJpeg({
|
||||||
|
filePath: target,
|
||||||
|
kind: "image",
|
||||||
|
adjustments: quick,
|
||||||
|
});
|
||||||
|
await mkdir(path.dirname(layered), { recursive: true });
|
||||||
|
const layeredTemporary = `${layered}.${randomUUID()}.tmp`;
|
||||||
|
await writeFile(layeredTemporary, rendered.data);
|
||||||
|
await rename(layeredTemporary, layered);
|
||||||
|
editedSizeBytes = rendered.data.byteLength;
|
||||||
|
} catch (error) {
|
||||||
|
console.error("simple edit layer rebuild failed", error);
|
||||||
|
return errorResponse(
|
||||||
|
500,
|
||||||
|
"the simple editor's adjustments could not be rebuilt on the new render",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
const editedAt = await saveBridgeRender({
|
const editedAt = await saveBridgeRender({
|
||||||
photoId: photo.id,
|
photoId: photo.id,
|
||||||
editedStoredName: storedName,
|
editedStoredName,
|
||||||
editedSizeBytes: data.byteLength,
|
editedSizeBytes,
|
||||||
advancedEditJson: recipe,
|
advancedEditJson: recipe,
|
||||||
editedBy: auth.user.id,
|
editedBy: auth.user.id,
|
||||||
});
|
});
|
||||||
@@ -100,6 +137,6 @@ export const POST = async (
|
|||||||
return jsonResponse({
|
return jsonResponse({
|
||||||
ok: true,
|
ok: true,
|
||||||
editedAt,
|
editedAt,
|
||||||
editedSizeBytes: data.byteLength,
|
editedSizeBytes,
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -4,9 +4,9 @@ import { createReadStream } from "node:fs";
|
|||||||
import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
|
import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { Readable } from "node:stream";
|
import { Readable } from "node:stream";
|
||||||
import sharp from "sharp";
|
|
||||||
import { authenticateBridge, getBridgePhoto } from "@/db/bridge";
|
import { authenticateBridge, getBridgePhoto } from "@/db/bridge";
|
||||||
import {
|
import {
|
||||||
|
bridgeEditedThumbStoredNameForEventPhoto,
|
||||||
bridgeProxyStoredNameForEventPhoto,
|
bridgeProxyStoredNameForEventPhoto,
|
||||||
bridgeThumbStoredNameForEventPhoto,
|
bridgeThumbStoredNameForEventPhoto,
|
||||||
eventPhotoPath,
|
eventPhotoPath,
|
||||||
@@ -14,7 +14,7 @@ import {
|
|||||||
import { errorResponse } from "@/lib/http";
|
import { errorResponse } from "@/lib/http";
|
||||||
import { mediaStorage } from "@/lib/media-storage";
|
import { mediaStorage } from "@/lib/media-storage";
|
||||||
import { defaultPhotoAdjustments } from "@/lib/photo-adjustments";
|
import { defaultPhotoAdjustments } from "@/lib/photo-adjustments";
|
||||||
import { renderPhotoJpeg } from "@/lib/photo-render";
|
import { renderPhotoJpeg, renderPhotoThumbnail } from "@/lib/photo-render";
|
||||||
|
|
||||||
const PROXY_MAX_EDGE = 4000;
|
const PROXY_MAX_EDGE = 4000;
|
||||||
const THUMB_MAX_EDGE = 480;
|
const THUMB_MAX_EDGE = 480;
|
||||||
@@ -31,14 +31,25 @@ function imageResponse(data: Buffer, contentType = "image/jpeg"): Response {
|
|||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Reads a cached derivative or writes it atomically on first use. */
|
/**
|
||||||
|
* Reads a cached derivative or writes it atomically on first use. When
|
||||||
|
* `newerThan` is given, a cache older than that timestamp is rebuilt, so a
|
||||||
|
* thumbnail of a re-rendered edit never goes stale.
|
||||||
|
*/
|
||||||
async function cached(
|
async function cached(
|
||||||
filePath: string,
|
filePath: string,
|
||||||
produce: () => Promise<Buffer>,
|
produce: () => Promise<Buffer>,
|
||||||
|
newerThan?: number,
|
||||||
): Promise<Buffer> {
|
): Promise<Buffer> {
|
||||||
try {
|
try {
|
||||||
const info = await stat(filePath);
|
const info = await stat(filePath);
|
||||||
if (info.isFile() && info.size > 0) return readFile(filePath);
|
if (
|
||||||
|
info.isFile() &&
|
||||||
|
info.size > 0 &&
|
||||||
|
(newerThan === undefined || info.mtimeMs >= newerThan)
|
||||||
|
) {
|
||||||
|
return readFile(filePath);
|
||||||
|
}
|
||||||
} catch {
|
} catch {
|
||||||
// Not generated yet.
|
// Not generated yet.
|
||||||
}
|
}
|
||||||
@@ -51,24 +62,12 @@ async function cached(
|
|||||||
}
|
}
|
||||||
|
|
||||||
async function thumbFor(filePath: string, kind: "raw" | "image") {
|
async function thumbFor(filePath: string, kind: "raw" | "image") {
|
||||||
if (kind === "raw") {
|
return renderPhotoThumbnail({
|
||||||
const rendered = await renderPhotoJpeg({
|
filePath,
|
||||||
filePath,
|
kind,
|
||||||
kind,
|
maxDimension: THUMB_MAX_EDGE,
|
||||||
adjustments: defaultPhotoAdjustments(),
|
quality: 82,
|
||||||
maxDimension: THUMB_MAX_EDGE,
|
});
|
||||||
});
|
|
||||||
return rendered.data;
|
|
||||||
}
|
|
||||||
return sharp(filePath)
|
|
||||||
.resize({
|
|
||||||
width: THUMB_MAX_EDGE,
|
|
||||||
height: THUMB_MAX_EDGE,
|
|
||||||
fit: "inside",
|
|
||||||
withoutEnlargement: true,
|
|
||||||
})
|
|
||||||
.jpeg({ quality: 82, mozjpeg: true })
|
|
||||||
.toBuffer();
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -126,13 +125,33 @@ export const GET = async (
|
|||||||
}
|
}
|
||||||
|
|
||||||
if (variant === "thumb") {
|
if (variant === "thumb") {
|
||||||
|
// With a saved edit, the grid should show the photo as it was developed —
|
||||||
|
// the editor's own look — not the untouched original.
|
||||||
|
let sourcePath = originalPath;
|
||||||
|
let sourceKind: "raw" | "image" = photo.kind;
|
||||||
|
let thumbName = bridgeThumbStoredNameForEventPhoto(
|
||||||
|
auth.session.eventId,
|
||||||
|
photo.id,
|
||||||
|
);
|
||||||
|
let editedMtime: number | undefined;
|
||||||
|
if (photo.editedStoredName) {
|
||||||
|
const editedPath = eventPhotoPath(storage.root, photo.editedStoredName);
|
||||||
|
const edited = await stat(editedPath).catch(() => null);
|
||||||
|
if (edited?.isFile()) {
|
||||||
|
sourcePath = editedPath;
|
||||||
|
sourceKind = "image";
|
||||||
|
editedMtime = edited.mtimeMs;
|
||||||
|
thumbName = bridgeEditedThumbStoredNameForEventPhoto(
|
||||||
|
auth.session.eventId,
|
||||||
|
photo.id,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
try {
|
try {
|
||||||
const thumbPath = eventPhotoPath(
|
const data = await cached(
|
||||||
storage.root,
|
eventPhotoPath(storage.root, thumbName),
|
||||||
bridgeThumbStoredNameForEventPhoto(auth.session.eventId, photo.id),
|
() => thumbFor(sourcePath, sourceKind),
|
||||||
);
|
editedMtime,
|
||||||
const data = await cached(thumbPath, () =>
|
|
||||||
thumbFor(originalPath, photo.kind),
|
|
||||||
);
|
);
|
||||||
return imageResponse(data);
|
return imageResponse(data);
|
||||||
} catch {
|
} catch {
|
||||||
|
|||||||
@@ -10,6 +10,17 @@ import { mediaStorage } from "@/lib/media-storage";
|
|||||||
import { eventPhotoPath } from "@/lib/event-photos";
|
import { eventPhotoPath } from "@/lib/event-photos";
|
||||||
import sharp from "sharp";
|
import sharp from "sharp";
|
||||||
|
|
||||||
|
/** The advanced editor's saved slider recipe, or null when it cannot be read. */
|
||||||
|
function savedRecipe(json: string | null): unknown {
|
||||||
|
if (!json) return null;
|
||||||
|
try {
|
||||||
|
const parsed = JSON.parse(json) as unknown;
|
||||||
|
return parsed && typeof parsed === "object" ? parsed : null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/** Reads the header dimensions without decoding the whole file. */
|
/** Reads the header dimensions without decoding the whole file. */
|
||||||
async function imageSize(
|
async function imageSize(
|
||||||
path: string,
|
path: string,
|
||||||
@@ -77,6 +88,12 @@ export const GET = async (
|
|||||||
width: sizes.get(row.id)?.width ?? 0,
|
width: sizes.get(row.id)?.width ?? 0,
|
||||||
height: sizes.get(row.id)?.height ?? 0,
|
height: sizes.get(row.id)?.height ?? 0,
|
||||||
takenAt: row.createdAt,
|
takenAt: row.createdAt,
|
||||||
|
// Reopening the editor restores the sliders exactly as they were saved;
|
||||||
|
// the editor falls back to neutral when this is null.
|
||||||
|
edits: savedRecipe(row.advancedEditJson),
|
||||||
|
// Stamps the thumbnail URL so a newly saved edit is not masked by a
|
||||||
|
// cached grid thumbnail from before it was rendered.
|
||||||
|
editedAt: row.editedAt,
|
||||||
})),
|
})),
|
||||||
editor: { returnUrl: bridgeReturnUrl(auth.session.eventId) },
|
editor: { returnUrl: bridgeReturnUrl(auth.session.eventId) },
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -2,7 +2,12 @@ import { NextRequest } from "next/server";
|
|||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { gateOrUser } from "@/auth/api";
|
import { gateOrUser } from "@/auth/api";
|
||||||
import { approveUser } from "@/auth/invites";
|
import { approveUser } from "@/auth/invites";
|
||||||
import { APP_ORIGIN, requestOrigin, signMagicToken } from "@/auth/magic-link";
|
import {
|
||||||
|
APP_ORIGIN,
|
||||||
|
INVITE_LINK_TTL,
|
||||||
|
requestOrigin,
|
||||||
|
signMagicToken,
|
||||||
|
} from "@/auth/magic-link";
|
||||||
import { getUserById } from "@/db/users";
|
import { getUserById } from "@/db/users";
|
||||||
import { sendWelcomeEmail } from "@/lib/welcome-email";
|
import { sendWelcomeEmail } from "@/lib/welcome-email";
|
||||||
|
|
||||||
@@ -48,7 +53,7 @@ export const POST = async (req: NextRequest) => {
|
|||||||
const approved = await getUserById(user.id);
|
const approved = await getUserById(user.id);
|
||||||
let welcome: { delivered: boolean; transport: string | null } | null = null;
|
let welcome: { delivered: boolean; transport: string | null } | null = null;
|
||||||
if (approved) {
|
if (approved) {
|
||||||
const token = await signMagicToken(approved.email);
|
const token = await signMagicToken(approved.email, INVITE_LINK_TTL);
|
||||||
const origin = requestOrigin(req) || APP_ORIGIN;
|
const origin = requestOrigin(req) || APP_ORIGIN;
|
||||||
const url = `${origin}/api/dev/complete?token=${encodeURIComponent(
|
const url = `${origin}/api/dev/complete?token=${encodeURIComponent(
|
||||||
token,
|
token,
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import {
|
|||||||
requestOrigin,
|
requestOrigin,
|
||||||
} from "@/auth/magic-link";
|
} from "@/auth/magic-link";
|
||||||
import { rateLimit } from "@/lib/rate-limit";
|
import { rateLimit } from "@/lib/rate-limit";
|
||||||
|
import { hasPasswordProtectedAdmin } from "@/db/users";
|
||||||
|
|
||||||
const JSON_HEADERS = { "content-type": "application/json" };
|
const JSON_HEADERS = { "content-type": "application/json" };
|
||||||
const bodySchema = z.object({ email: z.string().email() });
|
const bodySchema = z.object({ email: z.string().email() });
|
||||||
@@ -59,11 +60,29 @@ export const POST = async (req: NextRequest) => {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// Bootstrap only. Once an admin has a real password, a public request for
|
||||||
|
// that admin's email must not mint a session link. New-account and recovery
|
||||||
|
// links are still issued by signed-in admins from the People panel.
|
||||||
|
if (await hasPasswordProtectedAdmin()) {
|
||||||
|
return new Response(
|
||||||
|
JSON.stringify({
|
||||||
|
error:
|
||||||
|
"Use your username and password to sign in. Contact an admin if you need help.",
|
||||||
|
}),
|
||||||
|
{ status: 403, headers: JSON_HEADERS },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const result = await requestMagicLink(parsed.data.email, {
|
const result = await requestMagicLink(parsed.data.email, {
|
||||||
origin: requestOrigin(req),
|
origin: requestOrigin(req),
|
||||||
});
|
});
|
||||||
return new Response(JSON.stringify(result), {
|
// Never expose account metadata to an unauthenticated caller. The dev
|
||||||
|
// transport may still return the URL for local bootstrap/tests; production
|
||||||
|
// turns that transport off and the login UI never renders a URL anyway.
|
||||||
|
const payload: { ok: true; url?: string } = { ok: true };
|
||||||
|
if ("url" in result && result.url) payload.url = result.url;
|
||||||
|
return new Response(JSON.stringify(payload), {
|
||||||
status: 200,
|
status: 200,
|
||||||
headers: JSON_HEADERS,
|
headers: JSON_HEADERS,
|
||||||
});
|
});
|
||||||
|
|||||||
@@ -0,0 +1,61 @@
|
|||||||
|
import { NextRequest } from "next/server";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { gateOrUser } from "@/auth/api";
|
||||||
|
import {
|
||||||
|
createSpecialService,
|
||||||
|
SpecialServiceError,
|
||||||
|
} from "@/db/specials";
|
||||||
|
import { errorResponse, jsonResponse } from "@/lib/http";
|
||||||
|
|
||||||
|
const schema = z.object({
|
||||||
|
title: z.string().trim().min(1).max(140),
|
||||||
|
date: z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "choose a valid date"),
|
||||||
|
startTimeLocal: z
|
||||||
|
.string()
|
||||||
|
.regex(/^\d{2}:\d{2}$/, "choose a valid start time"),
|
||||||
|
durationMinutes: z.number().int().min(5).max(600).default(60),
|
||||||
|
location: z.string().trim().max(200).nullable().optional(),
|
||||||
|
notes: z.string().trim().max(2000).nullable().optional(),
|
||||||
|
roleIds: z.array(z.string().min(1)).max(12).default([]),
|
||||||
|
photographerId: z.string().min(1).nullable().optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
/**
|
||||||
|
* POST /api/dev/schedule/special
|
||||||
|
*
|
||||||
|
* Adds a one-off dated service to the schedule with only the positions the
|
||||||
|
* scheduler selected. Picking a photographer also creates their media event.
|
||||||
|
* Coordinators and admins only (`schedule.publish`).
|
||||||
|
*/
|
||||||
|
export const POST = async (req: NextRequest) => {
|
||||||
|
const gate = await gateOrUser("schedule.publish");
|
||||||
|
if (gate instanceof Response) return gate;
|
||||||
|
|
||||||
|
const parsed = schema.safeParse(await req.json().catch(() => null));
|
||||||
|
if (!parsed.success) {
|
||||||
|
return errorResponse(
|
||||||
|
400,
|
||||||
|
parsed.error.issues[0]?.message ?? "invalid special service",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await createSpecialService({
|
||||||
|
...parsed.data,
|
||||||
|
createdBy: gate.id,
|
||||||
|
});
|
||||||
|
return jsonResponse(result, 201);
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof SpecialServiceError) {
|
||||||
|
return errorResponse(error.status, error.message);
|
||||||
|
}
|
||||||
|
if ((error as { code?: string }).code === "23505") {
|
||||||
|
return errorResponse(
|
||||||
|
409,
|
||||||
|
"a special service already exists at that date and time",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
console.error("[special-service] create failed:", error);
|
||||||
|
return errorResponse(500, "failed to add the special service");
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -1,7 +1,12 @@
|
|||||||
import { NextRequest } from "next/server";
|
import { NextRequest } from "next/server";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
import { gateOrUser } from "@/auth/api";
|
import { gateOrUser } from "@/auth/api";
|
||||||
import { APP_ORIGIN, requestOrigin, signMagicToken } from "@/auth/magic-link";
|
import {
|
||||||
|
APP_ORIGIN,
|
||||||
|
INVITE_LINK_TTL,
|
||||||
|
requestOrigin,
|
||||||
|
signMagicToken,
|
||||||
|
} from "@/auth/magic-link";
|
||||||
import { validateUsername } from "@/auth/password";
|
import { validateUsername } from "@/auth/password";
|
||||||
import { SYSTEM_ROLES } from "@/auth/roles";
|
import { SYSTEM_ROLES } from "@/auth/roles";
|
||||||
import { db } from "@/db";
|
import { db } from "@/db";
|
||||||
@@ -128,8 +133,9 @@ export const POST = async (req: NextRequest) => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
// Hand the admin a sign-in link, exactly like the invite flow does. The
|
// Hand the admin a sign-in link, exactly like the invite flow does. The
|
||||||
// link only works once the account is active.
|
// link only works once the account is active. It is an invite, not a
|
||||||
const token = await signMagicToken(user.email);
|
// just-requested sign-in, so it gets the invite lifetime.
|
||||||
|
const token = await signMagicToken(user.email, INVITE_LINK_TTL);
|
||||||
const origin = requestOrigin(req) || APP_ORIGIN;
|
const origin = requestOrigin(req) || APP_ORIGIN;
|
||||||
const url = `${origin}/api/dev/complete?token=${encodeURIComponent(
|
const url = `${origin}/api/dev/complete?token=${encodeURIComponent(
|
||||||
token,
|
token,
|
||||||
|
|||||||
@@ -1,5 +1,6 @@
|
|||||||
import { NextRequest } from "next/server";
|
import { NextRequest } from "next/server";
|
||||||
import { gateSession } from "@/auth/api";
|
import { gateSession } from "@/auth/api";
|
||||||
|
import { requestOrigin } from "@/auth/magic-link";
|
||||||
import { bridgeUser, createBridgeSession } from "@/db/bridge";
|
import { bridgeUser, createBridgeSession } from "@/db/bridge";
|
||||||
import { getEventAccess } from "@/db/events";
|
import { getEventAccess } from "@/db/events";
|
||||||
import { errorResponse, jsonResponse } from "@/lib/http";
|
import { errorResponse, jsonResponse } from "@/lib/http";
|
||||||
@@ -7,7 +8,6 @@ import {
|
|||||||
BRIDGE_LOGIN_TTL_SECONDS,
|
BRIDGE_LOGIN_TTL_SECONDS,
|
||||||
advancedEditorUrl,
|
advancedEditorUrl,
|
||||||
bridgeConfigured,
|
bridgeConfigured,
|
||||||
bridgeReturnUrl,
|
|
||||||
signBridgeToken,
|
signBridgeToken,
|
||||||
} from "@/lib/bridge";
|
} from "@/lib/bridge";
|
||||||
|
|
||||||
@@ -19,7 +19,7 @@ import {
|
|||||||
* dashboard session; the editor only ever sees the scoped token.
|
* dashboard session; the editor only ever sees the scoped token.
|
||||||
*/
|
*/
|
||||||
export const POST = async (
|
export const POST = async (
|
||||||
_req: NextRequest,
|
req: NextRequest,
|
||||||
{ params }: { params: Promise<{ id: string }> },
|
{ params }: { params: Promise<{ id: string }> },
|
||||||
) => {
|
) => {
|
||||||
const gate = await gateSession();
|
const gate = await gateSession();
|
||||||
@@ -45,6 +45,12 @@ export const POST = async (
|
|||||||
eventId: id,
|
eventId: id,
|
||||||
});
|
});
|
||||||
|
|
||||||
|
// This request comes from the user's browser, so its origin is the address
|
||||||
|
// that actually works for them. `NEXTAUTH_URL` cannot be trusted here: the
|
||||||
|
// compose default is http://localhost:3000 even when the app is served from
|
||||||
|
// a LAN address. PUBLIC_ORIGIN still wins inside requestOrigin().
|
||||||
|
const returnUrl = `${requestOrigin(req)}/events/${id}`;
|
||||||
|
|
||||||
const token = signBridgeToken({
|
const token = signBridgeToken({
|
||||||
sid: session.id,
|
sid: session.id,
|
||||||
eid: id,
|
eid: id,
|
||||||
@@ -53,11 +59,12 @@ export const POST = async (
|
|||||||
name: user.name,
|
name: user.name,
|
||||||
kind: "login",
|
kind: "login",
|
||||||
exp: Math.floor(Date.now() / 1000) + BRIDGE_LOGIN_TTL_SECONDS,
|
exp: Math.floor(Date.now() / 1000) + BRIDGE_LOGIN_TTL_SECONDS,
|
||||||
|
ret: returnUrl,
|
||||||
});
|
});
|
||||||
|
|
||||||
return jsonResponse({
|
return jsonResponse({
|
||||||
url: `${editor}/api/bridge/login?token=${encodeURIComponent(token)}`,
|
url: `${editor}/api/bridge/login?token=${encodeURIComponent(token)}`,
|
||||||
expiresAt: session.expiresAt,
|
expiresAt: session.expiresAt,
|
||||||
returnUrl: bridgeReturnUrl(id),
|
returnUrl,
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -17,10 +17,12 @@ import { mediaStorage } from "@/lib/media-storage";
|
|||||||
* GET /api/events/:id/download
|
* GET /api/events/:id/download
|
||||||
*
|
*
|
||||||
* Streams every photo on the event as one ZIP, preserving folder names. Saved
|
* Streams every photo on the event as one ZIP, preserving folder names. Saved
|
||||||
* edits are included beside their originals as `<name>-edited.jpg`. The
|
* edits are included beside their originals as `<name>-edited.jpg`. With
|
||||||
* archive is store-only: JPEGs and camera RAW files are already compressed, so
|
* `?edited=1` the archive contains only the saved edits, which is what a
|
||||||
* deflating them would add CPU and latency without shrinking the download.
|
* photographer wants to hand on after a grading pass. The archive is
|
||||||
* Anyone assigned to the event (or a manager) can download it.
|
* store-only: JPEGs and camera RAW files are already compressed, so deflating
|
||||||
|
* them would add CPU and latency without shrinking the download. Anyone
|
||||||
|
* assigned to the event (or a manager) can download it.
|
||||||
*/
|
*/
|
||||||
export const GET = async (
|
export const GET = async (
|
||||||
req: NextRequest,
|
req: NextRequest,
|
||||||
@@ -36,13 +38,22 @@ export const GET = async (
|
|||||||
// `?folderId=` narrows the archive to one folder, so a photographer can pull
|
// `?folderId=` narrows the archive to one folder, so a photographer can pull
|
||||||
// just the shots they need without downloading the whole event.
|
// just the shots they need without downloading the whole event.
|
||||||
const folderId = req.nextUrl.searchParams.get("folderId")?.trim() || null;
|
const folderId = req.nextUrl.searchParams.get("folderId")?.trim() || null;
|
||||||
|
const onlyEdited = req.nextUrl.searchParams.get("edited") === "1";
|
||||||
const photos = (await listEventPhotosForArchive(id)).filter(
|
const photos = (await listEventPhotosForArchive(id)).filter(
|
||||||
(photo) => !folderId || photo.folderId === folderId,
|
(photo) =>
|
||||||
|
(!folderId || photo.folderId === folderId) &&
|
||||||
|
(!onlyEdited || Boolean(photo.editedStoredName)),
|
||||||
);
|
);
|
||||||
if (photos.length === 0) {
|
if (photos.length === 0) {
|
||||||
return errorResponse(
|
return errorResponse(
|
||||||
404,
|
404,
|
||||||
folderId ? "this folder has no photos" : "this event has no photos",
|
onlyEdited
|
||||||
|
? folderId
|
||||||
|
? "this folder has no edited photos"
|
||||||
|
: "this event has no edited photos"
|
||||||
|
: folderId
|
||||||
|
? "this folder has no photos"
|
||||||
|
: "this event has no photos",
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -55,13 +66,15 @@ export const GET = async (
|
|||||||
filename: string;
|
filename: string;
|
||||||
storedName: string;
|
storedName: string;
|
||||||
}[] = [];
|
}[] = [];
|
||||||
for (const photo of photos) {
|
if (!onlyEdited) {
|
||||||
entries.push({
|
for (const photo of photos) {
|
||||||
key: `${photo.id}:original`,
|
entries.push({
|
||||||
folderName: photo.folderName,
|
key: `${photo.id}:original`,
|
||||||
filename: photo.filename,
|
folderName: photo.folderName,
|
||||||
storedName: photo.storedName,
|
filename: photo.filename,
|
||||||
});
|
storedName: photo.storedName,
|
||||||
|
});
|
||||||
|
}
|
||||||
}
|
}
|
||||||
for (const photo of photos) {
|
for (const photo of photos) {
|
||||||
if (!photo.editedStoredName) continue;
|
if (!photo.editedStoredName) continue;
|
||||||
@@ -124,9 +137,14 @@ export const GET = async (
|
|||||||
"content-type": "application/zip",
|
"content-type": "application/zip",
|
||||||
"content-disposition": photoContentDisposition(
|
"content-disposition": photoContentDisposition(
|
||||||
eventArchiveFilename(
|
eventArchiveFilename(
|
||||||
folderId
|
[
|
||||||
? `${access.event.title} - ${photos[0].folderName}`
|
folderId
|
||||||
: access.event.title,
|
? `${access.event.title} - ${photos[0].folderName}`
|
||||||
|
: access.event.title,
|
||||||
|
onlyEdited ? "edited" : null,
|
||||||
|
]
|
||||||
|
.filter(Boolean)
|
||||||
|
.join(" - "),
|
||||||
),
|
),
|
||||||
false,
|
false,
|
||||||
),
|
),
|
||||||
|
|||||||
@@ -1,10 +1,11 @@
|
|||||||
import { NextRequest } from "next/server";
|
import { NextRequest } from "next/server";
|
||||||
import { randomUUID } from "node:crypto";
|
import { randomUUID } from "node:crypto";
|
||||||
import { mkdir, rename, stat, unlink, writeFile } from "node:fs/promises";
|
import { copyFile, mkdir, rename, stat, unlink, writeFile } from "node:fs/promises";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { gateSession } from "@/auth/api";
|
import { gateSession } from "@/auth/api";
|
||||||
import { getEventPhotoAccess, updateEventPhotoEdit } from "@/db/events";
|
import { getEventPhotoAccess, updateEventPhotoEdit } from "@/db/events";
|
||||||
import {
|
import {
|
||||||
|
advancedStoredNameForEventPhoto,
|
||||||
editedPhotoFilename,
|
editedPhotoFilename,
|
||||||
editedStoredNameForEventPhoto,
|
editedStoredNameForEventPhoto,
|
||||||
eventPhotoPath,
|
eventPhotoPath,
|
||||||
@@ -12,18 +13,43 @@ import {
|
|||||||
} from "@/lib/event-photos";
|
} from "@/lib/event-photos";
|
||||||
import { errorResponse, jsonResponse } from "@/lib/http";
|
import { errorResponse, jsonResponse } from "@/lib/http";
|
||||||
import { mediaStorage } from "@/lib/media-storage";
|
import { mediaStorage } from "@/lib/media-storage";
|
||||||
import { normalizePhotoAdjustments } from "@/lib/photo-adjustments";
|
import {
|
||||||
|
defaultPhotoAdjustments,
|
||||||
|
normalizePhotoAdjustments,
|
||||||
|
parseStoredPhotoAdjustments,
|
||||||
|
} from "@/lib/photo-adjustments";
|
||||||
import { PhotoRenderError, renderPhotoJpeg } from "@/lib/photo-render";
|
import { PhotoRenderError, renderPhotoJpeg } from "@/lib/photo-render";
|
||||||
|
|
||||||
const MAX_EDIT_BODY_BYTES = 32 * 1024;
|
const MAX_EDIT_BODY_BYTES = 32 * 1024;
|
||||||
|
|
||||||
|
/** True when the advanced editor has left a recipe that describes its render. */
|
||||||
|
function hasAdvancedRecipe(json: string | null): boolean {
|
||||||
|
if (!json) return false;
|
||||||
|
try {
|
||||||
|
const parsed: unknown = JSON.parse(json);
|
||||||
|
return Boolean(
|
||||||
|
parsed && typeof parsed === "object" && Object.keys(parsed).length > 0,
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function isNeutral(adjustments: ReturnType<typeof defaultPhotoAdjustments>) {
|
||||||
|
return (
|
||||||
|
JSON.stringify(adjustments) === JSON.stringify(defaultPhotoAdjustments())
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* POST /api/events/:id/folders/:folderId/photos/:photoId/edit
|
* POST /api/events/:id/folders/:folderId/photos/:photoId/edit
|
||||||
* Body: { adjustments: PhotoAdjustments }
|
* Body: { adjustments: PhotoAdjustments }
|
||||||
*
|
*
|
||||||
* Saves the recipe and renders a fresh full-resolution JPEG beside the
|
* Saves the recipe and renders a fresh full-resolution JPEG beside the
|
||||||
* original. The original file is never changed, so an edit can always be
|
* original. When the advanced editor has already rendered this photo, that
|
||||||
* reopened and adjusted again.
|
* render is the base and the simple recipe is layered on top, so saving here
|
||||||
|
* never throws the advanced edit away. The original is never changed, so an
|
||||||
|
* edit can always be reopened and adjusted again.
|
||||||
*/
|
*/
|
||||||
export const POST = async (
|
export const POST = async (
|
||||||
req: NextRequest,
|
req: NextRequest,
|
||||||
@@ -59,8 +85,12 @@ export const POST = async (
|
|||||||
if (!storage.ok) return errorResponse(503, storage.message);
|
if (!storage.ok) return errorResponse(503, storage.message);
|
||||||
|
|
||||||
const body = (await req.json().catch(() => null)) as
|
const body = (await req.json().catch(() => null)) as
|
||||||
| { adjustments?: unknown }
|
| { adjustments?: unknown; takeOver?: unknown }
|
||||||
| null;
|
| null;
|
||||||
|
// Taking over retires the advanced recipe: the sliders are rendered from the
|
||||||
|
// original file instead of on top of the advanced render, so the look is not
|
||||||
|
// applied twice.
|
||||||
|
const takeOver = body?.takeOver === true;
|
||||||
const adjustments = normalizePhotoAdjustments(body?.adjustments);
|
const adjustments = normalizePhotoAdjustments(body?.adjustments);
|
||||||
if (!adjustments) {
|
if (!adjustments) {
|
||||||
return errorResponse(400, "invalid photo adjustments");
|
return errorResponse(400, "invalid photo adjustments");
|
||||||
@@ -80,11 +110,69 @@ export const POST = async (
|
|||||||
);
|
);
|
||||||
const editedPath = eventPhotoPath(storage.root, editedStoredName);
|
const editedPath = eventPhotoPath(storage.root, editedStoredName);
|
||||||
|
|
||||||
|
// The advanced editor's render is the base for the simple recipe.
|
||||||
|
let renderPath = sourcePath;
|
||||||
|
let renderKind = access.photo.kind;
|
||||||
|
const advancedStoredName = advancedStoredNameForEventPhoto(
|
||||||
|
access.eventId,
|
||||||
|
access.photo.id,
|
||||||
|
);
|
||||||
|
const advancedPath = eventPhotoPath(storage.root, advancedStoredName);
|
||||||
|
if (!takeOver && hasAdvancedRecipe(access.photo.advancedEditJson)) {
|
||||||
|
let advancedInfo = await stat(advancedPath).catch(() => null);
|
||||||
|
if (!advancedInfo?.isFile()) {
|
||||||
|
// Rows saved before the advanced render had its own file kept it in the
|
||||||
|
// edited path; copy it aside once so layered renders never compound.
|
||||||
|
const previous = access.photo.editedStoredName;
|
||||||
|
if (previous && previous !== advancedStoredName) {
|
||||||
|
const legacyPath = eventPhotoPath(storage.root, previous);
|
||||||
|
const legacyInfo = await stat(legacyPath).catch(() => null);
|
||||||
|
if (legacyInfo?.isFile()) {
|
||||||
|
await mkdir(path.dirname(advancedPath), { recursive: true });
|
||||||
|
await copyFile(legacyPath, advancedPath).catch(() => undefined);
|
||||||
|
advancedInfo = await stat(advancedPath).catch(() => null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (advancedInfo?.isFile()) {
|
||||||
|
renderPath = advancedPath;
|
||||||
|
renderKind = "image";
|
||||||
|
}
|
||||||
|
|
||||||
|
// Nothing layered on top: keep the advanced render as the saved edit
|
||||||
|
// instead of re-rendering it. This is a save with no slider changes, so
|
||||||
|
// say so rather than claiming a new JPEG was written.
|
||||||
|
if (renderPath === advancedPath && isNeutral(adjustments)) {
|
||||||
|
const info = await stat(advancedPath);
|
||||||
|
const alreadySaved =
|
||||||
|
access.photo.editedStoredName === advancedStoredName &&
|
||||||
|
JSON.stringify(parseStoredPhotoAdjustments(access.photo.editJson)) ===
|
||||||
|
JSON.stringify(adjustments);
|
||||||
|
const updated = await updateEventPhotoEdit({
|
||||||
|
photoId: access.photo.id,
|
||||||
|
editJson: JSON.stringify(adjustments),
|
||||||
|
editedStoredName: advancedStoredName,
|
||||||
|
editedSizeBytes: info.size,
|
||||||
|
editedBy: gate.id,
|
||||||
|
clearAdvancedEdit: false,
|
||||||
|
});
|
||||||
|
if (!updated) return errorResponse(404, "unknown photo");
|
||||||
|
return jsonResponse({
|
||||||
|
ok: true,
|
||||||
|
unchanged: alreadySaved,
|
||||||
|
adjustments,
|
||||||
|
editedFilename: editedPhotoFilename(access.photo.filename),
|
||||||
|
editedSizeBytes: info.size,
|
||||||
|
editedAt: updated.editedAt,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
let rendered: Awaited<ReturnType<typeof renderPhotoJpeg>>;
|
let rendered: Awaited<ReturnType<typeof renderPhotoJpeg>>;
|
||||||
try {
|
try {
|
||||||
rendered = await renderPhotoJpeg({
|
rendered = await renderPhotoJpeg({
|
||||||
filePath: sourcePath,
|
filePath: renderPath,
|
||||||
kind: access.photo.kind,
|
kind: renderKind,
|
||||||
adjustments,
|
adjustments,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
@@ -113,6 +201,7 @@ export const POST = async (
|
|||||||
editedStoredName,
|
editedStoredName,
|
||||||
editedSizeBytes: rendered.data.byteLength,
|
editedSizeBytes: rendered.data.byteLength,
|
||||||
editedBy: gate.id,
|
editedBy: gate.id,
|
||||||
|
clearAdvancedEdit: takeOver,
|
||||||
});
|
});
|
||||||
if (!updated) {
|
if (!updated) {
|
||||||
await unlink(editedPath).catch(() => undefined);
|
await unlink(editedPath).catch(() => undefined);
|
||||||
@@ -127,6 +216,7 @@ export const POST = async (
|
|||||||
editedAt: updated.editedAt,
|
editedAt: updated.editedAt,
|
||||||
width: rendered.width,
|
width: rendered.width,
|
||||||
height: rendered.height,
|
height: rendered.height,
|
||||||
|
tookOver: takeOver,
|
||||||
});
|
});
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
await unlink(editedPath).catch(() => undefined);
|
await unlink(editedPath).catch(() => undefined);
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { gateSession } from "@/auth/api";
|
|||||||
import { deleteEventPhoto, getEventPhotoAccess } from "@/db/events";
|
import { deleteEventPhoto, getEventPhotoAccess } from "@/db/events";
|
||||||
import { canDeleteEventPhoto } from "@/lib/event-access";
|
import { canDeleteEventPhoto } from "@/lib/event-access";
|
||||||
import {
|
import {
|
||||||
|
advancedStoredNameForEventPhoto,
|
||||||
editedPhotoFilename,
|
editedPhotoFilename,
|
||||||
eventPhotoPath,
|
eventPhotoPath,
|
||||||
isBrowserRenderablePhoto,
|
isBrowserRenderablePhoto,
|
||||||
@@ -19,8 +20,11 @@ import { mediaStorage } from "@/lib/media-storage";
|
|||||||
*
|
*
|
||||||
* Streams the original bytes to anyone assigned to the event (or a manager).
|
* Streams the original bytes to anyone assigned to the event (or a manager).
|
||||||
* `variant=edited` serves the generated full-resolution JPEG instead, so the
|
* `variant=edited` serves the generated full-resolution JPEG instead, so the
|
||||||
* gallery can show the saved look without replacing the original. RAW files
|
* gallery can show the saved look without replacing the original.
|
||||||
* always download; `?download=1` forces an attachment for JPEGs too.
|
* `variant=advanced` serves the advanced editor's own render (without any
|
||||||
|
* simple-editor layer), which is the base the simple editor previews on top of
|
||||||
|
* so its sliders can be re-applied without baking them twice. RAW files always
|
||||||
|
* download; `?download=1` forces an attachment for JPEGs too.
|
||||||
*/
|
*/
|
||||||
export const GET = async (
|
export const GET = async (
|
||||||
req: NextRequest,
|
req: NextRequest,
|
||||||
@@ -43,7 +47,9 @@ export const GET = async (
|
|||||||
return errorResponse(404, "unknown photo");
|
return errorResponse(404, "unknown photo");
|
||||||
}
|
}
|
||||||
|
|
||||||
const wantsEdited = req.nextUrl.searchParams.get("variant") === "edited";
|
const variant = req.nextUrl.searchParams.get("variant");
|
||||||
|
const wantsEdited = variant === "edited";
|
||||||
|
const wantsAdvanced = variant === "advanced";
|
||||||
if (wantsEdited && !access.photo.editedStoredName) {
|
if (wantsEdited && !access.photo.editedStoredName) {
|
||||||
return errorResponse(404, "this photo has no saved edit");
|
return errorResponse(404, "this photo has no saved edit");
|
||||||
}
|
}
|
||||||
@@ -51,13 +57,27 @@ export const GET = async (
|
|||||||
const storage = await mediaStorage();
|
const storage = await mediaStorage();
|
||||||
if (!storage.ok) return errorResponse(503, storage.message);
|
if (!storage.ok) return errorResponse(503, storage.message);
|
||||||
|
|
||||||
const filePath = eventPhotoPath(
|
let servedStoredName = access.photo.storedName;
|
||||||
storage.root,
|
if (wantsEdited) {
|
||||||
wantsEdited
|
servedStoredName = access.photo.editedStoredName!;
|
||||||
? access.photo.editedStoredName!
|
} else if (wantsAdvanced) {
|
||||||
: access.photo.storedName,
|
const advancedName = advancedStoredNameForEventPhoto(id, access.photo.id);
|
||||||
);
|
const advancedInfo = await stat(
|
||||||
const filename = wantsEdited
|
eventPhotoPath(storage.root, advancedName),
|
||||||
|
).catch(() => null);
|
||||||
|
if (advancedInfo?.isFile()) {
|
||||||
|
servedStoredName = advancedName;
|
||||||
|
} else if (access.photo.editedStoredName) {
|
||||||
|
// Rows saved before the advanced render had its own file kept it here.
|
||||||
|
servedStoredName = access.photo.editedStoredName;
|
||||||
|
} else {
|
||||||
|
return errorResponse(404, "this photo has no advanced edit");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const generated = wantsEdited || wantsAdvanced;
|
||||||
|
const filePath = eventPhotoPath(storage.root, servedStoredName);
|
||||||
|
const filename = generated
|
||||||
? editedPhotoFilename(access.photo.filename)
|
? editedPhotoFilename(access.photo.filename)
|
||||||
: access.photo.filename;
|
: access.photo.filename;
|
||||||
let size: number;
|
let size: number;
|
||||||
@@ -69,7 +89,7 @@ export const GET = async (
|
|||||||
|
|
||||||
const inline =
|
const inline =
|
||||||
req.nextUrl.searchParams.get("download") !== "1" &&
|
req.nextUrl.searchParams.get("download") !== "1" &&
|
||||||
(wantsEdited || isBrowserRenderablePhoto(access.photo.filename));
|
(generated || isBrowserRenderablePhoto(access.photo.filename));
|
||||||
|
|
||||||
const stream = createReadStream(filePath);
|
const stream = createReadStream(filePath);
|
||||||
return new Response(
|
return new Response(
|
||||||
@@ -77,7 +97,7 @@ export const GET = async (
|
|||||||
{
|
{
|
||||||
status: 200,
|
status: 200,
|
||||||
headers: {
|
headers: {
|
||||||
"content-type": wantsEdited ? "image/jpeg" : access.photo.mimeType,
|
"content-type": generated ? "image/jpeg" : access.photo.mimeType,
|
||||||
"content-length": String(size),
|
"content-length": String(size),
|
||||||
"content-disposition": photoContentDisposition(filename, inline),
|
"content-disposition": photoContentDisposition(filename, inline),
|
||||||
"cache-control": "private, max-age=0, must-revalidate",
|
"cache-control": "private, max-age=0, must-revalidate",
|
||||||
|
|||||||
@@ -2,7 +2,6 @@ import { NextRequest } from "next/server";
|
|||||||
import { randomUUID } from "node:crypto";
|
import { randomUUID } from "node:crypto";
|
||||||
import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
|
import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import sharp from "sharp";
|
|
||||||
import { gateSession } from "@/auth/api";
|
import { gateSession } from "@/auth/api";
|
||||||
import { getEventPhotoAccess } from "@/db/events";
|
import { getEventPhotoAccess } from "@/db/events";
|
||||||
import {
|
import {
|
||||||
@@ -12,8 +11,7 @@ import {
|
|||||||
} from "@/lib/event-photos";
|
} from "@/lib/event-photos";
|
||||||
import { errorResponse } from "@/lib/http";
|
import { errorResponse } from "@/lib/http";
|
||||||
import { mediaStorage } from "@/lib/media-storage";
|
import { mediaStorage } from "@/lib/media-storage";
|
||||||
import { defaultPhotoAdjustments } from "@/lib/photo-adjustments";
|
import { PhotoRenderError, renderPhotoThumbnail } from "@/lib/photo-render";
|
||||||
import { PhotoRenderError, renderPhotoJpeg } from "@/lib/photo-render";
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* GET /api/events/:id/folders/:folderId/photos/:photoId/thumb
|
* GET /api/events/:id/folders/:folderId/photos/:photoId/thumb
|
||||||
@@ -69,20 +67,15 @@ export const GET = async (
|
|||||||
|
|
||||||
let data: Buffer;
|
let data: Buffer;
|
||||||
try {
|
try {
|
||||||
if (access.photo.kind === "raw") {
|
if (
|
||||||
const rendered = await renderPhotoJpeg({
|
access.photo.kind === "raw" ||
|
||||||
|
isBrowserRenderablePhoto(access.photo.filename)
|
||||||
|
) {
|
||||||
|
data = await renderPhotoThumbnail({
|
||||||
filePath: sourcePath,
|
filePath: sourcePath,
|
||||||
kind: "raw",
|
kind: access.photo.kind,
|
||||||
adjustments: defaultPhotoAdjustments(),
|
|
||||||
maxDimension: 640,
|
maxDimension: 640,
|
||||||
});
|
});
|
||||||
data = rendered.data;
|
|
||||||
} else if (isBrowserRenderablePhoto(access.photo.filename)) {
|
|
||||||
data = await sharp(sourcePath, { failOn: "none", limitInputPixels: 500_000_000 })
|
|
||||||
.autoOrient()
|
|
||||||
.resize(640, 640, { fit: "inside", withoutEnlargement: true })
|
|
||||||
.jpeg({ quality: 72 })
|
|
||||||
.toBuffer();
|
|
||||||
} else {
|
} else {
|
||||||
return errorResponse(415, "this photo format has no thumbnail");
|
return errorResponse(415, "this photo format has no thumbnail");
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,58 +1,14 @@
|
|||||||
import { NextRequest } from "next/server";
|
import { NextRequest } from "next/server";
|
||||||
import { createHash } from "node:crypto";
|
|
||||||
import { createWriteStream } from "node:fs";
|
|
||||||
import { mkdir, unlink } from "node:fs/promises";
|
|
||||||
import path from "node:path";
|
|
||||||
import { Readable, Transform } from "node:stream";
|
|
||||||
import { pipeline } from "node:stream/promises";
|
|
||||||
import { gateSession } from "@/auth/api";
|
import { gateSession } from "@/auth/api";
|
||||||
import {
|
import { getEventFolderAccess } from "@/db/events";
|
||||||
addEventPhoto,
|
import { errorResponse } from "@/lib/http";
|
||||||
findEventPhotoByChecksum,
|
import { uploadEventPhoto } from "@/lib/event-photo-upload";
|
||||||
getEventFolderAccess,
|
|
||||||
isUniqueViolation,
|
|
||||||
} from "@/db/events";
|
|
||||||
import {
|
|
||||||
MAX_EVENT_PHOTO_BYTES,
|
|
||||||
eventPhotoKindFor,
|
|
||||||
eventPhotoMimeFor,
|
|
||||||
eventPhotoPath,
|
|
||||||
sanitizePhotoFilename,
|
|
||||||
storedNameForEventPhoto,
|
|
||||||
} from "@/lib/event-photos";
|
|
||||||
import { errorResponse, jsonResponse } from "@/lib/http";
|
|
||||||
import { mediaStorage } from "@/lib/media-storage";
|
|
||||||
import { uuidv7 } from "@/lib/uuid";
|
|
||||||
|
|
||||||
class PhotoTooLarge extends Error {}
|
|
||||||
|
|
||||||
function publicPhoto(photo: {
|
|
||||||
id: string;
|
|
||||||
folderId: string;
|
|
||||||
filename: string;
|
|
||||||
mimeType: string;
|
|
||||||
sizeBytes: number;
|
|
||||||
kind: "raw" | "image";
|
|
||||||
createdAt: Date;
|
|
||||||
}) {
|
|
||||||
return {
|
|
||||||
id: photo.id,
|
|
||||||
folderId: photo.folderId,
|
|
||||||
filename: photo.filename,
|
|
||||||
mimeType: photo.mimeType,
|
|
||||||
sizeBytes: photo.sizeBytes,
|
|
||||||
kind: photo.kind,
|
|
||||||
createdAt: photo.createdAt,
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* POST /api/events/:id/folders/:folderId/photos?name=IMG_0001.CR3
|
* POST /api/events/:id/folders/:folderId/photos?name=IMG_0001.CR3
|
||||||
*
|
*
|
||||||
* A single photo is the raw request body (not multipart), so a 100 MB RAW file
|
* Folder-scoped upload kept for direct API use. The event page posts to
|
||||||
* streams straight to disk instead of being buffered in memory. The filename is
|
* `/api/events/:id/photos`, which picks the event's one implicit folder.
|
||||||
* passed as a query parameter because headers cannot carry arbitrary Unicode.
|
|
||||||
* The SHA-256 is computed while streaming and dedupes a re-upload per folder.
|
|
||||||
*/
|
*/
|
||||||
export const POST = async (
|
export const POST = async (
|
||||||
req: NextRequest,
|
req: NextRequest,
|
||||||
@@ -70,93 +26,9 @@ export const POST = async (
|
|||||||
return errorResponse(403, "you are not assigned to this event");
|
return errorResponse(403, "you are not assigned to this event");
|
||||||
}
|
}
|
||||||
|
|
||||||
// Photos are only ever written to the configured media storage share, so refuse
|
return uploadEventPhoto(req, {
|
||||||
// before reading a single byte when that destination is not ready.
|
eventId: id,
|
||||||
const storage = await mediaStorage();
|
folderId,
|
||||||
if (!storage.ok) return errorResponse(503, storage.message);
|
uploaderId: gate.id,
|
||||||
|
|
||||||
const suppliedName = req.nextUrl.searchParams.get("name");
|
|
||||||
if (!suppliedName) return errorResponse(400, "a filename is required");
|
|
||||||
const filename = sanitizePhotoFilename(suppliedName);
|
|
||||||
const kind = eventPhotoKindFor(filename);
|
|
||||||
if (!kind) {
|
|
||||||
return errorResponse(
|
|
||||||
415,
|
|
||||||
"only photo files are accepted (JPEG, PNG, WebP, HEIC, TIFF, PSD or camera RAW)",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
const declaredLength = Number(req.headers.get("content-length") ?? 0);
|
|
||||||
if (declaredLength > MAX_EVENT_PHOTO_BYTES) {
|
|
||||||
return errorResponse(413, "that photo is larger than 200 MB");
|
|
||||||
}
|
|
||||||
if (!req.body) return errorResponse(400, "a file body is required");
|
|
||||||
|
|
||||||
const photoId = uuidv7();
|
|
||||||
const storedName = storedNameForEventPhoto(id, photoId, filename);
|
|
||||||
const destination = eventPhotoPath(storage.root, storedName);
|
|
||||||
await mkdir(path.dirname(destination), { recursive: true });
|
|
||||||
|
|
||||||
const hash = createHash("sha256");
|
|
||||||
let size = 0;
|
|
||||||
const meter = new Transform({
|
|
||||||
transform(chunk: Buffer, _encoding, callback) {
|
|
||||||
size += chunk.length;
|
|
||||||
if (size > MAX_EVENT_PHOTO_BYTES) {
|
|
||||||
callback(new PhotoTooLarge());
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
hash.update(chunk);
|
|
||||||
callback(null, chunk);
|
|
||||||
},
|
|
||||||
});
|
});
|
||||||
|
|
||||||
try {
|
|
||||||
await pipeline(
|
|
||||||
Readable.from(req.body as unknown as AsyncIterable<Uint8Array>),
|
|
||||||
meter,
|
|
||||||
createWriteStream(destination, { flags: "wx" }),
|
|
||||||
);
|
|
||||||
} catch (error) {
|
|
||||||
await unlink(destination).catch(() => undefined);
|
|
||||||
if (error instanceof PhotoTooLarge) {
|
|
||||||
return errorResponse(413, "that photo is larger than 200 MB");
|
|
||||||
}
|
|
||||||
return errorResponse(500, "the upload did not complete");
|
|
||||||
}
|
|
||||||
|
|
||||||
if (size === 0) {
|
|
||||||
await unlink(destination).catch(() => undefined);
|
|
||||||
return errorResponse(400, "the uploaded file was empty");
|
|
||||||
}
|
|
||||||
|
|
||||||
const checksumSha256 = hash.digest("hex");
|
|
||||||
const existing = await findEventPhotoByChecksum(folderId, checksumSha256);
|
|
||||||
if (existing) {
|
|
||||||
await unlink(destination).catch(() => undefined);
|
|
||||||
return jsonResponse({ photo: publicPhoto(existing), duplicate: true });
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
|
||||||
const photo = await addEventPhoto({
|
|
||||||
folderId,
|
|
||||||
uploaderId: gate.id,
|
|
||||||
filename,
|
|
||||||
mimeType: eventPhotoMimeFor(filename),
|
|
||||||
sizeBytes: size,
|
|
||||||
storedName,
|
|
||||||
checksumSha256,
|
|
||||||
kind,
|
|
||||||
});
|
|
||||||
return jsonResponse({ photo: publicPhoto(photo) }, 201);
|
|
||||||
} catch (error) {
|
|
||||||
await unlink(destination).catch(() => undefined);
|
|
||||||
if (isUniqueViolation(error)) {
|
|
||||||
const raced = await findEventPhotoByChecksum(folderId, checksumSha256);
|
|
||||||
if (raced) {
|
|
||||||
return jsonResponse({ photo: publicPhoto(raced), duplicate: true });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,39 @@
|
|||||||
|
import { NextRequest } from "next/server";
|
||||||
|
import { gateSession } from "@/auth/api";
|
||||||
|
import { ensureEventFolder, getEventAccess } from "@/db/events";
|
||||||
|
import { errorResponse } from "@/lib/http";
|
||||||
|
import { uploadEventPhoto } from "@/lib/event-photo-upload";
|
||||||
|
import { mediaStorage } from "@/lib/media-storage";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* POST /api/events/:id/photos?name=IMG_0001.CR3
|
||||||
|
*
|
||||||
|
* The event page has no folder picker, so uploads land in the event's single
|
||||||
|
* folder (created as "Photos" on the first upload). Everything else is the same
|
||||||
|
* streamed, checksum-deduped upload the folder route uses.
|
||||||
|
*/
|
||||||
|
export const POST = async (
|
||||||
|
req: NextRequest,
|
||||||
|
{ params }: { params: Promise<{ id: string }> },
|
||||||
|
) => {
|
||||||
|
const gate = await gateSession();
|
||||||
|
if (gate instanceof Response) return gate;
|
||||||
|
|
||||||
|
const { id } = await params;
|
||||||
|
const access = await getEventAccess(id, gate.id, gate.systemRole);
|
||||||
|
if (!access) return errorResponse(404, "unknown event");
|
||||||
|
if (!access.canContribute) {
|
||||||
|
return errorResponse(403, "you are not assigned to this event");
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check storage before creating anything, so a blocked upload leaves no rows.
|
||||||
|
const storage = await mediaStorage();
|
||||||
|
if (!storage.ok) return errorResponse(503, storage.message);
|
||||||
|
|
||||||
|
const folder = await ensureEventFolder(id, gate.id);
|
||||||
|
return uploadEventPhoto(req, {
|
||||||
|
eventId: id,
|
||||||
|
folderId: folder.id,
|
||||||
|
uploaderId: gate.id,
|
||||||
|
});
|
||||||
|
};
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
import { NextRequest } from "next/server";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { clientIp } from "@/auth/api";
|
||||||
|
import { RespondError, applyAlternativeProposal } from "@/db/respond";
|
||||||
|
import { verifyRespondToken } from "@/lib/respond";
|
||||||
|
import { rateLimit } from "@/lib/rate-limit";
|
||||||
|
|
||||||
|
const JSON_HEADERS = { "content-type": "application/json" };
|
||||||
|
|
||||||
|
const bodySchema = z.object({
|
||||||
|
token: z.string().min(1),
|
||||||
|
instanceId: z.string().min(1),
|
||||||
|
note: z.string().max(500).optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
/** Map a refused proposal to its HTTP status. */
|
||||||
|
function errorStatus(code: RespondError["code"]): number {
|
||||||
|
switch (code) {
|
||||||
|
case "unknown_assignment":
|
||||||
|
case "unknown_instance":
|
||||||
|
return 404;
|
||||||
|
case "wrong_volunteer":
|
||||||
|
return 403;
|
||||||
|
case "not_actionable":
|
||||||
|
case "already_used":
|
||||||
|
case "invalid_alternative":
|
||||||
|
return 409;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* POST /api/respond/alternative — { token, instanceId, note? }
|
||||||
|
*
|
||||||
|
* The no-login "propose another Sunday" endpoint. The token must be an
|
||||||
|
* `alternative` link; its `jti` is consumed exactly once, so the same email
|
||||||
|
* link cannot file two proposals. The assignment itself is left live for a
|
||||||
|
* coordinator to reassign.
|
||||||
|
*/
|
||||||
|
export const POST = async (req: NextRequest) => {
|
||||||
|
const parsed = bodySchema.safeParse(await req.json().catch(() => null));
|
||||||
|
if (!parsed.success) {
|
||||||
|
return new Response(
|
||||||
|
JSON.stringify({ error: "a token and service date are required" }),
|
||||||
|
{ status: 400, headers: JSON_HEADERS },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const limit = rateLimit(`respond-alternative:${clientIp(req)}`, 30, 60_000);
|
||||||
|
if (!limit.ok) {
|
||||||
|
return new Response(
|
||||||
|
JSON.stringify({
|
||||||
|
error: "too many attempts; try again shortly",
|
||||||
|
code: "RATE_LIMITED",
|
||||||
|
}),
|
||||||
|
{
|
||||||
|
status: 429,
|
||||||
|
headers: {
|
||||||
|
...JSON_HEADERS,
|
||||||
|
"retry-after": String(limit.retryAfterSeconds),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const payload = await verifyRespondToken(parsed.data.token);
|
||||||
|
if (!payload) {
|
||||||
|
return new Response(
|
||||||
|
JSON.stringify({
|
||||||
|
error: "this link is invalid or has expired",
|
||||||
|
code: "invalid_token",
|
||||||
|
}),
|
||||||
|
{ status: 400, headers: JSON_HEADERS },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (payload.action !== "alternative") {
|
||||||
|
return new Response(
|
||||||
|
JSON.stringify({
|
||||||
|
error: "this link is for a different action",
|
||||||
|
code: "action_mismatch",
|
||||||
|
}),
|
||||||
|
{ status: 400, headers: JSON_HEADERS },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const result = await applyAlternativeProposal({
|
||||||
|
assignmentId: payload.assignmentId,
|
||||||
|
userId: payload.userId,
|
||||||
|
jti: payload.jti,
|
||||||
|
proposedInstanceId: parsed.data.instanceId,
|
||||||
|
note: parsed.data.note ?? null,
|
||||||
|
});
|
||||||
|
return new Response(JSON.stringify({ ok: true, ...result }), {
|
||||||
|
status: 200,
|
||||||
|
headers: JSON_HEADERS,
|
||||||
|
});
|
||||||
|
} catch (e) {
|
||||||
|
if (e instanceof RespondError) {
|
||||||
|
return new Response(
|
||||||
|
JSON.stringify({ error: e.message, code: e.code }),
|
||||||
|
{ status: errorStatus(e.code), headers: JSON_HEADERS },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
console.error("[respond-alternative] ERROR", e);
|
||||||
|
return new Response(JSON.stringify({ error: "failed to save the proposal" }), {
|
||||||
|
status: 500,
|
||||||
|
headers: JSON_HEADERS,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
@@ -17,8 +17,10 @@ function errorStatus(code: RespondError["code"]): number {
|
|||||||
switch (code) {
|
switch (code) {
|
||||||
case "already_used":
|
case "already_used":
|
||||||
case "not_actionable":
|
case "not_actionable":
|
||||||
|
case "invalid_alternative":
|
||||||
return 409;
|
return 409;
|
||||||
case "unknown_assignment":
|
case "unknown_assignment":
|
||||||
|
case "unknown_instance":
|
||||||
return 404;
|
return 404;
|
||||||
case "wrong_volunteer":
|
case "wrong_volunteer":
|
||||||
return 403;
|
return 403;
|
||||||
|
|||||||
@@ -0,0 +1,212 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useEffect, useState } from "react";
|
||||||
|
import { signIn } from "next-auth/react";
|
||||||
|
import {
|
||||||
|
Card,
|
||||||
|
CardContent,
|
||||||
|
CardDescription,
|
||||||
|
CardHeader,
|
||||||
|
CardTitle,
|
||||||
|
} from "@/components/ui/card";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Label } from "@/components/ui/label";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sign in with username/password. The email-link form is only available while
|
||||||
|
* the deployment has no password-protected admin (first-run bootstrap). It
|
||||||
|
* never renders a sign-in URL, even when the dev console transport returns one.
|
||||||
|
*/
|
||||||
|
export function LoginForm({ magicLinkEnabled }: { magicLinkEnabled: boolean }) {
|
||||||
|
const [login, setLogin] = useState("");
|
||||||
|
const [password, setPassword] = useState("");
|
||||||
|
const [passwordStatus, setPasswordStatus] = useState<{
|
||||||
|
kind: "idle" | "signing" | "error";
|
||||||
|
message?: string;
|
||||||
|
}>({ kind: "idle" });
|
||||||
|
|
||||||
|
const [email, setEmail] = useState("");
|
||||||
|
const [linkNotice, setLinkNotice] = useState<string | null>(null);
|
||||||
|
const [linkStatus, setLinkStatus] = useState<{
|
||||||
|
kind: "idle" | "sending" | "sent" | "error";
|
||||||
|
message?: string;
|
||||||
|
}>({ kind: "idle" });
|
||||||
|
|
||||||
|
// /api/dev/complete redirects here when a link is dead. Say why, instead of
|
||||||
|
// dropping people on a bare sign-in form after the link fails.
|
||||||
|
useEffect(() => {
|
||||||
|
const error = new URLSearchParams(window.location.search).get("error");
|
||||||
|
if (error === "invalid_link") {
|
||||||
|
setLinkNotice(
|
||||||
|
"That sign-in link has expired or is invalid. Ask a media team admin for a new one.",
|
||||||
|
);
|
||||||
|
} else if (error === "link_used") {
|
||||||
|
setLinkNotice(
|
||||||
|
"That sign-in link has already been used. Ask a media team admin for a new one.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
async function onPasswordSubmit(e: React.FormEvent) {
|
||||||
|
e.preventDefault();
|
||||||
|
setPasswordStatus({ kind: "signing" });
|
||||||
|
try {
|
||||||
|
const result = await signIn("password", {
|
||||||
|
login,
|
||||||
|
password,
|
||||||
|
redirect: false,
|
||||||
|
});
|
||||||
|
if (!result || result.error) {
|
||||||
|
setPasswordStatus({
|
||||||
|
kind: "error",
|
||||||
|
message: "That username or password did not match an active account.",
|
||||||
|
});
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Full navigation lets the server layout read the new session cookie.
|
||||||
|
window.location.assign("/schedule");
|
||||||
|
} catch {
|
||||||
|
setPasswordStatus({ kind: "error", message: "Network error." });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function onLinkSubmit(e: React.FormEvent) {
|
||||||
|
e.preventDefault();
|
||||||
|
setLinkStatus({ kind: "sending" });
|
||||||
|
try {
|
||||||
|
const res = await fetch("/api/dev/magic-link", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "content-type": "application/json" },
|
||||||
|
body: JSON.stringify({ email }),
|
||||||
|
});
|
||||||
|
const body = (await res.json().catch(() => ({}))) as { error?: string };
|
||||||
|
if (res.ok) {
|
||||||
|
setLinkStatus({ kind: "sent" });
|
||||||
|
} else {
|
||||||
|
setLinkStatus({
|
||||||
|
kind: "error",
|
||||||
|
message: body.error ?? "Something went wrong.",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
setLinkStatus({ kind: "error", message: "Network error." });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="flex min-h-screen items-center justify-center bg-gradient-to-b from-accent/50 via-background to-background px-4 py-8">
|
||||||
|
<div className="w-full max-w-sm space-y-4">
|
||||||
|
<div className="text-center">
|
||||||
|
<p className="text-xs font-semibold uppercase tracking-[0.22em] text-primary">
|
||||||
|
Glenloch Baptist Church
|
||||||
|
</p>
|
||||||
|
<p className="mt-1 text-2xl font-semibold tracking-tight">
|
||||||
|
Media Team Hub
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Card className="w-full border-t-4 border-t-primary shadow-sm">
|
||||||
|
<CardHeader>
|
||||||
|
<CardTitle>Sign in</CardTitle>
|
||||||
|
<CardDescription>
|
||||||
|
{magicLinkEnabled
|
||||||
|
? "Use your username and password, or request a one-time email link."
|
||||||
|
: "Sign in with your username and password. Contact a media team admin if you need help."}
|
||||||
|
</CardDescription>
|
||||||
|
</CardHeader>
|
||||||
|
<CardContent className="space-y-5">
|
||||||
|
{linkNotice && (
|
||||||
|
<p role="alert" className="rounded border border-border bg-muted p-3 text-sm">
|
||||||
|
{linkNotice}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
<form onSubmit={onPasswordSubmit} className="flex flex-col gap-4">
|
||||||
|
<div className="flex flex-col gap-2">
|
||||||
|
<Label htmlFor="login">Username or email</Label>
|
||||||
|
<Input
|
||||||
|
id="login"
|
||||||
|
name="login"
|
||||||
|
required
|
||||||
|
autoComplete="username"
|
||||||
|
value={login}
|
||||||
|
onChange={(e) => setLogin(e.target.value)}
|
||||||
|
placeholder="you@church.local"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-col gap-2">
|
||||||
|
<Label htmlFor="password">Password</Label>
|
||||||
|
<Input
|
||||||
|
id="password"
|
||||||
|
name="password"
|
||||||
|
type="password"
|
||||||
|
required
|
||||||
|
autoComplete="current-password"
|
||||||
|
value={password}
|
||||||
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<Button type="submit" disabled={passwordStatus.kind === "signing"}>
|
||||||
|
{passwordStatus.kind === "signing" ? "Signing in…" : "Sign in"}
|
||||||
|
</Button>
|
||||||
|
{passwordStatus.kind === "error" && passwordStatus.message && (
|
||||||
|
<p role="alert" className="text-sm text-destructive">
|
||||||
|
{passwordStatus.message}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</form>
|
||||||
|
|
||||||
|
{magicLinkEnabled && (
|
||||||
|
<>
|
||||||
|
<div className="flex items-center gap-3 text-xs uppercase tracking-wide text-muted-foreground">
|
||||||
|
<span className="h-px flex-1 bg-border" />
|
||||||
|
or
|
||||||
|
<span className="h-px flex-1 bg-border" />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<form onSubmit={onLinkSubmit} className="flex flex-col gap-3">
|
||||||
|
<Label htmlFor="email">Email a one-time sign-in link</Label>
|
||||||
|
<Input
|
||||||
|
id="email"
|
||||||
|
name="email"
|
||||||
|
type="email"
|
||||||
|
required
|
||||||
|
autoComplete="email"
|
||||||
|
value={email}
|
||||||
|
onChange={(e) => setEmail(e.target.value)}
|
||||||
|
placeholder="you@church.local"
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
type="submit"
|
||||||
|
variant="outline"
|
||||||
|
disabled={linkStatus.kind === "sending"}
|
||||||
|
>
|
||||||
|
{linkStatus.kind === "sending"
|
||||||
|
? "Sending link…"
|
||||||
|
: "Send sign-in link"}
|
||||||
|
</Button>
|
||||||
|
{linkStatus.kind === "sent" && (
|
||||||
|
<p className="rounded border border-border bg-muted p-3 text-sm">
|
||||||
|
If that address belongs to an active account, a single-use
|
||||||
|
sign-in link has been sent. It expires in 10 minutes.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{linkStatus.kind === "error" && linkStatus.message && (
|
||||||
|
<p role="alert" className="text-sm text-destructive">
|
||||||
|
{linkStatus.message}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</form>
|
||||||
|
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
First time here? The magic link will ask you to set a username
|
||||||
|
and password. If you are locked out, ask an admin for a reset
|
||||||
|
link.
|
||||||
|
</p>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</CardContent>
|
||||||
|
</Card>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
+8
-189
@@ -1,194 +1,13 @@
|
|||||||
"use client";
|
import { hasPasswordProtectedAdmin } from "@/db/users";
|
||||||
|
import { LoginForm } from "./login-form";
|
||||||
|
|
||||||
import { useState } from "react";
|
export const dynamic = "force-dynamic";
|
||||||
import { signIn } from "next-auth/react";
|
|
||||||
import {
|
|
||||||
Card,
|
|
||||||
CardContent,
|
|
||||||
CardDescription,
|
|
||||||
CardHeader,
|
|
||||||
CardTitle,
|
|
||||||
} from "@/components/ui/card";
|
|
||||||
import { Input } from "@/components/ui/input";
|
|
||||||
import { Button } from "@/components/ui/button";
|
|
||||||
import { Label } from "@/components/ui/label";
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sign in with the username/password set after the first magic link, or request
|
* Public sign-in. The email-link form is bootstrap-only: once an admin has a
|
||||||
* a new one-time link by email. The magic-link path remains the recovery path
|
* password, anyone who knew that admin's email could otherwise request a full
|
||||||
* when someone has not set credentials yet.
|
* admin session from this page.
|
||||||
*/
|
*/
|
||||||
export default function LoginPage() {
|
export default async function LoginPage() {
|
||||||
const [login, setLogin] = useState("");
|
return <LoginForm magicLinkEnabled={!(await hasPasswordProtectedAdmin())} />;
|
||||||
const [password, setPassword] = useState("");
|
|
||||||
const [passwordStatus, setPasswordStatus] = useState<{
|
|
||||||
kind: "idle" | "signing" | "error";
|
|
||||||
message?: string;
|
|
||||||
}>({ kind: "idle" });
|
|
||||||
|
|
||||||
const [email, setEmail] = useState("");
|
|
||||||
const [linkStatus, setLinkStatus] = useState<{
|
|
||||||
kind: "idle" | "sending" | "sent" | "error";
|
|
||||||
message?: string;
|
|
||||||
}>({ kind: "idle" });
|
|
||||||
|
|
||||||
async function onPasswordSubmit(e: React.FormEvent) {
|
|
||||||
e.preventDefault();
|
|
||||||
setPasswordStatus({ kind: "signing" });
|
|
||||||
try {
|
|
||||||
const result = await signIn("password", {
|
|
||||||
login,
|
|
||||||
password,
|
|
||||||
redirect: false,
|
|
||||||
});
|
|
||||||
if (!result || result.error) {
|
|
||||||
setPasswordStatus({
|
|
||||||
kind: "error",
|
|
||||||
message: "That username or password did not match an active account.",
|
|
||||||
});
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
// Full navigation lets the server layout read the new session cookie.
|
|
||||||
window.location.assign("/schedule");
|
|
||||||
} catch {
|
|
||||||
setPasswordStatus({ kind: "error", message: "Network error." });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async function onLinkSubmit(e: React.FormEvent) {
|
|
||||||
e.preventDefault();
|
|
||||||
setLinkStatus({ kind: "sending" });
|
|
||||||
try {
|
|
||||||
const res = await fetch("/api/dev/magic-link", {
|
|
||||||
method: "POST",
|
|
||||||
headers: { "content-type": "application/json" },
|
|
||||||
body: JSON.stringify({ email }),
|
|
||||||
});
|
|
||||||
const body = (await res.json()) as {
|
|
||||||
ok?: boolean;
|
|
||||||
url?: string;
|
|
||||||
error?: string;
|
|
||||||
};
|
|
||||||
if (res.ok) {
|
|
||||||
setLinkStatus({ kind: "sent", message: body.url });
|
|
||||||
} else {
|
|
||||||
setLinkStatus({
|
|
||||||
kind: "error",
|
|
||||||
message: body.error ?? "Something went wrong.",
|
|
||||||
});
|
|
||||||
}
|
|
||||||
} catch {
|
|
||||||
setLinkStatus({ kind: "error", message: "Network error." });
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="flex min-h-screen items-center justify-center bg-gradient-to-b from-accent/50 via-background to-background px-4 py-8">
|
|
||||||
<div className="w-full max-w-sm space-y-4">
|
|
||||||
<div className="text-center">
|
|
||||||
<p className="text-xs font-semibold uppercase tracking-[0.22em] text-primary">
|
|
||||||
Glenloch Baptist Church
|
|
||||||
</p>
|
|
||||||
<p className="mt-1 text-2xl font-semibold tracking-tight">
|
|
||||||
Media Team Hub
|
|
||||||
</p>
|
|
||||||
</div>
|
|
||||||
<Card className="w-full border-t-4 border-t-primary shadow-sm">
|
|
||||||
<CardHeader>
|
|
||||||
<CardTitle>Sign in</CardTitle>
|
|
||||||
<CardDescription>
|
|
||||||
Use your username and password, or request a one-time email link.
|
|
||||||
</CardDescription>
|
|
||||||
</CardHeader>
|
|
||||||
<CardContent className="space-y-5">
|
|
||||||
<form onSubmit={onPasswordSubmit} className="flex flex-col gap-4">
|
|
||||||
<div className="flex flex-col gap-2">
|
|
||||||
<Label htmlFor="login">Username or email</Label>
|
|
||||||
<Input
|
|
||||||
id="login"
|
|
||||||
name="login"
|
|
||||||
required
|
|
||||||
autoComplete="username"
|
|
||||||
value={login}
|
|
||||||
onChange={(e) => setLogin(e.target.value)}
|
|
||||||
placeholder="you@church.local"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="flex flex-col gap-2">
|
|
||||||
<Label htmlFor="password">Password</Label>
|
|
||||||
<Input
|
|
||||||
id="password"
|
|
||||||
name="password"
|
|
||||||
type="password"
|
|
||||||
required
|
|
||||||
autoComplete="current-password"
|
|
||||||
value={password}
|
|
||||||
onChange={(e) => setPassword(e.target.value)}
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<Button type="submit" disabled={passwordStatus.kind === "signing"}>
|
|
||||||
{passwordStatus.kind === "signing" ? "Signing in…" : "Sign in"}
|
|
||||||
</Button>
|
|
||||||
{passwordStatus.kind === "error" && passwordStatus.message && (
|
|
||||||
<p role="alert" className="text-sm text-destructive">
|
|
||||||
{passwordStatus.message}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</form>
|
|
||||||
|
|
||||||
<div className="flex items-center gap-3 text-xs uppercase tracking-wide text-muted-foreground">
|
|
||||||
<span className="h-px flex-1 bg-border" />
|
|
||||||
or
|
|
||||||
<span className="h-px flex-1 bg-border" />
|
|
||||||
</div>
|
|
||||||
|
|
||||||
<form onSubmit={onLinkSubmit} className="flex flex-col gap-3">
|
|
||||||
<Label htmlFor="email">Email a one-time sign-in link</Label>
|
|
||||||
<Input
|
|
||||||
id="email"
|
|
||||||
name="email"
|
|
||||||
type="email"
|
|
||||||
required
|
|
||||||
autoComplete="email"
|
|
||||||
value={email}
|
|
||||||
onChange={(e) => setEmail(e.target.value)}
|
|
||||||
placeholder="you@church.local"
|
|
||||||
/>
|
|
||||||
<Button
|
|
||||||
type="submit"
|
|
||||||
variant="outline"
|
|
||||||
disabled={linkStatus.kind === "sending"}
|
|
||||||
>
|
|
||||||
{linkStatus.kind === "sending" ? "Sending link…" : "Send sign-in link"}
|
|
||||||
</Button>
|
|
||||||
{linkStatus.kind === "sent" &&
|
|
||||||
(linkStatus.message ? (
|
|
||||||
<p className="rounded border border-border bg-muted p-3 text-sm break-all">
|
|
||||||
Sign-in link (dev console transport):<br />
|
|
||||||
<span className="text-foreground underline">
|
|
||||||
{linkStatus.message}
|
|
||||||
</span>
|
|
||||||
</p>
|
|
||||||
) : (
|
|
||||||
<p className="rounded border border-border bg-muted p-3 text-sm">
|
|
||||||
Check your email for a single-use sign-in link. It expires in
|
|
||||||
10 minutes.
|
|
||||||
</p>
|
|
||||||
))}
|
|
||||||
{linkStatus.kind === "error" && linkStatus.message && (
|
|
||||||
<p role="alert" className="text-sm text-destructive">
|
|
||||||
{linkStatus.message}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</form>
|
|
||||||
|
|
||||||
<p className="text-xs text-muted-foreground">
|
|
||||||
First time here? The magic link will ask you to set a username and
|
|
||||||
password. If you are locked out, ask an admin for a reset link.
|
|
||||||
</p>
|
|
||||||
</CardContent>
|
|
||||||
</Card>
|
|
||||||
</div>
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,12 +1,17 @@
|
|||||||
import { getRespondAssignment } from "@/db/respond";
|
import {
|
||||||
|
alternativeOptionsForAssignment,
|
||||||
|
getRespondAssignment,
|
||||||
|
} from "@/db/respond";
|
||||||
import { verifyRespondToken } from "@/lib/respond";
|
import { verifyRespondToken } from "@/lib/respond";
|
||||||
import { RespondForm } from "@/components/app/respond-form";
|
import { RespondForm } from "@/components/app/respond-form";
|
||||||
|
import { AlternativeForm } from "@/components/app/alternative-form";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Public respond page — unit E4 (ARCHITECTURE §5.6).
|
* Public respond page — unit E4 (ARCHITECTURE §5.6).
|
||||||
*
|
*
|
||||||
* `GET /respond?t=<token>&a=confirm|decline` renders the assignment and the two
|
* `GET /respond?t=<token>` renders the assignment and the action the token was
|
||||||
* buttons. It never mutates: the token is consumed only by the form's POST.
|
* minted for: confirm/decline, or the "propose another Sunday" form. It never
|
||||||
|
* mutates: the token is consumed only by the form's POST.
|
||||||
*/
|
*/
|
||||||
export default async function RespondPage({
|
export default async function RespondPage({
|
||||||
searchParams,
|
searchParams,
|
||||||
@@ -41,6 +46,10 @@ export default async function RespondPage({
|
|||||||
|
|
||||||
const alreadyAnswered =
|
const alreadyAnswered =
|
||||||
assignment.status === "confirmed" || assignment.status === "declined";
|
assignment.status === "confirmed" || assignment.status === "declined";
|
||||||
|
const alternatives =
|
||||||
|
payload.action === "alternative" && !alreadyAnswered
|
||||||
|
? await alternativeOptionsForAssignment(payload.assignmentId)
|
||||||
|
: null;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<main className="mx-auto flex min-h-dvh max-w-lg flex-col justify-center gap-4 px-6">
|
<main className="mx-auto flex min-h-dvh max-w-lg flex-col justify-center gap-4 px-6">
|
||||||
@@ -60,6 +69,21 @@ export default async function RespondPage({
|
|||||||
<p className="text-sm text-muted-foreground">
|
<p className="text-sm text-muted-foreground">
|
||||||
You already responded — this assignment is {assignment.status}.
|
You already responded — this assignment is {assignment.status}.
|
||||||
</p>
|
</p>
|
||||||
|
) : payload.action === "alternative" ? (
|
||||||
|
alternatives && alternatives.length > 0 ? (
|
||||||
|
<AlternativeForm
|
||||||
|
token={t}
|
||||||
|
options={alternatives.map((option) => ({
|
||||||
|
id: option.id,
|
||||||
|
label: option.label,
|
||||||
|
}))}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
There are no other upcoming services for this position right now.
|
||||||
|
Please decline so a coordinator can help.
|
||||||
|
</p>
|
||||||
|
)
|
||||||
) : (
|
) : (
|
||||||
<RespondForm token={t} />
|
<RespondForm token={t} />
|
||||||
)}
|
)}
|
||||||
|
|||||||
+8
-2
@@ -18,7 +18,13 @@ import { db } from "@/db";
|
|||||||
import { users } from "@/db/schema";
|
import { users } from "@/db/schema";
|
||||||
import { eq } from "drizzle-orm";
|
import { eq } from "drizzle-orm";
|
||||||
import { uuidv7 } from "@/lib/uuid";
|
import { uuidv7 } from "@/lib/uuid";
|
||||||
import { APP_ORIGIN, getUser, normalizeEmail, signMagicToken } from "./magic-link";
|
import {
|
||||||
|
APP_ORIGIN,
|
||||||
|
INVITE_LINK_TTL,
|
||||||
|
getUser,
|
||||||
|
normalizeEmail,
|
||||||
|
signMagicToken,
|
||||||
|
} from "./magic-link";
|
||||||
import type { UserStatus } from "@/db/schema";
|
import type { UserStatus } from "@/db/schema";
|
||||||
|
|
||||||
export type UserAction = "invite" | "approve" | "deny";
|
export type UserAction = "invite" | "approve" | "deny";
|
||||||
@@ -124,7 +130,7 @@ export async function inviteUser(input: {
|
|||||||
appOrigin?: string;
|
appOrigin?: string;
|
||||||
}) {
|
}) {
|
||||||
const user = await resolveOrCreateInvitee(input.email);
|
const user = await resolveOrCreateInvitee(input.email);
|
||||||
const token = await signMagicToken(user.email);
|
const token = await signMagicToken(user.email, INVITE_LINK_TTL);
|
||||||
const origin = input.appOrigin ?? APP_ORIGIN;
|
const origin = input.appOrigin ?? APP_ORIGIN;
|
||||||
const url = `${origin}/api/dev/complete?token=${encodeURIComponent(
|
const url = `${origin}/api/dev/complete?token=${encodeURIComponent(
|
||||||
token,
|
token,
|
||||||
|
|||||||
@@ -1,10 +1,25 @@
|
|||||||
import { describe, expect, it } from "vitest";
|
import { describe, expect, it } from "vitest";
|
||||||
import { requestOrigin } from "./magic-link";
|
import { decodeJwt } from "jose";
|
||||||
|
import { INVITE_LINK_TTL, requestOrigin, signMagicToken } from "./magic-link";
|
||||||
|
|
||||||
function req(url: string, headers: Record<string, string>) {
|
function req(url: string, headers: Record<string, string>) {
|
||||||
return { url, headers: new Headers(headers) };
|
return { url, headers: new Headers(headers) };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
describe("magic token lifetimes", () => {
|
||||||
|
it("keeps a just-requested sign-in link short", async () => {
|
||||||
|
const payload = decodeJwt(await signMagicToken("person@example.com"));
|
||||||
|
expect(payload.exp! - payload.iat!).toBe(10 * 60);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("lets an invite link survive days in an inbox", async () => {
|
||||||
|
const payload = decodeJwt(
|
||||||
|
await signMagicToken("person@example.com", INVITE_LINK_TTL),
|
||||||
|
);
|
||||||
|
expect(payload.exp! - payload.iat!).toBe(7 * 24 * 60 * 60);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe("requestOrigin", () => {
|
describe("requestOrigin", () => {
|
||||||
it("uses the proxy's forwarded scheme and host", () => {
|
it("uses the proxy's forwarded scheme and host", () => {
|
||||||
expect(
|
expect(
|
||||||
|
|||||||
+25
-7
@@ -44,11 +44,18 @@ export const MAGIC_LINK_DEV_TRANSPORT =
|
|||||||
? process.env.MAGIC_LINK_DEV_TRANSPORT === "true"
|
? process.env.MAGIC_LINK_DEV_TRANSPORT === "true"
|
||||||
: process.env.NODE_ENV !== "production";
|
: process.env.NODE_ENV !== "production";
|
||||||
|
|
||||||
export const APP_ORIGIN =
|
/**
|
||||||
process.env.AUTH_URL ??
|
* Canonical origin for links built outside a live request. PUBLIC_ORIGIN is the
|
||||||
process.env.NEXTAUTH_URL ??
|
* address volunteers actually receive, so it wins over the auth callback URL
|
||||||
process.env.APP_ORIGIN ??
|
* (which may be a LAN address used only for cookies).
|
||||||
"http://localhost:3000";
|
*/
|
||||||
|
export const APP_ORIGIN = (
|
||||||
|
process.env.PUBLIC_ORIGIN?.trim() ||
|
||||||
|
process.env.AUTH_URL?.trim() ||
|
||||||
|
process.env.NEXTAUTH_URL?.trim() ||
|
||||||
|
process.env.APP_ORIGIN?.trim() ||
|
||||||
|
"http://localhost:3000"
|
||||||
|
).replace(/\/+$/, "");
|
||||||
|
|
||||||
function firstHeaderValue(value: string | null): string | null {
|
function firstHeaderValue(value: string | null): string | null {
|
||||||
if (!value) return null;
|
if (!value) return null;
|
||||||
@@ -221,7 +228,18 @@ export async function getOrCreateUser(email: string) {
|
|||||||
return raced;
|
return raced;
|
||||||
}
|
}
|
||||||
|
|
||||||
export async function signMagicToken(email: string): Promise<string> {
|
/**
|
||||||
|
* Sign-in links are short-lived because they are requested and clicked in the
|
||||||
|
* same sitting. Invites and welcome mails are not: they land in an inbox and may
|
||||||
|
* be opened days later, so they get their own lifetime (still single use).
|
||||||
|
*/
|
||||||
|
export const SIGN_IN_LINK_TTL = "10m";
|
||||||
|
export const INVITE_LINK_TTL = "7d";
|
||||||
|
|
||||||
|
export async function signMagicToken(
|
||||||
|
email: string,
|
||||||
|
ttl: string = SIGN_IN_LINK_TTL,
|
||||||
|
): Promise<string> {
|
||||||
return new SignJWT({
|
return new SignJWT({
|
||||||
email,
|
email,
|
||||||
purpose: "magic-link",
|
purpose: "magic-link",
|
||||||
@@ -229,7 +247,7 @@ export async function signMagicToken(email: string): Promise<string> {
|
|||||||
.setProtectedHeader({ alg: "HS256" })
|
.setProtectedHeader({ alg: "HS256" })
|
||||||
.setJti(uuidv7())
|
.setJti(uuidv7())
|
||||||
.setIssuedAt()
|
.setIssuedAt()
|
||||||
.setExpirationTime("10m")
|
.setExpirationTime(ttl)
|
||||||
.sign(SECRET);
|
.sign(SECRET);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,111 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* "Propose another Sunday" on the public `/respond` page.
|
||||||
|
*
|
||||||
|
* Only rendered for an `alternative` email link. Submitting records the
|
||||||
|
* volunteer's preferred Sunday for a coordinator; it does not change the
|
||||||
|
* assignment, so a proposal never silently opens a hole in the schedule.
|
||||||
|
*/
|
||||||
|
export function AlternativeForm({
|
||||||
|
token,
|
||||||
|
options,
|
||||||
|
}: {
|
||||||
|
token: string;
|
||||||
|
options: { id: string; label: string }[];
|
||||||
|
}) {
|
||||||
|
const [instanceId, setInstanceId] = useState(options[0]?.id ?? "");
|
||||||
|
const [note, setNote] = useState("");
|
||||||
|
const [state, setState] = useState<"idle" | "sending" | "done" | "error">(
|
||||||
|
"idle",
|
||||||
|
);
|
||||||
|
const [message, setMessage] = useState("");
|
||||||
|
|
||||||
|
async function submit(event: React.FormEvent<HTMLFormElement>) {
|
||||||
|
event.preventDefault();
|
||||||
|
setState("sending");
|
||||||
|
setMessage("");
|
||||||
|
try {
|
||||||
|
const res = await fetch("/api/respond/alternative", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "content-type": "application/json" },
|
||||||
|
body: JSON.stringify({ token, instanceId, note }),
|
||||||
|
});
|
||||||
|
const body = (await res.json().catch(() => ({}))) as {
|
||||||
|
error?: string;
|
||||||
|
};
|
||||||
|
if (!res.ok) {
|
||||||
|
setMessage(body.error ?? "Could not send your proposal.");
|
||||||
|
setState("error");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
const picked =
|
||||||
|
options.find((option) => option.id === instanceId)?.label ??
|
||||||
|
"that Sunday";
|
||||||
|
setMessage(
|
||||||
|
`Thanks — your coordinator will see that you can serve on ${picked}.`,
|
||||||
|
);
|
||||||
|
setState("done");
|
||||||
|
} catch {
|
||||||
|
setMessage("Network error — please try again.");
|
||||||
|
setState("error");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (state === "done") {
|
||||||
|
return (
|
||||||
|
<p role="status" className="text-sm text-muted-foreground">
|
||||||
|
{message}
|
||||||
|
</p>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<form onSubmit={submit} className="space-y-3">
|
||||||
|
<label className="block space-y-1 text-sm">
|
||||||
|
<span className="font-medium">Which Sunday works instead?</span>
|
||||||
|
<select
|
||||||
|
value={instanceId}
|
||||||
|
onChange={(event) => setInstanceId(event.target.value)}
|
||||||
|
className="block min-h-11 w-full rounded-md border border-input bg-background px-3 text-sm"
|
||||||
|
>
|
||||||
|
{options.map((option) => (
|
||||||
|
<option key={option.id} value={option.id}>
|
||||||
|
{option.label}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<label className="block space-y-1 text-sm">
|
||||||
|
<span className="font-medium">
|
||||||
|
Anything the coordinator should know?{" "}
|
||||||
|
<span className="font-normal text-muted-foreground">(optional)</span>
|
||||||
|
</span>
|
||||||
|
<textarea
|
||||||
|
value={note}
|
||||||
|
onChange={(event) => setNote(event.target.value)}
|
||||||
|
maxLength={500}
|
||||||
|
rows={3}
|
||||||
|
className="block w-full rounded-md border border-input bg-background px-3 py-2 text-sm"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
disabled={state === "sending" || !instanceId}
|
||||||
|
className="inline-flex min-h-11 items-center rounded-md bg-primary px-4 text-sm font-medium text-primary-foreground disabled:opacity-50"
|
||||||
|
>
|
||||||
|
{state === "sending" ? "Sending…" : "Propose this Sunday"}
|
||||||
|
</button>
|
||||||
|
|
||||||
|
{state === "error" && (
|
||||||
|
<p role="alert" className="text-sm text-destructive">
|
||||||
|
{message}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import { Loader2, Wand2 } from "lucide-react";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Opens the event in the advanced editor. The bridge URL is minted by the API
|
||||||
|
* with the normal dashboard session, so this is a POST followed by a redirect.
|
||||||
|
*/
|
||||||
|
export function AdvancedEditorButton({ eventId }: { eventId: string }) {
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
async function open() {
|
||||||
|
setBusy(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const res = await fetch(`/api/events/${eventId}/advanced`, {
|
||||||
|
method: "POST",
|
||||||
|
});
|
||||||
|
const data = (await res.json().catch(() => ({}))) as {
|
||||||
|
url?: string;
|
||||||
|
error?: string;
|
||||||
|
};
|
||||||
|
if (!res.ok || !data.url) {
|
||||||
|
throw new Error(data.error ?? "The advanced editor could not be opened.");
|
||||||
|
}
|
||||||
|
window.location.assign(data.url);
|
||||||
|
} catch (cause) {
|
||||||
|
setError(
|
||||||
|
cause instanceof Error
|
||||||
|
? cause.message
|
||||||
|
: "The advanced editor could not be opened.",
|
||||||
|
);
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<span className="flex flex-wrap items-center gap-2">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
disabled={busy}
|
||||||
|
onClick={open}
|
||||||
|
>
|
||||||
|
{busy ? (
|
||||||
|
<Loader2 className="h-3.5 w-3.5 animate-spin" aria-hidden="true" />
|
||||||
|
) : (
|
||||||
|
<Wand2 className="h-3.5 w-3.5" aria-hidden="true" />
|
||||||
|
)}
|
||||||
|
Advanced editor
|
||||||
|
</Button>
|
||||||
|
{error && (
|
||||||
|
<span role="alert" className="text-xs text-destructive">
|
||||||
|
{error}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
"use client";
|
|
||||||
|
|
||||||
import { useState } from "react";
|
|
||||||
import { useRouter } from "next/navigation";
|
|
||||||
import { Button } from "@/components/ui/button";
|
|
||||||
import { Input } from "@/components/ui/input";
|
|
||||||
import { Label } from "@/components/ui/label";
|
|
||||||
|
|
||||||
const SELECT_CLASS =
|
|
||||||
"h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2";
|
|
||||||
|
|
||||||
/** Create a named folder inside an event ("Originals", "Edited selects"). */
|
|
||||||
export function FolderCreateForm({ eventId }: { eventId: string }) {
|
|
||||||
const router = useRouter();
|
|
||||||
const [name, setName] = useState("");
|
|
||||||
const [kind, setKind] = useState("originals");
|
|
||||||
const [busy, setBusy] = useState(false);
|
|
||||||
const [error, setError] = useState<string | null>(null);
|
|
||||||
|
|
||||||
async function create() {
|
|
||||||
setBusy(true);
|
|
||||||
setError(null);
|
|
||||||
try {
|
|
||||||
const res = await fetch(`/api/events/${eventId}/folders`, {
|
|
||||||
method: "POST",
|
|
||||||
headers: { "content-type": "application/json" },
|
|
||||||
body: JSON.stringify({ name, kind }),
|
|
||||||
});
|
|
||||||
const data = (await res.json().catch(() => ({}))) as { error?: string };
|
|
||||||
if (!res.ok) {
|
|
||||||
setError(data.error ?? "Could not create the folder.");
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
setName("");
|
|
||||||
router.refresh();
|
|
||||||
} catch {
|
|
||||||
setError("Network error.");
|
|
||||||
} finally {
|
|
||||||
setBusy(false);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return (
|
|
||||||
<div className="space-y-2 rounded-md border border-dashed border-border p-3">
|
|
||||||
<div className="flex flex-wrap items-end gap-2">
|
|
||||||
<div className="min-w-40 flex-1 space-y-1">
|
|
||||||
<Label htmlFor="folder-name">New folder</Label>
|
|
||||||
<Input
|
|
||||||
id="folder-name"
|
|
||||||
value={name}
|
|
||||||
onChange={(event) => setName(event.target.value)}
|
|
||||||
placeholder="Originals"
|
|
||||||
/>
|
|
||||||
</div>
|
|
||||||
<div className="space-y-1">
|
|
||||||
<Label htmlFor="folder-kind">Contents</Label>
|
|
||||||
<select
|
|
||||||
id="folder-kind"
|
|
||||||
className={SELECT_CLASS}
|
|
||||||
value={kind}
|
|
||||||
onChange={(event) => setKind(event.target.value)}
|
|
||||||
>
|
|
||||||
<option value="originals">RAW / originals</option>
|
|
||||||
<option value="edited">Edited exports</option>
|
|
||||||
<option value="mixed">Mixed</option>
|
|
||||||
</select>
|
|
||||||
</div>
|
|
||||||
<Button
|
|
||||||
type="button"
|
|
||||||
size="sm"
|
|
||||||
disabled={busy || name.trim().length === 0}
|
|
||||||
onClick={create}
|
|
||||||
>
|
|
||||||
{busy ? "Creating…" : "Create folder"}
|
|
||||||
</Button>
|
|
||||||
</div>
|
|
||||||
{error && (
|
|
||||||
<p role="alert" className="text-sm text-destructive">
|
|
||||||
{error}
|
|
||||||
</p>
|
|
||||||
)}
|
|
||||||
</div>
|
|
||||||
);
|
|
||||||
}
|
|
||||||
@@ -8,9 +8,45 @@ import { Badge } from "@/components/ui/badge";
|
|||||||
import { Input } from "@/components/ui/input";
|
import { Input } from "@/components/ui/input";
|
||||||
import { PhotoViewer, type ViewerPhoto } from "./photo-viewer";
|
import { PhotoViewer, type ViewerPhoto } from "./photo-viewer";
|
||||||
import type { PhotoAdjustments } from "@/lib/photo-adjustments";
|
import type { PhotoAdjustments } from "@/lib/photo-adjustments";
|
||||||
|
import type { AdvancedEditView } from "@/lib/advanced-edit";
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Grid image that degrades to a readable tile instead of a blank square when
|
||||||
|
* the thumbnail cannot be produced (damaged or unsupported RAW, missing file).
|
||||||
|
*/
|
||||||
|
function GalleryImage({ src, alt }: { src: string; alt: string }) {
|
||||||
|
const [failed, setFailed] = useState(false);
|
||||||
|
|
||||||
|
if (failed) {
|
||||||
|
return (
|
||||||
|
<div className="flex h-full w-full flex-col items-center justify-center gap-1 px-2 text-center text-muted-foreground">
|
||||||
|
<FileImage className="h-8 w-8" aria-hidden="true" />
|
||||||
|
<span className="text-[11px] font-medium">Preview unavailable</span>
|
||||||
|
<span className="w-full truncate text-[10px]" title={alt}>
|
||||||
|
{alt}
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
// Frames are private; the serving route sets the cache policy.
|
||||||
|
// eslint-disable-next-line @next/next/no-img-element
|
||||||
|
<img
|
||||||
|
src={src}
|
||||||
|
alt={alt}
|
||||||
|
loading="lazy"
|
||||||
|
decoding="async"
|
||||||
|
onError={() => setFailed(true)}
|
||||||
|
className="h-full w-full object-cover"
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export interface GalleryPhoto {
|
export interface GalleryPhoto {
|
||||||
id: string;
|
id: string;
|
||||||
|
/** Storage folder the photo lives in; photos are shown as one event gallery. */
|
||||||
|
folderId: string;
|
||||||
filename: string;
|
filename: string;
|
||||||
sizeBytes: number;
|
sizeBytes: number;
|
||||||
kind: "raw" | "image";
|
kind: "raw" | "image";
|
||||||
@@ -19,6 +55,10 @@ export interface GalleryPhoto {
|
|||||||
previewable: boolean;
|
previewable: boolean;
|
||||||
editable: boolean;
|
editable: boolean;
|
||||||
adjustments: PhotoAdjustments;
|
adjustments: PhotoAdjustments;
|
||||||
|
/** The saved edit was produced by the advanced (Lumenroom) editor. */
|
||||||
|
advancedEdit: boolean;
|
||||||
|
/** Read-only view of the advanced recipe and a quick-editor seed. */
|
||||||
|
advancedSummary: AdvancedEditView | null;
|
||||||
editedAt: string | null;
|
editedAt: string | null;
|
||||||
editedSizeBytes: number | null;
|
editedSizeBytes: number | null;
|
||||||
}
|
}
|
||||||
@@ -74,13 +114,13 @@ function extensionOf(filename: string): string {
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Folder gallery + uploader. Files upload one at a time as raw request bodies,
|
* The event's photo gallery + uploader. Files upload one at a time as raw
|
||||||
* which keeps a 100 MB RAW frame out of memory and gives usable per-file
|
* request bodies, which keeps a 100 MB RAW frame out of memory and gives usable
|
||||||
* progress on a phone. RAW files show a file tile; JPEG/PNG/WebP preview.
|
* per-file progress on a phone. RAW files show a file tile; JPEG/PNG/WebP
|
||||||
|
* preview.
|
||||||
*/
|
*/
|
||||||
export function PhotoGallery({
|
export function PhotoGallery({
|
||||||
eventId,
|
eventId,
|
||||||
folderId,
|
|
||||||
photos,
|
photos,
|
||||||
canContribute,
|
canContribute,
|
||||||
canManage,
|
canManage,
|
||||||
@@ -89,7 +129,6 @@ export function PhotoGallery({
|
|||||||
storageMessage,
|
storageMessage,
|
||||||
}: {
|
}: {
|
||||||
eventId: string;
|
eventId: string;
|
||||||
folderId: string;
|
|
||||||
photos: GalleryPhoto[];
|
photos: GalleryPhoto[];
|
||||||
canContribute: boolean;
|
canContribute: boolean;
|
||||||
canManage: boolean;
|
canManage: boolean;
|
||||||
@@ -131,7 +170,7 @@ export function PhotoGallery({
|
|||||||
setProgress({ done: index, total: files.length, current: file.name });
|
setProgress({ done: index, total: files.length, current: file.name });
|
||||||
try {
|
try {
|
||||||
const res = await fetch(
|
const res = await fetch(
|
||||||
`/api/events/${eventId}/folders/${folderId}/photos?name=${encodeURIComponent(file.name)}`,
|
`/api/events/${eventId}/photos?name=${encodeURIComponent(file.name)}`,
|
||||||
{
|
{
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: {
|
headers: {
|
||||||
@@ -171,7 +210,7 @@ export function PhotoGallery({
|
|||||||
setNotice(
|
setNotice(
|
||||||
[
|
[
|
||||||
uploaded > 0 ? `${uploaded} uploaded` : null,
|
uploaded > 0 ? `${uploaded} uploaded` : null,
|
||||||
duplicates > 0 ? `${duplicates} already in this folder` : null,
|
duplicates > 0 ? `${duplicates} already on this event` : null,
|
||||||
]
|
]
|
||||||
.filter(Boolean)
|
.filter(Boolean)
|
||||||
.join(" · ") || null,
|
.join(" · ") || null,
|
||||||
@@ -187,7 +226,7 @@ export function PhotoGallery({
|
|||||||
setError(null);
|
setError(null);
|
||||||
try {
|
try {
|
||||||
const res = await fetch(
|
const res = await fetch(
|
||||||
`/api/events/${eventId}/folders/${folderId}/photos/${photo.id}`,
|
`/api/events/${eventId}/folders/${photo.folderId}/photos/${photo.id}`,
|
||||||
{ method: "DELETE" },
|
{ method: "DELETE" },
|
||||||
);
|
);
|
||||||
const data = (await res.json().catch(() => ({}))) as { error?: string };
|
const data = (await res.json().catch(() => ({}))) as { error?: string };
|
||||||
@@ -214,7 +253,7 @@ export function PhotoGallery({
|
|||||||
|
|
||||||
{canContribute && (
|
{canContribute && (
|
||||||
<div className="space-y-2 rounded-md border border-border p-3">
|
<div className="space-y-2 rounded-md border border-border p-3">
|
||||||
<p className="text-sm font-medium">Upload photos to this folder</p>
|
<p className="text-sm font-medium">Upload photos to this event</p>
|
||||||
<div className="flex flex-wrap items-center gap-2">
|
<div className="flex flex-wrap items-center gap-2">
|
||||||
<Input
|
<Input
|
||||||
ref={inputRef}
|
ref={inputRef}
|
||||||
@@ -272,12 +311,12 @@ export function PhotoGallery({
|
|||||||
|
|
||||||
{photos.length === 0 ? (
|
{photos.length === 0 ? (
|
||||||
<p className="py-10 text-center text-sm text-muted-foreground">
|
<p className="py-10 text-center text-sm text-muted-foreground">
|
||||||
This folder is empty.
|
No photos yet. Upload the first frame for this event.
|
||||||
</p>
|
</p>
|
||||||
) : (
|
) : (
|
||||||
<ul className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4">
|
<ul className="grid grid-cols-2 gap-3 sm:grid-cols-3 lg:grid-cols-4">
|
||||||
{photos.map((photo) => {
|
{photos.map((photo) => {
|
||||||
const src = `/api/events/${eventId}/folders/${folderId}/photos/${photo.id}`;
|
const src = `/api/events/${eventId}/folders/${photo.folderId}/photos/${photo.id}`;
|
||||||
const editable = photo.editable && storageReady;
|
const editable = photo.editable && storageReady;
|
||||||
const canRemove = canManage || photo.uploaderId === currentUserId;
|
const canRemove = canManage || photo.uploaderId === currentUserId;
|
||||||
const version = photo.editedAt ? Date.parse(photo.editedAt) : 0;
|
const version = photo.editedAt ? Date.parse(photo.editedAt) : 0;
|
||||||
@@ -303,15 +342,7 @@ export function PhotoGallery({
|
|||||||
onClick={() => setViewing(photo)}
|
onClick={() => setViewing(photo)}
|
||||||
>
|
>
|
||||||
{photo.previewable || photo.editedAt || photo.kind === "raw" ? (
|
{photo.previewable || photo.editedAt || photo.kind === "raw" ? (
|
||||||
// Frames are private; the serving route sets the cache policy.
|
<GalleryImage src={displaySrc} alt={photo.filename} />
|
||||||
// eslint-disable-next-line @next/next/no-img-element
|
|
||||||
<img
|
|
||||||
src={displaySrc}
|
|
||||||
alt={photo.filename}
|
|
||||||
loading="lazy"
|
|
||||||
decoding="async"
|
|
||||||
className="h-full w-full object-cover"
|
|
||||||
/>
|
|
||||||
) : (
|
) : (
|
||||||
<div className="flex flex-col items-center gap-1 text-muted-foreground">
|
<div className="flex flex-col items-center gap-1 text-muted-foreground">
|
||||||
<FileImage className="h-8 w-8" aria-hidden="true" />
|
<FileImage className="h-8 w-8" aria-hidden="true" />
|
||||||
@@ -353,13 +384,31 @@ export function PhotoGallery({
|
|||||||
{photo.uploaderName}
|
{photo.uploaderName}
|
||||||
</p>
|
</p>
|
||||||
<div className="flex flex-wrap items-center gap-1">
|
<div className="flex flex-wrap items-center gap-1">
|
||||||
<a
|
{photo.editedAt ? (
|
||||||
href={`${src}?download=1`}
|
<>
|
||||||
className="inline-flex items-center gap-1 rounded px-1.5 py-1 text-[11px] font-medium text-primary hover:underline"
|
<a
|
||||||
>
|
href={`${src}?variant=edited&download=1&v=${version}`}
|
||||||
<Download className="h-3 w-3" aria-hidden="true" />
|
className="inline-flex items-center gap-1 rounded px-1.5 py-1 text-[11px] font-medium text-primary hover:underline"
|
||||||
Download
|
>
|
||||||
</a>
|
<Download className="h-3 w-3" aria-hidden="true" />
|
||||||
|
Download edited
|
||||||
|
</a>
|
||||||
|
<a
|
||||||
|
href={`${src}?download=1`}
|
||||||
|
className="inline-flex items-center gap-1 rounded px-1.5 py-1 text-[11px] font-medium text-muted-foreground hover:underline"
|
||||||
|
>
|
||||||
|
Original
|
||||||
|
</a>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<a
|
||||||
|
href={`${src}?download=1`}
|
||||||
|
className="inline-flex items-center gap-1 rounded px-1.5 py-1 text-[11px] font-medium text-primary hover:underline"
|
||||||
|
>
|
||||||
|
<Download className="h-3 w-3" aria-hidden="true" />
|
||||||
|
Download
|
||||||
|
</a>
|
||||||
|
)}
|
||||||
{editable && (
|
{editable && (
|
||||||
<button
|
<button
|
||||||
type="button"
|
type="button"
|
||||||
@@ -392,7 +441,7 @@ export function PhotoGallery({
|
|||||||
<PhotoViewer
|
<PhotoViewer
|
||||||
key={viewing.id}
|
key={viewing.id}
|
||||||
eventId={eventId}
|
eventId={eventId}
|
||||||
folderId={folderId}
|
folderId={viewing.folderId}
|
||||||
photo={{
|
photo={{
|
||||||
id: viewing.id,
|
id: viewing.id,
|
||||||
filename: viewing.filename,
|
filename: viewing.filename,
|
||||||
@@ -400,6 +449,8 @@ export function PhotoGallery({
|
|||||||
editedAt: viewing.editedAt,
|
editedAt: viewing.editedAt,
|
||||||
editedSizeBytes: viewing.editedSizeBytes,
|
editedSizeBytes: viewing.editedSizeBytes,
|
||||||
adjustments: viewing.adjustments,
|
adjustments: viewing.adjustments,
|
||||||
|
advancedEdit: viewing.advancedEdit,
|
||||||
|
advancedSummary: viewing.advancedSummary,
|
||||||
} satisfies ViewerPhoto}
|
} satisfies ViewerPhoto}
|
||||||
onClose={() => setViewing(null)}
|
onClose={() => setViewing(null)}
|
||||||
onSaved={() => router.refresh()}
|
onSaved={() => router.refresh()}
|
||||||
|
|||||||
@@ -39,6 +39,7 @@ import {
|
|||||||
} from "@/lib/photo-geometry";
|
} from "@/lib/photo-geometry";
|
||||||
import { PHOTO_EXPORT_PRESETS } from "@/lib/photo-exports";
|
import { PHOTO_EXPORT_PRESETS } from "@/lib/photo-exports";
|
||||||
import { PHOTO_PRESETS, applyPhotoPreset } from "@/lib/photo-presets";
|
import { PHOTO_PRESETS, applyPhotoPreset } from "@/lib/photo-presets";
|
||||||
|
import type { AdvancedEditView, QuickNumericSetting } from "@/lib/advanced-edit";
|
||||||
|
|
||||||
export interface ViewerPhoto {
|
export interface ViewerPhoto {
|
||||||
id: string;
|
id: string;
|
||||||
@@ -47,6 +48,10 @@ export interface ViewerPhoto {
|
|||||||
editedAt: string | null;
|
editedAt: string | null;
|
||||||
editedSizeBytes: number | null;
|
editedSizeBytes: number | null;
|
||||||
adjustments: PhotoAdjustments;
|
adjustments: PhotoAdjustments;
|
||||||
|
/** The saved edit came from the advanced editor; it cannot be re-applied here. */
|
||||||
|
advancedEdit: boolean;
|
||||||
|
/** Read-only view of the advanced recipe plus a quick-editor seed. */
|
||||||
|
advancedSummary: AdvancedEditView | null;
|
||||||
}
|
}
|
||||||
|
|
||||||
type EditorTab = "light" | "color" | "detail" | "geometry" | "presets";
|
type EditorTab = "light" | "color" | "detail" | "geometry" | "presets";
|
||||||
@@ -61,12 +66,6 @@ const TABS: { id: EditorTab; label: string }[] = [
|
|||||||
|
|
||||||
const CLIPBOARD_KEY = "glenloch-photo-adjustments";
|
const CLIPBOARD_KEY = "glenloch-photo-adjustments";
|
||||||
|
|
||||||
function formatBytes(bytes: number | null): string {
|
|
||||||
if (!bytes) return "";
|
|
||||||
if (bytes < 1024 * 1024) return `${Math.round(bytes / 1024)} KB`;
|
|
||||||
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
|
|
||||||
}
|
|
||||||
|
|
||||||
function cloneAdjustments(adjustments: PhotoAdjustments): PhotoAdjustments {
|
function cloneAdjustments(adjustments: PhotoAdjustments): PhotoAdjustments {
|
||||||
return {
|
return {
|
||||||
...adjustments,
|
...adjustments,
|
||||||
@@ -390,12 +389,35 @@ export function PhotoViewer({
|
|||||||
onNext?: () => void;
|
onNext?: () => void;
|
||||||
}) {
|
}) {
|
||||||
const src = `/api/events/${eventId}/folders/${folderId}/photos/${photo.id}`;
|
const src = `/api/events/${eventId}/folders/${folderId}/photos/${photo.id}`;
|
||||||
|
// An advanced edit is baked into its own render. The viewer previews that
|
||||||
|
// render and layers this editor's sliders on top, so both editors keep their
|
||||||
|
// work instead of the advanced look being replaced by a neutral render.
|
||||||
|
const showsAdvancedEdit = photo.advancedEdit && Boolean(photo.editedAt);
|
||||||
|
// A photo whose saved look is the advanced render and whose quick layer is
|
||||||
|
// untouched opens with the advanced settings already in the sliders, so the
|
||||||
|
// quick editor shows the same numbers the look was made with instead of a
|
||||||
|
// confusing row of zeros.
|
||||||
|
const advancedSeed = photo.advancedSummary?.seed ?? null;
|
||||||
|
const quickLayerIsNeutral =
|
||||||
|
JSON.stringify(photo.adjustments) === JSON.stringify(defaultPhotoAdjustments());
|
||||||
|
const autoSeed = showsAdvancedEdit && Boolean(advancedSeed) && quickLayerIsNeutral;
|
||||||
|
const [takeOverPending, setTakeOverPending] = useState(autoSeed);
|
||||||
|
const autoSeeded = useRef(autoSeed);
|
||||||
|
const showAdvancedPanel = showsAdvancedEdit;
|
||||||
|
// Once the sliders take over they render from the original file, so the
|
||||||
|
// preview must not keep the advanced render underneath them.
|
||||||
|
const basesOnAdvanced = showsAdvancedEdit && !takeOverPending;
|
||||||
|
const previewSrc = basesOnAdvanced
|
||||||
|
? `${src}?variant=advanced&v=${photo.editedAt ? Date.parse(photo.editedAt) : 0}`
|
||||||
|
: `${src}/preview`;
|
||||||
const canvasRef = useRef<HTMLCanvasElement>(null);
|
const canvasRef = useRef<HTMLCanvasElement>(null);
|
||||||
const rotatedRef = useRef<{ key: string; canvas: HTMLCanvasElement } | null>(
|
const rotatedRef = useRef<{ key: string; canvas: HTMLCanvasElement } | null>(
|
||||||
null,
|
null,
|
||||||
);
|
);
|
||||||
const [adjustments, setAdjustments] = useState<PhotoAdjustments>(() =>
|
const [adjustments, setAdjustments] = useState<PhotoAdjustments>(() =>
|
||||||
cloneAdjustments(photo.adjustments),
|
autoSeed && advancedSeed
|
||||||
|
? cloneAdjustments(advancedSeed)
|
||||||
|
: cloneAdjustments(photo.adjustments),
|
||||||
);
|
);
|
||||||
const [tab, setTab] = useState<EditorTab>("light");
|
const [tab, setTab] = useState<EditorTab>("light");
|
||||||
const [source, setSource] = useState<HTMLImageElement | null>(null);
|
const [source, setSource] = useState<HTMLImageElement | null>(null);
|
||||||
@@ -411,16 +433,19 @@ export function PhotoViewer({
|
|||||||
const [advancedBusy, setAdvancedBusy] = useState(false);
|
const [advancedBusy, setAdvancedBusy] = useState(false);
|
||||||
const [advancedError, setAdvancedError] = useState<string | null>(null);
|
const [advancedError, setAdvancedError] = useState<string | null>(null);
|
||||||
const [saveError, setSaveError] = useState<string | null>(null);
|
const [saveError, setSaveError] = useState<string | null>(null);
|
||||||
const [saveResult, setSaveResult] = useState<{
|
// Cache-buster for the saved JPEG links. The gallery remounts this viewer
|
||||||
editedAt: string;
|
// with fresh props after a save, so it is read once per opening.
|
||||||
editedSizeBytes: number;
|
const savedVersion = photo.editedAt ? Date.parse(photo.editedAt) : 0;
|
||||||
width: number;
|
|
||||||
height: number;
|
|
||||||
} | null>(null);
|
|
||||||
const [savedVersion, setSavedVersion] = useState(() =>
|
|
||||||
photo.editedAt ? Date.parse(photo.editedAt) : 0,
|
|
||||||
);
|
|
||||||
const [recipeMessage, setRecipeMessage] = useState<string | null>(null);
|
const [recipeMessage, setRecipeMessage] = useState<string | null>(null);
|
||||||
|
const [takeOverMessage, setTakeOverMessage] = useState<string | null>(null);
|
||||||
|
const [hoverSetting, setHoverSetting] = useState<{
|
||||||
|
label: string;
|
||||||
|
key: QuickNumericSetting;
|
||||||
|
amount: number;
|
||||||
|
} | null>(null);
|
||||||
|
const inlineRef = useRef<HTMLCanvasElement>(null);
|
||||||
|
const inlineSourceRef = useRef<HTMLImageElement | null>(null);
|
||||||
|
const [inlineReady, setInlineReady] = useState(false);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const onKey = (event: KeyboardEvent) => {
|
const onKey = (event: KeyboardEvent) => {
|
||||||
@@ -468,12 +493,12 @@ export function PhotoViewer({
|
|||||||
"The preview could not be prepared. You can still try saving the edit.",
|
"The preview could not be prepared. You can still try saving the edit.",
|
||||||
);
|
);
|
||||||
};
|
};
|
||||||
image.src = `${src}/preview`;
|
image.src = previewSrc;
|
||||||
return () => {
|
return () => {
|
||||||
active = false;
|
active = false;
|
||||||
image.src = "";
|
image.src = "";
|
||||||
};
|
};
|
||||||
}, [src]);
|
}, [previewSrc]);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (!source) return;
|
if (!source) return;
|
||||||
@@ -559,6 +584,52 @@ export function PhotoViewer({
|
|||||||
};
|
};
|
||||||
}, [adjustments, source, showOriginal]);
|
}, [adjustments, source, showOriginal]);
|
||||||
|
|
||||||
|
// The inline preview shows one advanced setting applied to the untouched
|
||||||
|
// original, so the summary reads as "what this control does" rather than a
|
||||||
|
// number on its own.
|
||||||
|
useEffect(() => {
|
||||||
|
if (!showAdvancedPanel) return;
|
||||||
|
let active = true;
|
||||||
|
const image = new Image();
|
||||||
|
image.onload = () => {
|
||||||
|
if (!active) return;
|
||||||
|
inlineSourceRef.current = image;
|
||||||
|
setInlineReady(true);
|
||||||
|
};
|
||||||
|
image.src = `${src}/preview`;
|
||||||
|
return () => {
|
||||||
|
active = false;
|
||||||
|
image.src = "";
|
||||||
|
};
|
||||||
|
}, [showAdvancedPanel, src]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const canvas = inlineRef.current;
|
||||||
|
const image = inlineSourceRef.current;
|
||||||
|
if (!canvas || !image || !hoverSetting) return;
|
||||||
|
const width = 240;
|
||||||
|
const height = Math.max(
|
||||||
|
1,
|
||||||
|
Math.round((width * image.naturalHeight) / Math.max(1, image.naturalWidth)),
|
||||||
|
);
|
||||||
|
if (canvas.width !== width || canvas.height !== height) {
|
||||||
|
canvas.width = width;
|
||||||
|
canvas.height = height;
|
||||||
|
}
|
||||||
|
const context = canvas.getContext("2d", { willReadFrequently: true });
|
||||||
|
if (!context) return;
|
||||||
|
context.drawImage(image, 0, 0, width, height);
|
||||||
|
const data = context.getImageData(0, 0, width, height);
|
||||||
|
applyPhotoAdjustmentsToRgba(
|
||||||
|
data.data,
|
||||||
|
width,
|
||||||
|
height,
|
||||||
|
{ ...defaultPhotoAdjustments(), [hoverSetting.key]: hoverSetting.amount },
|
||||||
|
4,
|
||||||
|
);
|
||||||
|
context.putImageData(data, 0, 0);
|
||||||
|
}, [hoverSetting, inlineReady]);
|
||||||
|
|
||||||
function update<K extends keyof PhotoAdjustments>(
|
function update<K extends keyof PhotoAdjustments>(
|
||||||
key: K,
|
key: K,
|
||||||
value: PhotoAdjustments[K],
|
value: PhotoAdjustments[K],
|
||||||
@@ -635,6 +706,31 @@ export function PhotoViewer({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Seed the sliders from the advanced recipe. The look is already saved in the
|
||||||
|
* advanced render, so nothing is written until the photographer saves; the
|
||||||
|
* next save retires the advanced recipe and renders from the original.
|
||||||
|
*/
|
||||||
|
function takeOverFromAdvanced() {
|
||||||
|
const view = photo.advancedSummary;
|
||||||
|
if (!view) return;
|
||||||
|
setAdjustments(cloneAdjustments(view.seed));
|
||||||
|
setTakeOverPending(true);
|
||||||
|
setTab("light");
|
||||||
|
setSaveError(null);
|
||||||
|
setRecipeMessage(null);
|
||||||
|
setTakeOverMessage(
|
||||||
|
"Advanced settings loaded. Review the sliders, then save to make this editor the source of truth.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function undoTakeOver() {
|
||||||
|
setAdjustments(cloneAdjustments(photo.adjustments));
|
||||||
|
setTakeOverPending(false);
|
||||||
|
setTakeOverMessage(null);
|
||||||
|
setSaveError(null);
|
||||||
|
}
|
||||||
|
|
||||||
async function save() {
|
async function save() {
|
||||||
setSaving(true);
|
setSaving(true);
|
||||||
setSaveError(null);
|
setSaveError(null);
|
||||||
@@ -642,27 +738,23 @@ export function PhotoViewer({
|
|||||||
const response = await fetch(`${src}/edit`, {
|
const response = await fetch(`${src}/edit`, {
|
||||||
method: "POST",
|
method: "POST",
|
||||||
headers: { "content-type": "application/json" },
|
headers: { "content-type": "application/json" },
|
||||||
body: JSON.stringify({ adjustments }),
|
body: JSON.stringify({
|
||||||
|
adjustments,
|
||||||
|
...(takeOverPending ? { takeOver: true } : {}),
|
||||||
|
}),
|
||||||
});
|
});
|
||||||
const data = (await response.json().catch(() => ({}))) as {
|
const data = (await response.json().catch(() => ({}))) as {
|
||||||
error?: string;
|
error?: string;
|
||||||
editedAt?: string;
|
editedAt?: string;
|
||||||
editedSizeBytes?: number;
|
|
||||||
width?: number;
|
|
||||||
height?: number;
|
|
||||||
};
|
};
|
||||||
if (!response.ok || !data.editedAt) {
|
if (!response.ok || !data.editedAt) {
|
||||||
setSaveError(data.error ?? "The edited JPEG could not be saved.");
|
setSaveError(data.error ?? "The edited JPEG could not be saved.");
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
setSaveResult({
|
// Saving is the end of the edit: refresh the gallery and close the
|
||||||
editedAt: data.editedAt,
|
// window so the new thumbnail and Edited badge are visible immediately.
|
||||||
editedSizeBytes: data.editedSizeBytes ?? 0,
|
|
||||||
width: data.width ?? 0,
|
|
||||||
height: data.height ?? 0,
|
|
||||||
});
|
|
||||||
setSavedVersion(Date.now());
|
|
||||||
onSaved();
|
onSaved();
|
||||||
|
onClose();
|
||||||
} catch {
|
} catch {
|
||||||
setSaveError("Network error while saving the edit.");
|
setSaveError("Network error while saving the edit.");
|
||||||
} finally {
|
} finally {
|
||||||
@@ -670,7 +762,7 @@ export function PhotoViewer({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
const hasSavedEdit = Boolean(photo.editedAt || saveResult);
|
const hasSavedEdit = Boolean(photo.editedAt);
|
||||||
const editedHref = `${src}?variant=edited&download=1&v=${savedVersion}`;
|
const editedHref = `${src}?variant=edited&download=1&v=${savedVersion}`;
|
||||||
|
|
||||||
return (
|
return (
|
||||||
@@ -811,7 +903,9 @@ export function PhotoViewer({
|
|||||||
<div className="flex flex-wrap items-center justify-between gap-2 px-3 pb-2 text-[11px] text-white/55">
|
<div className="flex flex-wrap items-center justify-between gap-2 px-3 pb-2 text-[11px] text-white/55">
|
||||||
<span>
|
<span>
|
||||||
{showOriginal
|
{showOriginal
|
||||||
? "Original look with crop"
|
? basesOnAdvanced
|
||||||
|
? "Before your slider changes"
|
||||||
|
: "Original look with crop"
|
||||||
: "Live preview · saved at full resolution"}
|
: "Live preview · saved at full resolution"}
|
||||||
</span>
|
</span>
|
||||||
{recipeMessage && <span>{recipeMessage}</span>}
|
{recipeMessage && <span>{recipeMessage}</span>}
|
||||||
@@ -852,6 +946,116 @@ export function PhotoViewer({
|
|||||||
<Histogram histogram={histogram} />
|
<Histogram histogram={histogram} />
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
{showAdvancedPanel && photo.advancedSummary && (
|
||||||
|
<details className="border-b border-border px-3 py-2">
|
||||||
|
<summary className="flex cursor-pointer items-center justify-between gap-2 text-xs font-medium">
|
||||||
|
<span>Advanced editor settings</span>
|
||||||
|
<span className="text-[11px] font-normal text-muted-foreground">
|
||||||
|
Read-only
|
||||||
|
</span>
|
||||||
|
</summary>
|
||||||
|
<div className="mt-2 space-y-2.5">
|
||||||
|
<div className="rounded-md border border-border bg-muted/20 p-1.5">
|
||||||
|
{/* Fixed height: a hover must not move the rows under the
|
||||||
|
cursor, or the preview would flicker on and off. */}
|
||||||
|
<div className="flex h-24 items-center justify-center overflow-hidden rounded bg-black/5">
|
||||||
|
<canvas
|
||||||
|
ref={inlineRef}
|
||||||
|
aria-label="Preview of the hovered advanced setting on the original photo"
|
||||||
|
className={`max-h-full max-w-full rounded ${hoverSetting ? "" : "hidden"}`}
|
||||||
|
/>
|
||||||
|
{!hoverSetting && (
|
||||||
|
<span className="px-2 text-center text-[10px] text-muted-foreground">
|
||||||
|
Hover a setting to preview it
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<p className="mt-1 h-7 text-[10px] leading-snug text-muted-foreground">
|
||||||
|
{hoverSetting
|
||||||
|
? `${hoverSetting.label} on the original file`
|
||||||
|
: "Each setting is shown on its own, applied to the original file."}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
{photo.advancedSummary.sections.length === 0 && (
|
||||||
|
<p className="text-[11px] leading-snug text-muted-foreground">
|
||||||
|
The advanced editor saved this photo without changing any
|
||||||
|
tone or colour setting.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{photo.advancedSummary.sections.map((section) => (
|
||||||
|
<div key={section.title}>
|
||||||
|
<p className="text-[10px] font-semibold uppercase tracking-wide text-muted-foreground">
|
||||||
|
{section.title}
|
||||||
|
</p>
|
||||||
|
<dl className="mt-0.5 space-y-0.5">
|
||||||
|
{section.items.map((item) => (
|
||||||
|
<div
|
||||||
|
key={`${section.title}-${item.label}`}
|
||||||
|
className={`-mx-1 flex items-baseline justify-between gap-3 rounded px-1 text-[11px] ${
|
||||||
|
item.preview ? "cursor-help hover:bg-muted/70" : ""
|
||||||
|
}`}
|
||||||
|
onMouseEnter={() =>
|
||||||
|
setHoverSetting(
|
||||||
|
item.preview
|
||||||
|
? {
|
||||||
|
label: item.label,
|
||||||
|
key: item.preview.key,
|
||||||
|
amount: item.preview.amount,
|
||||||
|
}
|
||||||
|
: null,
|
||||||
|
)
|
||||||
|
}
|
||||||
|
onMouseLeave={() => setHoverSetting(null)}
|
||||||
|
>
|
||||||
|
<dt className="text-muted-foreground">{item.label}</dt>
|
||||||
|
<dd className="font-mono tabular-nums">{item.value}</dd>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</dl>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
{photo.advancedSummary.onlyAdvanced.length > 0 && (
|
||||||
|
<p className="text-[11px] leading-snug text-muted-foreground">
|
||||||
|
Only in the advanced editor:{" "}
|
||||||
|
{photo.advancedSummary.onlyAdvanced.join(", ")}.
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{photo.advancedSummary.caveats.map((caveat) => (
|
||||||
|
<p
|
||||||
|
key={caveat}
|
||||||
|
className="text-[11px] leading-snug text-muted-foreground"
|
||||||
|
>
|
||||||
|
{caveat}
|
||||||
|
</p>
|
||||||
|
))}
|
||||||
|
{takeOverPending ? (
|
||||||
|
<p className="text-[11px] leading-snug text-muted-foreground">
|
||||||
|
{autoSeeded.current
|
||||||
|
? "The sliders already hold these settings, previewed on the original file. Saving makes them the saved look."
|
||||||
|
: "These settings are loaded in the sliders, previewed on the original file. Saving makes them the saved look."}
|
||||||
|
</p>
|
||||||
|
) : (
|
||||||
|
<>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
className="h-8 w-full text-xs"
|
||||||
|
disabled={saving}
|
||||||
|
onClick={takeOverFromAdvanced}
|
||||||
|
>
|
||||||
|
Take over in the quick editor
|
||||||
|
</Button>
|
||||||
|
<p className="text-[11px] leading-snug text-muted-foreground">
|
||||||
|
Loads these values into the sliders. Saving then retires
|
||||||
|
the advanced recipe and renders from the original file.
|
||||||
|
</p>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</details>
|
||||||
|
)}
|
||||||
|
|
||||||
<div className="flex gap-1 overflow-x-auto border-b border-border px-2 py-2">
|
<div className="flex gap-1 overflow-x-auto border-b border-border px-2 py-2">
|
||||||
{TABS.map((item) => (
|
{TABS.map((item) => (
|
||||||
<button
|
<button
|
||||||
@@ -1216,19 +1420,42 @@ export function PhotoViewer({
|
|||||||
</p>
|
</p>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
{saveResult && (
|
{basesOnAdvanced && (
|
||||||
<div
|
<p className="rounded-md border border-border bg-muted/40 p-2 text-[11px] leading-snug text-muted-foreground">
|
||||||
role="status"
|
The advanced editor's edit is kept as the base. Slider
|
||||||
className="space-y-1 rounded-md border border-border bg-muted/40 p-3 text-xs"
|
changes here are saved on top of it, and saving in the advanced
|
||||||
>
|
editor again keeps this layer.
|
||||||
<p className="font-medium">Full-resolution JPEG saved.</p>
|
</p>
|
||||||
<p className="text-muted-foreground">
|
)}
|
||||||
{saveResult.width} × {saveResult.height} ·{" "}
|
|
||||||
{formatBytes(saveResult.editedSizeBytes)}
|
{takeOverPending && (
|
||||||
|
<div className="space-y-1.5 rounded-md border border-border bg-muted/40 p-2">
|
||||||
|
<p className="text-[11px] leading-snug text-muted-foreground">
|
||||||
|
{autoSeeded.current
|
||||||
|
? "These sliders were filled from the advanced edit and are previewed on the original file."
|
||||||
|
: "These values came from the advanced edit and are previewed on the original file."}{" "}
|
||||||
|
Saving makes the quick editor the source of truth and retires
|
||||||
|
the advanced recipe.
|
||||||
</p>
|
</p>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="text-[11px] font-medium text-primary hover:underline"
|
||||||
|
onClick={undoTakeOver}
|
||||||
|
>
|
||||||
|
Undo takeover
|
||||||
|
</button>
|
||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
|
{takeOverMessage && !saveError && (
|
||||||
|
<p
|
||||||
|
role="status"
|
||||||
|
className="rounded-md border border-border bg-muted/40 p-2 text-[11px] leading-snug text-muted-foreground"
|
||||||
|
>
|
||||||
|
{takeOverMessage}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
{hasSavedEdit && (
|
{hasSavedEdit && (
|
||||||
<div className="space-y-2 rounded-md border border-border bg-muted/20 p-3">
|
<div className="space-y-2 rounded-md border border-border bg-muted/20 p-3">
|
||||||
<p className="text-xs font-medium">Download JPEG</p>
|
<p className="text-xs font-medium">Download JPEG</p>
|
||||||
|
|||||||
@@ -0,0 +1,252 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useState } from "react";
|
||||||
|
import Link from "next/link";
|
||||||
|
import { useRouter } from "next/navigation";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Input } from "@/components/ui/input";
|
||||||
|
import { Label } from "@/components/ui/label";
|
||||||
|
|
||||||
|
export interface SpecialServiceRole {
|
||||||
|
id: string;
|
||||||
|
name: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SpecialServicePerson {
|
||||||
|
id: string;
|
||||||
|
displayName: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Adds a one-off service to the week on screen. Unlike a recurring template it
|
||||||
|
* has no rrule: just a date, a time, and the positions this occurrence actually
|
||||||
|
* needs — a Wednesday prayer meeting can run with Audio alone.
|
||||||
|
*
|
||||||
|
* Picking a photographer creates their media event for the same date/time, so
|
||||||
|
* the shoot lands in their Events list with them already assigned.
|
||||||
|
*/
|
||||||
|
export function SpecialServiceForm({
|
||||||
|
roles,
|
||||||
|
volunteers,
|
||||||
|
defaultDate,
|
||||||
|
}: {
|
||||||
|
roles: SpecialServiceRole[];
|
||||||
|
volunteers: SpecialServicePerson[];
|
||||||
|
defaultDate: string;
|
||||||
|
}) {
|
||||||
|
const router = useRouter();
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
const [title, setTitle] = useState("");
|
||||||
|
const [date, setDate] = useState(defaultDate);
|
||||||
|
const [startTime, setStartTime] = useState("10:00");
|
||||||
|
const [duration, setDuration] = useState("60");
|
||||||
|
const [location, setLocation] = useState("");
|
||||||
|
const [roleIds, setRoleIds] = useState<string[]>([]);
|
||||||
|
const [photographerId, setPhotographerId] = useState("");
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [message, setMessage] = useState<string | null>(null);
|
||||||
|
const [eventId, setEventId] = useState<string | null>(null);
|
||||||
|
|
||||||
|
function toggleRole(id: string) {
|
||||||
|
setRoleIds((current) =>
|
||||||
|
current.includes(id)
|
||||||
|
? current.filter((value) => value !== id)
|
||||||
|
: [...current, id],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function submit(e: React.FormEvent) {
|
||||||
|
e.preventDefault();
|
||||||
|
setBusy(true);
|
||||||
|
setError(null);
|
||||||
|
setMessage(null);
|
||||||
|
setEventId(null);
|
||||||
|
try {
|
||||||
|
const res = await fetch("/api/dev/schedule/special", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "content-type": "application/json" },
|
||||||
|
body: JSON.stringify({
|
||||||
|
title,
|
||||||
|
date,
|
||||||
|
startTimeLocal: startTime,
|
||||||
|
durationMinutes: Number(duration) || 60,
|
||||||
|
location: location || null,
|
||||||
|
roleIds,
|
||||||
|
photographerId: photographerId || null,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
const data = (await res.json().catch(() => ({}))) as {
|
||||||
|
error?: string;
|
||||||
|
eventId?: string | null;
|
||||||
|
seats?: number;
|
||||||
|
};
|
||||||
|
if (!res.ok) {
|
||||||
|
setError(data.error ?? "Could not add the special service.");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setMessage(
|
||||||
|
`Added with ${data.seats ?? 0} position seat${(data.seats ?? 0) === 1 ? "" : "s"}${
|
||||||
|
data.eventId ? " and a media event for the photographer" : ""
|
||||||
|
}.`,
|
||||||
|
);
|
||||||
|
setEventId(data.eventId ?? null);
|
||||||
|
setTitle("");
|
||||||
|
setLocation("");
|
||||||
|
setRoleIds([]);
|
||||||
|
setPhotographerId("");
|
||||||
|
router.refresh();
|
||||||
|
} catch {
|
||||||
|
setError("Network error.");
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="rounded-md border border-border">
|
||||||
|
<div className="flex flex-wrap items-center justify-between gap-2 border-b border-border bg-muted/30 px-3 py-2">
|
||||||
|
<div>
|
||||||
|
<p className="text-sm font-semibold text-foreground">Special service</p>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
A one-off dated service with only the positions it needs.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
<Button
|
||||||
|
size="sm"
|
||||||
|
variant="outline"
|
||||||
|
onClick={() => setOpen((value) => !value)}
|
||||||
|
>
|
||||||
|
{open ? "Close" : "Add a special service"}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{open && (
|
||||||
|
<form onSubmit={submit} className="space-y-4 p-3">
|
||||||
|
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-4">
|
||||||
|
<div className="flex flex-col gap-2 sm:col-span-2">
|
||||||
|
<Label htmlFor="special-title">Title</Label>
|
||||||
|
<Input
|
||||||
|
id="special-title"
|
||||||
|
required
|
||||||
|
value={title}
|
||||||
|
onChange={(e) => setTitle(e.target.value)}
|
||||||
|
placeholder="Good Friday service"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-col gap-2">
|
||||||
|
<Label htmlFor="special-date">Date</Label>
|
||||||
|
<Input
|
||||||
|
id="special-date"
|
||||||
|
type="date"
|
||||||
|
required
|
||||||
|
value={date}
|
||||||
|
onChange={(e) => setDate(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-col gap-2">
|
||||||
|
<Label htmlFor="special-time">Start time</Label>
|
||||||
|
<Input
|
||||||
|
id="special-time"
|
||||||
|
type="time"
|
||||||
|
required
|
||||||
|
value={startTime}
|
||||||
|
onChange={(e) => setStartTime(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-col gap-2">
|
||||||
|
<Label htmlFor="special-duration">Minutes</Label>
|
||||||
|
<Input
|
||||||
|
id="special-duration"
|
||||||
|
type="number"
|
||||||
|
min={5}
|
||||||
|
max={600}
|
||||||
|
value={duration}
|
||||||
|
onChange={(e) => setDuration(e.target.value)}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="flex flex-col gap-2 sm:col-span-2 lg:col-span-3">
|
||||||
|
<Label htmlFor="special-location">Location</Label>
|
||||||
|
<Input
|
||||||
|
id="special-location"
|
||||||
|
value={location}
|
||||||
|
onChange={(e) => setLocation(e.target.value)}
|
||||||
|
placeholder="Main Auditorium"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<fieldset className="space-y-2">
|
||||||
|
<legend className="text-sm font-medium text-foreground">
|
||||||
|
Positions needed
|
||||||
|
</legend>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
Only the selected positions get seats. Leave all unchecked if the
|
||||||
|
service needs no media team.
|
||||||
|
</p>
|
||||||
|
<div className="flex flex-wrap gap-4">
|
||||||
|
{roles.map((role) => (
|
||||||
|
<label
|
||||||
|
key={role.id}
|
||||||
|
className="flex items-center gap-2 text-sm text-foreground"
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
className="h-4 w-4 accent-primary"
|
||||||
|
checked={roleIds.includes(role.id)}
|
||||||
|
onChange={() => toggleRole(role.id)}
|
||||||
|
/>
|
||||||
|
{role.name}
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</fieldset>
|
||||||
|
|
||||||
|
<div className="flex flex-col gap-2 sm:max-w-sm">
|
||||||
|
<Label htmlFor="special-photographer">Photographer (optional)</Label>
|
||||||
|
<select
|
||||||
|
id="special-photographer"
|
||||||
|
className="h-9 rounded-md border border-input bg-background px-3 text-sm"
|
||||||
|
value={photographerId}
|
||||||
|
onChange={(e) => setPhotographerId(e.target.value)}
|
||||||
|
>
|
||||||
|
<option value="">No photographer</option>
|
||||||
|
{volunteers.map((person) => (
|
||||||
|
<option key={person.id} value={person.id}>
|
||||||
|
{person.displayName}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
Creates a media event for this service and assigns them to it.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-wrap items-center gap-3">
|
||||||
|
<Button type="submit" disabled={busy}>
|
||||||
|
{busy ? "Adding…" : "Add special service"}
|
||||||
|
</Button>
|
||||||
|
{message && (
|
||||||
|
<p role="status" className="text-sm text-foreground">
|
||||||
|
{message}
|
||||||
|
{eventId && (
|
||||||
|
<>
|
||||||
|
{" "}
|
||||||
|
<Link className="underline" href={`/events/${eventId}`}>
|
||||||
|
Open the event
|
||||||
|
</Link>
|
||||||
|
</>
|
||||||
|
)}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
{error && (
|
||||||
|
<p role="alert" className="text-sm text-destructive">
|
||||||
|
{error}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -26,8 +26,9 @@ export function GuideShell({
|
|||||||
title: string;
|
title: string;
|
||||||
intro: string;
|
intro: string;
|
||||||
audience: string;
|
audience: string;
|
||||||
pdfHref: string;
|
/** Not every role guide has a PDF snapshot yet. */
|
||||||
pdfLabel: string;
|
pdfHref?: string;
|
||||||
|
pdfLabel?: string;
|
||||||
sections: GuideSectionLink[];
|
sections: GuideSectionLink[];
|
||||||
children: React.ReactNode;
|
children: React.ReactNode;
|
||||||
}) {
|
}) {
|
||||||
@@ -43,12 +44,14 @@ export function GuideShell({
|
|||||||
<ArrowLeft className="h-3.5 w-3.5" aria-hidden="true" />
|
<ArrowLeft className="h-3.5 w-3.5" aria-hidden="true" />
|
||||||
All training
|
All training
|
||||||
</Link>
|
</Link>
|
||||||
<Button asChild size="sm">
|
{pdfHref && pdfLabel ? (
|
||||||
<a href={pdfHref} download>
|
<Button asChild size="sm">
|
||||||
<Download aria-hidden="true" />
|
<a href={pdfHref} download>
|
||||||
{pdfLabel}
|
<Download aria-hidden="true" />
|
||||||
</a>
|
{pdfLabel}
|
||||||
</Button>
|
</a>
|
||||||
|
</Button>
|
||||||
|
) : null}
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
<header className="space-y-3">
|
<header className="space-y-3">
|
||||||
|
|||||||
+6
-2
@@ -32,6 +32,7 @@ import {
|
|||||||
} from "@/db/schema";
|
} from "@/db/schema";
|
||||||
import { autoFill, type AutoFillProposal, type AutoFillResult } from "@/domain/autoFill";
|
import { autoFill, type AutoFillProposal, type AutoFillResult } from "@/domain/autoFill";
|
||||||
import { isMentorReady } from "@/domain/mentor";
|
import { isMentorReady } from "@/domain/mentor";
|
||||||
|
import { enqueueAssignmentProposed } from "@/db/outbox";
|
||||||
import { uuidv7 } from "@/lib/uuid";
|
import { uuidv7 } from "@/lib/uuid";
|
||||||
|
|
||||||
const ACTIVE_ASSIGNMENT_STATUS = sql`${assignments.status} IN ('proposed','confirmed','completed')`;
|
const ACTIVE_ASSIGNMENT_STATUS = sql`${assignments.status} IN ('proposed','confirmed','completed')`;
|
||||||
@@ -349,20 +350,23 @@ export async function applyAutoFill(
|
|||||||
.limit(1);
|
.limit(1);
|
||||||
if (existing.length > 0) continue;
|
if (existing.length > 0) continue;
|
||||||
|
|
||||||
|
const assignmentId = uuidv7();
|
||||||
|
const now = new Date();
|
||||||
await db.transaction(async (tx) => {
|
await db.transaction(async (tx) => {
|
||||||
await tx.insert(assignments).values({
|
await tx.insert(assignments).values({
|
||||||
id: uuidv7(),
|
id: assignmentId,
|
||||||
slotId: proposal.slotId,
|
slotId: proposal.slotId,
|
||||||
userId: proposal.userId,
|
userId: proposal.userId,
|
||||||
status: "proposed",
|
status: "proposed",
|
||||||
source: "auto",
|
source: "auto",
|
||||||
assignedBy: opts.actorId,
|
assignedBy: opts.actorId,
|
||||||
assignedAt: new Date(),
|
assignedAt: now,
|
||||||
});
|
});
|
||||||
await tx
|
await tx
|
||||||
.update(slots)
|
.update(slots)
|
||||||
.set({ status: "proposed" })
|
.set({ status: "proposed" })
|
||||||
.where(eq(slots.id, proposal.slotId));
|
.where(eq(slots.id, proposal.slotId));
|
||||||
|
await enqueueAssignmentProposed(tx, assignmentId, { now });
|
||||||
});
|
});
|
||||||
written++;
|
written++;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -112,6 +112,12 @@ export interface BridgePhotoRow {
|
|||||||
sizeBytes: number;
|
sizeBytes: number;
|
||||||
storedName: string;
|
storedName: string;
|
||||||
editedStoredName: string | null;
|
editedStoredName: string | null;
|
||||||
|
/** Recipe saved by the advanced editor, so a reopen can restore its sliders. */
|
||||||
|
advancedEditJson: string | null;
|
||||||
|
/** Recipe from the simple editor, layered on top of the advanced render. */
|
||||||
|
editJson: string | null;
|
||||||
|
/** When the saved edit was rendered; stamps the thumbnail cache. */
|
||||||
|
editedAt: Date | null;
|
||||||
createdAt: Date;
|
createdAt: Date;
|
||||||
folderName: string;
|
folderName: string;
|
||||||
}
|
}
|
||||||
@@ -128,6 +134,9 @@ export async function listBridgePhotos(
|
|||||||
sizeBytes: eventPhotos.sizeBytes,
|
sizeBytes: eventPhotos.sizeBytes,
|
||||||
storedName: eventPhotos.storedName,
|
storedName: eventPhotos.storedName,
|
||||||
editedStoredName: eventPhotos.editedStoredName,
|
editedStoredName: eventPhotos.editedStoredName,
|
||||||
|
advancedEditJson: eventPhotos.advancedEditJson,
|
||||||
|
editJson: eventPhotos.editJson,
|
||||||
|
editedAt: eventPhotos.editedAt,
|
||||||
createdAt: eventPhotos.createdAt,
|
createdAt: eventPhotos.createdAt,
|
||||||
folderName: eventFolders.name,
|
folderName: eventFolders.name,
|
||||||
})
|
})
|
||||||
@@ -150,6 +159,9 @@ export async function getBridgePhoto(
|
|||||||
sizeBytes: eventPhotos.sizeBytes,
|
sizeBytes: eventPhotos.sizeBytes,
|
||||||
storedName: eventPhotos.storedName,
|
storedName: eventPhotos.storedName,
|
||||||
editedStoredName: eventPhotos.editedStoredName,
|
editedStoredName: eventPhotos.editedStoredName,
|
||||||
|
advancedEditJson: eventPhotos.advancedEditJson,
|
||||||
|
editJson: eventPhotos.editJson,
|
||||||
|
editedAt: eventPhotos.editedAt,
|
||||||
createdAt: eventPhotos.createdAt,
|
createdAt: eventPhotos.createdAt,
|
||||||
folderName: eventFolders.name,
|
folderName: eventFolders.name,
|
||||||
})
|
})
|
||||||
|
|||||||
+66
-7
@@ -17,9 +17,11 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { and, asc, desc, eq, gte, sql } from "drizzle-orm";
|
import { and, asc, desc, eq, gte, sql } from "drizzle-orm";
|
||||||
|
import { alias } from "drizzle-orm/pg-core";
|
||||||
import { db } from "@/db";
|
import { db } from "@/db";
|
||||||
import {
|
import {
|
||||||
assignments,
|
assignments,
|
||||||
|
assignmentProposals,
|
||||||
auditLog,
|
auditLog,
|
||||||
coverageRequests,
|
coverageRequests,
|
||||||
roles,
|
roles,
|
||||||
@@ -30,7 +32,10 @@ import {
|
|||||||
} from "@/db/schema";
|
} from "@/db/schema";
|
||||||
import { auditRow } from "@/db/audit";
|
import { auditRow } from "@/db/audit";
|
||||||
import { resolveAssignFacts, AssignFactError } from "@/db/assignments";
|
import { resolveAssignFacts, AssignFactError } from "@/db/assignments";
|
||||||
import { cancelAssignmentNotifications, enqueuePublishNotifications } from "@/db/outbox";
|
import {
|
||||||
|
cancelAssignmentNotifications,
|
||||||
|
enqueueAssignmentProposed,
|
||||||
|
} from "@/db/outbox";
|
||||||
import { enqueueRemindersForInstance } from "@/db/reminders";
|
import { enqueueRemindersForInstance } from "@/db/reminders";
|
||||||
import { classifyConflicts, hardConflicts } from "@/domain/conflicts";
|
import { classifyConflicts, hardConflicts } from "@/domain/conflicts";
|
||||||
import { uuidv7 } from "@/lib/uuid";
|
import { uuidv7 } from "@/lib/uuid";
|
||||||
@@ -100,7 +105,7 @@ export async function listPendingCoverageRequests(): Promise<
|
|||||||
assignmentId: coverageRequests.assignmentId,
|
assignmentId: coverageRequests.assignmentId,
|
||||||
slotId: slots.id,
|
slotId: slots.id,
|
||||||
roleName: roles.name,
|
roleName: roles.name,
|
||||||
serviceName: services.name,
|
serviceName: sql<string>`coalesce(${serviceInstances.titleOverride}, ${services.name})`,
|
||||||
startsAt: serviceInstances.startsAt,
|
startsAt: serviceInstances.startsAt,
|
||||||
callTime: slots.callTime,
|
callTime: slots.callTime,
|
||||||
location: services.location,
|
location: services.location,
|
||||||
@@ -343,17 +348,71 @@ export async function resolveCoverageRequest(
|
|||||||
}),
|
}),
|
||||||
);
|
);
|
||||||
|
|
||||||
// A published week's mail was written at publish time; the replacement
|
// The replacement is a proposed seat, so they get the same accept /
|
||||||
// needs its own rows. Both helpers are idempotent on dedupe_key.
|
// decline / propose-another-Sunday email as any other proposal. A
|
||||||
if (replacementUserId && request.instanceStatus === "published") {
|
// published week also needs its reminders topped up for the new seat.
|
||||||
await enqueuePublishNotifications(tx, request.instanceId, { now });
|
if (newAssignmentId) {
|
||||||
await enqueueRemindersForInstance(tx, request.instanceId, { now });
|
await enqueueAssignmentProposed(tx, newAssignmentId, { now });
|
||||||
|
if (request.instanceStatus === "published") {
|
||||||
|
await enqueueRemindersForInstance(tx, request.instanceId, { now });
|
||||||
|
}
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
return { status: "approved", assignmentId: newAssignmentId };
|
return { status: "approved", assignmentId: newAssignmentId };
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** A volunteer's "another Sunday" proposal, for the coordinator queue. */
|
||||||
|
export interface AlternativeProposalRow {
|
||||||
|
id: string;
|
||||||
|
requesterName: string;
|
||||||
|
requesterEmail: string;
|
||||||
|
roleName: string;
|
||||||
|
serviceName: string;
|
||||||
|
currentStartsAt: Date;
|
||||||
|
proposedStartsAt: Date;
|
||||||
|
note: string | null;
|
||||||
|
createdAt: Date;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Pending alternative-date proposals, soonest proposed Sunday first. */
|
||||||
|
export async function listPendingAlternativeProposals(): Promise<
|
||||||
|
AlternativeProposalRow[]
|
||||||
|
> {
|
||||||
|
const proposedInstance = alias(serviceInstances, "proposed_instance");
|
||||||
|
const rows = await db
|
||||||
|
.select({
|
||||||
|
id: assignmentProposals.id,
|
||||||
|
requesterName: sql<string>`coalesce(${users.displayName}, ${users.firstName} || ' ' || ${users.lastName})`,
|
||||||
|
requesterEmail: users.email,
|
||||||
|
roleName: roles.name,
|
||||||
|
serviceName: sql<string>`coalesce(${serviceInstances.titleOverride}, ${services.name})`,
|
||||||
|
currentStartsAt: serviceInstances.startsAt,
|
||||||
|
proposedStartsAt: proposedInstance.startsAt,
|
||||||
|
note: assignmentProposals.note,
|
||||||
|
createdAt: assignmentProposals.createdAt,
|
||||||
|
})
|
||||||
|
.from(assignmentProposals)
|
||||||
|
.innerJoin(assignments, eq(assignments.id, assignmentProposals.assignmentId))
|
||||||
|
.innerJoin(slots, eq(slots.id, assignments.slotId))
|
||||||
|
.innerJoin(roles, eq(roles.id, slots.roleId))
|
||||||
|
.innerJoin(serviceInstances, eq(serviceInstances.id, slots.serviceInstanceId))
|
||||||
|
.innerJoin(services, eq(services.id, serviceInstances.serviceId))
|
||||||
|
.innerJoin(
|
||||||
|
proposedInstance,
|
||||||
|
eq(proposedInstance.id, assignmentProposals.proposedInstanceId),
|
||||||
|
)
|
||||||
|
.innerJoin(users, eq(users.id, assignmentProposals.userId))
|
||||||
|
.where(eq(assignmentProposals.status, "pending"))
|
||||||
|
.orderBy(asc(proposedInstance.startsAt), asc(users.lastName));
|
||||||
|
|
||||||
|
return rows.map((row) => ({
|
||||||
|
...row,
|
||||||
|
currentStartsAt: row.currentStartsAt ?? new Date(0),
|
||||||
|
proposedStartsAt: row.proposedStartsAt ?? new Date(0),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
/* ------------------------------------------------------------------ utils */
|
/* ------------------------------------------------------------------ utils */
|
||||||
|
|
||||||
function auditLogRow(actorId: string, requestId: string, status: string) {
|
function auditLogRow(actorId: string, requestId: string, status: string) {
|
||||||
|
|||||||
@@ -73,6 +73,7 @@ export interface EventPhotoRow {
|
|||||||
checksumSha256: string;
|
checksumSha256: string;
|
||||||
kind: "raw" | "image";
|
kind: "raw" | "image";
|
||||||
editJson: string | null;
|
editJson: string | null;
|
||||||
|
advancedEditJson: string | null;
|
||||||
editedStoredName: string | null;
|
editedStoredName: string | null;
|
||||||
editedSizeBytes: number | null;
|
editedSizeBytes: number | null;
|
||||||
editedAt: Date | null;
|
editedAt: Date | null;
|
||||||
@@ -374,6 +375,7 @@ export async function getFolderDetail(
|
|||||||
checksumSha256: eventPhotos.checksumSha256,
|
checksumSha256: eventPhotos.checksumSha256,
|
||||||
kind: eventPhotos.kind,
|
kind: eventPhotos.kind,
|
||||||
editJson: eventPhotos.editJson,
|
editJson: eventPhotos.editJson,
|
||||||
|
advancedEditJson: eventPhotos.advancedEditJson,
|
||||||
editedStoredName: eventPhotos.editedStoredName,
|
editedStoredName: eventPhotos.editedStoredName,
|
||||||
editedSizeBytes: eventPhotos.editedSizeBytes,
|
editedSizeBytes: eventPhotos.editedSizeBytes,
|
||||||
editedAt: eventPhotos.editedAt,
|
editedAt: eventPhotos.editedAt,
|
||||||
@@ -402,6 +404,106 @@ export async function getFolderDetail(
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Every photo in an event, newest last, across all of its storage folders.
|
||||||
|
* The event page renders these as one gallery; folders are an internal detail
|
||||||
|
* and never shown to photographers.
|
||||||
|
*/
|
||||||
|
export async function listEventPhotos(
|
||||||
|
eventId: string,
|
||||||
|
): Promise<EventPhotoRow[]> {
|
||||||
|
return db
|
||||||
|
.select({
|
||||||
|
id: eventPhotos.id,
|
||||||
|
folderId: eventPhotos.folderId,
|
||||||
|
uploaderId: eventPhotos.uploaderId,
|
||||||
|
uploaderName: userName,
|
||||||
|
filename: eventPhotos.filename,
|
||||||
|
mimeType: eventPhotos.mimeType,
|
||||||
|
sizeBytes: eventPhotos.sizeBytes,
|
||||||
|
storedName: eventPhotos.storedName,
|
||||||
|
checksumSha256: eventPhotos.checksumSha256,
|
||||||
|
kind: eventPhotos.kind,
|
||||||
|
editJson: eventPhotos.editJson,
|
||||||
|
advancedEditJson: eventPhotos.advancedEditJson,
|
||||||
|
editedStoredName: eventPhotos.editedStoredName,
|
||||||
|
editedSizeBytes: eventPhotos.editedSizeBytes,
|
||||||
|
editedAt: eventPhotos.editedAt,
|
||||||
|
editedBy: eventPhotos.editedBy,
|
||||||
|
createdAt: eventPhotos.createdAt,
|
||||||
|
})
|
||||||
|
.from(eventPhotos)
|
||||||
|
.innerJoin(eventFolders, eq(eventFolders.id, eventPhotos.folderId))
|
||||||
|
.innerJoin(users, eq(users.id, eventPhotos.uploaderId))
|
||||||
|
.where(eq(eventFolders.eventId, eventId))
|
||||||
|
.orderBy(asc(eventPhotos.createdAt));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The folder new uploads land in. Events no longer expose folders, so this is
|
||||||
|
* the oldest existing folder (events created before the flattening keep theirs)
|
||||||
|
* or a single implicit "Photos" folder on the first upload. Two simultaneous
|
||||||
|
* first uploads race on the unique (event, name) index; the loser reads the
|
||||||
|
* winner's row.
|
||||||
|
*/
|
||||||
|
export async function ensureEventFolder(
|
||||||
|
eventId: string,
|
||||||
|
createdBy: string,
|
||||||
|
): Promise<EventFolderRow> {
|
||||||
|
const existing = await firstFolderFor(eventId);
|
||||||
|
if (existing) return existing;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const row = await createEventFolder({
|
||||||
|
eventId,
|
||||||
|
name: "Photos",
|
||||||
|
kind: "mixed",
|
||||||
|
createdBy,
|
||||||
|
});
|
||||||
|
return {
|
||||||
|
id: row.id,
|
||||||
|
name: row.name,
|
||||||
|
kind: row.kind,
|
||||||
|
createdAt: row.createdAt,
|
||||||
|
photoCount: 0,
|
||||||
|
totalBytes: 0,
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
if (isUniqueViolation(error)) {
|
||||||
|
const raced = await firstFolderFor(eventId);
|
||||||
|
if (raced) return raced;
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function firstFolderFor(eventId: string): Promise<EventFolderRow | null> {
|
||||||
|
const [row] = await db
|
||||||
|
.select({
|
||||||
|
folderId: eventFolders.id,
|
||||||
|
name: eventFolders.name,
|
||||||
|
kind: eventFolders.kind,
|
||||||
|
createdAt: eventFolders.createdAt,
|
||||||
|
photoCount: sql<number>`count(${eventPhotos.id})`,
|
||||||
|
totalBytes: sql<number>`coalesce(sum(${eventPhotos.sizeBytes}), 0)`,
|
||||||
|
})
|
||||||
|
.from(eventFolders)
|
||||||
|
.leftJoin(eventPhotos, eq(eventPhotos.folderId, eventFolders.id))
|
||||||
|
.where(eq(eventFolders.eventId, eventId))
|
||||||
|
.groupBy(eventFolders.id)
|
||||||
|
.orderBy(asc(eventFolders.createdAt))
|
||||||
|
.limit(1);
|
||||||
|
if (!row) return null;
|
||||||
|
return {
|
||||||
|
id: row.folderId,
|
||||||
|
name: row.name,
|
||||||
|
kind: row.kind,
|
||||||
|
createdAt: row.createdAt,
|
||||||
|
photoCount: numeric(row.photoCount),
|
||||||
|
totalBytes: numeric(row.totalBytes),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Every photo in an event with its folder name, for the whole-event ZIP. The
|
* Every photo in an event with its folder name, for the whole-event ZIP. The
|
||||||
* caller must check event access first; this query intentionally does not.
|
* caller must check event access first; this query intentionally does not.
|
||||||
@@ -672,11 +774,16 @@ export async function updateEventPhotoEdit(input: {
|
|||||||
editedStoredName: string;
|
editedStoredName: string;
|
||||||
editedSizeBytes: number;
|
editedSizeBytes: number;
|
||||||
editedBy: string;
|
editedBy: string;
|
||||||
|
/** True when the quick editor takes the look over from the advanced render. */
|
||||||
|
clearAdvancedEdit?: boolean;
|
||||||
}) {
|
}) {
|
||||||
const [row] = await db
|
const [row] = await db
|
||||||
.update(eventPhotos)
|
.update(eventPhotos)
|
||||||
.set({
|
.set({
|
||||||
|
// The simple recipe is applied on top of any advanced render, so the
|
||||||
|
// advanced recipe is kept and both editors stay in sync.
|
||||||
editJson: input.editJson,
|
editJson: input.editJson,
|
||||||
|
...(input.clearAdvancedEdit ? { advancedEditJson: null } : {}),
|
||||||
editedStoredName: input.editedStoredName,
|
editedStoredName: input.editedStoredName,
|
||||||
editedSizeBytes: input.editedSizeBytes,
|
editedSizeBytes: input.editedSizeBytes,
|
||||||
editedAt: new Date(),
|
editedAt: new Date(),
|
||||||
|
|||||||
+2
-2
@@ -37,7 +37,7 @@ export async function scheduleExportRows(
|
|||||||
return db
|
return db
|
||||||
.select({
|
.select({
|
||||||
occursOn: serviceInstances.occursOn,
|
occursOn: serviceInstances.occursOn,
|
||||||
serviceName: services.name,
|
serviceName: sql<string>`coalesce(${serviceInstances.titleOverride}, ${services.name})`,
|
||||||
startsAt: serviceInstances.startsAt,
|
startsAt: serviceInstances.startsAt,
|
||||||
callTime: slots.callTime,
|
callTime: slots.callTime,
|
||||||
roleName: roles.name,
|
roleName: roles.name,
|
||||||
@@ -103,7 +103,7 @@ export async function servingHistoryCsv(userId?: string): Promise<string> {
|
|||||||
const rows = await db
|
const rows = await db
|
||||||
.select({
|
.select({
|
||||||
occursOn: serviceInstances.occursOn,
|
occursOn: serviceInstances.occursOn,
|
||||||
serviceName: services.name,
|
serviceName: sql<string>`coalesce(${serviceInstances.titleOverride}, ${services.name})`,
|
||||||
roleName: roles.name,
|
roleName: roles.name,
|
||||||
userName: sql<string>`coalesce(${users.displayName}, ${users.firstName} || ' ' || ${users.lastName})`,
|
userName: sql<string>`coalesce(${users.displayName}, ${users.firstName} || ' ' || ${users.lastName})`,
|
||||||
email: users.email,
|
email: users.email,
|
||||||
|
|||||||
+1
-1
@@ -162,7 +162,7 @@ export async function gridForWeek(weekStart: string): Promise<GridWeek> {
|
|||||||
instance = {
|
instance = {
|
||||||
id: row.instanceId,
|
id: row.instanceId,
|
||||||
serviceId: row.serviceId,
|
serviceId: row.serviceId,
|
||||||
serviceName: row.serviceName,
|
serviceName: row.titleOverride ?? row.serviceName,
|
||||||
occursOn: occursOnISO(row.occursOn),
|
occursOn: occursOnISO(row.occursOn),
|
||||||
startsAt: row.startsAt ?? new Date(0),
|
startsAt: row.startsAt ?? new Date(0),
|
||||||
titleOverride: row.titleOverride ?? null,
|
titleOverride: row.titleOverride ?? null,
|
||||||
|
|||||||
+20
-4
@@ -11,13 +11,17 @@
|
|||||||
* - a `published` instance is never modified here,
|
* - a `published` instance is never modified here,
|
||||||
* - past instances fall outside the window and are never deleted.
|
* - past instances fall outside the window and are never deleted.
|
||||||
*
|
*
|
||||||
* Slot materialization from role requirements is D3; this unit only owns the
|
* Each new instance's seats are materialized immediately via D3's
|
||||||
* instance rows.
|
* `materializeSlotsForInstance`, so a generated week is assignable without
|
||||||
|
* waiting for the separate slot cron. Seat creation is idempotent per
|
||||||
|
* (instance, role, seat), so re-runs remain no-ops.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { and, count, eq, gte } from "drizzle-orm";
|
import { and, count, eq, gte } from "drizzle-orm";
|
||||||
import { db } from "@/db";
|
import { db } from "@/db";
|
||||||
import { services, serviceInstances } from "@/db/schema";
|
import { roles, services, serviceInstances } from "@/db/schema";
|
||||||
|
import { materializeSlotsForInstance } from "@/db/slots";
|
||||||
|
import type { RolePlanInput } from "@/domain/slots";
|
||||||
import { uuidv7 } from "@/lib/uuid";
|
import { uuidv7 } from "@/lib/uuid";
|
||||||
import { localToUtc } from "@/lib/tz";
|
import { localToUtc } from "@/lib/tz";
|
||||||
import {
|
import {
|
||||||
@@ -52,6 +56,13 @@ export async function generateInstances(opts: GenerateOptions = {}): Promise<Gen
|
|||||||
|
|
||||||
const active = await db.select().from(services).where(eq(services.active, true));
|
const active = await db.select().from(services).where(eq(services.active, true));
|
||||||
|
|
||||||
|
const roleRows = await db.select().from(roles).orderBy(roles.sortOrder);
|
||||||
|
const rolesInput: RolePlanInput[] = roleRows.map((role) => ({
|
||||||
|
id: role.id,
|
||||||
|
callTimeOffsetMinutes: role.callTimeOffsetMinutes,
|
||||||
|
defaultHeadcount: role.defaultHeadcount,
|
||||||
|
}));
|
||||||
|
|
||||||
let created = 0;
|
let created = 0;
|
||||||
for (const service of active) {
|
for (const service of active) {
|
||||||
const plan: ServicePlanInput = {
|
const plan: ServicePlanInput = {
|
||||||
@@ -78,7 +89,12 @@ export async function generateInstances(opts: GenerateOptions = {}): Promise<Gen
|
|||||||
target: [serviceInstances.serviceId, serviceInstances.startsAt],
|
target: [serviceInstances.serviceId, serviceInstances.startsAt],
|
||||||
})
|
})
|
||||||
.returning();
|
.returning();
|
||||||
if (row) created++;
|
if (row) {
|
||||||
|
created++;
|
||||||
|
if (row.startsAt) {
|
||||||
|
await materializeSlotsForInstance(row.id, row.startsAt, rolesInput);
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+177
-52
@@ -24,7 +24,10 @@ import {
|
|||||||
} from "@/db/schema";
|
} from "@/db/schema";
|
||||||
import { APP_ORIGIN } from "@/auth/magic-link";
|
import { APP_ORIGIN } from "@/auth/magic-link";
|
||||||
import { notificationDedupeKey } from "@/domain/notifications";
|
import { notificationDedupeKey } from "@/domain/notifications";
|
||||||
import { renderAssignmentPublishedEmail } from "@/domain/templates";
|
import {
|
||||||
|
renderAssignmentProposedEmail,
|
||||||
|
renderAssignmentPublishedEmail,
|
||||||
|
} from "@/domain/templates";
|
||||||
import { respondUrl, signRespondToken } from "@/lib/respond";
|
import { respondUrl, signRespondToken } from "@/lib/respond";
|
||||||
import { formatInTimezone } from "@/lib/tz";
|
import { formatInTimezone } from "@/lib/tz";
|
||||||
import { uuidv7 } from "@/lib/uuid";
|
import { uuidv7 } from "@/lib/uuid";
|
||||||
@@ -63,7 +66,7 @@ export async function enqueuePublishNotifications(
|
|||||||
displayName: users.displayName,
|
displayName: users.displayName,
|
||||||
timeZone: users.timezone,
|
timeZone: users.timezone,
|
||||||
roleName: roles.name,
|
roleName: roles.name,
|
||||||
serviceName: services.name,
|
serviceName: sql<string>`coalesce(${serviceInstances.titleOverride}, ${services.name})`,
|
||||||
location: services.location,
|
location: services.location,
|
||||||
startsAt: serviceInstances.startsAt,
|
startsAt: serviceInstances.startsAt,
|
||||||
callTime: slots.callTime,
|
callTime: slots.callTime,
|
||||||
@@ -85,51 +88,7 @@ export async function enqueuePublishNotifications(
|
|||||||
let enqueued = 0;
|
let enqueued = 0;
|
||||||
for (const row of rows) {
|
for (const row of rows) {
|
||||||
if (!row.startsAt) continue;
|
if (!row.startsAt) continue;
|
||||||
const timeZone = row.timeZone;
|
const email = await buildAssignmentEmail(row, origin, false);
|
||||||
const occursOnLabel = formatInTimezone(row.startsAt, timeZone, {
|
|
||||||
timeZone,
|
|
||||||
weekday: "long",
|
|
||||||
month: "short",
|
|
||||||
day: "numeric",
|
|
||||||
});
|
|
||||||
const startTimeLabel = formatInTimezone(row.startsAt, timeZone, {
|
|
||||||
timeZone,
|
|
||||||
hour: "numeric",
|
|
||||||
minute: "2-digit",
|
|
||||||
});
|
|
||||||
const callTimeLabel = row.callTime
|
|
||||||
? formatInTimezone(row.callTime, timeZone, {
|
|
||||||
timeZone,
|
|
||||||
hour: "numeric",
|
|
||||||
minute: "2-digit",
|
|
||||||
})
|
|
||||||
: null;
|
|
||||||
|
|
||||||
// Two single-purpose links per assignment (E4): confirm and decline.
|
|
||||||
const confirm = await signRespondToken({
|
|
||||||
assignmentId: row.assignmentId,
|
|
||||||
userId: row.userId,
|
|
||||||
action: "confirm",
|
|
||||||
});
|
|
||||||
const decline = await signRespondToken({
|
|
||||||
assignmentId: row.assignmentId,
|
|
||||||
userId: row.userId,
|
|
||||||
action: "decline",
|
|
||||||
});
|
|
||||||
const confirmUrl = respondUrl(origin, confirm.token, "confirm");
|
|
||||||
const declineUrl = respondUrl(origin, decline.token, "decline");
|
|
||||||
|
|
||||||
const rendered = renderAssignmentPublishedEmail({
|
|
||||||
volunteerFirstName: row.firstName,
|
|
||||||
roleName: row.roleName,
|
|
||||||
serviceName: row.serviceName,
|
|
||||||
occursOnLabel,
|
|
||||||
startTimeLabel,
|
|
||||||
callTimeLabel,
|
|
||||||
location: row.location ?? row.serviceName,
|
|
||||||
confirmUrl,
|
|
||||||
declineUrl,
|
|
||||||
});
|
|
||||||
|
|
||||||
const inserted = await executor
|
const inserted = await executor
|
||||||
.insert(notifications)
|
.insert(notifications)
|
||||||
@@ -143,11 +102,12 @@ export async function enqueuePublishNotifications(
|
|||||||
slotId: row.slotId,
|
slotId: row.slotId,
|
||||||
toAddress: row.email,
|
toAddress: row.email,
|
||||||
payloadJson: JSON.stringify({
|
payloadJson: JSON.stringify({
|
||||||
subject: rendered.subject,
|
subject: email.subject,
|
||||||
html: rendered.html,
|
html: email.html,
|
||||||
text: rendered.text,
|
text: email.text,
|
||||||
confirmUrl,
|
confirmUrl: email.confirmUrl,
|
||||||
declineUrl,
|
declineUrl: email.declineUrl,
|
||||||
|
alternativeUrl: email.alternativeUrl,
|
||||||
}),
|
}),
|
||||||
dedupeKey: notificationDedupeKey(
|
dedupeKey: notificationDedupeKey(
|
||||||
"assignment.published",
|
"assignment.published",
|
||||||
@@ -168,6 +128,171 @@ export async function enqueuePublishNotifications(
|
|||||||
return enqueued;
|
return enqueued;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/** The assignment fields every assignment email renders from. */
|
||||||
|
interface AssignmentEmailRow {
|
||||||
|
assignmentId: string;
|
||||||
|
slotId: string;
|
||||||
|
userId: string;
|
||||||
|
email: string;
|
||||||
|
firstName: string;
|
||||||
|
timeZone: string;
|
||||||
|
roleName: string;
|
||||||
|
serviceName: string;
|
||||||
|
location: string | null;
|
||||||
|
startsAt: Date | null;
|
||||||
|
callTime: Date | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Render an assignment email and mint its single-purpose links. */
|
||||||
|
async function buildAssignmentEmail(
|
||||||
|
row: AssignmentEmailRow,
|
||||||
|
origin: string,
|
||||||
|
includeAlternative: boolean,
|
||||||
|
): Promise<{
|
||||||
|
subject: string;
|
||||||
|
html: string;
|
||||||
|
text: string;
|
||||||
|
confirmUrl: string;
|
||||||
|
declineUrl: string;
|
||||||
|
alternativeUrl: string | null;
|
||||||
|
}> {
|
||||||
|
if (!row.startsAt) throw new Error("assignment has no start time");
|
||||||
|
const timeZone = row.timeZone;
|
||||||
|
const occursOnLabel = formatInTimezone(row.startsAt, timeZone, {
|
||||||
|
timeZone,
|
||||||
|
weekday: "long",
|
||||||
|
month: "short",
|
||||||
|
day: "numeric",
|
||||||
|
});
|
||||||
|
const startTimeLabel = formatInTimezone(row.startsAt, timeZone, {
|
||||||
|
timeZone,
|
||||||
|
hour: "numeric",
|
||||||
|
minute: "2-digit",
|
||||||
|
});
|
||||||
|
const callTimeLabel = row.callTime
|
||||||
|
? formatInTimezone(row.callTime, timeZone, {
|
||||||
|
timeZone,
|
||||||
|
hour: "numeric",
|
||||||
|
minute: "2-digit",
|
||||||
|
})
|
||||||
|
: null;
|
||||||
|
|
||||||
|
const confirm = await signRespondToken({
|
||||||
|
assignmentId: row.assignmentId,
|
||||||
|
userId: row.userId,
|
||||||
|
action: "confirm",
|
||||||
|
});
|
||||||
|
const decline = await signRespondToken({
|
||||||
|
assignmentId: row.assignmentId,
|
||||||
|
userId: row.userId,
|
||||||
|
action: "decline",
|
||||||
|
});
|
||||||
|
const alternative = includeAlternative
|
||||||
|
? await signRespondToken({
|
||||||
|
assignmentId: row.assignmentId,
|
||||||
|
userId: row.userId,
|
||||||
|
action: "alternative",
|
||||||
|
})
|
||||||
|
: null;
|
||||||
|
|
||||||
|
const confirmUrl = respondUrl(origin, confirm.token, "confirm");
|
||||||
|
const declineUrl = respondUrl(origin, decline.token, "decline");
|
||||||
|
const alternativeUrl = alternative
|
||||||
|
? respondUrl(origin, alternative.token, "alternative")
|
||||||
|
: null;
|
||||||
|
|
||||||
|
const ctx = {
|
||||||
|
volunteerFirstName: row.firstName,
|
||||||
|
roleName: row.roleName,
|
||||||
|
serviceName: row.serviceName,
|
||||||
|
occursOnLabel,
|
||||||
|
startTimeLabel,
|
||||||
|
callTimeLabel,
|
||||||
|
location: row.location ?? row.serviceName,
|
||||||
|
confirmUrl,
|
||||||
|
declineUrl,
|
||||||
|
};
|
||||||
|
const rendered = alternativeUrl
|
||||||
|
? renderAssignmentProposedEmail({ ...ctx, alternativeUrl })
|
||||||
|
: renderAssignmentPublishedEmail(ctx);
|
||||||
|
|
||||||
|
return { ...rendered, confirmUrl, declineUrl, alternativeUrl };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Enqueue the `assignment.proposed` email for one new assignment. The seat is
|
||||||
|
* proposed, not confirmed, so the volunteer is asked to accept, decline, or
|
||||||
|
* propose another Sunday. Draft and published weeks both get this email: a
|
||||||
|
* proposed seat always needs a response. Idempotent per assignment.
|
||||||
|
*/
|
||||||
|
export async function enqueueAssignmentProposed(
|
||||||
|
executor: OutboxDb,
|
||||||
|
assignmentId: string,
|
||||||
|
opts: { now?: Date; appOrigin?: string } = {},
|
||||||
|
): Promise<number> {
|
||||||
|
const now = opts.now ?? new Date();
|
||||||
|
const origin = opts.appOrigin ?? APP_ORIGIN;
|
||||||
|
|
||||||
|
const [row] = await executor
|
||||||
|
.select({
|
||||||
|
assignmentId: assignments.id,
|
||||||
|
slotId: assignments.slotId,
|
||||||
|
userId: users.id,
|
||||||
|
email: users.email,
|
||||||
|
firstName: users.firstName,
|
||||||
|
timeZone: users.timezone,
|
||||||
|
roleName: roles.name,
|
||||||
|
serviceName: sql<string>`coalesce(${serviceInstances.titleOverride}, ${services.name})`,
|
||||||
|
location: services.location,
|
||||||
|
startsAt: serviceInstances.startsAt,
|
||||||
|
callTime: slots.callTime,
|
||||||
|
})
|
||||||
|
.from(assignments)
|
||||||
|
.innerJoin(slots, eq(slots.id, assignments.slotId))
|
||||||
|
.innerJoin(roles, eq(roles.id, slots.roleId))
|
||||||
|
.innerJoin(serviceInstances, eq(serviceInstances.id, slots.serviceInstanceId))
|
||||||
|
.innerJoin(services, eq(services.id, serviceInstances.serviceId))
|
||||||
|
.innerJoin(users, eq(users.id, assignments.userId))
|
||||||
|
.where(eq(assignments.id, assignmentId))
|
||||||
|
.limit(1);
|
||||||
|
if (!row?.startsAt) return 0;
|
||||||
|
|
||||||
|
const email = await buildAssignmentEmail(row, origin, true);
|
||||||
|
const inserted = await executor
|
||||||
|
.insert(notifications)
|
||||||
|
.values({
|
||||||
|
id: uuidv7(),
|
||||||
|
userId: row.userId,
|
||||||
|
channel: "email",
|
||||||
|
templateKey: "assignment.proposed",
|
||||||
|
ruleKey: null,
|
||||||
|
assignmentId: row.assignmentId,
|
||||||
|
slotId: row.slotId,
|
||||||
|
toAddress: row.email,
|
||||||
|
payloadJson: JSON.stringify({
|
||||||
|
subject: email.subject,
|
||||||
|
html: email.html,
|
||||||
|
text: email.text,
|
||||||
|
confirmUrl: email.confirmUrl,
|
||||||
|
declineUrl: email.declineUrl,
|
||||||
|
alternativeUrl: email.alternativeUrl,
|
||||||
|
}),
|
||||||
|
dedupeKey: notificationDedupeKey(
|
||||||
|
"assignment.proposed",
|
||||||
|
row.assignmentId,
|
||||||
|
"email",
|
||||||
|
),
|
||||||
|
scheduledFor: now,
|
||||||
|
status: "queued",
|
||||||
|
attempts: 0,
|
||||||
|
createdAt: now,
|
||||||
|
})
|
||||||
|
.onConflictDoNothing({ target: notifications.dedupeKey })
|
||||||
|
.returning({ id: notifications.id });
|
||||||
|
|
||||||
|
return inserted.length;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Cancel an assignment's pending mail — a declined assignment must not keep a
|
* Cancel an assignment's pending mail — a declined assignment must not keep a
|
||||||
* "you're serving" reminder queued (§6.1 `cancel-if-declined`). Sent rows are
|
* "you're serving" reminder queued (§6.1 `cancel-if-declined`). Sent rows are
|
||||||
|
|||||||
@@ -73,7 +73,7 @@ export async function rankedCandidatesForSlot(
|
|||||||
roleName: roles.name,
|
roleName: roles.name,
|
||||||
isTraineeSlot: slots.isTraineeSlot,
|
isTraineeSlot: slots.isTraineeSlot,
|
||||||
serviceInstanceId: slots.serviceInstanceId,
|
serviceInstanceId: slots.serviceInstanceId,
|
||||||
serviceName: services.name,
|
serviceName: sql<string>`coalesce(${serviceInstances.titleOverride}, ${services.name})`,
|
||||||
location: services.location,
|
location: services.location,
|
||||||
startsAt: serviceInstances.startsAt,
|
startsAt: serviceInstances.startsAt,
|
||||||
occursOn: serviceInstances.occursOn,
|
occursOn: serviceInstances.occursOn,
|
||||||
|
|||||||
+2
-2
@@ -10,7 +10,7 @@
|
|||||||
* so republishing or a retry cannot double-book a reminder.
|
* so republishing or a retry cannot double-book a reminder.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { and, eq, inArray } from "drizzle-orm";
|
import { and, eq, inArray, sql } from "drizzle-orm";
|
||||||
import { db } from "@/db";
|
import { db } from "@/db";
|
||||||
import {
|
import {
|
||||||
assignments,
|
assignments,
|
||||||
@@ -158,7 +158,7 @@ export async function enqueueRemindersForInstance(
|
|||||||
firstName: users.firstName,
|
firstName: users.firstName,
|
||||||
timeZone: users.timezone,
|
timeZone: users.timezone,
|
||||||
roleName: roles.name,
|
roleName: roles.name,
|
||||||
serviceName: services.name,
|
serviceName: sql<string>`coalesce(${serviceInstances.titleOverride}, ${services.name})`,
|
||||||
location: services.location,
|
location: services.location,
|
||||||
callTime: slots.callTime,
|
callTime: slots.callTime,
|
||||||
})
|
})
|
||||||
|
|||||||
+203
-6
@@ -8,10 +8,11 @@
|
|||||||
* and writes the audit row — all in one transaction.
|
* and writes the audit row — all in one transaction.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { eq } from "drizzle-orm";
|
import { and, asc, eq, gt, ne, sql } from "drizzle-orm";
|
||||||
import { db } from "@/db";
|
import { db } from "@/db";
|
||||||
import {
|
import {
|
||||||
assignments,
|
assignments,
|
||||||
|
assignmentProposals,
|
||||||
auditLog,
|
auditLog,
|
||||||
roles,
|
roles,
|
||||||
serviceInstances,
|
serviceInstances,
|
||||||
@@ -23,8 +24,9 @@ import {
|
|||||||
} from "@/db/schema";
|
} from "@/db/schema";
|
||||||
import { auditRow } from "@/db/audit";
|
import { auditRow } from "@/db/audit";
|
||||||
import { cancelAssignmentNotifications } from "@/db/outbox";
|
import { cancelAssignmentNotifications } from "@/db/outbox";
|
||||||
import type { RespondAction } from "@/lib/respond";
|
import type { DecisionAction } from "@/lib/respond";
|
||||||
import { formatInTimezone } from "@/lib/tz";
|
import { formatInTimezone } from "@/lib/tz";
|
||||||
|
import { uuidv7 } from "@/lib/uuid";
|
||||||
|
|
||||||
/** Only a live assignment can be confirmed or declined. */
|
/** Only a live assignment can be confirmed or declined. */
|
||||||
const ACTIONABLE_STATUSES = new Set(["proposed", "confirmed"]);
|
const ACTIONABLE_STATUSES = new Set(["proposed", "confirmed"]);
|
||||||
@@ -33,7 +35,9 @@ export type RespondFailureCode =
|
|||||||
| "unknown_assignment"
|
| "unknown_assignment"
|
||||||
| "wrong_volunteer"
|
| "wrong_volunteer"
|
||||||
| "not_actionable"
|
| "not_actionable"
|
||||||
| "already_used";
|
| "already_used"
|
||||||
|
| "unknown_instance"
|
||||||
|
| "invalid_alternative";
|
||||||
|
|
||||||
export class RespondError extends Error {
|
export class RespondError extends Error {
|
||||||
readonly code: RespondFailureCode;
|
readonly code: RespondFailureCode;
|
||||||
@@ -69,7 +73,7 @@ export async function getRespondAssignment(
|
|||||||
displayName: users.displayName,
|
displayName: users.displayName,
|
||||||
timeZone: users.timezone,
|
timeZone: users.timezone,
|
||||||
roleName: roles.name,
|
roleName: roles.name,
|
||||||
serviceName: services.name,
|
serviceName: sql<string>`coalesce(${serviceInstances.titleOverride}, ${services.name})`,
|
||||||
location: services.location,
|
location: services.location,
|
||||||
startsAt: serviceInstances.startsAt,
|
startsAt: serviceInstances.startsAt,
|
||||||
callTime: slots.callTime,
|
callTime: slots.callTime,
|
||||||
@@ -124,7 +128,7 @@ export async function getRespondAssignment(
|
|||||||
export async function respondToAssignment(input: {
|
export async function respondToAssignment(input: {
|
||||||
assignmentId: string;
|
assignmentId: string;
|
||||||
userId: string;
|
userId: string;
|
||||||
action: RespondAction;
|
action: DecisionAction;
|
||||||
via?: ConfirmedVia;
|
via?: ConfirmedVia;
|
||||||
now?: Date;
|
now?: Date;
|
||||||
}): Promise<{ status: "confirmed" | "declined" }> {
|
}): Promise<{ status: "confirmed" | "declined" }> {
|
||||||
@@ -209,7 +213,7 @@ export async function respondToAssignment(input: {
|
|||||||
export async function applyRespond(input: {
|
export async function applyRespond(input: {
|
||||||
assignmentId: string;
|
assignmentId: string;
|
||||||
userId: string;
|
userId: string;
|
||||||
action: RespondAction;
|
action: DecisionAction;
|
||||||
jti: string;
|
jti: string;
|
||||||
now?: Date;
|
now?: Date;
|
||||||
}): Promise<{ status: "confirmed" | "declined" }> {
|
}): Promise<{ status: "confirmed" | "declined" }> {
|
||||||
@@ -301,3 +305,196 @@ export async function applyRespond(input: {
|
|||||||
|
|
||||||
return result;
|
return result;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface AlternativeOption {
|
||||||
|
id: string;
|
||||||
|
startsAt: Date;
|
||||||
|
label: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Upcoming instances of the same service after the seat's own date — the
|
||||||
|
* choices behind "propose another Sunday". Null when the assignment or its
|
||||||
|
* start time is unknown.
|
||||||
|
*/
|
||||||
|
export async function alternativeOptionsForAssignment(
|
||||||
|
assignmentId: string,
|
||||||
|
): Promise<AlternativeOption[] | null> {
|
||||||
|
const [current] = await db
|
||||||
|
.select({
|
||||||
|
instanceId: serviceInstances.id,
|
||||||
|
serviceId: serviceInstances.serviceId,
|
||||||
|
startsAt: serviceInstances.startsAt,
|
||||||
|
timeZone: users.timezone,
|
||||||
|
})
|
||||||
|
.from(assignments)
|
||||||
|
.innerJoin(slots, eq(slots.id, assignments.slotId))
|
||||||
|
.innerJoin(serviceInstances, eq(serviceInstances.id, slots.serviceInstanceId))
|
||||||
|
.innerJoin(users, eq(users.id, assignments.userId))
|
||||||
|
.where(eq(assignments.id, assignmentId))
|
||||||
|
.limit(1);
|
||||||
|
if (!current?.startsAt) return null;
|
||||||
|
|
||||||
|
const rows = await db
|
||||||
|
.select({ id: serviceInstances.id, startsAt: serviceInstances.startsAt })
|
||||||
|
.from(serviceInstances)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(serviceInstances.serviceId, current.serviceId),
|
||||||
|
gt(serviceInstances.startsAt, current.startsAt),
|
||||||
|
ne(serviceInstances.id, current.instanceId),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.orderBy(asc(serviceInstances.startsAt))
|
||||||
|
.limit(24);
|
||||||
|
|
||||||
|
return rows
|
||||||
|
.filter(
|
||||||
|
(row): row is { id: string; startsAt: Date } => row.startsAt != null,
|
||||||
|
)
|
||||||
|
.map((row) => ({
|
||||||
|
id: row.id,
|
||||||
|
startsAt: row.startsAt,
|
||||||
|
label: formatInTimezone(row.startsAt, current.timeZone, {
|
||||||
|
timeZone: current.timeZone,
|
||||||
|
weekday: "long",
|
||||||
|
month: "short",
|
||||||
|
day: "numeric",
|
||||||
|
hour: "numeric",
|
||||||
|
minute: "2-digit",
|
||||||
|
}),
|
||||||
|
}));
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Record "I can't serve that Sunday, but I can serve this one." The assignment
|
||||||
|
* is left live (like a coverage request) until a coordinator acts; the token is
|
||||||
|
* consumed exactly once in the same transaction as the proposal.
|
||||||
|
*/
|
||||||
|
export async function applyAlternativeProposal(input: {
|
||||||
|
assignmentId: string;
|
||||||
|
userId: string;
|
||||||
|
jti: string;
|
||||||
|
proposedInstanceId: string;
|
||||||
|
note?: string | null;
|
||||||
|
now?: Date;
|
||||||
|
}): Promise<{ proposalId: string; proposedInstanceId: string }> {
|
||||||
|
const now = input.now ?? new Date();
|
||||||
|
const proposalId = uuidv7();
|
||||||
|
|
||||||
|
return db.transaction(async (tx) => {
|
||||||
|
const consumed = await tx
|
||||||
|
.insert(usedTokens)
|
||||||
|
.values({
|
||||||
|
jti: input.jti,
|
||||||
|
assignmentId: input.assignmentId,
|
||||||
|
action: "alternative",
|
||||||
|
usedAt: now,
|
||||||
|
})
|
||||||
|
.onConflictDoNothing({ target: usedTokens.jti })
|
||||||
|
.returning({ jti: usedTokens.jti });
|
||||||
|
if (consumed.length === 0) {
|
||||||
|
throw new RespondError("already_used", "this link has already been used");
|
||||||
|
}
|
||||||
|
|
||||||
|
const [assignment] = await tx
|
||||||
|
.select({
|
||||||
|
userId: assignments.userId,
|
||||||
|
status: assignments.status,
|
||||||
|
instanceId: serviceInstances.id,
|
||||||
|
serviceId: serviceInstances.serviceId,
|
||||||
|
startsAt: serviceInstances.startsAt,
|
||||||
|
})
|
||||||
|
.from(assignments)
|
||||||
|
.innerJoin(slots, eq(slots.id, assignments.slotId))
|
||||||
|
.innerJoin(serviceInstances, eq(serviceInstances.id, slots.serviceInstanceId))
|
||||||
|
.where(eq(assignments.id, input.assignmentId))
|
||||||
|
.limit(1);
|
||||||
|
if (!assignment) {
|
||||||
|
throw new RespondError("unknown_assignment", "unknown assignment");
|
||||||
|
}
|
||||||
|
if (assignment.userId !== input.userId) {
|
||||||
|
throw new RespondError(
|
||||||
|
"wrong_volunteer",
|
||||||
|
"this link is not for this volunteer",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (!ACTIONABLE_STATUSES.has(assignment.status)) {
|
||||||
|
throw new RespondError(
|
||||||
|
"not_actionable",
|
||||||
|
`assignment is already ${assignment.status}`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const [proposed] = await tx
|
||||||
|
.select({
|
||||||
|
id: serviceInstances.id,
|
||||||
|
serviceId: serviceInstances.serviceId,
|
||||||
|
startsAt: serviceInstances.startsAt,
|
||||||
|
})
|
||||||
|
.from(serviceInstances)
|
||||||
|
.where(eq(serviceInstances.id, input.proposedInstanceId))
|
||||||
|
.limit(1);
|
||||||
|
if (!proposed) {
|
||||||
|
throw new RespondError("unknown_instance", "that service date was not found");
|
||||||
|
}
|
||||||
|
if (proposed.serviceId !== assignment.serviceId) {
|
||||||
|
throw new RespondError(
|
||||||
|
"invalid_alternative",
|
||||||
|
"choose another date for this service",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
!proposed.startsAt ||
|
||||||
|
!assignment.startsAt ||
|
||||||
|
proposed.id === assignment.instanceId ||
|
||||||
|
proposed.startsAt <= assignment.startsAt ||
|
||||||
|
proposed.startsAt <= now
|
||||||
|
) {
|
||||||
|
throw new RespondError("invalid_alternative", "choose a later service date");
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
await tx.insert(assignmentProposals).values({
|
||||||
|
id: proposalId,
|
||||||
|
assignmentId: input.assignmentId,
|
||||||
|
userId: input.userId,
|
||||||
|
proposedInstanceId: proposed.id,
|
||||||
|
note: input.note?.trim() || null,
|
||||||
|
status: "pending",
|
||||||
|
createdAt: now,
|
||||||
|
});
|
||||||
|
} catch (err) {
|
||||||
|
if (sqlState(err) === "23505") {
|
||||||
|
throw new RespondError(
|
||||||
|
"invalid_alternative",
|
||||||
|
"you already proposed another Sunday for this assignment",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
throw err;
|
||||||
|
}
|
||||||
|
|
||||||
|
await tx.insert(auditLog).values(
|
||||||
|
auditRow({
|
||||||
|
actorId: input.userId,
|
||||||
|
action: "assignment.alternative_proposed",
|
||||||
|
entityType: "assignment",
|
||||||
|
entityId: input.assignmentId,
|
||||||
|
after: { proposedInstanceId: proposed.id },
|
||||||
|
now,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
return { proposalId, proposedInstanceId: proposed.id };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Walk an error's cause chain to its SQLSTATE. */
|
||||||
|
function sqlState(err: unknown): string | undefined {
|
||||||
|
let node = err as { code?: string; cause?: unknown } | null;
|
||||||
|
while (node) {
|
||||||
|
if (node.code) return node.code;
|
||||||
|
node = (node.cause as { code?: string; cause?: unknown } | null) ?? null;
|
||||||
|
}
|
||||||
|
return undefined;
|
||||||
|
}
|
||||||
|
|||||||
+1
-1
@@ -154,7 +154,7 @@ export async function getRunSheet(
|
|||||||
const [instance] = await db
|
const [instance] = await db
|
||||||
.select({
|
.select({
|
||||||
id: serviceInstances.id,
|
id: serviceInstances.id,
|
||||||
serviceName: services.name,
|
serviceName: sql<string>`coalesce(${serviceInstances.titleOverride}, ${services.name})`,
|
||||||
location: services.location,
|
location: services.location,
|
||||||
startsAt: serviceInstances.startsAt,
|
startsAt: serviceInstances.startsAt,
|
||||||
endsAt: serviceInstances.endsAt,
|
endsAt: serviceInstances.endsAt,
|
||||||
|
|||||||
@@ -1249,6 +1249,53 @@ export const coverageRequests = pgTable(
|
|||||||
],
|
],
|
||||||
);
|
);
|
||||||
|
|
||||||
|
/* ------------------------------- assignment alternative-date proposals */
|
||||||
|
|
||||||
|
export const ASSIGNMENT_PROPOSAL_STATUSES = [
|
||||||
|
"pending",
|
||||||
|
"accepted",
|
||||||
|
"declined",
|
||||||
|
] as const;
|
||||||
|
export type AssignmentProposalStatus =
|
||||||
|
(typeof ASSIGNMENT_PROPOSAL_STATUSES)[number];
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A volunteer's answer to a proposed seat when they cannot serve that date but
|
||||||
|
* can serve another Sunday. The assignment stays live (like a coverage
|
||||||
|
* request) until a coordinator acts, so a proposal never silently opens a hole
|
||||||
|
* in the schedule.
|
||||||
|
*
|
||||||
|
* At most one pending proposal per assignment; resolved rows remain history.
|
||||||
|
*/
|
||||||
|
export const assignmentProposals = pgTable(
|
||||||
|
"assignment_proposals",
|
||||||
|
{
|
||||||
|
id: text("id").primaryKey(),
|
||||||
|
assignmentId: text("assignment_id")
|
||||||
|
.notNull()
|
||||||
|
.references(() => assignments.id, { onDelete: "cascade" }),
|
||||||
|
userId: text("user_id")
|
||||||
|
.notNull()
|
||||||
|
.references(() => users.id, { onDelete: "restrict" }),
|
||||||
|
proposedInstanceId: text("proposed_instance_id")
|
||||||
|
.notNull()
|
||||||
|
.references(() => serviceInstances.id, { onDelete: "cascade" }),
|
||||||
|
note: text("note"),
|
||||||
|
status: text("status", { enum: ASSIGNMENT_PROPOSAL_STATUSES })
|
||||||
|
.notNull()
|
||||||
|
.default("pending"),
|
||||||
|
createdAt: timestamp("created_at", { mode: "date", withTimezone: true })
|
||||||
|
.notNull()
|
||||||
|
.defaultNow(),
|
||||||
|
},
|
||||||
|
(table) => [
|
||||||
|
uniqueIndex("assignment_proposals_pending_assignment_idx")
|
||||||
|
.on(table.assignmentId)
|
||||||
|
.where(sql`${table.status} = 'pending'`),
|
||||||
|
index("assignment_proposals_status_idx").on(table.status, table.createdAt),
|
||||||
|
],
|
||||||
|
);
|
||||||
|
|
||||||
/* ------------------------------------------------------------ run sheet */
|
/* ------------------------------------------------------------ run sheet */
|
||||||
|
|
||||||
/**
|
/**
|
||||||
@@ -1488,6 +1535,7 @@ export const schema = {
|
|||||||
eventVideos,
|
eventVideos,
|
||||||
announcements,
|
announcements,
|
||||||
coverageRequests,
|
coverageRequests,
|
||||||
|
assignmentProposals,
|
||||||
serviceRunSheets,
|
serviceRunSheets,
|
||||||
runSheetItems,
|
runSheetItems,
|
||||||
serviceChecklistItems,
|
serviceChecklistItems,
|
||||||
|
|||||||
+34
-6
@@ -1,10 +1,15 @@
|
|||||||
/**
|
/**
|
||||||
* Seed script for Media Team Hub (Phase A2).
|
* Seed script for Media Team Hub (Phase A2).
|
||||||
*
|
*
|
||||||
* Idempotent: every insert uses ON CONFLICT DO NOTHING, so it is safe to run
|
* Populates the core scheduling tables with a small, browsable dataset — 3
|
||||||
* repeatedly. Populates the core scheduling tables with a small, browsable
|
* roles, 2 services, the next 2 Sundays of instances, their slots, and a few
|
||||||
* dataset — 3 roles, 2 services, the next 2 Sundays of instances, their slots,
|
* volunteers assigned to slots.
|
||||||
* and a few volunteers assigned to slots.
|
*
|
||||||
|
* NOT safe on a populated database: step 6 deletes every assignment before
|
||||||
|
* inserting the demo ones, and the demo services collide with real Sunday
|
||||||
|
* templates. It therefore refuses to run when non-seed users already exist
|
||||||
|
* unless SEED_FORCE=1 is set. The dev reset route truncates first, so it is
|
||||||
|
* unaffected.
|
||||||
*
|
*
|
||||||
* Run: pnpm db:seed (DATABASE_URL must point at the target DB)
|
* Run: pnpm db:seed (DATABASE_URL must point at the target DB)
|
||||||
*/
|
*/
|
||||||
@@ -31,6 +36,16 @@ import { localToUtc, nextSundaysInTz } from "../lib/tz";
|
|||||||
|
|
||||||
const CHURCH_TZ = "America/New_York";
|
const CHURCH_TZ = "America/New_York";
|
||||||
|
|
||||||
|
/** Accounts this script owns; anything else means the DB has real data. */
|
||||||
|
const SEED_EMAILS = new Set([
|
||||||
|
"admin@glenloch.local",
|
||||||
|
"coordinator@glenloch.local",
|
||||||
|
"jordan@glenloch.local",
|
||||||
|
"avery@glenloch.local",
|
||||||
|
"sam@glenloch.local",
|
||||||
|
"riley@glenloch.local",
|
||||||
|
]);
|
||||||
|
|
||||||
// Tables the seed owns. Truncating these (and cascading) gives a clean slate
|
// Tables the seed owns. Truncating these (and cascading) gives a clean slate
|
||||||
// for E2E resets without touching schema/migration tables.
|
// for E2E resets without touching schema/migration tables.
|
||||||
const RESET_TABLES = [
|
const RESET_TABLES = [
|
||||||
@@ -60,6 +75,16 @@ const RESET_TABLES = [
|
|||||||
|
|
||||||
/** Populate the core scheduling tables (idempotent: ON CONFLICT DO NOTHING). */
|
/** Populate the core scheduling tables (idempotent: ON CONFLICT DO NOTHING). */
|
||||||
export async function seed() {
|
export async function seed() {
|
||||||
|
const existingUsers = await db.select({ email: users.email }).from(users);
|
||||||
|
const foreignUsers = existingUsers.filter((u) => !SEED_EMAILS.has(u.email));
|
||||||
|
if (foreignUsers.length > 0 && process.env.SEED_FORCE !== "1") {
|
||||||
|
throw new Error(
|
||||||
|
`seed: refusing to run on a database with ${foreignUsers.length} non-seed user(s) ` +
|
||||||
|
`(${foreignUsers.map((u) => u.email).join(", ")}). ` +
|
||||||
|
"This script rewrites demo services and assignments; set SEED_FORCE=1 only on a throwaway database.",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/* 1. Roles — production positions (audio, livestream, slides) */
|
/* 1. Roles — production positions (audio, livestream, slides) */
|
||||||
const roleRows: (typeof roles.$inferInsert)[] = [
|
const roleRows: (typeof roles.$inferInsert)[] = [
|
||||||
{
|
{
|
||||||
@@ -144,7 +169,7 @@ export async function seed() {
|
|||||||
|
|
||||||
const slotRows: (typeof slots.$inferInsert)[] = [];
|
const slotRows: (typeof slots.$inferInsert)[] = [];
|
||||||
for (const inst of instanceRows) {
|
for (const inst of instanceRows) {
|
||||||
roleRows2.forEach((role, i) => {
|
roleRows2.forEach((role) => {
|
||||||
const callTime = role.callTimeOffsetMinutes
|
const callTime = role.callTimeOffsetMinutes
|
||||||
? new Date(inst.startsAt!.getTime() + role.callTimeOffsetMinutes * 60000)
|
? new Date(inst.startsAt!.getTime() + role.callTimeOffsetMinutes * 60000)
|
||||||
: null;
|
: null;
|
||||||
@@ -153,7 +178,10 @@ export async function seed() {
|
|||||||
serviceInstanceId: inst.id,
|
serviceInstanceId: inst.id,
|
||||||
eventId: null,
|
eventId: null,
|
||||||
roleId: role.id,
|
roleId: role.id,
|
||||||
slotIndex: i + 1,
|
// One seat per role per instance; the app also numbers every role's
|
||||||
|
// first seat 1, so a different index would insert duplicate seats on
|
||||||
|
// instances that already exist.
|
||||||
|
slotIndex: 1,
|
||||||
callTime,
|
callTime,
|
||||||
status: "open",
|
status: "open",
|
||||||
slotNote: null,
|
slotNote: null,
|
||||||
|
|||||||
+27
-14
@@ -6,11 +6,13 @@
|
|||||||
* `onConflictDoNothing`, so re-runs are no-ops and never disturb an admin's
|
* `onConflictDoNothing`, so re-runs are no-ops and never disturb an admin's
|
||||||
* assignments on an existing seat.
|
* assignments on an existing seat.
|
||||||
*
|
*
|
||||||
* Per §5.1, slots are created only for non-published instances: a published
|
* Per §5.1, a published week's slot set is owned by the publish flow, so
|
||||||
* week's slot set is owned by the publish flow, not the generator.
|
* existing seats are never touched. The one exception is a published instance
|
||||||
|
* with zero seats: that week was published before any seats existed and can
|
||||||
|
* never become assignable unless the generator repairs it.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { and, gte, ne } from "drizzle-orm";
|
import { eq, gte, sql } from "drizzle-orm";
|
||||||
import { db } from "@/db";
|
import { db } from "@/db";
|
||||||
import { roles, serviceInstances, slots } from "@/db/schema";
|
import { roles, serviceInstances, slots } from "@/db/schema";
|
||||||
import { uuidv7 } from "@/lib/uuid";
|
import { uuidv7 } from "@/lib/uuid";
|
||||||
@@ -55,22 +57,33 @@ export async function materializeSlotsForInstance(
|
|||||||
}
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Materialize slots for every non-published instance at or after `now`.
|
* Materialize seats for every instance at or after `now`. A published instance
|
||||||
* Published instances are left untouched (their slot set is owned by the
|
* with existing seats is left untouched (its slot set is owned by the publish
|
||||||
* publish flow).
|
* flow), but a published instance with no seats at all is repaired — otherwise
|
||||||
|
* it stays permanently unassignable.
|
||||||
*/
|
*/
|
||||||
export async function materializeSlots(now?: Date): Promise<{ created: number; instances: number }> {
|
export async function materializeSlots(now?: Date): Promise<{ created: number; instances: number }> {
|
||||||
const reference = now ?? new Date();
|
const reference = now ?? new Date();
|
||||||
const instances = await db
|
const instances = await db
|
||||||
.select()
|
.select({
|
||||||
|
id: serviceInstances.id,
|
||||||
|
startsAt: serviceInstances.startsAt,
|
||||||
|
status: serviceInstances.status,
|
||||||
|
seatCount: sql<number>`count(${slots.id})`,
|
||||||
|
})
|
||||||
.from(serviceInstances)
|
.from(serviceInstances)
|
||||||
.where(
|
.leftJoin(slots, eq(slots.serviceInstanceId, serviceInstances.id))
|
||||||
and(
|
.where(gte(serviceInstances.startsAt, reference))
|
||||||
gte(serviceInstances.startsAt, reference),
|
.groupBy(
|
||||||
ne(serviceInstances.status, "published"),
|
serviceInstances.id,
|
||||||
),
|
serviceInstances.startsAt,
|
||||||
|
serviceInstances.status,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
const target = instances.filter(
|
||||||
|
(inst) => inst.status !== "published" || Number(inst.seatCount) === 0,
|
||||||
|
);
|
||||||
|
|
||||||
const roleRows = await db.select().from(roles).orderBy(roles.sortOrder);
|
const roleRows = await db.select().from(roles).orderBy(roles.sortOrder);
|
||||||
const rolesInput: RolePlanInput[] = roleRows.map((r) => ({
|
const rolesInput: RolePlanInput[] = roleRows.map((r) => ({
|
||||||
id: r.id,
|
id: r.id,
|
||||||
@@ -79,10 +92,10 @@ export async function materializeSlots(now?: Date): Promise<{ created: number; i
|
|||||||
}));
|
}));
|
||||||
|
|
||||||
let created = 0;
|
let created = 0;
|
||||||
for (const inst of instances) {
|
for (const inst of target) {
|
||||||
if (!inst.startsAt) continue;
|
if (!inst.startsAt) continue;
|
||||||
created += await materializeSlotsForInstance(inst.id, inst.startsAt, rolesInput);
|
created += await materializeSlotsForInstance(inst.id, inst.startsAt, rolesInput);
|
||||||
}
|
}
|
||||||
|
|
||||||
return { created, instances: instances.length };
|
return { created, instances: target.length };
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,231 @@
|
|||||||
|
/**
|
||||||
|
* One-off ("special") services, scheduled from the week view.
|
||||||
|
*
|
||||||
|
* A special service is a dated service instance with no recurrence. It reuses
|
||||||
|
* the normal instance + slot pipeline so assignments, coverage and publishing
|
||||||
|
* work unchanged, but only the positions the scheduler picked are materialized
|
||||||
|
* — a Wednesday prayer meeting may need Audio alone, not all three seats.
|
||||||
|
*
|
||||||
|
* `service_instances.service_id` is required, so the instances hang off one
|
||||||
|
* inactive parent template. It never generates instances (it has no rrule) and
|
||||||
|
* stays out of the active template list; it exists only to satisfy the FK and
|
||||||
|
* to group one-off services in queries.
|
||||||
|
*
|
||||||
|
* When a photographer is picked at scheduling time, a media event for the same
|
||||||
|
* date and time is created and assigned to them immediately, so the shoot shows
|
||||||
|
* up in their Events list without a second trip through the Events page.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { and, eq, inArray } from "drizzle-orm";
|
||||||
|
import { db } from "@/db";
|
||||||
|
import {
|
||||||
|
eventPhotographers,
|
||||||
|
events,
|
||||||
|
roles,
|
||||||
|
serviceInstances,
|
||||||
|
services,
|
||||||
|
slots,
|
||||||
|
users,
|
||||||
|
} from "@/db/schema";
|
||||||
|
import { planSlots, type RolePlanInput } from "@/domain/slots";
|
||||||
|
import { CHURCH_TIMEZONE, localToUtc } from "@/lib/tz";
|
||||||
|
import { uuidv7 } from "@/lib/uuid";
|
||||||
|
|
||||||
|
/** Shared parent template for one-off instances; hidden from active services. */
|
||||||
|
export const SPECIAL_SERVICE_NAME = "Special services (one-off)";
|
||||||
|
|
||||||
|
export class SpecialServiceError extends Error {
|
||||||
|
constructor(
|
||||||
|
message: string,
|
||||||
|
readonly status = 400,
|
||||||
|
) {
|
||||||
|
super(message);
|
||||||
|
this.name = "SpecialServiceError";
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SpecialServiceInput {
|
||||||
|
title: string;
|
||||||
|
/** Local date, YYYY-MM-DD. */
|
||||||
|
date: string;
|
||||||
|
/** Local wall-clock start, HH:MM. */
|
||||||
|
startTimeLocal: string;
|
||||||
|
durationMinutes: number;
|
||||||
|
location?: string | null;
|
||||||
|
notes?: string | null;
|
||||||
|
/** Positions (roles) this occurrence needs; may be empty. */
|
||||||
|
roleIds: string[];
|
||||||
|
/** Pick a photographer up front to create their media event. */
|
||||||
|
photographerId?: string | null;
|
||||||
|
createdBy: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface SpecialServiceResult {
|
||||||
|
instanceId: string;
|
||||||
|
eventId: string | null;
|
||||||
|
seats: number;
|
||||||
|
}
|
||||||
|
|
||||||
|
type Tx = Parameters<Parameters<typeof db.transaction>[0]>[0];
|
||||||
|
|
||||||
|
async function getSpecialTemplateId(tx: Tx): Promise<string> {
|
||||||
|
const [existing] = await tx
|
||||||
|
.select({ id: services.id })
|
||||||
|
.from(services)
|
||||||
|
.where(eq(services.name, SPECIAL_SERVICE_NAME))
|
||||||
|
.limit(1);
|
||||||
|
if (existing) return existing.id;
|
||||||
|
|
||||||
|
try {
|
||||||
|
const [row] = await tx
|
||||||
|
.insert(services)
|
||||||
|
.values({
|
||||||
|
id: uuidv7(),
|
||||||
|
name: SPECIAL_SERVICE_NAME,
|
||||||
|
timezone: CHURCH_TIMEZONE,
|
||||||
|
startTimeLocal: "00:00",
|
||||||
|
durationMinutes: 60,
|
||||||
|
active: false,
|
||||||
|
notes:
|
||||||
|
"Parent for one-off services added from the Schedule. Not a recurring template.",
|
||||||
|
})
|
||||||
|
.returning({ id: services.id });
|
||||||
|
return row!.id;
|
||||||
|
} catch (error) {
|
||||||
|
// Another scheduler created the parent in the same instant.
|
||||||
|
if ((error as { code?: string }).code === "23505") {
|
||||||
|
const [raced] = await tx
|
||||||
|
.select({ id: services.id })
|
||||||
|
.from(services)
|
||||||
|
.where(eq(services.name, SPECIAL_SERVICE_NAME))
|
||||||
|
.limit(1);
|
||||||
|
if (raced) return raced.id;
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function createSpecialService(
|
||||||
|
input: SpecialServiceInput,
|
||||||
|
): Promise<SpecialServiceResult> {
|
||||||
|
if (!/^\d{4}-\d{2}-\d{2}$/.test(input.date)) {
|
||||||
|
throw new SpecialServiceError("choose a valid date");
|
||||||
|
}
|
||||||
|
if (!/^\d{2}:\d{2}$/.test(input.startTimeLocal)) {
|
||||||
|
throw new SpecialServiceError("choose a valid start time");
|
||||||
|
}
|
||||||
|
|
||||||
|
const startsAt = localToUtc(input.date, input.startTimeLocal, CHURCH_TIMEZONE);
|
||||||
|
if (Number.isNaN(startsAt.getTime())) {
|
||||||
|
throw new SpecialServiceError("choose a valid date and time");
|
||||||
|
}
|
||||||
|
const endsAt = new Date(
|
||||||
|
startsAt.getTime() + Math.max(1, input.durationMinutes) * 60_000,
|
||||||
|
);
|
||||||
|
|
||||||
|
const uniqueRoleIds = [...new Set(input.roleIds)];
|
||||||
|
const roleRows = uniqueRoleIds.length
|
||||||
|
? await db
|
||||||
|
.select()
|
||||||
|
.from(roles)
|
||||||
|
.where(and(inArray(roles.id, uniqueRoleIds), eq(roles.active, true)))
|
||||||
|
.orderBy(roles.sortOrder, roles.name)
|
||||||
|
: [];
|
||||||
|
if (roleRows.length !== uniqueRoleIds.length) {
|
||||||
|
throw new SpecialServiceError("one of the selected positions is not active");
|
||||||
|
}
|
||||||
|
|
||||||
|
return db.transaction(async (tx) => {
|
||||||
|
const serviceId = await getSpecialTemplateId(tx);
|
||||||
|
|
||||||
|
const [duplicate] = await tx
|
||||||
|
.select({ id: serviceInstances.id })
|
||||||
|
.from(serviceInstances)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(serviceInstances.serviceId, serviceId),
|
||||||
|
eq(serviceInstances.startsAt, startsAt),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.limit(1);
|
||||||
|
if (duplicate) {
|
||||||
|
throw new SpecialServiceError(
|
||||||
|
"a special service already exists at that date and time",
|
||||||
|
409,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const instanceId = uuidv7();
|
||||||
|
await tx.insert(serviceInstances).values({
|
||||||
|
id: instanceId,
|
||||||
|
serviceId,
|
||||||
|
occursOn: localToUtc(input.date, "00:00", CHURCH_TIMEZONE),
|
||||||
|
startsAt,
|
||||||
|
endsAt,
|
||||||
|
isSpecial: true,
|
||||||
|
titleOverride: input.title,
|
||||||
|
status: "draft",
|
||||||
|
notes: input.notes ?? null,
|
||||||
|
});
|
||||||
|
|
||||||
|
const plan: RolePlanInput[] = roleRows.map((role) => ({
|
||||||
|
id: role.id,
|
||||||
|
callTimeOffsetMinutes: role.callTimeOffsetMinutes,
|
||||||
|
defaultHeadcount: role.defaultHeadcount,
|
||||||
|
}));
|
||||||
|
let seats = 0;
|
||||||
|
for (const seat of planSlots(startsAt, plan)) {
|
||||||
|
await tx.insert(slots).values({
|
||||||
|
id: uuidv7(),
|
||||||
|
serviceInstanceId: instanceId,
|
||||||
|
eventId: null,
|
||||||
|
roleId: seat.roleId,
|
||||||
|
slotIndex: seat.slotIndex,
|
||||||
|
callTime: seat.callTime,
|
||||||
|
status: "open",
|
||||||
|
});
|
||||||
|
seats++;
|
||||||
|
}
|
||||||
|
|
||||||
|
let eventId: string | null = null;
|
||||||
|
if (input.photographerId) {
|
||||||
|
const [person] = await tx
|
||||||
|
.select({ id: users.id })
|
||||||
|
.from(users)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(users.id, input.photographerId),
|
||||||
|
eq(users.status, "active"),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.limit(1);
|
||||||
|
if (!person) {
|
||||||
|
throw new SpecialServiceError(
|
||||||
|
"that photographer is not an active team member",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
eventId = uuidv7();
|
||||||
|
await tx.insert(events).values({
|
||||||
|
id: eventId,
|
||||||
|
title: input.title,
|
||||||
|
eventType: "special service",
|
||||||
|
startsAt,
|
||||||
|
endsAt,
|
||||||
|
location: input.location ?? null,
|
||||||
|
description: "Photo coverage for this special service.",
|
||||||
|
createdBy: input.createdBy,
|
||||||
|
createdAt: new Date(),
|
||||||
|
});
|
||||||
|
await tx.insert(eventPhotographers).values({
|
||||||
|
eventId,
|
||||||
|
userId: input.photographerId,
|
||||||
|
role: "photographer",
|
||||||
|
assignedBy: input.createdBy,
|
||||||
|
assignedAt: new Date(),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return { instanceId, eventId, seats };
|
||||||
|
});
|
||||||
|
}
|
||||||
+21
-1
@@ -9,7 +9,7 @@
|
|||||||
* patch that omits a field (say, the phone) never nulls it out.
|
* patch that omits a field (say, the phone) never nulls it out.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { and, asc, eq, isNull, ne, or, sql } from "drizzle-orm";
|
import { and, asc, eq, isNotNull, isNull, ne, or, sql } from "drizzle-orm";
|
||||||
import { db } from "@/db";
|
import { db } from "@/db";
|
||||||
import { assignments, userSkills, users } from "@/db/schema";
|
import { assignments, userSkills, users } from "@/db/schema";
|
||||||
import type { SystemRole } from "@/auth/roles";
|
import type { SystemRole } from "@/auth/roles";
|
||||||
@@ -197,6 +197,26 @@ export async function hasAssignmentHistory(userId: string): Promise<boolean> {
|
|||||||
return Boolean(row);
|
return Boolean(row);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whether any admin has real credentials. Once this is true, public
|
||||||
|
* magic-link sign-in is closed: anyone who knew an admin's email could
|
||||||
|
* otherwise mint a full admin session from the login page. New-account and
|
||||||
|
* recovery links remain available to signed-in admins.
|
||||||
|
*/
|
||||||
|
export async function hasPasswordProtectedAdmin(): Promise<boolean> {
|
||||||
|
const [row] = await db
|
||||||
|
.select({ id: users.id })
|
||||||
|
.from(users)
|
||||||
|
.where(
|
||||||
|
and(
|
||||||
|
eq(users.systemRole, "admin"),
|
||||||
|
isNotNull(users.passwordHash),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.limit(1);
|
||||||
|
return Boolean(row);
|
||||||
|
}
|
||||||
|
|
||||||
/** Active admins who could still sign in, excluding the person being changed. */
|
/** Active admins who could still sign in, excluding the person being changed. */
|
||||||
export async function countOtherActiveAdmins(excludeUserId: string): Promise<number> {
|
export async function countOtherActiveAdmins(excludeUserId: string): Promise<number> {
|
||||||
const [row] = await db
|
const [row] = await db
|
||||||
|
|||||||
+2
-2
@@ -55,7 +55,7 @@ function serveSelect() {
|
|||||||
slotId: slots.id,
|
slotId: slots.id,
|
||||||
instanceId: serviceInstances.id,
|
instanceId: serviceInstances.id,
|
||||||
roleName: roles.name,
|
roleName: roles.name,
|
||||||
serviceName: services.name,
|
serviceName: sql<string>`coalesce(${serviceInstances.titleOverride}, ${services.name})`,
|
||||||
status: assignments.status,
|
status: assignments.status,
|
||||||
occursOn: serviceInstances.occursOn,
|
occursOn: serviceInstances.occursOn,
|
||||||
startsAt: serviceInstances.startsAt,
|
startsAt: serviceInstances.startsAt,
|
||||||
@@ -248,7 +248,7 @@ export async function calendarFeedForUser(
|
|||||||
.select({
|
.select({
|
||||||
id: assignments.id,
|
id: assignments.id,
|
||||||
roleName: roles.name,
|
roleName: roles.name,
|
||||||
serviceName: services.name,
|
serviceName: sql<string>`coalesce(${serviceInstances.titleOverride}, ${services.name})`,
|
||||||
startsAt: serviceInstances.startsAt,
|
startsAt: serviceInstances.startsAt,
|
||||||
endsAt: serviceInstances.endsAt,
|
endsAt: serviceInstances.endsAt,
|
||||||
callTime: slots.callTime,
|
callTime: slots.callTime,
|
||||||
|
|||||||
@@ -1,5 +1,9 @@
|
|||||||
import { describe, it, expect } from "vitest";
|
import { describe, it, expect } from "vitest";
|
||||||
import { escapeHtml, renderAssignmentPublishedEmail } from "./templates";
|
import {
|
||||||
|
escapeHtml,
|
||||||
|
renderAssignmentProposedEmail,
|
||||||
|
renderAssignmentPublishedEmail,
|
||||||
|
} from "./templates";
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* E3 — email templates.
|
* E3 — email templates.
|
||||||
@@ -56,6 +60,25 @@ describe("renderAssignmentPublishedEmail", () => {
|
|||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
|
describe("renderAssignmentProposedEmail", () => {
|
||||||
|
const proposed = {
|
||||||
|
...ctx,
|
||||||
|
alternativeUrl: "https://media.test/respond?t=abc&a=alternative",
|
||||||
|
};
|
||||||
|
|
||||||
|
it("asks for a response and offers all three links", () => {
|
||||||
|
const { subject } = renderAssignmentProposedEmail(proposed);
|
||||||
|
expect(subject).toBe("Can you serve on Slides — Sunday, Nov 22?");
|
||||||
|
const { html, text } = renderAssignmentProposedEmail(proposed);
|
||||||
|
expect(html).toContain("a=confirm");
|
||||||
|
expect(html).toContain("a=decline");
|
||||||
|
expect(html).toContain("a=alternative");
|
||||||
|
expect(html).toContain("Propose another Sunday");
|
||||||
|
expect(html).toContain("can you serve on Slides?");
|
||||||
|
expect(text).toContain("Propose another Sunday: ");
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
describe("escapeHtml", () => {
|
describe("escapeHtml", () => {
|
||||||
it("escapes the five HTML-significant characters", () => {
|
it("escapes the five HTML-significant characters", () => {
|
||||||
expect(escapeHtml(`&<>"'`)).toBe("&<>"'");
|
expect(escapeHtml(`&<>"'`)).toBe("&<>"'");
|
||||||
|
|||||||
+31
-3
@@ -24,6 +24,8 @@ export interface AssignmentEmailContext {
|
|||||||
location: string;
|
location: string;
|
||||||
confirmUrl: string;
|
confirmUrl: string;
|
||||||
declineUrl: string;
|
declineUrl: string;
|
||||||
|
/** Present on the proposed email: "I can serve another Sunday". */
|
||||||
|
alternativeUrl?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface RenderedEmail {
|
export interface RenderedEmail {
|
||||||
@@ -51,6 +53,21 @@ export function renderAssignmentPublishedEmail(
|
|||||||
return renderAssignmentEmail(ctx, `You're on ${ctx.roleName} — ${ctx.occursOnLabel}`);
|
return renderAssignmentEmail(ctx, `You're on ${ctx.roleName} — ${ctx.occursOnLabel}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The assignment.proposed email: the seat is not confirmed until the volunteer
|
||||||
|
* responds, so it offers all three choices — accept, decline, or propose a
|
||||||
|
* different Sunday.
|
||||||
|
*/
|
||||||
|
export function renderAssignmentProposedEmail(
|
||||||
|
ctx: AssignmentEmailContext & { alternativeUrl: string },
|
||||||
|
): RenderedEmail {
|
||||||
|
return renderAssignmentEmail(
|
||||||
|
ctx,
|
||||||
|
`Can you serve on ${ctx.roleName} — ${ctx.occursOnLabel}?`,
|
||||||
|
true,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
/** A reminder for the same assignment (E7): same body, reminder subject. */
|
/** A reminder for the same assignment (E7): same body, reminder subject. */
|
||||||
export function renderAssignmentReminderEmail(
|
export function renderAssignmentReminderEmail(
|
||||||
ctx: AssignmentEmailContext,
|
ctx: AssignmentEmailContext,
|
||||||
@@ -136,6 +153,7 @@ export function renderEventReminderEmail(
|
|||||||
function renderAssignmentEmail(
|
function renderAssignmentEmail(
|
||||||
ctx: AssignmentEmailContext,
|
ctx: AssignmentEmailContext,
|
||||||
subject: string,
|
subject: string,
|
||||||
|
proposed = false,
|
||||||
): RenderedEmail {
|
): RenderedEmail {
|
||||||
const callTime = ctx.callTimeLabel ?? CALL_TIME_UNSET;
|
const callTime = ctx.callTimeLabel ?? CALL_TIME_UNSET;
|
||||||
const firstName = escapeHtml(ctx.volunteerFirstName);
|
const firstName = escapeHtml(ctx.volunteerFirstName);
|
||||||
@@ -147,11 +165,14 @@ function renderAssignmentEmail(
|
|||||||
const location = escapeHtml(ctx.location);
|
const location = escapeHtml(ctx.location);
|
||||||
const confirmUrl = escapeHtml(ctx.confirmUrl);
|
const confirmUrl = escapeHtml(ctx.confirmUrl);
|
||||||
const declineUrl = escapeHtml(ctx.declineUrl);
|
const declineUrl = escapeHtml(ctx.declineUrl);
|
||||||
|
const alternativeUrl = ctx.alternativeUrl
|
||||||
|
? escapeHtml(ctx.alternativeUrl)
|
||||||
|
: null;
|
||||||
|
|
||||||
const html = `<!doctype html>
|
const html = `<!doctype html>
|
||||||
<html>
|
<html>
|
||||||
<body style="font-family: system-ui, sans-serif; line-height: 1.5; color: #111827;">
|
<body style="font-family: system-ui, sans-serif; line-height: 1.5; color: #111827;">
|
||||||
<h1 style="font-size: 20px;">${firstName}, you're on ${roleName}</h1>
|
<h1 style="font-size: 20px;">${firstName}, ${proposed ? `can you serve on ${roleName}?` : `you're on ${roleName}`}</h1>
|
||||||
<p>
|
<p>
|
||||||
${serviceName}<br />
|
${serviceName}<br />
|
||||||
${occursOn} at ${startTime}<br />
|
${occursOn} at ${startTime}<br />
|
||||||
@@ -162,17 +183,21 @@ function renderAssignmentEmail(
|
|||||||
<a href="${confirmUrl}" style="display:inline-block;padding:10px 16px;background:#932822;color:#fff;border-radius:6px;text-decoration:none;">Confirm</a>
|
<a href="${confirmUrl}" style="display:inline-block;padding:10px 16px;background:#932822;color:#fff;border-radius:6px;text-decoration:none;">Confirm</a>
|
||||||
|
|
||||||
<a href="${declineUrl}" style="display:inline-block;padding:10px 16px;border:1px solid #6b7280;color:#111827;border-radius:6px;text-decoration:none;">Can't make it</a>
|
<a href="${declineUrl}" style="display:inline-block;padding:10px 16px;border:1px solid #6b7280;color:#111827;border-radius:6px;text-decoration:none;">Can't make it</a>
|
||||||
|
${alternativeUrl ? `<a href="${alternativeUrl}" style="display:inline-block;margin-left:8px;padding:10px 16px;border:1px solid #6b7280;color:#111827;border-radius:6px;text-decoration:none;">Propose another Sunday</a>` : ""}
|
||||||
</p>
|
</p>
|
||||||
<p style="font-size: 12px; color: #6b7280;">
|
<p style="font-size: 12px; color: #6b7280;">
|
||||||
No login needed — the links above are single-use. If you can't serve,
|
No login needed — the links above are single-use. If you can't serve,
|
||||||
please decline so a coordinator can find cover.
|
please decline so a coordinator can find cover, or propose another
|
||||||
|
Sunday you are available.
|
||||||
</p>
|
</p>
|
||||||
<p style="font-size: 12px; color: #6b7280;">Media Team Hub · Glenloch</p>
|
<p style="font-size: 12px; color: #6b7280;">Media Team Hub · Glenloch</p>
|
||||||
</body>
|
</body>
|
||||||
</html>`;
|
</html>`;
|
||||||
|
|
||||||
const text = [
|
const text = [
|
||||||
`${ctx.volunteerFirstName}, you're on ${ctx.roleName}`,
|
proposed
|
||||||
|
? `${ctx.volunteerFirstName}, can you serve on ${ctx.roleName}?`
|
||||||
|
: `${ctx.volunteerFirstName}, you're on ${ctx.roleName}`,
|
||||||
"",
|
"",
|
||||||
ctx.serviceName,
|
ctx.serviceName,
|
||||||
`${ctx.occursOnLabel} at ${ctx.startTimeLabel}`,
|
`${ctx.occursOnLabel} at ${ctx.startTimeLabel}`,
|
||||||
@@ -181,6 +206,9 @@ function renderAssignmentEmail(
|
|||||||
"",
|
"",
|
||||||
"Confirm: " + ctx.confirmUrl,
|
"Confirm: " + ctx.confirmUrl,
|
||||||
"Can't make it: " + ctx.declineUrl,
|
"Can't make it: " + ctx.declineUrl,
|
||||||
|
...(ctx.alternativeUrl
|
||||||
|
? ["Propose another Sunday: " + ctx.alternativeUrl]
|
||||||
|
: []),
|
||||||
"",
|
"",
|
||||||
"No login needed — the links are single-use.",
|
"No login needed — the links are single-use.",
|
||||||
].join("\n");
|
].join("\n");
|
||||||
|
|||||||
@@ -0,0 +1,125 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import {
|
||||||
|
advancedEditViewFor,
|
||||||
|
advancedToQuickAdjustments,
|
||||||
|
parseAdvancedRecipe,
|
||||||
|
} from "./advanced-edit";
|
||||||
|
import { defaultPhotoAdjustments } from "./photo-adjustments";
|
||||||
|
|
||||||
|
const ADVANCED = {
|
||||||
|
exposure: 0.4,
|
||||||
|
contrast: 26,
|
||||||
|
highlights: -12,
|
||||||
|
shadows: 8,
|
||||||
|
whites: 10,
|
||||||
|
blacks: -14,
|
||||||
|
texture: 20,
|
||||||
|
clarity: 16,
|
||||||
|
dehaze: 0,
|
||||||
|
vibrance: 0,
|
||||||
|
saturation: 0,
|
||||||
|
temp: 6,
|
||||||
|
tint: -3,
|
||||||
|
bw: true,
|
||||||
|
bwFilter: "red",
|
||||||
|
bwFilterAmount: 100,
|
||||||
|
curve: {
|
||||||
|
rgb: [
|
||||||
|
{ x: 0, y: 0 },
|
||||||
|
{ x: 0.35, y: 0.42 },
|
||||||
|
{ x: 1, y: 1 },
|
||||||
|
],
|
||||||
|
red: [
|
||||||
|
{ x: 0, y: 0 },
|
||||||
|
{ x: 1, y: 1 },
|
||||||
|
],
|
||||||
|
green: [
|
||||||
|
{ x: 0, y: 0 },
|
||||||
|
{ x: 1, y: 1 },
|
||||||
|
],
|
||||||
|
blue: [
|
||||||
|
{ x: 0, y: 0 },
|
||||||
|
{ x: 1, y: 0.9 },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
hsl: { hue: [0, 0, 0, 0, 0, 0, 0, 0], sat: [0, 0, 0, 0, 0, 0, 0, 0], lum: [0, 0, 0, 0, 0, 0, 0, 0] },
|
||||||
|
grading: { shadows: { h: 210, s: 0 }, highlights: { h: 45, s: 0 }, balance: 0 },
|
||||||
|
sharpen: { amount: 40, radius: 1.4, detail: 30 },
|
||||||
|
noise: { luminance: 12, detail: 50 },
|
||||||
|
vignette: { amount: -18, midpoint: 50, feather: 50 },
|
||||||
|
grain: { amount: 14, size: 30, roughness: 50 },
|
||||||
|
crop: { x: 0, y: 0, w: 1, h: 1, angle: 0, quarter: 0, aspect: "original", flipH: false, flipV: false },
|
||||||
|
};
|
||||||
|
|
||||||
|
describe("advanced edit view", () => {
|
||||||
|
it("ignores photos without an advanced recipe", () => {
|
||||||
|
expect(advancedEditViewFor(null)).toBeNull();
|
||||||
|
expect(advancedEditViewFor("")).toBeNull();
|
||||||
|
expect(advancedEditViewFor("{}")).toBeNull();
|
||||||
|
expect(advancedEditViewFor("not json")).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("maps the tone and colour sliders onto the quick recipe", () => {
|
||||||
|
const seed = advancedToQuickAdjustments(parseAdvancedRecipe(JSON.stringify(ADVANCED))!);
|
||||||
|
expect(seed.exposure).toBe(0.4);
|
||||||
|
expect(seed.contrast).toBe(26);
|
||||||
|
expect(seed.highlights).toBe(-12);
|
||||||
|
expect(seed.whites).toBe(10);
|
||||||
|
expect(seed.blacks).toBe(-14);
|
||||||
|
expect(seed.clarity).toBe(16);
|
||||||
|
expect(seed.temperature).toBe(6);
|
||||||
|
expect(seed.tint).toBe(-3);
|
||||||
|
expect(seed.sharpen).toBe(40);
|
||||||
|
expect(seed.noiseReduction).toBe(12);
|
||||||
|
expect(seed.vignette).toBe(-18);
|
||||||
|
expect(seed.grain).toBe(14);
|
||||||
|
// A black-and-white advanced edit becomes the quick grey conversion.
|
||||||
|
expect(seed.saturation).toBe(-100);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("samples the advanced master curve with anchors for the quick curve", () => {
|
||||||
|
const seed = advancedToQuickAdjustments(parseAdvancedRecipe(JSON.stringify(ADVANCED))!);
|
||||||
|
expect(seed.curves[0].x).toBe(0);
|
||||||
|
expect(seed.curves[seed.curves.length - 1].x).toBe(1);
|
||||||
|
// The lifted midtone survives in the sampled curve.
|
||||||
|
const atMid = seed.curves.reduce((best, point) =>
|
||||||
|
Math.abs(point.x - 0.5) < Math.abs(best.x - 0.5) ? point : best,
|
||||||
|
);
|
||||||
|
expect(atMid.y).toBeGreaterThan(atMid.x);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("lists the settings the quick editor cannot hold", () => {
|
||||||
|
const view = advancedEditViewFor(JSON.stringify(ADVANCED))!;
|
||||||
|
expect(view.onlyAdvanced).toEqual(
|
||||||
|
expect.arrayContaining([
|
||||||
|
"Texture",
|
||||||
|
"red black & white filter",
|
||||||
|
"Sharpening radius and detail",
|
||||||
|
"Per-channel curves",
|
||||||
|
]),
|
||||||
|
);
|
||||||
|
const flat = view.sections.flatMap((section) => section.items.map((item) => item.label));
|
||||||
|
expect(flat).toContain("Contrast");
|
||||||
|
expect(flat).toContain("Black & white");
|
||||||
|
expect(flat).not.toContain("Dehaze");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("converts rotation and a crop into the quick geometry", () => {
|
||||||
|
const view = advancedEditViewFor(
|
||||||
|
JSON.stringify({
|
||||||
|
crop: { x: 0.1, y: 0, w: 0.8, h: 0.8, angle: 3, quarter: 1, aspect: "1:1", flipH: false, flipV: true },
|
||||||
|
}),
|
||||||
|
)!;
|
||||||
|
expect(view.seed.rotation).toBe(90);
|
||||||
|
expect(view.seed.straighten).toBe(3);
|
||||||
|
expect(view.seed.crop.aspect).toBe("1:1");
|
||||||
|
expect(view.seed.crop.zoom).toBeCloseTo(1.25, 3);
|
||||||
|
expect(view.onlyAdvanced).toContain("Flip");
|
||||||
|
expect(view.caveats.length).toBeGreaterThan(0);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("leaves a neutral recipe with the neutral quick adjustments", () => {
|
||||||
|
const seed = advancedToQuickAdjustments(parseAdvancedRecipe(JSON.stringify({ exposure: 0 }))!);
|
||||||
|
expect(seed).toEqual(defaultPhotoAdjustments());
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,571 @@
|
|||||||
|
/**
|
||||||
|
* Read the advanced (Lumenroom) recipe stored on an event photo.
|
||||||
|
*
|
||||||
|
* The two editors are separate applications with separate recipes. This module
|
||||||
|
* translates the advanced recipe into the quick editor's controls so the photo
|
||||||
|
* page can show what the advanced editor did, and so a photographer can hand
|
||||||
|
* the look over to the quick sliders. The translation is deliberately lossy:
|
||||||
|
* controls the quick editor has no equivalent for are reported instead of being
|
||||||
|
* silently dropped.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import {
|
||||||
|
MAX_CURVE_POINTS,
|
||||||
|
PHOTO_ADJUSTMENT_LIMITS,
|
||||||
|
createCurveEvaluator,
|
||||||
|
defaultPhotoAdjustments,
|
||||||
|
normalizePhotoAdjustments,
|
||||||
|
type CurvePoint,
|
||||||
|
type PhotoAdjustments,
|
||||||
|
type PhotoCropAspect,
|
||||||
|
type PhotoRotation,
|
||||||
|
} from "./photo-adjustments";
|
||||||
|
|
||||||
|
export interface AdvancedRecipe {
|
||||||
|
temp: number;
|
||||||
|
tint: number;
|
||||||
|
exposure: number;
|
||||||
|
contrast: number;
|
||||||
|
highlights: number;
|
||||||
|
shadows: number;
|
||||||
|
whites: number;
|
||||||
|
blacks: number;
|
||||||
|
texture: number;
|
||||||
|
clarity: number;
|
||||||
|
dehaze: number;
|
||||||
|
vibrance: number;
|
||||||
|
saturation: number;
|
||||||
|
bw: boolean;
|
||||||
|
bwFilter: string;
|
||||||
|
curve: { rgb: CurvePoint[]; red: CurvePoint[]; green: CurvePoint[]; blue: CurvePoint[] };
|
||||||
|
hsl: { hue: number[]; sat: number[]; lum: number[] };
|
||||||
|
grading: { shadows: number; highlights: number };
|
||||||
|
sharpen: { amount: number; radius: number; detail: number };
|
||||||
|
noise: { luminance: number; detail: number };
|
||||||
|
vignette: { amount: number; midpoint: number; feather: number };
|
||||||
|
grain: { amount: number; size: number; roughness: number };
|
||||||
|
crop: {
|
||||||
|
x: number;
|
||||||
|
y: number;
|
||||||
|
w: number;
|
||||||
|
h: number;
|
||||||
|
angle: number;
|
||||||
|
quarter: number;
|
||||||
|
aspect: string;
|
||||||
|
flipH: boolean;
|
||||||
|
flipV: boolean;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Quick-editor controls that take a single number. */
|
||||||
|
export type QuickNumericSetting = Exclude<
|
||||||
|
keyof PhotoAdjustments,
|
||||||
|
"curves" | "crop" | "rotation"
|
||||||
|
>;
|
||||||
|
|
||||||
|
export interface AdvancedEditItem {
|
||||||
|
label: string;
|
||||||
|
value: string;
|
||||||
|
/** The quick-editor control that shows this setting on its own. */
|
||||||
|
preview?: { key: QuickNumericSetting; amount: number };
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AdvancedEditView {
|
||||||
|
/** Non-neutral settings, grouped for display. */
|
||||||
|
sections: { title: string; items: AdvancedEditItem[] }[];
|
||||||
|
/** Settings the quick editor has no control for. */
|
||||||
|
onlyAdvanced: string[];
|
||||||
|
/** Notes about values that were mapped approximately. */
|
||||||
|
caveats: string[];
|
||||||
|
/** Quick-editor recipe that reproduces the advanced look as closely as possible. */
|
||||||
|
seed: PhotoAdjustments;
|
||||||
|
}
|
||||||
|
|
||||||
|
const IDENTITY: CurvePoint[] = [
|
||||||
|
{ x: 0, y: 0 },
|
||||||
|
{ x: 1, y: 1 },
|
||||||
|
];
|
||||||
|
|
||||||
|
function clamp(value: number, min: number, max: number): number {
|
||||||
|
return Math.min(max, Math.max(min, value));
|
||||||
|
}
|
||||||
|
|
||||||
|
function round(value: number, places = 2): number {
|
||||||
|
const factor = 10 ** places;
|
||||||
|
return Math.round(value * factor) / factor;
|
||||||
|
}
|
||||||
|
|
||||||
|
function num(value: unknown, fallback: number, min: number, max: number): number {
|
||||||
|
return typeof value === "number" && Number.isFinite(value)
|
||||||
|
? clamp(value, min, max)
|
||||||
|
: fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
function record(value: unknown): Record<string, unknown> {
|
||||||
|
return value && typeof value === "object" ? (value as Record<string, unknown>) : {};
|
||||||
|
}
|
||||||
|
|
||||||
|
function curvePoints(value: unknown): CurvePoint[] {
|
||||||
|
if (!Array.isArray(value)) return IDENTITY;
|
||||||
|
const points = value
|
||||||
|
.map((entry) => record(entry))
|
||||||
|
.filter((entry) => typeof entry.x === "number" && typeof entry.y === "number")
|
||||||
|
.map((entry) => ({
|
||||||
|
x: clamp(entry.x as number, 0, 1),
|
||||||
|
y: clamp(entry.y as number, 0, 1),
|
||||||
|
}))
|
||||||
|
.sort((a, b) => a.x - b.x);
|
||||||
|
return points.length >= 2 ? points : IDENTITY;
|
||||||
|
}
|
||||||
|
|
||||||
|
function bands(value: unknown): number[] {
|
||||||
|
if (!Array.isArray(value)) return [];
|
||||||
|
return value
|
||||||
|
.filter((entry): entry is number => typeof entry === "number" && Number.isFinite(entry))
|
||||||
|
.map((entry) => round(entry, 1));
|
||||||
|
}
|
||||||
|
|
||||||
|
function isNeutralBandList(values: number[]): boolean {
|
||||||
|
return values.every((value) => value === 0);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function isIdentityCurve(points: readonly CurvePoint[]): boolean {
|
||||||
|
if (points.length !== 2) return false;
|
||||||
|
return (
|
||||||
|
Math.abs(points[0].x) < 1e-6 &&
|
||||||
|
Math.abs(points[0].y) < 1e-6 &&
|
||||||
|
Math.abs(points[1].x - 1) < 1e-6 &&
|
||||||
|
Math.abs(points[1].y - 1) < 1e-6
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Parse the advanced recipe JSON; null when no recipe was saved. */
|
||||||
|
export function parseAdvancedRecipe(json: string | null | undefined): AdvancedRecipe | null {
|
||||||
|
if (!json) return null;
|
||||||
|
let parsed: unknown;
|
||||||
|
try {
|
||||||
|
parsed = JSON.parse(json);
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
if (!parsed || typeof parsed !== "object" || Object.keys(parsed).length === 0) {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
const raw = parsed as Record<string, unknown>;
|
||||||
|
const curve = record(raw.curve);
|
||||||
|
const hsl = record(raw.hsl);
|
||||||
|
const grading = record(raw.grading);
|
||||||
|
const gradingShadows = record(grading.shadows);
|
||||||
|
const gradingHighlights = record(grading.highlights);
|
||||||
|
const sharpen = record(raw.sharpen);
|
||||||
|
const noise = record(raw.noise);
|
||||||
|
const vignette = record(raw.vignette);
|
||||||
|
const grain = record(raw.grain);
|
||||||
|
const crop = record(raw.crop);
|
||||||
|
|
||||||
|
return {
|
||||||
|
temp: num(raw.temp, 0, -100, 100),
|
||||||
|
tint: num(raw.tint, 0, -100, 100),
|
||||||
|
exposure: num(raw.exposure, 0, -5, 5),
|
||||||
|
contrast: num(raw.contrast, 0, -100, 100),
|
||||||
|
highlights: num(raw.highlights, 0, -100, 100),
|
||||||
|
shadows: num(raw.shadows, 0, -100, 100),
|
||||||
|
whites: num(raw.whites, 0, -100, 100),
|
||||||
|
blacks: num(raw.blacks, 0, -100, 100),
|
||||||
|
texture: num(raw.texture, 0, -100, 100),
|
||||||
|
clarity: num(raw.clarity, 0, -100, 100),
|
||||||
|
dehaze: num(raw.dehaze, 0, -100, 100),
|
||||||
|
vibrance: num(raw.vibrance, 0, -100, 100),
|
||||||
|
saturation: num(raw.saturation, 0, -100, 100),
|
||||||
|
bw: raw.bw === true,
|
||||||
|
bwFilter: typeof raw.bwFilter === "string" ? raw.bwFilter : "none",
|
||||||
|
curve: {
|
||||||
|
rgb: curvePoints(curve.rgb),
|
||||||
|
red: curvePoints(curve.red),
|
||||||
|
green: curvePoints(curve.green),
|
||||||
|
blue: curvePoints(curve.blue),
|
||||||
|
},
|
||||||
|
hsl: {
|
||||||
|
hue: bands(hsl.hue),
|
||||||
|
sat: bands(hsl.sat),
|
||||||
|
lum: bands(hsl.lum),
|
||||||
|
},
|
||||||
|
grading: {
|
||||||
|
shadows: num(gradingShadows.s, 0, 0, 100),
|
||||||
|
highlights: num(gradingHighlights.s, 0, 0, 100),
|
||||||
|
},
|
||||||
|
sharpen: {
|
||||||
|
amount: num(sharpen.amount, 0, 0, 150),
|
||||||
|
radius: num(sharpen.radius, 1, 0.5, 3),
|
||||||
|
detail: num(sharpen.detail, 25, 0, 100),
|
||||||
|
},
|
||||||
|
noise: {
|
||||||
|
luminance: num(noise.luminance, 0, 0, 100),
|
||||||
|
detail: num(noise.detail, 50, 0, 100),
|
||||||
|
},
|
||||||
|
vignette: {
|
||||||
|
amount: num(vignette.amount, 0, -100, 100),
|
||||||
|
midpoint: num(vignette.midpoint, 50, 0, 100),
|
||||||
|
feather: num(vignette.feather, 50, 0, 100),
|
||||||
|
},
|
||||||
|
grain: {
|
||||||
|
amount: num(grain.amount, 0, 0, 100),
|
||||||
|
size: num(grain.size, 25, 10, 100),
|
||||||
|
roughness: num(grain.roughness, 50, 0, 100),
|
||||||
|
},
|
||||||
|
crop: {
|
||||||
|
x: num(crop.x, 0, 0, 1),
|
||||||
|
y: num(crop.y, 0, 0, 1),
|
||||||
|
w: num(crop.w, 1, 0.02, 1),
|
||||||
|
h: num(crop.h, 1, 0.02, 1),
|
||||||
|
angle: num(crop.angle, 0, -45, 45),
|
||||||
|
quarter: num(crop.quarter, 0, 0, 3),
|
||||||
|
aspect: typeof crop.aspect === "string" ? crop.aspect : "original",
|
||||||
|
flipH: crop.flipH === true,
|
||||||
|
flipV: crop.flipV === true,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sample the advanced master curve into the quick editor's format. The quick
|
||||||
|
* curve requires points at 0 and 1, and the advanced curve may not have them.
|
||||||
|
*/
|
||||||
|
function toQuickCurve(points: CurvePoint[]): CurvePoint[] {
|
||||||
|
if (isIdentityCurve(points)) return IDENTITY;
|
||||||
|
const padded = [...points];
|
||||||
|
if (padded[0].x > 1e-6) padded.unshift({ x: 0, y: padded[0].y });
|
||||||
|
if (padded[padded.length - 1].x < 1 - 1e-6) {
|
||||||
|
padded.push({ x: 1, y: padded[padded.length - 1].y });
|
||||||
|
}
|
||||||
|
const evaluate = createCurveEvaluator(padded);
|
||||||
|
const count = Math.min(MAX_CURVE_POINTS, Math.max(2, padded.length));
|
||||||
|
return Array.from({ length: count }, (_, index) => {
|
||||||
|
const x = count === 1 ? 0 : index / (count - 1);
|
||||||
|
return { x: round(x, 4), y: round(evaluate(x), 4) };
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const CROP_ASPECT_RATIOS: { aspect: PhotoCropAspect; ratio: number }[] = [
|
||||||
|
{ aspect: "1:1", ratio: 1 },
|
||||||
|
{ aspect: "4:5", ratio: 4 / 5 },
|
||||||
|
{ aspect: "5:4", ratio: 5 / 4 },
|
||||||
|
{ aspect: "4:3", ratio: 4 / 3 },
|
||||||
|
{ aspect: "3:4", ratio: 3 / 4 },
|
||||||
|
{ aspect: "16:9", ratio: 16 / 9 },
|
||||||
|
{ aspect: "9:16", ratio: 9 / 16 },
|
||||||
|
];
|
||||||
|
|
||||||
|
function closestAspect(width: number, height: number): PhotoCropAspect {
|
||||||
|
if (width >= 0.999 && height >= 0.999) return "original";
|
||||||
|
const ratio = width / Math.max(1e-6, height);
|
||||||
|
let best: PhotoCropAspect = "original";
|
||||||
|
let bestDelta = Infinity;
|
||||||
|
for (const option of CROP_ASPECT_RATIOS) {
|
||||||
|
const delta = Math.abs(ratio - option.ratio) / option.ratio;
|
||||||
|
if (delta < bestDelta) {
|
||||||
|
best = option.aspect;
|
||||||
|
bestDelta = delta;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return bestDelta <= 0.03 ? best : "original";
|
||||||
|
}
|
||||||
|
|
||||||
|
function isDefaultCrop(crop: AdvancedRecipe["crop"]): boolean {
|
||||||
|
return (
|
||||||
|
crop.x === 0 &&
|
||||||
|
crop.y === 0 &&
|
||||||
|
crop.w >= 0.999 &&
|
||||||
|
crop.h >= 0.999 &&
|
||||||
|
crop.angle === 0 &&
|
||||||
|
crop.quarter === 0
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Map the advanced look onto the quick editor's recipe. */
|
||||||
|
export function advancedToQuickAdjustments(recipe: AdvancedRecipe): PhotoAdjustments {
|
||||||
|
const limits = PHOTO_ADJUSTMENT_LIMITS;
|
||||||
|
const base = defaultPhotoAdjustments();
|
||||||
|
const quarter = ((Math.round(recipe.crop.quarter) % 4) + 4) % 4;
|
||||||
|
const zoom = clamp(1 / Math.max(0.02, Math.max(recipe.crop.w, recipe.crop.h)), 1, limits.cropZoom);
|
||||||
|
const offsetX = clamp(
|
||||||
|
(recipe.crop.x + recipe.crop.w / 2 - 0.5) / Math.max(1e-6, (1 - recipe.crop.w) / 2),
|
||||||
|
-1,
|
||||||
|
1,
|
||||||
|
);
|
||||||
|
const offsetY = clamp(
|
||||||
|
(recipe.crop.y + recipe.crop.h / 2 - 0.5) / Math.max(1e-6, (1 - recipe.crop.h) / 2),
|
||||||
|
-1,
|
||||||
|
1,
|
||||||
|
);
|
||||||
|
|
||||||
|
const adjustments: PhotoAdjustments = {
|
||||||
|
...base,
|
||||||
|
exposure: round(clamp(recipe.exposure, -limits.exposure, limits.exposure), 2),
|
||||||
|
contrast: Math.round(recipe.contrast),
|
||||||
|
shadows: Math.round(recipe.shadows),
|
||||||
|
highlights: Math.round(recipe.highlights),
|
||||||
|
whites: Math.round(recipe.whites),
|
||||||
|
blacks: Math.round(recipe.blacks),
|
||||||
|
brightness: 0,
|
||||||
|
clarity: Math.round(recipe.clarity),
|
||||||
|
dehaze: Math.round(recipe.dehaze),
|
||||||
|
temperature: Math.round(recipe.temp),
|
||||||
|
tint: Math.round(recipe.tint),
|
||||||
|
vibrance: Math.round(recipe.vibrance),
|
||||||
|
saturation: recipe.bw ? -100 : Math.round(recipe.saturation),
|
||||||
|
sharpen: Math.round(clamp(recipe.sharpen.amount, 0, limits.sharpen)),
|
||||||
|
noiseReduction: Math.round(clamp(recipe.noise.luminance, 0, limits.noiseReduction)),
|
||||||
|
vignette: Math.round(recipe.vignette.amount),
|
||||||
|
grain: Math.round(clamp(recipe.grain.amount, 0, limits.grain)),
|
||||||
|
curves: toQuickCurve(recipe.curve.rgb),
|
||||||
|
rotation: ((quarter * 90) % 360) as PhotoRotation,
|
||||||
|
straighten: round(clamp(recipe.crop.angle, -limits.straighten, limits.straighten), 2),
|
||||||
|
crop: {
|
||||||
|
aspect: closestAspect(recipe.crop.w, recipe.crop.h),
|
||||||
|
zoom: round(zoom, 3),
|
||||||
|
offsetX: round(offsetX, 3),
|
||||||
|
offsetY: round(offsetY, 3),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
return normalizePhotoAdjustments(adjustments) ?? base;
|
||||||
|
}
|
||||||
|
|
||||||
|
function signed(value: number, suffix = ""): string {
|
||||||
|
return `${value > 0 ? "+" : ""}${value}${suffix}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function identityAll(curves: AdvancedRecipe["curve"]): boolean {
|
||||||
|
return (
|
||||||
|
isIdentityCurve(curves.rgb) &&
|
||||||
|
isIdentityCurve(curves.red) &&
|
||||||
|
isIdentityCurve(curves.green) &&
|
||||||
|
isIdentityCurve(curves.blue)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const BW_FILTER_NAMES: Record<string, string> = {
|
||||||
|
yellow: "yellow",
|
||||||
|
orange: "orange",
|
||||||
|
red: "red",
|
||||||
|
green: "green",
|
||||||
|
blue: "blue",
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Build the read-only summary and the quick-editor seed for a stored recipe. */
|
||||||
|
export function advancedEditViewFor(
|
||||||
|
json: string | null | undefined,
|
||||||
|
): AdvancedEditView | null {
|
||||||
|
const recipe = parseAdvancedRecipe(json);
|
||||||
|
if (!recipe) return null;
|
||||||
|
|
||||||
|
const light: AdvancedEditItem[] = [];
|
||||||
|
const color: AdvancedEditItem[] = [];
|
||||||
|
const detail: AdvancedEditItem[] = [];
|
||||||
|
const geometry: AdvancedEditItem[] = [];
|
||||||
|
|
||||||
|
if (recipe.exposure !== 0) {
|
||||||
|
light.push({
|
||||||
|
label: "Exposure",
|
||||||
|
value: signed(recipe.exposure, " EV"),
|
||||||
|
preview: { key: "exposure", amount: recipe.exposure },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (recipe.contrast !== 0) {
|
||||||
|
light.push({
|
||||||
|
label: "Contrast",
|
||||||
|
value: signed(recipe.contrast),
|
||||||
|
preview: { key: "contrast", amount: recipe.contrast },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (recipe.highlights !== 0) {
|
||||||
|
light.push({
|
||||||
|
label: "Highlights",
|
||||||
|
value: signed(recipe.highlights),
|
||||||
|
preview: { key: "highlights", amount: recipe.highlights },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (recipe.shadows !== 0) {
|
||||||
|
light.push({
|
||||||
|
label: "Shadows",
|
||||||
|
value: signed(recipe.shadows),
|
||||||
|
preview: { key: "shadows", amount: recipe.shadows },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (recipe.whites !== 0) {
|
||||||
|
light.push({
|
||||||
|
label: "Whites",
|
||||||
|
value: signed(recipe.whites),
|
||||||
|
preview: { key: "whites", amount: recipe.whites },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (recipe.blacks !== 0) {
|
||||||
|
light.push({
|
||||||
|
label: "Blacks",
|
||||||
|
value: signed(recipe.blacks),
|
||||||
|
preview: { key: "blacks", amount: recipe.blacks },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (recipe.texture !== 0) light.push({ label: "Texture", value: signed(recipe.texture) });
|
||||||
|
if (recipe.clarity !== 0) {
|
||||||
|
light.push({
|
||||||
|
label: "Clarity",
|
||||||
|
value: signed(recipe.clarity),
|
||||||
|
preview: { key: "clarity", amount: recipe.clarity },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (recipe.dehaze !== 0) {
|
||||||
|
light.push({
|
||||||
|
label: "Dehaze",
|
||||||
|
value: signed(recipe.dehaze),
|
||||||
|
preview: { key: "dehaze", amount: recipe.dehaze },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (recipe.temp !== 0) {
|
||||||
|
color.push({
|
||||||
|
label: "Temperature",
|
||||||
|
value: signed(recipe.temp),
|
||||||
|
preview: { key: "temperature", amount: recipe.temp },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (recipe.tint !== 0) {
|
||||||
|
color.push({
|
||||||
|
label: "Tint",
|
||||||
|
value: signed(recipe.tint),
|
||||||
|
preview: { key: "tint", amount: recipe.tint },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (recipe.bw) {
|
||||||
|
color.push({
|
||||||
|
label: "Black & white",
|
||||||
|
value: "On",
|
||||||
|
preview: { key: "saturation", amount: -100 },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (recipe.vibrance !== 0) {
|
||||||
|
color.push({
|
||||||
|
label: "Vibrance",
|
||||||
|
value: signed(recipe.vibrance),
|
||||||
|
preview: { key: "vibrance", amount: recipe.vibrance },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (recipe.saturation !== 0) {
|
||||||
|
color.push({
|
||||||
|
label: "Saturation",
|
||||||
|
value: signed(recipe.saturation),
|
||||||
|
preview: { key: "saturation", amount: recipe.saturation },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (!identityAll(recipe.curve)) color.push({ label: "Curve", value: "Edited" });
|
||||||
|
if (!isNeutralBandList(recipe.hsl.hue) || !isNeutralBandList(recipe.hsl.sat) || !isNeutralBandList(recipe.hsl.lum)) {
|
||||||
|
color.push({ label: "Colour mixer", value: "Edited" });
|
||||||
|
}
|
||||||
|
if (recipe.grading.shadows > 0 || recipe.grading.highlights > 0) {
|
||||||
|
color.push({ label: "Colour grading", value: "On" });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (recipe.sharpen.amount !== 0) {
|
||||||
|
detail.push({
|
||||||
|
label: "Sharpen",
|
||||||
|
value: String(recipe.sharpen.amount),
|
||||||
|
preview: { key: "sharpen", amount: recipe.sharpen.amount },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (recipe.noise.luminance !== 0) {
|
||||||
|
detail.push({
|
||||||
|
label: "Noise reduction",
|
||||||
|
value: String(recipe.noise.luminance),
|
||||||
|
preview: { key: "noiseReduction", amount: recipe.noise.luminance },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (recipe.vignette.amount !== 0) {
|
||||||
|
detail.push({
|
||||||
|
label: "Vignette",
|
||||||
|
value: signed(recipe.vignette.amount),
|
||||||
|
preview: { key: "vignette", amount: recipe.vignette.amount },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (recipe.grain.amount !== 0) {
|
||||||
|
detail.push({
|
||||||
|
label: "Grain",
|
||||||
|
value: String(recipe.grain.amount),
|
||||||
|
preview: { key: "grain", amount: recipe.grain.amount },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!isDefaultCrop(recipe.crop)) {
|
||||||
|
if (recipe.crop.quarter !== 0) {
|
||||||
|
geometry.push({ label: "Rotate", value: `${Math.round(recipe.crop.quarter) * 90}°` });
|
||||||
|
}
|
||||||
|
if (recipe.crop.angle !== 0) {
|
||||||
|
geometry.push({ label: "Straighten", value: signed(round(recipe.crop.angle, 1), "°") });
|
||||||
|
}
|
||||||
|
if (recipe.crop.w < 0.999 || recipe.crop.h < 0.999) {
|
||||||
|
geometry.push({
|
||||||
|
label: "Crop",
|
||||||
|
value: `${Math.round(recipe.crop.w * 100)}% × ${Math.round(recipe.crop.h * 100)}%`,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
if (recipe.crop.flipH || recipe.crop.flipV) {
|
||||||
|
geometry.push({
|
||||||
|
label: "Flip",
|
||||||
|
value: recipe.crop.flipH && recipe.crop.flipV ? "Both" : recipe.crop.flipH ? "Horizontal" : "Vertical",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const onlyAdvanced: string[] = [];
|
||||||
|
if (recipe.texture !== 0) onlyAdvanced.push("Texture");
|
||||||
|
if (recipe.bw && recipe.bwFilter !== "none") {
|
||||||
|
onlyAdvanced.push(`${BW_FILTER_NAMES[recipe.bwFilter] ?? "Coloured"} black & white filter`);
|
||||||
|
}
|
||||||
|
if (recipe.sharpen.radius !== 1 || recipe.sharpen.detail !== 25) {
|
||||||
|
onlyAdvanced.push("Sharpening radius and detail");
|
||||||
|
}
|
||||||
|
if (recipe.noise.detail !== 50) onlyAdvanced.push("Noise detail");
|
||||||
|
if (recipe.vignette.midpoint !== 50 || recipe.vignette.feather !== 50) {
|
||||||
|
onlyAdvanced.push("Vignette midpoint and feather");
|
||||||
|
}
|
||||||
|
if (recipe.grain.size !== 25 || recipe.grain.roughness !== 50) {
|
||||||
|
onlyAdvanced.push("Grain size and roughness");
|
||||||
|
}
|
||||||
|
if (!isNeutralBandList(recipe.hsl.hue) || !isNeutralBandList(recipe.hsl.sat) || !isNeutralBandList(recipe.hsl.lum)) {
|
||||||
|
onlyAdvanced.push("Colour mixer");
|
||||||
|
}
|
||||||
|
if (recipe.grading.shadows > 0 || recipe.grading.highlights > 0) {
|
||||||
|
onlyAdvanced.push("Colour grading");
|
||||||
|
}
|
||||||
|
if (
|
||||||
|
!isIdentityCurve(recipe.curve.red) ||
|
||||||
|
!isIdentityCurve(recipe.curve.green) ||
|
||||||
|
!isIdentityCurve(recipe.curve.blue)
|
||||||
|
) {
|
||||||
|
onlyAdvanced.push("Per-channel curves");
|
||||||
|
}
|
||||||
|
if (recipe.crop.flipH || recipe.crop.flipV) onlyAdvanced.push("Flip");
|
||||||
|
|
||||||
|
const caveats: string[] = [];
|
||||||
|
if (recipe.crop.w < 0.999 || recipe.crop.h < 0.999) {
|
||||||
|
caveats.push("The crop becomes the closest quick-editor aspect and zoom; nudge it to match exactly.");
|
||||||
|
}
|
||||||
|
if (Math.abs(recipe.crop.angle) > PHOTO_ADJUSTMENT_LIMITS.straighten) {
|
||||||
|
caveats.push(`Straighten is limited to ±${PHOTO_ADJUSTMENT_LIMITS.straighten}° here.`);
|
||||||
|
}
|
||||||
|
|
||||||
|
const sections = [
|
||||||
|
{ title: "Light", items: light },
|
||||||
|
{ title: "Colour", items: color },
|
||||||
|
{ title: "Detail", items: detail },
|
||||||
|
{ title: "Crop", items: geometry },
|
||||||
|
].filter((section) => section.items.length > 0);
|
||||||
|
|
||||||
|
return {
|
||||||
|
sections,
|
||||||
|
onlyAdvanced,
|
||||||
|
caveats,
|
||||||
|
seed: advancedToQuickAdjustments(recipe),
|
||||||
|
};
|
||||||
|
}
|
||||||
+14
-2
@@ -24,6 +24,12 @@ export interface BridgeTokenPayload {
|
|||||||
kind: "login" | "service";
|
kind: "login" | "service";
|
||||||
/** Unix seconds. */
|
/** Unix seconds. */
|
||||||
exp: number;
|
exp: number;
|
||||||
|
/**
|
||||||
|
* Browser-facing URL to return to after editing. Captured from the request
|
||||||
|
* that opened the editor, because the server-to-server origin is not the
|
||||||
|
* address the user's browser used.
|
||||||
|
*/
|
||||||
|
ret?: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const BRIDGE_LOGIN_TTL_SECONDS = 10 * 60;
|
export const BRIDGE_LOGIN_TTL_SECONDS = 10 * 60;
|
||||||
@@ -108,9 +114,15 @@ export function verifyBridgeToken(
|
|||||||
return payload as BridgeTokenPayload;
|
return payload as BridgeTokenPayload;
|
||||||
}
|
}
|
||||||
|
|
||||||
/** Where the advanced editor sends a user back to after finishing. */
|
/**
|
||||||
|
* Where the advanced editor sends a user back to after finishing. Prefer the
|
||||||
|
* configured public origin; `NEXTAUTH_URL` is only a fallback because compose
|
||||||
|
* defaults it to localhost.
|
||||||
|
*/
|
||||||
export function bridgeReturnUrl(eventId: string): string | null {
|
export function bridgeReturnUrl(eventId: string): string | null {
|
||||||
const origin = process.env.NEXTAUTH_URL?.trim();
|
const origin = (
|
||||||
|
process.env.PUBLIC_ORIGIN?.trim() || process.env.NEXTAUTH_URL?.trim()
|
||||||
|
);
|
||||||
if (!origin) return null;
|
if (!origin) return null;
|
||||||
return `${origin.replace(/\/+$/, "")}/events/${eventId}`;
|
return `${origin.replace(/\/+$/, "")}/events/${eventId}`;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,160 @@
|
|||||||
|
import { createHash } from "node:crypto";
|
||||||
|
import { createWriteStream } from "node:fs";
|
||||||
|
import { mkdir, unlink } from "node:fs/promises";
|
||||||
|
import path from "node:path";
|
||||||
|
import { Readable, Transform } from "node:stream";
|
||||||
|
import { pipeline } from "node:stream/promises";
|
||||||
|
import type { NextRequest } from "next/server";
|
||||||
|
import {
|
||||||
|
addEventPhoto,
|
||||||
|
findEventPhotoByChecksum,
|
||||||
|
isUniqueViolation,
|
||||||
|
} from "@/db/events";
|
||||||
|
import {
|
||||||
|
MAX_EVENT_PHOTO_BYTES,
|
||||||
|
eventPhotoKindFor,
|
||||||
|
eventPhotoMimeFor,
|
||||||
|
eventPhotoPath,
|
||||||
|
sanitizePhotoFilename,
|
||||||
|
storedNameForEventPhoto,
|
||||||
|
} from "@/lib/event-photos";
|
||||||
|
import { errorResponse, jsonResponse } from "@/lib/http";
|
||||||
|
import { mediaStorage } from "@/lib/media-storage";
|
||||||
|
import { uuidv7 } from "@/lib/uuid";
|
||||||
|
|
||||||
|
class PhotoTooLarge extends Error {}
|
||||||
|
|
||||||
|
function publicPhoto(photo: {
|
||||||
|
id: string;
|
||||||
|
folderId: string;
|
||||||
|
filename: string;
|
||||||
|
mimeType: string;
|
||||||
|
sizeBytes: number;
|
||||||
|
kind: "raw" | "image";
|
||||||
|
createdAt: Date;
|
||||||
|
}) {
|
||||||
|
return {
|
||||||
|
id: photo.id,
|
||||||
|
folderId: photo.folderId,
|
||||||
|
filename: photo.filename,
|
||||||
|
mimeType: photo.mimeType,
|
||||||
|
sizeBytes: photo.sizeBytes,
|
||||||
|
kind: photo.kind,
|
||||||
|
createdAt: photo.createdAt,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A single photo is the raw request body (not multipart), so a 100 MB RAW file
|
||||||
|
* streams straight to disk instead of being buffered in memory. The filename is
|
||||||
|
* passed as a query parameter because headers cannot carry arbitrary Unicode.
|
||||||
|
* The SHA-256 is computed while streaming and dedupes a re-upload per folder.
|
||||||
|
*
|
||||||
|
* The caller owns the access check and picks the destination folder: the event
|
||||||
|
* page uploads through `/api/events/:id/photos`, while the folder route is kept
|
||||||
|
* for older links and direct API use.
|
||||||
|
*/
|
||||||
|
export async function uploadEventPhoto(
|
||||||
|
req: NextRequest,
|
||||||
|
input: { eventId: string; folderId: string; uploaderId: string },
|
||||||
|
): Promise<Response> {
|
||||||
|
// Photos are only ever written to the configured media storage share, so refuse
|
||||||
|
// before reading a single byte when that destination is not ready.
|
||||||
|
const storage = await mediaStorage();
|
||||||
|
if (!storage.ok) return errorResponse(503, storage.message);
|
||||||
|
|
||||||
|
const suppliedName = req.nextUrl.searchParams.get("name");
|
||||||
|
if (!suppliedName) return errorResponse(400, "a filename is required");
|
||||||
|
const filename = sanitizePhotoFilename(suppliedName);
|
||||||
|
const kind = eventPhotoKindFor(filename);
|
||||||
|
if (!kind) {
|
||||||
|
return errorResponse(
|
||||||
|
415,
|
||||||
|
"only photo files are accepted (JPEG, PNG, WebP, HEIC, TIFF, PSD or camera RAW)",
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const declaredLength = Number(req.headers.get("content-length") ?? 0);
|
||||||
|
if (declaredLength > MAX_EVENT_PHOTO_BYTES) {
|
||||||
|
return errorResponse(413, "that photo is larger than 200 MB");
|
||||||
|
}
|
||||||
|
if (!req.body) return errorResponse(400, "a file body is required");
|
||||||
|
|
||||||
|
const photoId = uuidv7();
|
||||||
|
const storedName = storedNameForEventPhoto(
|
||||||
|
input.eventId,
|
||||||
|
photoId,
|
||||||
|
filename,
|
||||||
|
);
|
||||||
|
const destination = eventPhotoPath(storage.root, storedName);
|
||||||
|
await mkdir(path.dirname(destination), { recursive: true });
|
||||||
|
|
||||||
|
const hash = createHash("sha256");
|
||||||
|
let size = 0;
|
||||||
|
const meter = new Transform({
|
||||||
|
transform(chunk: Buffer, _encoding, callback) {
|
||||||
|
size += chunk.length;
|
||||||
|
if (size > MAX_EVENT_PHOTO_BYTES) {
|
||||||
|
callback(new PhotoTooLarge());
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
hash.update(chunk);
|
||||||
|
callback(null, chunk);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
try {
|
||||||
|
await pipeline(
|
||||||
|
Readable.from(req.body as unknown as AsyncIterable<Uint8Array>),
|
||||||
|
meter,
|
||||||
|
createWriteStream(destination, { flags: "wx" }),
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
await unlink(destination).catch(() => undefined);
|
||||||
|
if (error instanceof PhotoTooLarge) {
|
||||||
|
return errorResponse(413, "that photo is larger than 200 MB");
|
||||||
|
}
|
||||||
|
return errorResponse(500, "the upload did not complete");
|
||||||
|
}
|
||||||
|
|
||||||
|
if (size === 0) {
|
||||||
|
await unlink(destination).catch(() => undefined);
|
||||||
|
return errorResponse(400, "the uploaded file was empty");
|
||||||
|
}
|
||||||
|
|
||||||
|
const checksumSha256 = hash.digest("hex");
|
||||||
|
const existing = await findEventPhotoByChecksum(
|
||||||
|
input.folderId,
|
||||||
|
checksumSha256,
|
||||||
|
);
|
||||||
|
if (existing) {
|
||||||
|
await unlink(destination).catch(() => undefined);
|
||||||
|
return jsonResponse({ photo: publicPhoto(existing), duplicate: true });
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const photo = await addEventPhoto({
|
||||||
|
folderId: input.folderId,
|
||||||
|
uploaderId: input.uploaderId,
|
||||||
|
filename,
|
||||||
|
mimeType: eventPhotoMimeFor(filename),
|
||||||
|
sizeBytes: size,
|
||||||
|
storedName,
|
||||||
|
checksumSha256,
|
||||||
|
kind,
|
||||||
|
});
|
||||||
|
return jsonResponse({ photo: publicPhoto(photo) }, 201);
|
||||||
|
} catch (error) {
|
||||||
|
await unlink(destination).catch(() => undefined);
|
||||||
|
if (isUniqueViolation(error)) {
|
||||||
|
const raced = await findEventPhotoByChecksum(
|
||||||
|
input.folderId,
|
||||||
|
checksumSha256,
|
||||||
|
);
|
||||||
|
if (raced) {
|
||||||
|
return jsonResponse({ photo: publicPhoto(raced), duplicate: true });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -160,6 +160,19 @@ export function editedStoredNameForEventPhoto(
|
|||||||
return `events/${eventId}/edits/${photoId}.jpg`;
|
return `events/${eventId}/edits/${photoId}.jpg`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The advanced editor's own render. Kept apart from the final edited JPEG so
|
||||||
|
* the simple editor can layer its adjustments on top without compounding
|
||||||
|
* renders, and so re-saving in either editor keeps the other's work.
|
||||||
|
*/
|
||||||
|
export function advancedStoredNameForEventPhoto(
|
||||||
|
eventId: string,
|
||||||
|
photoId: string,
|
||||||
|
): string {
|
||||||
|
assertEventPhotoIds(eventId, photoId);
|
||||||
|
return `events/${eventId}/edits/${photoId}-advanced.jpg`;
|
||||||
|
}
|
||||||
|
|
||||||
/** Lazily generated small grid thumbnail of the untouched original. */
|
/** Lazily generated small grid thumbnail of the untouched original. */
|
||||||
export function thumbStoredNameForEventPhoto(
|
export function thumbStoredNameForEventPhoto(
|
||||||
eventId: string,
|
eventId: string,
|
||||||
@@ -196,6 +209,19 @@ export function bridgeThumbStoredNameForEventPhoto(
|
|||||||
return `events/${eventId}/previews/${photoId}-bridge-thumb.jpg`;
|
return `events/${eventId}/previews/${photoId}-bridge-thumb.jpg`;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cached grid thumbnail of a photo's saved edit. Kept apart from the original
|
||||||
|
* thumbnail so the editor can reopen either, and refreshed whenever the edited
|
||||||
|
* JPEG is re-rendered.
|
||||||
|
*/
|
||||||
|
export function bridgeEditedThumbStoredNameForEventPhoto(
|
||||||
|
eventId: string,
|
||||||
|
photoId: string,
|
||||||
|
): string {
|
||||||
|
assertEventPhotoIds(eventId, photoId);
|
||||||
|
return `events/${eventId}/previews/${photoId}-bridge-thumb-edited.jpg`;
|
||||||
|
}
|
||||||
|
|
||||||
function assertEventPhotoIds(eventId: string, photoId: string): void {
|
function assertEventPhotoIds(eventId: string, photoId: string): void {
|
||||||
const safeId = /^[A-Za-z0-9_-]+$/;
|
const safeId = /^[A-Za-z0-9_-]+$/;
|
||||||
if (!safeId.test(eventId) || !safeId.test(photoId)) {
|
if (!safeId.test(eventId) || !safeId.test(photoId)) {
|
||||||
|
|||||||
+115
-1
@@ -10,13 +10,14 @@
|
|||||||
*/
|
*/
|
||||||
|
|
||||||
import { execFile } from "node:child_process";
|
import { execFile } from "node:child_process";
|
||||||
import { mkdtemp, rm } from "node:fs/promises";
|
import { mkdtemp, readdir, rm, symlink } from "node:fs/promises";
|
||||||
import { tmpdir } from "node:os";
|
import { tmpdir } from "node:os";
|
||||||
import path from "node:path";
|
import path from "node:path";
|
||||||
import { promisify } from "node:util";
|
import { promisify } from "node:util";
|
||||||
import sharp from "sharp";
|
import sharp from "sharp";
|
||||||
import {
|
import {
|
||||||
applyPhotoAdjustmentsToRgba,
|
applyPhotoAdjustmentsToRgba,
|
||||||
|
defaultPhotoAdjustments,
|
||||||
type PhotoAdjustments,
|
type PhotoAdjustments,
|
||||||
} from "./photo-adjustments";
|
} from "./photo-adjustments";
|
||||||
import { cropInterleavedRgb, cropRectForCanvas } from "./photo-geometry";
|
import { cropInterleavedRgb, cropRectForCanvas } from "./photo-geometry";
|
||||||
@@ -90,6 +91,119 @@ export interface RenderedPhoto {
|
|||||||
height: number;
|
height: number;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Cameras store one or more JPEG previews inside every RAW file; a full-size
|
||||||
|
* NEF preview is a ~1 MB JPEG written next to the symlink by exiv2 in about
|
||||||
|
* 10 ms. That is roughly seventy times faster than demosaicing the sensor data
|
||||||
|
* for a 640 px tile, so thumbnails try the preview first and only fall back to
|
||||||
|
* LibRaw when the camera embedded nothing big enough.
|
||||||
|
*/
|
||||||
|
async function extractEmbeddedPreview(
|
||||||
|
filePath: string,
|
||||||
|
minDimension: number,
|
||||||
|
): Promise<{ path: string; cleanup: () => Promise<void> } | null> {
|
||||||
|
const directory = await mkdtemp(path.join(tmpdir(), "glenloch-preview-"));
|
||||||
|
const cleanup = () => rm(directory, { recursive: true, force: true });
|
||||||
|
const link = path.join(
|
||||||
|
directory,
|
||||||
|
`source${path.extname(filePath) || ".raw"}`,
|
||||||
|
);
|
||||||
|
|
||||||
|
try {
|
||||||
|
// exiv2 writes the previews beside the file it is given. A symlink keeps
|
||||||
|
// the original (read-only) untouched and the output in the temp directory.
|
||||||
|
await symlink(filePath, link);
|
||||||
|
// A non-zero exit is normal when some embedded preview cannot be re-encoded
|
||||||
|
// (for example a TIFF thumbnail); the files that did land are inspected.
|
||||||
|
await execFileAsync("exiv2", ["-ep", link], { timeout: 30_000 }).catch(
|
||||||
|
() => undefined,
|
||||||
|
);
|
||||||
|
|
||||||
|
let best: { path: string; longEdge: number } | undefined;
|
||||||
|
for (const entry of await readdir(directory)) {
|
||||||
|
if (!/-preview\d+\.jpe?g$/i.test(entry)) continue;
|
||||||
|
const candidate = path.join(directory, entry);
|
||||||
|
try {
|
||||||
|
const metadata = await sharp(candidate, { failOn: "none" }).metadata();
|
||||||
|
const longEdge = Math.max(metadata.width ?? 0, metadata.height ?? 0);
|
||||||
|
if (longEdge < minDimension) continue;
|
||||||
|
if (!best || longEdge > best.longEdge) best = { path: candidate, longEdge };
|
||||||
|
} catch {
|
||||||
|
// Not a readable JPEG; try the next preview.
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!best) {
|
||||||
|
await cleanup().catch(() => undefined);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
return { path: best.path, cleanup };
|
||||||
|
} catch {
|
||||||
|
await cleanup().catch(() => undefined);
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Small grid thumbnail. RAW files use the camera's embedded preview when it is
|
||||||
|
* large enough; everything else (and RAW files without one) goes through the
|
||||||
|
* regular render pipeline.
|
||||||
|
*/
|
||||||
|
export async function renderPhotoThumbnail(input: {
|
||||||
|
filePath: string;
|
||||||
|
kind: "raw" | "image";
|
||||||
|
maxDimension: number;
|
||||||
|
quality?: number;
|
||||||
|
}): Promise<Buffer> {
|
||||||
|
if (input.kind === "raw") {
|
||||||
|
const preview = await extractEmbeddedPreview(
|
||||||
|
input.filePath,
|
||||||
|
input.maxDimension,
|
||||||
|
);
|
||||||
|
if (preview) {
|
||||||
|
try {
|
||||||
|
return await sharp(preview.path, {
|
||||||
|
failOn: "none",
|
||||||
|
limitInputPixels: 500_000_000,
|
||||||
|
})
|
||||||
|
.autoOrient()
|
||||||
|
.toColourspace("srgb")
|
||||||
|
.resize({
|
||||||
|
width: input.maxDimension,
|
||||||
|
height: input.maxDimension,
|
||||||
|
fit: "inside",
|
||||||
|
withoutEnlargement: true,
|
||||||
|
})
|
||||||
|
.jpeg({ quality: input.quality ?? 72, mozjpeg: true })
|
||||||
|
.toBuffer();
|
||||||
|
} finally {
|
||||||
|
await preview.cleanup().catch(() => undefined);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (input.kind === "image") {
|
||||||
|
return sharp(input.filePath, { failOn: "none", limitInputPixels: 500_000_000 })
|
||||||
|
.autoOrient()
|
||||||
|
.resize({
|
||||||
|
width: input.maxDimension,
|
||||||
|
height: input.maxDimension,
|
||||||
|
fit: "inside",
|
||||||
|
withoutEnlargement: true,
|
||||||
|
})
|
||||||
|
.jpeg({ quality: input.quality ?? 72 })
|
||||||
|
.toBuffer();
|
||||||
|
}
|
||||||
|
|
||||||
|
const rendered = await renderPhotoJpeg({
|
||||||
|
filePath: input.filePath,
|
||||||
|
kind: input.kind,
|
||||||
|
adjustments: defaultPhotoAdjustments(),
|
||||||
|
maxDimension: input.maxDimension,
|
||||||
|
});
|
||||||
|
return rendered.data;
|
||||||
|
}
|
||||||
|
|
||||||
/** Source dimensions after applying the EXIF orientation the browser sees. */
|
/** Source dimensions after applying the EXIF orientation the browser sees. */
|
||||||
async function orientedDimensions(
|
async function orientedDimensions(
|
||||||
filePath: string,
|
filePath: string,
|
||||||
|
|||||||
@@ -42,4 +42,18 @@ describe("respond tokens", () => {
|
|||||||
expect(url.startsWith("https://media.test/respond?t=")).toBe(true);
|
expect(url.startsWith("https://media.test/respond?t=")).toBe(true);
|
||||||
expect(url.endsWith("&a=decline")).toBe(true);
|
expect(url.endsWith("&a=decline")).toBe(true);
|
||||||
});
|
});
|
||||||
|
|
||||||
|
it("accepts the alternative-Sunday action", async () => {
|
||||||
|
const { token } = await signRespondToken({
|
||||||
|
...input,
|
||||||
|
action: "alternative",
|
||||||
|
});
|
||||||
|
const payload = await verifyRespondToken(token);
|
||||||
|
expect(payload?.action).toBe("alternative");
|
||||||
|
expect(
|
||||||
|
respondUrl("https://media.test", token, "alternative").endsWith(
|
||||||
|
"&a=alternative",
|
||||||
|
),
|
||||||
|
).toBe(true);
|
||||||
|
});
|
||||||
});
|
});
|
||||||
|
|||||||
+7
-4
@@ -1,11 +1,13 @@
|
|||||||
/**
|
/**
|
||||||
* Signed respond tokens — unit E4 (ARCHITECTURE §5.6).
|
* Signed respond tokens — unit E4 (ARCHITECTURE §5.6).
|
||||||
*
|
*
|
||||||
* Every assignment email carries two single-purpose links:
|
* Every assignment email carries single-purpose links:
|
||||||
* /respond?t=<jwt>&a=confirm | /respond?t=<jwt>&a=decline
|
* /respond?t=<jwt>&a=confirm | &a=decline | &a=alternative
|
||||||
*
|
*
|
||||||
* The JWT binds the assignment and volunteer (`{ assignmentId, userId, action,
|
* The JWT binds the assignment and volunteer (`{ assignmentId, userId, action,
|
||||||
* jti }`, HS256, +14d) so a link cannot be re-pointed at another assignment.
|
* jti }`, HS256, +14d) so a link cannot be re-pointed at another assignment.
|
||||||
|
* `alternative` opens the "propose another Sunday" page; it never changes the
|
||||||
|
* assignment, it records a proposal for a coordinator.
|
||||||
* Single use is recorded by `jti` in `used_tokens` by the data layer.
|
* Single use is recorded by `jti` in `used_tokens` by the data layer.
|
||||||
*/
|
*/
|
||||||
|
|
||||||
@@ -19,7 +21,8 @@ const SECRET = new TextEncoder().encode(
|
|||||||
"media-team-hub-dev-insecure-secret",
|
"media-team-hub-dev-insecure-secret",
|
||||||
);
|
);
|
||||||
|
|
||||||
export type RespondAction = "confirm" | "decline";
|
export type DecisionAction = "confirm" | "decline";
|
||||||
|
export type RespondAction = DecisionAction | "alternative";
|
||||||
|
|
||||||
export interface RespondTokenPayload {
|
export interface RespondTokenPayload {
|
||||||
assignmentId: string;
|
assignmentId: string;
|
||||||
@@ -66,7 +69,7 @@ export async function verifyRespondToken(
|
|||||||
if (
|
if (
|
||||||
typeof assignmentId !== "string" ||
|
typeof assignmentId !== "string" ||
|
||||||
typeof userId !== "string" ||
|
typeof userId !== "string" ||
|
||||||
(action !== "confirm" && action !== "decline") ||
|
(action !== "confirm" && action !== "decline" && action !== "alternative") ||
|
||||||
typeof jti !== "string"
|
typeof jti !== "string"
|
||||||
) {
|
) {
|
||||||
return null;
|
return null;
|
||||||
|
|||||||
@@ -0,0 +1,22 @@
|
|||||||
|
import { describe, expect, it } from "vitest";
|
||||||
|
import { trainingGuideForRole } from "./training-guides";
|
||||||
|
|
||||||
|
describe("trainingGuideForRole", () => {
|
||||||
|
it("shows the administration guide to admins", () => {
|
||||||
|
expect(trainingGuideForRole("admin").key).toBe("admin");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows the coordinator guide to coordinators", () => {
|
||||||
|
expect(trainingGuideForRole("coordinator").key).toBe("coordinator");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("shows the volunteer guide to volunteers and trainees", () => {
|
||||||
|
expect(trainingGuideForRole("volunteer").key).toBe("user");
|
||||||
|
expect(trainingGuideForRole("trainee").key).toBe("user");
|
||||||
|
});
|
||||||
|
|
||||||
|
it("falls back to the volunteer guide without a role", () => {
|
||||||
|
expect(trainingGuideForRole(null).key).toBe("user");
|
||||||
|
expect(trainingGuideForRole(undefined).key).toBe("user");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
import type { SystemRole } from "@/auth/roles";
|
||||||
|
|
||||||
|
export type TrainingGuideKey = "admin" | "coordinator" | "user";
|
||||||
|
|
||||||
|
export interface TrainingGuide {
|
||||||
|
key: TrainingGuideKey;
|
||||||
|
href: string;
|
||||||
|
title: string;
|
||||||
|
audience: string;
|
||||||
|
description: string;
|
||||||
|
/** Not every guide has a PDF snapshot yet. */
|
||||||
|
pdfHref?: string;
|
||||||
|
pdfLabel?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const TRAINING_GUIDES: Record<TrainingGuideKey, TrainingGuide> = {
|
||||||
|
admin: {
|
||||||
|
key: "admin",
|
||||||
|
href: "/training/guides/admin",
|
||||||
|
title: "Platform administration guide",
|
||||||
|
audience: "Admins",
|
||||||
|
description:
|
||||||
|
"People and access, skill verification, positions, services and publishing, coverage, run sheets, email, notifications, backups, and exports.",
|
||||||
|
pdfHref: "/training/media-team-admin-guide.pdf",
|
||||||
|
pdfLabel: "Download admin PDF",
|
||||||
|
},
|
||||||
|
coordinator: {
|
||||||
|
key: "coordinator",
|
||||||
|
href: "/training/guides/coordinator",
|
||||||
|
title: "Coordinator guide",
|
||||||
|
audience: "Coordinators",
|
||||||
|
description:
|
||||||
|
"Building and publishing weeks, assignment replies, coverage and swaps, run sheets, events, announcements, and exports.",
|
||||||
|
pdfHref: "/training/media-team-coordinator-guide.pdf",
|
||||||
|
pdfLabel: "Download coordinator PDF",
|
||||||
|
},
|
||||||
|
user: {
|
||||||
|
key: "user",
|
||||||
|
href: "/training/guides/user",
|
||||||
|
title: "Volunteer guide",
|
||||||
|
audience: "Volunteers and trainees",
|
||||||
|
description:
|
||||||
|
"Signing in, your next serve, the schedule, availability, swaps, run sheets, events and media, training, profile, and reminders.",
|
||||||
|
pdfHref: "/training/media-team-user-guide.pdf",
|
||||||
|
pdfLabel: "Download volunteer PDF",
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
/** Admins get the admin guide, coordinators theirs, everyone else the volunteer guide. */
|
||||||
|
export function trainingGuideForRole(
|
||||||
|
role: SystemRole | null | undefined,
|
||||||
|
): TrainingGuide {
|
||||||
|
if (role === "admin") return TRAINING_GUIDES.admin;
|
||||||
|
if (role === "coordinator") return TRAINING_GUIDES.coordinator;
|
||||||
|
return TRAINING_GUIDES.user;
|
||||||
|
}
|
||||||
@@ -60,7 +60,7 @@ export async function sendWelcomeEmail(
|
|||||||
<a href="${link}" style="display:inline-block;padding:10px 16px;background:#932822;color:#fff;border-radius:6px;text-decoration:none;">Sign in</a>
|
<a href="${link}" style="display:inline-block;padding:10px 16px;background:#932822;color:#fff;border-radius:6px;text-decoration:none;">Sign in</a>
|
||||||
</p>
|
</p>
|
||||||
<p style="font-size: 12px; color: #6b7280;">
|
<p style="font-size: 12px; color: #6b7280;">
|
||||||
The link expires in 10 minutes and works once. If it has expired, open the
|
The link expires in 7 days and works once. If it has expired, open the
|
||||||
sign-in page and request a fresh link with this email address. After
|
sign-in page and request a fresh link with this email address. After
|
||||||
signing in you can set a password from your profile.
|
signing in you can set a password from your profile.
|
||||||
</p>
|
</p>
|
||||||
@@ -75,7 +75,7 @@ export async function sendWelcomeEmail(
|
|||||||
`Sign in: ${user.email}`,
|
`Sign in: ${user.email}`,
|
||||||
`Username: ${user.username || user.email}`,
|
`Username: ${user.username || user.email}`,
|
||||||
"",
|
"",
|
||||||
`Open this link to sign in (expires in 10 minutes, single use):`,
|
`Open this link to sign in (expires in 7 days, single use):`,
|
||||||
url,
|
url,
|
||||||
"",
|
"",
|
||||||
"If it has expired, open the sign-in page and request a fresh link with this email address. After signing in you can set a password from your profile.",
|
"If it has expired, open the sign-in page and request a fresh link with this email address. After signing in you can set a password from your profile.",
|
||||||
|
|||||||
Reference in New Issue
Block a user