diff --git a/.gitignore b/.gitignore index 22240e2..cf77c83 100644 --- a/.gitignore +++ b/.gitignore @@ -9,3 +9,4 @@ node_modules/ dist/ coverage/ *.tsbuildinfo +.DS_Store diff --git a/.superpowers/sdd/2026-08-08-immich-redaktionsportal/task-9-report.md b/.superpowers/sdd/2026-08-08-immich-redaktionsportal/task-9-report.md index bd82fe7..594955b 100644 --- a/.superpowers/sdd/2026-08-08-immich-redaktionsportal/task-9-report.md +++ b/.superpowers/sdd/2026-08-08-immich-redaktionsportal/task-9-report.md @@ -122,3 +122,56 @@ ### 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. diff --git a/drizzle/0004_download_history_indexes.sql b/drizzle/0004_download_history_indexes.sql new file mode 100644 index 0000000..1da6363 --- /dev/null +++ b/drizzle/0004_download_history_indexes.sql @@ -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); \ No newline at end of file diff --git a/drizzle/meta/0004_snapshot.json b/drizzle/meta/0004_snapshot.json new file mode 100644 index 0000000..823c4e3 --- /dev/null +++ b/drizzle/meta/0004_snapshot.json @@ -0,0 +1,1579 @@ +{ + "id": "eda12e22-d840-49eb-a940-75cc95f41803", + "prevId": "090a698a-550f-4283-8632-f9c3d22d236d", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.album_grants": { + "name": "album_grants", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "editorial_account_id": { + "name": "editorial_account_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "immich_album_id": { + "name": "immich_album_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "granted_at": { + "name": "granted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "granted_by_user_id": { + "name": "granted_by_user_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "album_grants_editorial_account_id_idx": { + "name": "album_grants_editorial_account_id_idx", + "columns": [ + { + "expression": "editorial_account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "album_grants_immich_album_id_idx": { + "name": "album_grants_immich_album_id_idx", + "columns": [ + { + "expression": "immich_album_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "album_grants_editorial_active_album_unique": { + "name": "album_grants_editorial_active_album_unique", + "columns": [ + { + "expression": "editorial_account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"immich_album_id\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"album_grants\".\"revoked_at\" is null", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "album_grants_editorial_account_id_editorial_accounts_id_fk": { + "name": "album_grants_editorial_account_id_editorial_accounts_id_fk", + "tableFrom": "album_grants", + "tableTo": "editorial_accounts", + "columnsFrom": [ + "editorial_account_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "album_grants_granted_by_user_id_user_id_fk": { + "name": "album_grants_granted_by_user_id_user_id_fk", + "tableFrom": "album_grants", + "tableTo": "user", + "columnsFrom": [ + "granted_by_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "album_grants_immich_album_id_uuid_check": { + "name": "album_grants_immich_album_id_uuid_check", + "value": "\"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}$'" + } + }, + "isRLSEnabled": false + }, + "public.audit_events": { + "name": "audit_events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "event_type": { + "name": "event_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "actor_user_id": { + "name": "actor_user_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "actor_type": { + "name": "actor_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'system'" + }, + "entity_type": { + "name": "entity_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entity_id": { + "name": "entity_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "previous_values": { + "name": "previous_values", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "new_values": { + "name": "new_values", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "occurred_at": { + "name": "occurred_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "request_id": { + "name": "request_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "audit_events_actor_user_id_user_id_fk": { + "name": "audit_events_actor_user_id_user_id_fk", + "tableFrom": "audit_events", + "tableTo": "user", + "columnsFrom": [ + "actor_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.account": { + "name": "account", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "account_id": { + "name": "account_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "provider_id": { + "name": "provider_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "access_token": { + "name": "access_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "refresh_token": { + "name": "refresh_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "id_token": { + "name": "id_token", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "access_token_expires_at": { + "name": "access_token_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "refresh_token_expires_at": { + "name": "refresh_token_expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "scope": { + "name": "scope", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "password": { + "name": "password", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "account_user_id_user_id_fk": { + "name": "account_user_id_user_id_fk", + "tableFrom": "account", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.session": { + "name": "session", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "token": { + "name": "token", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "ip_address": { + "name": "ip_address", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_agent": { + "name": "user_agent", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "session_user_id_user_id_fk": { + "name": "session_user_id_user_id_fk", + "tableFrom": "session", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "session_token_unique": { + "name": "session_token_unique", + "nullsNotDistinct": false, + "columns": [ + "token" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.user": { + "name": "user", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email_verified": { + "name": "email_verified", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "image": { + "name": "image", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "role": { + "name": "role", + "type": "portal_role", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'EDITORIAL'" + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "user_email_unique": { + "name": "user_email_unique", + "nullsNotDistinct": false, + "columns": [ + "email" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.verification": { + "name": "verification", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "identifier": { + "name": "identifier", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.billing_report_items": { + "name": "billing_report_items", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "billing_report_id": { + "name": "billing_report_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "usage_id": { + "name": "usage_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "immich_asset_id_snapshot": { + "name": "immich_asset_id_snapshot", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "filename_snapshot": { + "name": "filename_snapshot", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "album_name_snapshot": { + "name": "album_name_snapshot", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "purpose_snapshot": { + "name": "purpose_snapshot", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "internal_reference_snapshot": { + "name": "internal_reference_snapshot", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "price_cents": { + "name": "price_cents", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "billing_report_items_report_usage_unique": { + "name": "billing_report_items_report_usage_unique", + "columns": [ + { + "expression": "billing_report_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "usage_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "billing_report_items_billing_report_id_billing_reports_id_fk": { + "name": "billing_report_items_billing_report_id_billing_reports_id_fk", + "tableFrom": "billing_report_items", + "tableTo": "billing_reports", + "columnsFrom": [ + "billing_report_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "billing_report_items_usage_id_usages_id_fk": { + "name": "billing_report_items_usage_id_usages_id_fk", + "tableFrom": "billing_report_items", + "tableTo": "usages", + "columnsFrom": [ + "usage_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.billing_reports": { + "name": "billing_reports", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "report_number": { + "name": "report_number", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "editorial_account_id": { + "name": "editorial_account_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "period_starts_at": { + "name": "period_starts_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "period_ends_at": { + "name": "period_ends_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "billing_address_snapshot": { + "name": "billing_address_snapshot", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "invoice_number": { + "name": "invoice_number", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "net_total_cents": { + "name": "net_total_cents", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "report_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'draft'" + }, + "pdf": { + "name": "pdf", + "type": "bytea", + "primaryKey": false, + "notNull": false + }, + "pdf_sha256": { + "name": "pdf_sha256", + "type": "varchar(64)", + "primaryKey": false, + "notNull": false + }, + "created_by_user_id": { + "name": "created_by_user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "finalized_at": { + "name": "finalized_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "cancelled_at": { + "name": "cancelled_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "cancellation_reason": { + "name": "cancellation_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "cancelled_by_user_id": { + "name": "cancelled_by_user_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "billing_reports_report_number_unique": { + "name": "billing_reports_report_number_unique", + "columns": [ + { + "expression": "report_number", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "billing_reports_invoice_number_unique": { + "name": "billing_reports_invoice_number_unique", + "columns": [ + { + "expression": "invoice_number", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "billing_reports_editorial_account_id_editorial_accounts_id_fk": { + "name": "billing_reports_editorial_account_id_editorial_accounts_id_fk", + "tableFrom": "billing_reports", + "tableTo": "editorial_accounts", + "columnsFrom": [ + "editorial_account_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "billing_reports_created_by_user_id_user_id_fk": { + "name": "billing_reports_created_by_user_id_user_id_fk", + "tableFrom": "billing_reports", + "tableTo": "user", + "columnsFrom": [ + "created_by_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "billing_reports_cancelled_by_user_id_user_id_fk": { + "name": "billing_reports_cancelled_by_user_id_user_id_fk", + "tableFrom": "billing_reports", + "tableTo": "user", + "columnsFrom": [ + "cancelled_by_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "billing_reports_pdf_sha256_hex_check": { + "name": "billing_reports_pdf_sha256_hex_check", + "value": "\"billing_reports\".\"pdf_sha256\" ~ '^[0-9a-f]{64}$'" + }, + "billing_reports_final_pdf_check": { + "name": "billing_reports_final_pdf_check", + "value": "\"billing_reports\".\"status\" <> 'final' OR (\"billing_reports\".\"pdf\" IS NOT NULL AND \"billing_reports\".\"pdf_sha256\" IS NOT NULL)" + } + }, + "isRLSEnabled": false + }, + "public.billing_address_versions": { + "name": "billing_address_versions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "editorial_account_id": { + "name": "editorial_account_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "company_name": { + "name": "company_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "contact_name": { + "name": "contact_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "address_line_1": { + "name": "address_line_1", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "address_line_2": { + "name": "address_line_2", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "postal_code": { + "name": "postal_code", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "city": { + "name": "city", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "country_code": { + "name": "country_code", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "valid_from": { + "name": "valid_from", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "superseded_by_id": { + "name": "superseded_by_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_by_user_id": { + "name": "created_by_user_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "billing_address_versions_editorial_account_id_editorial_accounts_id_fk": { + "name": "billing_address_versions_editorial_account_id_editorial_accounts_id_fk", + "tableFrom": "billing_address_versions", + "tableTo": "editorial_accounts", + "columnsFrom": [ + "editorial_account_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "billing_address_versions_superseded_by_id_billing_address_versions_id_fk": { + "name": "billing_address_versions_superseded_by_id_billing_address_versions_id_fk", + "tableFrom": "billing_address_versions", + "tableTo": "billing_address_versions", + "columnsFrom": [ + "superseded_by_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "billing_address_versions_created_by_user_id_user_id_fk": { + "name": "billing_address_versions_created_by_user_id_user_id_fk", + "tableFrom": "billing_address_versions", + "tableTo": "user", + "columnsFrom": [ + "created_by_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.editorial_accounts": { + "name": "editorial_accounts", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "user_id": { + "name": "user_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "contact_name": { + "name": "contact_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "login_email": { + "name": "login_email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "account_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'pending_email'" + }, + "current_price_cents": { + "name": "current_price_cents", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "approval_notice_status": { + "name": "approval_notice_status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'not_requested'" + }, + "current_billing_address_version_id": { + "name": "current_billing_address_version_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "email_verified_at": { + "name": "email_verified_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "accepted_terms_version": { + "name": "accepted_terms_version", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "accepted_terms_at": { + "name": "accepted_terms_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "privacy_acknowledged_at": { + "name": "privacy_acknowledged_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "editorial_accounts_user_id_user_id_fk": { + "name": "editorial_accounts_user_id_user_id_fk", + "tableFrom": "editorial_accounts", + "tableTo": "user", + "columnsFrom": [ + "user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "editorial_accounts_current_billing_address_version_id_billing_address_versions_id_fk": { + "name": "editorial_accounts_current_billing_address_version_id_billing_address_versions_id_fk", + "tableFrom": "editorial_accounts", + "tableTo": "billing_address_versions", + "columnsFrom": [ + "current_billing_address_version_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "editorial_accounts_user_id_unique": { + "name": "editorial_accounts_user_id_unique", + "nullsNotDistinct": false, + "columns": [ + "user_id" + ] + }, + "editorial_accounts_login_email_unique": { + "name": "editorial_accounts_login_email_unique", + "nullsNotDistinct": false, + "columns": [ + "login_email" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.download_events": { + "name": "download_events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "editorial_account_id": { + "name": "editorial_account_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "usage_id": { + "name": "usage_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "immich_asset_id": { + "name": "immich_asset_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "authorized_at": { + "name": "authorized_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "started_at": { + "name": "started_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "download_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'authorized'" + }, + "transferred_bytes": { + "name": "transferred_bytes", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "repeat_download_note": { + "name": "repeat_download_note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "request_id": { + "name": "request_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "idempotency_key": { + "name": "idempotency_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "intent_kind": { + "name": "intent_kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'new_usage'" + }, + "request_fingerprint": { + "name": "request_fingerprint", + "type": "varchar(64)", + "primaryKey": false, + "notNull": true + }, + "legacy_intent": { + "name": "legacy_intent", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + } + }, + "indexes": { + "download_events_editorial_authorized_id_idx": { + "name": "download_events_editorial_authorized_id_idx", + "columns": [ + { + "expression": "editorial_account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "authorized_at", + "isExpression": false, + "asc": false, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "download_events_editorial_idempotency_key_unique": { + "name": "download_events_editorial_idempotency_key_unique", + "columns": [ + { + "expression": "editorial_account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "idempotency_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "download_events_editorial_account_id_editorial_accounts_id_fk": { + "name": "download_events_editorial_account_id_editorial_accounts_id_fk", + "tableFrom": "download_events", + "tableTo": "editorial_accounts", + "columnsFrom": [ + "editorial_account_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "download_events_usage_id_usages_id_fk": { + "name": "download_events_usage_id_usages_id_fk", + "tableFrom": "download_events", + "tableTo": "usages", + "columnsFrom": [ + "usage_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "download_events_intent_kind_check": { + "name": "download_events_intent_kind_check", + "value": "\"download_events\".\"intent_kind\" in ('new_usage', 'repeat_download', 'legacy')" + }, + "download_events_request_fingerprint_hex_check": { + "name": "download_events_request_fingerprint_hex_check", + "value": "\"download_events\".\"request_fingerprint\" ~ '^[0-9a-f]{64}$'" + }, + "download_events_canonical_idempotency_key_check": { + "name": "download_events_canonical_idempotency_key_check", + "value": "\"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}$'" + }, + "download_events_canonical_immich_asset_id_check": { + "name": "download_events_canonical_immich_asset_id_check", + "value": "\"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}$'" + } + }, + "isRLSEnabled": false + }, + "public.usages": { + "name": "usages", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "editorial_account_id": { + "name": "editorial_account_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "immich_asset_id": { + "name": "immich_asset_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "filename_snapshot": { + "name": "filename_snapshot", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "immich_album_id_snapshot": { + "name": "immich_album_id_snapshot", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "album_name_snapshot": { + "name": "album_name_snapshot", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "purpose": { + "name": "purpose", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "internal_reference": { + "name": "internal_reference", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "price_cents": { + "name": "price_cents", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "billing_status": { + "name": "billing_status", + "type": "usage_billing_status", + "typeSchema": "public", + "primaryKey": false, + "notNull": true, + "default": "'open'" + }, + "billing_report_id": { + "name": "billing_report_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "usages_editorial_created_id_idx": { + "name": "usages_editorial_created_id_idx", + "columns": [ + { + "expression": "editorial_account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": false, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "usages_editorial_account_id_editorial_accounts_id_fk": { + "name": "usages_editorial_account_id_editorial_accounts_id_fk", + "tableFrom": "usages", + "tableTo": "editorial_accounts", + "columnsFrom": [ + "editorial_account_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "usages_billing_report_id_billing_reports_id_fk": { + "name": "usages_billing_report_id_billing_reports_id_fk", + "tableFrom": "usages", + "tableTo": "billing_reports", + "columnsFrom": [ + "billing_report_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "usages_canonical_immich_asset_id_check": { + "name": "usages_canonical_immich_asset_id_check", + "value": "\"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}$'" + }, + "usages_canonical_immich_album_id_check": { + "name": "usages_canonical_immich_album_id_check", + "value": "\"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}$'" + } + }, + "isRLSEnabled": false + } + }, + "enums": { + "public.portal_role": { + "name": "portal_role", + "schema": "public", + "values": [ + "ADMIN", + "EDITORIAL" + ] + }, + "public.report_status": { + "name": "report_status", + "schema": "public", + "values": [ + "draft", + "final", + "cancelled" + ] + }, + "public.account_status": { + "name": "account_status", + "schema": "public", + "values": [ + "pending_email", + "pending_approval", + "active", + "suspended", + "rejected" + ] + }, + "public.download_status": { + "name": "download_status", + "schema": "public", + "values": [ + "authorized", + "streaming", + "completed", + "failed_before_delivery", + "interrupted" + ] + }, + "public.usage_billing_status": { + "name": "usage_billing_status", + "schema": "public", + "values": [ + "open", + "billed", + "reopened", + "voided" + ] + } + }, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": {}, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index c2f8c87..bfee1a8 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -29,6 +29,13 @@ "when": 1786358492749, "tag": "0003_stream_delivery", "breakpoints": true + }, + { + "idx": 4, + "version": "7", + "when": 1786363479515, + "tag": "0004_download_history_indexes", + "breakpoints": true } ] -} +} \ No newline at end of file diff --git a/src/app/globals.css b/src/app/globals.css index de83a9d..f2f93f3 100644 --- a/src/app/globals.css +++ b/src/app/globals.css @@ -870,6 +870,16 @@ a { border-top: 1px solid var(--ink); } +.usage-attempt-history { + margin-top: 3rem; +} + +.usage-attempt-history h2 { + margin: 0 0 1rem; + font-size: clamp(1.3rem, 3vw, 2rem); + letter-spacing: -0.03em; +} + .usage-attempts li { display: grid; grid-template-columns: minmax(9rem, 1.2fr) minmax(11rem, 1.5fr) minmax(8rem, 1fr) 0.7fr 0.7fr; @@ -889,6 +899,31 @@ a { text-align: right; } +.usage-attempt-context { + display: grid; + gap: 0.2rem; +} + +.usage-attempt-context strong { + overflow-wrap: anywhere; + color: var(--ink); +} + +.usage-attempt-context small { + line-height: 1.35; +} + +.usage-attempt-price { + display: grid; + gap: 0.2rem; + text-align: right; +} + +.usage-attempt-price small { + color: var(--metadata); + white-space: nowrap; +} + .usage-attempt-empty { margin: 0; padding: 1rem 0; diff --git a/src/app/redaktion/nutzungen/page.test.tsx b/src/app/redaktion/nutzungen/page.test.tsx index 448197b..d9ecbf6 100644 --- a/src/app/redaktion/nutzungen/page.test.tsx +++ b/src/app/redaktion/nutzungen/page.test.tsx @@ -22,35 +22,81 @@ test("renders every terminal attempt with its immutable usage snapshot", () => { billingStatus: "open", priceCents: 1_500, billableCents: 1_500, - attempts: [ - { - downloadId: "download-3", - 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, - }, - { - downloadId: "download-2", - 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, - }, - { - downloadId: "download-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, - }, - ], + }, + ], + 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, @@ -69,8 +115,12 @@ test("renders every terminal attempt with its immutable usage snapshot", () => { expect(screen.getByText("Abgeschlossen")).not.toBeNull(); expect(screen.getByText("Unterbrochen")).not.toBeNull(); expect(screen.getByText("Vor Auslieferung fehlgeschlagen")).not.toBeNull(); - expect(screen.getAllByText(/15,00\s*€/)).toHaveLength(2); - expect(screen.getAllByText(/0,00\s*€/)).toHaveLength(2); + 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", ); @@ -89,6 +139,7 @@ test("renders a directional empty state", () => { { billingStatus: "voided", priceCents: 1_500, billableCents: 0, - attempts: [], }, ], + attempts: [], page: 1, pageSize: 20, hasNext: false, diff --git a/src/app/redaktion/nutzungen/usage-history-content.tsx b/src/app/redaktion/nutzungen/usage-history-content.tsx index 69cbd20..ff091a7 100644 --- a/src/app/redaktion/nutzungen/usage-history-content.tsx +++ b/src/app/redaktion/nutzungen/usage-history-content.tsx @@ -63,17 +63,6 @@ export function UsageHistoryContent({ history }: Readonly<{ history: UsageHistor ) : null} - {usage.attempts.length === 0 ? ( -

