diff --git a/drizzle/0002_accounting_intents.sql b/drizzle/0002_accounting_intents.sql new file mode 100644 index 0000000..c386136 --- /dev/null +++ b/drizzle/0002_accounting_intents.sql @@ -0,0 +1,7 @@ +ALTER TABLE "download_events" ADD COLUMN "intent_kind" text DEFAULT 'new_usage' NOT NULL;--> statement-breakpoint +ALTER TABLE "download_events" ADD COLUMN "request_fingerprint" varchar(64);--> statement-breakpoint +UPDATE "download_events" +SET "request_fingerprint" = md5("editorial_account_id"::text || ':' || "id"::text) || md5("id"::text || ':' || "editorial_account_id"::text);--> statement-breakpoint +ALTER TABLE "download_events" ALTER COLUMN "request_fingerprint" 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'));--> statement-breakpoint +ALTER TABLE "download_events" ADD CONSTRAINT "download_events_request_fingerprint_hex_check" CHECK ("download_events"."request_fingerprint" ~ '^[0-9a-f]{64}$'); diff --git a/drizzle/meta/0002_snapshot.json b/drizzle/meta/0002_snapshot.json new file mode 100644 index 0000000..6f1926f --- /dev/null +++ b/drizzle/meta/0002_snapshot.json @@ -0,0 +1,1472 @@ +{ + "id": "0cdb7b32-1eb5-4dcf-9949-3862dbbad2b4", + "prevId": "cfd5f4d1-55ac-46d9-9667-cd156f26e070", + "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": {} + } + }, + "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": {}, + "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 + } + }, + "indexes": { + "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')" + }, + "download_events_request_fingerprint_hex_check": { + "name": "download_events_request_fingerprint_hex_check", + "value": "\"download_events\".\"request_fingerprint\" ~ '^[0-9a-f]{64}$'" + } + }, + "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": {}, + "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": {}, + "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" + ] + } + }, + "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 3201171..6a7c747 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -15,6 +15,13 @@ "when": 1786303607054, "tag": "0001_editorial_approval_notice", "breakpoints": true + }, + { + "idx": 2, + "version": "7", + "when": 1786308409516, + "tag": "0002_accounting_intents", + "breakpoints": true } ] } \ No newline at end of file diff --git a/src/db/schema/usages.ts b/src/db/schema/usages.ts index 11c7bed..bba0bb7 100644 --- a/src/db/schema/usages.ts +++ b/src/db/schema/usages.ts @@ -1,4 +1,16 @@ -import { integer, pgEnum, pgTable, text, timestamp, uniqueIndex, uuid, bigint } from "drizzle-orm/pg-core"; +import { sql } from "drizzle-orm"; +import { + bigint, + check, + integer, + pgEnum, + pgTable, + text, + timestamp, + uniqueIndex, + uuid, + varchar, +} from "drizzle-orm/pg-core"; import { editorialAccounts } from "./editorials"; import { billingReports } from "./billing"; @@ -53,11 +65,21 @@ export const downloadEvents = pgTable( repeatDownloadNote: text("repeat_download_note"), requestId: uuid("request_id").notNull(), idempotencyKey: text("idempotency_key").notNull(), + intentKind: text("intent_kind").notNull().default("new_usage"), + requestFingerprint: varchar("request_fingerprint", { length: 64 }).notNull(), }, (table) => [ uniqueIndex("download_events_editorial_idempotency_key_unique").on( table.editorialAccountId, table.idempotencyKey, ), + check( + "download_events_intent_kind_check", + sql`${table.intentKind} in ('new_usage', 'repeat_download')`, + ), + check( + "download_events_request_fingerprint_hex_check", + sql`${table.requestFingerprint} ~ '^[0-9a-f]{64}$'`, + ), ], ); diff --git a/src/modules/downloads/service.test.ts b/src/modules/downloads/service.test.ts new file mode 100644 index 0000000..12052fa --- /dev/null +++ b/src/modules/downloads/service.test.ts @@ -0,0 +1,150 @@ +import { expect, test, vi } from "vitest"; + +import { + createDownloadService, + type PersistedRepeatIntent, + type RepeatDownloadRepository, + type RepeatIntentInput, +} from "./service"; +import { UsageAccountingError } from "@/modules/usages/types"; + +const editorialId = "11111111-1111-4111-8111-111111111111"; +const usageId = "44444444-4444-4444-8444-444444444444"; +const idempotencyKey = "55555555-5555-4555-8555-555555555555"; + +function createService() { + const intents = new Map(); + const events: RepeatIntentInput[] = []; + let active = 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"); + const key = `${input.editorialId}:${input.idempotencyKey}`; + const existing = intents.get(key); + if (existing) return existing; + events.push(input); + const intent: PersistedRepeatIntent = { + id: `download-${events.length}`, + usageId: input.usageId, + assetId: "asset-1", + priceCents: 0, + billable: false, + status: "authorized", + authorizedAt: new Date("2026-08-09T09:00:00.000Z"), + requestFingerprint: input.requestFingerprint, + kind: "repeat_download", + }; + intents.set(key, intent); + return intent; + }, + }; + + return { + service: createDownloadService({ repository }), + repository, + events, + setActive(value: boolean) { + active = value; + }, + setUsageOwner(value: string) { + usageOwner = value; + }, + setSnapshotPrice(value: number) { + snapshotPrice = value; + }, + getSnapshotPrice() { + return snapshotPrice; + }, + }; +} + +test("creates only a free authorized event for an owned prior usage", async () => { + const { service, events, getSnapshotPrice } = createService(); + + const intent = await service.createRepeatDownload({ + editorialId, + usageId, + note: " erneuter Abruf ", + idempotencyKey, + }); + + expect(intent).toMatchObject({ + usageId, + assetId: "asset-1", + priceCents: 0, + billable: false, + status: "authorized", + }); + expect(events).toEqual([expect.objectContaining({ note: "erneuter Abruf" })]); + expect(getSnapshotPrice()).toBe(1_500); +}); + +test("a changed usage snapshot price never changes the free repeat price", async () => { + const { service, setSnapshotPrice } = createService(); + setSnapshotPrice(9_900); + + await expect( + service.createRepeatDownload({ editorialId, usageId, idempotencyKey }), + ).resolves.toMatchObject({ priceCents: 0, billable: false }); +}); + +test("rejects a usage owned by another editorial without creating an event", async () => { + const { service, events, setUsageOwner } = createService(); + setUsageOwner("66666666-6666-4666-8666-666666666666"); + + await expect( + service.createRepeatDownload({ editorialId, usageId, idempotencyKey }), + ).rejects.toMatchObject({ code: "USAGE_NOT_FOUND" }); + expect(events).toHaveLength(0); +}); + +test("rejects a repeat for an inactive editorial", async () => { + const { service, events, setActive } = createService(); + setActive(false); + + await expect( + service.createRepeatDownload({ editorialId, usageId, idempotencyKey }), + ).rejects.toMatchObject({ code: "EDITORIAL_NOT_ACTIVE" }); + expect(events).toHaveLength(0); +}); + +test("returns the same free intent once for an equivalent retry", async () => { + const { service, events } = createService(); + const input = { editorialId, usageId, note: "noch einmal", idempotencyKey }; + + const first = await service.createRepeatDownload(input); + const second = await service.createRepeatDownload(input); + + expect(second).toEqual(first); + expect(events).toHaveLength(1); +}); + +test("rejects reuse of a repeat key with a materially different note", async () => { + const { service, events } = createService(); + await service.createRepeatDownload({ editorialId, usageId, note: "Web", idempotencyKey }); + + await expect( + service.createRepeatDownload({ editorialId, usageId, note: "Print", idempotencyKey }), + ).rejects.toMatchObject({ code: "IDEMPOTENCY_CONFLICT" }); + expect(events).toHaveLength(1); +}); + +test.each([ + ["x".repeat(201), idempotencyKey], + [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"); + + await expect( + service.createRepeatDownload({ editorialId, usageId, note, idempotencyKey: key }), + ).rejects.toMatchObject({ code: "INVALID_INPUT" }); + expect(findIntent).not.toHaveBeenCalled(); +}); diff --git a/src/modules/downloads/service.ts b/src/modules/downloads/service.ts new file mode 100644 index 0000000..d507155 --- /dev/null +++ b/src/modules/downloads/service.ts @@ -0,0 +1,177 @@ +import "server-only"; + +import { randomUUID } from "node:crypto"; + +import { and, eq } from "drizzle-orm"; +import type { NodePgDatabase } from "drizzle-orm/node-postgres"; + +import { db } from "@/db/client"; +import { downloadEvents, editorialAccounts, usages } from "@/db/schema"; +import type * as schema from "@/db/schema"; +import { + assertUuid, + type CreateRepeatDownloadInput, + type DownloadIntent, + normalizeOptionalText, + requestFingerprint, + UsageAccountingError, +} from "@/modules/usages/types"; +import { + findPersistedIntent, + lockEditorialAccounting, + resolveIntent, + type PersistedDownloadIntent, +} from "@/modules/usages/service"; + +export type PersistedRepeatIntent = PersistedDownloadIntent & { kind: "repeat_download" }; + +export type RepeatIntentInput = { + editorialId: string; + usageId: string; + note?: string; + idempotencyKey: string; + requestFingerprint: string; +}; + +export type RepeatDownloadRepository = { + findIntent(editorialId: string, idempotencyKey: string): Promise; + createRepeatIntent(input: RepeatIntentInput): Promise; +}; + +export function createDownloadService({ repository }: { repository: RepeatDownloadRepository }) { + return { + async createRepeatDownload(rawInput: CreateRepeatDownloadInput): Promise { + const input = normalizeRepeatInput(rawInput); + const fingerprint = requestFingerprint({ + kind: "repeat_download", + editorialId: input.editorialId, + 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, + }); + return resolveIntent(persisted, fingerprint, "repeat_download"); + }, + }; +} + +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 [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 existing = await findPersistedIntent( + transaction, + input.editorialId, + input.idempotencyKey, + ); + if (existing) return asRepeatIntent(existing); + + const [usage] = await transaction + .select({ id: usages.id, assetId: usages.immichAssetId }) + .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 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; + } + }, + }; +} + +function normalizeRepeatInput(input: CreateRepeatDownloadInput): CreateRepeatDownloadInput { + if (!input || typeof input !== "object") throw new UsageAccountingError("INVALID_INPUT"); + assertUuid(input.editorialId); + assertUuid(input.usageId); + assertUuid(input.idempotencyKey); + const note = normalizeOptionalText(input.note, 200); + return { + editorialId: input.editorialId, + usageId: input.usageId, + ...(note === undefined ? {} : { note }), + idempotencyKey: input.idempotencyKey, + }; +} + +function asRepeatIntent(intent: PersistedDownloadIntent): PersistedRepeatIntent { + if (intent.kind !== "repeat_download") { + throw new UsageAccountingError("IDEMPOTENCY_CONFLICT"); + } + return { ...intent, kind: "repeat_download" }; +} + +class RepeatIdempotencyRaceError extends Error {} + +export const downloadService = createDownloadService({ + repository: createRepeatDownloadRepository(db), +}); + +export const createRepeatDownload = downloadService.createRepeatDownload; diff --git a/src/modules/immich/client.test.ts b/src/modules/immich/client.test.ts index b700169..568dde7 100644 --- a/src/modules/immich/client.test.ts +++ b/src/modules/immich/client.test.ts @@ -6,6 +6,7 @@ import { createImmichClient } from "./client"; import { immichAlbum, immichAlbumDetail, + immichAsset, immichMetadataSearchResponse, } from "../../../tests/fixtures/immich"; @@ -73,6 +74,18 @@ test("gets album details from the documented album endpoint", async () => { await expect(client.getAlbum("album-1")).resolves.toEqual(immichAlbumDetail); }); +test("gets current asset metadata immediately before accounting", async () => { + server.use( + http.get(`${baseUrl}/api/assets/asset-1`, ({ request }) => { + expect(request.method).toBe("GET"); + expect(request.headers.get("x-api-key")).toBe(apiKey); + return HttpResponse.json(immichAsset); + }), + ); + + await expect(client.getAsset("asset-1")).resolves.toEqual(immichAsset); +}); + test("forces IMAGE and authorized album IDs in metadata search", async () => { server.use( http.post(`${baseUrl}/api/search/metadata`, async ({ request }) => { diff --git a/src/modules/immich/client.ts b/src/modules/immich/client.ts index a5f1e2e..1ea6d5a 100644 --- a/src/modules/immich/client.ts +++ b/src/modules/immich/client.ts @@ -8,6 +8,7 @@ import { ImmichClientError, type ImmichErrorCode } from "./errors"; import type { ImmichAlbum, ImmichAlbumSummary, + ImmichAsset, ImmichBinary, ImmichClient, ImmichSearchPage, @@ -27,6 +28,10 @@ const assetSchema = z }) .passthrough(); +const currentAssetSchema = assetSchema.extend({ + type: z.enum(["IMAGE", "VIDEO"]), +}); + const albumSummarySchema = z .object({ id: z.string(), @@ -325,6 +330,14 @@ export function createImmichClient({ signal, ); }, + getAsset(assetId, signal) { + return requestJson( + `/assets/${encodeURIComponent(assetId)}`, + { method: "GET" }, + currentAssetSchema, + signal, + ); + }, searchPhotos(input, signal) { return requestJson( "/search/metadata", diff --git a/src/modules/immich/types.ts b/src/modules/immich/types.ts index 242bcac..74e8ba9 100644 --- a/src/modules/immich/types.ts +++ b/src/modules/immich/types.ts @@ -8,7 +8,7 @@ export type ImmichAlbumSummary = { export type ImmichAsset = { id: string; - type: "IMAGE"; + type: "IMAGE" | "VIDEO"; originalFileName: string; originalMimeType: string; localDateTime: string | null; @@ -38,6 +38,7 @@ export interface ImmichClient { listAlbums(signal?: AbortSignal): Promise; listAlbumsForAsset(assetId: string, signal?: AbortSignal): Promise; getAlbum(albumId: string, signal?: AbortSignal): Promise; + getAsset(assetId: string, signal?: AbortSignal): Promise; searchPhotos( input: { albumIds: string[]; description?: string; page: number; size: number; type?: "IMAGE" }, signal?: AbortSignal, diff --git a/src/modules/usages/service.test.ts b/src/modules/usages/service.test.ts new file mode 100644 index 0000000..a1360e9 --- /dev/null +++ b/src/modules/usages/service.test.ts @@ -0,0 +1,271 @@ +import { expect, test, vi } from "vitest"; + +import { + createUsageService, + type BillableIntentInput, + type PersistedDownloadIntent, + type UsageRepository, +} from "./service"; +import { UsageAccountingError, type PriorUsage } from "./types"; + +const editorialId = "11111111-1111-4111-8111-111111111111"; +const idempotencyKey = "22222222-2222-4222-8222-222222222222"; + +const newUsageInput = { + editorialId, + assetId: "asset-1", + albumId: "album-1", + purpose: "Titelgeschichte", + reference: "Ausgabe 8/26", + idempotencyKey, +}; + +function createRepository() { + const intents = new Map(); + const usages: BillableIntentInput[] = []; + const priorUsages: PriorUsage[] = []; + let priceCents: number | null = 1_500; + let status = "active"; + + const repository: UsageRepository = { + async findIntent(requestEditorialId, key) { + return intents.get(`${requestEditorialId}:${key}`) ?? null; + }, + async createBillableIntent(input) { + if (status !== "active") { + throw new UsageAccountingError("EDITORIAL_NOT_ACTIVE"); + } + if (!Number.isSafeInteger(priceCents) || (priceCents ?? 0) <= 0) { + throw new UsageAccountingError("INVALID_PRICE"); + } + const key = `${input.editorialId}:${input.idempotencyKey}`; + const existing = intents.get(key); + if (existing) return existing; + + usages.push(input); + const intent: PersistedDownloadIntent = { + id: `download-${intents.size + 1}`, + usageId: `usage-${usages.length}`, + assetId: input.assetId, + priceCents: priceCents!, + billable: true, + status: "authorized", + authorizedAt: new Date("2026-08-09T08:00:00.000Z"), + requestFingerprint: input.requestFingerprint, + kind: "new_usage", + }; + intents.set(key, intent); + return intent; + }, + async listPriorUsages() { + return priorUsages; + }, + }; + + return { + repository, + intents, + usages, + priorUsages, + setPrice(value: number | null) { + priceCents = value; + }, + setStatus(value: string) { + status = value; + }, + }; +} + +function createService() { + const state = createRepository(); + const immich = { + listAlbumsForAsset: vi.fn().mockResolvedValue([ + { + id: "album-1", + albumName: "Presse 2026", + description: null, + albumThumbnailAssetId: "asset-1", + assetCount: 1, + }, + ]), + getAsset: vi.fn().mockResolvedValue({ + id: "asset-1", + type: "IMAGE" as const, + originalFileName: "jubel.jpg", + originalMimeType: "image/jpeg", + localDateTime: null, + fileCreatedAt: null, + albums: [{ id: "album-1" }], + }), + }; + return { ...state, immich, service: createUsageService({ repository: state.repository, immich }) }; +} + +test("snapshots the current editorial price and normalized Immich metadata", async () => { + const { service, usages } = createService(); + + const intent = await service.createNewUsage({ + ...newUsageInput, + purpose: " Titelgeschichte ", + reference: " Ausgabe 8/26 ", + }); + + expect(intent).toMatchObject({ priceCents: 1_500, billable: true, status: "authorized" }); + expect(usages).toEqual([ + expect.objectContaining({ + assetId: "asset-1", + albumId: "album-1", + albumName: "Presse 2026", + filename: "jubel.jpg", + purpose: "Titelgeschichte", + reference: "Ausgabe 8/26", + }), + ]); +}); + +test("returns the exact persisted intent for an equivalent idempotent retry", async () => { + const { service, usages, immich } = createService(); + + const first = await service.createNewUsage(newUsageInput); + const second = await service.createNewUsage(newUsageInput); + + expect(second).toEqual(first); + expect(usages).toHaveLength(1); + expect(immich.getAsset).toHaveBeenCalledTimes(1); +}); + +test("keeps the original snapshot after a price change while a new key uses the new price", async () => { + const { service, setPrice } = createService(); + const original = await service.createNewUsage(newUsageInput); + setPrice(2_100); + + await expect(service.createNewUsage(newUsageInput)).resolves.toEqual(original); + await expect( + service.createNewUsage({ + ...newUsageInput, + idempotencyKey: "33333333-3333-4333-8333-333333333333", + }), + ).resolves.toMatchObject({ priceCents: 2_100 }); +}); + +test.each([ + ["zero", 0], + ["missing", null], +] as const)("rejects a %s current price", async (_label, price) => { + const { service, setPrice } = createService(); + setPrice(price); + + await expect(service.createNewUsage(newUsageInput)).rejects.toMatchObject({ + code: "INVALID_PRICE", + }); +}); + +test.each(["suspended", "pending_approval"])("rejects a %s editorial account", async (status) => { + const { service, setStatus } = createService(); + setStatus(status); + + await expect(service.createNewUsage(newUsageInput)).rejects.toMatchObject({ + code: "EDITORIAL_NOT_ACTIVE", + }); +}); + +test.each([ + ["ab", "INVALID_INPUT"], + ["x".repeat(201), "INVALID_INPUT"], + ["Titelgeschichte", "INVALID_INPUT", "x".repeat(201)], + ["Titelgeschichte", "INVALID_INPUT", undefined, "not-a-uuid"], +] as const)( + "rejects malformed purpose, reference, or idempotency input before side effects", + async (purpose: string, code: string, reference?: string, key?: string) => { + const { service, repository, immich } = createService(); + const findIntent = vi.spyOn(repository, "findIntent"); + + await expect( + service.createNewUsage({ + ...newUsageInput, + purpose, + reference: reference ?? "Ausgabe 8/26", + idempotencyKey: key ?? idempotencyKey, + }), + ).rejects.toMatchObject({ code }); + expect(findIntent).not.toHaveBeenCalled(); + expect(immich.listAlbumsForAsset).not.toHaveBeenCalled(); + expect(immich.getAsset).not.toHaveBeenCalled(); + }, +); + +test("rejects an asset outside the exact requested album", async () => { + const { service, immich, usages } = createService(); + immich.listAlbumsForAsset.mockResolvedValue([ + { + id: "album-2", + albumName: "Andere Bilder", + description: null, + albumThumbnailAssetId: null, + assetCount: 1, + }, + ]); + + await expect(service.createNewUsage(newUsageInput)).rejects.toMatchObject({ + code: "ASSET_NOT_IN_ALBUM", + }); + expect(immich.getAsset).not.toHaveBeenCalled(); + expect(usages).toHaveLength(0); +}); + +test("rejects a missing asset immediately before accounting", async () => { + const { service, immich, usages } = createService(); + immich.getAsset.mockRejectedValue({ code: "IMMICH_NOT_FOUND" }); + + await expect(service.createNewUsage(newUsageInput)).rejects.toMatchObject({ + code: "ASSET_NOT_FOUND", + }); + expect(usages).toHaveLength(0); +}); + +test("rejects a non-image asset immediately before accounting", async () => { + const { service, immich, usages } = createService(); + immich.getAsset.mockResolvedValue({ + id: "asset-1", + type: "VIDEO", + originalFileName: "clip.mp4", + originalMimeType: "video/mp4", + localDateTime: null, + fileCreatedAt: null, + albums: [{ id: "album-1" }], + }); + + await expect(service.createNewUsage(newUsageInput)).rejects.toMatchObject({ + code: "ASSET_NOT_IMAGE", + }); + expect(usages).toHaveLength(0); +}); + +test("rejects reuse of an idempotency key for a materially different new usage", async () => { + const { service, usages, immich } = createService(); + await service.createNewUsage(newUsageInput); + + await expect( + service.createNewUsage({ ...newUsageInput, purpose: "Online-Aufmacher" }), + ).rejects.toMatchObject({ code: "IDEMPOTENCY_CONFLICT" }); + expect(usages).toHaveLength(1); + expect(immich.getAsset).toHaveBeenCalledTimes(1); +}); + +test("lists only the repository's prior usages for the requested editorial asset", async () => { + const { service, priorUsages } = createService(); + priorUsages.push({ + id: "usage-1", + assetId: "asset-1", + filename: "jubel.jpg", + albumId: "album-1", + albumName: "Presse 2026", + purpose: "Titelgeschichte", + reference: undefined, + priceCents: 1_500, + billingStatus: "open", + createdAt: new Date("2026-08-09T08:00:00.000Z"), + }); + + await expect(service.listPriorUsages(editorialId, "asset-1")).resolves.toEqual(priorUsages); +}); diff --git a/src/modules/usages/service.ts b/src/modules/usages/service.ts new file mode 100644 index 0000000..fa8f658 --- /dev/null +++ b/src/modules/usages/service.ts @@ -0,0 +1,422 @@ +import "server-only"; + +import { randomUUID } from "node:crypto"; + +import { and, desc, eq, isNull, sql } from "drizzle-orm"; +import type { NodePgDatabase } from "drizzle-orm/node-postgres"; + +import { db } from "@/db/client"; +import { + albumGrants, + auditEvents, + downloadEvents, + editorialAccounts, + usages, +} from "@/db/schema"; +import type * as schema from "@/db/schema"; +import { immichClient } from "@/modules/immich/client"; +import type { ImmichAlbumSummary } from "@/modules/immich/types"; + +import { + assertImmichIdentifier, + assertUuid, + type CreateNewUsageInput, + type DownloadIntent, + normalizeOptionalText, + normalizeRequiredText, + type PriorUsage, + requestFingerprint, + UsageAccountingError, +} from "./types"; + +export type PersistedDownloadIntent = DownloadIntent & { + requestFingerprint: string; + kind: "new_usage" | "repeat_download"; +}; + +export type BillableIntentInput = { + editorialId: string; + assetId: string; + albumId: string; + albumName: string; + filename: string; + purpose: string; + reference?: string; + idempotencyKey: string; + requestFingerprint: string; +}; + +export type UsageRepository = { + findIntent(editorialId: string, idempotencyKey: string): Promise; + createBillableIntent(input: BillableIntentInput): Promise; + listPriorUsages(editorialId: string, assetId: string): Promise; +}; + +type UsageImmich = { + listAlbumsForAsset(assetId: string): Promise; + getAsset(assetId: string): Promise<{ + id: string; + type: string; + originalFileName: string; + }>; +}; + +export function createUsageService({ + repository, + immich, +}: { + repository: UsageRepository; + immich: UsageImmich; +}) { + return { + async createNewUsage(rawInput: CreateNewUsageInput): Promise { + const input = normalizeNewUsageInput(rawInput); + const fingerprint = requestFingerprint({ + kind: "new_usage", + editorialId: input.editorialId, + assetId: input.assetId, + albumId: input.albumId, + purpose: input.purpose, + reference: input.reference ?? null, + }); + + const existing = await repository.findIntent(input.editorialId, input.idempotencyKey); + if (existing) return resolveIntent(existing, fingerprint, "new_usage"); + + const album = await loadRequestedAlbum(immich, input.assetId, input.albumId); + const asset = await loadImageAsset(immich, input.assetId); + const persisted = await repository.createBillableIntent({ + ...input, + albumName: normalizeUpstreamSnapshot(album.albumName), + filename: normalizeUpstreamSnapshot(asset.originalFileName), + requestFingerprint: fingerprint, + }); + return resolveIntent(persisted, fingerprint, "new_usage"); + }, + + async listPriorUsages(editorialId: string, assetId: string): Promise { + assertUuid(editorialId); + assertImmichIdentifier(assetId); + return repository.listPriorUsages(editorialId, assetId); + }, + }; +} + +export function createUsageServiceRepository( + database: NodePgDatabase, +): UsageRepository { + return { + findIntent(editorialId, idempotencyKey) { + return findPersistedIntent(database, editorialId, idempotencyKey); + }, + + async createBillableIntent(input) { + try { + return await database.transaction(async (transaction) => { + await lockEditorialAccounting(transaction, input.editorialId); + const [editorial] = await transaction + .select({ + id: editorialAccounts.id, + status: editorialAccounts.status, + currentPriceCents: editorialAccounts.currentPriceCents, + }) + .from(editorialAccounts) + .where(eq(editorialAccounts.id, input.editorialId)) + .for("update") + .limit(1); + if (!editorial || editorial.status !== "active") { + throw new UsageAccountingError("EDITORIAL_NOT_ACTIVE"); + } + if ( + !Number.isSafeInteger(editorial.currentPriceCents) || + (editorial.currentPriceCents ?? 0) <= 0 + ) { + throw new UsageAccountingError("INVALID_PRICE"); + } + + const [grant] = await transaction + .select({ id: albumGrants.id }) + .from(albumGrants) + .where( + and( + eq(albumGrants.editorialAccountId, input.editorialId), + eq(albumGrants.immichAlbumId, input.albumId), + isNull(albumGrants.revokedAt), + ), + ) + .for("update") + .limit(1); + if (!grant) throw new UsageAccountingError("ALBUM_NOT_GRANTED"); + + const existing = await findPersistedIntentInTransaction( + transaction, + input.editorialId, + input.idempotencyKey, + ); + if (existing) return existing; + + const createdAt = new Date(); + const [usage] = await transaction + .insert(usages) + .values({ + editorialAccountId: input.editorialId, + immichAssetId: input.assetId, + filenameSnapshot: input.filename, + immichAlbumIdSnapshot: input.albumId, + albumNameSnapshot: input.albumName, + purpose: input.purpose, + internalReference: input.reference, + priceCents: editorial.currentPriceCents!, + billingStatus: "open", + createdAt, + }) + .returning({ id: usages.id }); + const requestId = randomUUID(); + const [event] = await transaction + .insert(downloadEvents) + .values({ + editorialAccountId: input.editorialId, + usageId: usage.id, + immichAssetId: input.assetId, + authorizedAt: createdAt, + status: "authorized", + requestId, + idempotencyKey: input.idempotencyKey, + intentKind: "new_usage", + requestFingerprint: input.requestFingerprint, + }) + .onConflictDoNothing({ + target: [downloadEvents.editorialAccountId, downloadEvents.idempotencyKey], + }) + .returning({ id: downloadEvents.id }); + if (!event) throw new IdempotencyRaceError(); + + await transaction.insert(auditEvents).values({ + eventType: "billable_usage_created", + actorType: "editorial", + entityType: "usage", + entityId: usage.id, + newValues: { + editorialId: input.editorialId, + assetId: input.assetId, + albumId: input.albumId, + priceCents: editorial.currentPriceCents, + downloadId: event.id, + }, + occurredAt: createdAt, + requestId, + }); + return { + id: event.id, + usageId: usage.id, + assetId: input.assetId, + priceCents: editorial.currentPriceCents!, + billable: true, + status: "authorized" as const, + authorizedAt: createdAt, + requestFingerprint: input.requestFingerprint, + kind: "new_usage" as const, + }; + }); + } catch (error) { + if (!(error instanceof IdempotencyRaceError)) throw error; + const existing = await findPersistedIntent( + database, + input.editorialId, + input.idempotencyKey, + ); + if (existing) return existing; + throw error; + } + }, + + async listPriorUsages(editorialId, assetId) { + const rows = await database + .select({ + id: usages.id, + assetId: usages.immichAssetId, + filename: usages.filenameSnapshot, + albumId: usages.immichAlbumIdSnapshot, + albumName: usages.albumNameSnapshot, + purpose: usages.purpose, + reference: usages.internalReference, + priceCents: usages.priceCents, + billingStatus: usages.billingStatus, + createdAt: usages.createdAt, + }) + .from(usages) + .where( + and( + eq(usages.editorialAccountId, editorialId), + eq(usages.immichAssetId, assetId), + ), + ) + .orderBy(desc(usages.createdAt)); + return rows.map((row) => ({ ...row, reference: row.reference ?? undefined })); + }, + }; +} + +function normalizeNewUsageInput(input: CreateNewUsageInput): CreateNewUsageInput { + if (!input || typeof input !== "object") throw new UsageAccountingError("INVALID_INPUT"); + assertUuid(input.editorialId); + assertImmichIdentifier(input.assetId); + assertImmichIdentifier(input.albumId); + assertUuid(input.idempotencyKey); + const purpose = normalizeRequiredText(input.purpose, 3, 200); + const reference = normalizeOptionalText(input.reference, 200); + return { + editorialId: input.editorialId, + assetId: input.assetId, + albumId: input.albumId, + purpose, + ...(reference === undefined ? {} : { reference }), + idempotencyKey: input.idempotencyKey, + }; +} + +async function loadRequestedAlbum( + immich: UsageImmich, + assetId: string, + albumId: string, +): Promise { + let albums: ImmichAlbumSummary[]; + try { + albums = await immich.listAlbumsForAsset(assetId); + } catch { + throw new UsageAccountingError("IMMICH_UNAVAILABLE"); + } + const album = albums.find((candidate) => candidate.id === albumId); + if (!album) throw new UsageAccountingError("ASSET_NOT_IN_ALBUM"); + return album; +} + +async function loadImageAsset(immich: UsageImmich, assetId: string) { + let asset: Awaited>; + try { + asset = await immich.getAsset(assetId); + } catch (error) { + if (hasCode(error, "IMMICH_NOT_FOUND")) throw new UsageAccountingError("ASSET_NOT_FOUND"); + throw new UsageAccountingError("IMMICH_UNAVAILABLE"); + } + if (asset.id !== assetId) throw new UsageAccountingError("IMMICH_UNAVAILABLE"); + if (asset.type !== "IMAGE") throw new UsageAccountingError("ASSET_NOT_IMAGE"); + return asset; +} + +function normalizeUpstreamSnapshot(value: string): string { + const normalized = value.trim(); + if (!normalized) throw new UsageAccountingError("IMMICH_UNAVAILABLE"); + return normalized; +} + +function hasCode(error: unknown, code: string): boolean { + return typeof error === "object" && error !== null && "code" in error && error.code === code; +} + +export function resolveIntent( + persisted: PersistedDownloadIntent, + fingerprint: string, + kind: PersistedDownloadIntent["kind"], +): DownloadIntent { + if (persisted.requestFingerprint !== fingerprint || persisted.kind !== kind) { + throw new UsageAccountingError("IDEMPOTENCY_CONFLICT"); + } + const { requestFingerprint: _fingerprint, kind: _kind, ...intent } = persisted; + return intent; +} + +class IdempotencyRaceError extends Error {} + +export async function findPersistedIntent( + database: NodePgDatabase, + editorialId: string, + idempotencyKey: string, +): Promise { + const [row] = await database + .select(intentSelection) + .from(downloadEvents) + .innerJoin(usages, eq(usages.id, downloadEvents.usageId)) + .where( + and( + eq(downloadEvents.editorialAccountId, editorialId), + eq(downloadEvents.idempotencyKey, idempotencyKey), + ), + ) + .limit(1); + return row ? persistedIntent(row) : null; +} + +async function findPersistedIntentInTransaction( + transaction: NodePgDatabase, + editorialId: string, + idempotencyKey: string, +): Promise { + const [row] = await transaction + .select(intentSelection) + .from(downloadEvents) + .innerJoin(usages, eq(usages.id, downloadEvents.usageId)) + .where( + and( + eq(downloadEvents.editorialAccountId, editorialId), + eq(downloadEvents.idempotencyKey, idempotencyKey), + ), + ) + .limit(1); + return row ? persistedIntent(row) : null; +} + +const intentSelection = { + id: downloadEvents.id, + usageId: downloadEvents.usageId, + assetId: downloadEvents.immichAssetId, + authorizedAt: downloadEvents.authorizedAt, + intentKind: downloadEvents.intentKind, + requestFingerprint: downloadEvents.requestFingerprint, + usagePriceCents: usages.priceCents, +}; + +function persistedIntent(row: { + id: string; + usageId: string; + assetId: string; + authorizedAt: Date; + intentKind: string; + requestFingerprint: string; + usagePriceCents: number; +}): PersistedDownloadIntent { + if ( + row.intentKind !== "new_usage" && + row.intentKind !== "repeat_download" + ) { + throw new UsageAccountingError("IDEMPOTENCY_CONFLICT"); + } + return { + id: row.id, + usageId: row.usageId, + assetId: row.assetId, + priceCents: row.intentKind === "new_usage" ? row.usagePriceCents : 0, + billable: row.intentKind === "new_usage", + status: "authorized", + authorizedAt: row.authorizedAt, + requestFingerprint: row.requestFingerprint, + kind: row.intentKind, + }; +} + +export async function lockEditorialAccounting( + transaction: NodePgDatabase, + editorialId: string, +): Promise { + await transaction.execute( + sql`select pg_advisory_xact_lock(hashtextextended(${editorialId}, 0))`, + ); +} + +export const usageService = createUsageService({ + repository: createUsageServiceRepository(db), + immich: immichClient, +}); + +export const createNewUsage = usageService.createNewUsage; +export const listPriorUsages = usageService.listPriorUsages; diff --git a/src/modules/usages/types.ts b/src/modules/usages/types.ts new file mode 100644 index 0000000..53c4d09 --- /dev/null +++ b/src/modules/usages/types.ts @@ -0,0 +1,113 @@ +import { createHash } from "node:crypto"; + +export type CreateNewUsageInput = { + editorialId: string; + assetId: string; + albumId: string; + purpose: string; + reference?: string; + idempotencyKey: string; +}; + +export type CreateRepeatDownloadInput = { + editorialId: string; + usageId: string; + note?: string; + idempotencyKey: string; +}; + +export type DownloadIntent = { + id: string; + usageId: string; + assetId: string; + priceCents: number; + billable: boolean; + status: "authorized"; + authorizedAt: Date; +}; + +export type PriorUsage = { + id: string; + assetId: string; + filename: string; + albumId: string; + albumName: string; + purpose: string; + reference: string | undefined; + priceCents: number; + billingStatus: "open" | "billed" | "reopened"; + createdAt: Date; +}; + +export type UsageAccountingErrorCode = + | "INVALID_INPUT" + | "IDEMPOTENCY_CONFLICT" + | "EDITORIAL_NOT_ACTIVE" + | "INVALID_PRICE" + | "ALBUM_NOT_GRANTED" + | "ASSET_NOT_IN_ALBUM" + | "ASSET_NOT_FOUND" + | "ASSET_NOT_IMAGE" + | "IMMICH_UNAVAILABLE" + | "USAGE_NOT_FOUND"; + +export class UsageAccountingError extends Error { + readonly name = "UsageAccountingError"; + + constructor(readonly code: UsageAccountingErrorCode) { + super(code); + } +} + +type FingerprintPayload = + | { + kind: "new_usage"; + editorialId: string; + assetId: string; + albumId: string; + purpose: string; + reference: string | null; + } + | { + kind: "repeat_download"; + editorialId: string; + usageId: string; + note: string | null; + }; + +export function requestFingerprint(payload: FingerprintPayload): string { + return createHash("sha256").update(JSON.stringify(payload)).digest("hex"); +} + +export function normalizeRequiredText(value: unknown, minimum: number, maximum: number): string { + if (typeof value !== "string") throw new UsageAccountingError("INVALID_INPUT"); + const normalized = value.trim(); + const length = [...normalized].length; + if (length < minimum || length > maximum) { + throw new UsageAccountingError("INVALID_INPUT"); + } + return normalized; +} + +export function normalizeOptionalText(value: unknown, maximum: number): string | undefined { + if (value === undefined) return undefined; + if (typeof value !== "string") throw new UsageAccountingError("INVALID_INPUT"); + const normalized = value.trim(); + if ([...normalized].length > maximum) throw new UsageAccountingError("INVALID_INPUT"); + return normalized || undefined; +} + +export function assertUuid(value: unknown): asserts value is 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 UsageAccountingError("INVALID_INPUT"); + } +} + +export function assertImmichIdentifier(value: unknown): asserts value is string { + if (typeof value !== "string" || !/^[A-Za-z0-9_-]{1,200}$/.test(value)) { + throw new UsageAccountingError("INVALID_INPUT"); + } +} diff --git a/tests/db/postgres.ts b/tests/db/postgres.ts index 3527c75..f2faefb 100644 --- a/tests/db/postgres.ts +++ b/tests/db/postgres.ts @@ -15,6 +15,8 @@ type DownloadSeed = { }; export type PostgresTestDatabase = { + database: NodePgDatabase; + pool: Pool; seedEditorialWithUsage(): Promise; insertDownload(input: DownloadSeed & { idempotencyKey: string }): Promise; stop(): Promise; @@ -33,6 +35,8 @@ export async function startPostgres(): Promise { const db = drizzle({ client: pool, schema }); return { + database: db, + pool, async seedEditorialWithUsage() { return seedEditorialWithUsage(db); }, @@ -43,6 +47,7 @@ export async function startPostgres(): Promise { immichAssetId: input.assetId, requestId: randomUUID(), idempotencyKey: input.idempotencyKey, + requestFingerprint: "0".repeat(64), }); }, async stop() { diff --git a/tests/db/usage-accounting.test.ts b/tests/db/usage-accounting.test.ts new file mode 100644 index 0000000..e47d776 --- /dev/null +++ b/tests/db/usage-accounting.test.ts @@ -0,0 +1,333 @@ +import { randomUUID } from "node:crypto"; + +import { and, count, eq } from "drizzle-orm"; +import { afterAll, expect, test, vi } from "vitest"; + +import { + albumGrants, + auditEvents, + downloadEvents, + editorialAccounts, + usages, + users, +} from "@/db/schema"; +import { + createUsageService, + createUsageServiceRepository, +} from "@/modules/usages/service"; +import { + createDownloadService, + createRepeatDownloadRepository, +} from "@/modules/downloads/service"; +import { startPostgres } from "./postgres"; + +const testDb = await startPostgres(); +const database = testDb.database; + +afterAll(() => testDb.stop()); + +const asset = { + id: "asset-1", + type: "IMAGE" as const, + originalFileName: "jubel.jpg", + originalMimeType: "image/jpeg", + localDateTime: null, + fileCreatedAt: null, + albums: [{ id: "album-1" }], +}; + +function createServices() { + const immich = { + listAlbumsForAsset: vi.fn().mockResolvedValue([ + { + id: "album-1", + albumName: "Presse 2026", + description: null, + albumThumbnailAssetId: "asset-1", + assetCount: 1, + }, + ]), + getAsset: vi.fn().mockResolvedValue(asset), + }; + return { + usageService: createUsageService({ + repository: createUsageServiceRepository(database), + immich, + }), + downloadService: createDownloadService({ + repository: createRepeatDownloadRepository(database), + }), + immich, + }; +} + +async function seedEditorial({ + status = "active", + priceCents = 1_500, + albumId = "album-1", + revoked = false, +}: { + status?: "active" | "suspended" | "pending_approval"; + priceCents?: number | null; + albumId?: string; + revoked?: boolean; +} = {}) { + const userId = randomUUID(); + const editorialId = randomUUID(); + await database.insert(users).values({ + id: userId, + name: "Test Redaktion", + email: `${userId}@example.com`, + emailVerified: true, + }); + await database.insert(editorialAccounts).values({ + id: editorialId, + userId, + name: "Test Redaktion", + contactName: "Testkontakt", + loginEmail: `${userId}@example.com`, + status, + currentPriceCents: priceCents, + }); + await database.insert(albumGrants).values({ + editorialAccountId: editorialId, + immichAlbumId: albumId, + revokedAt: revoked ? new Date("2026-08-08T00:00:00.000Z") : null, + }); + return editorialId; +} + +function newInput(editorialId: string, idempotencyKey = randomUUID()) { + return { + editorialId, + assetId: "asset-1", + albumId: "album-1", + purpose: "Titelgeschichte", + reference: "Ausgabe 8/26", + idempotencyKey, + }; +} + +test("atomically snapshots price and metadata, authorizes one event, and audits no secrets", async () => { + const editorialId = await seedEditorial(); + const { usageService } = createServices(); + const input = newInput(editorialId); + + const intent = await usageService.createNewUsage(input); + + const [usage] = await database.select().from(usages).where(eq(usages.id, intent.usageId)); + const [event] = await database.select().from(downloadEvents).where(eq(downloadEvents.id, intent.id)); + const [audit] = await database + .select() + .from(auditEvents) + .where(and(eq(auditEvents.eventType, "billable_usage_created"), eq(auditEvents.entityId, intent.usageId))); + expect(usage).toMatchObject({ + editorialAccountId: editorialId, + immichAssetId: "asset-1", + filenameSnapshot: "jubel.jpg", + immichAlbumIdSnapshot: "album-1", + albumNameSnapshot: "Presse 2026", + purpose: "Titelgeschichte", + internalReference: "Ausgabe 8/26", + priceCents: 1_500, + billingStatus: "open", + }); + expect(event).toMatchObject({ + editorialAccountId: editorialId, + usageId: intent.usageId, + status: "authorized", + intentKind: "new_usage", + }); + expect(audit).toMatchObject({ actorType: "editorial", entityType: "usage" }); + expect(JSON.stringify(audit)).not.toContain(input.idempotencyKey); + expect(JSON.stringify(audit)).not.toContain("test-immich-key"); +}); + +test.each([ + ["zero price", "active", 0, false, "INVALID_PRICE"], + ["missing price", "active", null, false, "INVALID_PRICE"], + ["suspended account", "suspended", 1_500, false, "EDITORIAL_NOT_ACTIVE"], + ["revoked grant", "active", 1_500, true, "ALBUM_NOT_GRANTED"], +] as const)("rejects %s transactionally without accounting rows", async (_label, status, priceCents, revoked, code) => { + const editorialId = await seedEditorial({ status, priceCents, revoked }); + const { usageService } = createServices(); + + await expect(usageService.createNewUsage(newInput(editorialId))).rejects.toMatchObject({ code }); + const [usageCount] = await database + .select({ value: count() }) + .from(usages) + .where(eq(usages.editorialAccountId, editorialId)); + const [eventCount] = await database + .select({ value: count() }) + .from(downloadEvents) + .where(eq(downloadEvents.editorialAccountId, editorialId)); + expect({ usages: usageCount.value, events: eventCount.value }).toEqual({ usages: 0, events: 0 }); +}); + +test("requires an active grant for the exact requested album", async () => { + const editorialId = await seedEditorial({ albumId: "album-2" }); + const { usageService } = createServices(); + + await expect(usageService.createNewUsage(newInput(editorialId))).rejects.toMatchObject({ + code: "ALBUM_NOT_GRANTED", + }); +}); + +test("same-key concurrency across database clients creates exactly one usage, event, and audit", async () => { + const editorialId = await seedEditorial(); + const { usageService } = createServices(); + const input = newInput(editorialId); + + const [first, second] = await Promise.all([ + usageService.createNewUsage(input), + usageService.createNewUsage(input), + ]); + + expect(second).toEqual(first); + const [usageCount] = await database + .select({ value: count() }) + .from(usages) + .where(eq(usages.editorialAccountId, editorialId)); + const [eventCount] = await database + .select({ value: count() }) + .from(downloadEvents) + .where(eq(downloadEvents.editorialAccountId, editorialId)); + const [auditCount] = await database + .select({ value: count() }) + .from(auditEvents) + .where(and(eq(auditEvents.eventType, "billable_usage_created"), eq(auditEvents.entityId, first.usageId))); + expect({ usages: usageCount.value, events: eventCount.value, audits: auditCount.value }).toEqual({ + usages: 1, + events: 1, + audits: 1, + }); +}); + +test("the same key may be reused by a different editorial but not for a different payload", async () => { + const firstEditorialId = await seedEditorial(); + const secondEditorialId = await seedEditorial(); + const { usageService } = createServices(); + const key = randomUUID(); + await usageService.createNewUsage(newInput(firstEditorialId, key)); + + await expect( + usageService.createNewUsage({ ...newInput(firstEditorialId, key), purpose: "Online-Aufmacher" }), + ).rejects.toMatchObject({ code: "IDEMPOTENCY_CONFLICT" }); + await expect(usageService.createNewUsage(newInput(secondEditorialId, key))).resolves.toMatchObject({ + billable: true, + }); +}); + +test("an audit failure rolls back both the usage and authorized event", async () => { + const editorialId = await seedEditorial(); + const { usageService } = createServices(); + await testDb.pool.query(` + create function reject_billable_usage_audit() returns trigger language plpgsql as $$ + begin + if new.event_type = 'billable_usage_created' then raise exception 'audit rejected'; end if; + return new; + end $$ + `); + await testDb.pool.query(` + create trigger reject_billable_usage_audit before insert on audit_events + for each row execute function reject_billable_usage_audit() + `); + + try { + await expect(usageService.createNewUsage(newInput(editorialId))).rejects.toThrow("audit rejected"); + } finally { + await testDb.pool.query("drop trigger reject_billable_usage_audit on audit_events"); + await testDb.pool.query("drop function reject_billable_usage_audit()"); + } + + const [usageCount] = await database + .select({ value: count() }) + .from(usages) + .where(eq(usages.editorialAccountId, editorialId)); + const [eventCount] = await database + .select({ value: count() }) + .from(downloadEvents) + .where(eq(downloadEvents.editorialAccountId, editorialId)); + expect({ usages: usageCount.value, events: eventCount.value }).toEqual({ usages: 0, events: 0 }); +}); + +test("a repeat remains free after a price change and creates no additional usage", async () => { + const editorialId = await seedEditorial(); + const { usageService, downloadService } = createServices(); + const first = await usageService.createNewUsage(newInput(editorialId)); + await database + .update(editorialAccounts) + .set({ currentPriceCents: 2_100 }) + .where(eq(editorialAccounts.id, editorialId)); + + const repeat = await downloadService.createRepeatDownload({ + editorialId, + usageId: first.usageId, + note: "Web-Ausgabe", + idempotencyKey: randomUUID(), + }); + + expect(repeat).toMatchObject({ usageId: first.usageId, priceCents: 0, billable: false }); + const [usageCount] = await database + .select({ value: count() }) + .from(usages) + .where(eq(usages.editorialAccountId, editorialId)); + expect(usageCount.value).toBe(1); +}); + +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)); + const repeatInput = { + editorialId, + usageId: first.usageId, + note: "Web-Ausgabe", + idempotencyKey: randomUUID(), + }; + + const [repeatOne, repeatTwo] = await Promise.all([ + downloadService.createRepeatDownload(repeatInput), + downloadService.createRepeatDownload(repeatInput), + ]); + + expect(repeatTwo).toEqual(repeatOne); + const [eventCount] = await database + .select({ value: count() }) + .from(downloadEvents) + .where(and(eq(downloadEvents.usageId, first.usageId), eq(downloadEvents.intentKind, "repeat_download"))); + expect(eventCount.value).toBe(1); +}); + +test("a suspended owner cannot create a repeat event", async () => { + const editorialId = await seedEditorial(); + const { usageService, downloadService } = createServices(); + const first = await usageService.createNewUsage(newInput(editorialId)); + await database + .update(editorialAccounts) + .set({ status: "suspended" }) + .where(eq(editorialAccounts.id, editorialId)); + + await expect( + downloadService.createRepeatDownload({ + editorialId, + usageId: first.usageId, + idempotencyKey: randomUUID(), + }), + ).rejects.toMatchObject({ code: "EDITORIAL_NOT_ACTIVE" }); +}); + +test("repeat ownership is scoped to the active editorial", async () => { + const ownerId = await seedEditorial(); + const otherEditorialId = await seedEditorial(); + const { usageService, downloadService } = createServices(); + const first = await usageService.createNewUsage(newInput(ownerId)); + + await expect( + downloadService.createRepeatDownload({ + editorialId: otherEditorialId, + usageId: first.usageId, + idempotencyKey: randomUUID(), + }), + ).rejects.toMatchObject({ code: "USAGE_NOT_FOUND" }); +});