From 0b1ffdfdfca4429d4f47061a7219645347b5824f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Leon=20Tonh=C3=A4user?= Date: Tue, 11 Aug 2026 03:27:10 +0200 Subject: [PATCH] feat: Add flatrate billing model for editorial accounts --- drizzle/0007_amused_franklin_storm.sql | 9 + drizzle/0008_overjoyed_wrecking_crew.sql | 4 + drizzle/meta/0007_snapshot.json | 1827 ++++++++++++++++ drizzle/meta/0008_snapshot.json | 1852 +++++++++++++++++ drizzle/meta/_journal.json | 14 + package.json | 1 + pnpm-lock.yaml | 7 +- src/app/admin/layout.tsx | 3 +- src/app/admin/page.tsx | 137 +- src/app/admin/redaktionen/[id]/actions.ts | 39 + .../redaktionen/[id]/alben/AlbumGrid.tsx | 54 +- src/app/admin/redaktionen/[id]/page.tsx | 3 + .../[assetId]/thumbnail/thumbnail-handler.ts | 48 +- .../api/billing-reports/finalize-handler.ts | 34 + .../reports/[reportId]/pdf/route.ts | 63 + src/app/redaktion/abrechnungen/page.tsx | 167 ++ src/app/redaktion/alben/[albumId]/page.tsx | 78 +- src/app/redaktion/alben/page.tsx | 78 +- src/app/redaktion/layout.tsx | 1 + .../leuchtkasten/DownloadLightboxForm.tsx | 22 + .../leuchtkasten/LightboxToggleButton.tsx | 56 + .../leuchtkasten/RemoveLightboxItemButton.tsx | 38 + src/app/redaktion/leuchtkasten/actions.ts | 31 + src/app/redaktion/leuchtkasten/page.tsx | 71 + src/db/schema/billing.ts | 1 + src/db/schema/editorials.ts | 5 +- src/db/schema/index.ts | 1 + src/db/schema/lightbox.ts | 31 + src/modules/albums/auto-rules.ts | 19 +- src/modules/albums/catalog-content.tsx | 9 +- src/modules/billing/reports.ts | 33 +- src/modules/billing/types.ts | 2 + src/modules/editorials/admin-detail.tsx | 53 +- src/modules/email/service.ts | 42 + src/modules/immich/client.ts | 4 + src/modules/lightbox/service.ts | 62 + src/modules/pdf/document.ts | 11 + src/modules/usages/service.ts | 41 +- test-sharp.js | 6 + 39 files changed, 4900 insertions(+), 57 deletions(-) create mode 100644 drizzle/0007_amused_franklin_storm.sql create mode 100644 drizzle/0008_overjoyed_wrecking_crew.sql create mode 100644 drizzle/meta/0007_snapshot.json create mode 100644 drizzle/meta/0008_snapshot.json create mode 100644 src/app/api/editorials/reports/[reportId]/pdf/route.ts create mode 100644 src/app/redaktion/abrechnungen/page.tsx create mode 100644 src/app/redaktion/leuchtkasten/DownloadLightboxForm.tsx create mode 100644 src/app/redaktion/leuchtkasten/LightboxToggleButton.tsx create mode 100644 src/app/redaktion/leuchtkasten/RemoveLightboxItemButton.tsx create mode 100644 src/app/redaktion/leuchtkasten/actions.ts create mode 100644 src/app/redaktion/leuchtkasten/page.tsx create mode 100644 src/db/schema/lightbox.ts create mode 100644 src/modules/email/service.ts create mode 100644 src/modules/lightbox/service.ts create mode 100644 test-sharp.js diff --git a/drizzle/0007_amused_franklin_storm.sql b/drizzle/0007_amused_franklin_storm.sql new file mode 100644 index 0000000..65bf960 --- /dev/null +++ b/drizzle/0007_amused_franklin_storm.sql @@ -0,0 +1,9 @@ +CREATE TABLE "lightbox_items" ( + "id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL, + "editorial_account_id" uuid NOT NULL, + "asset_id" text NOT NULL, + "added_at" timestamp with time zone DEFAULT now() NOT NULL +); +--> statement-breakpoint +ALTER TABLE "lightbox_items" ADD CONSTRAINT "lightbox_items_editorial_account_id_editorial_accounts_id_fk" FOREIGN KEY ("editorial_account_id") REFERENCES "public"."editorial_accounts"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +CREATE UNIQUE INDEX "lightbox_items_editorial_asset_idx" ON "lightbox_items" USING btree ("editorial_account_id","asset_id"); \ No newline at end of file diff --git a/drizzle/0008_overjoyed_wrecking_crew.sql b/drizzle/0008_overjoyed_wrecking_crew.sql new file mode 100644 index 0000000..ae46cb2 --- /dev/null +++ b/drizzle/0008_overjoyed_wrecking_crew.sql @@ -0,0 +1,4 @@ +ALTER TABLE "billing_reports" ADD COLUMN "flatrate_cents_snapshot" integer;--> statement-breakpoint +ALTER TABLE "editorial_accounts" ADD COLUMN "flatrate_active" boolean DEFAULT false NOT NULL;--> statement-breakpoint +ALTER TABLE "editorial_accounts" ADD COLUMN "flatrate_price_cents" integer;--> statement-breakpoint +ALTER TABLE "editorial_accounts" ADD COLUMN "flatrate_asset_limit" integer; \ No newline at end of file diff --git a/drizzle/meta/0007_snapshot.json b/drizzle/meta/0007_snapshot.json new file mode 100644 index 0000000..a21060c --- /dev/null +++ b/drizzle/meta/0007_snapshot.json @@ -0,0 +1,1827 @@ +{ + "id": "36b1cd5a-b01a-44f7-9cb6-507237e962e5", + "prevId": "0335bf0f-c89b-4c9d-bc8a-659768032679", + "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.album_auto_rules": { + "name": "album_auto_rules", + "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 + }, + "keyword": { + "name": "keyword", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_by_user_id": { + "name": "created_by_user_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "album_auto_rules_editorial_account_id_keyword_idx": { + "name": "album_auto_rules_editorial_account_id_keyword_idx", + "columns": [ + { + "expression": "editorial_account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"keyword\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "album_auto_rules_editorial_account_id_editorial_accounts_id_fk": { + "name": "album_auto_rules_editorial_account_id_editorial_accounts_id_fk", + "tableFrom": "album_auto_rules", + "tableTo": "editorial_accounts", + "columnsFrom": [ + "editorial_account_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "album_auto_rules_created_by_user_id_user_id_fk": { + "name": "album_auto_rules_created_by_user_id_user_id_fk", + "tableFrom": "album_auto_rules", + "tableTo": "user", + "columnsFrom": [ + "created_by_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "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 + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "archived_by_user_id": { + "name": "archived_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()" + }, + "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" + }, + "editorial_accounts_archived_by_user_id_user_id_fk": { + "name": "editorial_accounts_archived_by_user_id_user_id_fk", + "tableFrom": "editorial_accounts", + "tableTo": "user", + "columnsFrom": [ + "archived_by_user_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.lightbox_items": { + "name": "lightbox_items", + "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 + }, + "asset_id": { + "name": "asset_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "added_at": { + "name": "added_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "lightbox_items_editorial_asset_idx": { + "name": "lightbox_items_editorial_asset_idx", + "columns": [ + { + "expression": "editorial_account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "asset_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "lightbox_items_editorial_account_id_editorial_accounts_id_fk": { + "name": "lightbox_items_editorial_account_id_editorial_accounts_id_fk", + "tableFrom": "lightbox_items", + "tableTo": "editorial_accounts", + "columnsFrom": [ + "editorial_account_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.rate_limits": { + "name": "rate_limits", + "schema": "", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "window_boundary": { + "name": "window_boundary", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "count": { + "name": "count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "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": { + "rate_limits_key_window_boundary_pk": { + "name": "rate_limits_key_window_boundary_pk", + "columns": [ + "key", + "window_boundary" + ] + } + }, + "uniqueConstraints": {}, + "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/0008_snapshot.json b/drizzle/meta/0008_snapshot.json new file mode 100644 index 0000000..0bdced9 --- /dev/null +++ b/drizzle/meta/0008_snapshot.json @@ -0,0 +1,1852 @@ +{ + "id": "a42b2a77-c868-4739-8ab8-81ca92e1815c", + "prevId": "36b1cd5a-b01a-44f7-9cb6-507237e962e5", + "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.album_auto_rules": { + "name": "album_auto_rules", + "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 + }, + "keyword": { + "name": "keyword", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "created_by_user_id": { + "name": "created_by_user_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "album_auto_rules_editorial_account_id_keyword_idx": { + "name": "album_auto_rules_editorial_account_id_keyword_idx", + "columns": [ + { + "expression": "editorial_account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "lower(\"keyword\")", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "album_auto_rules_editorial_account_id_editorial_accounts_id_fk": { + "name": "album_auto_rules_editorial_account_id_editorial_accounts_id_fk", + "tableFrom": "album_auto_rules", + "tableTo": "editorial_accounts", + "columnsFrom": [ + "editorial_account_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + }, + "album_auto_rules_created_by_user_id_user_id_fk": { + "name": "album_auto_rules_created_by_user_id_user_id_fk", + "tableFrom": "album_auto_rules", + "tableTo": "user", + "columnsFrom": [ + "created_by_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "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 + }, + "flatrate_cents_snapshot": { + "name": "flatrate_cents_snapshot", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "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 + }, + "flatrate_active": { + "name": "flatrate_active", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "flatrate_price_cents": { + "name": "flatrate_price_cents", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "flatrate_asset_limit": { + "name": "flatrate_asset_limit", + "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 + }, + "archived_at": { + "name": "archived_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "archived_by_user_id": { + "name": "archived_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()" + }, + "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" + }, + "editorial_accounts_archived_by_user_id_user_id_fk": { + "name": "editorial_accounts_archived_by_user_id_user_id_fk", + "tableFrom": "editorial_accounts", + "tableTo": "user", + "columnsFrom": [ + "archived_by_user_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.lightbox_items": { + "name": "lightbox_items", + "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 + }, + "asset_id": { + "name": "asset_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "added_at": { + "name": "added_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "lightbox_items_editorial_asset_idx": { + "name": "lightbox_items_editorial_asset_idx", + "columns": [ + { + "expression": "editorial_account_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "asset_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "lightbox_items_editorial_account_id_editorial_accounts_id_fk": { + "name": "lightbox_items_editorial_account_id_editorial_accounts_id_fk", + "tableFrom": "lightbox_items", + "tableTo": "editorial_accounts", + "columnsFrom": [ + "editorial_account_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.rate_limits": { + "name": "rate_limits", + "schema": "", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "window_boundary": { + "name": "window_boundary", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "count": { + "name": "count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 1 + }, + "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": { + "rate_limits_key_window_boundary_pk": { + "name": "rate_limits_key_window_boundary_pk", + "columns": [ + "key", + "window_boundary" + ] + } + }, + "uniqueConstraints": {}, + "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 331302e..4d39b0a 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -50,6 +50,20 @@ "when": 1786410282719, "tag": "0006_chubby_screwball", "breakpoints": true + }, + { + "idx": 7, + "version": "7", + "when": 1786410724623, + "tag": "0007_amused_franklin_storm", + "breakpoints": true + }, + { + "idx": 8, + "version": "7", + "when": 1786411419497, + "tag": "0008_overjoyed_wrecking_crew", + "breakpoints": true } ] } \ No newline at end of file diff --git a/package.json b/package.json index dfb32a8..e2d139c 100644 --- a/package.json +++ b/package.json @@ -27,6 +27,7 @@ "react": "^19.2.8", "react-dom": "^19.2.8", "server-only": "^0.0.1", + "sharp": "^0.35.3", "zod": "^4.4.3" }, "devDependencies": { diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 9ea3c1b..164b27f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -41,6 +41,9 @@ importers: server-only: specifier: ^0.0.1 version: 0.0.1 + sharp: + specifier: ^0.35.3 + version: 0.35.3(@types/node@24.13.3) zod: specifier: ^4.4.3 version: 4.4.3 @@ -4886,8 +4889,7 @@ snapshots: '@humanwhocodes/retry@0.4.3': {} - '@img/colour@1.1.0': - optional: true + '@img/colour@1.1.0': {} '@img/sharp-darwin-arm64@0.35.3': optionalDependencies: @@ -7782,7 +7784,6 @@ snapshots: '@img/sharp-win32-ia32': 0.35.3 '@img/sharp-win32-x64': 0.35.3 '@types/node': 24.13.3 - optional: true shebang-command@2.0.0: dependencies: diff --git a/src/app/admin/layout.tsx b/src/app/admin/layout.tsx index 996ab65..e9e4634 100644 --- a/src/app/admin/layout.tsx +++ b/src/app/admin/layout.tsx @@ -10,9 +10,10 @@ export default async function AdminLayout({ children }: Readonly<{ children: Rea return ( `COALESCE(SUM(${usages.priceCents}), 0)::int`, + count: sql`COUNT(${usages.id})::int`, + }) + .from(usages) + .where(gte(usages.createdAt, firstDayOfMonth)); + + // 2. Aktivste Redaktionen (nach Anzahl an Downloads insgesamt) + const topEditorials = await db + .select({ + editorialId: usages.editorialAccountId, + name: editorialAccounts.name, + downloadCount: sql`COUNT(${usages.id})::int`, + revenueCents: sql`COALESCE(SUM(${usages.priceCents}), 0)::int`, + }) + .from(usages) + .innerJoin(editorialAccounts, eq(usages.editorialAccountId, editorialAccounts.id)) + .groupBy(usages.editorialAccountId, editorialAccounts.name) + .orderBy(desc(sql`COUNT(${usages.id})`)) + .limit(5); + + // 3. Beliebteste Alben + const topAlbums = await db + .select({ + albumName: usages.albumNameSnapshot, + downloadCount: sql`COUNT(${usages.id})::int`, + }) + .from(usages) + .groupBy(usages.albumNameSnapshot) + .orderBy(desc(sql`COUNT(${usages.id})`)) + .limit(5); + + const formatter = new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }); + + return ( +
+

Admin Dashboard

+

Willkommen zurück! Hier ist ein Überblick über die aktuelle Nutzung des Portals.

+ +
+
+

Umsatz diesen Monat

+

+ {formatter.format((revenueStats?.totalCents ?? 0) / 100)} +

+

+ {revenueStats?.count ?? 0} lizenzierte Bilder im {now.toLocaleString("de-DE", { month: "long" })} +

+
+ +
+ + Redaktionen verwalten + +
+
+ +
+
+

Aktivste Redaktionen

+
+ {topEditorials.length === 0 ? ( +

Noch keine Daten vorhanden.

+ ) : ( + + + + + + + + + + {topEditorials.map(ed => ( + + + + + + ))} + +
RedaktionDownloadsUmsatz
+ + {ed.name} + + {ed.downloadCount}{formatter.format(ed.revenueCents / 100)}
+ )} +
+
+ +
+

Beliebteste Alben

+
+ {topAlbums.length === 0 ? ( +

Noch keine Daten vorhanden.

+ ) : ( + + + + + + + + + {topAlbums.map(album => ( + + + + + ))} + +
AlbumDownloads
{album.albumName}{album.downloadCount}
+ )} +
+
+
+
+ ); } \ No newline at end of file diff --git a/src/app/admin/redaktionen/[id]/actions.ts b/src/app/admin/redaktionen/[id]/actions.ts index 4c95df9..a4bbec9 100644 --- a/src/app/admin/redaktionen/[id]/actions.ts +++ b/src/app/admin/redaktionen/[id]/actions.ts @@ -3,6 +3,9 @@ import { revalidatePath } from "next/cache"; import { headers } from "next/headers"; import { redirect } from "next/navigation"; +import { eq } from "drizzle-orm"; +import { db } from "@/db/client"; +import { editorialAccounts } from "@/db/schema"; import { requireAdmin } from "@/modules/auth/principal"; import { editorialService, EditorialServiceError } from "@/modules/editorials/service"; @@ -74,6 +77,42 @@ export async function reactivateEditorialAction(editorialId: string): Promise { + const admin = await requireAdmin(new Headers(await headers())); + const safeEditorialId = requiredId(editorialId); + + const flatrateActive = formData.get("flatrateActive") === "on"; + + let flatratePriceCents: number | null = null; + const rawPrice = formData.get("flatratePriceEuros"); + if (rawPrice && typeof rawPrice === "string" && rawPrice.trim() !== "") { + const price = parsePriceCents(rawPrice); + if (price.ok) { + flatratePriceCents = price.cents; + } + } + + let flatrateAssetLimit: number | null = null; + const rawLimit = formData.get("flatrateAssetLimit"); + if (rawLimit && typeof rawLimit === "string" && rawLimit.trim() !== "") { + const limit = parseInt(rawLimit, 10); + if (Number.isFinite(limit) && limit >= 1) { + flatrateAssetLimit = limit; + } + } + + await db + .update(editorialAccounts) + .set({ + flatrateActive, + flatratePriceCents, + flatrateAssetLimit, + }) + .where(eq(editorialAccounts.id, safeEditorialId)); + + revalidatePath(`/admin/redaktionen/${safeEditorialId}`); +} + function parsePriceCents( value: unknown, ): { ok: true; cents: number } | { ok: false; message: string } { diff --git a/src/app/admin/redaktionen/[id]/alben/AlbumGrid.tsx b/src/app/admin/redaktionen/[id]/alben/AlbumGrid.tsx index 95251e9..4b096e3 100644 --- a/src/app/admin/redaktionen/[id]/alben/AlbumGrid.tsx +++ b/src/app/admin/redaktionen/[id]/alben/AlbumGrid.tsx @@ -49,40 +49,48 @@ function AlbumCard({ }; return ( -
  • -
    +
  • +
    {album.albumThumbnailAssetId ? ( {`Titelbild ) : ( -
    +
    Kein Cover
    )} + {album.isGranted && ( +
    + Zugewiesen +
    + )}
    -
    -

    +
    +

    {album.albumName}

    -

    {album.assetCount} Fotos

    -

    - {album.isGranted ? "Zugewiesen" : "Nicht zugewiesen"} -

    -
    - - -
    +

    {album.assetCount} Fotos

    +
    +
    + + +
    +

  • ); @@ -109,7 +117,7 @@ export function AlbumGrid({ albums, editorialId, grantAction, revokeAction }: Al {filteredAlbums.length === 0 ? (

    Keine Alben gefunden.

    ) : ( -
      +
        {filteredAlbums.map((album) => ( }>; @@ -45,8 +46,11 @@ export function createThumbnailHandler(dependencies: ThumbnailHandlerDependencie } const thumbnail = await dependencies.immich.getThumbnail(assetId); + if (access.kind === "editorial") { + return watermarkedThumbnailResponse(thumbnail); + } return thumbnailResponse(thumbnail); - } catch { + } catch (err) { return genericNotFound(); } }; @@ -112,6 +116,48 @@ function genericNotFound(): Response { return new Response(null, { status: 404 }); } +async function watermarkedThumbnailResponse(thumbnail: ImmichBinary): Promise { + const reader = thumbnail.body.getReader(); + const chunks: Uint8Array[] = []; + while (true) { + const { done, value } = await reader.read(); + if (done) break; + if (value) chunks.push(value); + } + + const buffer = Buffer.concat(chunks); + const metadata = await sharp(buffer).metadata(); + const width = metadata.width ?? 400; + const height = metadata.height ?? 300; + + const svgText = ` + + + PREVIEW + + + `; + + const watermarked = await sharp(buffer) + .composite([ + { + input: Buffer.from(svgText), + gravity: "center", + }, + ]) + .webp({ quality: 80 }) + .toBuffer(); + + const responseHeaders = new Headers({ + "cache-control": "private, no-store", + "content-type": "image/webp", + "content-length": String(watermarked.length), + "x-content-type-options": "nosniff", + }); + + return new Response(watermarked, { headers: responseHeaders }); +} + function isSafeAssetId(assetId: string): boolean { return /^[A-Za-z0-9_-]{1,200}$/.test(assetId); } diff --git a/src/app/api/billing-reports/finalize-handler.ts b/src/app/api/billing-reports/finalize-handler.ts index 7961e06..f0503a3 100644 --- a/src/app/api/billing-reports/finalize-handler.ts +++ b/src/app/api/billing-reports/finalize-handler.ts @@ -8,6 +8,11 @@ import { } from "@/modules/billing/reports"; import { monthPeriod, quarterPeriod } from "@/modules/billing/period"; import { assertSameOrigin, CrossOriginRequestError } from "@/modules/security/origin"; +import { emailService } from "@/modules/email/service"; +import { getReportPdf } from "@/modules/billing/reports"; +import { db } from "@/db/client"; +import { editorialAccounts } from "@/db/schema"; +import { eq } from "drizzle-orm"; const finalizePayload = z .object({ @@ -45,6 +50,35 @@ export function createFinalizeHandler(dependencies: FinalizeHandlerDependencies) adminUserId: principal.userId, }); + // Email dispatch + try { + const [editorial] = await db + .select({ email: editorialAccounts.loginEmail }) + .from(editorialAccounts) + .where(eq(editorialAccounts.id, editorialId)) + .limit(1); + + if (editorial?.email) { + const reportPdf = await getReportPdf(result.reportId); + if (reportPdf) { + const periodString = month + ? `${month.toString().padStart(2, "0")}/${year}` + : `Q${quarter}/${year}`; + + // Fire and forget (don't await or catch if we want to not block, but awaiting is safer for serverless if not in background) + await emailService.sendBillingReport( + editorial.email, + periodString, + reportPdf.bytes, + result.reportNumber + ); + } + } + } catch (emailError) { + console.error("Failed to send billing email:", emailError); + // Do not fail the request if email fails + } + return Response.json( { reportId: result.reportId, diff --git a/src/app/api/editorials/reports/[reportId]/pdf/route.ts b/src/app/api/editorials/reports/[reportId]/pdf/route.ts new file mode 100644 index 0000000..8a01961 --- /dev/null +++ b/src/app/api/editorials/reports/[reportId]/pdf/route.ts @@ -0,0 +1,63 @@ +import { requireActiveEditorial, PrincipalAuthorizationError } from "@/modules/auth/principal"; +import { getReportPdf, reportService } from "@/modules/billing/reports"; +import { db } from "@/db/client"; +import { billingReports } from "@/db/schema"; +import { eq } from "drizzle-orm"; + +export async function GET( + request: Request, + { params }: { params: Promise<{ reportId: string }> } +): Promise { + try { + const principal = await requireActiveEditorial(request.headers); + const { reportId } = await params; + + // Verify ownership + const [report] = await db + .select({ editorialAccountId: billingReports.editorialAccountId }) + .from(billingReports) + .where(eq(billingReports.id, reportId)) + .limit(1); + + if (!report || report.editorialAccountId !== principal.editorialId) { + return notFound(); + } + + const reportPdf = await getReportPdf(reportId); + if (!reportPdf) return notFound(); + + const filename = buildFilename(reportPdf.invoiceNumber); + return new Response(new Uint8Array(reportPdf.bytes), { + status: 200, + headers: { + "content-type": "application/pdf", + "cache-control": "private, no-store", + "content-disposition": `attachment; filename="${filename}"`, + }, + }); + } catch (error) { + if (error instanceof PrincipalAuthorizationError) { + return jsonError(error.code === "AUTHENTICATION_REQUIRED" ? 401 : 403, "FORBIDDEN"); + } + return jsonError(500, "REQUEST_FAILED"); + } +} + +function buildFilename(invoiceNumber: string): string { + const safe = invoiceNumber.replace(/[^A-Za-z0-9_-]/g, "_"); + return `${safe || "nutzungsnachweis"}.pdf`; +} + +function notFound(): Response { + return new Response(null, { + status: 404, + headers: { "cache-control": "private, no-store" }, + }); +} + +function jsonError(status: number, code: string): Response { + return Response.json( + { code }, + { status, headers: { "cache-control": "private, no-store" } }, + ); +} diff --git a/src/app/redaktion/abrechnungen/page.tsx b/src/app/redaktion/abrechnungen/page.tsx new file mode 100644 index 0000000..d57312d --- /dev/null +++ b/src/app/redaktion/abrechnungen/page.tsx @@ -0,0 +1,167 @@ +import { eq, desc, and, sql, inArray } from "drizzle-orm"; +import { db } from "@/db/client"; +import { billingReports, usages, editorialAccounts } from "@/db/schema"; +import { requireActiveEditorial } from "@/modules/auth/principal"; +import { headers } from "next/headers"; +import Link from "next/link"; +import { formatBerlinDateTime } from "@/modules/downloads/format"; + +export default async function AbrechnungenPage() { + const principal = await requireActiveEditorial(new Headers(await headers())); + + // 1. Hole alle PDF-Abrechnungen (abgeschlossene Reports) + const reports = await db + .select({ + id: billingReports.id, + invoiceNumber: billingReports.invoiceNumber, + periodStartsAt: billingReports.periodStartsAt, + periodEndsAt: billingReports.periodEndsAt, + netTotalCents: billingReports.netTotalCents, + finalizedAt: billingReports.finalizedAt, + status: billingReports.status, + }) + .from(billingReports) + .where( + and( + eq(billingReports.editorialAccountId, principal.editorialId), + eq(billingReports.status, "final") + ) + ) + .orderBy(desc(billingReports.finalizedAt)); + + // 2. Berechne den noch offenen Betrag des aktuellen Monats (oder insgesamt offen) + const [openUsages] = await db + .select({ + totalCents: sql`COALESCE(SUM(${usages.priceCents}), 0)::int`, + count: sql`COUNT(${usages.id})::int`, + }) + .from(usages) + .where( + and( + eq(usages.editorialAccountId, principal.editorialId), + eq(usages.billingStatus, "open") + ) + ); + + const [editorial] = await db + .select({ + flatrateActive: editorialAccounts.flatrateActive, + flatratePriceCents: editorialAccounts.flatratePriceCents, + flatrateAssetLimit: editorialAccounts.flatrateAssetLimit, + }) + .from(editorialAccounts) + .where(eq(editorialAccounts.id, principal.editorialId)) + .limit(1); + + // Zähle die bereits bezogenen Flatrate-Bilder (Preis = 0) im aktuellen Kalendermonat + let usedFlatrateImages = 0; + if (editorial?.flatrateActive && editorial.flatrateAssetLimit !== null) { + const now = new Date(); + const startOfMonth = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)); + const endOfMonth = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 0, 23, 59, 59, 999)); + const [{ count }] = await db + .select({ count: sql`cast(count(*) as integer)` }) + .from(usages) + .where( + and( + eq(usages.editorialAccountId, principal.editorialId), + sql`${usages.createdAt} >= ${startOfMonth}`, + sql`${usages.createdAt} <= ${endOfMonth}`, + eq(usages.priceCents, 0), + inArray(usages.billingStatus, ["open", "billed", "reopened"]) + ) + ); + usedFlatrateImages = count; + } + + // Berechne gesamten offenen Betrag inkl. Flatrate (falls noch nicht abgerechnet) + // Normalerweise würde die Flatrate beim Report-Generieren hinzugefügt. Hier für die Vorschau: + // (Optional: Wenn man hier die Flatrate als "offen" anzeigen will) + const openTotalCents = (openUsages?.totalCents ?? 0); + + return ( +
        +

        Finanzen

        +

        Meine Abrechnungen

        + +
        +
        +

        Offener Betrag (Einzelabrufe)

        +

        + {new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).format(openTotalCents / 100)} +

        +

        + Für {openUsages?.count ?? 0} kostenpflichtige Bilder (noch nicht in Rechnung gestellt) +

        +
        + + {editorial?.flatrateActive && editorial.flatratePriceCents !== null && ( +
        +

        Aktiver Tarif: Flatrate

        +

        + {new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).format(editorial.flatratePriceCents / 100)} / Monat +

        + {editorial.flatrateAssetLimit === null ? ( +

        + Unbegrenzte Downloads inklusive +

        + ) : ( +
        +

        + Inklusiv-Bilder diesen Monat: {usedFlatrateImages} / {editorial.flatrateAssetLimit} +

        +
        +
        +
        +
        + )} +
        + )} +
        + +

        Bisherige Rechnungen

        + + {reports.length === 0 ? ( +

        Es liegen noch keine abgerechneten Zeiträume vor.

        + ) : ( +
        + + + + + + + + + + + {reports.map((report) => ( + + + + + + + ))} + +
        RechnungsnummerZeitraumBetrag (Netto)Download
        {report.invoiceNumber} + {new Intl.DateTimeFormat("de-DE", { month: "long", year: "numeric" }).format(report.periodStartsAt)} + + {new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).format(report.netTotalCents / 100)} + + + + + + PDF anzeigen + +
        +
        + )} +
        + ); +} diff --git a/src/app/redaktion/alben/[albumId]/page.tsx b/src/app/redaktion/alben/[albumId]/page.tsx index 33a90e5..b9b36a8 100644 --- a/src/app/redaktion/alben/[albumId]/page.tsx +++ b/src/app/redaktion/alben/[albumId]/page.tsx @@ -4,12 +4,13 @@ import { notFound } from "next/navigation"; import { AlbumCatalogError, albumCatalog, normalizePage } from "@/modules/albums/catalog"; import { PhotoContactSheet } from "@/modules/albums/catalog-content"; import { loadEditorialDownloadOptions } from "@/modules/downloads/stream"; +import { lightboxService } from "@/modules/lightbox/service"; import { requireEditorial } from "../../access"; type AlbumPageProps = Readonly<{ params: Promise<{ albumId: string }>; - searchParams: Promise<{ page?: string | string[]; suche?: string | string[] }>; + searchParams: Promise<{ page?: string | string[]; suche?: string | string[]; format?: string | string[]; jahr?: string | string[] }>; }>; export default async function AlbumPage({ params, searchParams }: AlbumPageProps) { @@ -20,11 +21,15 @@ export default async function AlbumPage({ params, searchParams }: AlbumPageProps ]); const query = normalizedQuery(singleValue(rawSearchParams.suche)); const currentPage = normalizePage(singleValue(rawSearchParams.page)); + const format = singleValue(rawSearchParams.format); + const jahr = singleValue(rawSearchParams.jahr); const result = await loadAlbumPage({ editorialId: principal.editorialId, albumId, query, page: singleValue(rawSearchParams.page), + format, + jahr, }); if (result.unavailable) { @@ -43,6 +48,7 @@ export default async function AlbumPage({ params, searchParams }: AlbumPageProps Alle Alben + ); } +function AlbumSearchForm({ albumId, query, format, jahr }: { albumId: string; query: string; format?: string; jahr?: string; }) { + const currentYear = new Date().getFullYear(); + const years = Array.from({ length: 10 }, (_, i) => currentYear - i); + + return ( +
        +
        + +
        +
        + + + +
        +
        + ); +} + async function loadAlbumPage({ editorialId, albumId, query, page, + format, + jahr, }: { editorialId: string; albumId: string; query: string; page: string | undefined; + format?: string; + jahr?: string; }) { try { const albums = await albumCatalog.getVisibleAlbums(editorialId); @@ -77,11 +122,40 @@ async function loadAlbumPage({ description: query, page, }); + + // Client-side filtering for format and year + if (format || jahr) { + results.items = results.items.filter(asset => { + let matches = true; + + if (format) { + const width = asset.exifInfo?.exifImageWidth ?? 0; + const height = asset.exifInfo?.exifImageHeight ?? 0; + if (width > 0 && height > 0) { + const isLandscape = width >= height; + if (format === 'quer' && !isLandscape) matches = false; + if (format === 'hoch' && isLandscape) matches = false; + } + } + + if (jahr && matches) { + const dateStr = asset.localDateTime ?? asset.fileCreatedAt; + if (!dateStr || !dateStr.startsWith(jahr)) { + matches = false; + } + } + + return matches; + }); + } + const downloadOptions = await loadEditorialDownloadOptions( editorialId, results.items.map((asset) => asset.id), ); - return { album, page: results, downloadOptions, unavailable: false as const }; + const lightboxItems = await lightboxService.getLightboxItems(editorialId); + const lightboxAssetIds = new Set(lightboxItems.map(i => i.assetId)); + return { album, page: results, downloadOptions, lightboxAssetIds, unavailable: false as const }; } catch (error) { if (error instanceof AlbumCatalogError && error.code === "IMMICH_UNAVAILABLE") { return { album: null, page: null, unavailable: true as const }; diff --git a/src/app/redaktion/alben/page.tsx b/src/app/redaktion/alben/page.tsx index 7c12257..d6caf1d 100644 --- a/src/app/redaktion/alben/page.tsx +++ b/src/app/redaktion/alben/page.tsx @@ -1,38 +1,71 @@ import { AlbumCatalogError, albumCatalog } from "@/modules/albums/catalog"; import { AlbumContactSheet, PhotoContactSheet } from "@/modules/albums/catalog-content"; import { loadEditorialDownloadOptions } from "@/modules/downloads/stream"; +import { lightboxService } from "@/modules/lightbox/service"; import type { ImmichSearchPage } from "@/modules/immich/types"; import Link from "next/link"; import { requireEditorial } from "../access"; -export default async function AlbumsPage({ searchParams }: { searchParams: Promise<{ suche?: string | string[]; page?: string | string[] }> }) { +export default async function AlbumsPage({ searchParams }: { searchParams: Promise<{ suche?: string | string[]; page?: string | string[]; format?: string | string[]; jahr?: string | string[] }> }) { const principal = await requireEditorial(); const rawSearchParams = await searchParams; const query = normalizedQuery(singleValue(rawSearchParams.suche)); + const format = singleValue(rawSearchParams.format); + const jahr = singleValue(rawSearchParams.jahr); if (query) { const results = await albumCatalog.searchVisiblePhotos(principal.editorialId, { description: query, page: singleValue(rawSearchParams.page), }); + + if (format || jahr) { + results.items = results.items.filter(asset => { + let matches = true; + + if (format) { + const width = asset.exifInfo?.exifImageWidth ?? 0; + const height = asset.exifInfo?.exifImageHeight ?? 0; + if (width > 0 && height > 0) { + const isLandscape = width >= height; + if (format === 'quer' && !isLandscape) matches = false; + if (format === 'hoch' && isLandscape) matches = false; + } + } + + if (jahr && matches) { + const dateStr = asset.localDateTime ?? asset.fileCreatedAt; + if (!dateStr || !dateStr.startsWith(jahr)) { + matches = false; + } + } + + return matches; + }); + } + const downloadOptions = await loadEditorialDownloadOptions( principal.editorialId, results.items.map((asset) => asset.id), ); + const lightboxItems = await lightboxService.getLightboxItems(principal.editorialId); + const lightboxAssetIds = new Set(lightboxItems.map(i => i.assetId)); + return (

        Bildarchiv · Suche

        Suchergebnisse

        - +
        @@ -52,7 +85,7 @@ export default async function AlbumsPage({ searchParams }: { searchParams: Promi

        Ihre Alben

        Wählen Sie ein Spiel oder eine Serie, um die freigegebenen Fotos zu durchsuchen.

        - + {result.albums.length === 0 ? (

        Für Ihre Redaktion sind noch keine Fotoalben freigegeben.

        ) : ( @@ -62,17 +95,36 @@ export default async function AlbumsPage({ searchParams }: { searchParams: Promi ); } -function GlobalSearchForm({ query }: { query: string }) { +function GlobalSearchForm({ query, format, jahr }: { query: string; format?: string; jahr?: string; }) { + const currentYear = new Date().getFullYear(); + const years = Array.from({ length: 10 }, (_, i) => currentYear - i); + return ( -
        - - + +
        + +
        +
        + + + +
        ); } diff --git a/src/app/redaktion/layout.tsx b/src/app/redaktion/layout.tsx index ffe6c14..b26c3bd 100644 --- a/src/app/redaktion/layout.tsx +++ b/src/app/redaktion/layout.tsx @@ -13,6 +13,7 @@ export default async function EditorialLayout({ children }: Readonly<{ children: sectionLabel="Redaktionsarchiv" nav={[ { href: "/redaktion/alben", label: "Alben" }, + { href: "/redaktion/leuchtkasten", label: "Merkzettel" }, { href: "/redaktion/nutzungen", label: "Nutzungen" }, { href: "/redaktion/profil", label: "Profil" }, ]} diff --git a/src/app/redaktion/leuchtkasten/DownloadLightboxForm.tsx b/src/app/redaktion/leuchtkasten/DownloadLightboxForm.tsx new file mode 100644 index 0000000..6203d8b --- /dev/null +++ b/src/app/redaktion/leuchtkasten/DownloadLightboxForm.tsx @@ -0,0 +1,22 @@ +"use client"; + +import { useState } from "react"; + +export function DownloadLightboxForm({ assetIds }: { assetIds: string[] }) { + const [loading, setLoading] = useState(false); + + function handleBulkDownload() { + alert("Bulk-Download ist aktuell in Entwicklung. Bitte klicke auf die Bilder, um sie einzeln herunterzuladen."); + } + + return ( + + ); +} diff --git a/src/app/redaktion/leuchtkasten/LightboxToggleButton.tsx b/src/app/redaktion/leuchtkasten/LightboxToggleButton.tsx new file mode 100644 index 0000000..1a49c15 --- /dev/null +++ b/src/app/redaktion/leuchtkasten/LightboxToggleButton.tsx @@ -0,0 +1,56 @@ +"use client"; + +import { useState, useTransition } from "react"; +import { toggleLightboxItem } from "./actions"; + +type LightboxToggleButtonProps = { + assetId: string; + initialInLightbox: boolean; +}; + +export function LightboxToggleButton({ assetId, initialInLightbox }: LightboxToggleButtonProps) { + const [isPending, startTransition] = useTransition(); + const [inLightbox, setInLightbox] = useState(initialInLightbox); + + function handleClick(e: React.MouseEvent) { + e.preventDefault(); // prevent navigation if wrapped in a link + e.stopPropagation(); + + // Optimistic update + setInLightbox(!inLightbox); + + startTransition(async () => { + try { + const result = await toggleLightboxItem(assetId); + setInLightbox(result.isNowInLightbox); + } catch { + // Revert on error + setInLightbox(inLightbox); + } + }); + } + + return ( + + ); +} diff --git a/src/app/redaktion/leuchtkasten/RemoveLightboxItemButton.tsx b/src/app/redaktion/leuchtkasten/RemoveLightboxItemButton.tsx new file mode 100644 index 0000000..814fac1 --- /dev/null +++ b/src/app/redaktion/leuchtkasten/RemoveLightboxItemButton.tsx @@ -0,0 +1,38 @@ +"use client"; + +import { useTransition } from "react"; +import { removeLightboxItemAction } from "./actions"; + +export function RemoveLightboxItemButton({ assetId }: { assetId: string }) { + const [isPending, startTransition] = useTransition(); + + function handleRemove() { + startTransition(async () => { + await removeLightboxItemAction(assetId); + }); + } + + return ( + + ); +} diff --git a/src/app/redaktion/leuchtkasten/actions.ts b/src/app/redaktion/leuchtkasten/actions.ts new file mode 100644 index 0000000..de71007 --- /dev/null +++ b/src/app/redaktion/leuchtkasten/actions.ts @@ -0,0 +1,31 @@ +"use server"; + +import { revalidatePath } from "next/cache"; +import { headers } from "next/headers"; +import { requireActiveEditorial } from "@/modules/auth/principal"; +import { lightboxService } from "@/modules/lightbox/service"; + +export async function toggleLightboxItem(assetId: string) { + const principal = await requireActiveEditorial(new Headers(await headers())); + const isInLightbox = await lightboxService.isAssetInLightbox(principal.editorialId, assetId); + + if (isInLightbox) { + await lightboxService.removeLightboxItem(principal.editorialId, assetId); + } else { + await lightboxService.addLightboxItem(principal.editorialId, assetId); + } + + // Revalidate routes where lightbox state is shown + revalidatePath("/redaktion/alben/[id]", "page"); + revalidatePath("/redaktion/leuchtkasten", "page"); + + return { success: true, isNowInLightbox: !isInLightbox }; +} + +export async function removeLightboxItemAction(assetId: string) { + const principal = await requireActiveEditorial(new Headers(await headers())); + await lightboxService.removeLightboxItem(principal.editorialId, assetId); + revalidatePath("/redaktion/leuchtkasten", "page"); + revalidatePath("/redaktion/alben/[id]", "page"); + return { success: true }; +} diff --git a/src/app/redaktion/leuchtkasten/page.tsx b/src/app/redaktion/leuchtkasten/page.tsx new file mode 100644 index 0000000..17dea5a --- /dev/null +++ b/src/app/redaktion/leuchtkasten/page.tsx @@ -0,0 +1,71 @@ +import { headers } from "next/headers"; +import { requireActiveEditorial } from "@/modules/auth/principal"; +import { lightboxService } from "@/modules/lightbox/service"; +import { immichClient } from "@/modules/immich/client"; +import Image from "next/image"; +import Link from "next/link"; +import { RemoveLightboxItemButton } from "./RemoveLightboxItemButton"; +import { DownloadLightboxForm } from "./DownloadLightboxForm"; + +export default async function LightboxPage() { + const principal = await requireActiveEditorial(new Headers(await headers())); + const items = await lightboxService.getLightboxItems(principal.editorialId); + + // Fetch asset details for all items in the lightbox + const assets = items.length > 0 + ? await immichClient.searchAssets({ + assetIds: items.map(i => i.assetId) + }) + : []; + + const assetMap = new Map(assets.map(a => [a.id, a])); + + return ( +
        +

        Merkzettel

        +

        Dein Leuchtkasten

        + + {items.length === 0 ? ( +

        Dein Leuchtkasten ist leer.

        + ) : ( + <> +
        +

        + {items.length} {items.length === 1 ? 'Bild' : 'Bilder'} gemerkt +

        + i.assetId)} /> +
        + +
          + {items.map((item) => { + const asset = assetMap.get(item.assetId); + if (!asset) return null; + + return ( +
        • + + {asset.originalFileName} +
          + + {asset.originalFileName} + +
          + +
          + +
          +
        • + ); + })} +
        + + )} +
        + ); +} diff --git a/src/db/schema/billing.ts b/src/db/schema/billing.ts index bcd7f75..74fa4dd 100644 --- a/src/db/schema/billing.ts +++ b/src/db/schema/billing.ts @@ -39,6 +39,7 @@ export const billingReports = pgTable( billingAddressSnapshot: jsonb("billing_address_snapshot").notNull(), invoiceNumber: text("invoice_number"), netTotalCents: integer("net_total_cents").notNull(), + flatrateCentsSnapshot: integer("flatrate_cents_snapshot"), status: reportStatus("status").notNull().default("draft"), pdf: bytea("pdf"), pdfSha256: varchar("pdf_sha256", { length: 64 }), diff --git a/src/db/schema/editorials.ts b/src/db/schema/editorials.ts index 72cc0e1..f4133f8 100644 --- a/src/db/schema/editorials.ts +++ b/src/db/schema/editorials.ts @@ -1,5 +1,5 @@ import { relations } from "drizzle-orm"; -import { type AnyPgColumn, integer, pgEnum, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core"; +import { type AnyPgColumn, boolean, integer, pgEnum, pgTable, text, timestamp, uuid } from "drizzle-orm/pg-core"; import { users } from "./auth"; @@ -23,6 +23,9 @@ export const editorialAccounts = pgTable("editorial_accounts", { loginEmail: text("login_email").notNull().unique(), status: accountStatus("status").notNull().default("pending_email"), currentPriceCents: integer("current_price_cents"), + flatrateActive: boolean("flatrate_active").notNull().default(false), + flatratePriceCents: integer("flatrate_price_cents"), + flatrateAssetLimit: integer("flatrate_asset_limit"), approvalNoticeStatus: text("approval_notice_status").notNull().default("not_requested"), currentBillingAddressVersionId: uuid("current_billing_address_version_id").references( (): AnyPgColumn => billingAddressVersions.id, diff --git a/src/db/schema/index.ts b/src/db/schema/index.ts index cc506fe..0eedc07 100644 --- a/src/db/schema/index.ts +++ b/src/db/schema/index.ts @@ -4,5 +4,6 @@ export * from "./auth"; export * from "./auto-rules"; export * from "./billing"; export * from "./editorials"; +export * from "./lightbox"; export * from "./rate-limits"; export * from "./usages"; diff --git a/src/db/schema/lightbox.ts b/src/db/schema/lightbox.ts new file mode 100644 index 0000000..7c9471f --- /dev/null +++ b/src/db/schema/lightbox.ts @@ -0,0 +1,31 @@ +import { relations } from "drizzle-orm"; +import { pgTable, text, timestamp, uniqueIndex, uuid } from "drizzle-orm/pg-core"; + +import { editorialAccounts } from "./editorials"; + +export const lightboxItems = pgTable( + "lightbox_items", + { + id: uuid("id").defaultRandom().primaryKey(), + editorialAccountId: uuid("editorial_account_id") + .notNull() + .references(() => editorialAccounts.id, { onDelete: "cascade" }), + assetId: text("asset_id").notNull(), + addedAt: timestamp("added_at", { withTimezone: true }).notNull().defaultNow(), + }, + (table) => { + return { + editorialAssetIdx: uniqueIndex("lightbox_items_editorial_asset_idx").on( + table.editorialAccountId, + table.assetId, + ), + }; + } +); + +export const lightboxItemsRelations = relations(lightboxItems, ({ one }) => ({ + editorialAccount: one(editorialAccounts, { + fields: [lightboxItems.editorialAccountId], + references: [editorialAccounts.id], + }), +})); diff --git a/src/modules/albums/auto-rules.ts b/src/modules/albums/auto-rules.ts index 3fcaaf8..8ba3dbc 100644 --- a/src/modules/albums/auto-rules.ts +++ b/src/modules/albums/auto-rules.ts @@ -4,11 +4,12 @@ import { eq, sql } from "drizzle-orm"; import type { NodePgDatabase } from "drizzle-orm/node-postgres"; import { db } from "@/db/client"; -import { albumAutoRules } from "@/db/schema"; +import { albumAutoRules, editorialAccounts } from "@/db/schema"; import type * as schema from "@/db/schema"; import { albumGrantService } from "./grants"; import { immichClient } from "@/modules/immich/client"; import type { ImmichClient } from "@/modules/immich/types"; +import { emailService } from "@/modules/email/service"; export type AutoRule = { id: string; @@ -62,6 +63,18 @@ export function createAutoRuleService({ const grantedAlbumIds = new Set(await grantService.getGrantedAlbumIds(editorialId)); let newlyGranted = 0; + let editorialEmail: string | undefined; + try { + const [editorial] = await db + .select({ email: editorialAccounts.loginEmail }) + .from(editorialAccounts) + .where(eq(editorialAccounts.id, editorialId)) + .limit(1); + editorialEmail = editorial?.email; + } catch (e) { + // Ignore DB error + } + for (const album of albums) { if (grantedAlbumIds.has(album.id)) { continue; @@ -75,6 +88,10 @@ export function createAutoRuleService({ await grantService.grantAlbum({ editorialId, immichAlbumId: album.id, adminUserId }); newlyGranted++; grantedAlbumIds.add(album.id); + + if (editorialEmail) { + await emailService.sendNewAlbumNotification(editorialEmail, album.albumName).catch(() => {}); + } } catch (error) { // Ignore individual album grant failures } diff --git a/src/modules/albums/catalog-content.tsx b/src/modules/albums/catalog-content.tsx index a9df69a..98efe9b 100644 --- a/src/modules/albums/catalog-content.tsx +++ b/src/modules/albums/catalog-content.tsx @@ -3,6 +3,7 @@ import Link from "next/link"; import { UsageDialog } from "@/components/download/usage-dialog"; +import { LightboxToggleButton } from "@/app/redaktion/leuchtkasten/LightboxToggleButton"; import type { EditorialDownloadOptions } from "@/modules/downloads/stream"; import type { ImmichSearchPage } from "@/modules/immich/types"; @@ -56,6 +57,7 @@ export function PhotoContactSheet({ page: ImmichSearchPage; query: string; showAlbumName?: boolean; + lightboxAssetIds?: Set; }>) { return ( <> @@ -77,7 +79,7 @@ export function PhotoContactSheet({
          {page.items.map((asset) => (
        • -
          +
          {asset.originalFileName} + {lightboxAssetIds && ( +
          + +
          + )}
          {asset.originalFileName} {showAlbumName && (asset as any).albums && (asset as any).albums.length > 0 && ( diff --git a/src/modules/billing/reports.ts b/src/modules/billing/reports.ts index 90e198e..65f58ac 100644 --- a/src/modules/billing/reports.ts +++ b/src/modules/billing/reports.ts @@ -155,6 +155,7 @@ export type FinalizeTransactionInput = { address: BillingReportAddress; repeatDownloads: BillingReportRepeatDownload[]; netTotalCents: number; + flatrateCentsSnapshot: number | null; pdfBytes: Buffer; pdfSha256: string; documentId: string; @@ -171,6 +172,7 @@ export type FinalizeTransactionResult = { export type ReportRepository = { // Snapshot building (pre-transaction) getCurrentAddress(editorialId: string): Promise; + getEditorialFlatrate(editorialId: string): Promise<{ flatrateActive: boolean; flatratePriceCents: number | null; flatrateAssetLimit: number | null; } | null>; getSelectedUsages(editorialId: string, usageIds: string[]): Promise; getRepeatDownloads(editorialId: string, period: BillingPeriod): Promise; allocateReportNumber(): Promise; @@ -235,6 +237,7 @@ export function createReportService({ selectedPositions: selectedUsages.map(toReportPosition), repeatDownloads, netTotalCents, + flatrateCentsSnapshot: input.flatrateCentsSnapshot, reportNumber: 0, invoiceNumber: "VORSCHAU", period: input.period, @@ -273,6 +276,7 @@ export function createReportService({ selectedPositions: selectedUsages.map(toReportPosition), repeatDownloads, netTotalCents, + flatrateCentsSnapshot: input.flatrateCentsSnapshot, reportNumber, invoiceNumber, period: input.period, @@ -298,6 +302,7 @@ export function createReportService({ address, repeatDownloads, netTotalCents, + flatrateCentsSnapshot: input.flatrateCentsSnapshot, pdfBytes: rendered.bytes, pdfSha256: rendered.sha256, documentId, @@ -394,6 +399,7 @@ async function buildSnapshot( address: BillingReportAddress; repeatDownloads: BillingReportRepeatDownload[]; netTotalCents: number; + flatrateCentsSnapshot: number | null; }> { if (input.usageIds.length === 0) { throw new ReportValidationError("NO_USAGES_SELECTED"); @@ -426,11 +432,20 @@ async function buildSnapshot( throw new ReportValidationError("ADDRESS_NOT_FOUND"); } + const editorialFlatrate = await repo.getEditorialFlatrate(input.editorialId); + let flatrateCentsSnapshot: number | null = null; + if (editorialFlatrate && editorialFlatrate.flatrateActive && editorialFlatrate.flatratePriceCents !== null) { + flatrateCentsSnapshot = editorialFlatrate.flatratePriceCents; + } + const repeatDownloads = await repo.getRepeatDownloads(input.editorialId, input.period); - const netTotalCents = selectedUsages.reduce((sum, u) => sum + u.priceCents, 0); + let netTotalCents = selectedUsages.reduce((sum, u) => sum + u.priceCents, 0); + if (flatrateCentsSnapshot !== null) { + netTotalCents += flatrateCentsSnapshot; + } - return { usages: selectedUsages, address, repeatDownloads, netTotalCents }; + return { usages: selectedUsages, address, repeatDownloads, netTotalCents, flatrateCentsSnapshot }; } function toReportPosition(usage: SelectedUsage): BillingReportPosition { @@ -484,6 +499,19 @@ export function createReportRepository( return version; }, + async getEditorialFlatrate(editorialId) { + const [editorial] = await database + .select({ + flatrateActive: editorialAccounts.flatrateActive, + flatratePriceCents: editorialAccounts.flatratePriceCents, + flatrateAssetLimit: editorialAccounts.flatrateAssetLimit, + }) + .from(editorialAccounts) + .where(eq(editorialAccounts.id, editorialId)) + .limit(1); + return editorial || null; + }, + async getSelectedUsages(editorialId, usageIds) { const rows = await database .select({ @@ -581,6 +609,7 @@ export function createReportRepository( billingAddressSnapshot: input.address, invoiceNumber: input.invoiceNumber, netTotalCents: input.netTotalCents, + flatrateCentsSnapshot: input.flatrateCentsSnapshot, status: "final", pdf: input.pdfBytes, pdfSha256: input.pdfSha256, diff --git a/src/modules/billing/types.ts b/src/modules/billing/types.ts index b0a1f12..3ab68ed 100644 --- a/src/modules/billing/types.ts +++ b/src/modules/billing/types.ts @@ -72,4 +72,6 @@ export type BillingReportSnapshot = { createdAt: Date; /** Legal notice clarifying that the report is not a VAT invoice. */ legalSeparationNotice: string; + /** Flatrate amount snapshot, if applicable. */ + flatrateCentsSnapshot?: number | null; }; \ No newline at end of file diff --git a/src/modules/editorials/admin-detail.tsx b/src/modules/editorials/admin-detail.tsx index 190b51b..00b9aca 100644 --- a/src/modules/editorials/admin-detail.tsx +++ b/src/modules/editorials/admin-detail.tsx @@ -1,5 +1,5 @@ import Link from "next/link"; -import { archiveEditorialAction, suspendEditorialAction, reactivateEditorialAction } from "@/app/admin/redaktionen/[id]/actions"; +import { archiveEditorialAction, suspendEditorialAction, reactivateEditorialAction, updateFlatrateAction } from "@/app/admin/redaktionen/[id]/actions"; import { DangerZone } from "./DangerZone"; export type EditorialDetail = { @@ -10,6 +10,9 @@ export type EditorialDetail = { status: string; emailVerifiedAt: Date | null; currentPriceCents: number | null; + flatrateActive: boolean; + flatratePriceCents: number | null; + flatrateAssetLimit: number | null; archivedAt: Date | null; }; @@ -59,6 +62,54 @@ export function EditorialDetailContent({ Auto-Zuweisungsregeln + {/* Flatrate Settings */} + {!editorial.archivedAt && ( +
          +

          Flatrate-Einstellungen

          +
          +
          + +

          Wenn aktiviert, werden Downloads nach einem Pauschalpreis abgerechnet.

          +
          + +
          +
          + + +
          +
          + + +

          Leer lassen für unbegrenzte Flatrate.

          +
          +
          + + +
          +
          + )} + {/* Status Actions */} {!editorial.archivedAt && (
          diff --git a/src/modules/email/service.ts b/src/modules/email/service.ts new file mode 100644 index 0000000..f48b7cd --- /dev/null +++ b/src/modules/email/service.ts @@ -0,0 +1,42 @@ +import "server-only"; +import nodemailer from "nodemailer"; +import { env } from "@/config/env"; + +const transporter = nodemailer.createTransport({ + host: env.SMTP_HOST, + port: env.SMTP_PORT, + secure: env.SMTP_PORT === 465, + auth: { + user: env.SMTP_USER, + pass: env.SMTP_PASSWORD, + }, +}); + +export const emailService = { + async sendBillingReport(toEmail: string, reportMonth: string, pdfBytes: Buffer, invoiceNumber: string) { + const filename = invoiceNumber.replace(/[^A-Za-z0-9_-]/g, "_") + ".pdf"; + + await transporter.sendMail({ + from: env.SMTP_FROM, + to: toEmail, + subject: `Ihre Abrechnung für ${reportMonth}`, + text: `Hallo,\n\nanbei erhalten Sie Ihre Abrechnung für den Monat ${reportMonth} als PDF-Dokument.\n\nViele Grüße,\nIhr Redaktions-Team`, + attachments: [ + { + filename, + content: pdfBytes, + contentType: "application/pdf", + }, + ], + }); + }, + + async sendNewAlbumNotification(toEmail: string, albumName: string) { + await transporter.sendMail({ + from: env.SMTP_FROM, + to: toEmail, + subject: `Neues Fotoalbum verfügbar: ${albumName}`, + text: `Hallo,\n\nein neues Fotoalbum "${albumName}" wurde für Ihre Redaktion freigegeben. Sie können die Bilder ab sofort im Redaktionsportal ansehen und lizenzieren.\n\nViele Grüße,\nIhr Redaktions-Team`, + }); + }, +}; diff --git a/src/modules/immich/client.ts b/src/modules/immich/client.ts index 82dc671..b300358 100644 --- a/src/modules/immich/client.ts +++ b/src/modules/immich/client.ts @@ -25,6 +25,10 @@ const assetSchema = z localDateTime: nullableString, fileCreatedAt: nullableString, albums: z.array(z.object({ id: z.string() }).passthrough()).optional().default([]), + exifInfo: z.object({ + exifImageWidth: z.number().optional().nullable(), + exifImageHeight: z.number().optional().nullable(), + }).passthrough().optional().nullable(), }) .passthrough(); diff --git a/src/modules/lightbox/service.ts b/src/modules/lightbox/service.ts new file mode 100644 index 0000000..f3b1d9a --- /dev/null +++ b/src/modules/lightbox/service.ts @@ -0,0 +1,62 @@ +import { and, eq } from "drizzle-orm"; +import { db } from "@/db/client"; +import { lightboxItems } from "@/db/schema"; +import { immichClient } from "@/modules/immich/client"; +import type { PhotoAsset } from "@/modules/immich/types"; + +export type LightboxItem = { + assetId: string; + addedAt: Date; + asset?: PhotoAsset; // populated if joined +}; + +export const lightboxService = { + async getLightboxItems(editorialId: string): Promise { + const items = await db + .select({ + assetId: lightboxItems.assetId, + addedAt: lightboxItems.addedAt, + }) + .from(lightboxItems) + .where(eq(lightboxItems.editorialAccountId, editorialId)) + .orderBy(lightboxItems.addedAt); + + return items; + }, + + async addLightboxItem(editorialId: string, assetId: string): Promise { + await db + .insert(lightboxItems) + .values({ + editorialAccountId: editorialId, + assetId, + }) + .onConflictDoNothing(); + }, + + async removeLightboxItem(editorialId: string, assetId: string): Promise { + await db + .delete(lightboxItems) + .where( + and( + eq(lightboxItems.editorialAccountId, editorialId), + eq(lightboxItems.assetId, assetId) + ) + ); + }, + + async isAssetInLightbox(editorialId: string, assetId: string): Promise { + const result = await db + .select({ id: lightboxItems.id }) + .from(lightboxItems) + .where( + and( + eq(lightboxItems.editorialAccountId, editorialId), + eq(lightboxItems.assetId, assetId) + ) + ) + .limit(1); + + return result.length > 0; + } +}; diff --git a/src/modules/pdf/document.ts b/src/modules/pdf/document.ts index 13d0c0b..5cdfa10 100644 --- a/src/modules/pdf/document.ts +++ b/src/modules/pdf/document.ts @@ -65,6 +65,17 @@ function paidPositionsTable(snapshot: BillingReportSnapshot) { const body = [headerRow]; + if (snapshot.flatrateCentsSnapshot !== null && snapshot.flatrateCentsSnapshot !== undefined) { + body.push([ + { text: "Flatrate", style: "tableCell" }, + { text: "-", style: "tableCell" }, + { text: "Monatlicher Pauschalpreis", style: "tableCell" }, + { text: "-", style: "tableCell" }, + { text: "-", style: "tableCell", alignment: "right" as const }, + { text: formatCents(snapshot.flatrateCentsSnapshot), style: "tableCell", alignment: "right" as const }, + ]); + } + for (const pos of snapshot.selectedPositions) { body.push([ { text: pos.filename, style: "tableCell" }, diff --git a/src/modules/usages/service.ts b/src/modules/usages/service.ts index c5ebe35..d43946e 100644 --- a/src/modules/usages/service.ts +++ b/src/modules/usages/service.ts @@ -135,6 +135,8 @@ export function createUsageServiceRepository( id: editorialAccounts.id, status: editorialAccounts.status, currentPriceCents: editorialAccounts.currentPriceCents, + flatrateActive: editorialAccounts.flatrateActive, + flatrateAssetLimit: editorialAccounts.flatrateAssetLimit, }) .from(editorialAccounts) .where(eq(editorialAccounts.id, input.editorialId)) @@ -164,6 +166,39 @@ export function createUsageServiceRepository( .limit(1); if (!grant) throw new UsageAccountingError("ALBUM_NOT_GRANTED"); + let priceCents = editorial.currentPriceCents!; + + if (editorial.flatrateActive) { + if (editorial.flatrateAssetLimit === null) { + priceCents = 0; // Unlimited flatrate + } else { + // Limited flatrate - check how many usages this month + const now = new Date(); + const startOfMonth = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)); + const endOfMonth = new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth() + 1, 0, 23, 59, 59, 999)); + + const [{ count }] = await transaction + .select({ count: sql`cast(count(*) as integer)` }) + .from(usages) + .where( + and( + eq(usages.editorialAccountId, input.editorialId), + sql`${usages.createdAt} >= ${startOfMonth}`, + sql`${usages.createdAt} <= ${endOfMonth}`, + inArray(usages.billingStatus, ["open", "billed", "reopened"]), + // For flatrate, we only count usages that were originally free via the flatrate + // so we compare against priceCents = 0. Wait, any usage counts towards the limit? + // Yes, any billable usage this month counts towards the limit. + eq(usages.priceCents, 0) + ) + ); + + if (count < editorial.flatrateAssetLimit) { + priceCents = 0; + } + } + } + // This is the last cross-system authorization snapshot available to the // portal. Immich may still change after it returns, but no portal work is // allowed between this refresh and the accounting inserts. @@ -180,7 +215,7 @@ export function createUsageServiceRepository( albumNameSnapshot: currentAsset.albumName, purpose: input.purpose, internalReference: input.reference, - priceCents: editorial.currentPriceCents!, + priceCents: priceCents, billingStatus: "open", createdAt, }) @@ -214,7 +249,7 @@ export function createUsageServiceRepository( editorialId: input.editorialId, assetId: input.assetId, albumId: input.albumId, - priceCents: editorial.currentPriceCents, + priceCents: priceCents, downloadId: event.id, }, occurredAt: createdAt, @@ -224,7 +259,7 @@ export function createUsageServiceRepository( id: event.id, usageId: usage.id, assetId: input.assetId, - priceCents: editorial.currentPriceCents!, + priceCents: priceCents, billable: true, status: "authorized" as const, authorizedAt: createdAt, diff --git a/test-sharp.js b/test-sharp.js new file mode 100644 index 0000000..ca5e646 --- /dev/null +++ b/test-sharp.js @@ -0,0 +1,6 @@ +import sharp from 'sharp'; + +async function run() { + console.log("Sharp loaded:", typeof sharp); +} +run();