- Keine Auslieferungsversuche auf dieser Auslieferungsseite. -

- ) : ( -
    - {usage.attempts.map((attempt) => ( - - ))} -
- )} ))} @@ -81,21 +70,47 @@ export function UsageHistoryContent({ history }: Readonly<{ history: UsageHistor )} + +
+

Downloadversuche

+ {history.attempts.length === 0 ? ( +

Noch keine Downloadversuche erfasst.

+ ) : ( +
    + {history.attempts.map((attempt) => ( + + ))} +
+ )} +
); } function AttemptRow({ attempt }: Readonly<{ attempt: UsageHistoryAttempt }>) { + const displayedAt = attempt.finishedAt ?? attempt.requestedAt; return (
  • -
  • ); } @@ -142,6 +157,8 @@ function AttemptPagination({ history }: Readonly<{ history: UsageHistoryPage }>) function statusLabel(status: UsageHistoryAttempt["status"]): string { const labels: Record = { + authorized: "Autorisiert", + streaming: "Wird ausgeliefert", completed: "Abgeschlossen", interrupted: "Unterbrochen", failed_before_delivery: "Vor Auslieferung fehlgeschlagen", diff --git a/src/db/schema/usages.ts b/src/db/schema/usages.ts index 2d1ef1c..21ba293 100644 --- a/src/db/schema/usages.ts +++ b/src/db/schema/usages.ts @@ -3,6 +3,7 @@ import { bigint, boolean, check, + index, integer, pgEnum, pgTable, @@ -49,6 +50,11 @@ export const usages = pgTable( createdAt: timestamp("created_at", { withTimezone: true }).notNull().defaultNow(), }, (table) => [ + index("usages_editorial_created_id_idx").on( + table.editorialAccountId, + table.createdAt.desc(), + table.id.desc(), + ), check( "usages_canonical_immich_asset_id_check", sql`${table.immichAssetId} ~ '^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$'`, @@ -84,6 +90,11 @@ export const downloadEvents = pgTable( legacyIntent: boolean("legacy_intent").notNull().default(false), }, (table) => [ + index("download_events_editorial_authorized_id_idx").on( + table.editorialAccountId, + table.authorizedAt.desc(), + table.id.desc(), + ), uniqueIndex("download_events_editorial_idempotency_key_unique").on( table.editorialAccountId, table.idempotencyKey, diff --git a/src/modules/downloads/eligibility.ts b/src/modules/downloads/eligibility.ts index 00a2321..64da72d 100644 --- a/src/modules/downloads/eligibility.ts +++ b/src/modules/downloads/eligibility.ts @@ -1,6 +1,6 @@ import "server-only"; -import { and, eq, gt, inArray } from "drizzle-orm"; +import { and, eq, gt, inArray, sql, type SQL, type SQLWrapper } from "drizzle-orm"; import type { NodePgDatabase } from "drizzle-orm/node-postgres"; import { downloadEvents } from "@/db/schema"; @@ -15,6 +15,23 @@ export function isFreeRepeatEligible( return billingStatus !== "voided" && deliveredOriginal; } +export function deliveredOriginalEventCondition( + editorialId: string, + usageId: string | SQLWrapper, +): SQL { + const scopedUsage = + typeof usageId === "string" + ? eq(downloadEvents.usageId, usageId) + : sql`${downloadEvents.usageId} = ${usageId}`; + return and( + eq(downloadEvents.editorialAccountId, editorialId), + scopedUsage, + eq(downloadEvents.intentKind, "new_usage"), + inArray(downloadEvents.status, ["completed", "interrupted"]), + gt(downloadEvents.transferredBytes, 0), + )!; +} + export async function hasDeliveredOriginal( database: NodePgDatabase, editorialId: string, @@ -23,15 +40,7 @@ export async function hasDeliveredOriginal( const [delivery] = await database .select({ id: downloadEvents.id }) .from(downloadEvents) - .where( - and( - eq(downloadEvents.editorialAccountId, editorialId), - eq(downloadEvents.usageId, usageId), - eq(downloadEvents.intentKind, "new_usage"), - inArray(downloadEvents.status, ["completed", "interrupted"]), - gt(downloadEvents.transferredBytes, 0), - ), - ) + .where(deliveredOriginalEventCondition(editorialId, usageId)) .limit(1); return Boolean(delivery); } diff --git a/src/modules/downloads/service.test.ts b/src/modules/downloads/service.test.ts index edc8e69..ee0763b 100644 --- a/src/modules/downloads/service.test.ts +++ b/src/modules/downloads/service.test.ts @@ -17,16 +17,15 @@ function createService() { const intents = new Map(); const events: RepeatIntentInput[] = []; let active = true; + let eligible = true; let usageOwner = editorialId; let snapshotPrice = 1_500; const repository: RepeatDownloadRepository = { - async findIntent(requestEditorialId, key) { - return intents.get(`${requestEditorialId}:${key}`) ?? null; - }, async createRepeatIntent(input) { if (!active) throw new UsageAccountingError("EDITORIAL_NOT_ACTIVE"); if (usageOwner !== input.editorialId) throw new UsageAccountingError("USAGE_NOT_FOUND"); + if (!eligible) throw new UsageAccountingError("USAGE_NOT_FOUND"); const key = `${input.editorialId}:${input.idempotencyKey}`; const existing = intents.get(key); if (existing) return existing; @@ -54,6 +53,9 @@ function createService() { setActive(value: boolean) { active = value; }, + setEligible(value: boolean) { + eligible = value; + }, setUsageOwner(value: string) { usageOwner = value; }, @@ -127,6 +129,17 @@ test("returns the same free intent once for an equivalent retry", async () => { expect(events).toHaveLength(1); }); +test("revalidates eligibility under the repository lock for the same idempotency key", async () => { + const { service, setEligible } = createService(); + const input = { editorialId, usageId, note: "noch einmal", idempotencyKey }; + await service.createRepeatDownload(input); + setEligible(false); + + await expect(service.createRepeatDownload(input)).rejects.toMatchObject({ + code: "USAGE_NOT_FOUND", + }); +}); + test("treats mixed-case UUID input as the same repeat intent", async () => { const { service, events } = createService(); const uppercaseInput = { @@ -159,10 +172,10 @@ test.each([ [undefined, "not-a-uuid"], ] as const)("rejects malformed repeat input before repository side effects", async (note, key) => { const { service, repository } = createService(); - const findIntent = vi.spyOn(repository, "findIntent"); + const createRepeatIntent = vi.spyOn(repository, "createRepeatIntent"); await expect( service.createRepeatDownload({ editorialId, usageId, note, idempotencyKey: key }), ).rejects.toMatchObject({ code: "INVALID_INPUT" }); - expect(findIntent).not.toHaveBeenCalled(); + expect(createRepeatIntent).not.toHaveBeenCalled(); }); diff --git a/src/modules/downloads/service.ts b/src/modules/downloads/service.ts index 883f506..55665d8 100644 --- a/src/modules/downloads/service.ts +++ b/src/modules/downloads/service.ts @@ -36,7 +36,6 @@ export type RepeatIntentInput = { }; export type RepeatDownloadRepository = { - findIntent(editorialId: string, idempotencyKey: string): Promise; createRepeatIntent(input: RepeatIntentInput): Promise; }; @@ -50,8 +49,6 @@ export function createDownloadService({ repository }: { repository: RepeatDownlo usageId: input.usageId, note: input.note ?? null, }); - const existing = await repository.findIntent(input.editorialId, input.idempotencyKey); - if (existing) return resolveIntent(existing, fingerprint, "repeat_download"); const persisted = await repository.createRepeatIntent({ ...input, requestFingerprint: fingerprint, @@ -65,109 +62,108 @@ export function createRepeatDownloadRepository( database: NodePgDatabase, ): RepeatDownloadRepository { return { - findIntent(editorialId, idempotencyKey) { - return findPersistedIntent(database, editorialId, idempotencyKey); - }, - async createRepeatIntent(input) { - try { - return await database.transaction(async (transaction) => { - await lockEditorialAccounting(transaction, input.editorialId); - const existing = await findPersistedIntent( - transaction, - input.editorialId, - input.idempotencyKey, - ); - if ( - existing && - (existing.kind !== "repeat_download" || - existing.requestFingerprint !== input.requestFingerprint) - ) { - throw new UsageAccountingError("IDEMPOTENCY_CONFLICT"); - } - - const [editorial] = await transaction - .select({ id: editorialAccounts.id, status: editorialAccounts.status }) - .from(editorialAccounts) - .where(eq(editorialAccounts.id, input.editorialId)) - .for("update") - .limit(1); - if (!editorial || editorial.status !== "active") { - throw new UsageAccountingError("EDITORIAL_NOT_ACTIVE"); - } - - const [usage] = await transaction - .select({ - id: usages.id, - assetId: usages.immichAssetId, - billingStatus: usages.billingStatus, - }) - .from(usages) - .where( - and( - eq(usages.id, input.usageId), - eq(usages.editorialAccountId, input.editorialId), - ), - ) - .for("update") - .limit(1); - if (!usage) throw new UsageAccountingError("USAGE_NOT_FOUND"); - const deliveredOriginal = await hasDeliveredOriginal( - transaction, - input.editorialId, - usage.id, - ); - if (!isFreeRepeatEligible(usage.billingStatus, deliveredOriginal)) { - throw new UsageAccountingError("USAGE_NOT_FOUND"); - } - if (existing) return asRepeatIntent(existing); - - const authorizedAt = new Date(); - const [event] = await transaction - .insert(downloadEvents) - .values({ - editorialAccountId: input.editorialId, - usageId: usage.id, - immichAssetId: usage.assetId, - authorizedAt, - status: "authorized", - repeatDownloadNote: input.note, - requestId: randomUUID(), - idempotencyKey: input.idempotencyKey, - intentKind: "repeat_download", - requestFingerprint: input.requestFingerprint, - }) - .onConflictDoNothing({ - target: [downloadEvents.editorialAccountId, downloadEvents.idempotencyKey], - }) - .returning({ id: downloadEvents.id }); - if (!event) throw new RepeatIdempotencyRaceError(); - return { - id: event.id, - usageId: usage.id, - assetId: usage.assetId, - priceCents: 0, - billable: false, - status: "authorized" as const, - authorizedAt, - requestFingerprint: input.requestFingerprint, - kind: "repeat_download" as const, - }; - }); - } catch (error) { - if (!(error instanceof RepeatIdempotencyRaceError)) throw error; - const existing = await findPersistedIntent( - database, - input.editorialId, - input.idempotencyKey, - ); - if (existing) return asRepeatIntent(existing); - throw error; + for (let attempt = 0; attempt < 2; attempt += 1) { + try { + return await createRepeatIntentTransaction(database, input); + } catch (error) { + if (!(error instanceof RepeatIdempotencyRaceError) || attempt === 1) throw error; + } } + throw new RepeatIdempotencyRaceError(); }, }; } +async function createRepeatIntentTransaction( + database: NodePgDatabase, + input: RepeatIntentInput, +): Promise { + return database.transaction(async (transaction) => { + await lockEditorialAccounting(transaction, input.editorialId); + const existing = await findPersistedIntent( + transaction, + input.editorialId, + input.idempotencyKey, + ); + if ( + existing && + (existing.kind !== "repeat_download" || + existing.requestFingerprint !== input.requestFingerprint) + ) { + throw new UsageAccountingError("IDEMPOTENCY_CONFLICT"); + } + + const [editorial] = await transaction + .select({ id: editorialAccounts.id, status: editorialAccounts.status }) + .from(editorialAccounts) + .where(eq(editorialAccounts.id, input.editorialId)) + .for("update") + .limit(1); + if (!editorial || editorial.status !== "active") { + throw new UsageAccountingError("EDITORIAL_NOT_ACTIVE"); + } + + const [usage] = await transaction + .select({ + id: usages.id, + assetId: usages.immichAssetId, + billingStatus: usages.billingStatus, + }) + .from(usages) + .where( + and( + eq(usages.id, input.usageId), + eq(usages.editorialAccountId, input.editorialId), + ), + ) + .for("update") + .limit(1); + if (!usage) throw new UsageAccountingError("USAGE_NOT_FOUND"); + const deliveredOriginal = await hasDeliveredOriginal( + transaction, + input.editorialId, + usage.id, + ); + if (!isFreeRepeatEligible(usage.billingStatus, deliveredOriginal)) { + throw new UsageAccountingError("USAGE_NOT_FOUND"); + } + if (existing) return asRepeatIntent(existing); + + const authorizedAt = new Date(); + const [event] = await transaction + .insert(downloadEvents) + .values({ + editorialAccountId: input.editorialId, + usageId: usage.id, + immichAssetId: usage.assetId, + authorizedAt, + status: "authorized", + repeatDownloadNote: input.note, + requestId: randomUUID(), + idempotencyKey: input.idempotencyKey, + intentKind: "repeat_download", + requestFingerprint: input.requestFingerprint, + }) + .onConflictDoNothing({ + target: [downloadEvents.editorialAccountId, downloadEvents.idempotencyKey], + }) + .returning({ id: downloadEvents.id }); + if (!event) throw new RepeatIdempotencyRaceError(); + return { + id: event.id, + usageId: usage.id, + assetId: usage.assetId, + priceCents: 0, + billable: false, + status: "authorized", + authorizedAt, + requestFingerprint: input.requestFingerprint, + kind: "repeat_download", + }; + }); +} + function normalizeRepeatInput(input: CreateRepeatDownloadInput): CreateRepeatDownloadInput { if (!input || typeof input !== "object") throw new UsageAccountingError("INVALID_INPUT"); const note = normalizeOptionalText(input.note, 200); diff --git a/src/modules/downloads/stream.test.ts b/src/modules/downloads/stream.test.ts index 1f6df72..1f78c06 100644 --- a/src/modules/downloads/stream.test.ts +++ b/src/modules/downloads/stream.test.ts @@ -194,6 +194,7 @@ test("normalizes and bounds history pagination before the scoped repository quer const repository = { listEditorialUsageHistory: vi.fn().mockResolvedValue({ items: [], + attempts: [], page: HISTORY_MAX_PAGE, pageSize: 20, hasNext: false, diff --git a/src/modules/downloads/stream.ts b/src/modules/downloads/stream.ts index 960065a..93c2a65 100644 --- a/src/modules/downloads/stream.ts +++ b/src/modules/downloads/stream.ts @@ -1,6 +1,6 @@ import "server-only"; -import { and, desc, eq, inArray, sql } from "drizzle-orm"; +import { and, desc, eq, exists, inArray, sql } from "drizzle-orm"; import type { NodePgDatabase } from "drizzle-orm/node-postgres"; import { db } from "@/db/client"; @@ -8,11 +8,17 @@ import { auditEvents, downloadEvents, editorialAccounts, usages } from "@/db/sch import type * as schema from "@/db/schema"; import { normalizeUuid, UsageAccountingError } from "@/modules/usages/types"; -import { hasDeliveredOriginal, isFreeRepeatEligible } from "./eligibility"; +import { + deliveredOriginalEventCondition, + hasDeliveredOriginal, + isFreeRepeatEligible, +} from "./eligibility"; export const HISTORY_PAGE_SIZE = 20; export const HISTORY_MAX_PAGE = 1_000; export const HISTORY_ATTEMPT_PAGE_SIZE = 25; +export const DOWNLOAD_OPTIONS_MAX_ASSETS = 60; +export const DOWNLOAD_OPTIONS_MAX_USAGES = 300; export type ClaimedDownload = { id: string; @@ -351,12 +357,18 @@ function assertByteCount(value: number) { export type UsageHistoryAttempt = { downloadId: string; - status: "completed" | "interrupted" | "failed_before_delivery"; + usageId: string; + status: typeof downloadEvents.$inferSelect.status; requestedAt: Date; - finishedAt: Date; + finishedAt?: Date; transferredBytes: number; repeat: boolean; billableCents: number; + filename: string; + albumName: string; + purpose: string; + reference?: string; + priceCents: number; }; export type UsageHistoryItem = { @@ -369,11 +381,11 @@ export type UsageHistoryItem = { billingStatus: "open" | "billed" | "reopened" | "voided"; priceCents: number; billableCents: number; - attempts: UsageHistoryAttempt[]; }; export type UsageHistoryPage = { items: UsageHistoryItem[]; + attempts: UsageHistoryAttempt[]; page: number; pageSize: number; hasNext: boolean; @@ -443,20 +455,9 @@ export function createPostgresDownloadHistoryRepository( .offset(offset); const hasNext = usageRows.length > HISTORY_PAGE_SIZE; const pageRows = usageRows.slice(0, HISTORY_PAGE_SIZE); - if (pageRows.length === 0) { - return { - items: [], - page, - pageSize: HISTORY_PAGE_SIZE, - hasNext, - attemptPageSize: HISTORY_ATTEMPT_PAGE_SIZE, - }; - } - - const usageIds = pageRows.map((usage) => usage.usageId); const authorizedAtMicros = sql`floor(extract(epoch from ${downloadEvents.authorizedAt}) * 1000000)::bigint`; const beforeCursor = attemptCursor - ? sql`(${authorizedAtMicros}, ${downloadEvents.id}) < (${attemptCursor.authorizedAtMicros}::bigint, ${attemptCursor.downloadId}::uuid)` + ? sql`(${downloadEvents.authorizedAt}, ${downloadEvents.id}) < (timestamptz 'epoch' + ${attemptCursor.authorizedAtMicros}::bigint * interval '1 microsecond', ${attemptCursor.downloadId}::uuid)` : undefined; const eventRowsWithNext = await database .select({ @@ -468,17 +469,24 @@ export function createPostgresDownloadHistoryRepository( transferredBytes: downloadEvents.transferredBytes, intentKind: downloadEvents.intentKind, authorizedAtMicros, + filename: usages.filenameSnapshot, + albumName: usages.albumNameSnapshot, + purpose: usages.purpose, + reference: usages.internalReference, + priceCents: usages.priceCents, + billingStatus: usages.billingStatus, }) .from(downloadEvents) + .innerJoin( + usages, + and( + eq(usages.id, downloadEvents.usageId), + eq(usages.editorialAccountId, editorialId), + ), + ) .where( and( eq(downloadEvents.editorialAccountId, editorialId), - inArray(downloadEvents.usageId, usageIds), - inArray(downloadEvents.status, [ - "completed", - "interrupted", - "failed_before_delivery", - ]), beforeCursor, ), ) @@ -495,13 +503,6 @@ export function createPostgresDownloadHistoryRepository( }) : undefined; - const eventsByUsage = new Map(); - for (const event of eventRows) { - const attempts = eventsByUsage.get(event.usageId) ?? []; - attempts.push(event); - eventsByUsage.set(event.usageId, attempts); - } - return { items: pageRows.map((usage) => { const billableCents = usage.billingStatus === "voided" ? 0 : usage.priceCents; @@ -515,20 +516,26 @@ export function createPostgresDownloadHistoryRepository( billingStatus: usage.billingStatus, priceCents: usage.priceCents, billableCents, - attempts: (eventsByUsage.get(usage.usageId) ?? []).map((event) => ({ - downloadId: event.downloadId, - status: terminalStatus(event.status), - requestedAt: event.requestedAt, - finishedAt: event.finishedAt ?? event.requestedAt, - transferredBytes: event.transferredBytes ?? 0, - repeat: event.intentKind === "repeat_download", - billableCents: - event.intentKind === "new_usage" && usage.billingStatus !== "voided" - ? usage.priceCents - : 0, - })), }; }), + attempts: eventRows.map((event) => ({ + downloadId: event.downloadId, + usageId: event.usageId, + status: event.status, + requestedAt: event.requestedAt, + ...(event.finishedAt === null ? {} : { finishedAt: event.finishedAt }), + transferredBytes: event.transferredBytes ?? 0, + repeat: event.intentKind === "repeat_download", + billableCents: + event.intentKind === "new_usage" && event.billingStatus !== "voided" + ? event.priceCents + : 0, + filename: event.filename, + albumName: event.albumName, + purpose: event.purpose, + ...(event.reference === null ? {} : { reference: event.reference }), + priceCents: event.priceCents, + })), page, pageSize: HISTORY_PAGE_SIZE, hasNext, @@ -539,17 +546,6 @@ export function createPostgresDownloadHistoryRepository( }; } -function terminalStatus(status: string): UsageHistoryAttempt["status"] { - if ( - status === "completed" || - status === "interrupted" || - status === "failed_before_delivery" - ) { - return status; - } - throw new Error("Non-terminal download in history query"); -} - function claimedIntentKind(value: string): ClaimedDownload["intentKind"] { if (value === "new_usage" || value === "repeat_download" || value === "legacy") { return value; @@ -601,57 +597,72 @@ export type EditorialDownloadOptions = { priorUsagesByAsset: Record; }; -export async function loadEditorialDownloadOptions( - editorialId: string, - assetIds: string[], -): Promise { - const normalizedEditorialId = normalizeUuid(editorialId); - const normalizedAssets = [...new Set(assetIds.map(normalizeUuid))]; - const [editorial] = await db - .select({ currentPriceCents: editorialAccounts.currentPriceCents }) - .from(editorialAccounts) - .where( - and( - eq(editorialAccounts.id, normalizedEditorialId), - eq(editorialAccounts.status, "active"), - ), - ) - .limit(1); - const priceCents = editorial?.currentPriceCents; - if (!Number.isSafeInteger(priceCents) || (priceCents ?? 0) <= 0) { - throw new UsageAccountingError("INVALID_PRICE"); - } - if (normalizedAssets.length === 0) { - return { priceCents: priceCents!, priorUsagesByAsset: {} }; - } +export function createEditorialDownloadOptionsLoader( + database: NodePgDatabase, +) { + return async function loadOptions( + editorialId: string, + assetIds: string[], + ): Promise { + const normalizedEditorialId = normalizeUuid(editorialId); + const normalizedAssets = [...new Set(assetIds.map(normalizeUuid))]; + if (normalizedAssets.length > DOWNLOAD_OPTIONS_MAX_ASSETS) { + throw new UsageAccountingError("INVALID_INPUT"); + } + const [editorial] = await database + .select({ currentPriceCents: editorialAccounts.currentPriceCents }) + .from(editorialAccounts) + .where( + and( + eq(editorialAccounts.id, normalizedEditorialId), + eq(editorialAccounts.status, "active"), + ), + ) + .limit(1); + const priceCents = editorial?.currentPriceCents; + if (!Number.isSafeInteger(priceCents) || (priceCents ?? 0) <= 0) { + throw new UsageAccountingError("INVALID_PRICE"); + } + if (normalizedAssets.length === 0) { + return { priceCents: priceCents!, priorUsagesByAsset: {} }; + } - const rows = await db - .select({ - id: usages.id, - assetId: usages.immichAssetId, - purpose: usages.purpose, - createdAt: usages.createdAt, - }) - .from(usages) - .where( - and( - eq(usages.editorialAccountId, normalizedEditorialId), - inArray(usages.immichAssetId, normalizedAssets), - inArray(usages.billingStatus, ["open", "billed", "reopened"]), - ), - ) - .orderBy(desc(usages.createdAt)); - const priorUsagesByAsset: Record = {}; - for (const row of rows) { - (priorUsagesByAsset[row.assetId] ??= []).push({ - id: row.id, - purpose: row.purpose, - createdAt: row.createdAt.toISOString(), - }); - } - return { priceCents: priceCents!, priorUsagesByAsset }; + const deliveredOriginal = database + .select({ id: downloadEvents.id }) + .from(downloadEvents) + .where(deliveredOriginalEventCondition(normalizedEditorialId, usages.id)); + const rows = await database + .select({ + id: usages.id, + assetId: usages.immichAssetId, + purpose: usages.purpose, + createdAt: usages.createdAt, + }) + .from(usages) + .where( + and( + eq(usages.editorialAccountId, normalizedEditorialId), + inArray(usages.immichAssetId, normalizedAssets), + inArray(usages.billingStatus, ["open", "billed", "reopened"]), + exists(deliveredOriginal), + ), + ) + .orderBy(desc(usages.createdAt), desc(usages.id)) + .limit(DOWNLOAD_OPTIONS_MAX_USAGES); + const priorUsagesByAsset: Record = {}; + for (const row of rows) { + (priorUsagesByAsset[row.assetId] ??= []).push({ + id: row.id, + purpose: row.purpose, + createdAt: row.createdAt.toISOString(), + }); + } + return { priceCents: priceCents!, priorUsagesByAsset }; + }; } +export const loadEditorialDownloadOptions = createEditorialDownloadOptionsLoader(db); + const downloadHistoryService = createDownloadHistoryService({ repository: createPostgresDownloadHistoryRepository(db), }); diff --git a/src/modules/usages/service.test.ts b/src/modules/usages/service.test.ts index 9c31178..49b7fd7 100644 --- a/src/modules/usages/service.test.ts +++ b/src/modules/usages/service.test.ts @@ -80,6 +80,12 @@ function createRepository() { setStatus(value: string) { status = value; }, + setIntentStatus(value: string) { + const key = `${editorialId}:${idempotencyKey}`; + const intent = intents.get(key); + if (!intent) throw new Error("intent missing"); + intents.set(key, { ...intent, status: value } as unknown as PersistedDownloadIntent); + }, }; } @@ -174,6 +180,16 @@ test("keeps the original snapshot after a price change while a new key uses the ).resolves.toMatchObject({ priceCents: 2_100 }); }); +test("does not expose a terminal persisted event as an authorized intent", async () => { + const { service, setIntentStatus } = createService(); + await service.createNewUsage(newUsageInput); + setIntentStatus("failed_before_delivery"); + + await expect(service.createNewUsage(newUsageInput)).rejects.toMatchObject({ + code: "USAGE_NOT_FOUND", + }); +}); + test.each([ ["zero", 0], ["missing", null], diff --git a/src/modules/usages/service.ts b/src/modules/usages/service.ts index 29f1df1..c5ebe35 100644 --- a/src/modules/usages/service.ts +++ b/src/modules/usages/service.ts @@ -2,7 +2,7 @@ import "server-only"; import { randomUUID } from "node:crypto"; -import { and, desc, eq, inArray, isNull, sql } from "drizzle-orm"; +import { and, desc, eq, exists, inArray, isNull, sql } from "drizzle-orm"; import type { NodePgDatabase } from "drizzle-orm/node-postgres"; import { db } from "@/db/client"; @@ -16,6 +16,7 @@ import { import type * as schema from "@/db/schema"; import { immichClient } from "@/modules/immich/client"; import type { ImmichAlbumSummary } from "@/modules/immich/types"; +import { deliveredOriginalEventCondition } from "@/modules/downloads/eligibility"; import { type CreateNewUsageInput, @@ -28,7 +29,8 @@ import { UsageAccountingError, } from "./types"; -export type PersistedDownloadIntent = DownloadIntent & { +export type PersistedDownloadIntent = Omit & { + status: typeof downloadEvents.$inferSelect.status; requestFingerprint: string; kind: "new_usage" | "repeat_download"; }; @@ -243,6 +245,10 @@ export function createUsageServiceRepository( }, async listPriorUsages(editorialId, assetId) { + const deliveredOriginal = database + .select({ id: downloadEvents.id }) + .from(downloadEvents) + .where(deliveredOriginalEventCondition(editorialId, usages.id)); const rows = await database .select({ id: usages.id, @@ -262,6 +268,7 @@ export function createUsageServiceRepository( eq(usages.editorialAccountId, editorialId), eq(usages.immichAssetId, assetId), inArray(usages.billingStatus, ["open", "billed", "reopened"]), + exists(deliveredOriginal), ), ) .orderBy(desc(usages.createdAt)); @@ -331,8 +338,11 @@ export function resolveIntent( if (persisted.requestFingerprint !== fingerprint || persisted.kind !== kind) { throw new UsageAccountingError("IDEMPOTENCY_CONFLICT"); } + if (persisted.status !== "authorized") { + throw new UsageAccountingError("USAGE_NOT_FOUND"); + } const { requestFingerprint: _fingerprint, kind: _kind, ...intent } = persisted; - return intent; + return { ...intent, status: "authorized" }; } class IdempotencyRaceError extends Error {} @@ -382,6 +392,7 @@ const intentSelection = { usageId: downloadEvents.usageId, assetId: downloadEvents.immichAssetId, authorizedAt: downloadEvents.authorizedAt, + eventStatus: downloadEvents.status, intentKind: downloadEvents.intentKind, requestFingerprint: downloadEvents.requestFingerprint, usagePriceCents: usages.priceCents, @@ -392,6 +403,7 @@ function persistedIntent(row: { usageId: string; assetId: string; authorizedAt: Date; + eventStatus: PersistedDownloadIntent["status"]; intentKind: string; requestFingerprint: string; usagePriceCents: number; @@ -408,7 +420,7 @@ function persistedIntent(row: { assetId: row.assetId, priceCents: row.intentKind === "new_usage" ? row.usagePriceCents : 0, billable: row.intentKind === "new_usage", - status: "authorized", + status: row.eventStatus, authorizedAt: row.authorizedAt, requestFingerprint: row.requestFingerprint, kind: row.intentKind, diff --git a/tests/db/download-delivery.test.ts b/tests/db/download-delivery.test.ts index 503629c..f4a5898 100644 --- a/tests/db/download-delivery.test.ts +++ b/tests/db/download-delivery.test.ts @@ -5,6 +5,7 @@ import { afterAll, expect, test } from "vitest"; import { createDownloadDeliveryRepository, createDownloadHistoryService, + createEditorialDownloadOptionsLoader, createPostgresDownloadHistoryRepository, HISTORY_ATTEMPT_PAGE_SIZE, } from "@/modules/downloads/stream"; @@ -137,11 +138,13 @@ test("a later new-use void invalidates a pre-authorized eligible repeat", async const repeats = createDownloadService({ repository: createRepeatDownloadRepository(testDb.database), }); - const repeatIntent = await repeats.createRepeatDownload({ + const repeatKey = randomUUID(); + const repeatInput = { editorialId: seed.editorialId, usageId: seed.usageId, - idempotencyKey: randomUUID(), - }); + idempotencyKey: repeatKey, + }; + const repeatIntent = await repeats.createRepeatDownload(repeatInput); const failed = await delivery.failBeforeDelivery(failingNewId, { voidNewUsage: true }); const repeatClaim = await delivery.claimAuthorized(seed.editorialId, repeatIntent.id); @@ -153,6 +156,101 @@ test("a later new-use void invalidates a pre-authorized eligible repeat", async [repeatIntent.id], ); expect(repeatRow.rows[0]).toEqual({ status: "failed_before_delivery" }); + await expect(repeats.createRepeatDownload(repeatInput)).rejects.toMatchObject({ + code: "USAGE_NOT_FOUND", + }); +}); + +test("dialog choices include only owned usages with delivered original bytes", async () => { + const own = await testDb.seedEditorialWithUsage(); + const foreign = await testDb.seedEditorialWithUsage(); + const billedAssetId = randomUUID(); + const reopenedAssetId = randomUUID(); + const zeroByteAssetId = randomUUID(); + const deliveredOpen = await insertUsage(own.editorialId, own.assetId, "open", "Open geliefert"); + const deliveredBilled = await insertUsage( + own.editorialId, + billedAssetId, + "billed", + "Abgerechnet geliefert", + ); + const deliveredReopened = await insertUsage( + own.editorialId, + reopenedAssetId, + "reopened", + "Wieder geöffnet geliefert", + ); + const zeroByte = await insertUsage( + own.editorialId, + zeroByteAssetId, + "open", + "Null Byte", + ); + const eventSeeds = [ + { ...own, usageId: deliveredOpen, id: randomUUID(), bytes: 7, status: "completed" }, + { + ...own, + usageId: deliveredBilled, + assetId: billedAssetId, + id: randomUUID(), + bytes: 9, + status: "completed", + }, + { + ...own, + usageId: deliveredReopened, + assetId: reopenedAssetId, + id: randomUUID(), + bytes: 3, + status: "interrupted", + }, + { + ...own, + usageId: zeroByte, + assetId: zeroByteAssetId, + id: randomUUID(), + bytes: 0, + status: "completed", + }, + { ...foreign, id: randomUUID(), bytes: 11, status: "completed" }, + ] as const; + for (const event of eventSeeds) { + await testDb.insertDownload({ + editorialId: event.editorialId, + usageId: event.usageId, + assetId: event.assetId, + id: event.id, + idempotencyKey: randomUUID(), + }); + await testDb.pool.query( + "update download_events set status = $2, started_at = now(), completed_at = now(), transferred_bytes = $3 where id = $1", + [event.id, event.status, event.bytes], + ); + } + const loadOptions = createEditorialDownloadOptionsLoader(testDb.database); + + const options = await loadOptions(own.editorialId, [ + own.assetId, + billedAssetId, + reopenedAssetId, + zeroByteAssetId, + ]); + + expect(options.priorUsagesByAsset[own.assetId]?.map((usage) => usage.purpose)).toEqual([ + "Open geliefert", + ]); + expect(options.priorUsagesByAsset[billedAssetId]?.map((usage) => usage.purpose)).toEqual([ + "Abgerechnet geliefert", + ]); + expect(options.priorUsagesByAsset[reopenedAssetId]?.map((usage) => usage.purpose)).toEqual([ + "Wieder geöffnet geliefert", + ]); + expect(options.priorUsagesByAsset[zeroByteAssetId]).toBeUndefined(); + expect( + Object.values(options.priorUsagesByAsset) + .flat() + .some((usage) => usage.id === foreign.usageId), + ).toBe(false); }); test("a failed repeat attempt never mutates the original usage", async () => { @@ -200,7 +298,7 @@ test("terminal completion and interruption race to exactly one database transiti expect(["completed", "interrupted"]).toContain(event.rows[0].status); }); -test("history is editorial-scoped, terminal-only, and paginated by usage", async () => { +test("history keeps the global all-status attempt stream editorial-scoped", async () => { const own = await testDb.seedEditorialWithUsage(); const foreign = await testDb.seedEditorialWithUsage(); const ownCompleted = randomUUID(); @@ -234,14 +332,14 @@ test("history is editorial-scoped, terminal-only, and paginated by usage", async expect(page.items).toHaveLength(1); expect(page.items[0].usageId).toBe(own.usageId); - expect(new Set(page.items[0].attempts.map((attempt) => attempt.downloadId))).toEqual( - new Set([ownInterrupted, ownCompleted]), + expect(new Set(page.attempts.map((attempt) => attempt.downloadId))).toEqual( + new Set([ownAuthorized, ownInterrupted, ownCompleted]), ); - expect(page.items[0].attempts.some((attempt) => attempt.downloadId === ownAuthorized)).toBe(false); - expect(page.items[0].attempts.some((attempt) => attempt.downloadId === foreignCompleted)).toBe(false); + expect(page.attempts.some((attempt) => attempt.downloadId === foreignCompleted)).toBe(false); + expect(page.attempts.every((attempt) => attempt.filename === "bild.jpg")).toBe(true); }); -test("history bounds terminal attempts and exposes every attempt through pagination", async () => { +test("global attempt traversal is independent of usage pages and stable across status changes", async () => { const own = await testDb.seedEditorialWithUsage(); const attemptIds: string[] = []; for (let index = 0; index < HISTORY_ATTEMPT_PAGE_SIZE + 1; index += 1) { @@ -254,26 +352,77 @@ test("history bounds terminal attempts and exposes every attempt through paginat intentKind: index === 0 ? "new_usage" : "repeat_download", }); } - await testDb.pool.query( - "update download_events set status = 'completed', started_at = now(), completed_at = now(), transferred_bytes = 5 where usage_id = $1", - [own.usageId], - ); const history = createDownloadHistoryService({ repository: createPostgresDownloadHistoryRepository(testDb.database), }); - const first = await history.listEditorialUsageHistory(own.editorialId, 1, 1); + const first = await history.listEditorialUsageHistory(own.editorialId, 2); expect(first.nextAttemptCursor).toBeDefined(); + expect(first.items).toHaveLength(0); + await testDb.pool.query( + "update download_events set status = 'completed', started_at = now(), completed_at = now(), transferred_bytes = 5 where id = $1", + [first.attempts[0].downloadId], + ); + const laterEventId = randomUUID(); + await testDb.insertDownload({ + ...own, + id: laterEventId, + idempotencyKey: randomUUID(), + intentKind: "repeat_download", + }); const second = await history.listEditorialUsageHistory( own.editorialId, - 1, + 2, first.nextAttemptCursor, ); - const firstIds = first.items.flatMap((usage) => usage.attempts.map((attempt) => attempt.downloadId)); - const secondIds = second.items.flatMap((usage) => usage.attempts.map((attempt) => attempt.downloadId)); + const firstIds = first.attempts.map((attempt) => attempt.downloadId); + const secondIds = second.attempts.map((attempt) => attempt.downloadId); expect(firstIds).toHaveLength(HISTORY_ATTEMPT_PAGE_SIZE); expect(secondIds).toHaveLength(1); expect(second.nextAttemptCursor).toBeUndefined(); expect(new Set([...firstIds, ...secondIds])).toEqual(new Set(attemptIds)); + expect([...firstIds, ...secondIds]).not.toContain(laterEventId); }); + +test("history ordering queries can use the editorial keyset indexes", async () => { + const own = await testDb.seedEditorialWithUsage(); + const client = await testDb.pool.connect(); + try { + await client.query("begin"); + await client.query("set local enable_seqscan = off"); + const events = await client.query( + "explain (costs off) select id from download_events where editorial_account_id = $1 order by authorized_at desc, id desc limit 26", + [own.editorialId], + ); + const usageRows = await client.query( + "explain (costs off) select id from usages where editorial_account_id = $1 order by created_at desc, id desc limit 21", + [own.editorialId], + ); + const eventPlan = events.rows.map((row) => row["QUERY PLAN"]).join("\n"); + const usagePlan = usageRows.rows.map((row) => row["QUERY PLAN"]).join("\n"); + + expect(eventPlan).toContain("download_events_editorial_authorized_id_idx"); + expect(usagePlan).toContain("usages_editorial_created_id_idx"); + } finally { + await client.query("rollback"); + client.release(); + } +}); + +async function insertUsage( + editorialId: string, + assetId: string, + billingStatus: "open" | "billed" | "reopened", + purpose: string, +): Promise { + const usageId = randomUUID(); + await testDb.pool.query( + `insert into usages ( + id, editorial_account_id, immich_asset_id, filename_snapshot, + immich_album_id_snapshot, album_name_snapshot, purpose, price_cents, billing_status + ) values ($1, $2, $3, 'dialog.jpg', 'bbbbbbbb-bbbb-4bbb-8bbb-bbbbbbbbbbbb', 'Dialog', $4, 1500, $5)`, + [usageId, editorialId, assetId, purpose, billingStatus], + ); + return usageId; +} diff --git a/tests/db/download-history-index-migration-sql.test.ts b/tests/db/download-history-index-migration-sql.test.ts new file mode 100644 index 0000000..11fb79c --- /dev/null +++ b/tests/db/download-history-index-migration-sql.test.ts @@ -0,0 +1,19 @@ +import { readFile } from "node:fs/promises"; +import path from "node:path"; + +import { expect, test } from "vitest"; + +test("0004 adds both editorial history keyset indexes without rewriting history", async () => { + const migration = await readFile( + path.join(process.cwd(), "drizzle/0004_download_history_indexes.sql"), + "utf8", + ); + + expect(migration).toContain( + '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)', + ); + expect(migration).toContain( + 'CREATE INDEX "usages_editorial_created_id_idx" ON "usages" USING btree ("editorial_account_id","created_at" DESC NULLS LAST,"id" DESC NULLS LAST)', + ); + expect(migration).not.toMatch(/delete\s+from\s+"?(usages|download_events)"?/i); +}); diff --git a/tests/db/usage-accounting.test.ts b/tests/db/usage-accounting.test.ts index e1d5c42..93c6d92 100644 --- a/tests/db/usage-accounting.test.ts +++ b/tests/db/usage-accounting.test.ts @@ -432,6 +432,7 @@ test("a repeat remains free after a price change and creates no additional usage const editorialId = await seedEditorial(); const { usageService, downloadService } = createServices(); const first = await usageService.createNewUsage(newInput(editorialId)); + await markDelivered(first.id); await database .update(editorialAccounts) .set({ currentPriceCents: 2_100 }) @@ -456,6 +457,7 @@ test("same-key repeat concurrency creates one free event", async () => { const editorialId = await seedEditorial(); const { usageService, downloadService } = createServices(); const first = await usageService.createNewUsage(newInput(editorialId)); + await markDelivered(first.id); const repeatInput = { editorialId, usageId: first.usageId, @@ -476,7 +478,7 @@ test("same-key repeat concurrency creates one free event", async () => { expect(eventCount.value).toBe(1); }); -test("returns a repeat winner committed while waiting before later suspension is checked", async () => { +test("rechecks suspension after an idempotent repeat winner commits", async () => { const editorialId = await seedEditorial(); const { usageService } = createServices(); const first = await usageService.createNewUsage(newInput(editorialId)); @@ -486,20 +488,8 @@ test("returns a repeat winner committed while waiting before later suspension is note: "Web-Ausgabe", idempotencyKey: randomUUID(), }; - const realRepository = createRepeatDownloadRepository(database); - let releaseFastMiss!: () => void; - const fastMiss = new Promise((resolve) => { - releaseFastMiss = resolve; - }); const downloadService = createDownloadService({ - repository: { - ...realRepository, - async findIntent(requestEditorialId, key) { - const intent = await realRepository.findIntent(requestEditorialId, key); - releaseFastMiss(); - return intent; - }, - }, + repository: createRepeatDownloadRepository(database), }); const eventId = randomUUID(); const authorizedAt = new Date("2026-08-09T11:00:00.000Z"); @@ -509,7 +499,6 @@ test("returns a repeat winner committed while waiting before later suspension is try { const pending = downloadService.createRepeatDownload(input); - await fastMiss; await locker.query( `insert into download_events ( id, editorial_account_id, usage_id, immich_asset_id, authorized_at, @@ -538,15 +527,7 @@ test("returns a repeat winner committed while waiting before later suspension is ]); await locker.query("commit"); - await expect(pending).resolves.toEqual({ - id: eventId, - usageId: first.usageId, - assetId, - priceCents: 0, - billable: false, - status: "authorized", - authorizedAt, - }); + await expect(pending).rejects.toMatchObject({ code: "EDITORIAL_NOT_ACTIVE" }); } finally { await locker.query("rollback"); locker.release(); @@ -585,3 +566,16 @@ test("repeat ownership is scoped to the active editorial", async () => { }), ).rejects.toMatchObject({ code: "USAGE_NOT_FOUND" }); }); + +async function markDelivered(downloadId: string): Promise { + const deliveredAt = new Date(); + await database + .update(downloadEvents) + .set({ + status: "completed", + startedAt: deliveredAt, + completedAt: deliveredAt, + transferredBytes: 1, + }) + .where(eq(downloadEvents.id, downloadId)); +}