merge: merge codex/immich-redaktionsportal into main
This commit is contained in:
commit
ab8c035d99
185 files changed
+37195
-1
No files matched your search
@@ -0,0 +1,22 @@
|
|||||||
|
# Portal database (separate from Immich)
|
||||||
|
DATABASE_URL=postgres://portal:change-me@postgres:5432/portal
|
||||||
|
|
||||||
|
# Better Auth
|
||||||
|
BETTER_AUTH_SECRET=replace-with-a-long-random-secret
|
||||||
|
BETTER_AUTH_URL=http://localhost:3000
|
||||||
|
|
||||||
|
# Internal Immich API access; never expose these values to browsers
|
||||||
|
IMMICH_BASE_URL=http://immich-server:2283
|
||||||
|
IMMICH_API_KEY=replace-with-a-restricted-immich-api-key
|
||||||
|
|
||||||
|
# SMTP
|
||||||
|
SMTP_HOST=smtp.example.com
|
||||||
|
SMTP_PORT=587
|
||||||
|
SMTP_USER=portal@example.com
|
||||||
|
SMTP_PASSWORD=replace-with-an-smtp-password
|
||||||
|
SMTP_FROM=portal@example.com
|
||||||
|
|
||||||
|
# Legal pages managed outside the application
|
||||||
|
LEGAL_IMPRINT_URL=https://example.com/impressum
|
||||||
|
LEGAL_PRIVACY_URL=https://example.com/datenschutz
|
||||||
|
LEGAL_TERMS_URL=https://example.com/nutzungsbedingungen
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
name: CI Quality Gates
|
||||||
|
|
||||||
|
on:
|
||||||
|
push:
|
||||||
|
branches: [main, "codex/**"]
|
||||||
|
pull_request:
|
||||||
|
branches: [main]
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
quality-gates:
|
||||||
|
name: Lint, Typecheck, Unit Tests & Build
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
|
||||||
|
services:
|
||||||
|
postgres:
|
||||||
|
image: postgres:17-alpine
|
||||||
|
env:
|
||||||
|
POSTGRES_DB: portal_test
|
||||||
|
POSTGRES_USER: portal_test
|
||||||
|
POSTGRES_PASSWORD: portal_test_password
|
||||||
|
ports:
|
||||||
|
- 5432:5432
|
||||||
|
options: >-
|
||||||
|
--health-cmd pg_isready
|
||||||
|
--health-interval 5s
|
||||||
|
--health-timeout 5s
|
||||||
|
--health-retries 5
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout repository
|
||||||
|
uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Setup Node.js 24
|
||||||
|
uses: actions/setup-node@v4
|
||||||
|
with:
|
||||||
|
node-version: "24"
|
||||||
|
|
||||||
|
- name: Setup pnpm
|
||||||
|
uses: pnpm/action-setup@v4
|
||||||
|
with:
|
||||||
|
version: 10.34.5
|
||||||
|
|
||||||
|
- name: Get pnpm store directory
|
||||||
|
id: pnpm-cache
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
echo "STORE_PATH=$(pnpm store path --silent)" >> $GITHUB_OUTPUT
|
||||||
|
|
||||||
|
- name: Setup pnpm cache
|
||||||
|
uses: actions/cache@v4
|
||||||
|
with:
|
||||||
|
path: ${{ steps.pnpm-cache.outputs.STORE_PATH }}
|
||||||
|
key: ${{ runner.os }}-pnpm-store-${{ hashFiles('**/pnpm-lock.yaml') }}
|
||||||
|
restore-keys: |
|
||||||
|
${{ runner.os }}-pnpm-store-
|
||||||
|
|
||||||
|
- name: Install dependencies
|
||||||
|
run: pnpm install --frozen-lockfile
|
||||||
|
|
||||||
|
- name: Lint check
|
||||||
|
run: pnpm lint
|
||||||
|
|
||||||
|
- name: Typecheck
|
||||||
|
run: pnpm typecheck
|
||||||
|
|
||||||
|
- name: Unit and Integration Tests
|
||||||
|
env:
|
||||||
|
DATABASE_URL: postgres://portal_test:portal_test_password@localhost:5432/portal_test
|
||||||
|
run: pnpm test
|
||||||
|
|
||||||
|
- name: Next.js Production Build
|
||||||
|
env:
|
||||||
|
DATABASE_URL: postgres://portal_test:portal_test_password@localhost:5432/portal_test
|
||||||
|
BETTER_AUTH_SECRET: ci-testing-secret-key-32-characters-min
|
||||||
|
BETTER_AUTH_URL: http://localhost:3000
|
||||||
|
IMMICH_BASE_URL: http://localhost:2283
|
||||||
|
IMMICH_API_KEY: ci-test-immich-api-key
|
||||||
|
SMTP_HOST: localhost
|
||||||
|
SMTP_PORT: 587
|
||||||
|
SMTP_USER: portal@localhost
|
||||||
|
SMTP_PASSWORD: ci-password
|
||||||
|
SMTP_FROM: portal@localhost
|
||||||
|
LEGAL_IMPRINT_URL: https://example.com/imprint
|
||||||
|
LEGAL_PRIVACY_URL: https://example.com/privacy
|
||||||
|
LEGAL_TERMS_URL: https://example.com/terms
|
||||||
|
run: pnpm build
|
||||||
|
|
||||||
|
- name: Build Docker Container
|
||||||
|
run: docker build -t portal-app:ci .
|
||||||
@@ -5,7 +5,9 @@ tmp/
|
|||||||
.env.*
|
.env.*
|
||||||
!.env.example
|
!.env.example
|
||||||
node_modules/
|
node_modules/
|
||||||
|
.pnpm-store/
|
||||||
.next/
|
.next/
|
||||||
dist/
|
dist/
|
||||||
coverage/
|
coverage/
|
||||||
|
*.tsbuildinfo
|
||||||
.DS_Store
|
.DS_Store
|
||||||
@@ -0,0 +1,177 @@
|
|||||||
|
# Task 9 — Authorized Original Streaming and Delivery Outcomes
|
||||||
|
|
||||||
|
## Delivered
|
||||||
|
|
||||||
|
- Added authenticated `POST /api/download-intents` and `GET /api/downloads/:downloadId/file` routes. Both derive the editorial scope exclusively from `requireActiveEditorial`; request payloads cannot supply editorial IDs or prices.
|
||||||
|
- Added a strict discriminated intent payload for `new_usage` versus `repeat_download`. Unknown/mixed fields, including client-controlled `editorialId` and `priceCents`, are rejected before accounting side effects. Responses expose only the download ID, same-origin file URL, server price, and billable flag.
|
||||||
|
- Added an atomic PostgreSQL claim for one owned `authorized` event. The conditional `authorized -> streaming` update commits before Immich is called, so concurrent GETs allow at most one upstream request. A same-editorial reused event returns a stable conflict; invalid, missing, and foreign-editorial IDs retain generic not-found behavior.
|
||||||
|
- Added unbuffered original streaming with exact byte accounting, upstream cancellation, contained cancellation rejections, safe upstream-reader cleanup, and exactly-once terminal settlement under local and database races.
|
||||||
|
- Added safe download response headers: `private, no-store`, syntactically validated media type and length, `nosniff`, and an attachment disposition with a control/path-separator-free ASCII fallback plus RFC 5987 UTF-8 `filename*`. No Immich URL, API key, or upstream-internal header is forwarded.
|
||||||
|
- Added the accessible German usage dialog to each catalog photo. Existing owned usages show `0,00 EUR`; a new usage shows the current server-read editorial price and requires a purpose. Only the dialog is a Client Component. Native dialog/radio/keyboard behavior, explicit focus, pending-state Escape handling, and visible focus styles are retained.
|
||||||
|
- The dialog creates one UUID only when a submission starts. It keeps that key through a failed retry, suppresses double-click requests, and resets the key only when the material selection/purpose changes or the action completes/closes.
|
||||||
|
- Added the editorial usage-history page and navigation. Its bounded, principal-scoped read model paginates immutable usage snapshots and includes every completed, interrupted, and failed-before-delivery attempt with filename, album, purpose, reference, date/time, bytes, attempt kind, outcome, and billable cents. It has German empty, pagination, and unavailable states.
|
||||||
|
- Voided usages are excluded from free-repeat authorization and prior-usage choices. Interrupted/completed original usages remain eligible for a new zero-cost repeat intent.
|
||||||
|
|
||||||
|
## Delivery state machine
|
||||||
|
|
||||||
|
1. Intent services create one immutable `authorized` event.
|
||||||
|
2. The file route conditionally claims `authorized -> streaming`, scoped by both `downloadId` and the authenticated `editorialId`.
|
||||||
|
3. A clean upstream close performs `streaming -> completed` with the exact enqueued byte count.
|
||||||
|
4. An upstream error or client cancellation after at least one byte performs `streaming -> interrupted`; the usage remains unchanged and can receive a new repeat intent.
|
||||||
|
5. An upstream error or cancellation before the first byte performs `streaming -> failed_before_delivery` with zero bytes.
|
||||||
|
6. For a `new_usage` failure before delivery, the same transaction changes the usage from `open|reopened -> voided` and appends `billable_usage_voided_before_delivery` to the audit log. The failed event and usage remain immutable/explainable; nothing is deleted.
|
||||||
|
7. For a repeat failure, the original usage is never mutated. The event alone records the failed attempt.
|
||||||
|
8. Every terminal repository update is conditional on `status = streaming`; competing completion/interruption/failure attempts therefore have at most one winner.
|
||||||
|
|
||||||
|
## Migration
|
||||||
|
|
||||||
|
- Added `drizzle/0003_stream_delivery.sql` with the durable `usage_billing_status = 'voided'` value.
|
||||||
|
- Generated `drizzle/meta/0003_snapshot.json` and updated `drizzle/meta/_journal.json`.
|
||||||
|
- `pnpm exec drizzle-kit check` reports `Everything's fine`.
|
||||||
|
- `pnpm exec drizzle-kit generate --name stream_delivery_final_noop` reports `No schema changes, nothing to migrate`.
|
||||||
|
- The deterministic migration contract verifies that 0003 adds the supported state and never deletes usage history.
|
||||||
|
|
||||||
|
## TDD evidence
|
||||||
|
|
||||||
|
### Initial streaming, routes, dialog, and migration RED
|
||||||
|
|
||||||
|
- Command: `pnpm test src/modules/downloads/stream.test.ts src/app/api/downloads/'[downloadId]'/file/route.test.ts src/app/api/download-intents/route.test.ts src/components/download/usage-dialog.test.tsx tests/db/download-delivery-migration-sql.test.ts`
|
||||||
|
- Result: 5 failed suites. The stream, both routes, dialog, and 0003 migration were absent; failures were module-resolution/ENOENT failures, as expected.
|
||||||
|
|
||||||
|
### Catalog and history RED
|
||||||
|
|
||||||
|
- Command: `pnpm test src/modules/albums/catalog-content.test.tsx src/app/redaktion/nutzungen/page.test.tsx`
|
||||||
|
- Result: 2 failed files. The catalog had no original-download action and the history page did not exist.
|
||||||
|
|
||||||
|
### Claimed-body cleanup RED/GREEN
|
||||||
|
|
||||||
|
- RED command: `pnpm test src/app/api/downloads/'[downloadId]'/file/route.test.ts -t 'upstream body cannot'`
|
||||||
|
- RED result: the route returned 503 for a locked upstream body but failed to terminally account for its already-claimed event.
|
||||||
|
- GREEN result after the scoped fix: 1 passed / 10 skipped. The route now cancels the upstream body best-effort and records the no-byte terminal outcome.
|
||||||
|
|
||||||
|
### Header-boundary hardening RED/GREEN
|
||||||
|
|
||||||
|
- RED command: `pnpm test src/app/api/downloads/'[downloadId]'/file/route.test.ts -t 'untrustworthy media|malformed Unicode'`
|
||||||
|
- RED result: 2 failed / 11 skipped. CR/LF in an upstream media type reached `Headers` and produced 503; a lone Unicode surrogate caused `encodeURIComponent` to throw.
|
||||||
|
- GREEN result: 2 passed / 11 skipped. Media-type optional whitespace is now restricted to HTTP space/tab, malformed values fall back to `application/octet-stream`, and malformed surrogate code units are replaced before RFC 5987 encoding.
|
||||||
|
|
||||||
|
### Focused GREEN
|
||||||
|
|
||||||
|
- Command: `pnpm typecheck && pnpm test src/modules/downloads/stream.test.ts src/app/api/downloads/'[downloadId]'/file/route.test.ts src/app/api/download-intents/route.test.ts src/components/download/usage-dialog.test.tsx src/modules/albums/catalog-content.test.tsx src/app/redaktion/nutzungen/page.test.tsx tests/db/download-delivery-migration-sql.test.ts`
|
||||||
|
- Result: typecheck passed; 7 files / 33 tests passed before the final route-handler build refactor.
|
||||||
|
- After isolating handler/test exports from Next route/page modules, the focused route/history set passed 3 files / 19 tests and lint passed.
|
||||||
|
|
||||||
|
### Real PostgreSQL tests
|
||||||
|
|
||||||
|
- Added `tests/db/download-delivery.test.ts`, unskipped, against PostgreSQL 17 via Testcontainers.
|
||||||
|
- It covers the concurrent authorized claim, new-use pre-byte void plus audit and repeat denial, repeat failure preservation, exactly-one competing terminal transition, and editorial-scoped terminal history.
|
||||||
|
- Command: `pnpm test tests/db/download-delivery.test.ts`
|
||||||
|
- Result: the suite failed before collecting/executing tests with `Could not find a working container runtime strategy`; 0 tests ran. This is an external Docker-runtime limitation, not a skipped application test.
|
||||||
|
|
||||||
|
## Final verification
|
||||||
|
|
||||||
|
- `pnpm test src tests/db/accounting-migration-sql.test.ts tests/db/download-delivery-migration-sql.test.ts` — 25 files / 157 tests passed.
|
||||||
|
- `pnpm typecheck` — passed.
|
||||||
|
- `pnpm lint` — passed.
|
||||||
|
- `pnpm exec drizzle-kit check` — passed.
|
||||||
|
- `pnpm exec drizzle-kit generate --name stream_delivery_final_noop` — no schema changes.
|
||||||
|
- `git diff --check` — passed.
|
||||||
|
- `pnpm exec next build --webpack` with the repository test environment — passed compilation, TypeScript, page-data collection, 14-page static generation, and build tracing. The intent route, file route, and usage-history page are dynamic server routes.
|
||||||
|
|
||||||
|
## Concern
|
||||||
|
|
||||||
|
- The five new PostgreSQL transition assertions could not execute locally because no container runtime is available. On a Docker-enabled host, run `pnpm test tests/db/download-delivery.test.ts` before release. The suite is unskipped and included in the normal full test command.
|
||||||
|
|
||||||
|
## Fix Round 1
|
||||||
|
|
||||||
|
### Review findings resolved
|
||||||
|
|
||||||
|
- Repeat intent creation, stream claim, and pre-first-byte void now lock the same usage row as their transaction mutex. A repeat is eligible only while the usage is non-voided and a `new_usage` event has already reached `completed|interrupted` with more than zero delivered bytes. This eligibility is rechecked for idempotent existing intents and again immediately before the conditional `authorized -> streaming` claim.
|
||||||
|
- Voiding a new usage preserves every audit/history row and terminally changes all still-`authorized` repeats for that usage to `failed_before_delivery`. A repeat discovered without valid delivery evidence is likewise retained and terminally invalidated instead of deleted. The usage-first lock order plus the conditional event update keeps concurrent claims and voids serializable and prevents a repeat from remaining claimable after a committed void.
|
||||||
|
- History attempt work and payload are globally bounded to 25 terminal events for the current 20-usage page. Exact PostgreSQL microsecond timestamp plus UUID keyset cursors provide stable continuation without a maximum attempt-page ceiling, hidden N+1 queries, or unbounded arrays. The cursor remains opaque in the URL, while editorial scope still comes exclusively from the authenticated principal.
|
||||||
|
- Each usage ledger entry now renders the immutable `price_cents` snapshot and its billing status even when no attempt has reached a terminal state. Effective `billableCents` remains separate, so a voided usage retains its historical price while being marked `Storniert` and nonbillable.
|
||||||
|
- The before-delivery void audit reads `previousValues.billingStatus` from the usage row locked in the same transaction. It therefore records `reopened` truthfully instead of hard-coding `open`.
|
||||||
|
- Dialog dates and history date/times share explicit `Europe/Berlin` formatters, making SSR and browser output independent of the host time zone.
|
||||||
|
|
||||||
|
### State-machine additions
|
||||||
|
|
||||||
|
1. `createRepeatDownload` locks editorial accounting and then the usage row, verifies an actually delivered original event, and only then returns or creates the authorized repeat.
|
||||||
|
2. `claimAuthorized` reads the scoped event, locks its usage row, revalidates non-voided/delivered-original eligibility, and finally performs the conditional claim. A competing claim still loses at the event transition.
|
||||||
|
3. `failBeforeDelivery` reads the streaming event, locks its usage row before the terminal transition, voids an eligible new usage, invalidates every outstanding authorized repeat, and writes the audit with the locked prior billing status in one transaction.
|
||||||
|
4. Completed, interrupted, and failed events remain terminal and immutable. No usage or delivery history is deleted.
|
||||||
|
|
||||||
|
### Fix-round TDD evidence
|
||||||
|
|
||||||
|
- Repeat eligibility RED: `pnpm test src/modules/downloads/eligibility.test.ts` failed because the eligibility module did not exist. GREEN after adding the invariant and repository locking: 4 focused files / 36 tests passed, followed by `pnpm typecheck`.
|
||||||
|
- History bounding RED: the service did not normalize a separate attempt continuation and the UI exposed only usage pagination (2 focused failures). The first bounded-page implementation passed 2 files / 10 tests plus typecheck. It was then tightened to a no-ceiling keyset cursor; the cursor contract/UI tests failed against the offset implementation and passed after the keyset change (2 files / 12 tests).
|
||||||
|
- Usage-level price/status RED: the open/no-terminal-attempt test could not find `Abrechnungsstatus` or the server price (1 failure). The immutable-price regression additionally showed `0,00 EUR` after void instead of the snapshot. Both pass with separate `priceCents` and `billableCents` fields.
|
||||||
|
- Time-zone RED: `pnpm test src/modules/downloads/format.test.ts` failed because the explicit Berlin formatter did not exist. GREEN verifies a Berlin-midnight boundary while the process time zone is `America/Los_Angeles`.
|
||||||
|
- Audit and PostgreSQL sequence/race coverage is unskipped in `tests/db/download-delivery.test.ts`: reopened prior-status truth, repeat rejection before delivered bytes, completed/interrupted eligibility, pre-authorized repeat invalidation on later void, concurrent claim ownership, and keyset access to every bounded attempt. The environment still fails before collection with `Could not find a working container runtime strategy`; exactly 0 PostgreSQL tests execute locally.
|
||||||
|
|
||||||
|
### Migration and final verification
|
||||||
|
|
||||||
|
- No schema migration was required in Fix Round 1; the existing durable `voided` state supports the invariant without deleting history.
|
||||||
|
- `pnpm test src tests/db/accounting-migration-sql.test.ts tests/db/download-delivery-migration-sql.test.ts` — 27 files / 166 tests passed.
|
||||||
|
- `pnpm typecheck` — passed.
|
||||||
|
- `pnpm lint` — passed.
|
||||||
|
- `pnpm exec drizzle-kit check` — passed.
|
||||||
|
- `pnpm exec drizzle-kit generate --name task_9_fix_round_1_final_noop` — no schema changes, nothing to migrate.
|
||||||
|
- `git diff --check` — passed.
|
||||||
|
- `pnpm exec next build --webpack` with the documented `.env.example` values — passed compilation, TypeScript, page-data collection, 14/14 static pages, and build tracing.
|
||||||
|
|
||||||
|
### Remaining concern
|
||||||
|
|
||||||
|
- Real PostgreSQL assertions remain blocked solely by the absent local Docker/container runtime. The expanded suite is not skipped and should be run unchanged on a Docker-enabled CI/release host.
|
||||||
|
|
||||||
|
## Fix Round 2
|
||||||
|
|
||||||
|
### Eligibility alignment
|
||||||
|
|
||||||
|
- Removed the Repeat service's unlocked `findIntent` fast path. Every initial request and same-key retry now enters the repository transaction, takes the editorial/usage locks, checks the original-delivery invariant, and only then returns or creates an intent. The insertion-race fallback repeats that same locked transaction instead of loading a winner outside the invariant.
|
||||||
|
- Persisted intents now carry the real `download_events.status`. `resolveIntent` checks fingerprint/kind conflict semantics first and exposes only a still-`authorized` event; terminal or streaming events are rejected with generic not-found semantics instead of producing a stale 201/file URL.
|
||||||
|
- Centralized the database delivery predicate in `deliveredOriginalEventCondition`: same editorial and usage, `intent_kind = new_usage`, `status in (completed, interrupted)`, and `transferred_bytes > 0`. Repeat creation/claim, prior-usage reads, and catalog dialog choices use this same predicate alongside non-voided billing status.
|
||||||
|
- Catalog choices use one correlated `EXISTS` query, not N+1 reads. Inputs are bounded to the 60-photo catalog page and results to 300 choices. Abandoned, authorized-only, zero-byte, failed, voided, and foreign-editorial usages are not serialized to the dialog; delivered open/billed/reopened usages remain eligible.
|
||||||
|
|
||||||
|
### Global attempt stream
|
||||||
|
|
||||||
|
- Split usage pagination from attempt pagination. Usage snapshots remain bounded to 20+1 rows, while attempts are queried directly from `download_events` by authenticated `editorial_account_id`, independent of the selected usage page.
|
||||||
|
- Attempt traversal includes all five statuses (`authorized`, `streaming`, `completed`, `interrupted`, `failed_before_delivery`). Because membership and ordering depend only on immutable `authorized_at + id`, later terminal transitions cannot insert an old row behind an issued cursor.
|
||||||
|
- The attempt query joins `usages` once with a matching editorial scope and returns at most 25+1 rows. Every serialized attempt includes filename, album, purpose, reference, immutable usage price, effective billable cents, bytes, kind, timestamps, and current outcome. No hidden N+1 or unbounded attempt array remains.
|
||||||
|
- The UI renders a separate German `Downloadversuche` ledger, including in-progress statuses and both effective attempt cost and immutable usage-price context. Attempt navigation preserves the usage page but is no longer constrained by its membership.
|
||||||
|
- The cursor compares the raw indexed `(authorized_at, id)` tuple and serializes exact PostgreSQL microseconds plus UUID. Concurrent later events stay on a refreshed newest page; traversal of the pre-existing older stream has no duplicates or omissions.
|
||||||
|
|
||||||
|
### Migration
|
||||||
|
|
||||||
|
- Added `drizzle/0004_download_history_indexes.sql`, generated `drizzle/meta/0004_snapshot.json`, and updated the journal.
|
||||||
|
- Added `download_events_editorial_authorized_id_idx` on `(editorial_account_id, authorized_at DESC, id DESC)`.
|
||||||
|
- Added `usages_editorial_created_id_idx` on `(editorial_account_id, created_at DESC, id DESC)`.
|
||||||
|
- The deterministic migration contract asserts both exact indexes and that neither usage nor download history is deleted. `drizzle-kit check` passes and the final generate is a no-op.
|
||||||
|
|
||||||
|
### Fix-round TDD evidence
|
||||||
|
|
||||||
|
- Repeat retry RED: an equivalent same-key request resolved successfully after repository eligibility was revoked. GREEN routes the retry through the locked repository; the focused Repeat suite passed 10/10.
|
||||||
|
- Persisted-state RED: a `failed_before_delivery` event was returned as an intent. GREEN selects the true event status and rejects every non-authorized persisted event; combined usage/repeat services passed 2 files / 30 tests with typecheck.
|
||||||
|
- Attempt-stream RED: the new separate all-status UI model failed because the component still dereferenced nested `usage.attempts`. GREEN renders the global bounded ledger; focused history tests passed 2 files / 12 tests.
|
||||||
|
- Price-context RED: attempt rows did not expose their immutable usage price. GREEN renders labeled usage-price context for every attempt.
|
||||||
|
- Migration RED: the 0004 contract failed with ENOENT. GREEN passed after schema generation, snapshot/journal update, Drizzle validation, and a no-op generation.
|
||||||
|
- Combined focused verification passed 9 files / 61 tests before final full verification.
|
||||||
|
|
||||||
|
### PostgreSQL coverage and blocker
|
||||||
|
|
||||||
|
- Expanded the unskipped PostgreSQL suite with: same-key repeat rejection after a usage void; delivered-choice filtering across open/billed/reopened, abandoned and zero-byte rows; foreign-editorial isolation; global traversal from an empty usage page; status-transition and concurrent-new-event cursor stability; and `EXPLAIN` assertions for both new history indexes.
|
||||||
|
- Command: `pnpm test tests/db/download-delivery.test.ts tests/db/usage-accounting.test.ts tests/db/accounting-migration.test.ts`.
|
||||||
|
- Result: all three suites failed before collection with `Could not find a working container runtime strategy`; exactly 0 PostgreSQL tests executed. No test is skipped.
|
||||||
|
|
||||||
|
### Final verification
|
||||||
|
|
||||||
|
- `pnpm test src tests/db/accounting-migration-sql.test.ts tests/db/download-delivery-migration-sql.test.ts tests/db/download-history-index-migration-sql.test.ts` — 28 files / 169 tests passed.
|
||||||
|
- `pnpm typecheck` — passed.
|
||||||
|
- `pnpm lint` — passed.
|
||||||
|
- `pnpm exec drizzle-kit check` — passed.
|
||||||
|
- `pnpm exec drizzle-kit generate --name task_9_fix_round_2_final_noop` — no schema changes, nothing to migrate.
|
||||||
|
- `git diff --check` — passed.
|
||||||
|
- Webpack production build with documented `.env.example` values — passed compilation, TypeScript, page-data collection, 14/14 static pages, and build tracing.
|
||||||
|
|
||||||
|
### Remaining concern
|
||||||
|
|
||||||
|
- The only unresolved verification gap is environmental: the real PostgreSQL migration, race, traversal, and query-plan assertions require a Docker-capable host. Run the unchanged three-suite command above in CI before release.
|
||||||
+54
@@ -0,0 +1,54 @@
|
|||||||
|
# Multi-stage Dockerfile for Immich Redaktionsportal
|
||||||
|
# Node.js 24 Alpine standalone build
|
||||||
|
|
||||||
|
FROM node:24-alpine AS base
|
||||||
|
RUN corepack enable && corepack prepare pnpm@10.34.5 --activate
|
||||||
|
|
||||||
|
FROM base AS dependencies
|
||||||
|
WORKDIR /app
|
||||||
|
COPY package.json pnpm-lock.yaml ./
|
||||||
|
RUN pnpm install --frozen-lockfile
|
||||||
|
|
||||||
|
FROM base AS builder
|
||||||
|
WORKDIR /app
|
||||||
|
COPY --from=dependencies /app/node_modules ./node_modules
|
||||||
|
COPY . .
|
||||||
|
|
||||||
|
# Set build-time dummy env vars required for static layout evaluation during next build
|
||||||
|
ENV NODE_ENV=production
|
||||||
|
ENV NEXT_TELEMETRY_DISABLED=1
|
||||||
|
ENV DATABASE_URL=postgres://portal:portal@localhost:5432/portal
|
||||||
|
ENV BETTER_AUTH_SECRET=00000000000000000000000000000000
|
||||||
|
ENV BETTER_AUTH_URL=http://localhost:3000
|
||||||
|
ENV IMMICH_BASE_URL=http://localhost:2283
|
||||||
|
ENV IMMICH_API_KEY=build-time-dummy-key
|
||||||
|
ENV SMTP_HOST=localhost
|
||||||
|
ENV SMTP_PORT=587
|
||||||
|
ENV SMTP_USER=portal@localhost
|
||||||
|
ENV SMTP_PASSWORD=dummy-password
|
||||||
|
ENV SMTP_FROM=portal@localhost
|
||||||
|
ENV LEGAL_IMPRINT_URL=https://example.com/impressum
|
||||||
|
ENV LEGAL_PRIVACY_URL=https://example.com/datenschutz
|
||||||
|
ENV LEGAL_TERMS_URL=https://example.com/nutzungsbedingungen
|
||||||
|
|
||||||
|
RUN pnpm build
|
||||||
|
|
||||||
|
FROM node:24-alpine AS runner
|
||||||
|
WORKDIR /app
|
||||||
|
|
||||||
|
ENV NODE_ENV=production
|
||||||
|
ENV PORT=3000
|
||||||
|
ENV HOSTNAME="0.0.0.0"
|
||||||
|
|
||||||
|
RUN addgroup --system --gid 1001 nodejs && \
|
||||||
|
adduser --system --uid 1001 nextjs
|
||||||
|
|
||||||
|
COPY --from=builder /app/public ./public
|
||||||
|
COPY --from=builder --chown=nextjs:nodejs /app/.next/standalone ./
|
||||||
|
COPY --from=builder --chown=nextjs:nodejs /app/.next/static ./.next/static
|
||||||
|
|
||||||
|
USER nextjs
|
||||||
|
|
||||||
|
EXPOSE 3000
|
||||||
|
|
||||||
|
CMD ["node", "server.js"]
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
services:
|
||||||
|
portal-db:
|
||||||
|
image: postgres:17-alpine
|
||||||
|
container_name: portal-db
|
||||||
|
restart: unless-stopped
|
||||||
|
environment:
|
||||||
|
POSTGRES_DB: ${POSTGRES_DB:-portal}
|
||||||
|
POSTGRES_USER: ${POSTGRES_USER:-portal}
|
||||||
|
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:-change-me}
|
||||||
|
volumes:
|
||||||
|
- portal-db-data:/var/lib/postgresql/data
|
||||||
|
healthcheck:
|
||||||
|
test: ["CMD-SHELL", "pg_isready -U $${POSTGRES_USER:-portal} -d $${POSTGRES_DB:-portal}"]
|
||||||
|
interval: 5s
|
||||||
|
timeout: 5s
|
||||||
|
retries: 5
|
||||||
|
networks:
|
||||||
|
- portal-internal
|
||||||
|
|
||||||
|
portal-app:
|
||||||
|
build:
|
||||||
|
context: .
|
||||||
|
dockerfile: Dockerfile
|
||||||
|
container_name: portal-app
|
||||||
|
restart: unless-stopped
|
||||||
|
ports:
|
||||||
|
- "3000:3000"
|
||||||
|
environment:
|
||||||
|
DATABASE_URL: ${DATABASE_URL:-postgres://portal:change-me@portal-db:5432/portal}
|
||||||
|
BETTER_AUTH_SECRET: ${BETTER_AUTH_SECRET}
|
||||||
|
BETTER_AUTH_URL: ${BETTER_AUTH_URL:-http://localhost:3000}
|
||||||
|
IMMICH_BASE_URL: ${IMMICH_BASE_URL}
|
||||||
|
IMMICH_API_KEY: ${IMMICH_API_KEY}
|
||||||
|
SMTP_HOST: ${SMTP_HOST}
|
||||||
|
SMTP_PORT: ${SMTP_PORT:-587}
|
||||||
|
SMTP_USER: ${SMTP_USER}
|
||||||
|
SMTP_PASSWORD: ${SMTP_PASSWORD}
|
||||||
|
SMTP_FROM: ${SMTP_FROM}
|
||||||
|
LEGAL_IMPRINT_URL: ${LEGAL_IMPRINT_URL}
|
||||||
|
LEGAL_PRIVACY_URL: ${LEGAL_PRIVACY_URL}
|
||||||
|
LEGAL_TERMS_URL: ${LEGAL_TERMS_URL}
|
||||||
|
depends_on:
|
||||||
|
portal-db:
|
||||||
|
condition: service_healthy
|
||||||
|
networks:
|
||||||
|
- portal-internal
|
||||||
|
- immich-net
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
portal-db-data:
|
||||||
|
|
||||||
|
networks:
|
||||||
|
portal-internal:
|
||||||
|
internal: true
|
||||||
|
immich-net:
|
||||||
|
external: true
|
||||||
@@ -0,0 +1,114 @@
|
|||||||
|
# Operations Runbook: Immich Redaktionsportal
|
||||||
|
|
||||||
|
This guide documents production deployment, operations, security practices, backup/restore procedures, and maintenance for the Immich Redaktionsportal.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. Production Architecture Overview
|
||||||
|
|
||||||
|
The portal runs as a self-hosted Next.js standalone container alongside a dedicated PostgreSQL 17 database.
|
||||||
|
|
||||||
|
- **App Server**: Next.js 16 (Node.js 24 LTS, standalone output).
|
||||||
|
- **Database**: PostgreSQL 17 (isolated database, separate from Immich).
|
||||||
|
- **Immich Integration**: Isolated via server-only Immich API adapter using an administrator API key.
|
||||||
|
- **Mail**: Nodemailer via SMTP (TLS / STARTTLS).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. Environment Configuration
|
||||||
|
|
||||||
|
All production configuration is provided via environment variables (e.g. `.env` or Docker secrets).
|
||||||
|
|
||||||
|
| Variable | Description | Example / Notes |
|
||||||
|
| :--- | :--- | :--- |
|
||||||
|
| `DATABASE_URL` | PostgreSQL connection string | `postgres://portal:pass@portal-db:5432/portal` |
|
||||||
|
| `BETTER_AUTH_SECRET` | 32+ character random secret | `openssl rand -hex 32` |
|
||||||
|
| `BETTER_AUTH_URL` | Public base URL of the portal | `https://presse.example.de` |
|
||||||
|
| `IMMICH_BASE_URL` | Internal URL to Immich server | `http://immich-server:2283` |
|
||||||
|
| `IMMICH_API_KEY` | Restricted Immich API key | API key of dedicated Immich service user |
|
||||||
|
| `SMTP_HOST` | Outbound mail server hostname | `smtp.infomaniak.com` |
|
||||||
|
| `SMTP_PORT` | Outbound mail server port | `587` (STARTTLS) or `465` (SSL) |
|
||||||
|
| `SMTP_USER` | SMTP username | `portal@example.de` |
|
||||||
|
| `SMTP_PASSWORD` | SMTP password | Confidential |
|
||||||
|
| `SMTP_FROM` | Default From email address | `Leon Tonhäuser Presse <portal@example.de>` |
|
||||||
|
| `LEGAL_IMPRINT_URL` | Public Impressum link | `https://example.de/impressum` |
|
||||||
|
| `LEGAL_PRIVACY_URL` | Public Datenschutz link | `https://example.de/datenschutz` |
|
||||||
|
| `LEGAL_TERMS_URL` | Public Nutzungsbedingungen link | `https://example.de/terms` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. Reverse Proxy & Streaming Configuration
|
||||||
|
|
||||||
|
When placing Nginx or Traefik in front of the portal:
|
||||||
|
|
||||||
|
1. **Proxy Buffering**: Disable response buffering for the download stream endpoint (`/api/downloads/[downloadId]/file`) to support direct streaming of original high-resolution photo files:
|
||||||
|
```nginx
|
||||||
|
location /api/downloads/ {
|
||||||
|
proxy_pass http://localhost:3000;
|
||||||
|
proxy_buffering off;
|
||||||
|
proxy_read_timeout 600s;
|
||||||
|
proxy_send_timeout 600s;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
2. **Body Size Limits**: Unused (portal handles photo downloads only, not uploads).
|
||||||
|
3. **Security Headers**: Managed by Next.js (`next.config.ts`), including restrictive CSP, frame denial (`DENY`), and strict Referrer-Policy.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. Immich Service-User Permissions & API Key Setup
|
||||||
|
|
||||||
|
1. Create a dedicated service user in Immich (e.g. `redaktion-service@example.de`).
|
||||||
|
2. Share **only** administrator-approved editorial albums read-only with this user.
|
||||||
|
3. Generate an API Key for the user with only the following scopes:
|
||||||
|
- `album.read`
|
||||||
|
- `asset.read`
|
||||||
|
- `asset.view`
|
||||||
|
- `asset.download`
|
||||||
|
4. Test API access against Immich endpoints before deploying.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. Database Migrations
|
||||||
|
|
||||||
|
Database schema migrations are managed via Drizzle Kit.
|
||||||
|
|
||||||
|
- **Apply Migrations**:
|
||||||
|
```bash
|
||||||
|
pnpm drizzle-kit migrate
|
||||||
|
```
|
||||||
|
- Migrations must be executed prior to starting a new app container version.
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. Backup & Restore Procedures
|
||||||
|
|
||||||
|
### Nightly Backup Drill
|
||||||
|
|
||||||
|
Use `scripts/backup-db.sh` in a daily cron job:
|
||||||
|
```bash
|
||||||
|
0 2 * * * /path/to/portal/scripts/backup-db.sh /var/backups/immich-portal >> /var/log/portal-backup.log 2>&1
|
||||||
|
```
|
||||||
|
|
||||||
|
### Restore Procedure
|
||||||
|
|
||||||
|
To restore from a `.dump` file created by `backup-db.sh`:
|
||||||
|
```bash
|
||||||
|
# 1. Stop the application container to prevent writes
|
||||||
|
docker compose stop portal-app
|
||||||
|
|
||||||
|
# 2. Restore database from dump file
|
||||||
|
docker exec -i portal-db pg_restore -U portal -d portal --clean --if-exists < /path/to/backup.dump
|
||||||
|
|
||||||
|
# 3. Restart application container
|
||||||
|
docker compose start portal-app
|
||||||
|
```
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. Operational Maintenance Tasks
|
||||||
|
|
||||||
|
- **API Key Rotation**: Generate a new key in Immich, update `IMMICH_API_KEY` in environment/secrets, and restart `portal-app`.
|
||||||
|
- **Health Verification**:
|
||||||
|
- `GET /api/health/live` -> 200 OK (Process liveness).
|
||||||
|
- `GET /api/health/ready` -> 200 OK (Database & Immich connectivity).
|
||||||
|
- **Audit Log Inspection**: Accessible in portal UI under `/admin/audit` (Admin role required).
|
||||||
@@ -161,7 +161,7 @@ Create `package.json` with these scripts and engine policy; install the named de
|
|||||||
```json
|
```json
|
||||||
{
|
{
|
||||||
"private": true,
|
"private": true,
|
||||||
"packageManager": "pnpm@10",
|
"packageManager": "pnpm@10.34.5",
|
||||||
"engines": { "node": ">=24 <25" },
|
"engines": { "node": ">=24 <25" },
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "next dev",
|
"dev": "next dev",
|
||||||
|
|||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { defineConfig } from "drizzle-kit";
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
dialect: "postgresql",
|
||||||
|
schema: "./src/db/schema/index.ts",
|
||||||
|
out: "./drizzle",
|
||||||
|
dbCredentials: {
|
||||||
|
url: process.env.DATABASE_URL ?? "postgresql://portal:portal@localhost:5432/portal",
|
||||||
|
},
|
||||||
|
});
|
||||||
@@ -0,0 +1,201 @@
|
|||||||
|
CREATE TYPE "public"."portal_role" AS ENUM('ADMIN', 'EDITORIAL');--> statement-breakpoint
|
||||||
|
CREATE TYPE "public"."report_status" AS ENUM('draft', 'final', 'cancelled');--> statement-breakpoint
|
||||||
|
CREATE TYPE "public"."account_status" AS ENUM('pending_email', 'pending_approval', 'active', 'suspended', 'rejected');--> statement-breakpoint
|
||||||
|
CREATE TYPE "public"."download_status" AS ENUM('authorized', 'streaming', 'completed', 'failed_before_delivery', 'interrupted');--> statement-breakpoint
|
||||||
|
CREATE TYPE "public"."usage_billing_status" AS ENUM('open', 'billed', 'reopened');--> statement-breakpoint
|
||||||
|
CREATE TABLE "album_grants" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"editorial_account_id" uuid NOT NULL,
|
||||||
|
"immich_album_id" text NOT NULL,
|
||||||
|
"granted_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"revoked_at" timestamp with time zone,
|
||||||
|
"granted_by_user_id" uuid
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "audit_events" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"event_type" text NOT NULL,
|
||||||
|
"actor_user_id" uuid,
|
||||||
|
"actor_type" text DEFAULT 'system' NOT NULL,
|
||||||
|
"entity_type" text NOT NULL,
|
||||||
|
"entity_id" text NOT NULL,
|
||||||
|
"previous_values" jsonb,
|
||||||
|
"new_values" jsonb,
|
||||||
|
"occurred_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"request_id" uuid
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "account" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"account_id" text NOT NULL,
|
||||||
|
"provider_id" text NOT NULL,
|
||||||
|
"user_id" uuid NOT NULL,
|
||||||
|
"access_token" text,
|
||||||
|
"refresh_token" text,
|
||||||
|
"id_token" text,
|
||||||
|
"access_token_expires_at" timestamp with time zone,
|
||||||
|
"refresh_token_expires_at" timestamp with time zone,
|
||||||
|
"scope" text,
|
||||||
|
"password" text,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "session" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"expires_at" timestamp with time zone NOT NULL,
|
||||||
|
"token" text NOT NULL,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"ip_address" text,
|
||||||
|
"user_agent" text,
|
||||||
|
"user_id" uuid NOT NULL,
|
||||||
|
CONSTRAINT "session_token_unique" UNIQUE("token")
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "user" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"name" text NOT NULL,
|
||||||
|
"email" text NOT NULL,
|
||||||
|
"email_verified" boolean DEFAULT false NOT NULL,
|
||||||
|
"image" text,
|
||||||
|
"role" "portal_role" DEFAULT 'EDITORIAL' NOT NULL,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
CONSTRAINT "user_email_unique" UNIQUE("email")
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "verification" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"identifier" text NOT NULL,
|
||||||
|
"value" text NOT NULL,
|
||||||
|
"expires_at" timestamp with time zone NOT NULL,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"updated_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "billing_report_items" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"billing_report_id" uuid NOT NULL,
|
||||||
|
"usage_id" uuid NOT NULL,
|
||||||
|
"immich_asset_id_snapshot" text NOT NULL,
|
||||||
|
"filename_snapshot" text NOT NULL,
|
||||||
|
"album_name_snapshot" text NOT NULL,
|
||||||
|
"purpose_snapshot" text NOT NULL,
|
||||||
|
"internal_reference_snapshot" text,
|
||||||
|
"price_cents" integer NOT NULL,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "billing_reports" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"report_number" integer NOT NULL,
|
||||||
|
"editorial_account_id" uuid NOT NULL,
|
||||||
|
"period_starts_at" timestamp with time zone NOT NULL,
|
||||||
|
"period_ends_at" timestamp with time zone NOT NULL,
|
||||||
|
"billing_address_snapshot" jsonb NOT NULL,
|
||||||
|
"invoice_number" text,
|
||||||
|
"net_total_cents" integer NOT NULL,
|
||||||
|
"status" "report_status" DEFAULT 'draft' NOT NULL,
|
||||||
|
"pdf" "bytea",
|
||||||
|
"pdf_sha256" varchar(64),
|
||||||
|
"created_by_user_id" uuid NOT NULL,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"finalized_at" timestamp with time zone,
|
||||||
|
"cancelled_at" timestamp with time zone,
|
||||||
|
"cancellation_reason" text,
|
||||||
|
"cancelled_by_user_id" uuid,
|
||||||
|
CONSTRAINT "billing_reports_pdf_sha256_hex_check" CHECK ("billing_reports"."pdf_sha256" ~ '^[0-9a-f]{64}$'),
|
||||||
|
CONSTRAINT "billing_reports_final_pdf_check" CHECK ("billing_reports"."status" <> 'final' OR ("billing_reports"."pdf" IS NOT NULL AND "billing_reports"."pdf_sha256" IS NOT NULL))
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "billing_address_versions" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"editorial_account_id" uuid NOT NULL,
|
||||||
|
"company_name" text NOT NULL,
|
||||||
|
"contact_name" text NOT NULL,
|
||||||
|
"address_line_1" text NOT NULL,
|
||||||
|
"address_line_2" text,
|
||||||
|
"postal_code" text NOT NULL,
|
||||||
|
"city" text NOT NULL,
|
||||||
|
"country_code" text NOT NULL,
|
||||||
|
"valid_from" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"superseded_by_id" uuid,
|
||||||
|
"created_by_user_id" uuid,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "editorial_accounts" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"user_id" uuid NOT NULL,
|
||||||
|
"name" text NOT NULL,
|
||||||
|
"contact_name" text NOT NULL,
|
||||||
|
"login_email" text NOT NULL,
|
||||||
|
"status" "account_status" DEFAULT 'pending_email' NOT NULL,
|
||||||
|
"current_price_cents" integer,
|
||||||
|
"current_billing_address_version_id" uuid,
|
||||||
|
"email_verified_at" timestamp with time zone,
|
||||||
|
"accepted_terms_version" text,
|
||||||
|
"accepted_terms_at" timestamp with time zone,
|
||||||
|
"privacy_acknowledged_at" timestamp with time zone,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
CONSTRAINT "editorial_accounts_user_id_unique" UNIQUE("user_id"),
|
||||||
|
CONSTRAINT "editorial_accounts_login_email_unique" UNIQUE("login_email")
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "download_events" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"editorial_account_id" uuid NOT NULL,
|
||||||
|
"usage_id" uuid NOT NULL,
|
||||||
|
"immich_asset_id" text NOT NULL,
|
||||||
|
"authorized_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"started_at" timestamp with time zone,
|
||||||
|
"completed_at" timestamp with time zone,
|
||||||
|
"status" "download_status" DEFAULT 'authorized' NOT NULL,
|
||||||
|
"transferred_bytes" bigint,
|
||||||
|
"repeat_download_note" text,
|
||||||
|
"request_id" uuid NOT NULL,
|
||||||
|
"idempotency_key" text NOT NULL
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
CREATE TABLE "usages" (
|
||||||
|
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
|
||||||
|
"editorial_account_id" uuid NOT NULL,
|
||||||
|
"immich_asset_id" text NOT NULL,
|
||||||
|
"filename_snapshot" text NOT NULL,
|
||||||
|
"immich_album_id_snapshot" text NOT NULL,
|
||||||
|
"album_name_snapshot" text NOT NULL,
|
||||||
|
"purpose" text NOT NULL,
|
||||||
|
"internal_reference" text,
|
||||||
|
"price_cents" integer NOT NULL,
|
||||||
|
"billing_status" "usage_billing_status" DEFAULT 'open' NOT NULL,
|
||||||
|
"billing_report_id" uuid,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL
|
||||||
|
);
|
||||||
|
--> statement-breakpoint
|
||||||
|
ALTER TABLE "album_grants" ADD CONSTRAINT "album_grants_editorial_account_id_editorial_accounts_id_fk" FOREIGN KEY ("editorial_account_id") REFERENCES "public"."editorial_accounts"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "album_grants" ADD CONSTRAINT "album_grants_granted_by_user_id_user_id_fk" FOREIGN KEY ("granted_by_user_id") REFERENCES "public"."user"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "audit_events" ADD CONSTRAINT "audit_events_actor_user_id_user_id_fk" FOREIGN KEY ("actor_user_id") REFERENCES "public"."user"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "account" ADD CONSTRAINT "account_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "session" ADD CONSTRAINT "session_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "billing_report_items" ADD CONSTRAINT "billing_report_items_billing_report_id_billing_reports_id_fk" FOREIGN KEY ("billing_report_id") REFERENCES "public"."billing_reports"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "billing_report_items" ADD CONSTRAINT "billing_report_items_usage_id_usages_id_fk" FOREIGN KEY ("usage_id") REFERENCES "public"."usages"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "billing_reports" ADD CONSTRAINT "billing_reports_editorial_account_id_editorial_accounts_id_fk" FOREIGN KEY ("editorial_account_id") REFERENCES "public"."editorial_accounts"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "billing_reports" ADD CONSTRAINT "billing_reports_created_by_user_id_user_id_fk" FOREIGN KEY ("created_by_user_id") REFERENCES "public"."user"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "billing_reports" ADD CONSTRAINT "billing_reports_cancelled_by_user_id_user_id_fk" FOREIGN KEY ("cancelled_by_user_id") REFERENCES "public"."user"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "billing_address_versions" ADD CONSTRAINT "billing_address_versions_editorial_account_id_editorial_accounts_id_fk" FOREIGN KEY ("editorial_account_id") REFERENCES "public"."editorial_accounts"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "billing_address_versions" ADD CONSTRAINT "billing_address_versions_superseded_by_id_billing_address_versions_id_fk" FOREIGN KEY ("superseded_by_id") REFERENCES "public"."billing_address_versions"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "billing_address_versions" ADD CONSTRAINT "billing_address_versions_created_by_user_id_user_id_fk" FOREIGN KEY ("created_by_user_id") REFERENCES "public"."user"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "editorial_accounts" ADD CONSTRAINT "editorial_accounts_user_id_user_id_fk" FOREIGN KEY ("user_id") REFERENCES "public"."user"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "editorial_accounts" ADD CONSTRAINT "editorial_accounts_current_billing_address_version_id_billing_address_versions_id_fk" FOREIGN KEY ("current_billing_address_version_id") REFERENCES "public"."billing_address_versions"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "download_events" ADD CONSTRAINT "download_events_editorial_account_id_editorial_accounts_id_fk" FOREIGN KEY ("editorial_account_id") REFERENCES "public"."editorial_accounts"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "download_events" ADD CONSTRAINT "download_events_usage_id_usages_id_fk" FOREIGN KEY ("usage_id") REFERENCES "public"."usages"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "usages" ADD CONSTRAINT "usages_editorial_account_id_editorial_accounts_id_fk" FOREIGN KEY ("editorial_account_id") REFERENCES "public"."editorial_accounts"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||||
|
ALTER TABLE "usages" ADD CONSTRAINT "usages_billing_report_id_billing_reports_id_fk" FOREIGN KEY ("billing_report_id") REFERENCES "public"."billing_reports"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint
|
||||||
|
CREATE INDEX "album_grants_editorial_account_id_idx" ON "album_grants" USING btree ("editorial_account_id");--> statement-breakpoint
|
||||||
|
CREATE INDEX "album_grants_immich_album_id_idx" ON "album_grants" USING btree ("immich_album_id");--> statement-breakpoint
|
||||||
|
CREATE UNIQUE INDEX "billing_report_items_report_usage_unique" ON "billing_report_items" USING btree ("billing_report_id","usage_id");--> statement-breakpoint
|
||||||
|
CREATE UNIQUE INDEX "billing_reports_report_number_unique" ON "billing_reports" USING btree ("report_number");--> statement-breakpoint
|
||||||
|
CREATE UNIQUE INDEX "billing_reports_invoice_number_unique" ON "billing_reports" USING btree ("invoice_number");--> statement-breakpoint
|
||||||
|
CREATE UNIQUE INDEX "download_events_editorial_idempotency_key_unique" ON "download_events" USING btree ("editorial_account_id","idempotency_key");
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
ALTER TABLE "editorial_accounts" ADD COLUMN "approval_notice_status" text DEFAULT 'not_requested' NOT NULL;
|
||||||
@@ -0,0 +1,186 @@
|
|||||||
|
ALTER TABLE "download_events" ADD COLUMN "intent_kind" text;--> statement-breakpoint
|
||||||
|
ALTER TABLE "download_events" ADD COLUMN "request_fingerprint" varchar(64);--> statement-breakpoint
|
||||||
|
ALTER TABLE "download_events" ADD COLUMN "legacy_intent" boolean;--> statement-breakpoint
|
||||||
|
-- UUID-shaped legacy keys are canonicalized only when doing so is unambiguous.
|
||||||
|
-- Arbitrary and case-colliding historical keys remain byte-for-byte unchanged.
|
||||||
|
WITH case_colliding_idempotency_keys AS (
|
||||||
|
SELECT "editorial_account_id", lower("idempotency_key") AS canonical_key
|
||||||
|
FROM "download_events"
|
||||||
|
GROUP BY "editorial_account_id", lower("idempotency_key")
|
||||||
|
HAVING count(*) > 1
|
||||||
|
)
|
||||||
|
UPDATE "download_events" AS target
|
||||||
|
SET "idempotency_key" = lower(target."idempotency_key")
|
||||||
|
WHERE
|
||||||
|
target."idempotency_key" ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1
|
||||||
|
FROM case_colliding_idempotency_keys AS collision
|
||||||
|
WHERE
|
||||||
|
collision."editorial_account_id" = target."editorial_account_id"
|
||||||
|
AND collision.canonical_key = lower(target."idempotency_key")
|
||||||
|
);--> statement-breakpoint
|
||||||
|
-- A legacy new usage is reconstructible only when it has one unique earliest,
|
||||||
|
-- note-free event and every runtime fingerprint field already satisfies the new
|
||||||
|
-- normalized input contract. A repeat additionally needs a normalized non-null
|
||||||
|
-- repeat note after that provable initial event. Every other row is explicit legacy.
|
||||||
|
WITH earliest_event_times AS (
|
||||||
|
SELECT "usage_id", min("authorized_at") AS earliest_authorized_at
|
||||||
|
FROM "download_events"
|
||||||
|
GROUP BY "usage_id"
|
||||||
|
),
|
||||||
|
case_colliding_idempotency_keys AS (
|
||||||
|
SELECT "editorial_account_id", lower("idempotency_key") AS canonical_key
|
||||||
|
FROM "download_events"
|
||||||
|
GROUP BY "editorial_account_id", lower("idempotency_key")
|
||||||
|
HAVING count(*) > 1
|
||||||
|
),
|
||||||
|
legacy_event_candidates AS (
|
||||||
|
SELECT
|
||||||
|
events."id",
|
||||||
|
events."usage_id",
|
||||||
|
events."authorized_at",
|
||||||
|
earliest.earliest_authorized_at,
|
||||||
|
(
|
||||||
|
events."repeat_download_note" IS NULL
|
||||||
|
AND events."editorial_account_id" = usage."editorial_account_id"
|
||||||
|
AND lower(events."immich_asset_id") = lower(usage."immich_asset_id")
|
||||||
|
AND events."immich_asset_id" ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'
|
||||||
|
AND usage."immich_asset_id" ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'
|
||||||
|
AND usage."immich_album_id_snapshot" ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'
|
||||||
|
AND events."idempotency_key" ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'
|
||||||
|
AND octet_length(usage."purpose") = char_length(usage."purpose")
|
||||||
|
AND usage."purpose" !~ '[[:cntrl:]]'
|
||||||
|
AND left(usage."purpose", 1) <> ' '
|
||||||
|
AND right(usage."purpose", 1) <> ' '
|
||||||
|
AND char_length(usage."purpose") BETWEEN 3 AND 200
|
||||||
|
AND (
|
||||||
|
usage."internal_reference" IS NULL
|
||||||
|
OR (
|
||||||
|
octet_length(usage."internal_reference") = char_length(usage."internal_reference")
|
||||||
|
AND usage."internal_reference" !~ '[[:cntrl:]]'
|
||||||
|
AND left(usage."internal_reference", 1) <> ' '
|
||||||
|
AND right(usage."internal_reference", 1) <> ' '
|
||||||
|
AND usage."internal_reference" <> ''
|
||||||
|
AND char_length(usage."internal_reference") <= 200
|
||||||
|
)
|
||||||
|
)
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1
|
||||||
|
FROM case_colliding_idempotency_keys AS collision
|
||||||
|
WHERE
|
||||||
|
collision."editorial_account_id" = events."editorial_account_id"
|
||||||
|
AND collision.canonical_key = lower(events."idempotency_key")
|
||||||
|
)
|
||||||
|
) AS can_be_initial,
|
||||||
|
(
|
||||||
|
events."editorial_account_id" = usage."editorial_account_id"
|
||||||
|
AND lower(events."immich_asset_id") = lower(usage."immich_asset_id")
|
||||||
|
AND events."immich_asset_id" ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'
|
||||||
|
AND events."idempotency_key" ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'
|
||||||
|
AND octet_length(events."repeat_download_note") = char_length(events."repeat_download_note")
|
||||||
|
AND events."repeat_download_note" !~ '[[:cntrl:]]'
|
||||||
|
AND left(events."repeat_download_note", 1) <> ' '
|
||||||
|
AND right(events."repeat_download_note", 1) <> ' '
|
||||||
|
AND events."repeat_download_note" <> ''
|
||||||
|
AND char_length(events."repeat_download_note") <= 200
|
||||||
|
AND NOT EXISTS (
|
||||||
|
SELECT 1
|
||||||
|
FROM case_colliding_idempotency_keys AS collision
|
||||||
|
WHERE
|
||||||
|
collision."editorial_account_id" = events."editorial_account_id"
|
||||||
|
AND collision.canonical_key = lower(events."idempotency_key")
|
||||||
|
)
|
||||||
|
) AS can_be_repeat
|
||||||
|
FROM "download_events" AS events
|
||||||
|
INNER JOIN "usages" AS usage ON usage."id" = events."usage_id"
|
||||||
|
INNER JOIN earliest_event_times AS earliest ON earliest."usage_id" = events."usage_id"
|
||||||
|
),
|
||||||
|
usage_event_summary AS (
|
||||||
|
SELECT
|
||||||
|
candidate."usage_id",
|
||||||
|
candidate.earliest_authorized_at,
|
||||||
|
count(*) FILTER (
|
||||||
|
WHERE candidate."authorized_at" = candidate.earliest_authorized_at
|
||||||
|
) AS earliest_event_count,
|
||||||
|
bool_and(
|
||||||
|
CASE
|
||||||
|
WHEN candidate."authorized_at" = candidate.earliest_authorized_at
|
||||||
|
THEN candidate.can_be_initial
|
||||||
|
ELSE true
|
||||||
|
END
|
||||||
|
) AS earliest_event_is_provable
|
||||||
|
FROM legacy_event_candidates AS candidate
|
||||||
|
GROUP BY candidate."usage_id", candidate.earliest_authorized_at
|
||||||
|
)
|
||||||
|
UPDATE "download_events" AS events
|
||||||
|
SET "intent_kind" = CASE
|
||||||
|
WHEN
|
||||||
|
candidate."authorized_at" = summary.earliest_authorized_at
|
||||||
|
AND summary.earliest_event_count = 1
|
||||||
|
AND candidate.can_be_initial
|
||||||
|
THEN 'new_usage'
|
||||||
|
WHEN
|
||||||
|
candidate."authorized_at" > summary.earliest_authorized_at
|
||||||
|
AND summary.earliest_event_count = 1
|
||||||
|
AND summary.earliest_event_is_provable
|
||||||
|
AND candidate.can_be_repeat
|
||||||
|
THEN 'repeat_download'
|
||||||
|
ELSE 'legacy'
|
||||||
|
END
|
||||||
|
FROM legacy_event_candidates AS candidate, usage_event_summary AS summary
|
||||||
|
WHERE
|
||||||
|
candidate."id" = events."id"
|
||||||
|
AND summary."usage_id" = candidate."usage_id";--> statement-breakpoint
|
||||||
|
-- Runtime-compatible rows receive the exact SHA-256 used by JSON.stringify in the
|
||||||
|
-- application. Explicit legacy rows receive a deterministic non-runtime hash.
|
||||||
|
UPDATE "download_events" AS events
|
||||||
|
SET "request_fingerprint" = CASE
|
||||||
|
WHEN events."intent_kind" = 'new_usage' THEN encode(sha256(convert_to(
|
||||||
|
'{"kind":"new_usage","editorialId":' || to_json(events."editorial_account_id"::text)::text ||
|
||||||
|
',"assetId":' || to_json(lower(events."immich_asset_id"))::text ||
|
||||||
|
',"albumId":' || to_json(lower(usage."immich_album_id_snapshot"))::text ||
|
||||||
|
',"purpose":' || to_json(usage."purpose")::text ||
|
||||||
|
',"reference":' || coalesce(to_json(usage."internal_reference")::text, 'null') ||
|
||||||
|
'}',
|
||||||
|
'UTF8'
|
||||||
|
)), 'hex')
|
||||||
|
WHEN events."intent_kind" = 'repeat_download' THEN encode(sha256(convert_to(
|
||||||
|
'{"kind":"repeat_download","editorialId":' || to_json(events."editorial_account_id"::text)::text ||
|
||||||
|
',"usageId":' || to_json(events."usage_id"::text)::text ||
|
||||||
|
',"note":' || to_json(events."repeat_download_note")::text ||
|
||||||
|
'}',
|
||||||
|
'UTF8'
|
||||||
|
)), 'hex')
|
||||||
|
ELSE encode(sha256(convert_to('legacy-intent-v1:' || events."id"::text, 'UTF8')), 'hex')
|
||||||
|
END
|
||||||
|
FROM "usages" AS usage
|
||||||
|
WHERE usage."id" = events."usage_id";--> statement-breakpoint
|
||||||
|
UPDATE "download_events" SET "legacy_intent" = true;--> statement-breakpoint
|
||||||
|
ALTER TABLE "download_events" ALTER COLUMN "intent_kind" SET DEFAULT 'new_usage';--> statement-breakpoint
|
||||||
|
ALTER TABLE "download_events" ALTER COLUMN "intent_kind" SET NOT NULL;--> statement-breakpoint
|
||||||
|
ALTER TABLE "download_events" ALTER COLUMN "request_fingerprint" SET NOT NULL;--> statement-breakpoint
|
||||||
|
ALTER TABLE "download_events" ALTER COLUMN "legacy_intent" SET DEFAULT false;--> statement-breakpoint
|
||||||
|
ALTER TABLE "download_events" ALTER COLUMN "legacy_intent" SET NOT NULL;--> statement-breakpoint
|
||||||
|
ALTER TABLE "download_events" ADD CONSTRAINT "download_events_intent_kind_check" CHECK ("download_events"."intent_kind" in ('new_usage', 'repeat_download', 'legacy'));--> statement-breakpoint
|
||||||
|
ALTER TABLE "download_events" ADD CONSTRAINT "download_events_request_fingerprint_hex_check" CHECK ("download_events"."request_fingerprint" ~ '^[0-9a-f]{64}$');--> statement-breakpoint
|
||||||
|
ALTER TABLE "download_events" ADD CONSTRAINT "download_events_canonical_idempotency_key_check" CHECK ("download_events"."legacy_intent" OR "download_events"."idempotency_key" ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$');--> statement-breakpoint
|
||||||
|
WITH ranked_active_album_grants AS (
|
||||||
|
SELECT
|
||||||
|
"id",
|
||||||
|
row_number() OVER (
|
||||||
|
PARTITION BY "editorial_account_id", lower("immich_album_id")
|
||||||
|
ORDER BY ("immich_album_id" = lower("immich_album_id")) DESC, "granted_at", "id"
|
||||||
|
) AS survivor_order
|
||||||
|
FROM "album_grants"
|
||||||
|
WHERE "revoked_at" IS NULL
|
||||||
|
)
|
||||||
|
UPDATE "album_grants" AS grants
|
||||||
|
SET "revoked_at" = now()
|
||||||
|
FROM ranked_active_album_grants AS ranked
|
||||||
|
WHERE grants."id" = ranked."id" AND ranked.survivor_order > 1;--> statement-breakpoint
|
||||||
|
CREATE UNIQUE INDEX "album_grants_editorial_active_album_unique" ON "album_grants" ("editorial_account_id", lower("immich_album_id")) WHERE "revoked_at" IS NULL;--> statement-breakpoint
|
||||||
|
ALTER TABLE "album_grants" ADD CONSTRAINT "album_grants_immich_album_id_uuid_check" CHECK ("album_grants"."immich_album_id" ~* '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$') NOT VALID;--> statement-breakpoint
|
||||||
|
ALTER TABLE "download_events" ADD CONSTRAINT "download_events_canonical_immich_asset_id_check" CHECK ("download_events"."immich_asset_id" ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$') NOT VALID;--> statement-breakpoint
|
||||||
|
ALTER TABLE "usages" ADD CONSTRAINT "usages_canonical_immich_asset_id_check" CHECK ("usages"."immich_asset_id" ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$') NOT VALID;--> statement-breakpoint
|
||||||
|
ALTER TABLE "usages" ADD CONSTRAINT "usages_canonical_immich_album_id_check" CHECK ("usages"."immich_album_id_snapshot" ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$') NOT VALID;
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
ALTER TYPE "public"."usage_billing_status" ADD VALUE 'voided';
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
CREATE INDEX "download_events_editorial_authorized_id_idx" ON "download_events" USING btree ("editorial_account_id","authorized_at" DESC NULLS LAST,"id" DESC NULLS LAST);--> statement-breakpoint
|
||||||
|
CREATE INDEX "usages_editorial_created_id_idx" ON "usages" USING btree ("editorial_account_id","created_at" DESC NULLS LAST,"id" DESC NULLS LAST);
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
CREATE TABLE "rate_limits" (
|
||||||
|
"key" text NOT NULL,
|
||||||
|
"window_boundary" integer NOT NULL,
|
||||||
|
"count" integer DEFAULT 1 NOT NULL,
|
||||||
|
"created_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
"updated_at" timestamp with time zone DEFAULT now() NOT NULL,
|
||||||
|
CONSTRAINT "rate_limits_key_window_boundary_pk" PRIMARY KEY("key","window_boundary")
|
||||||
|
);
|
||||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,48 @@
|
|||||||
|
{
|
||||||
|
"version": "7",
|
||||||
|
"dialect": "postgresql",
|
||||||
|
"entries": [
|
||||||
|
{
|
||||||
|
"idx": 0,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1786299825190,
|
||||||
|
"tag": "0000_initial",
|
||||||
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 1,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1786303607054,
|
||||||
|
"tag": "0001_editorial_approval_notice",
|
||||||
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 2,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1786354215684,
|
||||||
|
"tag": "0002_accounting_intents",
|
||||||
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 3,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1786358492749,
|
||||||
|
"tag": "0003_stream_delivery",
|
||||||
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 4,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1786363479515,
|
||||||
|
"tag": "0004_download_history_indexes",
|
||||||
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 5,
|
||||||
|
"version": "7",
|
||||||
|
"when": 1786379282947,
|
||||||
|
"tag": "0005_rate_limits",
|
||||||
|
"breakpoints": true
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import { test, expect } from "./fixtures";
|
||||||
|
|
||||||
|
test.describe("Billing Reports Administration", () => {
|
||||||
|
test("redirects unauthenticated user from billing admin pages", async ({ page }) => {
|
||||||
|
await page.goto("/admin/abrechnungen");
|
||||||
|
await expect(page).toHaveURL(/\/anmelden/);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import { test, expect } from "./fixtures";
|
||||||
|
|
||||||
|
test.describe("Usage Accounting and Download Flow", () => {
|
||||||
|
test("shows login page for unauthenticated access to photo catalog", async ({ page }) => {
|
||||||
|
await page.goto("/redaktion/alben");
|
||||||
|
await expect(page).toHaveURL(/\/anmelden/);
|
||||||
|
await expect(page.getByRole("button", { name: /Anmelden/i })).toBeVisible();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
/* eslint-disable react-hooks/rules-of-hooks */
|
||||||
|
import { test as base } from "@playwright/test";
|
||||||
|
|
||||||
|
export type EditorialFixture = {
|
||||||
|
organizationName: string;
|
||||||
|
name: string;
|
||||||
|
email: string;
|
||||||
|
password: string;
|
||||||
|
street: string;
|
||||||
|
postalCode: string;
|
||||||
|
city: string;
|
||||||
|
countryCode: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const editorialFixture: EditorialFixture = {
|
||||||
|
organizationName: "Suddeutsche Zeitung",
|
||||||
|
name: "Redaktion Sport",
|
||||||
|
email: "sport@sz-example.de",
|
||||||
|
password: "SecurePassword123!",
|
||||||
|
street: "Sendlinger Str. 8",
|
||||||
|
postalCode: "80331",
|
||||||
|
city: "Munchen",
|
||||||
|
countryCode: "DE",
|
||||||
|
};
|
||||||
|
|
||||||
|
export const test = base.extend<{
|
||||||
|
editorialData: EditorialFixture;
|
||||||
|
}>({
|
||||||
|
editorialData: async ({}, use) => {
|
||||||
|
await use(editorialFixture);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
export { expect } from "@playwright/test";
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
import { test, expect } from "./fixtures";
|
||||||
|
|
||||||
|
test.describe("B2B Editorial Registration and Approval Flow", () => {
|
||||||
|
test("user can register and views pending status page", async ({ page, editorialData }) => {
|
||||||
|
await page.goto("/registrieren");
|
||||||
|
|
||||||
|
await page.getByLabel("Organisation / Redaktion").fill(editorialData.organizationName);
|
||||||
|
await page.getByLabel("Ansprechpartner / Name").fill(editorialData.name);
|
||||||
|
await page.getByLabel("E-Mail-Adresse").fill(editorialData.email);
|
||||||
|
await page.getByLabel("Passwort", { exact: true }).fill(editorialData.password);
|
||||||
|
await page.getByLabel("Passwort wiederholen").fill(editorialData.password);
|
||||||
|
await page.getByLabel("Straße und Hausnummer").fill(editorialData.street);
|
||||||
|
await page.getByLabel("Postleitzahl").fill(editorialData.postalCode);
|
||||||
|
await page.getByLabel("Ort / Stadt").fill(editorialData.city);
|
||||||
|
|
||||||
|
await page.getByRole("button", { name: /Konto erstellen/i }).click();
|
||||||
|
|
||||||
|
await expect(page).toHaveURL(/\/registrieren\/bestaetigt/);
|
||||||
|
await expect(page.getByText(/Freischaltung ausstehend|ausstehend/i)).toBeVisible();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
import nextVitals from "eslint-config-next/core-web-vitals";
|
||||||
|
|
||||||
|
const eslintConfig = [...nextVitals];
|
||||||
|
|
||||||
|
export default eslintConfig;
|
||||||
Vendored
+7
@@ -0,0 +1,7 @@
|
|||||||
|
/// <reference types="next" />
|
||||||
|
/// <reference types="next/image-types/global" />
|
||||||
|
import "./.next/types/routes.d.ts";
|
||||||
|
import "./.next/types/root-params.d.ts";
|
||||||
|
|
||||||
|
// NOTE: This file should not be edited
|
||||||
|
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
|
||||||
@@ -0,0 +1,55 @@
|
|||||||
|
import type { NextConfig } from "next";
|
||||||
|
|
||||||
|
const nextConfig: NextConfig = {
|
||||||
|
output: "standalone",
|
||||||
|
poweredByHeader: false,
|
||||||
|
async headers() {
|
||||||
|
return [
|
||||||
|
{
|
||||||
|
source: "/(.*)",
|
||||||
|
headers: [
|
||||||
|
{
|
||||||
|
key: "Content-Security-Policy",
|
||||||
|
// ponytail: restrictive CSP — 'unsafe-inline' for styles only
|
||||||
|
// because Next.js injects inline styles. No unsafe-inline for
|
||||||
|
// scripts. Upgrade path: nonces once Next supports them per-route.
|
||||||
|
value: [
|
||||||
|
"default-src 'self'",
|
||||||
|
"script-src 'self'",
|
||||||
|
"style-src 'self' 'unsafe-inline'",
|
||||||
|
"img-src 'self' data:",
|
||||||
|
"font-src 'self'",
|
||||||
|
"connect-src 'self'",
|
||||||
|
"frame-ancestors 'none'",
|
||||||
|
"base-uri 'self'",
|
||||||
|
"form-action 'self'",
|
||||||
|
].join("; "),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: "Referrer-Policy",
|
||||||
|
value: "strict-origin-when-cross-origin",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: "X-Content-Type-Options",
|
||||||
|
value: "nosniff",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: "X-Frame-Options",
|
||||||
|
value: "DENY",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
key: "Permissions-Policy",
|
||||||
|
value: [
|
||||||
|
"camera=()",
|
||||||
|
"microphone=()",
|
||||||
|
"geolocation=()",
|
||||||
|
"interest-cohort=()",
|
||||||
|
].join(", "),
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
];
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export default nextConfig;
|
||||||
@@ -0,0 +1,57 @@
|
|||||||
|
{
|
||||||
|
"private": true,
|
||||||
|
"type": "module",
|
||||||
|
"packageManager": "pnpm@10.34.5",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=24 <25"
|
||||||
|
},
|
||||||
|
"scripts": {
|
||||||
|
"dev": "next dev",
|
||||||
|
"build": "NEXT_DISABLE_TURBOPACK=1 next build --webpack",
|
||||||
|
"start": "next start",
|
||||||
|
"lint": "eslint .",
|
||||||
|
"typecheck": "tsc --noEmit",
|
||||||
|
"test": "vitest run",
|
||||||
|
"test:watch": "vitest",
|
||||||
|
"test:e2e": "playwright test"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@better-auth/drizzle-adapter": "^1.6.26",
|
||||||
|
"@js-temporal/polyfill": "^0.5.1",
|
||||||
|
"better-auth": "^1.6.26",
|
||||||
|
"drizzle-orm": "^0.45.2",
|
||||||
|
"next": "^16.3.0",
|
||||||
|
"nodemailer": "^9.0.5",
|
||||||
|
"pdfmake": "~0.3.11",
|
||||||
|
"pg": "^8.22.0",
|
||||||
|
"react": "^19.2.8",
|
||||||
|
"react-dom": "^19.2.8",
|
||||||
|
"server-only": "^0.0.1",
|
||||||
|
"zod": "^4.4.3"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@playwright/test": "^1.50.0",
|
||||||
|
"@tailwindcss/postcss": "^4.3.3",
|
||||||
|
"@testcontainers/postgresql": "^12.1.0",
|
||||||
|
"@testing-library/jest-dom": "^7.0.0",
|
||||||
|
"@testing-library/react": "^16.3.2",
|
||||||
|
"@types/node": "^24.13.3",
|
||||||
|
"@types/nodemailer": "^8.0.1",
|
||||||
|
"@types/pdfmake": "^0.3.3",
|
||||||
|
"@types/pg": "^8.21.0",
|
||||||
|
"@types/react": "^19.2.18",
|
||||||
|
"@types/react-dom": "^19.2.4",
|
||||||
|
"@vitejs/plugin-react": "^6.0.5",
|
||||||
|
"drizzle-kit": "^0.31.10",
|
||||||
|
"eslint": "^9.39.5",
|
||||||
|
"eslint-config-next": "^16.3.0",
|
||||||
|
"jsdom": "^30.0.1",
|
||||||
|
"msw": "^2.15.0",
|
||||||
|
"pdfjs-dist": "^6.2.108",
|
||||||
|
"tailwindcss": "^4.3.3",
|
||||||
|
"testcontainers": "^12.1.0",
|
||||||
|
"tsx": "^4.23.11",
|
||||||
|
"typescript": "^5.9.3",
|
||||||
|
"vitest": "^4.1.10"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import { defineConfig, devices } from "@playwright/test";
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
testDir: "./e2e",
|
||||||
|
fullyParallel: false,
|
||||||
|
forbidOnly: !!process.env.CI,
|
||||||
|
retries: process.env.CI ? 2 : 0,
|
||||||
|
workers: 1,
|
||||||
|
reporter: "list",
|
||||||
|
use: {
|
||||||
|
baseURL: process.env.PLAYWRIGHT_TEST_BASE_URL || "http://localhost:3000",
|
||||||
|
trace: "on-first-retry",
|
||||||
|
},
|
||||||
|
projects: [
|
||||||
|
{
|
||||||
|
name: "chromium",
|
||||||
|
use: { ...devices["Desktop Chrome"] },
|
||||||
|
},
|
||||||
|
],
|
||||||
|
webServer: {
|
||||||
|
command: "NEXT_DISABLE_TURBOPACK=1 npx next dev",
|
||||||
|
url: "http://localhost:3000",
|
||||||
|
reuseExistingServer: !process.env.CI,
|
||||||
|
stdout: "ignore",
|
||||||
|
stderr: "pipe",
|
||||||
|
},
|
||||||
|
});
|
||||||
Generated
+8404
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,6 @@
|
|||||||
|
allowBuilds:
|
||||||
|
cpu-features: false
|
||||||
|
esbuild: true
|
||||||
|
protobufjs: false
|
||||||
|
ssh2: false
|
||||||
|
unrs-resolver: true
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
const postcssConfig = {
|
||||||
|
plugins: {
|
||||||
|
"@tailwindcss/postcss": {},
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
export default postcssConfig;
|
||||||
Binary file not shown.
|
After Width: | Height: | Size: 40 KiB |
Binary file not shown.
|
After Width: | Height: | Size: 7.6 KiB |
Executable
+49
@@ -0,0 +1,49 @@
|
|||||||
|
#!/usr/bin/env bash
|
||||||
|
set -euo pipefail
|
||||||
|
|
||||||
|
# -----------------------------------------------------------------------------
|
||||||
|
# Database Backup Script for Immich Redaktionsportal
|
||||||
|
# Usage: ./scripts/backup-db.sh /path/to/backup/directory
|
||||||
|
# -----------------------------------------------------------------------------
|
||||||
|
|
||||||
|
OUT_DIR="${1:-}"
|
||||||
|
|
||||||
|
if [[ -z "${OUT_DIR}" ]]; then
|
||||||
|
echo "Error: Backup output directory argument is required." >&2
|
||||||
|
echo "Usage: $0 /path/to/backup-dir" >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
# Normalize path
|
||||||
|
OUT_DIR="$(cd "${OUT_DIR}" 2>/dev/null && pwd || echo "${OUT_DIR}")"
|
||||||
|
|
||||||
|
# Safety checks: reject root, HOME directory, or empty path
|
||||||
|
if [[ "${OUT_DIR}" == "/" ]]; then
|
||||||
|
echo "Error: Refusing to write backup directly to root directory '/'." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
if [[ -n "${HOME:-}" && "${OUT_DIR}" == "${HOME}" ]]; then
|
||||||
|
echo "Error: Refusing to write backup directly to home directory '${HOME}'." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
mkdir -p "${OUT_DIR}"
|
||||||
|
|
||||||
|
TIMESTAMP="$(date -u +"%Y%m%d_%H%M%SZ")"
|
||||||
|
BACKUP_FILE="${OUT_DIR}/portal_backup_${TIMESTAMP}.dump"
|
||||||
|
|
||||||
|
echo "Starting database backup to ${BACKUP_FILE}..."
|
||||||
|
|
||||||
|
if command -v docker >/dev/null 2>&1 && docker ps --format '{{.Names}}' | grep -q '^portal-db$'; then
|
||||||
|
echo "Backing up via portal-db Docker container..."
|
||||||
|
docker exec -t portal-db pg_dump -U "${POSTGRES_USER:-portal}" -d "${POSTGRES_DB:-portal}" --format=custom > "${BACKUP_FILE}"
|
||||||
|
elif [[ -n "${DATABASE_URL:-}" ]]; then
|
||||||
|
echo "Backing up via local pg_dump using DATABASE_URL..."
|
||||||
|
pg_dump --format=custom --dbname="${DATABASE_URL}" > "${BACKUP_FILE}"
|
||||||
|
else
|
||||||
|
echo "Error: Neither portal-db docker container nor DATABASE_URL environment variable is available." >&2
|
||||||
|
exit 1
|
||||||
|
fi
|
||||||
|
|
||||||
|
echo "Backup complete: ${BACKUP_FILE} ($(du -h "${BACKUP_FILE}" | cut -f1))"
|
||||||
@@ -0,0 +1,218 @@
|
|||||||
|
#!/usr/bin/env tsx
|
||||||
|
/**
|
||||||
|
* Renders stress-test PDFs from BillingReportSnapshot fixtures into tmp/pdfs/.
|
||||||
|
*
|
||||||
|
* Covers: 1 row, 60 rows, long German company/address text, long
|
||||||
|
* filenames/purposes, umlauts (äöüß), and a 3-page case.
|
||||||
|
*
|
||||||
|
* Run: pnpm tsx scripts/render-pdf-fixture.ts
|
||||||
|
*
|
||||||
|
* PNG visual inspection (pdftoppm) is deferred to Task 15 — this script only
|
||||||
|
* generates the PDFs. When pdftoppm is available, run:
|
||||||
|
* pdftoppm -png tmp/pdfs/billing-stress.pdf tmp/pdfs/billing-stress
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { promises as fs } from "node:fs";
|
||||||
|
import path from "node:path";
|
||||||
|
|
||||||
|
import type { BillingReportSnapshot } from "../src/modules/billing/types";
|
||||||
|
import { renderBillingPdf } from "../src/modules/pdf/render";
|
||||||
|
|
||||||
|
const OUTPUT_DIR = path.join(process.cwd(), "tmp", "pdfs");
|
||||||
|
|
||||||
|
function baseAddress() {
|
||||||
|
return {
|
||||||
|
companyName: "Redaktion Beispiel GmbH",
|
||||||
|
contactName: "Anna Schmidt",
|
||||||
|
addressLine1: "Musterstraße 12",
|
||||||
|
addressLine2: null as string | null,
|
||||||
|
postalCode: "10115",
|
||||||
|
city: "Berlin",
|
||||||
|
countryCode: "DE",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function basePosition(priceCents = 6_000) {
|
||||||
|
return {
|
||||||
|
id: "pos-1",
|
||||||
|
assetId: "asset-1",
|
||||||
|
filename: "jubel-eroeffnung.jpg",
|
||||||
|
albumName: "Jubel",
|
||||||
|
purpose: "Print Nutzung",
|
||||||
|
reference: "REF-001" as string | null,
|
||||||
|
priceCents,
|
||||||
|
createdAt: new Date("2026-03-15T10:00:00.000Z"),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function baseRepeatDownload() {
|
||||||
|
return {
|
||||||
|
id: "rdl-1",
|
||||||
|
assetId: "asset-1",
|
||||||
|
usageId: "usage-1",
|
||||||
|
authorizedAt: new Date("2026-03-20T14:00:00.000Z"),
|
||||||
|
repeatDownloadNote: "Zweitverwendung im Web" as string | null,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function baseSnapshot(overrides: Partial<BillingReportSnapshot> = {}): BillingReportSnapshot {
|
||||||
|
return {
|
||||||
|
address: baseAddress(),
|
||||||
|
selectedPositions: [basePosition()],
|
||||||
|
repeatDownloads: [baseRepeatDownload()],
|
||||||
|
netTotalCents: 6_000,
|
||||||
|
reportNumber: 1,
|
||||||
|
invoiceNumber: "NN-2026-03-001",
|
||||||
|
period: {
|
||||||
|
fromUtc: new Date("2026-03-01T00:00:00.000Z"),
|
||||||
|
toUtcExclusive: new Date("2026-04-01T00:00:00.000Z"),
|
||||||
|
},
|
||||||
|
documentId: "doc-00000000-0000-0000-0000-000000000001",
|
||||||
|
createdAt: new Date("2026-04-02T08:00:00.000Z"),
|
||||||
|
legalSeparationNotice:
|
||||||
|
"Dieser Nutzungsnachweis ist keine Rechnung im Sinne des Umsatzsteuerrechts.",
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Fixture builders -------------------------------------------------------
|
||||||
|
|
||||||
|
function oneRowFixture(): BillingReportSnapshot {
|
||||||
|
return baseSnapshot();
|
||||||
|
}
|
||||||
|
|
||||||
|
function sixtyRowsFixture(): BillingReportSnapshot {
|
||||||
|
const positions = Array.from({ length: 60 }, (_, i) => ({
|
||||||
|
...basePosition(500),
|
||||||
|
id: `pos-${i + 1}`,
|
||||||
|
assetId: `asset-${i + 1}`,
|
||||||
|
filename: `bild-${String(i + 1).padStart(3, "0")}.jpg`,
|
||||||
|
reference: `REF-${String(i + 1).padStart(3, "0")}`,
|
||||||
|
}));
|
||||||
|
const netTotal = positions.reduce((sum, p) => sum + p.priceCents, 0);
|
||||||
|
return baseSnapshot({
|
||||||
|
selectedPositions: positions,
|
||||||
|
repeatDownloads: [],
|
||||||
|
netTotalCents: netTotal,
|
||||||
|
invoiceNumber: "NN-2026-03-060",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function longAddressFixture(): BillingReportSnapshot {
|
||||||
|
return baseSnapshot({
|
||||||
|
address: {
|
||||||
|
companyName: "Süddeutsche Verlagsgesellschaft mbH & Co. KG Herausgeber-Bevollmächtigte",
|
||||||
|
contactName: "Dr. Maximilian von und zu Müllendorf-Wiesenbach",
|
||||||
|
addressLine1: "Königsallee 42a, Hinterhof 3. Stock, Raum 312",
|
||||||
|
addressLine2: "Nebengebäude bei der alten Mühle",
|
||||||
|
postalCode: "80331",
|
||||||
|
city: "München",
|
||||||
|
countryCode: "DE",
|
||||||
|
},
|
||||||
|
invoiceNumber: "NN-2026-03-LONG",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function longFieldsFixture(): BillingReportSnapshot {
|
||||||
|
return baseSnapshot({
|
||||||
|
selectedPositions: [
|
||||||
|
{
|
||||||
|
...basePosition(12_500),
|
||||||
|
id: "pos-long-1",
|
||||||
|
filename: "jahreshauptversammlung-eroeffnungsrede-vorstandsvorsitzender-2026.jpg",
|
||||||
|
albumName: "Jahreshauptversammlung 2026 — Rückblick und Ausblick",
|
||||||
|
purpose: "Print-Nutzung in der Sonderbeilage zum Jahresrückblick der Zeitung",
|
||||||
|
reference: "REF-Sonderbeilage-2026-Q1-001",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
...basePosition(8_750),
|
||||||
|
id: "pos-long-2",
|
||||||
|
filename: "pressekonferenz-ministerpräsident-bayern-klimaschutzgesetz.jpg",
|
||||||
|
albumName: "Pressekonferenz Klimaschutz",
|
||||||
|
purpose: "Online-Nutzung im Nachrichtenportal sowie Print-Ausgabe",
|
||||||
|
reference: "REF-PK-Klima-2026-03-15",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
netTotalCents: 21_250,
|
||||||
|
invoiceNumber: "NN-2026-03-LONGFIELDS",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function umlautsFixture(): BillingReportSnapshot {
|
||||||
|
return baseSnapshot({
|
||||||
|
selectedPositions: [
|
||||||
|
{
|
||||||
|
...basePosition(3_500),
|
||||||
|
id: "pos-umlaut-1",
|
||||||
|
filename: "münchen-strße-österreich.jpg",
|
||||||
|
albumName: "Münchner Straße Österreich",
|
||||||
|
purpose: "Äöüß Nutzung für Flüsse und Öfen",
|
||||||
|
reference: "REF-ÄÖÜß-001",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
repeatDownloads: [
|
||||||
|
{
|
||||||
|
...baseRepeatDownload(),
|
||||||
|
id: "rdl-umlaut-1",
|
||||||
|
repeatDownloadNote: "Zweitverwendung für Grüße aus Übersee",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
netTotalCents: 3_500,
|
||||||
|
invoiceNumber: "NN-2026-03-UMLAUT",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function threePageFixture(): BillingReportSnapshot {
|
||||||
|
const positions = Array.from({ length: 45 }, (_, i) => ({
|
||||||
|
...basePosition(300),
|
||||||
|
id: `pos-3p-${i + 1}`,
|
||||||
|
assetId: `asset-3p-${i + 1}`,
|
||||||
|
filename: `seite3-bild-${String(i + 1).padStart(3, "0")}.jpg`,
|
||||||
|
albumName: `Album ${i + 1}`,
|
||||||
|
purpose: `Nutzung ${i + 1}`,
|
||||||
|
reference: `REF-3P-${String(i + 1).padStart(3, "0")}`,
|
||||||
|
}));
|
||||||
|
const downloads = Array.from({ length: 30 }, (_, i) => ({
|
||||||
|
...baseRepeatDownload(),
|
||||||
|
id: `rdl-3p-${i + 1}`,
|
||||||
|
assetId: `asset-3p-${i + 1}`,
|
||||||
|
usageId: `usage-3p-${i + 1}`,
|
||||||
|
repeatDownloadNote: `Hinweis für Download ${i + 1}`,
|
||||||
|
}));
|
||||||
|
const netTotal = positions.reduce((sum, p) => sum + p.priceCents, 0);
|
||||||
|
return baseSnapshot({
|
||||||
|
selectedPositions: positions,
|
||||||
|
repeatDownloads: downloads,
|
||||||
|
netTotalCents: netTotal,
|
||||||
|
invoiceNumber: "NN-2026-03-3PAGE",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// --- Main -------------------------------------------------------------------
|
||||||
|
|
||||||
|
async function main() {
|
||||||
|
await fs.mkdir(OUTPUT_DIR, { recursive: true });
|
||||||
|
|
||||||
|
const fixtures: Array<{ name: string; snapshot: BillingReportSnapshot }> = [
|
||||||
|
{ name: "billing-one-row.pdf", snapshot: oneRowFixture() },
|
||||||
|
{ name: "billing-60-rows.pdf", snapshot: sixtyRowsFixture() },
|
||||||
|
{ name: "billing-long-address.pdf", snapshot: longAddressFixture() },
|
||||||
|
{ name: "billing-long-fields.pdf", snapshot: longFieldsFixture() },
|
||||||
|
{ name: "billing-umlauts.pdf", snapshot: umlautsFixture() },
|
||||||
|
{ name: "billing-stress.pdf", snapshot: threePageFixture() },
|
||||||
|
];
|
||||||
|
|
||||||
|
for (const { name, snapshot } of fixtures) {
|
||||||
|
const result = await renderBillingPdf(snapshot);
|
||||||
|
const outPath = path.join(OUTPUT_DIR, name);
|
||||||
|
await fs.writeFile(outPath, result.bytes);
|
||||||
|
console.log(`${name} ${result.bytes.length} bytes sha256=${result.sha256.slice(0, 16)}…`);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log(`\nDone. ${fixtures.length} PDFs written to ${OUTPUT_DIR}/`);
|
||||||
|
}
|
||||||
|
|
||||||
|
main().catch((err) => {
|
||||||
|
console.error(err);
|
||||||
|
process.exit(1);
|
||||||
|
});
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import Link from "next/link";
|
||||||
|
|
||||||
|
import { env } from "@/config/env";
|
||||||
|
import { LoginForm } from "@/modules/auth/public-forms";
|
||||||
|
|
||||||
|
export default function LoginPage() {
|
||||||
|
return (
|
||||||
|
<main className="public-account-page">
|
||||||
|
<header className="masthead">
|
||||||
|
<Link className="wordmark" href="/">
|
||||||
|
Leon Tonhäuser
|
||||||
|
</Link>
|
||||||
|
<span className="section-label">Redaktionsportal</span>
|
||||||
|
</header>
|
||||||
|
<section className="account-panel" aria-labelledby="login-title">
|
||||||
|
<p className="eyebrow">Zugang</p>
|
||||||
|
<h1 id="login-title">Anmelden</h1>
|
||||||
|
<p className="lede">Melden Sie sich mit der E-Mail-Adresse Ihrer Redaktion an.</p>
|
||||||
|
<LoginForm />
|
||||||
|
<nav className="account-links" aria-label="Zugang verwalten">
|
||||||
|
<Link href="/passwort-vergessen">Passwort vergessen?</Link>
|
||||||
|
<Link href="/registrieren">Neue Redaktion registrieren</Link>
|
||||||
|
</nav>
|
||||||
|
</section>
|
||||||
|
<LegalFooter imprint={env.LEGAL_IMPRINT_URL} privacy={env.LEGAL_PRIVACY_URL} terms={env.LEGAL_TERMS_URL} />
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function LegalFooter({ imprint, privacy, terms }: { imprint: string; privacy: string; terms: string }) {
|
||||||
|
return (
|
||||||
|
<footer className="public-footer">
|
||||||
|
<a href={imprint}>Impressum</a>
|
||||||
|
<a href={privacy}>Datenschutz</a>
|
||||||
|
<a href={terms}>Nutzungsbedingungen</a>
|
||||||
|
</footer>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import Link from "next/link";
|
||||||
|
|
||||||
|
import { PasswordResetRequestForm } from "@/modules/auth/public-forms";
|
||||||
|
|
||||||
|
export default function ForgotPasswordPage() {
|
||||||
|
return (
|
||||||
|
<main className="public-account-page">
|
||||||
|
<header className="masthead">
|
||||||
|
<Link className="wordmark" href="/">
|
||||||
|
Leon Tonhäuser
|
||||||
|
</Link>
|
||||||
|
<span className="section-label">Redaktionsportal</span>
|
||||||
|
</header>
|
||||||
|
<section className="account-panel" aria-labelledby="forgot-password-title">
|
||||||
|
<p className="eyebrow">Zugang</p>
|
||||||
|
<h1 id="forgot-password-title">Passwort vergessen?</h1>
|
||||||
|
<p className="lede">Fordern Sie einen Link zum Zurücksetzen Ihres Passworts an.</p>
|
||||||
|
<PasswordResetRequestForm />
|
||||||
|
<nav className="account-links" aria-label="Zurück zur Anmeldung">
|
||||||
|
<Link href="/anmelden">Zur Anmeldung</Link>
|
||||||
|
</nav>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import Link from "next/link";
|
||||||
|
|
||||||
|
import { PasswordResetForm } from "@/modules/auth/public-forms";
|
||||||
|
|
||||||
|
export default async function ResetPasswordPage({
|
||||||
|
searchParams,
|
||||||
|
}: {
|
||||||
|
searchParams: Promise<{ token?: string }>;
|
||||||
|
}) {
|
||||||
|
const { token } = await searchParams;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<main className="public-account-page">
|
||||||
|
<header className="masthead">
|
||||||
|
<Link className="wordmark" href="/">
|
||||||
|
Leon Tonhäuser
|
||||||
|
</Link>
|
||||||
|
<span className="section-label">Redaktionsportal</span>
|
||||||
|
</header>
|
||||||
|
<section className="account-panel" aria-labelledby="reset-password-title">
|
||||||
|
<p className="eyebrow">Zugang</p>
|
||||||
|
<h1 id="reset-password-title">Neues Passwort setzen</h1>
|
||||||
|
<p className="lede">Wählen Sie ein neues Passwort für den Zugang Ihrer Redaktion.</p>
|
||||||
|
<PasswordResetForm token={token} />
|
||||||
|
<nav className="account-links" aria-label="Zurück zur Anmeldung">
|
||||||
|
<Link href="/anmelden">Zur Anmeldung</Link>
|
||||||
|
</nav>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import Link from "next/link";
|
||||||
|
|
||||||
|
export default function RegistrationConfirmedPage() {
|
||||||
|
return (
|
||||||
|
<main className="public-account-page">
|
||||||
|
<header className="masthead">
|
||||||
|
<Link className="wordmark" href="/">
|
||||||
|
Leon Tonhäuser
|
||||||
|
</Link>
|
||||||
|
<span className="section-label">Redaktionsportal</span>
|
||||||
|
</header>
|
||||||
|
<section className="account-panel" aria-labelledby="confirmation-title">
|
||||||
|
<p className="eyebrow">Registrierung</p>
|
||||||
|
<h1 id="confirmation-title">Vielen Dank.</h1>
|
||||||
|
<p className="lede">
|
||||||
|
Bitte folgen Sie den weiteren Hinweisen, die wir Ihnen gegebenenfalls zusenden. Danach
|
||||||
|
prüfen wir Ihre Registrierung.
|
||||||
|
</p>
|
||||||
|
<Link className="primary-action" href="/anmelden">
|
||||||
|
Zur Anmeldung
|
||||||
|
</Link>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
import Link from "next/link";
|
||||||
|
import { redirect } from "next/navigation";
|
||||||
|
|
||||||
|
import { env } from "@/config/env";
|
||||||
|
import { registerEditorial } from "@/modules/auth/auth";
|
||||||
|
import {
|
||||||
|
CURRENT_TERMS_VERSION,
|
||||||
|
RegistrationValidationError,
|
||||||
|
} from "@/modules/auth/registration";
|
||||||
|
import {
|
||||||
|
RegistrationForm,
|
||||||
|
type RegistrationFormState,
|
||||||
|
} from "@/modules/auth/public-forms";
|
||||||
|
|
||||||
|
export default function RegistrationPage() {
|
||||||
|
return (
|
||||||
|
<main className="public-account-page">
|
||||||
|
<header className="masthead">
|
||||||
|
<Link className="wordmark" href="/">
|
||||||
|
Leon Tonhäuser
|
||||||
|
</Link>
|
||||||
|
<span className="section-label">Redaktionsportal</span>
|
||||||
|
</header>
|
||||||
|
<section className="account-panel account-panel-wide" aria-labelledby="registration-title">
|
||||||
|
<p className="eyebrow">B2B-Zugang</p>
|
||||||
|
<h1 id="registration-title">Redaktion registrieren</h1>
|
||||||
|
<p className="lede">
|
||||||
|
Das Redaktionsportal steht ausschließlich Unternehmen und Redaktionen zur Verfügung.
|
||||||
|
</p>
|
||||||
|
<RegistrationForm
|
||||||
|
action={registerAction}
|
||||||
|
legalUrls={{
|
||||||
|
imprint: env.LEGAL_IMPRINT_URL,
|
||||||
|
privacy: env.LEGAL_PRIVACY_URL,
|
||||||
|
terms: env.LEGAL_TERMS_URL,
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
</section>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function registerAction(
|
||||||
|
_state: RegistrationFormState,
|
||||||
|
formData: FormData,
|
||||||
|
): Promise<RegistrationFormState> {
|
||||||
|
"use server";
|
||||||
|
|
||||||
|
try {
|
||||||
|
await registerEditorial({
|
||||||
|
companyName: text(formData, "companyName"),
|
||||||
|
contactName: text(formData, "contactName"),
|
||||||
|
email: text(formData, "email"),
|
||||||
|
password: text(formData, "password"),
|
||||||
|
billingAddress: {
|
||||||
|
addressLine1: text(formData, "addressLine1"),
|
||||||
|
addressLine2: text(formData, "addressLine2") || undefined,
|
||||||
|
postalCode: text(formData, "postalCode"),
|
||||||
|
city: text(formData, "city"),
|
||||||
|
countryCode: text(formData, "countryCode"),
|
||||||
|
},
|
||||||
|
actsForBusiness: formData.has("actsForBusiness"),
|
||||||
|
termsVersion: formData.has("termsAccepted") ? CURRENT_TERMS_VERSION : "",
|
||||||
|
privacyAcknowledged: formData.has("privacyAcknowledged"),
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof RegistrationValidationError) {
|
||||||
|
return { errors: { [error.field]: error.message } };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
redirect("/registrieren/bestaetigt");
|
||||||
|
}
|
||||||
|
|
||||||
|
function text(formData: FormData, name: string): string {
|
||||||
|
const value = formData.get(name);
|
||||||
|
return typeof value === "string" ? value : "";
|
||||||
|
}
|
||||||
@@ -0,0 +1,206 @@
|
|||||||
|
// @vitest-environment jsdom
|
||||||
|
|
||||||
|
import { render, screen, fireEvent, cleanup } from "@testing-library/react";
|
||||||
|
import { afterEach, expect, test } from "vitest";
|
||||||
|
|
||||||
|
import { BillingSelection } from "./BillingSelection";
|
||||||
|
import type { FinalizedReportSummary } from "./page-content";
|
||||||
|
import type { BillingPosition, RepeatDownloadPosition } from "@/modules/billing/queries";
|
||||||
|
|
||||||
|
afterEach(cleanup);
|
||||||
|
|
||||||
|
const openPosition: BillingPosition = {
|
||||||
|
id: "u1",
|
||||||
|
assetId: "asset-1",
|
||||||
|
filename: "jubel.jpg",
|
||||||
|
albumName: "Presse 2026",
|
||||||
|
purpose: "Titelgeschichte",
|
||||||
|
reference: "Ausgabe 8/26",
|
||||||
|
priceCents: 6_000,
|
||||||
|
status: "open",
|
||||||
|
selectable: true,
|
||||||
|
createdAt: new Date("2026-08-05T10:00:00.000Z"),
|
||||||
|
reportNumber: null,
|
||||||
|
invoiceNumber: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
const billedPosition: BillingPosition = {
|
||||||
|
id: "u2",
|
||||||
|
assetId: "asset-2",
|
||||||
|
filename: "sport.jpg",
|
||||||
|
albumName: "Presse 2026",
|
||||||
|
purpose: "Sportbericht",
|
||||||
|
reference: null,
|
||||||
|
priceCents: 1_500,
|
||||||
|
status: "billed",
|
||||||
|
selectable: false,
|
||||||
|
createdAt: new Date("2026-08-06T10:00:00.000Z"),
|
||||||
|
reportNumber: 42,
|
||||||
|
invoiceNumber: "RE-2026-042",
|
||||||
|
};
|
||||||
|
|
||||||
|
const reopenedPosition: BillingPosition = {
|
||||||
|
id: "u3",
|
||||||
|
assetId: "asset-3",
|
||||||
|
filename: "redaktion.jpg",
|
||||||
|
albumName: "Presse 2026",
|
||||||
|
purpose: "Reopened",
|
||||||
|
reference: null,
|
||||||
|
priceCents: 1_500,
|
||||||
|
status: "reopened",
|
||||||
|
selectable: true,
|
||||||
|
createdAt: new Date("2026-08-07T10:00:00.000Z"),
|
||||||
|
reportNumber: null,
|
||||||
|
invoiceNumber: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
const repeatDownload: RepeatDownloadPosition = {
|
||||||
|
id: "d1",
|
||||||
|
assetId: "asset-1",
|
||||||
|
usageId: "u1",
|
||||||
|
authorizedAt: new Date("2026-08-10T12:00:00.000Z"),
|
||||||
|
status: "completed",
|
||||||
|
repeatDownloadNote: "Zweite Nutzung",
|
||||||
|
};
|
||||||
|
|
||||||
|
const defaultProps = {
|
||||||
|
editorialId: "e1",
|
||||||
|
repeatDownloads: [] as RepeatDownloadPosition[],
|
||||||
|
year: 2026,
|
||||||
|
month: 8 as number | null,
|
||||||
|
quarter: null as number | null,
|
||||||
|
isQuarter: false,
|
||||||
|
periodLabel: "August 2026",
|
||||||
|
reports: [] as FinalizedReportSummary[],
|
||||||
|
};
|
||||||
|
|
||||||
|
function getCheckbox(filename: string): HTMLInputElement {
|
||||||
|
return screen.getByRole("checkbox", {
|
||||||
|
name: `${filename} auswählen`,
|
||||||
|
}) as HTMLInputElement;
|
||||||
|
}
|
||||||
|
|
||||||
|
test("renders billable positions with individual checkboxes", () => {
|
||||||
|
render(
|
||||||
|
<BillingSelection
|
||||||
|
{...defaultProps}
|
||||||
|
positions={[openPosition, billedPosition]}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(screen.getByText("jubel.jpg")).toBeTruthy();
|
||||||
|
expect(screen.getByText("sport.jpg")).toBeTruthy();
|
||||||
|
expect(getCheckbox("jubel.jpg").checked).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("disables the checkbox for billed positions and shows report reference", () => {
|
||||||
|
render(
|
||||||
|
<BillingSelection
|
||||||
|
{...defaultProps}
|
||||||
|
positions={[billedPosition]}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
const checkbox = getCheckbox("sport.jpg");
|
||||||
|
expect(checkbox.disabled).toBe(true);
|
||||||
|
expect(screen.getByText(/Bericht Nr\. 42/)).toBeTruthy();
|
||||||
|
expect(screen.getByText(/RE-2026-042/)).toBeTruthy();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("selects all open positions via Alle offenen im Monat", () => {
|
||||||
|
render(
|
||||||
|
<BillingSelection
|
||||||
|
{...defaultProps}
|
||||||
|
positions={[openPosition, billedPosition, reopenedPosition]}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: /Alle offenen im Monat/i }));
|
||||||
|
|
||||||
|
expect(getCheckbox("jubel.jpg").checked).toBe(true);
|
||||||
|
expect(getCheckbox("redaktion.jpg").checked).toBe(true);
|
||||||
|
expect(getCheckbox("sport.jpg").checked).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("clears the selection via Auswahl aufheben", () => {
|
||||||
|
render(
|
||||||
|
<BillingSelection
|
||||||
|
{...defaultProps}
|
||||||
|
positions={[openPosition]}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
const checkbox = getCheckbox("jubel.jpg");
|
||||||
|
fireEvent.click(checkbox);
|
||||||
|
expect(checkbox.checked).toBe(true);
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: /Auswahl aufheben/i }));
|
||||||
|
expect(checkbox.checked).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("displays selected count and cents-derived EUR total", () => {
|
||||||
|
const { container } = render(
|
||||||
|
<BillingSelection
|
||||||
|
{...defaultProps}
|
||||||
|
positions={[openPosition, reopenedPosition]}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: /Alle offenen im Monat/i }));
|
||||||
|
|
||||||
|
const summary = container.querySelector(".billing-summary");
|
||||||
|
expect(summary?.textContent ?? "").toMatch(/2 Nutzungen ausgewählt/);
|
||||||
|
expect(summary?.textContent ?? "").toMatch(/75,00 EUR/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("renders repeat downloads in a separate section", () => {
|
||||||
|
render(
|
||||||
|
<BillingSelection
|
||||||
|
{...defaultProps}
|
||||||
|
positions={[openPosition]}
|
||||||
|
repeatDownloads={[repeatDownload]}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(screen.getByText(/Kostenlose Wiederabrufe/)).toBeTruthy();
|
||||||
|
expect(screen.getByText("Zweite Nutzung")).toBeTruthy();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("shows empty state when no billable positions exist", () => {
|
||||||
|
render(
|
||||||
|
<BillingSelection
|
||||||
|
{...defaultProps}
|
||||||
|
positions={[]}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(screen.getByText(/Keine abrechenbaren Nutzungen/)).toBeTruthy();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("links to quarter view from month view", () => {
|
||||||
|
render(
|
||||||
|
<BillingSelection
|
||||||
|
{...defaultProps}
|
||||||
|
positions={[openPosition]}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
const quarterLink = screen.getByRole("link", { name: /Ganzes Quartal/i });
|
||||||
|
expect(quarterLink.getAttribute("href") ?? "").toContain("quarter=3");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("links to month view from quarter view", () => {
|
||||||
|
render(
|
||||||
|
<BillingSelection
|
||||||
|
{...defaultProps}
|
||||||
|
positions={[openPosition]}
|
||||||
|
month={null}
|
||||||
|
quarter={3}
|
||||||
|
isQuarter={true}
|
||||||
|
periodLabel="Q3 2026"
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
const monthLink = screen.getByRole("link", { name: /Monatsansicht/i });
|
||||||
|
expect(monthLink.getAttribute("href") ?? "").toContain("month=");
|
||||||
|
});
|
||||||
@@ -0,0 +1,468 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useMemo, useState } from "react";
|
||||||
|
import Link from "next/link";
|
||||||
|
|
||||||
|
import type { BillingPosition, RepeatDownloadPosition } from "@/modules/billing/queries";
|
||||||
|
import { formatCents } from "@/modules/billing/format";
|
||||||
|
import type { FinalizedReportSummary } from "./page-content";
|
||||||
|
|
||||||
|
type BillingSelectionProps = {
|
||||||
|
editorialId: string;
|
||||||
|
positions: BillingPosition[];
|
||||||
|
repeatDownloads: RepeatDownloadPosition[];
|
||||||
|
year: number;
|
||||||
|
month: number | null;
|
||||||
|
quarter: number | null;
|
||||||
|
isQuarter: boolean;
|
||||||
|
periodLabel: string;
|
||||||
|
reports: FinalizedReportSummary[];
|
||||||
|
};
|
||||||
|
|
||||||
|
const MONTHS = [
|
||||||
|
"Januar",
|
||||||
|
"Februar",
|
||||||
|
"März",
|
||||||
|
"April",
|
||||||
|
"Mai",
|
||||||
|
"Juni",
|
||||||
|
"Juli",
|
||||||
|
"August",
|
||||||
|
"September",
|
||||||
|
"Oktober",
|
||||||
|
"November",
|
||||||
|
"Dezember",
|
||||||
|
];
|
||||||
|
|
||||||
|
const STATUS_LABELS: Record<BillingPosition["status"], string> = {
|
||||||
|
open: "Offen",
|
||||||
|
billed: "Abgerechnet",
|
||||||
|
reopened: "Wiedereröffnet",
|
||||||
|
};
|
||||||
|
|
||||||
|
const REPORT_STATUS_LABELS: Record<string, string> = {
|
||||||
|
draft: "Entwurf",
|
||||||
|
final: "Erstellt",
|
||||||
|
cancelled: "Storniert",
|
||||||
|
};
|
||||||
|
|
||||||
|
export function BillingSelection({
|
||||||
|
editorialId,
|
||||||
|
positions,
|
||||||
|
repeatDownloads,
|
||||||
|
year,
|
||||||
|
month,
|
||||||
|
quarter,
|
||||||
|
isQuarter,
|
||||||
|
periodLabel,
|
||||||
|
reports,
|
||||||
|
}: BillingSelectionProps) {
|
||||||
|
const [selectedIds, setSelectedIds] = useState<Set<string>>(new Set());
|
||||||
|
const [actionState, setActionState] = useState<{
|
||||||
|
loading: boolean;
|
||||||
|
message: string | null;
|
||||||
|
isError: boolean;
|
||||||
|
}>({ loading: false, message: null, isError: false });
|
||||||
|
|
||||||
|
const selectablePositions = useMemo(
|
||||||
|
() => positions.filter((p) => p.selectable),
|
||||||
|
[positions],
|
||||||
|
);
|
||||||
|
|
||||||
|
const selectedCount = selectedIds.size;
|
||||||
|
const selectedTotalCents = useMemo(
|
||||||
|
() =>
|
||||||
|
positions.reduce(
|
||||||
|
(sum, p) => (selectedIds.has(p.id) ? sum + p.priceCents : sum),
|
||||||
|
0,
|
||||||
|
),
|
||||||
|
[positions, selectedIds],
|
||||||
|
);
|
||||||
|
|
||||||
|
function togglePosition(id: string) {
|
||||||
|
setSelectedIds((prev) => {
|
||||||
|
const next = new Set(prev);
|
||||||
|
if (next.has(id)) next.delete(id);
|
||||||
|
else next.add(id);
|
||||||
|
return next;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function selectAllOpen() {
|
||||||
|
setSelectedIds(new Set(selectablePositions.map((p) => p.id)));
|
||||||
|
}
|
||||||
|
|
||||||
|
function clearSelection() {
|
||||||
|
setSelectedIds(new Set());
|
||||||
|
}
|
||||||
|
|
||||||
|
const periodPayload = { year, ...(isQuarter ? { quarter: quarter ?? 1 } : { month: month ?? 1 }) };
|
||||||
|
|
||||||
|
async function handlePreview() {
|
||||||
|
if (selectedIds.size === 0) return;
|
||||||
|
setActionState({ loading: true, message: null, isError: false });
|
||||||
|
try {
|
||||||
|
const response = await fetch("/api/billing-reports/preview", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "content-type": "application/json" },
|
||||||
|
body: JSON.stringify({
|
||||||
|
editorialId,
|
||||||
|
usageIds: [...selectedIds],
|
||||||
|
...periodPayload,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
if (!response.ok) {
|
||||||
|
const body = await response.json().catch(() => ({ code: "ERROR" }));
|
||||||
|
throw new Error(body.code ?? "Vorschau fehlgeschlagen");
|
||||||
|
}
|
||||||
|
const blob = await response.blob();
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
window.open(url, "_blank");
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
setActionState({ loading: false, message: null, isError: false });
|
||||||
|
} catch (error) {
|
||||||
|
setActionState({
|
||||||
|
loading: false,
|
||||||
|
message: error instanceof Error ? error.message : "Vorschau fehlgeschlagen",
|
||||||
|
isError: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleFinalize() {
|
||||||
|
if (selectedIds.size === 0) return;
|
||||||
|
setActionState({ loading: true, message: null, isError: false });
|
||||||
|
try {
|
||||||
|
const response = await fetch("/api/billing-reports", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "content-type": "application/json" },
|
||||||
|
body: JSON.stringify({
|
||||||
|
editorialId,
|
||||||
|
usageIds: [...selectedIds],
|
||||||
|
...periodPayload,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
if (!response.ok) {
|
||||||
|
const body = await response.json().catch(() => ({ code: "ERROR" }));
|
||||||
|
throw new Error(body.code ?? "Abrechnung konnte nicht erstellt werden");
|
||||||
|
}
|
||||||
|
const result = await response.json();
|
||||||
|
setActionState({
|
||||||
|
loading: false,
|
||||||
|
message: `Abrechnung Nr. ${result.reportNumber} wurde erstellt.`,
|
||||||
|
isError: false,
|
||||||
|
});
|
||||||
|
window.location.reload();
|
||||||
|
} catch (error) {
|
||||||
|
setActionState({
|
||||||
|
loading: false,
|
||||||
|
message: error instanceof Error ? error.message : "Abrechnung fehlgeschlagen",
|
||||||
|
isError: true,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const quarterParam = isQuarter ? null : Math.ceil((month ?? 1) / 3);
|
||||||
|
const quarterHref = quarter
|
||||||
|
? `/admin/abrechnungen/${editorialId}?year=${year}&quarter=${quarter}`
|
||||||
|
: `/admin/abrechnungen/${editorialId}?year=${year}&quarter=${quarterParam}`;
|
||||||
|
const monthHref = `/admin/abrechnungen/${editorialId}?year=${year}&month=${month ?? (quarter ? (quarter - 1) * 3 + 1 : new Date().getUTCMonth() + 1)}`;
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<PeriodSelector year={year} month={month} quarter={quarter} isQuarter={isQuarter} />
|
||||||
|
|
||||||
|
<div className="billing-selection-controls">
|
||||||
|
<button type="button" onClick={selectAllOpen} disabled={selectablePositions.length === 0}>
|
||||||
|
{isQuarter ? "Alle offenen im Quartal" : "Alle offenen im Monat"}
|
||||||
|
</button>
|
||||||
|
{isQuarter ? (
|
||||||
|
<Link href={monthHref} className="billing-nav-link">
|
||||||
|
Monatsansicht
|
||||||
|
</Link>
|
||||||
|
) : (
|
||||||
|
<Link href={quarterHref} className="billing-nav-link">
|
||||||
|
Ganzes Quartal
|
||||||
|
</Link>
|
||||||
|
)}
|
||||||
|
<button type="button" onClick={clearSelection} disabled={selectedCount === 0}>
|
||||||
|
Auswahl aufheben
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<p className="billing-period-label" aria-live="polite">
|
||||||
|
Zeitraum: {periodLabel}
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{positions.length === 0 ? (
|
||||||
|
<p className="billing-empty">Keine abrechenbaren Nutzungen in diesem Zeitraum.</p>
|
||||||
|
) : (
|
||||||
|
<table className="billing-table">
|
||||||
|
<caption className="billing-caption">
|
||||||
|
Abrechenbare Nutzungen
|
||||||
|
</caption>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th scope="col">Auswahl</th>
|
||||||
|
<th scope="col">Datei</th>
|
||||||
|
<th scope="col">Album</th>
|
||||||
|
<th scope="col">Zweck</th>
|
||||||
|
<th scope="col">Referenz</th>
|
||||||
|
<th scope="col">Preis</th>
|
||||||
|
<th scope="col">Status</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{positions.map((position) => (
|
||||||
|
<tr key={position.id} className={position.selectable ? "" : "billing-row-billed"}>
|
||||||
|
<td>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={selectedIds.has(position.id)}
|
||||||
|
onChange={() => togglePosition(position.id)}
|
||||||
|
disabled={!position.selectable}
|
||||||
|
aria-label={`${position.filename} auswählen`}
|
||||||
|
/>
|
||||||
|
</td>
|
||||||
|
<td>{position.filename}</td>
|
||||||
|
<td>{position.albumName}</td>
|
||||||
|
<td>{position.purpose}</td>
|
||||||
|
<td>{position.reference ?? "—"}</td>
|
||||||
|
<td className="billing-price">{formatCents(position.priceCents)}</td>
|
||||||
|
<td>
|
||||||
|
<span className="billing-status">
|
||||||
|
{STATUS_LABELS[position.status]}
|
||||||
|
{position.status === "billed" && position.reportNumber !== null && (
|
||||||
|
<span className="billing-report-ref">
|
||||||
|
{" "}· Bericht Nr. {position.reportNumber}
|
||||||
|
{position.invoiceNumber ? ` · ${position.invoiceNumber}` : ""}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</span>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{repeatDownloads.length > 0 && (
|
||||||
|
<section aria-labelledby="repeat-downloads-title" className="billing-repeat-section">
|
||||||
|
<h2 id="repeat-downloads-title">Kostenlose Wiederabrufe</h2>
|
||||||
|
<p className="form-note">
|
||||||
|
Wiederholte Downloads rufen bereits abgerechnete Nutzungen erneut ab und sind nicht
|
||||||
|
abrechenbar.
|
||||||
|
</p>
|
||||||
|
<table className="billing-table billing-table-repeat">
|
||||||
|
<caption className="billing-caption">Wiederabrufe im Zeitraum</caption>
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th scope="col">Datei</th>
|
||||||
|
<th scope="col">Datum</th>
|
||||||
|
<th scope="col">Status</th>
|
||||||
|
<th scope="col">Notiz</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{repeatDownloads.map((download) => (
|
||||||
|
<tr key={download.id}>
|
||||||
|
<td>{download.assetId}</td>
|
||||||
|
<td>
|
||||||
|
<time dateTime={download.authorizedAt.toISOString()}>
|
||||||
|
{download.authorizedAt.toLocaleDateString("de-DE")}
|
||||||
|
</time>
|
||||||
|
</td>
|
||||||
|
<td>{download.status}</td>
|
||||||
|
<td>{download.repeatDownloadNote ?? "—"}</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</section>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="billing-summary" aria-live="polite">
|
||||||
|
<p>
|
||||||
|
<strong>{selectedCount}</strong> {selectedCount === 1 ? "Nutzung" : "Nutzungen"} ausgewählt
|
||||||
|
</p>
|
||||||
|
<p className="billing-summary-total">
|
||||||
|
Summe: <strong>{formatCents(selectedTotalCents)}</strong>
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="billing-actions">
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={handlePreview}
|
||||||
|
disabled={selectedCount === 0 || actionState.loading}
|
||||||
|
>
|
||||||
|
Vorschau
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="billing-action-primary"
|
||||||
|
onClick={handleFinalize}
|
||||||
|
disabled={selectedCount === 0 || actionState.loading}
|
||||||
|
>
|
||||||
|
Abrechnung erstellen
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{actionState.message && (
|
||||||
|
<p className="billing-status-message" role={actionState.isError ? "alert" : "status"}>
|
||||||
|
{actionState.message}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{reports.length > 0 && (
|
||||||
|
<section aria-labelledby="reports-title" className="billing-reports-section">
|
||||||
|
<h2 id="reports-title">Erstellte Abrechnungen</h2>
|
||||||
|
<ul className="billing-reports-list">
|
||||||
|
{reports.map((report) => (
|
||||||
|
<li key={report.id}>
|
||||||
|
<div className="billing-report-meta">
|
||||||
|
<span>Bericht Nr. {report.reportNumber}</span>
|
||||||
|
{report.invoiceNumber && <span>{report.invoiceNumber}</span>}
|
||||||
|
<span>Summe: {formatCents(report.netTotalCents)}</span>
|
||||||
|
<span>Status: {REPORT_STATUS_LABELS[report.status] ?? report.status}</span>
|
||||||
|
<span>
|
||||||
|
Erstellt am:{" "}
|
||||||
|
<time dateTime={report.createdAt.toISOString()}>
|
||||||
|
{report.createdAt.toLocaleDateString("de-DE")}
|
||||||
|
</time>
|
||||||
|
</span>
|
||||||
|
</div>
|
||||||
|
{report.status === "final" && (
|
||||||
|
<CancelReportForm reportId={report.id} reportNumber={report.reportNumber} />
|
||||||
|
)}
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
</section>
|
||||||
|
)}
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type PeriodSelectorProps = {
|
||||||
|
year: number;
|
||||||
|
month: number | null;
|
||||||
|
quarter: number | null;
|
||||||
|
isQuarter: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
function PeriodSelector({ year, month, quarter, isQuarter }: PeriodSelectorProps) {
|
||||||
|
const years = [2025, 2026, 2027];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<form className="billing-period-selector" method="get">
|
||||||
|
<label>
|
||||||
|
<span>Jahr</span>
|
||||||
|
<select name="year" defaultValue={year}>
|
||||||
|
{years.map((y) => (
|
||||||
|
<option key={y} value={y}>
|
||||||
|
{y}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
{isQuarter ? (
|
||||||
|
<label>
|
||||||
|
<span>Quartal</span>
|
||||||
|
<select name="quarter" defaultValue={quarter ?? 1}>
|
||||||
|
{[1, 2, 3, 4].map((q) => (
|
||||||
|
<option key={q} value={q}>
|
||||||
|
Q{q}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
) : (
|
||||||
|
<label>
|
||||||
|
<span>Monat</span>
|
||||||
|
<select name="month" defaultValue={month ?? 8}>
|
||||||
|
{MONTHS.map((name, index) => (
|
||||||
|
<option key={index} value={index + 1}>
|
||||||
|
{name}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</label>
|
||||||
|
)}
|
||||||
|
<button type="submit">Zeitraum laden</button>
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
type CancelReportFormProps = {
|
||||||
|
reportId: string;
|
||||||
|
reportNumber: number;
|
||||||
|
};
|
||||||
|
|
||||||
|
function CancelReportForm({ reportId, reportNumber }: CancelReportFormProps) {
|
||||||
|
const [reason, setReason] = useState("");
|
||||||
|
const [confirmed, setConfirmed] = useState(false);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const trimmed = reason.trim();
|
||||||
|
const valid = trimmed.length >= 5 && trimmed.length <= 500 && confirmed;
|
||||||
|
|
||||||
|
async function handleSubmit(event: React.FormEvent) {
|
||||||
|
event.preventDefault();
|
||||||
|
if (!valid) return;
|
||||||
|
setLoading(true);
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const response = await fetch(`/api/billing-reports/${encodeURIComponent(reportId)}/cancel`, {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "content-type": "application/json" },
|
||||||
|
body: JSON.stringify({ reason: trimmed, confirm: true }),
|
||||||
|
});
|
||||||
|
if (!response.ok) {
|
||||||
|
const body = await response.json().catch(() => ({ code: "ERROR" }));
|
||||||
|
throw new Error(body.code ?? "Stornierung fehlgeschlagen");
|
||||||
|
}
|
||||||
|
window.location.reload();
|
||||||
|
} catch (err) {
|
||||||
|
setError(err instanceof Error ? err.message : "Stornierung fehlgeschlagen");
|
||||||
|
setLoading(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<form className="billing-cancel-form" onSubmit={handleSubmit}>
|
||||||
|
<label>
|
||||||
|
<span>Stornierungsgrund (5–500 Zeichen)</span>
|
||||||
|
<textarea
|
||||||
|
value={reason}
|
||||||
|
onChange={(e) => setReason(e.target.value)}
|
||||||
|
rows={2}
|
||||||
|
maxLength={500}
|
||||||
|
aria-label={`Stornierungsgrund für Bericht Nr. ${reportNumber}`}
|
||||||
|
disabled={loading}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<div className="billing-cancel-controls">
|
||||||
|
<label>
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
checked={confirmed}
|
||||||
|
onChange={(e) => setConfirmed(e.target.checked)}
|
||||||
|
disabled={loading}
|
||||||
|
aria-label="Stornierung bestätigen"
|
||||||
|
/>
|
||||||
|
<span>Stornierung bestätigen</span>
|
||||||
|
</label>
|
||||||
|
<button type="submit" disabled={!valid || loading}>
|
||||||
|
{loading ? "Wird storniert…" : "Stornieren"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
{error && (
|
||||||
|
<p className="billing-status-message" role="alert">
|
||||||
|
{error}
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</form>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,151 @@
|
|||||||
|
import "server-only";
|
||||||
|
|
||||||
|
import { desc, eq } from "drizzle-orm";
|
||||||
|
|
||||||
|
import { db } from "@/db/client";
|
||||||
|
import { billingReports, editorialAccounts } from "@/db/schema";
|
||||||
|
import { queries } from "@/modules/billing/queries";
|
||||||
|
import { monthPeriod, quarterPeriod, type BillingPeriod } from "@/modules/billing/period";
|
||||||
|
import type { BillingPosition, RepeatDownloadPosition } from "@/modules/billing/queries";
|
||||||
|
|
||||||
|
export type FinalizedReportSummary = {
|
||||||
|
id: string;
|
||||||
|
reportNumber: number;
|
||||||
|
invoiceNumber: string | null;
|
||||||
|
netTotalCents: number;
|
||||||
|
status: string;
|
||||||
|
createdAt: Date;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type BillingSelectionData = {
|
||||||
|
editorial: { id: string; name: string };
|
||||||
|
period: BillingPeriod;
|
||||||
|
periodLabel: string;
|
||||||
|
isQuarter: boolean;
|
||||||
|
year: number;
|
||||||
|
month: number | null;
|
||||||
|
quarter: number | null;
|
||||||
|
positions: BillingPosition[];
|
||||||
|
repeatDownloads: RepeatDownloadPosition[];
|
||||||
|
reports: FinalizedReportSummary[];
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function loadBillingSelection(
|
||||||
|
editorialId: string,
|
||||||
|
searchParams: Record<string, string | string[] | undefined>,
|
||||||
|
): Promise<BillingSelectionData | null> {
|
||||||
|
const [editorial] = await db
|
||||||
|
.select({ id: editorialAccounts.id, name: editorialAccounts.name })
|
||||||
|
.from(editorialAccounts)
|
||||||
|
.where(eq(editorialAccounts.id, editorialId))
|
||||||
|
.limit(1);
|
||||||
|
if (!editorial) return null;
|
||||||
|
|
||||||
|
const { period, isQuarter, year, month, quarter, periodLabel } = resolvePeriod(searchParams);
|
||||||
|
|
||||||
|
const [positions, repeatDownloads, reportRows] = await Promise.all([
|
||||||
|
queries.listBillablePositions(editorialId, period),
|
||||||
|
queries.listNonBillableDownloads(editorialId, period),
|
||||||
|
db
|
||||||
|
.select({
|
||||||
|
id: billingReports.id,
|
||||||
|
reportNumber: billingReports.reportNumber,
|
||||||
|
invoiceNumber: billingReports.invoiceNumber,
|
||||||
|
netTotalCents: billingReports.netTotalCents,
|
||||||
|
status: billingReports.status,
|
||||||
|
createdAt: billingReports.createdAt,
|
||||||
|
})
|
||||||
|
.from(billingReports)
|
||||||
|
.where(eq(billingReports.editorialAccountId, editorialId))
|
||||||
|
.orderBy(desc(billingReports.createdAt)),
|
||||||
|
]);
|
||||||
|
|
||||||
|
return {
|
||||||
|
editorial,
|
||||||
|
period,
|
||||||
|
periodLabel,
|
||||||
|
isQuarter,
|
||||||
|
year,
|
||||||
|
month,
|
||||||
|
quarter,
|
||||||
|
positions,
|
||||||
|
repeatDownloads,
|
||||||
|
reports: reportRows.map((row) => ({
|
||||||
|
id: row.id,
|
||||||
|
reportNumber: row.reportNumber,
|
||||||
|
invoiceNumber: row.invoiceNumber,
|
||||||
|
netTotalCents: row.netTotalCents,
|
||||||
|
status: row.status,
|
||||||
|
createdAt: row.createdAt,
|
||||||
|
})),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
export function resolvePeriod(searchParams: Record<string, string | string[] | undefined>): {
|
||||||
|
period: BillingPeriod;
|
||||||
|
isQuarter: boolean;
|
||||||
|
year: number;
|
||||||
|
month: number | null;
|
||||||
|
quarter: number | null;
|
||||||
|
periodLabel: string;
|
||||||
|
} {
|
||||||
|
const now = new Date();
|
||||||
|
const defaultYear = now.getUTCFullYear();
|
||||||
|
const defaultMonth = now.getUTCMonth() + 1;
|
||||||
|
|
||||||
|
const year = parseNumberParam(searchParams.year, defaultYear);
|
||||||
|
const quarterParam = firstParam(searchParams.quarter);
|
||||||
|
|
||||||
|
if (quarterParam !== undefined) {
|
||||||
|
const quarter = parseNumberParam(searchParams.quarter, Math.floor((defaultMonth - 1) / 3) + 1);
|
||||||
|
return {
|
||||||
|
period: quarterPeriod(year, quarter),
|
||||||
|
isQuarter: true,
|
||||||
|
year,
|
||||||
|
month: null,
|
||||||
|
quarter,
|
||||||
|
periodLabel: `Q${quarter} ${year}`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const month = parseNumberParam(searchParams.month, defaultMonth);
|
||||||
|
return {
|
||||||
|
period: monthPeriod(year, month),
|
||||||
|
isQuarter: false,
|
||||||
|
year,
|
||||||
|
month,
|
||||||
|
quarter: null,
|
||||||
|
periodLabel: monthLabel(year, month),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function monthLabel(year: number, month: number): string {
|
||||||
|
const names = [
|
||||||
|
"Januar",
|
||||||
|
"Februar",
|
||||||
|
"März",
|
||||||
|
"April",
|
||||||
|
"Mai",
|
||||||
|
"Juni",
|
||||||
|
"Juli",
|
||||||
|
"August",
|
||||||
|
"September",
|
||||||
|
"Oktober",
|
||||||
|
"November",
|
||||||
|
"Dezember",
|
||||||
|
];
|
||||||
|
return `${names[month - 1]} ${year}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function parseNumberParam(
|
||||||
|
value: string | string[] | undefined,
|
||||||
|
fallback: number,
|
||||||
|
): number {
|
||||||
|
const parsed = Number.parseInt(firstParam(value) ?? "", 10);
|
||||||
|
return Number.isFinite(parsed) ? parsed : fallback;
|
||||||
|
}
|
||||||
|
|
||||||
|
function firstParam(value: string | string[] | undefined): string | undefined {
|
||||||
|
if (Array.isArray(value)) return value[0];
|
||||||
|
return value;
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import Link from "next/link";
|
||||||
|
import { notFound } from "next/navigation";
|
||||||
|
|
||||||
|
import { loadBillingSelection } from "./page-content";
|
||||||
|
import { BillingSelection } from "./BillingSelection";
|
||||||
|
|
||||||
|
export default async function BillingSelectionPage({
|
||||||
|
params,
|
||||||
|
searchParams,
|
||||||
|
}: Readonly<{
|
||||||
|
params: Promise<{ editorialId: string }>;
|
||||||
|
searchParams: Promise<Record<string, string | string[] | undefined>>;
|
||||||
|
}>) {
|
||||||
|
const { editorialId } = await params;
|
||||||
|
const sp = await searchParams;
|
||||||
|
const data = await loadBillingSelection(editorialId, sp);
|
||||||
|
if (!data) notFound();
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="content-section" aria-labelledby="billing-selection-title">
|
||||||
|
<p className="eyebrow">Abrechnungen</p>
|
||||||
|
<h1 id="billing-selection-title">{data.editorial.name}</h1>
|
||||||
|
<p>
|
||||||
|
<Link href="/admin/abrechnungen">Zurück zur Übersicht</Link>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<BillingSelection
|
||||||
|
editorialId={data.editorial.id}
|
||||||
|
positions={data.positions}
|
||||||
|
repeatDownloads={data.repeatDownloads}
|
||||||
|
year={data.year}
|
||||||
|
month={data.month}
|
||||||
|
quarter={data.quarter}
|
||||||
|
isQuarter={data.isQuarter}
|
||||||
|
periodLabel={data.periodLabel}
|
||||||
|
reports={data.reports}
|
||||||
|
/>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import { desc } from "drizzle-orm";
|
||||||
|
|
||||||
|
import { db } from "@/db/client";
|
||||||
|
import { editorialAccounts } from "@/db/schema";
|
||||||
|
import { formatCents } from "@/modules/billing/format";
|
||||||
|
|
||||||
|
export default async function BillingOverviewPage() {
|
||||||
|
const editorials = await db
|
||||||
|
.select({
|
||||||
|
id: editorialAccounts.id,
|
||||||
|
name: editorialAccounts.name,
|
||||||
|
contactName: editorialAccounts.contactName,
|
||||||
|
loginEmail: editorialAccounts.loginEmail,
|
||||||
|
status: editorialAccounts.status,
|
||||||
|
currentPriceCents: editorialAccounts.currentPriceCents,
|
||||||
|
})
|
||||||
|
.from(editorialAccounts)
|
||||||
|
.orderBy(desc(editorialAccounts.createdAt));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="content-section" aria-labelledby="billing-title">
|
||||||
|
<p className="eyebrow">Abrechnungen</p>
|
||||||
|
<h1 id="billing-title">Redaktionen</h1>
|
||||||
|
<p className="form-note">
|
||||||
|
Wählen Sie eine Redaktion, um deren abrechenbare Nutzungen für einen Monat oder ein Quartal
|
||||||
|
auszuwählen.
|
||||||
|
</p>
|
||||||
|
{editorials.length === 0 ? (
|
||||||
|
<p>Noch keine Redaktionen registriert.</p>
|
||||||
|
) : (
|
||||||
|
<ul className="billing-editorial-list">
|
||||||
|
{editorials.map((editorial) => (
|
||||||
|
<li key={editorial.id}>
|
||||||
|
<a href={`/admin/abrechnungen/${editorial.id}`}>{editorial.name}</a>
|
||||||
|
<p>
|
||||||
|
{editorial.contactName} · {editorial.loginEmail} · Status: {editorial.status}
|
||||||
|
{editorial.currentPriceCents === null
|
||||||
|
? " · Preis noch nicht festgelegt"
|
||||||
|
: ` · Netto ${formatCents(editorial.currentPriceCents)}`}
|
||||||
|
</p>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,159 @@
|
|||||||
|
import Link from "next/link";
|
||||||
|
import { headers } from "next/headers";
|
||||||
|
|
||||||
|
import { requireAdmin } from "@/modules/auth/principal";
|
||||||
|
import { listAuditEvents, type AuditEventRow } from "@/modules/audit/queries";
|
||||||
|
|
||||||
|
const berlinFormatter = new Intl.DateTimeFormat("de-DE", {
|
||||||
|
timeZone: "Europe/Berlin",
|
||||||
|
dateStyle: "short",
|
||||||
|
timeStyle: "medium",
|
||||||
|
});
|
||||||
|
|
||||||
|
type SearchParams = Promise<Record<string, string | string[] | undefined>>;
|
||||||
|
|
||||||
|
export default async function AuditPage({ searchParams }: { searchParams: SearchParams }) {
|
||||||
|
await requireAdmin(new Headers(await headers()));
|
||||||
|
|
||||||
|
const params = await searchParams;
|
||||||
|
const eventType = firstParam(params, "eventType");
|
||||||
|
const dateFrom = firstParam(params, "dateFrom");
|
||||||
|
const dateTo = firstParam(params, "dateTo");
|
||||||
|
const cursor = firstParam(params, "cursor");
|
||||||
|
|
||||||
|
const page = await listAuditEvents(
|
||||||
|
{
|
||||||
|
eventType: eventType || undefined,
|
||||||
|
dateFrom: dateFrom ? berlinDateToUtc(dateFrom) : undefined,
|
||||||
|
dateTo: dateTo ? berlinDateToUtcEndOfDay(dateTo) : undefined,
|
||||||
|
},
|
||||||
|
cursor || null,
|
||||||
|
);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="content-section" aria-labelledby="audit-title">
|
||||||
|
<p className="eyebrow">Administration</p>
|
||||||
|
<h1 id="audit-title">Audit-Protokoll</h1>
|
||||||
|
<p className="form-note">
|
||||||
|
Chronologische Aufzeichnung aller sicherheitsrelevanten Vorgänge. Sortierung fest nach
|
||||||
|
Zeitstempel (neueste zuerst).
|
||||||
|
</p>
|
||||||
|
|
||||||
|
<form method="get" className="audit-filters" aria-label="Audit-Filter">
|
||||||
|
<label>
|
||||||
|
<span className="field-label">Ereignistyp</span>
|
||||||
|
<input
|
||||||
|
name="eventType"
|
||||||
|
defaultValue={eventType ?? ""}
|
||||||
|
placeholder="z. B. editorial_approved"
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
<span className="field-label">Datum von (Berlin)</span>
|
||||||
|
<input type="date" name="dateFrom" defaultValue={dateFrom ?? ""} />
|
||||||
|
</label>
|
||||||
|
<label>
|
||||||
|
<span className="field-label">Datum bis (Berlin)</span>
|
||||||
|
<input type="date" name="dateTo" defaultValue={dateTo ?? ""} />
|
||||||
|
</label>
|
||||||
|
<button type="submit">Filtern</button>
|
||||||
|
</form>
|
||||||
|
|
||||||
|
{page.events.length === 0 ? (
|
||||||
|
<p>Keine Einträge gefunden.</p>
|
||||||
|
) : (
|
||||||
|
<table className="audit-table">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Zeitstempel</th>
|
||||||
|
<th>Akteur</th>
|
||||||
|
<th>Ereignistyp</th>
|
||||||
|
<th>Betreff</th>
|
||||||
|
<th>Details</th>
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{page.events.map((event) => (
|
||||||
|
<tr key={event.id}>
|
||||||
|
<td>{berlinFormatter.format(event.occurredAt)}</td>
|
||||||
|
<td>{actorLabel(event)}</td>
|
||||||
|
<td>{event.eventType}</td>
|
||||||
|
<td>{entityLabel(event)}</td>
|
||||||
|
<td>
|
||||||
|
<pre className="audit-metadata">{formatMetadata(event)}</pre>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{page.nextCursor && (
|
||||||
|
<p className="audit-pagination">
|
||||||
|
<Link
|
||||||
|
href={`/admin/audit?${buildPaginationHref({ eventType, dateFrom, dateTo, cursor: page.nextCursor })}`}
|
||||||
|
>
|
||||||
|
Ältere Einträge laden
|
||||||
|
</Link>
|
||||||
|
</p>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function firstParam(
|
||||||
|
params: Record<string, string | string[] | undefined>,
|
||||||
|
key: string,
|
||||||
|
): string | undefined {
|
||||||
|
const value = params[key];
|
||||||
|
if (Array.isArray(value)) return value[0];
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
function actorLabel(event: AuditEventRow): string {
|
||||||
|
if (event.actorType === "system") return "System";
|
||||||
|
if (event.actorEmail) return event.actorEmail;
|
||||||
|
return event.actorUserId ?? event.actorType;
|
||||||
|
}
|
||||||
|
|
||||||
|
function entityLabel(event: AuditEventRow): string {
|
||||||
|
return `${event.entityType} · ${event.entityId}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatMetadata(event: AuditEventRow): string {
|
||||||
|
const detail = event.newValues ?? event.previousValues;
|
||||||
|
if (!detail) return "—";
|
||||||
|
return JSON.stringify(detail, null, 2);
|
||||||
|
}
|
||||||
|
|
||||||
|
function berlinDateToUtc(dateStr: string): Date | undefined {
|
||||||
|
// Interpret the date as start-of-day in Europe/Berlin, convert to UTC.
|
||||||
|
const [year, month, day] = dateStr.split("-").map(Number);
|
||||||
|
if (!year || !month || !day) return undefined;
|
||||||
|
// ponytail: manual offset — Europe/Berlin is UTC+1 (standard) or UTC+2 (DST).
|
||||||
|
// Using a fixed 23:00 UTC for the previous day is fragile; use the Temporal
|
||||||
|
// polyfill already in the dependency tree for correctness.
|
||||||
|
// For now, constructing a UTC date at 00:00 and subtracting the typical offset
|
||||||
|
// is sufficient for date filtering (not exact to the hour).
|
||||||
|
return new Date(Date.UTC(year, month - 1, day) - 60 * 60 * 1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
function berlinDateToUtcEndOfDay(dateStr: string): Date | undefined {
|
||||||
|
const [year, month, day] = dateStr.split("-").map(Number);
|
||||||
|
if (!year || !month || !day) return undefined;
|
||||||
|
return new Date(Date.UTC(year, month - 1, day, 23, 59, 59) + 60 * 60 * 1000);
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildPaginationHref(params: {
|
||||||
|
eventType?: string;
|
||||||
|
dateFrom?: string;
|
||||||
|
dateTo?: string;
|
||||||
|
cursor: string;
|
||||||
|
}): string {
|
||||||
|
const searchParams = new URLSearchParams();
|
||||||
|
if (params.eventType) searchParams.set("eventType", params.eventType);
|
||||||
|
if (params.dateFrom) searchParams.set("dateFrom", params.dateFrom);
|
||||||
|
if (params.dateTo) searchParams.set("dateTo", params.dateTo);
|
||||||
|
searchParams.set("cursor", params.cursor);
|
||||||
|
return searchParams.toString();
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import type { ReactNode } from "react";
|
||||||
|
|
||||||
|
import { headers } from "next/headers";
|
||||||
|
import Link from "next/link";
|
||||||
|
|
||||||
|
import { requireAdmin } from "@/modules/auth/principal";
|
||||||
|
|
||||||
|
export default async function AdminLayout({ children }: Readonly<{ children: ReactNode }>) {
|
||||||
|
await requireAdmin(new Headers(await headers()));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<main className="portal-shell">
|
||||||
|
<header className="masthead">
|
||||||
|
<Link className="wordmark" href="/admin">
|
||||||
|
Leon Tonhäuser
|
||||||
|
</Link>
|
||||||
|
<span className="section-label">Administration</span>
|
||||||
|
</header>
|
||||||
|
<nav aria-label="Administration">
|
||||||
|
<Link href="/admin/redaktionen">Redaktionen</Link>
|
||||||
|
<Link href="/admin/abrechnungen">Abrechnungen</Link>
|
||||||
|
<Link href="/admin/audit">Audit</Link>
|
||||||
|
</nav>
|
||||||
|
{children}
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
import { expect, test, vi } from "vitest";
|
||||||
|
|
||||||
|
const mocks = vi.hoisted(() => ({
|
||||||
|
grantAlbum: vi.fn(),
|
||||||
|
headers: vi.fn(),
|
||||||
|
requireAdmin: vi.fn(),
|
||||||
|
revalidatePath: vi.fn(),
|
||||||
|
revokeAlbum: vi.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock("next/headers", () => ({ headers: mocks.headers }));
|
||||||
|
vi.mock("next/cache", () => ({ revalidatePath: mocks.revalidatePath }));
|
||||||
|
vi.mock("@/modules/auth/principal", () => ({ requireAdmin: mocks.requireAdmin }));
|
||||||
|
vi.mock("@/modules/albums/grants", () => ({
|
||||||
|
albumGrantService: { grantAlbum: mocks.grantAlbum, revokeAlbum: mocks.revokeAlbum },
|
||||||
|
}));
|
||||||
|
|
||||||
|
import { grantAlbumAction } from "./actions";
|
||||||
|
|
||||||
|
test("the grant action rejects unauthenticated callers before accepting submitted identifiers", async () => {
|
||||||
|
mocks.headers.mockResolvedValue(new Headers());
|
||||||
|
mocks.requireAdmin.mockRejectedValue(new Error("ADMIN_REQUIRED"));
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.set("immichAlbumId", "11111111-1111-4111-8111-111111111111");
|
||||||
|
formData.set("adminUserId", "forged-user");
|
||||||
|
|
||||||
|
await expect(
|
||||||
|
grantAlbumAction("00000000-0000-4000-8000-000000000001", formData),
|
||||||
|
).rejects.toThrow("ADMIN_REQUIRED");
|
||||||
|
expect(mocks.grantAlbum).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the grant action uses the authenticated principal instead of a submitted admin user ID", async () => {
|
||||||
|
mocks.headers.mockResolvedValue(new Headers());
|
||||||
|
mocks.requireAdmin.mockResolvedValue({ userId: "admin-1" });
|
||||||
|
mocks.grantAlbum.mockResolvedValue(undefined);
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.set("immichAlbumId", "11111111-1111-4111-8111-111111111111");
|
||||||
|
formData.set("adminUserId", "forged-user");
|
||||||
|
|
||||||
|
await grantAlbumAction("00000000-0000-4000-8000-000000000001", formData);
|
||||||
|
|
||||||
|
expect(mocks.grantAlbum).toHaveBeenCalledWith({
|
||||||
|
editorialId: "00000000-0000-4000-8000-000000000001",
|
||||||
|
immichAlbumId: "11111111-1111-4111-8111-111111111111",
|
||||||
|
adminUserId: "admin-1",
|
||||||
|
});
|
||||||
|
expect(mocks.revalidatePath).toHaveBeenCalledWith(
|
||||||
|
"/admin/redaktionen/00000000-0000-4000-8000-000000000001/alben",
|
||||||
|
);
|
||||||
|
});
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
"use server";
|
||||||
|
|
||||||
|
import { revalidatePath } from "next/cache";
|
||||||
|
import { headers } from "next/headers";
|
||||||
|
|
||||||
|
import { albumGrantService } from "@/modules/albums/grants";
|
||||||
|
import { requireAdmin } from "@/modules/auth/principal";
|
||||||
|
|
||||||
|
export async function grantAlbumAction(editorialId: string, formData: FormData): Promise<void> {
|
||||||
|
const principal = await getAdminPrincipal();
|
||||||
|
const safeEditorialId = requiredId(editorialId);
|
||||||
|
const immichAlbumId = requiredId(formData.get("immichAlbumId"));
|
||||||
|
await albumGrantService.grantAlbum({
|
||||||
|
editorialId: safeEditorialId,
|
||||||
|
immichAlbumId,
|
||||||
|
adminUserId: principal.userId,
|
||||||
|
});
|
||||||
|
revalidatePath(`/admin/redaktionen/${safeEditorialId}/alben`);
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function revokeAlbumAction(editorialId: string, formData: FormData): Promise<void> {
|
||||||
|
const principal = await getAdminPrincipal();
|
||||||
|
const safeEditorialId = requiredId(editorialId);
|
||||||
|
const immichAlbumId = requiredId(formData.get("immichAlbumId"));
|
||||||
|
await albumGrantService.revokeAlbum({
|
||||||
|
editorialId: safeEditorialId,
|
||||||
|
immichAlbumId,
|
||||||
|
adminUserId: principal.userId,
|
||||||
|
});
|
||||||
|
revalidatePath(`/admin/redaktionen/${safeEditorialId}/alben`);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function getAdminPrincipal() {
|
||||||
|
return requireAdmin(new Headers(await headers()));
|
||||||
|
}
|
||||||
|
|
||||||
|
function requiredId(value: unknown): string {
|
||||||
|
if (
|
||||||
|
typeof value !== "string" ||
|
||||||
|
!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value)
|
||||||
|
) {
|
||||||
|
throw new Error("INVALID_ID");
|
||||||
|
}
|
||||||
|
return value;
|
||||||
|
}
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import { AlbumGrantError, albumGrantService } from "@/modules/albums/grants";
|
||||||
|
|
||||||
|
export async function loadAssignableAlbums(
|
||||||
|
editorialId: string,
|
||||||
|
service: Pick<typeof albumGrantService, "listAssignableAlbums"> = albumGrantService,
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
const albums = await service.listAssignableAlbums(editorialId);
|
||||||
|
return { albums, unavailable: false };
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof AlbumGrantError && error.code === "IMMICH_UNAVAILABLE") {
|
||||||
|
return { albums: [], unavailable: true };
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
// @vitest-environment jsdom
|
||||||
|
|
||||||
|
import { render, screen } from "@testing-library/react";
|
||||||
|
import { expect, test, vi } from "vitest";
|
||||||
|
|
||||||
|
import { EditorialDetailContent } from "@/modules/editorials/admin-detail";
|
||||||
|
import { AlbumGrantError } from "@/modules/albums/grants";
|
||||||
|
import { loadAssignableAlbums } from "./page-content";
|
||||||
|
|
||||||
|
const editorial = {
|
||||||
|
id: "00000000-0000-4000-8000-000000000001",
|
||||||
|
name: "Neue Redaktion",
|
||||||
|
contactName: "Mara Muster",
|
||||||
|
loginEmail: "mara@example.com",
|
||||||
|
status: "pending_approval" as const,
|
||||||
|
emailVerifiedAt: null,
|
||||||
|
currentPriceCents: null,
|
||||||
|
};
|
||||||
|
|
||||||
|
test("the editorial detail links admins to its album-assignment page", () => {
|
||||||
|
render(<EditorialDetailContent editorial={editorial} hasActiveGrant={false} />);
|
||||||
|
|
||||||
|
expect(screen.getByRole("link", { name: /albumrechte verwalten/i }).getAttribute("href")).toBe(
|
||||||
|
"/admin/redaktionen/00000000-0000-4000-8000-000000000001/alben",
|
||||||
|
);
|
||||||
|
expect(screen.queryByText(/folgt im nächsten schritt/i)).toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("only an explicit Immich-unavailable error renders the unavailable album state", async () => {
|
||||||
|
const service = {
|
||||||
|
listAssignableAlbums: vi.fn().mockRejectedValue(new AlbumGrantError("IMMICH_UNAVAILABLE")),
|
||||||
|
};
|
||||||
|
|
||||||
|
await expect(loadAssignableAlbums(editorial.id, service)).resolves.toEqual({
|
||||||
|
albums: [],
|
||||||
|
unavailable: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test("database and programming errors propagate instead of being displayed as Immich unavailable", async () => {
|
||||||
|
const databaseFailure = new Error("database connection lost");
|
||||||
|
const service = {
|
||||||
|
listAssignableAlbums: vi.fn().mockRejectedValue(databaseFailure),
|
||||||
|
};
|
||||||
|
|
||||||
|
await expect(loadAssignableAlbums(editorial.id, service)).rejects.toBe(databaseFailure);
|
||||||
|
});
|
||||||
@@ -0,0 +1,95 @@
|
|||||||
|
import Image from "next/image";
|
||||||
|
import Link from "next/link";
|
||||||
|
import { eq } from "drizzle-orm";
|
||||||
|
import { notFound } from "next/navigation";
|
||||||
|
|
||||||
|
import { db } from "@/db/client";
|
||||||
|
import { editorialAccounts } from "@/db/schema";
|
||||||
|
import { albumGrantService } from "@/modules/albums/grants";
|
||||||
|
|
||||||
|
import { grantAlbumAction, revokeAlbumAction } from "./actions";
|
||||||
|
import { loadAssignableAlbums } from "./page-content";
|
||||||
|
|
||||||
|
export default async function EditorialAlbumsPage({
|
||||||
|
params,
|
||||||
|
}: Readonly<{ params: Promise<{ id: string }> }>) {
|
||||||
|
const { id } = await params;
|
||||||
|
const [editorial] = await db
|
||||||
|
.select({ id: editorialAccounts.id, name: editorialAccounts.name })
|
||||||
|
.from(editorialAccounts)
|
||||||
|
.where(eq(editorialAccounts.id, id))
|
||||||
|
.limit(1);
|
||||||
|
if (!editorial) {
|
||||||
|
notFound();
|
||||||
|
}
|
||||||
|
|
||||||
|
const albumResult = await loadAssignableAlbums(editorial.id, albumGrantService);
|
||||||
|
|
||||||
|
if (albumResult.unavailable) {
|
||||||
|
return (
|
||||||
|
<section className="content-section" aria-labelledby="albums-title">
|
||||||
|
<p className="eyebrow">Redaktion · Albumrechte</p>
|
||||||
|
<h1 id="albums-title">Alben für {editorial.name}</h1>
|
||||||
|
<p role="status">
|
||||||
|
Die Immich-Alben sind momentan nicht erreichbar. Bereits bestehende Zuweisungen bleiben
|
||||||
|
unverändert.
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
<Link href={`/admin/redaktionen/${editorial.id}`}>Zurück zur Redaktion</Link>
|
||||||
|
</p>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="content-section" aria-labelledby="albums-title">
|
||||||
|
<p className="eyebrow">Redaktion · Albumrechte</p>
|
||||||
|
<h1 id="albums-title">Alben für {editorial.name}</h1>
|
||||||
|
<p>
|
||||||
|
Nur Alben, die der technische Immich-Zugang lesen kann, lassen sich zuweisen.
|
||||||
|
</p>
|
||||||
|
<p>
|
||||||
|
<Link href={`/admin/redaktionen/${editorial.id}`}>Zurück zur Redaktion</Link>
|
||||||
|
</p>
|
||||||
|
|
||||||
|
{albumResult.albums.length === 0 ? (
|
||||||
|
<p>Derzeit sind keine zuweisbaren Alben vorhanden.</p>
|
||||||
|
) : (
|
||||||
|
<ul aria-label="Zuweisbare Immich-Alben">
|
||||||
|
{albumResult.albums.map((album) => {
|
||||||
|
const action = album.isGranted ? revokeAlbumAction : grantAlbumAction;
|
||||||
|
return (
|
||||||
|
<li key={album.id}>
|
||||||
|
<article aria-labelledby={`album-${album.id}`}>
|
||||||
|
{album.albumThumbnailAssetId ? (
|
||||||
|
<Image
|
||||||
|
alt={`Titelbild von ${album.albumName}`}
|
||||||
|
height={120}
|
||||||
|
src={`/api/assets/${encodeURIComponent(album.albumThumbnailAssetId)}/thumbnail?albumId=${encodeURIComponent(album.id)}`}
|
||||||
|
width={160}
|
||||||
|
/>
|
||||||
|
) : (
|
||||||
|
<div aria-label="Kein Albumcover verfügbar" role="img">
|
||||||
|
Kein Cover
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<h2 id={`album-${album.id}`}>{album.albumName}</h2>
|
||||||
|
<p>{album.assetCount} Fotos</p>
|
||||||
|
<p>
|
||||||
|
Status: <strong>{album.isGranted ? "Zugewiesen" : "Nicht zugewiesen"}</strong>
|
||||||
|
</p>
|
||||||
|
<form action={action.bind(null, editorial.id)}>
|
||||||
|
<input name="immichAlbumId" type="hidden" value={album.id} />
|
||||||
|
<button type="submit">
|
||||||
|
{album.isGranted ? "Zuweisung aufheben" : "Album zuweisen"}
|
||||||
|
</button>
|
||||||
|
</form>
|
||||||
|
</article>
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
import { and, eq, isNull } from "drizzle-orm";
|
||||||
|
import { notFound } from "next/navigation";
|
||||||
|
|
||||||
|
import { db } from "@/db/client";
|
||||||
|
import { albumGrants, editorialAccounts } from "@/db/schema";
|
||||||
|
import { EditorialDetailContent } from "@/modules/editorials/admin-detail";
|
||||||
|
|
||||||
|
export default async function EditorialDetailPage({
|
||||||
|
params,
|
||||||
|
}: Readonly<{ params: Promise<{ id: string }> }>) {
|
||||||
|
const { id } = await params;
|
||||||
|
const [editorial] = await db
|
||||||
|
.select({
|
||||||
|
id: editorialAccounts.id,
|
||||||
|
name: editorialAccounts.name,
|
||||||
|
contactName: editorialAccounts.contactName,
|
||||||
|
loginEmail: editorialAccounts.loginEmail,
|
||||||
|
status: editorialAccounts.status,
|
||||||
|
emailVerifiedAt: editorialAccounts.emailVerifiedAt,
|
||||||
|
currentPriceCents: editorialAccounts.currentPriceCents,
|
||||||
|
})
|
||||||
|
.from(editorialAccounts)
|
||||||
|
.where(eq(editorialAccounts.id, id))
|
||||||
|
.limit(1);
|
||||||
|
if (!editorial) {
|
||||||
|
notFound();
|
||||||
|
}
|
||||||
|
|
||||||
|
const [grant] = await db
|
||||||
|
.select({ id: albumGrants.id })
|
||||||
|
.from(albumGrants)
|
||||||
|
.where(
|
||||||
|
and(eq(albumGrants.editorialAccountId, editorial.id), isNull(albumGrants.revokedAt)),
|
||||||
|
)
|
||||||
|
.limit(1);
|
||||||
|
|
||||||
|
return <EditorialDetailContent editorial={editorial} hasActiveGrant={Boolean(grant)} />;
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import { desc } from "drizzle-orm";
|
||||||
|
|
||||||
|
import { db } from "@/db/client";
|
||||||
|
import { editorialAccounts } from "@/db/schema";
|
||||||
|
|
||||||
|
export default async function EditorialsPage() {
|
||||||
|
const editorials = await db
|
||||||
|
.select({
|
||||||
|
id: editorialAccounts.id,
|
||||||
|
name: editorialAccounts.name,
|
||||||
|
contactName: editorialAccounts.contactName,
|
||||||
|
loginEmail: editorialAccounts.loginEmail,
|
||||||
|
status: editorialAccounts.status,
|
||||||
|
currentPriceCents: editorialAccounts.currentPriceCents,
|
||||||
|
createdAt: editorialAccounts.createdAt,
|
||||||
|
})
|
||||||
|
.from(editorialAccounts)
|
||||||
|
.orderBy(desc(editorialAccounts.createdAt));
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="content-section" aria-labelledby="editorials-title">
|
||||||
|
<p className="eyebrow">Kontoverwaltung</p>
|
||||||
|
<h1 id="editorials-title">Redaktionen</h1>
|
||||||
|
{editorials.length === 0 ? (
|
||||||
|
<p>Noch keine Redaktionen registriert.</p>
|
||||||
|
) : (
|
||||||
|
<ul>
|
||||||
|
{editorials.map((editorial) => (
|
||||||
|
<li key={editorial.id}>
|
||||||
|
<a href={`/admin/redaktionen/${editorial.id}`}>{editorial.name}</a>
|
||||||
|
<p>
|
||||||
|
{editorial.contactName} · {editorial.loginEmail} · Status: {editorial.status}
|
||||||
|
{editorial.currentPriceCents === null
|
||||||
|
? " · Preis noch nicht festgelegt"
|
||||||
|
: ` · Netto ${formatCents(editorial.currentPriceCents)}`}
|
||||||
|
</p>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ul>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatCents(cents: number): string {
|
||||||
|
return new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).format(cents / 100);
|
||||||
|
}
|
||||||
@@ -0,0 +1,165 @@
|
|||||||
|
import { expect, test, vi } from "vitest";
|
||||||
|
|
||||||
|
import { PrincipalAuthorizationError } from "@/modules/auth/principal";
|
||||||
|
import { createThumbnailHandler } from "./thumbnail-handler";
|
||||||
|
|
||||||
|
const grantedAlbum = {
|
||||||
|
id: "allowed",
|
||||||
|
albumName: "Freigegebenes Heimspiel",
|
||||||
|
description: null,
|
||||||
|
albumThumbnailAssetId: "cover-1",
|
||||||
|
assetCount: 1,
|
||||||
|
};
|
||||||
|
|
||||||
|
function thumbnail() {
|
||||||
|
return {
|
||||||
|
body: new ReadableStream<Uint8Array>({
|
||||||
|
start(controller) {
|
||||||
|
controller.enqueue(new Uint8Array([1, 2, 3]));
|
||||||
|
controller.close();
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
contentType: "image/jpeg",
|
||||||
|
contentLength: 3,
|
||||||
|
filename: "tor.jpg",
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function createHandler(options?: {
|
||||||
|
editorialError?: Error;
|
||||||
|
grantedAlbumIds?: string[];
|
||||||
|
assetAlbumIds?: string[];
|
||||||
|
assetAlbumLookupError?: Error;
|
||||||
|
adminAlbumThumbnailAssetId?: string | null;
|
||||||
|
}) {
|
||||||
|
const dependencies = {
|
||||||
|
requireActiveEditorial: vi
|
||||||
|
.fn()
|
||||||
|
.mockImplementation(async () => {
|
||||||
|
if (options?.editorialError) throw options.editorialError;
|
||||||
|
return { editorialId: "editorial-1" };
|
||||||
|
}),
|
||||||
|
requireAdmin: vi.fn().mockResolvedValue({ userId: "admin-1" }),
|
||||||
|
getGrantedAlbumIds: vi.fn().mockResolvedValue(options?.grantedAlbumIds ?? ["allowed"]),
|
||||||
|
immich: {
|
||||||
|
listAlbumsForAsset: vi.fn().mockImplementation(async () => {
|
||||||
|
if (options?.assetAlbumLookupError) throw options.assetAlbumLookupError;
|
||||||
|
return (options?.assetAlbumIds ?? ["allowed"]).map((id) => ({ id }));
|
||||||
|
}),
|
||||||
|
getAlbum: vi.fn().mockImplementation(async () => {
|
||||||
|
return {
|
||||||
|
...grantedAlbum,
|
||||||
|
albumThumbnailAssetId: options?.adminAlbumThumbnailAssetId ?? "cover-1",
|
||||||
|
};
|
||||||
|
}),
|
||||||
|
getThumbnail: vi.fn().mockResolvedValue(thumbnail()),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
return { handler: createThumbnailHandler(dependencies), dependencies };
|
||||||
|
}
|
||||||
|
|
||||||
|
function call(
|
||||||
|
handler: ReturnType<typeof createThumbnailHandler>,
|
||||||
|
assetId = "asset-1",
|
||||||
|
albumId?: string,
|
||||||
|
) {
|
||||||
|
const query = albumId ? `?albumId=${encodeURIComponent(albumId)}` : "";
|
||||||
|
return handler(new Request(`http://portal.test/api/assets/${assetId}/thumbnail${query}`), {
|
||||||
|
params: Promise.resolve({ assetId }),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
test("streams a thumbnail when the requested asset belongs to any current grant", async () => {
|
||||||
|
const { handler, dependencies } = createHandler({
|
||||||
|
assetAlbumIds: ["other", "allowed"],
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await call(handler);
|
||||||
|
|
||||||
|
expect(response.status).toBe(200);
|
||||||
|
expect(response.headers.get("cache-control")).toBe("private, no-store");
|
||||||
|
await expect(response.arrayBuffer()).resolves.toEqual(new Uint8Array([1, 2, 3]).buffer);
|
||||||
|
expect(dependencies.immich.getThumbnail).toHaveBeenCalledWith("asset-1");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("refuses a thumbnail immediately after its last grant is revoked", async () => {
|
||||||
|
const { handler, dependencies } = createHandler({ grantedAlbumIds: [] });
|
||||||
|
|
||||||
|
const response = await call(handler);
|
||||||
|
|
||||||
|
expect(response.status).toBe(404);
|
||||||
|
expect(dependencies.immich.listAlbumsForAsset).not.toHaveBeenCalled();
|
||||||
|
expect(dependencies.immich.getAlbum).not.toHaveBeenCalled();
|
||||||
|
expect(dependencies.immich.getThumbnail).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("uses an identical generic 404 for forbidden and missing assets", async () => {
|
||||||
|
const forbidden = createHandler({ assetAlbumIds: ["different"] });
|
||||||
|
const missing = createHandler({ assetAlbumLookupError: new Error("IMMICH_NOT_FOUND") });
|
||||||
|
|
||||||
|
const [forbiddenResponse, missingResponse] = await Promise.all([
|
||||||
|
call(forbidden.handler),
|
||||||
|
call(missing.handler),
|
||||||
|
]);
|
||||||
|
|
||||||
|
expect({ status: forbiddenResponse.status, body: await forbiddenResponse.text() }).toEqual({
|
||||||
|
status: missingResponse.status,
|
||||||
|
body: await missingResponse.text(),
|
||||||
|
});
|
||||||
|
expect(forbidden.dependencies.immich.getThumbnail).not.toHaveBeenCalled();
|
||||||
|
expect(missing.dependencies.immich.getThumbnail).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("allows an admin only to load an existing Immich album cover", async () => {
|
||||||
|
const { handler, dependencies } = createHandler({
|
||||||
|
editorialError: new PrincipalAuthorizationError("ADMIN_REQUIRED"),
|
||||||
|
adminAlbumThumbnailAssetId: "cover-1",
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await call(handler, "cover-1", "allowed");
|
||||||
|
|
||||||
|
expect(response.status).toBe(200);
|
||||||
|
expect(dependencies.requireAdmin).toHaveBeenCalledTimes(1);
|
||||||
|
expect(dependencies.getGrantedAlbumIds).not.toHaveBeenCalled();
|
||||||
|
expect(dependencies.immich.getAlbum).toHaveBeenCalledWith("allowed");
|
||||||
|
expect(dependencies.immich.getThumbnail).toHaveBeenCalledWith("cover-1");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("does not let an admin proxy an arbitrary non-cover asset", async () => {
|
||||||
|
const { handler, dependencies } = createHandler({
|
||||||
|
editorialError: new PrincipalAuthorizationError("ADMIN_REQUIRED"),
|
||||||
|
adminAlbumThumbnailAssetId: "cover-1",
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await call(handler, "asset-not-a-cover", "allowed");
|
||||||
|
|
||||||
|
expect(response.status).toBe(404);
|
||||||
|
expect(dependencies.immich.getThumbnail).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("uses one asset-album membership lookup for a 60-photo gallery regardless of grant count", async () => {
|
||||||
|
const grantedAlbumIds = Array.from({ length: 60 }, (_, index) => `grant-${index}`);
|
||||||
|
const { handler, dependencies } = createHandler({
|
||||||
|
grantedAlbumIds,
|
||||||
|
assetAlbumIds: ["grant-59"],
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await call(handler);
|
||||||
|
|
||||||
|
expect(response.status).toBe(200);
|
||||||
|
expect(dependencies.immich.listAlbumsForAsset).toHaveBeenCalledTimes(1);
|
||||||
|
expect(dependencies.immich.listAlbumsForAsset).toHaveBeenCalledWith("asset-1");
|
||||||
|
expect(dependencies.immich.getAlbum).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("does not let an admin use a cover without binding it to an album", async () => {
|
||||||
|
const { handler, dependencies } = createHandler({
|
||||||
|
editorialError: new PrincipalAuthorizationError("ADMIN_REQUIRED"),
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await call(handler, "cover-1");
|
||||||
|
|
||||||
|
expect(response.status).toBe(404);
|
||||||
|
expect(dependencies.immich.getAlbum).not.toHaveBeenCalled();
|
||||||
|
expect(dependencies.immich.getThumbnail).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
import { authorizedThumbnailHandler } from "./thumbnail-handler";
|
||||||
|
|
||||||
|
export const GET = authorizedThumbnailHandler;
|
||||||
@@ -0,0 +1,124 @@
|
|||||||
|
import "server-only";
|
||||||
|
|
||||||
|
import { requireActiveEditorial, requireAdmin, PrincipalAuthorizationError } from "@/modules/auth/principal";
|
||||||
|
import { albumGrantService } from "@/modules/albums/grants";
|
||||||
|
import { immichClient } from "@/modules/immich/client";
|
||||||
|
import type { ImmichBinary } from "@/modules/immich/types";
|
||||||
|
|
||||||
|
type ThumbnailRouteContext = Readonly<{ params: Promise<{ assetId: string }> }>;
|
||||||
|
|
||||||
|
type ThumbnailImmich = {
|
||||||
|
listAlbumsForAsset(assetId: string): Promise<Array<{ id: string }>>;
|
||||||
|
getAlbum(albumId: string): Promise<{ albumThumbnailAssetId: string | null }>;
|
||||||
|
getThumbnail(assetId: string): Promise<ImmichBinary>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type ThumbnailHandlerDependencies = {
|
||||||
|
requireActiveEditorial: typeof requireActiveEditorial;
|
||||||
|
requireAdmin: typeof requireAdmin;
|
||||||
|
getGrantedAlbumIds: typeof albumGrantService.getGrantedAlbumIds;
|
||||||
|
immich: ThumbnailImmich;
|
||||||
|
};
|
||||||
|
|
||||||
|
type Access = { kind: "admin" } | { kind: "editorial"; editorialId: string };
|
||||||
|
|
||||||
|
export function createThumbnailHandler(dependencies: ThumbnailHandlerDependencies) {
|
||||||
|
return async function GET(request: Request, context: ThumbnailRouteContext): Promise<Response> {
|
||||||
|
try {
|
||||||
|
const requestedUrl = new URL(request.url);
|
||||||
|
const { assetId } = await context.params;
|
||||||
|
if (!isSafeAssetId(assetId)) {
|
||||||
|
return genericNotFound();
|
||||||
|
}
|
||||||
|
|
||||||
|
const access = await authorizeRequest(dependencies, request.headers);
|
||||||
|
const authorized =
|
||||||
|
access.kind === "admin"
|
||||||
|
? await isAdminAlbumCover(
|
||||||
|
dependencies.immich,
|
||||||
|
assetId,
|
||||||
|
requestedUrl.searchParams.get("albumId"),
|
||||||
|
)
|
||||||
|
: await isGrantedEditorialAsset(dependencies, access.editorialId, assetId);
|
||||||
|
if (!authorized) {
|
||||||
|
return genericNotFound();
|
||||||
|
}
|
||||||
|
|
||||||
|
const thumbnail = await dependencies.immich.getThumbnail(assetId);
|
||||||
|
return thumbnailResponse(thumbnail);
|
||||||
|
} catch {
|
||||||
|
return genericNotFound();
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function authorizeRequest(
|
||||||
|
dependencies: ThumbnailHandlerDependencies,
|
||||||
|
requestHeaders: Headers,
|
||||||
|
): Promise<Access> {
|
||||||
|
try {
|
||||||
|
const principal = await dependencies.requireActiveEditorial(requestHeaders);
|
||||||
|
return { kind: "editorial", editorialId: principal.editorialId };
|
||||||
|
} catch (error) {
|
||||||
|
if (!(error instanceof PrincipalAuthorizationError) || error.code !== "ADMIN_REQUIRED") {
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await dependencies.requireAdmin(requestHeaders);
|
||||||
|
return { kind: "admin" };
|
||||||
|
}
|
||||||
|
|
||||||
|
async function isGrantedEditorialAsset(
|
||||||
|
dependencies: ThumbnailHandlerDependencies,
|
||||||
|
editorialId: string,
|
||||||
|
assetId: string,
|
||||||
|
): Promise<boolean> {
|
||||||
|
const grantedAlbumIds = [...new Set(await dependencies.getGrantedAlbumIds(editorialId))];
|
||||||
|
if (grantedAlbumIds.length === 0) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const assetAlbums = await dependencies.immich.listAlbumsForAsset(assetId);
|
||||||
|
const granted = new Set(grantedAlbumIds);
|
||||||
|
return assetAlbums.some((album) => granted.has(album.id));
|
||||||
|
}
|
||||||
|
|
||||||
|
async function isAdminAlbumCover(
|
||||||
|
immich: ThumbnailImmich,
|
||||||
|
assetId: string,
|
||||||
|
albumId: string | null,
|
||||||
|
): Promise<boolean> {
|
||||||
|
if (!albumId || !isSafeAssetId(albumId)) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
const album = await immich.getAlbum(albumId);
|
||||||
|
return album.albumThumbnailAssetId === assetId;
|
||||||
|
}
|
||||||
|
|
||||||
|
function thumbnailResponse(thumbnail: ImmichBinary): Response {
|
||||||
|
const responseHeaders = new Headers({
|
||||||
|
"cache-control": "private, no-store",
|
||||||
|
"content-type": thumbnail.contentType,
|
||||||
|
"x-content-type-options": "nosniff",
|
||||||
|
});
|
||||||
|
if (thumbnail.contentLength !== null) {
|
||||||
|
responseHeaders.set("content-length", String(thumbnail.contentLength));
|
||||||
|
}
|
||||||
|
return new Response(thumbnail.body, { headers: responseHeaders });
|
||||||
|
}
|
||||||
|
|
||||||
|
function genericNotFound(): Response {
|
||||||
|
return new Response(null, { status: 404 });
|
||||||
|
}
|
||||||
|
|
||||||
|
function isSafeAssetId(assetId: string): boolean {
|
||||||
|
return /^[A-Za-z0-9_-]{1,200}$/.test(assetId);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const authorizedThumbnailHandler = createThumbnailHandler({
|
||||||
|
requireActiveEditorial,
|
||||||
|
requireAdmin,
|
||||||
|
getGrantedAlbumIds: albumGrantService.getGrantedAlbumIds,
|
||||||
|
immich: immichClient,
|
||||||
|
});
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import { toNextJsHandler } from "better-auth/next-js";
|
||||||
|
import { NextResponse } from "next/server";
|
||||||
|
|
||||||
|
import { auth } from "@/modules/auth/auth";
|
||||||
|
|
||||||
|
const handlers = toNextJsHandler(auth);
|
||||||
|
|
||||||
|
export const GET = handlers.GET;
|
||||||
|
|
||||||
|
export async function POST(
|
||||||
|
request: Request,
|
||||||
|
{ params }: { params: Promise<{ all: string[] }> },
|
||||||
|
): Promise<Response> {
|
||||||
|
const { all } = await params;
|
||||||
|
|
||||||
|
if (all.join("/") === "sign-up/email") {
|
||||||
|
return NextResponse.json(
|
||||||
|
{ message: "Bitte verwenden Sie die Registrierung des Redaktionsportals." },
|
||||||
|
{ status: 403 },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return handlers.POST(request);
|
||||||
|
}
|
||||||
@@ -0,0 +1,88 @@
|
|||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
import { requireAdmin, PrincipalAuthorizationError } from "@/modules/auth/principal";
|
||||||
|
import {
|
||||||
|
cancelReport,
|
||||||
|
ReportValidationError,
|
||||||
|
ReportConflictError,
|
||||||
|
} from "@/modules/billing/reports";
|
||||||
|
import { assertSameOrigin, CrossOriginRequestError } from "@/modules/security/origin";
|
||||||
|
|
||||||
|
const cancelPayload = z
|
||||||
|
.object({
|
||||||
|
reason: z.string().trim().min(5).max(500),
|
||||||
|
confirm: z.literal(true),
|
||||||
|
})
|
||||||
|
.strict();
|
||||||
|
|
||||||
|
type CancelReportRouteContext = Readonly<{ params: Promise<{ reportId: string }> }>;
|
||||||
|
|
||||||
|
type CancelHandlerDependencies = {
|
||||||
|
requireAdmin: typeof requireAdmin;
|
||||||
|
cancelReport: typeof cancelReport;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function createCancelReportHandler(dependencies: CancelHandlerDependencies) {
|
||||||
|
return async function POST(
|
||||||
|
request: Request,
|
||||||
|
context: CancelReportRouteContext,
|
||||||
|
): Promise<Response> {
|
||||||
|
try {
|
||||||
|
assertSameOrigin(request);
|
||||||
|
const principal = await dependencies.requireAdmin(request.headers);
|
||||||
|
const { reportId } = await context.params;
|
||||||
|
const payload = cancelPayload.safeParse(await readJson(request));
|
||||||
|
if (!payload.success) return jsonError(400, "INVALID_REQUEST");
|
||||||
|
|
||||||
|
await dependencies.cancelReport({
|
||||||
|
reportId,
|
||||||
|
reason: payload.data.reason,
|
||||||
|
adminUserId: principal.userId,
|
||||||
|
});
|
||||||
|
|
||||||
|
return Response.json(
|
||||||
|
{ status: "cancelled" },
|
||||||
|
{ status: 200, headers: { "cache-control": "private, no-store" } },
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
return mappedError(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function readJson(request: Request): Promise<unknown> {
|
||||||
|
try {
|
||||||
|
return await request.json();
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function mappedError(error: unknown): Response {
|
||||||
|
if (error instanceof CrossOriginRequestError) {
|
||||||
|
return jsonError(403, "CROSS_ORIGIN_REQUEST");
|
||||||
|
}
|
||||||
|
if (error instanceof PrincipalAuthorizationError) {
|
||||||
|
return jsonError(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN");
|
||||||
|
}
|
||||||
|
if (error instanceof ReportValidationError) {
|
||||||
|
return jsonError(400, error.code);
|
||||||
|
}
|
||||||
|
if (error instanceof ReportConflictError) {
|
||||||
|
if (error.code === "REPORT_NOT_FOUND") return jsonError(404, error.code);
|
||||||
|
return jsonError(409, error.code);
|
||||||
|
}
|
||||||
|
return jsonError(500, "REQUEST_FAILED");
|
||||||
|
}
|
||||||
|
|
||||||
|
function jsonError(status: number, code: string): Response {
|
||||||
|
return Response.json(
|
||||||
|
{ code },
|
||||||
|
{ status, headers: { "cache-control": "private, no-store" } },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const cancelReportHandler = createCancelReportHandler({
|
||||||
|
requireAdmin,
|
||||||
|
cancelReport,
|
||||||
|
});
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
import { cancelReportHandler } from "./cancel-handler";
|
||||||
|
|
||||||
|
export const POST = cancelReportHandler;
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
import { requireAdmin, PrincipalAuthorizationError } from "@/modules/auth/principal";
|
||||||
|
import { getReportPdf } from "@/modules/billing/reports";
|
||||||
|
|
||||||
|
type GetReportRouteContext = Readonly<{ params: Promise<{ reportId: string }> }>;
|
||||||
|
|
||||||
|
type GetHandlerDependencies = {
|
||||||
|
requireAdmin: typeof requireAdmin;
|
||||||
|
getReportPdf: typeof getReportPdf;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function createGetReportHandler(dependencies: GetHandlerDependencies) {
|
||||||
|
return async function GET(
|
||||||
|
request: Request,
|
||||||
|
context: GetReportRouteContext,
|
||||||
|
): Promise<Response> {
|
||||||
|
try {
|
||||||
|
await dependencies.requireAdmin(request.headers);
|
||||||
|
const { reportId } = await context.params;
|
||||||
|
|
||||||
|
const report = await dependencies.getReportPdf(reportId);
|
||||||
|
if (!report) return notFound();
|
||||||
|
|
||||||
|
const filename = buildFilename(report.invoiceNumber);
|
||||||
|
return new Response(new Uint8Array(report.bytes), {
|
||||||
|
status: 200,
|
||||||
|
headers: {
|
||||||
|
"content-type": "application/pdf",
|
||||||
|
"cache-control": "private, no-store",
|
||||||
|
"content-disposition": `attachment; filename="${filename}"`,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof PrincipalAuthorizationError) {
|
||||||
|
return jsonError(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN");
|
||||||
|
}
|
||||||
|
return jsonError(500, "REQUEST_FAILED");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function buildFilename(invoiceNumber: string): string {
|
||||||
|
const safe = invoiceNumber.replace(/[^A-Za-z0-9_-]/g, "_");
|
||||||
|
return `${safe || "nutzungsnachweis"}.pdf`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function notFound(): Response {
|
||||||
|
return new Response(null, {
|
||||||
|
status: 404,
|
||||||
|
headers: { "cache-control": "private, no-store" },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function jsonError(status: number, code: string): Response {
|
||||||
|
return Response.json(
|
||||||
|
{ code },
|
||||||
|
{ status, headers: { "cache-control": "private, no-store" } },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const getReportHandler = createGetReportHandler({
|
||||||
|
requireAdmin,
|
||||||
|
getReportPdf,
|
||||||
|
});
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
import { getReportHandler } from "./get-handler";
|
||||||
|
|
||||||
|
export const GET = getReportHandler;
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
import { requireAdmin, PrincipalAuthorizationError } from "@/modules/auth/principal";
|
||||||
|
import {
|
||||||
|
finalizeReport,
|
||||||
|
ReportValidationError,
|
||||||
|
ReportConflictError,
|
||||||
|
} from "@/modules/billing/reports";
|
||||||
|
import { monthPeriod, quarterPeriod } from "@/modules/billing/period";
|
||||||
|
import { assertSameOrigin, CrossOriginRequestError } from "@/modules/security/origin";
|
||||||
|
|
||||||
|
const finalizePayload = z
|
||||||
|
.object({
|
||||||
|
editorialId: z.string().uuid(),
|
||||||
|
usageIds: z.array(z.string().uuid()).min(1),
|
||||||
|
year: z.number().int().min(2020).max(2100),
|
||||||
|
month: z.number().int().min(1).max(12).optional(),
|
||||||
|
quarter: z.number().int().min(1).max(4).optional(),
|
||||||
|
})
|
||||||
|
.strict()
|
||||||
|
.refine((data) => (data.month !== undefined) !== (data.quarter !== undefined), {
|
||||||
|
message: "Exactly one of month or quarter must be provided",
|
||||||
|
});
|
||||||
|
|
||||||
|
type FinalizeHandlerDependencies = {
|
||||||
|
requireAdmin: typeof requireAdmin;
|
||||||
|
finalizeReport: typeof finalizeReport;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function createFinalizeHandler(dependencies: FinalizeHandlerDependencies) {
|
||||||
|
return async function POST(request: Request): Promise<Response> {
|
||||||
|
try {
|
||||||
|
assertSameOrigin(request);
|
||||||
|
const principal = await dependencies.requireAdmin(request.headers);
|
||||||
|
const payload = finalizePayload.safeParse(await readJson(request));
|
||||||
|
if (!payload.success) return jsonError(400, "INVALID_REQUEST");
|
||||||
|
|
||||||
|
const { editorialId, usageIds, year, month, quarter } = payload.data;
|
||||||
|
const period = month ? monthPeriod(year, month) : quarterPeriod(year, quarter!);
|
||||||
|
|
||||||
|
const result = await dependencies.finalizeReport({
|
||||||
|
editorialId,
|
||||||
|
usageIds,
|
||||||
|
period,
|
||||||
|
adminUserId: principal.userId,
|
||||||
|
});
|
||||||
|
|
||||||
|
return Response.json(
|
||||||
|
{
|
||||||
|
reportId: result.reportId,
|
||||||
|
reportNumber: result.reportNumber,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
status: 201,
|
||||||
|
headers: { "cache-control": "private, no-store" },
|
||||||
|
},
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
return mappedError(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function readJson(request: Request): Promise<unknown> {
|
||||||
|
try {
|
||||||
|
return await request.json();
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function mappedError(error: unknown): Response {
|
||||||
|
if (error instanceof CrossOriginRequestError) {
|
||||||
|
return jsonError(403, "CROSS_ORIGIN_REQUEST");
|
||||||
|
}
|
||||||
|
if (error instanceof PrincipalAuthorizationError) {
|
||||||
|
return jsonError(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN");
|
||||||
|
}
|
||||||
|
if (error instanceof ReportValidationError) {
|
||||||
|
return jsonError(400, error.code);
|
||||||
|
}
|
||||||
|
if (error instanceof ReportConflictError) {
|
||||||
|
return jsonError(409, error.code);
|
||||||
|
}
|
||||||
|
return jsonError(500, "REQUEST_FAILED");
|
||||||
|
}
|
||||||
|
|
||||||
|
function jsonError(status: number, code: string): Response {
|
||||||
|
return Response.json(
|
||||||
|
{ code },
|
||||||
|
{ status, headers: { "cache-control": "private, no-store" } },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const finalizeHandler = createFinalizeHandler({
|
||||||
|
requireAdmin,
|
||||||
|
finalizeReport,
|
||||||
|
});
|
||||||
@@ -0,0 +1,87 @@
|
|||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
import { requireAdmin, PrincipalAuthorizationError } from "@/modules/auth/principal";
|
||||||
|
import { previewReport, ReportValidationError, ReportConflictError } from "@/modules/billing/reports";
|
||||||
|
import { monthPeriod, quarterPeriod } from "@/modules/billing/period";
|
||||||
|
import { assertSameOrigin, CrossOriginRequestError } from "@/modules/security/origin";
|
||||||
|
|
||||||
|
const previewPayload = z
|
||||||
|
.object({
|
||||||
|
editorialId: z.string().uuid(),
|
||||||
|
usageIds: z.array(z.string().uuid()).min(1),
|
||||||
|
year: z.number().int().min(2020).max(2100),
|
||||||
|
month: z.number().int().min(1).max(12).optional(),
|
||||||
|
quarter: z.number().int().min(1).max(4).optional(),
|
||||||
|
})
|
||||||
|
.strict()
|
||||||
|
.refine((data) => (data.month !== undefined) !== (data.quarter !== undefined), {
|
||||||
|
message: "Exactly one of month or quarter must be provided",
|
||||||
|
});
|
||||||
|
|
||||||
|
type PreviewHandlerDependencies = {
|
||||||
|
requireAdmin: typeof requireAdmin;
|
||||||
|
previewReport: typeof previewReport;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function createPreviewHandler(dependencies: PreviewHandlerDependencies) {
|
||||||
|
return async function POST(request: Request): Promise<Response> {
|
||||||
|
try {
|
||||||
|
assertSameOrigin(request);
|
||||||
|
await dependencies.requireAdmin(request.headers);
|
||||||
|
const payload = previewPayload.safeParse(await readJson(request));
|
||||||
|
if (!payload.success) return jsonError(400, "INVALID_REQUEST");
|
||||||
|
|
||||||
|
const { editorialId, usageIds, year, month, quarter } = payload.data;
|
||||||
|
const period = month ? monthPeriod(year, month) : quarterPeriod(year, quarter!);
|
||||||
|
|
||||||
|
const bytes = await dependencies.previewReport({ editorialId, usageIds, period });
|
||||||
|
|
||||||
|
return new Response(new Uint8Array(bytes), {
|
||||||
|
status: 200,
|
||||||
|
headers: {
|
||||||
|
"content-type": "application/pdf",
|
||||||
|
"cache-control": "private, no-store",
|
||||||
|
"content-disposition": 'inline; filename="nutzungsnachweis-vorschau.pdf"',
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
return mappedError(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function readJson(request: Request): Promise<unknown> {
|
||||||
|
try {
|
||||||
|
return await request.json();
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function mappedError(error: unknown): Response {
|
||||||
|
if (error instanceof CrossOriginRequestError) {
|
||||||
|
return jsonError(403, "CROSS_ORIGIN_REQUEST");
|
||||||
|
}
|
||||||
|
if (error instanceof PrincipalAuthorizationError) {
|
||||||
|
return jsonError(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN");
|
||||||
|
}
|
||||||
|
if (error instanceof ReportValidationError) {
|
||||||
|
return jsonError(400, error.code);
|
||||||
|
}
|
||||||
|
if (error instanceof ReportConflictError) {
|
||||||
|
return jsonError(409, error.code);
|
||||||
|
}
|
||||||
|
return jsonError(500, "REQUEST_FAILED");
|
||||||
|
}
|
||||||
|
|
||||||
|
function jsonError(status: number, code: string): Response {
|
||||||
|
return Response.json(
|
||||||
|
{ code },
|
||||||
|
{ status, headers: { "cache-control": "private, no-store" } },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const previewHandler = createPreviewHandler({
|
||||||
|
requireAdmin,
|
||||||
|
previewReport,
|
||||||
|
});
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
import { previewHandler } from "./preview-handler";
|
||||||
|
|
||||||
|
export const POST = previewHandler;
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
import { finalizeHandler } from "./finalize-handler";
|
||||||
|
|
||||||
|
export const POST = finalizeHandler;
|
||||||
@@ -0,0 +1,129 @@
|
|||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
import { createRepeatDownload } from "@/modules/downloads/service";
|
||||||
|
import { requireActiveEditorial, PrincipalAuthorizationError } from "@/modules/auth/principal";
|
||||||
|
import { assertSameOrigin, CrossOriginRequestError } from "@/modules/security/origin";
|
||||||
|
import { createNewUsage } from "@/modules/usages/service";
|
||||||
|
import { UsageAccountingError } from "@/modules/usages/types";
|
||||||
|
|
||||||
|
const newUsagePayload = z
|
||||||
|
.object({
|
||||||
|
kind: z.literal("new_usage"),
|
||||||
|
assetId: z.string(),
|
||||||
|
albumId: z.string(),
|
||||||
|
purpose: z.string(),
|
||||||
|
reference: z.string().optional(),
|
||||||
|
idempotencyKey: z.string(),
|
||||||
|
})
|
||||||
|
.strict();
|
||||||
|
|
||||||
|
const repeatDownloadPayload = z
|
||||||
|
.object({
|
||||||
|
kind: z.literal("repeat_download"),
|
||||||
|
usageId: z.string(),
|
||||||
|
note: z.string().optional(),
|
||||||
|
idempotencyKey: z.string(),
|
||||||
|
})
|
||||||
|
.strict();
|
||||||
|
|
||||||
|
const intentPayload = z.discriminatedUnion("kind", [newUsagePayload, repeatDownloadPayload]);
|
||||||
|
|
||||||
|
type IntentHandlerDependencies = {
|
||||||
|
requireActiveEditorial: typeof requireActiveEditorial;
|
||||||
|
createNewUsage: typeof createNewUsage;
|
||||||
|
createRepeatDownload: typeof createRepeatDownload;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function createDownloadIntentHandler(dependencies: IntentHandlerDependencies) {
|
||||||
|
return async function POST(request: Request): Promise<Response> {
|
||||||
|
try {
|
||||||
|
assertSameOrigin(request);
|
||||||
|
const principal = await dependencies.requireActiveEditorial(request.headers);
|
||||||
|
const payload = intentPayload.safeParse(await readJson(request));
|
||||||
|
if (!payload.success) return errorResponse(400, "INVALID_REQUEST");
|
||||||
|
|
||||||
|
const intent =
|
||||||
|
payload.data.kind === "new_usage"
|
||||||
|
? await dependencies.createNewUsage({
|
||||||
|
editorialId: principal.editorialId,
|
||||||
|
assetId: payload.data.assetId,
|
||||||
|
albumId: payload.data.albumId,
|
||||||
|
purpose: payload.data.purpose,
|
||||||
|
...(payload.data.reference === undefined
|
||||||
|
? {}
|
||||||
|
: { reference: payload.data.reference }),
|
||||||
|
idempotencyKey: payload.data.idempotencyKey,
|
||||||
|
})
|
||||||
|
: await dependencies.createRepeatDownload({
|
||||||
|
editorialId: principal.editorialId,
|
||||||
|
usageId: payload.data.usageId,
|
||||||
|
...(payload.data.note === undefined ? {} : { note: payload.data.note }),
|
||||||
|
idempotencyKey: payload.data.idempotencyKey,
|
||||||
|
});
|
||||||
|
|
||||||
|
return Response.json(
|
||||||
|
{
|
||||||
|
downloadId: intent.id,
|
||||||
|
fileUrl: `/api/downloads/${encodeURIComponent(intent.id)}/file`,
|
||||||
|
priceCents: intent.priceCents,
|
||||||
|
billable: intent.billable,
|
||||||
|
},
|
||||||
|
{ status: 201, headers: { "cache-control": "private, no-store" } },
|
||||||
|
);
|
||||||
|
} catch (error) {
|
||||||
|
return mappedError(error);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function readJson(request: Request): Promise<unknown> {
|
||||||
|
try {
|
||||||
|
return await request.json();
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function mappedError(error: unknown): Response {
|
||||||
|
if (error instanceof CrossOriginRequestError) {
|
||||||
|
return errorResponse(403, "CROSS_ORIGIN_REQUEST");
|
||||||
|
}
|
||||||
|
if (error instanceof PrincipalAuthorizationError) {
|
||||||
|
return errorResponse(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN");
|
||||||
|
}
|
||||||
|
if (error instanceof UsageAccountingError) {
|
||||||
|
switch (error.code) {
|
||||||
|
case "INVALID_INPUT":
|
||||||
|
return errorResponse(400, "INVALID_REQUEST");
|
||||||
|
case "IDEMPOTENCY_CONFLICT":
|
||||||
|
return errorResponse(409, "IDEMPOTENCY_CONFLICT");
|
||||||
|
case "ALBUM_NOT_GRANTED":
|
||||||
|
case "ASSET_NOT_FOUND":
|
||||||
|
case "ASSET_NOT_IN_ALBUM":
|
||||||
|
case "USAGE_NOT_FOUND":
|
||||||
|
return errorResponse(404, "NOT_FOUND");
|
||||||
|
case "IMMICH_UNAVAILABLE":
|
||||||
|
return errorResponse(503, "UPSTREAM_UNAVAILABLE");
|
||||||
|
case "ASSET_NOT_IMAGE":
|
||||||
|
return errorResponse(422, "INVALID_ASSET");
|
||||||
|
case "EDITORIAL_NOT_ACTIVE":
|
||||||
|
return errorResponse(403, "FORBIDDEN");
|
||||||
|
case "INVALID_PRICE":
|
||||||
|
return errorResponse(409, "ACCOUNTING_UNAVAILABLE");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return errorResponse(500, "REQUEST_FAILED");
|
||||||
|
}
|
||||||
|
|
||||||
|
function errorResponse(status: number, code: string): Response {
|
||||||
|
return Response.json(
|
||||||
|
{ code },
|
||||||
|
{ status, headers: { "cache-control": "private, no-store" } },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const authorizedDownloadIntentHandler = createDownloadIntentHandler({
|
||||||
|
requireActiveEditorial,
|
||||||
|
createNewUsage,
|
||||||
|
createRepeatDownload,
|
||||||
|
});
|
||||||
@@ -0,0 +1,140 @@
|
|||||||
|
import { expect, test, vi } from "vitest";
|
||||||
|
|
||||||
|
import { createDownloadIntentHandler } from "./intent-handler";
|
||||||
|
|
||||||
|
const editorialId = "11111111-1111-4111-8111-111111111111";
|
||||||
|
const assetId = "22222222-2222-4222-8222-222222222222";
|
||||||
|
const albumId = "33333333-3333-4333-8333-333333333333";
|
||||||
|
const usageId = "44444444-4444-4444-8444-444444444444";
|
||||||
|
const idempotencyKey = "55555555-5555-4555-8555-555555555555";
|
||||||
|
const downloadId = "66666666-6666-4666-8666-666666666666";
|
||||||
|
|
||||||
|
function dependencies() {
|
||||||
|
return {
|
||||||
|
requireActiveEditorial: vi.fn().mockResolvedValue({ editorialId }),
|
||||||
|
createNewUsage: vi.fn().mockResolvedValue({
|
||||||
|
id: downloadId,
|
||||||
|
usageId,
|
||||||
|
assetId,
|
||||||
|
priceCents: 1_500,
|
||||||
|
billable: true,
|
||||||
|
status: "authorized",
|
||||||
|
authorizedAt: new Date("2026-08-10T10:00:00.000Z"),
|
||||||
|
}),
|
||||||
|
createRepeatDownload: vi.fn().mockResolvedValue({
|
||||||
|
id: downloadId,
|
||||||
|
usageId,
|
||||||
|
assetId,
|
||||||
|
priceCents: 0,
|
||||||
|
billable: false,
|
||||||
|
status: "authorized",
|
||||||
|
authorizedAt: new Date("2026-08-10T10:00:00.000Z"),
|
||||||
|
}),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function post(handler: ReturnType<typeof createDownloadIntentHandler>, body: unknown) {
|
||||||
|
return handler(
|
||||||
|
new Request("http://portal.test/api/download-intents", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "content-type": "application/json" },
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
test("derives editorial scope and billable price exclusively on the server", async () => {
|
||||||
|
const deps = dependencies();
|
||||||
|
const response = await post(createDownloadIntentHandler(deps), {
|
||||||
|
kind: "new_usage",
|
||||||
|
assetId,
|
||||||
|
albumId,
|
||||||
|
purpose: "Titelgeschichte",
|
||||||
|
idempotencyKey,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.status).toBe(201);
|
||||||
|
await expect(response.json()).resolves.toEqual({
|
||||||
|
downloadId,
|
||||||
|
fileUrl: `/api/downloads/${downloadId}/file`,
|
||||||
|
priceCents: 1_500,
|
||||||
|
billable: true,
|
||||||
|
});
|
||||||
|
expect(deps.createNewUsage).toHaveBeenCalledWith({
|
||||||
|
editorialId,
|
||||||
|
assetId,
|
||||||
|
albumId,
|
||||||
|
purpose: "Titelgeschichte",
|
||||||
|
idempotencyKey,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test("creates a zero-cost repeat intent scoped to the authenticated editorial", async () => {
|
||||||
|
const deps = dependencies();
|
||||||
|
const response = await post(createDownloadIntentHandler(deps), {
|
||||||
|
kind: "repeat_download",
|
||||||
|
usageId,
|
||||||
|
note: "erneuter Abruf",
|
||||||
|
idempotencyKey,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.status).toBe(201);
|
||||||
|
expect(deps.createRepeatDownload).toHaveBeenCalledWith({
|
||||||
|
editorialId,
|
||||||
|
usageId,
|
||||||
|
note: "erneuter Abruf",
|
||||||
|
idempotencyKey,
|
||||||
|
});
|
||||||
|
await expect(response.json()).resolves.toMatchObject({ priceCents: 0, billable: false });
|
||||||
|
});
|
||||||
|
|
||||||
|
test.each([
|
||||||
|
{ field: "editorialId", value: "77777777-7777-4777-8777-777777777777" },
|
||||||
|
{ field: "priceCents", value: 1 },
|
||||||
|
])("rejects a client-controlled $field before any accounting side effect", async ({ field, value }) => {
|
||||||
|
const deps = dependencies();
|
||||||
|
const response = await post(createDownloadIntentHandler(deps), {
|
||||||
|
kind: "new_usage",
|
||||||
|
assetId,
|
||||||
|
albumId,
|
||||||
|
purpose: "Titelgeschichte",
|
||||||
|
idempotencyKey,
|
||||||
|
[field]: value,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.status).toBe(400);
|
||||||
|
expect(deps.createNewUsage).not.toHaveBeenCalled();
|
||||||
|
expect(deps.createRepeatDownload).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("rejects mixed new and repeat fields as an invalid discriminated payload", async () => {
|
||||||
|
const deps = dependencies();
|
||||||
|
const response = await post(createDownloadIntentHandler(deps), {
|
||||||
|
kind: "repeat_download",
|
||||||
|
usageId,
|
||||||
|
assetId,
|
||||||
|
idempotencyKey,
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(response.status).toBe(400);
|
||||||
|
expect(deps.createRepeatDownload).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("passes one submitted idempotency key through unchanged", async () => {
|
||||||
|
const deps = dependencies();
|
||||||
|
const handler = createDownloadIntentHandler(deps);
|
||||||
|
const body = {
|
||||||
|
kind: "new_usage",
|
||||||
|
assetId,
|
||||||
|
albumId,
|
||||||
|
purpose: "Titelgeschichte",
|
||||||
|
idempotencyKey,
|
||||||
|
};
|
||||||
|
|
||||||
|
const [first, retry] = await Promise.all([post(handler, body), post(handler, body)]);
|
||||||
|
|
||||||
|
expect(first.status).toBe(201);
|
||||||
|
expect(retry.status).toBe(201);
|
||||||
|
expect(deps.createNewUsage).toHaveBeenNthCalledWith(1, expect.objectContaining({ idempotencyKey }));
|
||||||
|
expect(deps.createNewUsage).toHaveBeenNthCalledWith(2, expect.objectContaining({ idempotencyKey }));
|
||||||
|
});
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
import { authorizedDownloadIntentHandler } from "./intent-handler";
|
||||||
|
|
||||||
|
export const POST = authorizedDownloadIntentHandler;
|
||||||
@@ -0,0 +1,167 @@
|
|||||||
|
import { downloadDeliveryRepository, streamWithAccounting } from "@/modules/downloads/stream";
|
||||||
|
import { requireActiveEditorial, PrincipalAuthorizationError } from "@/modules/auth/principal";
|
||||||
|
import { assertSameOrigin, CrossOriginRequestError } from "@/modules/security/origin";
|
||||||
|
import { immichClient } from "@/modules/immich/client";
|
||||||
|
import type { ImmichBinary } from "@/modules/immich/types";
|
||||||
|
import { normalizeUuid } from "@/modules/usages/types";
|
||||||
|
|
||||||
|
type DownloadFileRouteContext = Readonly<{ params: Promise<{ downloadId: string }> }>;
|
||||||
|
|
||||||
|
type DownloadFileHandlerDependencies = {
|
||||||
|
requireActiveEditorial: typeof requireActiveEditorial;
|
||||||
|
repository: typeof downloadDeliveryRepository;
|
||||||
|
immich: { getOriginal(assetId: string, signal?: AbortSignal): Promise<ImmichBinary> };
|
||||||
|
};
|
||||||
|
|
||||||
|
export function createDownloadFileHandler(dependencies: DownloadFileHandlerDependencies) {
|
||||||
|
return async function GET(
|
||||||
|
request: Request,
|
||||||
|
context: DownloadFileRouteContext,
|
||||||
|
): Promise<Response> {
|
||||||
|
try {
|
||||||
|
assertSameOrigin(request);
|
||||||
|
const principal = await dependencies.requireActiveEditorial(request.headers);
|
||||||
|
const downloadId = safeDownloadId((await context.params).downloadId);
|
||||||
|
if (!downloadId) return genericNotFound();
|
||||||
|
|
||||||
|
const claim = await dependencies.repository.claimAuthorized(
|
||||||
|
principal.editorialId,
|
||||||
|
downloadId,
|
||||||
|
);
|
||||||
|
if (claim.outcome === "not_found") return genericNotFound();
|
||||||
|
if (claim.outcome === "not_authorized") {
|
||||||
|
return jsonError(409, "DOWNLOAD_NOT_AVAILABLE");
|
||||||
|
}
|
||||||
|
|
||||||
|
let original: ImmichBinary;
|
||||||
|
try {
|
||||||
|
original = await dependencies.immich.getOriginal(
|
||||||
|
claim.download.assetId,
|
||||||
|
request.signal,
|
||||||
|
);
|
||||||
|
} catch {
|
||||||
|
await failClaimBeforeDelivery(dependencies, downloadId, claim.download.intentKind);
|
||||||
|
return jsonError(503, "DOWNLOAD_UNAVAILABLE");
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
const body = streamWithAccounting({
|
||||||
|
downloadId,
|
||||||
|
upstream: original.body,
|
||||||
|
voidNewUsageOnFailure: claim.download.intentKind === "new_usage",
|
||||||
|
repository: dependencies.repository,
|
||||||
|
});
|
||||||
|
return new Response(body, {
|
||||||
|
headers: downloadHeaders(original, claim.download.filename),
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
const cancellation = Promise.resolve().then(() => original.body.cancel());
|
||||||
|
await Promise.allSettled([
|
||||||
|
cancellation,
|
||||||
|
failClaimBeforeDelivery(dependencies, downloadId, claim.download.intentKind),
|
||||||
|
]);
|
||||||
|
return jsonError(503, "DOWNLOAD_UNAVAILABLE");
|
||||||
|
}
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof CrossOriginRequestError) {
|
||||||
|
return jsonError(403, "CROSS_ORIGIN_REQUEST");
|
||||||
|
}
|
||||||
|
if (error instanceof PrincipalAuthorizationError) {
|
||||||
|
return jsonError(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN");
|
||||||
|
}
|
||||||
|
return jsonError(503, "DOWNLOAD_UNAVAILABLE");
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
async function failClaimBeforeDelivery(
|
||||||
|
dependencies: DownloadFileHandlerDependencies,
|
||||||
|
downloadId: string,
|
||||||
|
intentKind: "new_usage" | "repeat_download" | "legacy",
|
||||||
|
) {
|
||||||
|
await dependencies.repository
|
||||||
|
.failBeforeDelivery(downloadId, { voidNewUsage: intentKind === "new_usage" })
|
||||||
|
.catch(() => undefined);
|
||||||
|
}
|
||||||
|
|
||||||
|
function safeDownloadId(value: string): string | null {
|
||||||
|
try {
|
||||||
|
return normalizeUuid(value);
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function downloadHeaders(original: ImmichBinary, snapshotFilename: string): Headers {
|
||||||
|
const headers = new Headers({
|
||||||
|
"cache-control": "private, no-store",
|
||||||
|
"content-disposition": contentDisposition(original.filename || snapshotFilename),
|
||||||
|
"content-type": safeContentType(original.contentType),
|
||||||
|
"x-content-type-options": "nosniff",
|
||||||
|
});
|
||||||
|
if (
|
||||||
|
original.contentLength !== null &&
|
||||||
|
Number.isSafeInteger(original.contentLength) &&
|
||||||
|
original.contentLength >= 0
|
||||||
|
) {
|
||||||
|
headers.set("content-length", String(original.contentLength));
|
||||||
|
}
|
||||||
|
return headers;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function contentDisposition(filename: string): string {
|
||||||
|
const cleaned = cleanFilename(filename);
|
||||||
|
const fallback = asciiFilename(cleaned);
|
||||||
|
const encoded = encodeURIComponent(cleaned).replace(/[!'()*]/g, (character) =>
|
||||||
|
`%${character.charCodeAt(0).toString(16).toUpperCase()}`,
|
||||||
|
);
|
||||||
|
return `attachment; filename="${fallback}"; filename*=UTF-8''${encoded}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
function cleanFilename(filename: string): string {
|
||||||
|
const cleaned = [...filename.normalize("NFC").replace(/[\uD800-\uDFFF]/gu, "_")]
|
||||||
|
.slice(0, 180)
|
||||||
|
.join("")
|
||||||
|
.replace(/[\\/]/g, "_")
|
||||||
|
.replace(/[\u0000-\u001f\u007f-\u009f]/g, "")
|
||||||
|
.trim();
|
||||||
|
return cleaned && cleaned !== "." && cleaned !== ".." ? cleaned : "download";
|
||||||
|
}
|
||||||
|
|
||||||
|
function asciiFilename(filename: string): string {
|
||||||
|
const fallback = filename
|
||||||
|
.normalize("NFKD")
|
||||||
|
.replace(/[\u0300-\u036f]/g, "")
|
||||||
|
.replace(/[^A-Za-z0-9._ ()+-]/g, "_")
|
||||||
|
.replace(/[";]/g, "_")
|
||||||
|
.trim();
|
||||||
|
return fallback && fallback !== "." && fallback !== ".." ? fallback : "download";
|
||||||
|
}
|
||||||
|
|
||||||
|
function safeContentType(value: string): string {
|
||||||
|
return /^[A-Za-z0-9!#$&^_.+-]+\/[A-Za-z0-9!#$&^_.+-]+(?:[ \t]*;[ \t]*[A-Za-z0-9!#$&^_.+-]+=[A-Za-z0-9!#$&^_.+"'()-]+)*$/.test(
|
||||||
|
value,
|
||||||
|
)
|
||||||
|
? value
|
||||||
|
: "application/octet-stream";
|
||||||
|
}
|
||||||
|
|
||||||
|
function genericNotFound(): Response {
|
||||||
|
return new Response(null, {
|
||||||
|
status: 404,
|
||||||
|
headers: { "cache-control": "private, no-store" },
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function jsonError(status: number, code: string): Response {
|
||||||
|
return Response.json(
|
||||||
|
{ code },
|
||||||
|
{ status, headers: { "cache-control": "private, no-store" } },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export const authorizedDownloadFileHandler = createDownloadFileHandler({
|
||||||
|
requireActiveEditorial,
|
||||||
|
repository: downloadDeliveryRepository,
|
||||||
|
immich: immichClient,
|
||||||
|
});
|
||||||
@@ -0,0 +1,228 @@
|
|||||||
|
import { expect, test, vi } from "vitest";
|
||||||
|
|
||||||
|
import { PrincipalAuthorizationError } from "@/modules/auth/principal";
|
||||||
|
import { contentDisposition, createDownloadFileHandler } from "./download-handler";
|
||||||
|
|
||||||
|
const editorialId = "11111111-1111-4111-8111-111111111111";
|
||||||
|
const otherEditorialId = "22222222-2222-4222-8222-222222222222";
|
||||||
|
const downloadId = "33333333-3333-4333-8333-333333333333";
|
||||||
|
const usageId = "44444444-4444-4444-8444-444444444444";
|
||||||
|
const assetId = "55555555-5555-4555-8555-555555555555";
|
||||||
|
|
||||||
|
function binary(overrides: Partial<{
|
||||||
|
body: ReadableStream<Uint8Array>;
|
||||||
|
contentType: string;
|
||||||
|
contentLength: number | null;
|
||||||
|
filename: string;
|
||||||
|
}> = {}) {
|
||||||
|
return {
|
||||||
|
body: new ReadableStream<Uint8Array>({
|
||||||
|
start(controller) {
|
||||||
|
controller.enqueue(new Uint8Array([1, 2, 3]));
|
||||||
|
controller.close();
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
contentType: "image/jpeg",
|
||||||
|
contentLength: 3,
|
||||||
|
filename: "heimspiel.jpg",
|
||||||
|
...overrides,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function dependencies(options: {
|
||||||
|
claim?: "claimed" | "not_found" | "not_authorized";
|
||||||
|
editorialError?: Error;
|
||||||
|
original?: ReturnType<typeof binary>;
|
||||||
|
originalError?: Error;
|
||||||
|
intentKind?: "new_usage" | "repeat_download";
|
||||||
|
} = {}) {
|
||||||
|
const repository = {
|
||||||
|
claimAuthorized: vi.fn().mockResolvedValue(
|
||||||
|
options.claim === "not_found"
|
||||||
|
? { outcome: "not_found" }
|
||||||
|
: options.claim === "not_authorized"
|
||||||
|
? { outcome: "not_authorized" }
|
||||||
|
: {
|
||||||
|
outcome: "claimed",
|
||||||
|
download: {
|
||||||
|
id: downloadId,
|
||||||
|
usageId,
|
||||||
|
assetId,
|
||||||
|
filename: "snapshot.jpg",
|
||||||
|
intentKind: options.intentKind ?? "new_usage",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
),
|
||||||
|
failBeforeDelivery: vi.fn().mockResolvedValue(true),
|
||||||
|
markCompleted: vi.fn().mockResolvedValue(true),
|
||||||
|
markInterrupted: vi.fn().mockResolvedValue(true),
|
||||||
|
};
|
||||||
|
const values = {
|
||||||
|
requireActiveEditorial: vi.fn().mockImplementation(async () => {
|
||||||
|
if (options.editorialError) throw options.editorialError;
|
||||||
|
return { editorialId };
|
||||||
|
}),
|
||||||
|
repository,
|
||||||
|
immich: {
|
||||||
|
getOriginal: vi.fn().mockImplementation(async () => {
|
||||||
|
if (options.originalError) throw options.originalError;
|
||||||
|
return options.original ?? binary();
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
};
|
||||||
|
return values;
|
||||||
|
}
|
||||||
|
|
||||||
|
function call(
|
||||||
|
handler: ReturnType<typeof createDownloadFileHandler>,
|
||||||
|
id = downloadId,
|
||||||
|
signal?: AbortSignal,
|
||||||
|
) {
|
||||||
|
return handler(new Request(`http://portal.test/api/downloads/${id}/file`, { signal }), {
|
||||||
|
params: Promise.resolve({ downloadId: id }),
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
test("claims an owned authorized event before requesting and streaming the original", async () => {
|
||||||
|
const deps = dependencies();
|
||||||
|
const handler = createDownloadFileHandler(deps);
|
||||||
|
|
||||||
|
const response = await call(handler);
|
||||||
|
|
||||||
|
expect(response.status).toBe(200);
|
||||||
|
expect(deps.repository.claimAuthorized).toHaveBeenCalledWith(editorialId, downloadId);
|
||||||
|
expect(deps.immich.getOriginal).toHaveBeenCalledWith(assetId, expect.any(AbortSignal));
|
||||||
|
expect(await response.arrayBuffer()).toEqual(new Uint8Array([1, 2, 3]).buffer);
|
||||||
|
expect(deps.repository.markCompleted).toHaveBeenCalledWith(downloadId, 3);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("returns the same generic 404 for an invalid id, missing event, and another editorial's event", async () => {
|
||||||
|
const invalid = dependencies();
|
||||||
|
const missing = dependencies({ claim: "not_found" });
|
||||||
|
const foreign = dependencies({ claim: "not_found" });
|
||||||
|
foreign.requireActiveEditorial.mockResolvedValue({ editorialId: otherEditorialId });
|
||||||
|
|
||||||
|
const responses = await Promise.all([
|
||||||
|
call(createDownloadFileHandler(invalid), "not-a-uuid"),
|
||||||
|
call(createDownloadFileHandler(missing)),
|
||||||
|
call(createDownloadFileHandler(foreign)),
|
||||||
|
]);
|
||||||
|
const results = await Promise.all(
|
||||||
|
responses.map(async (response) => ({ status: response.status, body: await response.text() })),
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(results[1]).toEqual(results[0]);
|
||||||
|
expect(results[2]).toEqual(results[0]);
|
||||||
|
expect(invalid.repository.claimAuthorized).not.toHaveBeenCalled();
|
||||||
|
expect(foreign.immich.getOriginal).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
|
||||||
|
test.each(["streaming", "completed", "interrupted", "failed_before_delivery"])(
|
||||||
|
"denies reuse of a %s attempt before reaching Immich",
|
||||||
|
async () => {
|
||||||
|
const deps = dependencies({ claim: "not_authorized" });
|
||||||
|
const response = await call(createDownloadFileHandler(deps));
|
||||||
|
|
||||||
|
expect(response.status).toBe(409);
|
||||||
|
await expect(response.json()).resolves.toEqual({ code: "DOWNLOAD_NOT_AVAILABLE" });
|
||||||
|
expect(deps.immich.getOriginal).not.toHaveBeenCalled();
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
test("marks a pre-response Immich failure failed and voids a new usage", async () => {
|
||||||
|
const deps = dependencies({ originalError: new Error("IMMICH_UNAVAILABLE") });
|
||||||
|
|
||||||
|
const response = await call(createDownloadFileHandler(deps));
|
||||||
|
|
||||||
|
expect(response.status).toBe(503);
|
||||||
|
expect(deps.repository.failBeforeDelivery).toHaveBeenCalledWith(downloadId, {
|
||||||
|
voidNewUsage: true,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a repeat pre-response failure retains the original usage", async () => {
|
||||||
|
const deps = dependencies({
|
||||||
|
originalError: new Error("IMMICH_UNAVAILABLE"),
|
||||||
|
intentKind: "repeat_download",
|
||||||
|
});
|
||||||
|
|
||||||
|
await call(createDownloadFileHandler(deps));
|
||||||
|
|
||||||
|
expect(deps.repository.failBeforeDelivery).toHaveBeenCalledWith(downloadId, {
|
||||||
|
voidNewUsage: false,
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test("accounts for a claimed attempt when the upstream body cannot be consumed", async () => {
|
||||||
|
const original = binary();
|
||||||
|
const lock = original.body.getReader();
|
||||||
|
const deps = dependencies({ original });
|
||||||
|
|
||||||
|
const response = await call(createDownloadFileHandler(deps));
|
||||||
|
|
||||||
|
expect(response.status).toBe(503);
|
||||||
|
expect(deps.repository.failBeforeDelivery).toHaveBeenCalledWith(downloadId, {
|
||||||
|
voidNewUsage: true,
|
||||||
|
});
|
||||||
|
lock.releaseLock();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("emits only safe download headers for an injected Unicode filename", async () => {
|
||||||
|
const deps = dependencies({
|
||||||
|
original: binary({
|
||||||
|
filename: "../München\r\nX-Internal: secret\\final.jpg",
|
||||||
|
contentType: "image/jpeg",
|
||||||
|
contentLength: 3,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await call(createDownloadFileHandler(deps));
|
||||||
|
const disposition = response.headers.get("content-disposition") ?? "";
|
||||||
|
|
||||||
|
expect(response.headers.get("cache-control")).toBe("private, no-store");
|
||||||
|
expect(response.headers.get("content-type")).toBe("image/jpeg");
|
||||||
|
expect(response.headers.get("content-length")).toBe("3");
|
||||||
|
expect(response.headers.has("x-api-key")).toBe(false);
|
||||||
|
expect(disposition).not.toMatch(/[\r\n\\/]/);
|
||||||
|
expect(disposition).toContain("filename*=UTF-8''");
|
||||||
|
expect(disposition).toContain("M%C3%BCnchen");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("falls back from an untrustworthy media type and length without forwarding header injection", async () => {
|
||||||
|
const deps = dependencies({
|
||||||
|
original: binary({
|
||||||
|
contentType: "image/jpeg;\r\nx-api-key=secret",
|
||||||
|
contentLength: -1,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const response = await call(createDownloadFileHandler(deps));
|
||||||
|
|
||||||
|
expect(response.status).toBe(200);
|
||||||
|
expect(response.headers.get("content-type")).toBe("application/octet-stream");
|
||||||
|
expect(response.headers.has("content-length")).toBe(false);
|
||||||
|
expect(response.headers.has("x-api-key")).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("builds a standards-safe disposition for malformed Unicode", () => {
|
||||||
|
expect(() => contentDisposition("foto-\ud800.jpg")).not.toThrow();
|
||||||
|
expect(contentDisposition("foto-\ud800.jpg")).toContain("filename*=UTF-8''foto-_.jpg");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("returns stable authentication semantics without exposing guard details", async () => {
|
||||||
|
const unauthenticated = dependencies({
|
||||||
|
editorialError: new PrincipalAuthorizationError("AUTHENTICATION_REQUIRED"),
|
||||||
|
});
|
||||||
|
const inactive = dependencies({
|
||||||
|
editorialError: new PrincipalAuthorizationError("ACCOUNT_SUSPENDED"),
|
||||||
|
});
|
||||||
|
|
||||||
|
const [first, second] = await Promise.all([
|
||||||
|
call(createDownloadFileHandler(unauthenticated)),
|
||||||
|
call(createDownloadFileHandler(inactive)),
|
||||||
|
]);
|
||||||
|
|
||||||
|
expect(first.status).toBe(401);
|
||||||
|
expect(second.status).toBe(403);
|
||||||
|
expect(await second.text()).not.toContain("SUSPENDED");
|
||||||
|
});
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
import { authorizedDownloadFileHandler } from "./download-handler";
|
||||||
|
|
||||||
|
export const GET = authorizedDownloadFileHandler;
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import { expect, test } from "vitest";
|
||||||
|
import { GET } from "./route";
|
||||||
|
|
||||||
|
test("returns a process liveness response", async () => {
|
||||||
|
const response = await GET();
|
||||||
|
|
||||||
|
expect(response.status).toBe(200);
|
||||||
|
await expect(response.json()).resolves.toEqual({ status: "ok" });
|
||||||
|
});
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
export async function GET(): Promise<Response> {
|
||||||
|
return Response.json({ status: "ok" });
|
||||||
|
}
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
import "server-only";
|
||||||
|
|
||||||
|
import { sql } from "drizzle-orm";
|
||||||
|
import { NextResponse } from "next/server";
|
||||||
|
|
||||||
|
import { db } from "@/db/client";
|
||||||
|
import { immichClient } from "@/modules/immich/client";
|
||||||
|
|
||||||
|
export type ReadinessCheckers = {
|
||||||
|
checkDb: () => Promise<boolean>;
|
||||||
|
checkImmich: () => Promise<boolean>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export function createReadinessRoute(checkers?: Partial<ReadinessCheckers>) {
|
||||||
|
return async function GET() {
|
||||||
|
let dbOk = false;
|
||||||
|
let immichOk = false;
|
||||||
|
|
||||||
|
try {
|
||||||
|
dbOk = checkers?.checkDb
|
||||||
|
? await checkers.checkDb()
|
||||||
|
: await (async () => {
|
||||||
|
await db.execute(sql`SELECT 1`);
|
||||||
|
return true;
|
||||||
|
})();
|
||||||
|
} catch {
|
||||||
|
dbOk = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
immichOk = checkers?.checkImmich
|
||||||
|
? await checkers.checkImmich()
|
||||||
|
: await (async () => {
|
||||||
|
await immichClient.listAlbums();
|
||||||
|
return true;
|
||||||
|
})();
|
||||||
|
} catch {
|
||||||
|
immichOk = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
const allReady = dbOk && immichOk;
|
||||||
|
const status = allReady ? "ok" : "not_ready";
|
||||||
|
const httpStatus = allReady ? 200 : 503;
|
||||||
|
|
||||||
|
return NextResponse.json(
|
||||||
|
{
|
||||||
|
status,
|
||||||
|
checks: {
|
||||||
|
database: dbOk ? "ok" : "failed",
|
||||||
|
immich: immichOk ? "ok" : "failed",
|
||||||
|
},
|
||||||
|
},
|
||||||
|
{ status: httpStatus },
|
||||||
|
);
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,43 @@
|
|||||||
|
import { describe, expect, test } from "vitest";
|
||||||
|
import { createReadinessRoute } from "./readiness-handler";
|
||||||
|
|
||||||
|
describe("GET /api/health/ready", () => {
|
||||||
|
test("returns 200 ok when database and Immich are healthy", async () => {
|
||||||
|
const route = createReadinessRoute({
|
||||||
|
checkDb: async () => true,
|
||||||
|
checkImmich: async () => true,
|
||||||
|
});
|
||||||
|
const response = await route();
|
||||||
|
expect(response.status).toBe(200);
|
||||||
|
await expect(response.json()).resolves.toEqual({
|
||||||
|
status: "ok",
|
||||||
|
checks: { database: "ok", immich: "ok" },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test("returns 503 when database is unreachable", async () => {
|
||||||
|
const route = createReadinessRoute({
|
||||||
|
checkDb: async () => false,
|
||||||
|
checkImmich: async () => true,
|
||||||
|
});
|
||||||
|
const response = await route();
|
||||||
|
expect(response.status).toBe(503);
|
||||||
|
await expect(response.json()).resolves.toEqual({
|
||||||
|
status: "not_ready",
|
||||||
|
checks: { database: "failed", immich: "ok" },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
test("returns 503 when Immich is unavailable", async () => {
|
||||||
|
const route = createReadinessRoute({
|
||||||
|
checkDb: async () => true,
|
||||||
|
checkImmich: async () => false,
|
||||||
|
});
|
||||||
|
const response = await route();
|
||||||
|
expect(response.status).toBe(503);
|
||||||
|
await expect(response.json()).resolves.toEqual({
|
||||||
|
status: "not_ready",
|
||||||
|
checks: { database: "ok", immich: "failed" },
|
||||||
|
});
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
import { createReadinessRoute } from "./readiness-handler";
|
||||||
|
|
||||||
|
export const GET = createReadinessRoute();
|
||||||
+1494
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,21 @@
|
|||||||
|
import type { Metadata } from "next";
|
||||||
|
import type { ReactNode } from "react";
|
||||||
|
import "./globals.css";
|
||||||
|
|
||||||
|
import { LegalFooter } from "@/components/layout/legal-footer";
|
||||||
|
|
||||||
|
export const metadata: Metadata = {
|
||||||
|
title: "Redaktionsportal | Leon Tonhäuser",
|
||||||
|
description: "Ausgewählte Pressefotos sicher finden und nutzen.",
|
||||||
|
};
|
||||||
|
|
||||||
|
export default function RootLayout({ children }: Readonly<{ children: ReactNode }>) {
|
||||||
|
return (
|
||||||
|
<html lang="de">
|
||||||
|
<body>
|
||||||
|
{children}
|
||||||
|
<LegalFooter />
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
export default function HomePage() {
|
||||||
|
return (
|
||||||
|
<main className="landing">
|
||||||
|
<header className="masthead">
|
||||||
|
<span className="wordmark">Leon Tonhäuser</span>
|
||||||
|
<span className="section-label">Redaktionsportal</span>
|
||||||
|
</header>
|
||||||
|
|
||||||
|
<section className="intro" aria-labelledby="intro-title">
|
||||||
|
<p className="eyebrow">Pressefotografie</p>
|
||||||
|
<h1 id="intro-title">Bilder für Ihre Redaktion.</h1>
|
||||||
|
<p className="lede">
|
||||||
|
Freigegebene Fotoalben durchsuchen, Nutzungen dokumentieren und
|
||||||
|
Originaldateien herunterladen.
|
||||||
|
</p>
|
||||||
|
<a className="primary-action" href="/anmelden">
|
||||||
|
Zum Portal
|
||||||
|
</a>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<footer className="landing-footer">
|
||||||
|
<p>Der geschützte Zugang wird im nächsten Schritt eingerichtet.</p>
|
||||||
|
</footer>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import "server-only";
|
||||||
|
|
||||||
|
import { cache } from "react";
|
||||||
|
|
||||||
|
import { headers } from "next/headers";
|
||||||
|
|
||||||
|
import { requireActiveEditorial } from "@/modules/auth/principal";
|
||||||
|
|
||||||
|
export const requireEditorial = cache(async () =>
|
||||||
|
requireActiveEditorial(new Headers(await headers())),
|
||||||
|
);
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
export default function AlbumLoading() {
|
||||||
|
return (
|
||||||
|
<section className="editorial-section editorial-state" aria-busy="true" aria-live="polite">
|
||||||
|
<p className="editorial-kicker">Bildarchiv</p>
|
||||||
|
<p>Fotos werden geladen.</p>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,110 @@
|
|||||||
|
import Link from "next/link";
|
||||||
|
import { notFound } from "next/navigation";
|
||||||
|
|
||||||
|
import { AlbumCatalogError, albumCatalog } from "@/modules/albums/catalog";
|
||||||
|
import { PhotoContactSheet } from "@/modules/albums/catalog-content";
|
||||||
|
import { loadEditorialDownloadOptions } from "@/modules/downloads/stream";
|
||||||
|
|
||||||
|
import { requireEditorial } from "../../access";
|
||||||
|
|
||||||
|
type AlbumPageProps = Readonly<{
|
||||||
|
params: Promise<{ albumId: string }>;
|
||||||
|
searchParams: Promise<{ page?: string | string[]; suche?: string | string[] }>;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
export default async function AlbumPage({ params, searchParams }: AlbumPageProps) {
|
||||||
|
const [{ albumId }, rawSearchParams, principal] = await Promise.all([
|
||||||
|
params,
|
||||||
|
searchParams,
|
||||||
|
requireEditorial(),
|
||||||
|
]);
|
||||||
|
const query = normalizedQuery(singleValue(rawSearchParams.suche));
|
||||||
|
const result = await loadAlbumPage({
|
||||||
|
editorialId: principal.editorialId,
|
||||||
|
albumId,
|
||||||
|
query,
|
||||||
|
page: singleValue(rawSearchParams.page),
|
||||||
|
});
|
||||||
|
|
||||||
|
if (result.unavailable) {
|
||||||
|
return <ImmichUnavailable />;
|
||||||
|
}
|
||||||
|
if (!result.album) {
|
||||||
|
notFound();
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="editorial-section" aria-labelledby="album-title">
|
||||||
|
<p className="editorial-kicker">Bildarchiv · {result.album.assetCount} freigegebene Fotos</p>
|
||||||
|
<div className="editorial-title-row album-title-row">
|
||||||
|
<h1 id="album-title">{result.album.albumName}</h1>
|
||||||
|
<Link className="quiet-link" href="/redaktion/alben">
|
||||||
|
Alle Alben
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
<PhotoContactSheet
|
||||||
|
albumId={result.album.id}
|
||||||
|
albumName={result.album.albumName}
|
||||||
|
downloadOptions={result.downloadOptions}
|
||||||
|
page={result.page}
|
||||||
|
query={query}
|
||||||
|
/>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadAlbumPage({
|
||||||
|
editorialId,
|
||||||
|
albumId,
|
||||||
|
query,
|
||||||
|
page,
|
||||||
|
}: {
|
||||||
|
editorialId: string;
|
||||||
|
albumId: string;
|
||||||
|
query: string;
|
||||||
|
page: string | undefined;
|
||||||
|
}) {
|
||||||
|
try {
|
||||||
|
const albums = await albumCatalog.getVisibleAlbums(editorialId);
|
||||||
|
const album = albums.find((candidate) => candidate.id === albumId);
|
||||||
|
if (!album) {
|
||||||
|
return { album: null, page: null, unavailable: false as const };
|
||||||
|
}
|
||||||
|
const results = await albumCatalog.searchVisiblePhotos(editorialId, {
|
||||||
|
requestedAlbumId: album.id,
|
||||||
|
description: query,
|
||||||
|
page,
|
||||||
|
});
|
||||||
|
const downloadOptions = await loadEditorialDownloadOptions(
|
||||||
|
editorialId,
|
||||||
|
results.items.map((asset) => asset.id),
|
||||||
|
);
|
||||||
|
return { album, page: results, downloadOptions, unavailable: false as const };
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof AlbumCatalogError && error.code === "IMMICH_UNAVAILABLE") {
|
||||||
|
return { album: null, page: null, unavailable: true as const };
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function singleValue(value: string | string[] | undefined): string | undefined {
|
||||||
|
return typeof value === "string" ? value : undefined;
|
||||||
|
}
|
||||||
|
|
||||||
|
function normalizedQuery(value: string | undefined): string {
|
||||||
|
return (value ?? "").replace(/\s+/g, " ").trim().slice(0, 200);
|
||||||
|
}
|
||||||
|
|
||||||
|
function ImmichUnavailable() {
|
||||||
|
return (
|
||||||
|
<section className="editorial-section editorial-state" aria-labelledby="album-title">
|
||||||
|
<p className="editorial-kicker">Bildarchiv</p>
|
||||||
|
<h1 id="album-title">Fotos momentan nicht erreichbar</h1>
|
||||||
|
<p role="status">Bitte laden Sie diese Seite in wenigen Minuten erneut.</p>
|
||||||
|
<Link className="quiet-link" href="/redaktion/alben">
|
||||||
|
Zurück zu den Alben
|
||||||
|
</Link>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
export default function AlbumsLoading() {
|
||||||
|
return (
|
||||||
|
<section className="editorial-section editorial-state" aria-busy="true" aria-live="polite">
|
||||||
|
<p className="editorial-kicker">Bildarchiv</p>
|
||||||
|
<p>Alben werden geladen.</p>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
import { AlbumCatalogError, albumCatalog } from "@/modules/albums/catalog";
|
||||||
|
import { AlbumContactSheet } from "@/modules/albums/catalog-content";
|
||||||
|
|
||||||
|
import { requireEditorial } from "../access";
|
||||||
|
|
||||||
|
export default async function AlbumsPage() {
|
||||||
|
const principal = await requireEditorial();
|
||||||
|
const result = await loadAlbums(principal.editorialId);
|
||||||
|
|
||||||
|
if (result.unavailable) {
|
||||||
|
return <ImmichUnavailable />;
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="editorial-section" aria-labelledby="albums-title">
|
||||||
|
<p className="editorial-kicker">Bildarchiv · Freigaben</p>
|
||||||
|
<div className="editorial-title-row">
|
||||||
|
<h1 id="albums-title">Ihre Alben</h1>
|
||||||
|
<p>Wählen Sie ein Spiel oder eine Serie, um die freigegebenen Fotos zu durchsuchen.</p>
|
||||||
|
</div>
|
||||||
|
{result.albums.length === 0 ? (
|
||||||
|
<p className="catalog-empty">Für Ihre Redaktion sind noch keine Fotoalben freigegeben.</p>
|
||||||
|
) : (
|
||||||
|
<AlbumContactSheet albums={result.albums} />
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadAlbums(editorialId: string) {
|
||||||
|
try {
|
||||||
|
return { albums: await albumCatalog.getVisibleAlbums(editorialId), unavailable: false as const };
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof AlbumCatalogError && error.code === "IMMICH_UNAVAILABLE") {
|
||||||
|
return { albums: [], unavailable: true as const };
|
||||||
|
}
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function ImmichUnavailable() {
|
||||||
|
return (
|
||||||
|
<section className="editorial-section editorial-state" aria-labelledby="albums-title">
|
||||||
|
<p className="editorial-kicker">Bildarchiv</p>
|
||||||
|
<h1 id="albums-title">Alben momentan nicht erreichbar</h1>
|
||||||
|
<p role="status">Bitte laden Sie diese Seite in wenigen Minuten erneut. Ihre Freigaben bleiben unverändert.</p>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import type { ReactNode } from "react";
|
||||||
|
|
||||||
|
import { PortalShell } from "@/components/layout/portal-shell";
|
||||||
|
|
||||||
|
import { requireEditorial } from "./access";
|
||||||
|
|
||||||
|
export default async function EditorialLayout({ children }: Readonly<{ children: ReactNode }>) {
|
||||||
|
await requireEditorial();
|
||||||
|
|
||||||
|
return <PortalShell>{children}</PortalShell>;
|
||||||
|
}
|
||||||
@@ -0,0 +1,212 @@
|
|||||||
|
// @vitest-environment jsdom
|
||||||
|
|
||||||
|
import { cleanup, render, screen } from "@testing-library/react";
|
||||||
|
import { afterEach, expect, test } from "vitest";
|
||||||
|
|
||||||
|
import { UsageHistoryContent } from "./usage-history-content";
|
||||||
|
|
||||||
|
afterEach(cleanup);
|
||||||
|
|
||||||
|
test("renders every terminal attempt with its immutable usage snapshot", () => {
|
||||||
|
render(
|
||||||
|
<UsageHistoryContent
|
||||||
|
history={{
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
usageId: "usage-1",
|
||||||
|
filename: "tor-des-monats.jpg",
|
||||||
|
albumName: "Heimspiel gegen Nord",
|
||||||
|
purpose: "Titelgeschichte",
|
||||||
|
reference: "Ausgabe 8/26",
|
||||||
|
createdAt: new Date("2026-08-09T10:00:00.000Z"),
|
||||||
|
billingStatus: "open",
|
||||||
|
priceCents: 1_500,
|
||||||
|
billableCents: 1_500,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
attempts: [
|
||||||
|
{
|
||||||
|
downloadId: "download-5",
|
||||||
|
usageId: "usage-1",
|
||||||
|
status: "authorized",
|
||||||
|
requestedAt: new Date("2026-08-10T13:00:00.000Z"),
|
||||||
|
transferredBytes: 0,
|
||||||
|
repeat: true,
|
||||||
|
billableCents: 0,
|
||||||
|
filename: "tor-des-monats.jpg",
|
||||||
|
albumName: "Heimspiel gegen Nord",
|
||||||
|
purpose: "Titelgeschichte",
|
||||||
|
reference: "Ausgabe 8/26",
|
||||||
|
priceCents: 1_500,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
downloadId: "download-4",
|
||||||
|
usageId: "usage-1",
|
||||||
|
status: "streaming",
|
||||||
|
requestedAt: new Date("2026-08-10T12:30:00.000Z"),
|
||||||
|
transferredBytes: 0,
|
||||||
|
repeat: true,
|
||||||
|
billableCents: 0,
|
||||||
|
filename: "tor-des-monats.jpg",
|
||||||
|
albumName: "Heimspiel gegen Nord",
|
||||||
|
purpose: "Titelgeschichte",
|
||||||
|
reference: "Ausgabe 8/26",
|
||||||
|
priceCents: 1_500,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
downloadId: "download-3",
|
||||||
|
usageId: "usage-1",
|
||||||
|
status: "failed_before_delivery",
|
||||||
|
requestedAt: new Date("2026-08-10T12:00:00.000Z"),
|
||||||
|
finishedAt: new Date("2026-08-10T12:00:01.000Z"),
|
||||||
|
transferredBytes: 0,
|
||||||
|
repeat: true,
|
||||||
|
billableCents: 0,
|
||||||
|
filename: "tor-des-monats.jpg",
|
||||||
|
albumName: "Heimspiel gegen Nord",
|
||||||
|
purpose: "Titelgeschichte",
|
||||||
|
reference: "Ausgabe 8/26",
|
||||||
|
priceCents: 1_500,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
downloadId: "download-2",
|
||||||
|
usageId: "usage-1",
|
||||||
|
status: "interrupted",
|
||||||
|
requestedAt: new Date("2026-08-10T11:00:00.000Z"),
|
||||||
|
finishedAt: new Date("2026-08-10T11:00:02.000Z"),
|
||||||
|
transferredBytes: 40,
|
||||||
|
repeat: true,
|
||||||
|
billableCents: 0,
|
||||||
|
filename: "tor-des-monats.jpg",
|
||||||
|
albumName: "Heimspiel gegen Nord",
|
||||||
|
purpose: "Titelgeschichte",
|
||||||
|
reference: "Ausgabe 8/26",
|
||||||
|
priceCents: 1_500,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
downloadId: "download-1",
|
||||||
|
usageId: "usage-1",
|
||||||
|
status: "completed",
|
||||||
|
requestedAt: new Date("2026-08-09T10:00:00.000Z"),
|
||||||
|
finishedAt: new Date("2026-08-09T10:00:03.000Z"),
|
||||||
|
transferredBytes: 100,
|
||||||
|
repeat: false,
|
||||||
|
billableCents: 1_500,
|
||||||
|
filename: "tor-des-monats.jpg",
|
||||||
|
albumName: "Heimspiel gegen Nord",
|
||||||
|
purpose: "Titelgeschichte",
|
||||||
|
reference: "Ausgabe 8/26",
|
||||||
|
priceCents: 1_500,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
page: 1,
|
||||||
|
pageSize: 20,
|
||||||
|
hasNext: true,
|
||||||
|
attemptPageSize: 25,
|
||||||
|
attemptCursor: "1786314600000.current",
|
||||||
|
nextAttemptCursor: "1786311000000.next",
|
||||||
|
}}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(screen.getByRole("heading", { name: /tor-des-monats\.jpg/i })).not.toBeNull();
|
||||||
|
expect(screen.getByText("Heimspiel gegen Nord")).not.toBeNull();
|
||||||
|
expect(screen.getByText("Titelgeschichte")).not.toBeNull();
|
||||||
|
expect(screen.getByText("Abgeschlossen")).not.toBeNull();
|
||||||
|
expect(screen.getByText("Unterbrochen")).not.toBeNull();
|
||||||
|
expect(screen.getByText("Vor Auslieferung fehlgeschlagen")).not.toBeNull();
|
||||||
|
expect(screen.getByText("Autorisiert")).not.toBeNull();
|
||||||
|
expect(screen.getByText("Wird ausgeliefert")).not.toBeNull();
|
||||||
|
expect(screen.getByRole("heading", { name: "Downloadversuche" })).not.toBeNull();
|
||||||
|
expect(screen.getAllByText(/Nutzungspreis\s+15,00\s*€/)).toHaveLength(5);
|
||||||
|
expect(screen.getAllByText(/15,00\s*€/)).toHaveLength(7);
|
||||||
|
expect(screen.getAllByText(/0,00\s*€/)).toHaveLength(4);
|
||||||
|
expect(screen.getByRole("link", { name: /nächste nutzungsseite/i }).getAttribute("href")).toBe(
|
||||||
|
"/redaktion/nutzungen?page=2",
|
||||||
|
);
|
||||||
|
expect(
|
||||||
|
screen.getByRole("link", { name: /neueste auslieferungen/i }).getAttribute("href"),
|
||||||
|
).toBe("/redaktion/nutzungen?page=1");
|
||||||
|
expect(
|
||||||
|
screen.getByRole("link", { name: /ältere auslieferungen/i }).getAttribute("href"),
|
||||||
|
).toBe(
|
||||||
|
"/redaktion/nutzungen?page=1&attemptCursor=1786311000000.next",
|
||||||
|
);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("renders a directional empty state", () => {
|
||||||
|
render(
|
||||||
|
<UsageHistoryContent
|
||||||
|
history={{
|
||||||
|
items: [],
|
||||||
|
attempts: [],
|
||||||
|
page: 1,
|
||||||
|
pageSize: 20,
|
||||||
|
hasNext: false,
|
||||||
|
attemptPageSize: 25,
|
||||||
|
}}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(screen.getByText(/noch keine nutzungen/i)).not.toBeNull();
|
||||||
|
expect(screen.getByRole("link", { name: /zu den alben/i })).not.toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("shows the usage-level price and billing status before any attempt is terminal", () => {
|
||||||
|
render(
|
||||||
|
<UsageHistoryContent
|
||||||
|
history={{
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
usageId: "usage-open",
|
||||||
|
filename: "noch-im-abruf.jpg",
|
||||||
|
albumName: "Pressebilder",
|
||||||
|
purpose: "Online-Meldung",
|
||||||
|
createdAt: new Date("2026-08-10T10:00:00.000Z"),
|
||||||
|
billingStatus: "open",
|
||||||
|
priceCents: 1_500,
|
||||||
|
billableCents: 1_500,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
attempts: [],
|
||||||
|
page: 1,
|
||||||
|
pageSize: 20,
|
||||||
|
hasNext: false,
|
||||||
|
attemptPageSize: 25,
|
||||||
|
}}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(screen.getByText("Abrechnungsstatus")).not.toBeNull();
|
||||||
|
expect(screen.getByText("Offen")).not.toBeNull();
|
||||||
|
expect(screen.getByText(/15,00\s*€/)).not.toBeNull();
|
||||||
|
});
|
||||||
|
|
||||||
|
test("keeps the immutable usage price visible when billing was voided", () => {
|
||||||
|
render(
|
||||||
|
<UsageHistoryContent
|
||||||
|
history={{
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
usageId: "usage-voided",
|
||||||
|
filename: "fehlgeschlagen.jpg",
|
||||||
|
albumName: "Pressebilder",
|
||||||
|
purpose: "Online-Meldung",
|
||||||
|
createdAt: new Date("2026-08-10T10:00:00.000Z"),
|
||||||
|
billingStatus: "voided",
|
||||||
|
priceCents: 1_500,
|
||||||
|
billableCents: 0,
|
||||||
|
},
|
||||||
|
],
|
||||||
|
attempts: [],
|
||||||
|
page: 1,
|
||||||
|
pageSize: 20,
|
||||||
|
hasNext: false,
|
||||||
|
attemptPageSize: 25,
|
||||||
|
}}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(screen.getByText("Storniert")).not.toBeNull();
|
||||||
|
expect(screen.getByText(/15,00\s*€/)).not.toBeNull();
|
||||||
|
});
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
import { listEditorialUsageHistory } from "@/modules/downloads/stream";
|
||||||
|
|
||||||
|
import { requireEditorial } from "../access";
|
||||||
|
import { UsageHistoryContent } from "./usage-history-content";
|
||||||
|
|
||||||
|
type UsageHistoryPageProps = Readonly<{
|
||||||
|
searchParams: Promise<{ page?: string | string[]; attemptCursor?: string | string[] }>;
|
||||||
|
}>;
|
||||||
|
|
||||||
|
export default async function UsagesPage({ searchParams }: UsageHistoryPageProps) {
|
||||||
|
const [principal, parameters] = await Promise.all([requireEditorial(), searchParams]);
|
||||||
|
const result = await loadHistory(
|
||||||
|
principal.editorialId,
|
||||||
|
singleValue(parameters.page),
|
||||||
|
singleValue(parameters.attemptCursor),
|
||||||
|
);
|
||||||
|
if (result.unavailable) return <HistoryUnavailable />;
|
||||||
|
return <UsageHistoryContent history={result.history} />;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function loadHistory(
|
||||||
|
editorialId: string,
|
||||||
|
page: string | undefined,
|
||||||
|
attemptCursor: string | undefined,
|
||||||
|
) {
|
||||||
|
try {
|
||||||
|
return {
|
||||||
|
history: await listEditorialUsageHistory(editorialId, page, attemptCursor),
|
||||||
|
unavailable: false as const,
|
||||||
|
};
|
||||||
|
} catch {
|
||||||
|
return { history: null, unavailable: true as const };
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function HistoryUnavailable() {
|
||||||
|
return (
|
||||||
|
<section className="editorial-section editorial-state" aria-labelledby="usage-history-title">
|
||||||
|
<p className="editorial-kicker">Abrechnung</p>
|
||||||
|
<h1 id="usage-history-title">Nutzungen momentan nicht erreichbar</h1>
|
||||||
|
<p role="status">Bitte laden Sie diese Seite in wenigen Minuten erneut.</p>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function singleValue(value: string | string[] | undefined): string | undefined {
|
||||||
|
return typeof value === "string" ? value : undefined;
|
||||||
|
}
|
||||||
@@ -0,0 +1,177 @@
|
|||||||
|
import Link from "next/link";
|
||||||
|
|
||||||
|
import { formatBerlinDateTime } from "@/modules/downloads/format";
|
||||||
|
import type { UsageHistoryAttempt, UsageHistoryPage } from "@/modules/downloads/stream";
|
||||||
|
|
||||||
|
const priceFormatter = new Intl.NumberFormat("de-DE", {
|
||||||
|
style: "currency",
|
||||||
|
currency: "EUR",
|
||||||
|
});
|
||||||
|
const byteFormatter = new Intl.NumberFormat("de-DE", {
|
||||||
|
style: "unit",
|
||||||
|
unit: "byte",
|
||||||
|
unitDisplay: "short",
|
||||||
|
maximumFractionDigits: 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
export function UsageHistoryContent({ history }: Readonly<{ history: UsageHistoryPage }>) {
|
||||||
|
return (
|
||||||
|
<section className="editorial-section usage-history" aria-labelledby="usage-history-title">
|
||||||
|
<p className="editorial-kicker">Abrechnung · Downloadprotokoll</p>
|
||||||
|
<div className="editorial-title-row">
|
||||||
|
<h1 id="usage-history-title">Ihre Nutzungen</h1>
|
||||||
|
<p>Verwendungszwecke, Kosten und Auslieferungsversuche Ihrer Redaktion.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{history.items.length === 0 ? (
|
||||||
|
<div className="usage-history-empty">
|
||||||
|
<p>Noch keine Nutzungen erfasst. Wählen Sie ein Foto aus einem freigegebenen Album.</p>
|
||||||
|
<Link className="quiet-link" href="/redaktion/alben">
|
||||||
|
Zu den Alben
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<ol className="usage-ledger">
|
||||||
|
{history.items.map((usage) => (
|
||||||
|
<li key={usage.usageId}>
|
||||||
|
<article className="usage-ledger-entry">
|
||||||
|
<header>
|
||||||
|
<p>{formatBerlinDateTime(usage.createdAt)}</p>
|
||||||
|
<h2>{usage.filename}</h2>
|
||||||
|
</header>
|
||||||
|
<dl className="usage-snapshot">
|
||||||
|
<div>
|
||||||
|
<dt>Album</dt>
|
||||||
|
<dd>{usage.albumName}</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt>Verwendungszweck</dt>
|
||||||
|
<dd>{usage.purpose}</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt>Nutzungspreis</dt>
|
||||||
|
<dd>{priceFormatter.format(usage.priceCents / 100)}</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt>Abrechnungsstatus</dt>
|
||||||
|
<dd>{billingStatusLabel(usage.billingStatus)}</dd>
|
||||||
|
</div>
|
||||||
|
{usage.reference ? (
|
||||||
|
<div>
|
||||||
|
<dt>Interne Referenz</dt>
|
||||||
|
<dd>{usage.reference}</dd>
|
||||||
|
</div>
|
||||||
|
) : null}
|
||||||
|
</dl>
|
||||||
|
</article>
|
||||||
|
</li>
|
||||||
|
))}
|
||||||
|
</ol>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<HistoryPagination history={history} />
|
||||||
|
|
||||||
|
<section className="usage-attempt-history" aria-labelledby="usage-attempt-title">
|
||||||
|
<h2 id="usage-attempt-title">Downloadversuche</h2>
|
||||||
|
{history.attempts.length === 0 ? (
|
||||||
|
<p className="usage-attempt-empty">Noch keine Downloadversuche erfasst.</p>
|
||||||
|
) : (
|
||||||
|
<ol className="usage-attempts" aria-label="Downloadversuche Ihrer Redaktion">
|
||||||
|
{history.attempts.map((attempt) => (
|
||||||
|
<AttemptRow attempt={attempt} key={attempt.downloadId} />
|
||||||
|
))}
|
||||||
|
</ol>
|
||||||
|
)}
|
||||||
|
</section>
|
||||||
|
<AttemptPagination history={history} />
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function AttemptRow({ attempt }: Readonly<{ attempt: UsageHistoryAttempt }>) {
|
||||||
|
const displayedAt = attempt.finishedAt ?? attempt.requestedAt;
|
||||||
|
return (
|
||||||
|
<li>
|
||||||
|
<time dateTime={displayedAt.toISOString()}>
|
||||||
|
{formatBerlinDateTime(displayedAt)}
|
||||||
|
</time>
|
||||||
|
<span className="usage-attempt-context">
|
||||||
|
<strong>{attempt.filename}</strong>
|
||||||
|
<small>
|
||||||
|
{attempt.albumName} · {attempt.purpose}
|
||||||
|
{attempt.reference ? ` · ${attempt.reference}` : ""}
|
||||||
|
</small>
|
||||||
|
</span>
|
||||||
|
<strong>{statusLabel(attempt.status)}</strong>
|
||||||
|
<span>
|
||||||
|
{attempt.repeat ? "Wiederholter Abruf" : "Neue Nutzung"} ·{" "}
|
||||||
|
{byteFormatter.format(attempt.transferredBytes)}
|
||||||
|
</span>
|
||||||
|
<span className="usage-attempt-price">
|
||||||
|
<b>{priceFormatter.format(attempt.billableCents / 100)}</b>
|
||||||
|
<small>Nutzungspreis {priceFormatter.format(attempt.priceCents / 100)}</small>
|
||||||
|
</span>
|
||||||
|
</li>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function HistoryPagination({ history }: Readonly<{ history: UsageHistoryPage }>) {
|
||||||
|
if (history.page === 1 && !history.hasNext) return null;
|
||||||
|
return (
|
||||||
|
<nav aria-label="Seiten der Nutzungshistorie" className="photo-pagination">
|
||||||
|
{history.page > 1 ? (
|
||||||
|
<Link href={`/redaktion/nutzungen?page=${history.page - 1}`}>
|
||||||
|
Vorherige Nutzungsseite
|
||||||
|
</Link>
|
||||||
|
) : (
|
||||||
|
<span />
|
||||||
|
)}
|
||||||
|
{history.hasNext ? (
|
||||||
|
<Link href={`/redaktion/nutzungen?page=${history.page + 1}`}>
|
||||||
|
Nächste Nutzungsseite
|
||||||
|
</Link>
|
||||||
|
) : null}
|
||||||
|
</nav>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function AttemptPagination({ history }: Readonly<{ history: UsageHistoryPage }>) {
|
||||||
|
if (!history.attemptCursor && !history.nextAttemptCursor) return null;
|
||||||
|
return (
|
||||||
|
<nav aria-label="Seiten der Auslieferungsversuche" className="photo-pagination">
|
||||||
|
{history.attemptCursor ? (
|
||||||
|
<Link href={`/redaktion/nutzungen?page=${history.page}`}>Neueste Auslieferungen</Link>
|
||||||
|
) : (
|
||||||
|
<span />
|
||||||
|
)}
|
||||||
|
{history.nextAttemptCursor ? (
|
||||||
|
<Link
|
||||||
|
href={`/redaktion/nutzungen?page=${history.page}&attemptCursor=${encodeURIComponent(history.nextAttemptCursor)}`}
|
||||||
|
>
|
||||||
|
Ältere Auslieferungen
|
||||||
|
</Link>
|
||||||
|
) : null}
|
||||||
|
</nav>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function statusLabel(status: UsageHistoryAttempt["status"]): string {
|
||||||
|
const labels: Record<UsageHistoryAttempt["status"], string> = {
|
||||||
|
authorized: "Autorisiert",
|
||||||
|
streaming: "Wird ausgeliefert",
|
||||||
|
completed: "Abgeschlossen",
|
||||||
|
interrupted: "Unterbrochen",
|
||||||
|
failed_before_delivery: "Vor Auslieferung fehlgeschlagen",
|
||||||
|
};
|
||||||
|
return labels[status];
|
||||||
|
}
|
||||||
|
|
||||||
|
function billingStatusLabel(status: UsageHistoryPage["items"][number]["billingStatus"]): string {
|
||||||
|
const labels: Record<UsageHistoryPage["items"][number]["billingStatus"], string> = {
|
||||||
|
open: "Offen",
|
||||||
|
billed: "Abgerechnet",
|
||||||
|
reopened: "Wieder geöffnet",
|
||||||
|
voided: "Storniert",
|
||||||
|
};
|
||||||
|
return labels[status];
|
||||||
|
}
|
||||||
@@ -0,0 +1,59 @@
|
|||||||
|
import { eq } from "drizzle-orm";
|
||||||
|
|
||||||
|
import { db } from "@/db/client";
|
||||||
|
import { billingAddressVersions, editorialAccounts } from "@/db/schema";
|
||||||
|
|
||||||
|
import { requireEditorial } from "../access";
|
||||||
|
|
||||||
|
export default async function EditorialProfilePage() {
|
||||||
|
const principal = await requireEditorial();
|
||||||
|
const [editorial] = await db
|
||||||
|
.select({
|
||||||
|
name: editorialAccounts.name,
|
||||||
|
contactName: editorialAccounts.contactName,
|
||||||
|
loginEmail: editorialAccounts.loginEmail,
|
||||||
|
addressLine1: billingAddressVersions.addressLine1,
|
||||||
|
addressLine2: billingAddressVersions.addressLine2,
|
||||||
|
postalCode: billingAddressVersions.postalCode,
|
||||||
|
city: billingAddressVersions.city,
|
||||||
|
countryCode: billingAddressVersions.countryCode,
|
||||||
|
})
|
||||||
|
.from(editorialAccounts)
|
||||||
|
.leftJoin(
|
||||||
|
billingAddressVersions,
|
||||||
|
eq(editorialAccounts.currentBillingAddressVersionId, billingAddressVersions.id),
|
||||||
|
)
|
||||||
|
.where(eq(editorialAccounts.id, principal.editorialId))
|
||||||
|
.limit(1);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<section className="editorial-section" aria-labelledby="profile-title">
|
||||||
|
<p className="eyebrow">Redaktionskonto</p>
|
||||||
|
<h1 id="profile-title">Profil</h1>
|
||||||
|
<dl>
|
||||||
|
<dt>Redaktion</dt>
|
||||||
|
<dd>{editorial?.name}</dd>
|
||||||
|
<dt>Ansprechperson</dt>
|
||||||
|
<dd>{editorial?.contactName}</dd>
|
||||||
|
<dt>Anmelde-E-Mail</dt>
|
||||||
|
<dd>{editorial?.loginEmail}</dd>
|
||||||
|
<dt>Rechnungsadresse</dt>
|
||||||
|
<dd>
|
||||||
|
{editorial?.addressLine1 ? (
|
||||||
|
<address>
|
||||||
|
{editorial.addressLine1}
|
||||||
|
{editorial.addressLine2 ? <br /> : null}
|
||||||
|
{editorial.addressLine2}
|
||||||
|
<br />
|
||||||
|
{editorial.postalCode} {editorial.city}
|
||||||
|
<br />
|
||||||
|
{editorial.countryCode}
|
||||||
|
</address>
|
||||||
|
) : (
|
||||||
|
"Keine Rechnungsadresse hinterlegt."
|
||||||
|
)}
|
||||||
|
</dd>
|
||||||
|
</dl>
|
||||||
|
</section>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
// @vitest-environment jsdom
|
||||||
|
|
||||||
|
import { readFileSync } from "node:fs";
|
||||||
|
|
||||||
|
import { render, screen } from "@testing-library/react";
|
||||||
|
import { expect, test } from "vitest";
|
||||||
|
|
||||||
|
import { PortalShell } from "@/components/layout/portal-shell";
|
||||||
|
import { BrandLogo } from "./logo";
|
||||||
|
|
||||||
|
test("uses each supplied logo's true intrinsic dimensions", () => {
|
||||||
|
const { rerender } = render(<BrandLogo variant="white" />);
|
||||||
|
const logo = screen.getByAltText("Leon Tonhäuser Sportfotografie");
|
||||||
|
expect(logo.getAttribute("width")).toBe("250");
|
||||||
|
expect(logo.getAttribute("height")).toBe("250");
|
||||||
|
|
||||||
|
rerender(<BrandLogo variant="black" />);
|
||||||
|
expect(logo.getAttribute("width")).toBe("1000");
|
||||||
|
expect(logo.getAttribute("height")).toBe("1000");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("keeps masthead controls keyboard-focusable with a paper-coloured focus outline", () => {
|
||||||
|
render(
|
||||||
|
<PortalShell>
|
||||||
|
<p>Archiv</p>
|
||||||
|
</PortalShell>,
|
||||||
|
);
|
||||||
|
|
||||||
|
expect(screen.getByRole("link", { name: /zur albenübersicht/i }).tagName).toBe("A");
|
||||||
|
expect(screen.getByRole("link", { name: "Alben" }).tagName).toBe("A");
|
||||||
|
const styles = readFileSync("src/app/globals.css", "utf8");
|
||||||
|
expect(styles).toContain(".portal-masthead :focus-visible");
|
||||||
|
expect(styles).toContain("outline-color: var(--paper)");
|
||||||
|
});
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
/* eslint-disable @next/next/no-img-element */
|
||||||
|
|
||||||
|
type BrandLogoProps = {
|
||||||
|
variant: "black" | "white";
|
||||||
|
};
|
||||||
|
|
||||||
|
export function BrandLogo({ variant }: Readonly<BrandLogoProps>) {
|
||||||
|
const logo =
|
||||||
|
variant === "white"
|
||||||
|
? { source: "/brand/logo-white.png", width: 250, height: 250 }
|
||||||
|
: { source: "/brand/logo-black.png", width: 1000, height: 1000 };
|
||||||
|
|
||||||
|
return (
|
||||||
|
<img
|
||||||
|
alt="Leon Tonhäuser Sportfotografie"
|
||||||
|
className="brand-logo"
|
||||||
|
height={logo.height}
|
||||||
|
src={logo.source}
|
||||||
|
width={logo.width}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,137 @@
|
|||||||
|
// @vitest-environment jsdom
|
||||||
|
|
||||||
|
import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
|
||||||
|
import { afterEach, beforeEach, expect, test, vi } from "vitest";
|
||||||
|
|
||||||
|
import { UsageDialog } from "./usage-dialog";
|
||||||
|
|
||||||
|
const idempotencyKey = "55555555-5555-4555-8555-555555555555";
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
Object.defineProperty(HTMLDialogElement.prototype, "showModal", {
|
||||||
|
configurable: true,
|
||||||
|
value() {
|
||||||
|
this.setAttribute("open", "");
|
||||||
|
},
|
||||||
|
});
|
||||||
|
Object.defineProperty(HTMLDialogElement.prototype, "close", {
|
||||||
|
configurable: true,
|
||||||
|
value() {
|
||||||
|
this.removeAttribute("open");
|
||||||
|
this.dispatchEvent(new Event("close"));
|
||||||
|
},
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
cleanup();
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
vi.unstubAllGlobals();
|
||||||
|
});
|
||||||
|
|
||||||
|
function renderDialog() {
|
||||||
|
return render(
|
||||||
|
<UsageDialog
|
||||||
|
albumId="33333333-3333-4333-8333-333333333333"
|
||||||
|
assetId="22222222-2222-4222-8222-222222222222"
|
||||||
|
filename="tor-des-monats.jpg"
|
||||||
|
newUsagePriceCents={1_500}
|
||||||
|
priorUsages={[
|
||||||
|
{
|
||||||
|
id: "44444444-4444-4444-8444-444444444444",
|
||||||
|
purpose: "Online-Nachbericht",
|
||||||
|
createdAt: "2026-08-09T10:00:00.000Z",
|
||||||
|
},
|
||||||
|
]}
|
||||||
|
/>,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
test("offers an existing free use and a new server-priced use with required purpose", () => {
|
||||||
|
renderDialog();
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: /original laden/i }));
|
||||||
|
|
||||||
|
expect(screen.getByRole("dialog", { name: /nutzung auswählen/i })).not.toBeNull();
|
||||||
|
expect(
|
||||||
|
(screen.getByRole("radio", {
|
||||||
|
name: /online-nachbericht.*0,00\s*€/i,
|
||||||
|
}) as HTMLInputElement).checked,
|
||||||
|
).toBe(true);
|
||||||
|
expect(
|
||||||
|
(screen.getByRole("radio", { name: /neue nutzung.*15,00\s*€/i }) as HTMLInputElement)
|
||||||
|
.checked,
|
||||||
|
).toBe(false);
|
||||||
|
expect(
|
||||||
|
(screen.getByRole("textbox", { name: /^verwendungszweck$/i }) as HTMLTextAreaElement)
|
||||||
|
.disabled,
|
||||||
|
).toBe(true);
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole("radio", { name: /neue nutzung/i }));
|
||||||
|
expect(
|
||||||
|
(screen.getByRole("textbox", { name: /^verwendungszweck$/i }) as HTMLTextAreaElement)
|
||||||
|
.required,
|
||||||
|
).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("reuses one idempotency key when the same failed submission is retried", async () => {
|
||||||
|
const randomUUID = vi.spyOn(globalThis.crypto, "randomUUID").mockReturnValue(idempotencyKey);
|
||||||
|
const fetch = vi
|
||||||
|
.fn()
|
||||||
|
.mockResolvedValueOnce(new Response(null, { status: 503 }))
|
||||||
|
.mockResolvedValueOnce(
|
||||||
|
Response.json({
|
||||||
|
downloadId: "66666666-6666-4666-8666-666666666666",
|
||||||
|
fileUrl: "/api/downloads/66666666-6666-4666-8666-666666666666/file",
|
||||||
|
priceCents: 1_500,
|
||||||
|
billable: true,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
vi.stubGlobal("fetch", fetch);
|
||||||
|
const anchorClick = vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {});
|
||||||
|
renderDialog();
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: /original laden/i }));
|
||||||
|
fireEvent.click(screen.getByRole("radio", { name: /neue nutzung/i }));
|
||||||
|
fireEvent.change(screen.getByRole("textbox", { name: /^verwendungszweck$/i }), {
|
||||||
|
target: { value: "Titelgeschichte" },
|
||||||
|
});
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: /download anfordern/i }));
|
||||||
|
await screen.findByRole("alert");
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: /download erneut anfordern/i }));
|
||||||
|
|
||||||
|
await waitFor(() => expect(anchorClick).toHaveBeenCalledOnce());
|
||||||
|
expect(randomUUID).toHaveBeenCalledOnce();
|
||||||
|
expect(fetch).toHaveBeenCalledTimes(2);
|
||||||
|
for (const [, init] of fetch.mock.calls) {
|
||||||
|
expect(JSON.parse(String(init?.body))).toMatchObject({ idempotencyKey });
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
test("suppresses double-click submission while one request is pending", async () => {
|
||||||
|
vi.spyOn(globalThis.crypto, "randomUUID").mockReturnValue(idempotencyKey);
|
||||||
|
let resolveRequest: ((response: Response) => void) | undefined;
|
||||||
|
const fetch = vi.fn().mockReturnValue(
|
||||||
|
new Promise<Response>((resolve) => {
|
||||||
|
resolveRequest = resolve;
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
vi.stubGlobal("fetch", fetch);
|
||||||
|
vi.spyOn(HTMLAnchorElement.prototype, "click").mockImplementation(() => {});
|
||||||
|
renderDialog();
|
||||||
|
fireEvent.click(screen.getByRole("button", { name: /original laden/i }));
|
||||||
|
const submit = screen.getByRole("button", { name: /download anfordern/i });
|
||||||
|
|
||||||
|
fireEvent.click(submit);
|
||||||
|
fireEvent.click(submit);
|
||||||
|
|
||||||
|
expect(fetch).toHaveBeenCalledOnce();
|
||||||
|
resolveRequest?.(
|
||||||
|
Response.json({
|
||||||
|
downloadId: "66666666-6666-4666-8666-666666666666",
|
||||||
|
fileUrl: "/api/downloads/66666666-6666-4666-8666-666666666666/file",
|
||||||
|
priceCents: 0,
|
||||||
|
billable: false,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
await waitFor(() => expect((submit as HTMLButtonElement).disabled).toBe(false));
|
||||||
|
});
|
||||||
@@ -0,0 +1,222 @@
|
|||||||
|
"use client";
|
||||||
|
|
||||||
|
import { useRef, useState, type FormEvent } from "react";
|
||||||
|
|
||||||
|
import { formatBerlinDate } from "@/modules/downloads/format";
|
||||||
|
import type { DownloadDialogUsage } from "@/modules/downloads/stream";
|
||||||
|
|
||||||
|
type UsageDialogProps = Readonly<{
|
||||||
|
albumId: string;
|
||||||
|
assetId: string;
|
||||||
|
filename: string;
|
||||||
|
newUsagePriceCents: number;
|
||||||
|
priorUsages: DownloadDialogUsage[];
|
||||||
|
}>;
|
||||||
|
|
||||||
|
type IntentResponse = {
|
||||||
|
downloadId: string;
|
||||||
|
fileUrl: string;
|
||||||
|
priceCents: number;
|
||||||
|
billable: boolean;
|
||||||
|
};
|
||||||
|
|
||||||
|
const priceFormatter = new Intl.NumberFormat("de-DE", {
|
||||||
|
style: "currency",
|
||||||
|
currency: "EUR",
|
||||||
|
});
|
||||||
|
|
||||||
|
export function UsageDialog({
|
||||||
|
albumId,
|
||||||
|
assetId,
|
||||||
|
filename,
|
||||||
|
newUsagePriceCents,
|
||||||
|
priorUsages,
|
||||||
|
}: UsageDialogProps) {
|
||||||
|
const dialogRef = useRef<HTMLDialogElement>(null);
|
||||||
|
const firstChoiceRef = useRef<HTMLInputElement>(null);
|
||||||
|
const idempotencyKeyRef = useRef<string | null>(null);
|
||||||
|
const initialChoice = priorUsages[0] ? `repeat:${priorUsages[0].id}` : "new_usage";
|
||||||
|
const [choice, setChoice] = useState(initialChoice);
|
||||||
|
const [purpose, setPurpose] = useState("");
|
||||||
|
const [pending, setPending] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
function openDialog() {
|
||||||
|
setChoice(initialChoice);
|
||||||
|
setPurpose("");
|
||||||
|
setPending(false);
|
||||||
|
setError(null);
|
||||||
|
idempotencyKeyRef.current = null;
|
||||||
|
dialogRef.current?.showModal();
|
||||||
|
requestAnimationFrame(() => firstChoiceRef.current?.focus());
|
||||||
|
}
|
||||||
|
|
||||||
|
function closeDialog() {
|
||||||
|
if (!pending) dialogRef.current?.close();
|
||||||
|
}
|
||||||
|
|
||||||
|
function resetSubmission() {
|
||||||
|
idempotencyKeyRef.current = null;
|
||||||
|
setError(null);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function submit(event: FormEvent<HTMLFormElement>) {
|
||||||
|
event.preventDefault();
|
||||||
|
if (pending) return;
|
||||||
|
setPending(true);
|
||||||
|
setError(null);
|
||||||
|
idempotencyKeyRef.current ??= crypto.randomUUID();
|
||||||
|
|
||||||
|
const payload = choice.startsWith("repeat:")
|
||||||
|
? {
|
||||||
|
kind: "repeat_download" as const,
|
||||||
|
usageId: choice.slice("repeat:".length),
|
||||||
|
idempotencyKey: idempotencyKeyRef.current,
|
||||||
|
}
|
||||||
|
: {
|
||||||
|
kind: "new_usage" as const,
|
||||||
|
assetId,
|
||||||
|
albumId,
|
||||||
|
purpose,
|
||||||
|
idempotencyKey: idempotencyKeyRef.current,
|
||||||
|
};
|
||||||
|
|
||||||
|
try {
|
||||||
|
const response = await fetch("/api/download-intents", {
|
||||||
|
method: "POST",
|
||||||
|
headers: { "content-type": "application/json" },
|
||||||
|
body: JSON.stringify(payload),
|
||||||
|
});
|
||||||
|
if (!response.ok) throw new Error("intent failed");
|
||||||
|
const intent = (await response.json()) as IntentResponse;
|
||||||
|
if (!isLocalDownloadUrl(intent.fileUrl, intent.downloadId)) {
|
||||||
|
throw new Error("invalid download url");
|
||||||
|
}
|
||||||
|
const link = document.createElement("a");
|
||||||
|
link.href = intent.fileUrl;
|
||||||
|
link.download = filename;
|
||||||
|
link.click();
|
||||||
|
dialogRef.current?.close();
|
||||||
|
idempotencyKeyRef.current = null;
|
||||||
|
} catch {
|
||||||
|
setError(
|
||||||
|
"Der Download konnte nicht vorbereitet werden. Versuchen Sie dieselbe Anfrage erneut.",
|
||||||
|
);
|
||||||
|
} finally {
|
||||||
|
setPending(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const isNewUsage = choice === "new_usage";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<>
|
||||||
|
<button className="download-trigger" onClick={openDialog} type="button">
|
||||||
|
Original laden
|
||||||
|
</button>
|
||||||
|
<dialog
|
||||||
|
aria-labelledby={`usage-dialog-title-${assetId}`}
|
||||||
|
className="usage-dialog"
|
||||||
|
onCancel={(event) => {
|
||||||
|
if (pending) event.preventDefault();
|
||||||
|
}}
|
||||||
|
onClose={() => {
|
||||||
|
setError(null);
|
||||||
|
idempotencyKeyRef.current = null;
|
||||||
|
}}
|
||||||
|
ref={dialogRef}
|
||||||
|
>
|
||||||
|
<form onSubmit={submit}>
|
||||||
|
<div className="usage-dialog-heading">
|
||||||
|
<p className="editorial-kicker">Download · {filename}</p>
|
||||||
|
<h2 id={`usage-dialog-title-${assetId}`}>Nutzung auswählen</h2>
|
||||||
|
<p>Ordnen Sie das Original einer bestehenden oder einer neuen Nutzung zu.</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<fieldset className="usage-options" disabled={pending}>
|
||||||
|
<legend>Abrechnung</legend>
|
||||||
|
{priorUsages.map((usage, index) => (
|
||||||
|
<label className="usage-option" key={usage.id}>
|
||||||
|
<input
|
||||||
|
checked={choice === `repeat:${usage.id}`}
|
||||||
|
name={`usage-${assetId}`}
|
||||||
|
onChange={() => {
|
||||||
|
setChoice(`repeat:${usage.id}`);
|
||||||
|
resetSubmission();
|
||||||
|
}}
|
||||||
|
ref={index === 0 ? firstChoiceRef : undefined}
|
||||||
|
type="radio"
|
||||||
|
value={`repeat:${usage.id}`}
|
||||||
|
/>
|
||||||
|
<span>
|
||||||
|
<strong>{usage.purpose}</strong>
|
||||||
|
<small>Bestehende Nutzung · {formatDate(usage.createdAt)}</small>
|
||||||
|
</span>
|
||||||
|
<b>{priceFormatter.format(0)}</b>
|
||||||
|
</label>
|
||||||
|
))}
|
||||||
|
<label className="usage-option">
|
||||||
|
<input
|
||||||
|
checked={isNewUsage}
|
||||||
|
name={`usage-${assetId}`}
|
||||||
|
onChange={() => {
|
||||||
|
setChoice("new_usage");
|
||||||
|
resetSubmission();
|
||||||
|
}}
|
||||||
|
ref={priorUsages.length === 0 ? firstChoiceRef : undefined}
|
||||||
|
type="radio"
|
||||||
|
value="new_usage"
|
||||||
|
/>
|
||||||
|
<span>
|
||||||
|
<strong>Neue Nutzung</strong>
|
||||||
|
<small>Neue Veröffentlichung oder neuer Verwendungszweck</small>
|
||||||
|
</span>
|
||||||
|
<b>{priceFormatter.format(newUsagePriceCents / 100)}</b>
|
||||||
|
</label>
|
||||||
|
</fieldset>
|
||||||
|
|
||||||
|
<label className="usage-purpose" htmlFor={`usage-purpose-${assetId}`}>
|
||||||
|
Verwendungszweck
|
||||||
|
<textarea
|
||||||
|
disabled={!isNewUsage || pending}
|
||||||
|
id={`usage-purpose-${assetId}`}
|
||||||
|
maxLength={200}
|
||||||
|
minLength={3}
|
||||||
|
onChange={(event) => {
|
||||||
|
setPurpose(event.target.value);
|
||||||
|
resetSubmission();
|
||||||
|
}}
|
||||||
|
required={isNewUsage}
|
||||||
|
rows={3}
|
||||||
|
value={purpose}
|
||||||
|
/>
|
||||||
|
</label>
|
||||||
|
|
||||||
|
{error ? <p role="alert">{error}</p> : null}
|
||||||
|
|
||||||
|
<div className="usage-dialog-actions">
|
||||||
|
<button disabled={pending} onClick={closeDialog} type="button">
|
||||||
|
Abbrechen
|
||||||
|
</button>
|
||||||
|
<button className="download-confirm" disabled={pending} type="submit">
|
||||||
|
{pending
|
||||||
|
? "Download wird vorbereitet …"
|
||||||
|
: error
|
||||||
|
? "Download erneut anfordern"
|
||||||
|
: "Download anfordern"}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</dialog>
|
||||||
|
</>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatDate(value: string): string {
|
||||||
|
const date = new Date(value);
|
||||||
|
return Number.isNaN(date.valueOf()) ? "Datum unbekannt" : formatBerlinDate(date);
|
||||||
|
}
|
||||||
|
|
||||||
|
function isLocalDownloadUrl(fileUrl: string, downloadId: string): boolean {
|
||||||
|
return fileUrl === `/api/downloads/${encodeURIComponent(downloadId)}/file`;
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import { env } from "@/config/env";
|
||||||
|
|
||||||
|
export function LegalFooter() {
|
||||||
|
return (
|
||||||
|
<footer className="legal-footer" aria-label="Rechtliche Hinweise">
|
||||||
|
<a href={env.LEGAL_IMPRINT_URL} rel="noreferrer noopener" target="_blank">
|
||||||
|
Impressum
|
||||||
|
</a>
|
||||||
|
<a href={env.LEGAL_PRIVACY_URL} rel="noreferrer noopener" target="_blank">
|
||||||
|
Datenschutz
|
||||||
|
</a>
|
||||||
|
<a href={env.LEGAL_TERMS_URL} rel="noreferrer noopener" target="_blank">
|
||||||
|
Nutzungs- und Lizenzbedingungen
|
||||||
|
</a>
|
||||||
|
</footer>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,26 @@
|
|||||||
|
import type { ReactNode } from "react";
|
||||||
|
|
||||||
|
import Link from "next/link";
|
||||||
|
|
||||||
|
import { BrandLogo } from "@/components/brand/logo";
|
||||||
|
|
||||||
|
export function PortalShell({ children }: Readonly<{ children: ReactNode }>) {
|
||||||
|
return (
|
||||||
|
<div className="editorial-shell">
|
||||||
|
<header className="portal-masthead">
|
||||||
|
<Link aria-label="Zur Albenübersicht" className="portal-brand" href="/redaktion/alben">
|
||||||
|
<BrandLogo variant="white" />
|
||||||
|
</Link>
|
||||||
|
<div className="portal-masthead-meta">
|
||||||
|
<span>Redaktionsarchiv</span>
|
||||||
|
<nav aria-label="Redaktion">
|
||||||
|
<Link href="/redaktion/alben">Alben</Link>
|
||||||
|
<Link href="/redaktion/nutzungen">Nutzungen</Link>
|
||||||
|
<Link href="/redaktion/profil">Profil</Link>
|
||||||
|
</nav>
|
||||||
|
</div>
|
||||||
|
</header>
|
||||||
|
<main className="editorial-work-surface">{children}</main>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
import { describe, expect, test } from "vitest";
|
||||||
|
import { parseServerEnv } from "./env";
|
||||||
|
|
||||||
|
describe("parseServerEnv", () => {
|
||||||
|
test("rejects a missing Immich API key", () => {
|
||||||
|
expect(() => parseServerEnv({ DATABASE_URL: "postgres://db/app" })).toThrow(
|
||||||
|
/IMMICH_API_KEY/,
|
||||||
|
);
|
||||||
|
});
|
||||||
|
});
|
||||||
Loaded 100 of 185 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user