From edd87e7cd558e858d30129f8278513266c1c3cec Mon Sep 17 00:00:00 2001 From: Bianca Date: Fri, 13 Nov 2026 20:36:53 +0100 Subject: [PATCH 1/5] feat(web): add the documents catalog with categories and versions Add web.documents so the website's documents page loads its PDFs from the backend. Categories and documents are managed and reordered from the admin dashboard; each document keeps a version history and the website shows the latest one (greatest date, then greatest id). - Tables web_document_categories, web_documents and web_document_versions (migration 0037_web_documents). - Public getCatalog and getDocument hide documents without versions and categories without such documents; getAdminCatalog shows everything. - Writes require web:content:write and return { error: CODE } results. Deleting a version or a document also deletes its blobs. Co-Authored-By: Claude Opus 5.5 --- drizzle/0037_web_documents.sql | 52 + drizzle/meta/0037_snapshot.json | 4505 +++++++++++++++++++++++++++ drizzle/meta/_journal.json | 7 + src/db/schema/web/documents.ts | 61 + src/db/schema/web/index.ts | 2 + src/routers/web/documents.ts | 424 +++ src/routers/web/index.ts | 11 +- tests/documents-postgres.fixture.ts | 256 ++ tests/documents-postgres.test.ts | 16 + 9 files changed, 5333 insertions(+), 1 deletion(-) create mode 100644 drizzle/0037_web_documents.sql create mode 100644 drizzle/meta/0037_snapshot.json create mode 100644 src/db/schema/web/documents.ts create mode 100644 src/routers/web/documents.ts create mode 100644 tests/documents-postgres.fixture.ts create mode 100644 tests/documents-postgres.test.ts diff --git a/drizzle/0037_web_documents.sql b/drizzle/0037_web_documents.sql new file mode 100644 index 0000000..51d57f6 --- /dev/null +++ b/drizzle/0037_web_documents.sql @@ -0,0 +1,52 @@ +CREATE TABLE "web_document_categories" ( + "id" integer PRIMARY KEY GENERATED ALWAYS AS IDENTITY (sequence name "web_document_categories_id_seq" INCREMENT BY 1 MINVALUE 1 MAXVALUE 2147483647 START WITH 1 CACHE 1), + "slug" text NOT NULL, + "title" text NOT NULL, + "description" text NOT NULL, + "position" integer DEFAULT 0 NOT NULL, + "legacy_created_by_tg_id" bigint, + "legacy_modified_by_tg_id" bigint, + "created_by_sub" text, + "modified_by_sub" text, + "updated_at" timestamp (0) with time zone, + "created_at" timestamp (0) with time zone DEFAULT now() NOT NULL, + CONSTRAINT "web_document_categories_slug_unique" UNIQUE("slug"), + CONSTRAINT "web_document_categories_creator_check" CHECK ("web_document_categories"."legacy_created_by_tg_id" IS NOT NULL OR "web_document_categories"."created_by_sub" IS NOT NULL) +); +--> statement-breakpoint +CREATE TABLE "web_document_versions" ( + "id" integer PRIMARY KEY GENERATED ALWAYS AS IDENTITY (sequence name "web_document_versions_id_seq" INCREMENT BY 1 MINVALUE 1 MAXVALUE 2147483647 START WITH 1 CACHE 1), + "document_id" integer NOT NULL, + "version" text NOT NULL, + "date" text NOT NULL, + "file" text NOT NULL, + "legacy_created_by_tg_id" bigint, + "legacy_modified_by_tg_id" bigint, + "created_by_sub" text, + "modified_by_sub" text, + "updated_at" timestamp (0) with time zone, + "created_at" timestamp (0) with time zone DEFAULT now() NOT NULL, + CONSTRAINT "web_document_versions_document_id_version_unique" UNIQUE("document_id","version"), + CONSTRAINT "web_document_versions_creator_check" CHECK ("web_document_versions"."legacy_created_by_tg_id" IS NOT NULL OR "web_document_versions"."created_by_sub" IS NOT NULL) +); +--> statement-breakpoint +CREATE TABLE "web_documents" ( + "id" integer PRIMARY KEY GENERATED ALWAYS AS IDENTITY (sequence name "web_documents_id_seq" INCREMENT BY 1 MINVALUE 1 MAXVALUE 2147483647 START WITH 1 CACHE 1), + "category_id" integer NOT NULL, + "slug" text NOT NULL, + "title" text NOT NULL, + "description" text, + "position" integer DEFAULT 0 NOT NULL, + "legacy_created_by_tg_id" bigint, + "legacy_modified_by_tg_id" bigint, + "created_by_sub" text, + "modified_by_sub" text, + "updated_at" timestamp (0) with time zone, + "created_at" timestamp (0) with time zone DEFAULT now() NOT NULL, + CONSTRAINT "web_documents_slug_unique" UNIQUE("slug"), + CONSTRAINT "web_documents_creator_check" CHECK ("web_documents"."legacy_created_by_tg_id" IS NOT NULL OR "web_documents"."created_by_sub" IS NOT NULL) +); +--> statement-breakpoint +ALTER TABLE "web_document_versions" ADD CONSTRAINT "web_document_versions_document_id_web_documents_id_fk" FOREIGN KEY ("document_id") REFERENCES "public"."web_documents"("id") ON DELETE cascade ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "web_documents" ADD CONSTRAINT "web_documents_category_id_web_document_categories_id_fk" FOREIGN KEY ("category_id") REFERENCES "public"."web_document_categories"("id") ON DELETE restrict ON UPDATE no action;--> statement-breakpoint +CREATE INDEX "web_documents_category_id_idx" ON "web_documents" USING btree ("category_id"); \ No newline at end of file diff --git a/drizzle/meta/0037_snapshot.json b/drizzle/meta/0037_snapshot.json new file mode 100644 index 0000000..f8b5347 --- /dev/null +++ b/drizzle/meta/0037_snapshot.json @@ -0,0 +1,4505 @@ +{ + "id": "3e3fdc41-9cdd-470d-a3b2-501568ab9989", + "prevId": "e95be3b8-6f1e-4888-815d-7f179376214e", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.common_group_labels": { + "name": "common_group_labels", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "common_group_labels_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "label": { + "name": "label", + "type": "varchar(128)", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "varchar", + "primaryKey": false, + "notNull": false + }, + "color": { + "name": "color", + "type": "varchar(7)", + "primaryKey": false, + "notNull": true, + "default": "'#ffffff'" + }, + "legacy_created_by_tg_id": { + "name": "legacy_created_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "legacy_modified_by_tg_id": { + "name": "legacy_modified_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "created_by_sub": { + "name": "created_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "modified_by_sub": { + "name": "modified_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "common_group_labels_label_unique": { + "name": "common_group_labels_label_unique", + "nullsNotDistinct": false, + "columns": [ + "label" + ] + } + }, + "policies": {}, + "checkConstraints": { + "common_group_labels_creator_check": { + "name": "common_group_labels_creator_check", + "value": "\"common_group_labels\".\"legacy_created_by_tg_id\" IS NOT NULL OR \"common_group_labels\".\"created_by_sub\" IS NOT NULL" + } + }, + "isRLSEnabled": false + }, + "public.common_idp_state": { + "name": "common_idp_state", + "schema": "", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.esign_documents": { + "name": "esign_documents", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "request_id": { + "name": "request_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "file_name": { + "name": "file_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "content": { + "name": "content", + "type": "bytea", + "primaryKey": false, + "notNull": true + }, + "sha256": { + "name": "sha256", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "size": { + "name": "size", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "pages": { + "name": "pages", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "source": { + "name": "source", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_by_sub": { + "name": "created_by_sub", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "esign_documents_request_version_idx": { + "name": "esign_documents_request_version_idx", + "columns": [ + { + "expression": "request_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "version", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"esign_documents\".\"request_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "esign_documents_request_id_esign_requests_id_fk": { + "name": "esign_documents_request_id_esign_requests_id_fk", + "tableFrom": "esign_documents", + "tableTo": "esign_requests", + "columnsFrom": [ + "request_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.esign_drive_access": { + "name": "esign_drive_access", + "schema": "", + "columns": { + "drive_id": { + "name": "drive_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "request_roles": { + "name": "request_roles", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'::text[]" + }, + "request_permissions": { + "name": "request_permissions", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'::text[]" + }, + "sign_roles": { + "name": "sign_roles", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'::text[]" + }, + "sign_permissions": { + "name": "sign_permissions", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'::text[]" + }, + "updated_by_sub": { + "name": "updated_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.esign_events": { + "name": "esign_events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "request_id": { + "name": "request_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "at": { + "name": "at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "actor_sub": { + "name": "actor_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "data": { + "name": "data", + "type": "jsonb", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "esign_events_request_idx": { + "name": "esign_events_request_idx", + "columns": [ + { + "expression": "request_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "esign_events_request_id_esign_requests_id_fk": { + "name": "esign_events_request_id_esign_requests_id_fk", + "tableFrom": "esign_events", + "tableTo": "esign_requests", + "columnsFrom": [ + "request_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.esign_jobs": { + "name": "esign_jobs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "ticket_hash": { + "name": "ticket_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "request_id": { + "name": "request_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "signer_id": { + "name": "signer_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "sub": { + "name": "sub", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "base_version": { + "name": "base_version", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "places": { + "name": "places", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "step": { + "name": "step", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true + }, + "prepared": { + "name": "prepared", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "prepared_pdf": { + "name": "prepared_pdf", + "type": "bytea", + "primaryKey": false, + "notNull": false + }, + "error_code": { + "name": "error_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error_message": { + "name": "error_message", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "seen_at": { + "name": "seen_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "esign_jobs_request_idx": { + "name": "esign_jobs_request_idx", + "columns": [ + { + "expression": "request_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "esign_jobs_request_id_esign_requests_id_fk": { + "name": "esign_jobs_request_id_esign_requests_id_fk", + "tableFrom": "esign_jobs", + "tableTo": "esign_requests", + "columnsFrom": [ + "request_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "esign_jobs_signer_id_esign_signers_id_fk": { + "name": "esign_jobs_signer_id_esign_signers_id_fk", + "tableFrom": "esign_jobs", + "tableTo": "esign_signers", + "columnsFrom": [ + "signer_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "esign_jobs_ticket_hash_unique": { + "name": "esign_jobs_ticket_hash_unique", + "nullsNotDistinct": false, + "columns": [ + "ticket_hash" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.esign_profiles": { + "name": "esign_profiles", + "schema": "", + "columns": { + "sub": { + "name": "sub", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "fiscal_code": { + "name": "fiscal_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "certificate_subject": { + "name": "certificate_subject", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.esign_requests": { + "name": "esign_requests", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'in_progress'" + }, + "ordered": { + "name": "ordered", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "output": { + "name": "output", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "email": { + "name": "email", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "delivery": { + "name": "delivery", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "drives": { + "name": "drives", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'::text[]" + }, + "created_by_sub": { + "name": "created_by_sub", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "cancelled_at": { + "name": "cancelled_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "esign_requests_status_idx": { + "name": "esign_requests_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "esign_requests_created_by_idx": { + "name": "esign_requests_created_by_idx", + "columns": [ + { + "expression": "created_by_sub", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.esign_signers": { + "name": "esign_signers", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "request_id": { + "name": "request_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "sub": { + "name": "sub", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "places": { + "name": "places", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "signatures_done": { + "name": "signatures_done", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "signed_at": { + "name": "signed_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "fiscal_code": { + "name": "fiscal_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "certificate_subject": { + "name": "certificate_subject", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "certificate_issuer": { + "name": "certificate_issuer", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "decline_reason": { + "name": "decline_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "esign_signers_request_idx": { + "name": "esign_signers_request_idx", + "columns": [ + { + "expression": "request_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "esign_signers_sub_idx": { + "name": "esign_signers_sub_idx", + "columns": [ + { + "expression": "sub", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "esign_signers_request_position_idx": { + "name": "esign_signers_request_position_idx", + "columns": [ + { + "expression": "request_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "position", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "esign_signers_request_id_esign_requests_id_fk": { + "name": "esign_signers_request_id_esign_requests_id_fk", + "tableFrom": "esign_signers", + "tableTo": "esign_requests", + "columnsFrom": [ + "request_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.people_activity": { + "name": "people_activity", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "people_activity_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "person_id": { + "name": "person_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "actor": { + "name": "actor", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "at": { + "name": "at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "people_activity_person_idx": { + "name": "people_activity_person_idx", + "columns": [ + { + "expression": "person_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "people_activity_person_id_people_persons_id_fk": { + "name": "people_activity_person_id_people_persons_id_fk", + "tableFrom": "people_activity", + "tableTo": "people_persons", + "columnsFrom": [ + "person_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.people_assignments": { + "name": "people_assignments", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "person_id": { + "name": "person_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "team": { + "name": "team", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "team_role": { + "name": "team_role", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "capo_scope": { + "name": "capo_scope", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "capo_of_reference_id": { + "name": "capo_of_reference_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "fields": { + "name": "fields", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "since": { + "name": "since", + "type": "date", + "primaryKey": false, + "notNull": true + }, + "ended_on": { + "name": "ended_on", + "type": "date", + "primaryKey": false, + "notNull": false + }, + "end_reason": { + "name": "end_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "assigned_by": { + "name": "assigned_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "change": { + "name": "change", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "refusal": { + "name": "refusal", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "command_id": { + "name": "command_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "people_assignments_person_idx": { + "name": "people_assignments_person_idx", + "columns": [ + { + "expression": "person_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "people_assignments_current_idx": { + "name": "people_assignments_current_idx", + "columns": [ + { + "expression": "person_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "kind", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"team\", '')", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"people_assignments\".\"ended_on\" is null", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "people_assignments_person_id_people_persons_id_fk": { + "name": "people_assignments_person_id_people_persons_id_fk", + "tableFrom": "people_assignments", + "tableTo": "people_persons", + "columnsFrom": [ + "person_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "people_assignments_capo_of_reference_id_people_persons_id_fk": { + "name": "people_assignments_capo_of_reference_id_people_persons_id_fk", + "tableFrom": "people_assignments", + "tableTo": "people_persons", + "columnsFrom": [ + "capo_of_reference_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "people_assignments_command_id_people_role_commands_id_fk": { + "name": "people_assignments_command_id_people_role_commands_id_fk", + "tableFrom": "people_assignments", + "tableTo": "people_role_commands", + "columnsFrom": [ + "command_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "people_assignments_kind_check": { + "name": "people_assignments_kind_check", + "value": "\"people_assignments\".\"kind\" in ('admin', 'capo', 'team')" + }, + "people_assignments_team_check": { + "name": "people_assignments_team_check", + "value": "(\"people_assignments\".\"kind\" = 'team') = (\"people_assignments\".\"team\" is not null and \"people_assignments\".\"team_role\" in ('member', 'lead'))" + }, + "people_assignments_capo_ref_check": { + "name": "people_assignments_capo_ref_check", + "value": "\"people_assignments\".\"kind\" = 'admin' or \"people_assignments\".\"capo_of_reference_id\" is null" + }, + "people_assignments_change_check": { + "name": "people_assignments_change_check", + "value": "\"people_assignments\".\"change\" in ('start', 'end')" + }, + "people_assignments_status_check": { + "name": "people_assignments_status_check", + "value": "\"people_assignments\".\"status\" in ('pending', 'sent', 'applied', 'refused')" + }, + "people_assignments_sent_check": { + "name": "people_assignments_sent_check", + "value": "(\"people_assignments\".\"status\" = 'sent') = (\"people_assignments\".\"command_id\" is not null)" + } + }, + "isRLSEnabled": false + }, + "public.people_counters": { + "name": "people_counters", + "schema": "", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "value": { + "name": "value", + "type": "bigint", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.people_invites": { + "name": "people_invites", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "person_id": { + "name": "person_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sent_by": { + "name": "sent_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sent_at": { + "name": "sent_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "accepted_at": { + "name": "accepted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "accepted_by": { + "name": "accepted_by", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "people_invites_person_idx": { + "name": "people_invites_person_idx", + "columns": [ + { + "expression": "person_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "people_invites_person_id_people_persons_id_fk": { + "name": "people_invites_person_id_people_persons_id_fk", + "tableFrom": "people_invites", + "tableTo": "people_persons", + "columnsFrom": [ + "person_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "people_invites_token_hash_unique": { + "name": "people_invites_token_hash_unique", + "nullsNotDistinct": false, + "columns": [ + "token_hash" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.people_mail": { + "name": "people_mail", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "person_id": { + "name": "person_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "to": { + "name": "to", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "subject": { + "name": "subject", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "attempted_at": { + "name": "attempted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "people_mail_person_id_people_persons_id_fk": { + "name": "people_mail_person_id_people_persons_id_fk", + "tableFrom": "people_mail", + "tableTo": "people_persons", + "columnsFrom": [ + "person_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.people_persons": { + "name": "people_persons", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "first_name": { + "name": "first_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "last_name": { + "name": "last_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "contact_email": { + "name": "contact_email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "phone": { + "name": "phone", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "telegram_username": { + "name": "telegram_username", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "account_sub": { + "name": "account_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "linked_at": { + "name": "linked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "linked_by": { + "name": "linked_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "link_method": { + "name": "link_method", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "updated_by": { + "name": "updated_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "people_persons_account_sub_unique": { + "name": "people_persons_account_sub_unique", + "nullsNotDistinct": false, + "columns": [ + "account_sub" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.people_role_commands": { + "name": "people_role_commands", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "person_id": { + "name": "person_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "request": { + "name": "request", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "purpose": { + "name": "purpose", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'roles'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "answered_at": { + "name": "answered_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "people_role_commands_queued_idx": { + "name": "people_role_commands_queued_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"people_role_commands\".\"status\" = 'queued'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "people_role_commands_person_id_people_persons_id_fk": { + "name": "people_role_commands_person_id_people_persons_id_fk", + "tableFrom": "people_role_commands", + "tableTo": "people_persons", + "columnsFrom": [ + "person_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "people_role_commands_status_check": { + "name": "people_role_commands_status_check", + "value": "\"people_role_commands\".\"status\" in ('queued', 'applied', 'refused')" + }, + "people_role_commands_purpose_check": { + "name": "people_role_commands_purpose_check", + "value": "\"people_role_commands\".\"purpose\" in ('roles', 'unlink')" + } + }, + "isRLSEnabled": false + }, + "public.soci_activity": { + "name": "soci_activity", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "soci_activity_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "member_id": { + "name": "member_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "actor": { + "name": "actor", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "at": { + "name": "at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "soci_activity_member_idx": { + "name": "soci_activity_member_idx", + "columns": [ + { + "expression": "member_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "soci_activity_member_id_soci_members_id_fk": { + "name": "soci_activity_member_id_soci_members_id_fk", + "tableFrom": "soci_activity", + "tableTo": "soci_members", + "columnsFrom": [ + "member_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.soci_fees": { + "name": "soci_fees", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "soci_fees_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "member_id": { + "name": "member_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "year": { + "name": "year", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "amount_cents": { + "name": "amount_cents", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "file_id": { + "name": "file_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "transfer_date": { + "name": "transfer_date", + "type": "date", + "primaryKey": false, + "notNull": false + }, + "declared_cents": { + "name": "declared_cents", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "uploaded_at": { + "name": "uploaded_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "reviewed_by": { + "name": "reviewed_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "reviewed_at": { + "name": "reviewed_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "rejection_reason": { + "name": "rejection_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "paid_on": { + "name": "paid_on", + "type": "date", + "primaryKey": false, + "notNull": false + }, + "method": { + "name": "method", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "note": { + "name": "note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "recorded_by": { + "name": "recorded_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "soci_fees_member_year_idx": { + "name": "soci_fees_member_year_idx", + "columns": [ + { + "expression": "member_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "year", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + }, + "soci_fees_year_idx": { + "name": "soci_fees_year_idx", + "columns": [ + { + "expression": "year", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "soci_fees_member_id_soci_members_id_fk": { + "name": "soci_fees_member_id_soci_members_id_fk", + "tableFrom": "soci_fees", + "tableTo": "soci_members", + "columnsFrom": [ + "member_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "soci_fees_file_id_soci_files_id_fk": { + "name": "soci_fees_file_id_soci_files_id_fk", + "tableFrom": "soci_fees", + "tableTo": "soci_files", + "columnsFrom": [ + "file_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "soci_fees_status_check": { + "name": "soci_fees_status_check", + "value": "\"soci_fees\".\"status\" in ('due', 'uploaded', 'paid', 'exempt')" + }, + "soci_fees_method_check": { + "name": "soci_fees_method_check", + "value": "\"soci_fees\".\"method\" in ('transfer', 'admission', 'other')" + }, + "soci_fees_paid_check": { + "name": "soci_fees_paid_check", + "value": "(\"soci_fees\".\"status\" = 'paid') = (\"soci_fees\".\"paid_on\" is not null and \"soci_fees\".\"method\" is not null and \"soci_fees\".\"recorded_by\" is not null)" + }, + "soci_fees_upload_check": { + "name": "soci_fees_upload_check", + "value": "\"soci_fees\".\"status\" <> 'uploaded' or (\"soci_fees\".\"file_id\" is not null and \"soci_fees\".\"transfer_date\" is not null and \"soci_fees\".\"declared_cents\" is not null and \"soci_fees\".\"uploaded_at\" is not null)" + } + }, + "isRLSEnabled": false + }, + "public.soci_files": { + "name": "soci_files", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "member_id": { + "name": "member_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "file_name": { + "name": "file_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "content_type": { + "name": "content_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "content": { + "name": "content", + "type": "bytea", + "primaryKey": false, + "notNull": true + }, + "uploaded_by": { + "name": "uploaded_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "uploaded_at": { + "name": "uploaded_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "soci_files_member_idx": { + "name": "soci_files_member_idx", + "columns": [ + { + "expression": "member_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "soci_files_member_id_soci_members_id_fk": { + "name": "soci_files_member_id_soci_members_id_fk", + "tableFrom": "soci_files", + "tableTo": "soci_members", + "columnsFrom": [ + "member_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "soci_files_type_check": { + "name": "soci_files_type_check", + "value": "\"soci_files\".\"content_type\" in ('application/pdf', 'image/png', 'image/jpeg')" + } + }, + "isRLSEnabled": false + }, + "public.soci_mail": { + "name": "soci_mail", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "member_id": { + "name": "member_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "to": { + "name": "to", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "data": { + "name": "data", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "attempted_at": { + "name": "attempted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "soci_mail_status_idx": { + "name": "soci_mail_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "soci_mail_member_id_soci_members_id_fk": { + "name": "soci_mail_member_id_soci_members_id_fk", + "tableFrom": "soci_mail", + "tableTo": "soci_members", + "columnsFrom": [ + "member_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "soci_mail_status_check": { + "name": "soci_mail_status_check", + "value": "\"soci_mail\".\"status\" in ('pending', 'sending', 'sent', 'failed')" + } + }, + "isRLSEnabled": false + }, + "public.soci_members": { + "name": "soci_members", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "soci_members_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "number": { + "name": "number", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "entra_object_id": { + "name": "entra_object_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "mailbox": { + "name": "mailbox", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "display_name": { + "name": "display_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "first_name": { + "name": "first_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "last_name": { + "name": "last_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "alias": { + "name": "alias", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "codice_fiscale": { + "name": "codice_fiscale", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "birth_date": { + "name": "birth_date", + "type": "date", + "primaryKey": false, + "notNull": false + }, + "birth_place": { + "name": "birth_place", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "residence": { + "name": "residence", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "phone": { + "name": "phone", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "admitted_on": { + "name": "admitted_on", + "type": "date", + "primaryKey": false, + "notNull": true + }, + "ended_on": { + "name": "ended_on", + "type": "date", + "primaryKey": false, + "notNull": false + }, + "end_reason": { + "name": "end_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "end_note": { + "name": "end_note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "account_state": { + "name": "account_state", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "account_deleted_on": { + "name": "account_deleted_on", + "type": "date", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "updated_by": { + "name": "updated_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "soci_members_active_codice_fiscale_idx": { + "name": "soci_members_active_codice_fiscale_idx", + "columns": [ + { + "expression": "codice_fiscale", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"soci_members\".\"ended_on\" is null and \"soci_members\".\"codice_fiscale\" is not null", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "soci_members_number_unique": { + "name": "soci_members_number_unique", + "nullsNotDistinct": false, + "columns": [ + "number" + ] + }, + "soci_members_entra_object_id_unique": { + "name": "soci_members_entra_object_id_unique", + "nullsNotDistinct": false, + "columns": [ + "entra_object_id" + ] + } + }, + "policies": {}, + "checkConstraints": { + "soci_members_end_check": { + "name": "soci_members_end_check", + "value": "(\"soci_members\".\"ended_on\" is null) = (\"soci_members\".\"end_reason\" is null) and (\"soci_members\".\"ended_on\" is not null or \"soci_members\".\"end_note\" is null)" + }, + "soci_members_end_reason_check": { + "name": "soci_members_end_reason_check", + "value": "\"soci_members\".\"end_reason\" in ('lapsed', 'resigned', 'expelled', 'deceased', 'other')" + }, + "soci_members_account_state_check": { + "name": "soci_members_account_state_check", + "value": "\"soci_members\".\"account_state\" in ('active', 'pending_deletion', 'deleted')" + }, + "soci_members_account_deleted_check": { + "name": "soci_members_account_deleted_check", + "value": "(\"soci_members\".\"account_state\" = 'deleted') = (\"soci_members\".\"account_deleted_on\" is not null)" + }, + "soci_members_number_check": { + "name": "soci_members_number_check", + "value": "\"soci_members\".\"number\" > 0" + } + }, + "isRLSEnabled": false + }, + "public.soci_numbers": { + "name": "soci_numbers", + "schema": "", + "columns": { + "number": { + "name": "number", + "type": "integer", + "primaryKey": true, + "notNull": true + }, + "member_id": { + "name": "member_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "assigned_at": { + "name": "assigned_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "soci_numbers_member_idx": { + "name": "soci_numbers_member_idx", + "columns": [ + { + "expression": "member_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "soci_numbers_member_id_soci_members_id_fk": { + "name": "soci_numbers_member_id_soci_members_id_fk", + "tableFrom": "soci_numbers", + "tableTo": "soci_members", + "columnsFrom": [ + "member_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.tg_audit_log": { + "name": "tg_audit_log", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "tg_audit_log_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "target_id": { + "name": "target_id", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "group_id": { + "name": "group_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "type": { + "name": "type", + "type": "varchar(32)", + "primaryKey": false, + "notNull": true + }, + "until": { + "name": "until", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "reason": { + "name": "reason", + "type": "varchar(256)", + "primaryKey": false, + "notNull": false + }, + "actor_sub": { + "name": "actor_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "actor_tg_id": { + "name": "actor_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "client": { + "name": "client", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "basis": { + "name": "basis", + "type": "varchar(32)", + "primaryKey": false, + "notNull": true, + "default": "'legacy'" + }, + "review": { + "name": "review", + "type": "varchar(32)", + "primaryKey": false, + "notNull": false + }, + "idempotency_key": { + "name": "idempotency_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "auditlog_actor_tg_id_idx": { + "name": "auditlog_actor_tg_id_idx", + "columns": [ + { + "expression": "actor_tg_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "auditlog_idempotency_key_idx": { + "name": "auditlog_idempotency_key_idx", + "columns": [ + { + "expression": "idempotency_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.tg_grants": { + "name": "tg_grants", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "tg_grants_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "telegram_user_id": { + "name": "telegram_user_id", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "valid_since": { + "name": "valid_since", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true + }, + "valid_until": { + "name": "valid_until", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "granted_by_sub": { + "name": "granted_by_sub", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "granted_via_client": { + "name": "granted_via_client", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "interrupted_at": { + "name": "interrupted_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "interrupted_by_sub": { + "name": "interrupted_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "interrupted_by_tg_id": { + "name": "interrupted_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "tg_grants_telegram_user_id_idx": { + "name": "tg_grants_telegram_user_id_idx", + "columns": [ + { + "expression": "telegram_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "tg_grants_validity_check": { + "name": "tg_grants_validity_check", + "value": "\"tg_grants\".\"valid_since\" < \"tg_grants\".\"valid_until\"" + } + }, + "isRLSEnabled": false + }, + "public.tg_groups": { + "name": "tg_groups", + "schema": "", + "columns": { + "telegram_id": { + "name": "telegram_id", + "type": "bigint", + "primaryKey": true, + "notNull": true + }, + "title": { + "name": "title", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "tag": { + "name": "tag", + "type": "varchar", + "primaryKey": false, + "notNull": false + }, + "link": { + "name": "link", + "type": "varchar(128)", + "primaryKey": false, + "notNull": false + }, + "hide": { + "name": "hide", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "tg_groups_link_unique": { + "name": "tg_groups_link_unique", + "nullsNotDistinct": false, + "columns": [ + "link" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.tg_group_label_relations": { + "name": "tg_group_label_relations", + "schema": "", + "columns": { + "group_id": { + "name": "group_id", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "label_id": { + "name": "label_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "tg_group_label_relations_group_id_tg_groups_telegram_id_fk": { + "name": "tg_group_label_relations_group_id_tg_groups_telegram_id_fk", + "tableFrom": "tg_group_label_relations", + "tableTo": "tg_groups", + "columnsFrom": [ + "group_id" + ], + "columnsTo": [ + "telegram_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "tg_group_label_relations_label_id_common_group_labels_id_fk": { + "name": "tg_group_label_relations_label_id_common_group_labels_id_fk", + "tableFrom": "tg_group_label_relations", + "tableTo": "common_group_labels", + "columnsFrom": [ + "label_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "tg_group_label_relations_group_id_label_id_pk": { + "name": "tg_group_label_relations_group_id_label_id_pk", + "columns": [ + "group_id", + "label_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.tg_messages": { + "name": "tg_messages", + "schema": "", + "columns": { + "chat_id": { + "name": "chat_id", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "message_id": { + "name": "message_id", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "author_id": { + "name": "author_id", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "timestamp": { + "name": "timestamp", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true + }, + "message": { + "name": "message", + "type": "varchar(8704)", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "tg_messages_chat_author_timestamp_idx": { + "name": "tg_messages_chat_author_timestamp_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "author_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "timestamp", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "tg_messages_chat_id_message_id_pk": { + "name": "tg_messages_chat_id_message_id_pk", + "columns": [ + "chat_id", + "message_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.tg_test": { + "name": "tg_test", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "tg_test_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "text": { + "name": "text", + "type": "varchar", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.tg_users": { + "name": "tg_users", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "bigint", + "primaryKey": true, + "notNull": true + }, + "first_name": { + "name": "first_name", + "type": "varchar(512)", + "primaryKey": false, + "notNull": true + }, + "last_name": { + "name": "last_name", + "type": "varchar(512)", + "primaryKey": false, + "notNull": false + }, + "username": { + "name": "username", + "type": "varchar(128)", + "primaryKey": false, + "notNull": false + }, + "is_bot": { + "name": "is_bot", + "type": "boolean", + "primaryKey": false, + "notNull": true + }, + "lang_code": { + "name": "lang_code", + "type": "varchar(35)", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.wa_group_label_relations": { + "name": "wa_group_label_relations", + "schema": "", + "columns": { + "group_id": { + "name": "group_id", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "label_id": { + "name": "label_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "wa_group_label_relations_group_id_wa_groups_group_id_fk": { + "name": "wa_group_label_relations_group_id_wa_groups_group_id_fk", + "tableFrom": "wa_group_label_relations", + "tableTo": "wa_groups", + "columnsFrom": [ + "group_id" + ], + "columnsTo": [ + "group_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "wa_group_label_relations_label_id_common_group_labels_id_fk": { + "name": "wa_group_label_relations_label_id_common_group_labels_id_fk", + "tableFrom": "wa_group_label_relations", + "tableTo": "common_group_labels", + "columnsFrom": [ + "label_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "wa_group_label_relations_group_id_label_id_pk": { + "name": "wa_group_label_relations_group_id_label_id_pk", + "columns": [ + "group_id", + "label_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.wa_groups": { + "name": "wa_groups", + "schema": "", + "columns": { + "group_id": { + "name": "group_id", + "type": "bigint", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "wa_groups_group_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "9223372036854775807", + "cache": "1", + "cycle": false + } + }, + "title": { + "name": "title", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "link": { + "name": "link", + "type": "varchar(128)", + "primaryKey": false, + "notNull": false + }, + "hide": { + "name": "hide", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "wa_groups_link_unique": { + "name": "wa_groups_link_unique", + "nullsNotDistinct": false, + "columns": [ + "link" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.web_associations": { + "name": "web_associations", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "web_associations_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description_it": { + "name": "description_it", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description_en": { + "name": "description_en", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "logo": { + "name": "logo", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "website": { + "name": "website", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "facebook": { + "name": "facebook", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "instagram": { + "name": "instagram", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tiktok": { + "name": "tiktok", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "x": { + "name": "x", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "youtube": { + "name": "youtube", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "telegram": { + "name": "telegram", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "linkedin": { + "name": "linkedin", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "spotify": { + "name": "spotify", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "legacy_created_by_tg_id": { + "name": "legacy_created_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "legacy_modified_by_tg_id": { + "name": "legacy_modified_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "created_by_sub": { + "name": "created_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "modified_by_sub": { + "name": "modified_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "web_associations_creator_check": { + "name": "web_associations_creator_check", + "value": "\"web_associations\".\"legacy_created_by_tg_id\" IS NOT NULL OR \"web_associations\".\"created_by_sub\" IS NOT NULL" + } + }, + "isRLSEnabled": false + }, + "public.web_document_categories": { + "name": "web_document_categories", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "web_document_categories_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "legacy_created_by_tg_id": { + "name": "legacy_created_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "legacy_modified_by_tg_id": { + "name": "legacy_modified_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "created_by_sub": { + "name": "created_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "modified_by_sub": { + "name": "modified_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "web_document_categories_slug_unique": { + "name": "web_document_categories_slug_unique", + "nullsNotDistinct": false, + "columns": [ + "slug" + ] + } + }, + "policies": {}, + "checkConstraints": { + "web_document_categories_creator_check": { + "name": "web_document_categories_creator_check", + "value": "\"web_document_categories\".\"legacy_created_by_tg_id\" IS NOT NULL OR \"web_document_categories\".\"created_by_sub\" IS NOT NULL" + } + }, + "isRLSEnabled": false + }, + "public.web_document_versions": { + "name": "web_document_versions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "web_document_versions_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "document_id": { + "name": "document_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "version": { + "name": "version", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "date": { + "name": "date", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "file": { + "name": "file", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "legacy_created_by_tg_id": { + "name": "legacy_created_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "legacy_modified_by_tg_id": { + "name": "legacy_modified_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "created_by_sub": { + "name": "created_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "modified_by_sub": { + "name": "modified_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "web_document_versions_document_id_web_documents_id_fk": { + "name": "web_document_versions_document_id_web_documents_id_fk", + "tableFrom": "web_document_versions", + "tableTo": "web_documents", + "columnsFrom": [ + "document_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "web_document_versions_document_id_version_unique": { + "name": "web_document_versions_document_id_version_unique", + "nullsNotDistinct": false, + "columns": [ + "document_id", + "version" + ] + } + }, + "policies": {}, + "checkConstraints": { + "web_document_versions_creator_check": { + "name": "web_document_versions_creator_check", + "value": "\"web_document_versions\".\"legacy_created_by_tg_id\" IS NOT NULL OR \"web_document_versions\".\"created_by_sub\" IS NOT NULL" + } + }, + "isRLSEnabled": false + }, + "public.web_documents": { + "name": "web_documents", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "web_documents_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "category_id": { + "name": "category_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "slug": { + "name": "slug", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "legacy_created_by_tg_id": { + "name": "legacy_created_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "legacy_modified_by_tg_id": { + "name": "legacy_modified_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "created_by_sub": { + "name": "created_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "modified_by_sub": { + "name": "modified_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "web_documents_category_id_idx": { + "name": "web_documents_category_id_idx", + "columns": [ + { + "expression": "category_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "web_documents_category_id_web_document_categories_id_fk": { + "name": "web_documents_category_id_web_document_categories_id_fk", + "tableFrom": "web_documents", + "tableTo": "web_document_categories", + "columnsFrom": [ + "category_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "web_documents_slug_unique": { + "name": "web_documents_slug_unique", + "nullsNotDistinct": false, + "columns": [ + "slug" + ] + } + }, + "policies": {}, + "checkConstraints": { + "web_documents_creator_check": { + "name": "web_documents_creator_check", + "value": "\"web_documents\".\"legacy_created_by_tg_id\" IS NOT NULL OR \"web_documents\".\"created_by_sub\" IS NOT NULL" + } + }, + "isRLSEnabled": false + }, + "public.web_faq_categories": { + "name": "web_faq_categories", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "web_faq_categories_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "title_it": { + "name": "title_it", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title_en": { + "name": "title_en", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "icon": { + "name": "icon", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "legacy_created_by_tg_id": { + "name": "legacy_created_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "legacy_modified_by_tg_id": { + "name": "legacy_modified_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "created_by_sub": { + "name": "created_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "modified_by_sub": { + "name": "modified_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "web_faq_categories_creator_check": { + "name": "web_faq_categories_creator_check", + "value": "\"web_faq_categories\".\"legacy_created_by_tg_id\" IS NOT NULL OR \"web_faq_categories\".\"created_by_sub\" IS NOT NULL" + } + }, + "isRLSEnabled": false + }, + "public.web_faqs": { + "name": "web_faqs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "web_faqs_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "title_it": { + "name": "title_it", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title_en": { + "name": "title_en", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description_it": { + "name": "description_it", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description_en": { + "name": "description_en", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "category_id": { + "name": "category_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "legacy_created_by_tg_id": { + "name": "legacy_created_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "legacy_modified_by_tg_id": { + "name": "legacy_modified_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "created_by_sub": { + "name": "created_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "modified_by_sub": { + "name": "modified_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "web_faqs_category_id_web_faq_categories_id_fk": { + "name": "web_faqs_category_id_web_faq_categories_id_fk", + "tableFrom": "web_faqs", + "tableTo": "web_faq_categories", + "columnsFrom": [ + "category_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "web_faqs_creator_check": { + "name": "web_faqs_creator_check", + "value": "\"web_faqs\".\"legacy_created_by_tg_id\" IS NOT NULL OR \"web_faqs\".\"created_by_sub\" IS NOT NULL" + } + }, + "isRLSEnabled": false + }, + "public.web_freshman_cards": { + "name": "web_freshman_cards", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "icon": { + "name": "icon", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "href": { + "name": "href", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "legacy_created_by_tg_id": { + "name": "legacy_created_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "legacy_modified_by_tg_id": { + "name": "legacy_modified_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "created_by_sub": { + "name": "created_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "modified_by_sub": { + "name": "modified_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "web_freshman_cards_creator_check": { + "name": "web_freshman_cards_creator_check", + "value": "\"web_freshman_cards\".\"legacy_created_by_tg_id\" IS NOT NULL OR \"web_freshman_cards\".\"created_by_sub\" IS NOT NULL" + }, + "web_freshman_cards_slot_check": { + "name": "web_freshman_cards_slot_check", + "value": "\"web_freshman_cards\".\"id\" in ('featured-1', 'featured-2', 'guides-1', 'guides-2', 'guides-3', 'guides-4', 'guides-5', 'materials-1', 'tools-1', 'tools-2', 'telegram-1', 'telegram-2', 'telegram-3', 'telegram-4', 'telegram-5', 'telegram-6', 'telegram-7', 'telegram-8')" + }, + "web_freshman_cards_icon_check": { + "name": "web_freshman_cards_icon_check", + "value": "\"web_freshman_cards\".\"icon\" in ('chart', 'monitor', 'book', 'map', 'news', 'money', 'folder', 'repeat', 'refresh', 'bell', 'user', 'users', 'cart', 'home')" + } + }, + "isRLSEnabled": false + }, + "public.web_freshman_faqs": { + "name": "web_freshman_faqs", + "schema": "", + "columns": { + "position": { + "name": "position", + "type": "integer", + "primaryKey": true, + "notNull": true + }, + "faq_id": { + "name": "faq_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "legacy_created_by_tg_id": { + "name": "legacy_created_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "legacy_modified_by_tg_id": { + "name": "legacy_modified_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "created_by_sub": { + "name": "created_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "modified_by_sub": { + "name": "modified_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "web_freshman_faqs_faq_id_web_faqs_id_fk": { + "name": "web_freshman_faqs_faq_id_web_faqs_id_fk", + "tableFrom": "web_freshman_faqs", + "tableTo": "web_faqs", + "columnsFrom": [ + "faq_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "restrict", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "web_freshman_faqs_faq_id_unique": { + "name": "web_freshman_faqs_faq_id_unique", + "nullsNotDistinct": false, + "columns": [ + "faq_id" + ] + } + }, + "policies": {}, + "checkConstraints": { + "web_freshman_faqs_creator_check": { + "name": "web_freshman_faqs_creator_check", + "value": "\"web_freshman_faqs\".\"legacy_created_by_tg_id\" IS NOT NULL OR \"web_freshman_faqs\".\"created_by_sub\" IS NOT NULL" + }, + "web_freshman_faqs_position_check": { + "name": "web_freshman_faqs_position_check", + "value": "\"web_freshman_faqs\".\"position\" between 0 and 4" + } + }, + "isRLSEnabled": false + }, + "public.web_group_link_reports": { + "name": "web_group_link_reports", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "web_group_link_reports_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "group_id": { + "name": "group_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "type": { + "name": "type", + "type": "varchar(2)", + "primaryKey": false, + "notNull": false + }, + "report_type": { + "name": "report_type", + "type": "varchar(32)", + "primaryKey": false, + "notNull": true + }, + "reported_link": { + "name": "reported_link", + "type": "varchar(256)", + "primaryKey": false, + "notNull": false + }, + "label": { + "name": "label", + "type": "varchar(256)", + "primaryKey": false, + "notNull": false + }, + "details": { + "name": "details", + "type": "varchar(500)", + "primaryKey": false, + "notNull": false + }, + "status": { + "name": "status", + "type": "varchar(16)", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.web_guides_matricole": { + "name": "web_guides_matricole", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "web_guides_matricole_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "version": { + "name": "version", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "date": { + "name": "date", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "file": { + "name": "file", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "legacy_created_by_tg_id": { + "name": "legacy_created_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "legacy_modified_by_tg_id": { + "name": "legacy_modified_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "created_by_sub": { + "name": "created_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "modified_by_sub": { + "name": "modified_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "web_guides_matricole_version_unique": { + "name": "web_guides_matricole_version_unique", + "nullsNotDistinct": false, + "columns": [ + "version" + ] + } + }, + "policies": {}, + "checkConstraints": { + "web_guides_matricole_creator_check": { + "name": "web_guides_matricole_creator_check", + "value": "\"web_guides_matricole\".\"legacy_created_by_tg_id\" IS NOT NULL OR \"web_guides_matricole\".\"created_by_sub\" IS NOT NULL" + } + }, + "isRLSEnabled": false + }, + "public.web_projects": { + "name": "web_projects", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "web_projects_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description_it": { + "name": "description_it", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description_en": { + "name": "description_en", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "logo": { + "name": "logo", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "link": { + "name": "link", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "category": { + "name": "category", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'general'" + }, + "order": { + "name": "order", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "legacy_created_by_tg_id": { + "name": "legacy_created_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "legacy_modified_by_tg_id": { + "name": "legacy_modified_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "created_by_sub": { + "name": "created_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "modified_by_sub": { + "name": "modified_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "web_projects_creator_check": { + "name": "web_projects_creator_check", + "value": "\"web_projects\".\"legacy_created_by_tg_id\" IS NOT NULL OR \"web_projects\".\"created_by_sub\" IS NOT NULL" + } + }, + "isRLSEnabled": false + }, + "public.web_test": { + "name": "web_test", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "web_test_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "text": { + "name": "text", + "type": "varchar", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + } + }, + "enums": {}, + "schemas": {}, + "sequences": {}, + "roles": {}, + "policies": {}, + "views": { + "public.groups_view": { + "columns": { + "telegram_id": { + "name": "telegram_id", + "type": "bigint", + "primaryKey": true, + "notNull": true + }, + "title": { + "name": "title", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "link": { + "name": "link", + "type": "varchar(128)", + "primaryKey": false, + "notNull": false + }, + "hide": { + "name": "hide", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + } + }, + "definition": "(select \"telegram_id\", \"title\", \"link\", \"hide\", 'tg' as \"type\" from \"tg_groups\") union all (select \"group_id\", \"title\", \"link\", \"hide\", 'wa' as \"type\" from \"wa_groups\")", + "name": "groups_view", + "schema": "public", + "isExisting": false, + "materialized": false + }, + "public.group_label_relations_view": { + "columns": { + "group_id": { + "name": "group_id", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "label_id": { + "name": "label_id", + "type": "integer", + "primaryKey": false, + "notNull": true + } + }, + "definition": "(select \"group_id\", \"label_id\", 'tg' as \"type\" from \"tg_group_label_relations\") union all (select \"group_id\", \"label_id\", 'wa' as \"type\" from \"wa_group_label_relations\")", + "name": "group_label_relations_view", + "schema": "public", + "isExisting": false, + "materialized": false + } + }, + "_meta": { + "columns": {}, + "schemas": {}, + "tables": {} + } +} \ No newline at end of file diff --git a/drizzle/meta/_journal.json b/drizzle/meta/_journal.json index 92e4b30..01e4071 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -260,6 +260,13 @@ "when": 1794572877513, "tag": "0036_soci_fees", "breakpoints": true + }, + { + "idx": 37, + "version": "7", + "when": 1794598289997, + "tag": "0037_web_documents", + "breakpoints": true } ] } \ No newline at end of file diff --git a/src/db/schema/web/documents.ts b/src/db/schema/web/documents.ts new file mode 100644 index 0000000..ed06f88 --- /dev/null +++ b/src/db/schema/web/documents.ts @@ -0,0 +1,61 @@ +import { bigint, index, integer, text, unique } from "drizzle-orm/pg-core" +import { authorSubColumns, hasCreator, timeColumns } from "@/db/columns" +import { createTable } from "../create-table" + +export const webDocumentCategories = createTable.web( + "document_categories", + { + id: integer().primaryKey().generatedAlwaysAsIdentity(), + slug: text("slug").notNull().unique(), + title: text("title").notNull(), + description: text("description").notNull(), + position: integer("position").notNull().default(0), + legacyCreatedByTgId: bigint("legacy_created_by_tg_id", { mode: "number" }), + legacyModifiedByTgId: bigint("legacy_modified_by_tg_id", { mode: "number" }), + ...authorSubColumns, + ...timeColumns, + }, + (t) => [hasCreator("web_document_categories", t)] +) + +export const webDocuments = createTable.web( + "documents", + { + id: integer().primaryKey().generatedAlwaysAsIdentity(), + categoryId: integer("category_id") + .notNull() + .references(() => webDocumentCategories.id, { onDelete: "restrict" }), + slug: text("slug").notNull().unique(), + title: text("title").notNull(), + description: text("description"), + position: integer("position").notNull().default(0), + legacyCreatedByTgId: bigint("legacy_created_by_tg_id", { mode: "number" }), + legacyModifiedByTgId: bigint("legacy_modified_by_tg_id", { mode: "number" }), + ...authorSubColumns, + ...timeColumns, + }, + (t) => [hasCreator("web_documents", t), index("web_documents_category_id_idx").on(t.categoryId)] +) + +/** Every uploaded PDF of a document; the website shows the latest by date, then by id. */ +export const webDocumentVersions = createTable.web( + "document_versions", + { + id: integer().primaryKey().generatedAlwaysAsIdentity(), + documentId: integer("document_id") + .notNull() + .references(() => webDocuments.id, { onDelete: "cascade" }), + version: text("version").notNull(), + /** YYYY-MM-DD, like the freshman guides. */ + date: text("date").notNull(), + file: text("file").notNull(), + legacyCreatedByTgId: bigint("legacy_created_by_tg_id", { mode: "number" }), + legacyModifiedByTgId: bigint("legacy_modified_by_tg_id", { mode: "number" }), + ...authorSubColumns, + ...timeColumns, + }, + (t) => [ + hasCreator("web_document_versions", t), + unique("web_document_versions_document_id_version_unique").on(t.documentId, t.version), + ] +) diff --git a/src/db/schema/web/index.ts b/src/db/schema/web/index.ts index 8df6487..15d73c3 100644 --- a/src/db/schema/web/index.ts +++ b/src/db/schema/web/index.ts @@ -1,4 +1,5 @@ import * as associations from "./associations" +import * as documents from "./documents" import * as faqs from "./faqs" import * as freshman from "./freshman" import * as groupLinkReports from "./group-link-reports" @@ -13,5 +14,6 @@ export const schema = { ...freshman, ...projects, ...guides_matricole, + ...documents, ...groupLinkReports, } diff --git a/src/routers/web/documents.ts b/src/routers/web/documents.ts new file mode 100644 index 0000000..4759040 --- /dev/null +++ b/src/routers/web/documents.ts @@ -0,0 +1,424 @@ +import { and, asc, desc, eq, max, ne } from "drizzle-orm" +import z from "zod" +import { deleteBlob, uploadBlob } from "@/azure/blob" +import { DB, SCHEMA } from "@/db" +import { authorOf, createdByColumns, modifiedByColumns } from "@/idp/author" +import { dashboard, publicData } from "@/idp/policies" +import { createTRPCRouter, policy } from "@/trpc" + +const CATEGORIES = SCHEMA.WEB.webDocumentCategories +const DOCUMENTS = SCHEMA.WEB.webDocuments +const VERSIONS = SCHEMA.WEB.webDocumentVersions + +const slugSchema = z + .string() + .max(100) + .regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "Use lowercase kebab-case") +const titleSchema = z.string().trim().min(1).max(200) +const descriptionSchema = z.string().trim().max(2000) +const idSchema = z.number().int().positive() +const orderSchema = z + .array(idSchema) + .min(1) + .refine((ids) => new Set(ids).size === ids.length, "Duplicate ids") + +const documentFileSchema = z + .file() + .mime(["application/pdf"]) + .min(1) + .max(10 * 1024 * 1024) + +const versionFormSchema = z.object({ + documentId: z.coerce.number().int().positive(), + version: z.string().trim().min(1).max(50), + date: z.iso.date(), + file: documentFileSchema, +}) + +const versionSchema = z.object({ id: z.number(), version: z.string(), date: z.string(), file: z.string() }) +const categoryRowSchema = z.object({ + id: z.number(), + slug: z.string(), + title: z.string(), + description: z.string(), + position: z.number(), +}) +const documentRowSchema = z.object({ + id: z.number(), + categoryId: z.number(), + slug: z.string(), + title: z.string(), + description: z.string().nullable(), + position: z.number(), +}) + +const versionColumns = { id: VERSIONS.id, version: VERSIONS.version, date: VERSIONS.date, file: VERSIONS.file } +const categoryColumns = { + id: CATEGORIES.id, + slug: CATEGORIES.slug, + title: CATEGORIES.title, + description: CATEGORIES.description, + position: CATEGORIES.position, +} +const documentColumns = { + id: DOCUMENTS.id, + categoryId: DOCUMENTS.categoryId, + slug: DOCUMENTS.slug, + title: DOCUMENTS.title, + description: DOCUMENTS.description, + position: DOCUMENTS.position, +} +/** Newest first: the greatest date, then the greatest id. */ +const newestFirst = [desc(VERSIONS.date), desc(VERSIONS.id)] + +type Tx = Parameters[0]>[0] + +/** Every category, document and version in display order, read from one snapshot. */ +async function readCatalog() { + return DB.transaction( + async (tx) => { + const categories = await tx + .select(categoryColumns) + .from(CATEGORIES) + .orderBy(asc(CATEGORIES.position), asc(CATEGORIES.id)) + const documents = await tx + .select(documentColumns) + .from(DOCUMENTS) + .orderBy(asc(DOCUMENTS.position), asc(DOCUMENTS.id)) + const versions = await tx + .select({ ...versionColumns, documentId: VERSIONS.documentId }) + .from(VERSIONS) + .orderBy(...newestFirst) + + const versionsByDocument = new Map[]>() + for (const { documentId, ...version } of versions) { + const list = versionsByDocument.get(documentId) ?? [] + list.push(version) + versionsByDocument.set(documentId, list) + } + return categories.map((category) => ({ + ...category, + documents: documents + .filter((document) => document.categoryId === category.id) + .map(({ categoryId: _, ...document }) => ({ + ...document, + versions: versionsByDocument.get(document.id) ?? [], + })), + })) + }, + { isolationLevel: "repeatable read", accessMode: "read only" } + ) +} + +async function slugTaken(tx: Tx, table: typeof CATEGORIES | typeof DOCUMENTS, slug: string, exceptId?: number) { + const [row] = await tx + .select({ id: table.id }) + .from(table) + .where(exceptId === undefined ? eq(table.slug, slug) : and(eq(table.slug, slug), ne(table.id, exceptId))) + .limit(1) + return !!row +} + +/** The position after the last document of a category. */ +async function nextDocumentPosition(tx: Tx, categoryId: number) { + const [{ last }] = await tx + .select({ last: max(DOCUMENTS.position) }) + .from(DOCUMENTS) + .where(eq(DOCUMENTS.categoryId, categoryId)) + return last === null ? 0 : last + 1 +} + +/** Locks a category so documents cannot be added to it while it is being deleted, and vice versa. */ +async function lockCategory(tx: Tx, id: number) { + const [row] = await tx.select({ id: CATEGORIES.id }).from(CATEGORIES).where(eq(CATEGORIES.id, id)).for("share") + return !!row +} + +export default createTRPCRouter({ + getCatalog: policy(publicData) + .output( + z.array( + categoryRowSchema.extend({ + documents: z.array(documentRowSchema.omit({ categoryId: true }).extend({ latest: versionSchema })), + }) + ) + ) + .query(async () => { + const catalog = await readCatalog() + return catalog + .map(({ documents, ...category }) => ({ + ...category, + documents: documents.flatMap(({ versions, ...document }) => + versions.length ? [{ ...document, latest: versions[0] }] : [] + ), + })) + .filter((category) => category.documents.length > 0) + }), + + getDocument: policy(publicData) + .input(z.object({ slug: z.string() })) + .output( + documentRowSchema + .omit({ categoryId: true, position: true }) + .extend({ + category: categoryRowSchema.pick({ id: true, slug: true, title: true }), + latest: versionSchema, + versions: z.array(versionSchema), + }) + .nullable() + ) + .query(async ({ input }) => { + return DB.transaction( + async (tx) => { + const [document] = await tx + .select({ + id: DOCUMENTS.id, + slug: DOCUMENTS.slug, + title: DOCUMENTS.title, + description: DOCUMENTS.description, + category: { id: CATEGORIES.id, slug: CATEGORIES.slug, title: CATEGORIES.title }, + }) + .from(DOCUMENTS) + .innerJoin(CATEGORIES, eq(DOCUMENTS.categoryId, CATEGORIES.id)) + .where(eq(DOCUMENTS.slug, input.slug)) + .limit(1) + if (!document) return null + const versions = await tx + .select(versionColumns) + .from(VERSIONS) + .where(eq(VERSIONS.documentId, document.id)) + .orderBy(...newestFirst) + if (!versions.length) return null + return { ...document, latest: versions[0], versions } + }, + { isolationLevel: "repeatable read", accessMode: "read only" } + ) + }), + + getAdminCatalog: policy(dashboard("admin:access")) + .output( + z.array( + categoryRowSchema.extend({ + documents: z.array(documentRowSchema.omit({ categoryId: true }).extend({ versions: z.array(versionSchema) })), + }) + ) + ) + .query(async () => readCatalog()), + + createCategory: policy(dashboard("web:content:write")) + .input(z.object({ slug: slugSchema, title: titleSchema, description: descriptionSchema })) + .mutation(async ({ input, ctx }) => { + return DB.transaction(async (tx) => { + const [{ last }] = await tx.select({ last: max(CATEGORIES.position) }).from(CATEGORIES) + const [row] = await tx + .insert(CATEGORIES) + .values({ ...input, position: last === null ? 0 : last + 1, ...createdByColumns(authorOf(ctx.actor)) }) + .onConflictDoNothing({ target: CATEGORIES.slug }) + .returning(categoryColumns) + if (!row) return { error: "DUPLICATE_SLUG" as const } + return row + }) + }), + + updateCategory: policy(dashboard("web:content:write")) + .input( + z.object({ + id: idSchema, + slug: slugSchema.optional(), + title: titleSchema.optional(), + description: descriptionSchema.optional(), + }) + ) + .mutation(async ({ input, ctx }) => { + const { id, ...fields } = input + return DB.transaction(async (tx) => { + if (fields.slug !== undefined && (await slugTaken(tx, CATEGORIES, fields.slug, id))) + return { error: "DUPLICATE_SLUG" as const } + const [row] = await tx + .update(CATEGORIES) + .set({ ...fields, ...modifiedByColumns(authorOf(ctx.actor)) }) + .where(eq(CATEGORIES.id, id)) + .returning(categoryColumns) + if (!row) return { error: "NOT_FOUND" as const } + return row + }) + }), + + deleteCategory: policy(dashboard("web:content:write")) + .input(z.object({ id: idSchema })) + .mutation(async ({ input }) => { + return DB.transaction(async (tx) => { + const [category] = await tx + .select({ id: CATEGORIES.id }) + .from(CATEGORIES) + .where(eq(CATEGORIES.id, input.id)) + .for("update") + if (!category) return { error: "NOT_FOUND" as const } + const [document] = await tx + .select({ id: DOCUMENTS.id }) + .from(DOCUMENTS) + .where(eq(DOCUMENTS.categoryId, input.id)) + .limit(1) + if (document) return { error: "CATEGORY_NOT_EMPTY" as const } + await tx.delete(CATEGORIES).where(eq(CATEGORIES.id, input.id)) + return { error: null } + }) + }), + + reorderCategories: policy(dashboard("web:content:write")) + .input(z.object({ ids: orderSchema })) + .mutation(async ({ input }) => { + await DB.transaction(async (tx) => { + for (const [position, id] of input.ids.entries()) + await tx.update(CATEGORIES).set({ position }).where(eq(CATEGORIES.id, id)) + }) + return { error: null } + }), + + createDocument: policy(dashboard("web:content:write")) + .input( + z.object({ + categoryId: idSchema, + slug: slugSchema, + title: titleSchema, + description: descriptionSchema.nullish(), + }) + ) + .mutation(async ({ input, ctx }) => { + return DB.transaction(async (tx) => { + if (!(await lockCategory(tx, input.categoryId))) return { error: "CATEGORY_NOT_FOUND" as const } + const [row] = await tx + .insert(DOCUMENTS) + .values({ + ...input, + description: input.description || null, + position: await nextDocumentPosition(tx, input.categoryId), + ...createdByColumns(authorOf(ctx.actor)), + }) + .onConflictDoNothing({ target: DOCUMENTS.slug }) + .returning(documentColumns) + if (!row) return { error: "DUPLICATE_SLUG" as const } + return row + }) + }), + + updateDocument: policy(dashboard("web:content:write")) + .input( + z.object({ + id: idSchema, + categoryId: idSchema.optional(), + slug: slugSchema.optional(), + title: titleSchema.optional(), + description: descriptionSchema.nullish(), + }) + ) + .mutation(async ({ input, ctx }) => { + const { id, categoryId, description, ...fields } = input + return DB.transaction(async (tx) => { + const [current] = await tx + .select({ categoryId: DOCUMENTS.categoryId }) + .from(DOCUMENTS) + .where(eq(DOCUMENTS.id, id)) + .for("update") + if (!current) return { error: "NOT_FOUND" as const } + const moving = categoryId !== undefined && categoryId !== current.categoryId + if (moving && !(await lockCategory(tx, categoryId))) return { error: "CATEGORY_NOT_FOUND" as const } + if (fields.slug !== undefined && (await slugTaken(tx, DOCUMENTS, fields.slug, id))) + return { error: "DUPLICATE_SLUG" as const } + const [row] = await tx + .update(DOCUMENTS) + .set({ + ...fields, + ...(description !== undefined ? { description: description || null } : {}), + // A document moved to another category goes last in it. + ...(moving ? { categoryId, position: await nextDocumentPosition(tx, categoryId) } : {}), + ...modifiedByColumns(authorOf(ctx.actor)), + }) + .where(eq(DOCUMENTS.id, id)) + .returning(documentColumns) + return row + }) + }), + + deleteDocument: policy(dashboard("web:content:write")) + .input(z.object({ id: idSchema })) + .mutation(async ({ input }) => { + const files = await DB.transaction(async (tx) => { + const [document] = await tx + .select({ id: DOCUMENTS.id }) + .from(DOCUMENTS) + .where(eq(DOCUMENTS.id, input.id)) + .for("update") + if (!document) return null + const versions = await tx + .delete(VERSIONS) + .where(eq(VERSIONS.documentId, input.id)) + .returning({ file: VERSIONS.file }) + await tx.delete(DOCUMENTS).where(eq(DOCUMENTS.id, input.id)) + return versions.map((version) => version.file) + }) + if (!files) return { error: "NOT_FOUND" as const } + await Promise.all(files.map((file) => deleteBlob(file))) + return { error: null } + }), + + reorderDocuments: policy(dashboard("web:content:write")) + .input(z.object({ categoryId: idSchema, ids: orderSchema })) + .mutation(async ({ input }) => { + await DB.transaction(async (tx) => { + for (const [position, id] of input.ids.entries()) + await tx + .update(DOCUMENTS) + .set({ position }) + .where(and(eq(DOCUMENTS.id, id), eq(DOCUMENTS.categoryId, input.categoryId))) + }) + return { error: null } + }), + + addVersion: policy(dashboard("web:content:write")) + .input( + z + .instanceof(FormData) + .transform((fd): Record => Object.fromEntries(fd.entries())) + .pipe(versionFormSchema) + ) + .mutation(async ({ input, ctx }) => { + const { documentId, version, date, file } = input + const author = createdByColumns(authorOf(ctx.actor)) + + const [document] = await DB.select({ id: DOCUMENTS.id }).from(DOCUMENTS).where(eq(DOCUMENTS.id, documentId)) + if (!document) return { error: "NOT_FOUND" as const } + const [existing] = await DB.select({ id: VERSIONS.id }) + .from(VERSIONS) + .where(and(eq(VERSIONS.documentId, documentId), eq(VERSIONS.version, version))) + if (existing) return { error: "DUPLICATE_VERSION" as const } + + const uploadedFile = await uploadBlob(Buffer.from(await file.arrayBuffer()), "pdf", file.type) + // The document may have been deleted, or the version added, while the file was uploading. + const result = await DB.transaction(async (tx) => { + const [locked] = await tx + .select({ id: DOCUMENTS.id }) + .from(DOCUMENTS) + .where(eq(DOCUMENTS.id, documentId)) + .for("share") + if (!locked) return { error: "NOT_FOUND" as const } + const [row] = await tx + .insert(VERSIONS) + .values({ documentId, version, date, file: uploadedFile.url, ...author }) + .onConflictDoNothing({ target: [VERSIONS.documentId, VERSIONS.version] }) + .returning(versionColumns) + return row ?? { error: "DUPLICATE_VERSION" as const } + }) + if ("error" in result) await deleteBlob(uploadedFile.url) + return result + }), + + deleteVersion: policy(dashboard("web:content:write")) + .input(z.object({ id: idSchema })) + .mutation(async ({ input }) => { + const [deleted] = await DB.delete(VERSIONS).where(eq(VERSIONS.id, input.id)).returning({ file: VERSIONS.file }) + if (!deleted) return { error: "NOT_FOUND" as const } + await deleteBlob(deleted.file) + return { error: null } + }), +}) diff --git a/src/routers/web/index.ts b/src/routers/web/index.ts index 233b8db..10e09f3 100644 --- a/src/routers/web/index.ts +++ b/src/routers/web/index.ts @@ -1,9 +1,18 @@ import { createTRPCRouter } from "@/trpc" import { reports } from "../web/reports" import associations from "./associations" +import documents from "./documents" import faqs from "./faqs" import freshman from "./freshman" import guides_matricole from "./guides_matricole" import projects from "./projects" -export const webRouter = createTRPCRouter({ associations, faqs, freshman, projects, guides_matricole, reports }) +export const webRouter = createTRPCRouter({ + associations, + documents, + faqs, + freshman, + projects, + guides_matricole, + reports, +}) diff --git a/tests/documents-postgres.fixture.ts b/tests/documents-postgres.fixture.ts new file mode 100644 index 0000000..a72cc26 --- /dev/null +++ b/tests/documents-postgres.fixture.ts @@ -0,0 +1,256 @@ +import assert from "node:assert/strict" +import { SQL } from "bun" +import type { Context } from "@/trpc" + +// A disposable database on the integration server, with the fixed test credentials used in CI. +const config = { hostname: "127.0.0.1", port: Number(process.env.SEED_TEST_DB_PORT), username: "seed_test" } +const password = "seed_test" +const database = `documents_test_${process.pid}` +const admin = new SQL({ ...config, password, database: "postgres" }) +await admin.unsafe(`CREATE DATABASE ${database}`) +const connection = new SQL({ ...config, password, database }) +const checked: string[] = [] +let closeBackend: (() => Promise) | undefined +try { + Object.assign(process.env, { + NODE_ENV: "test", + DB_HOST: config.hostname, + DB_PORT: String(config.port), + DB_USER: config.username, + DB_PASS: password, + DB_NAME: database, + ENCRYPTION_KEY: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", + }) + const { DB } = await import("@/db") // Applies every migration, the documents tables included. + closeBackend = () => DB.$client.close() + + // Keep uploads in memory instead of Azure. + const blob = await import("@/azure/blob") + const stored = new Set() + const removed: string[] = [] + Object.assign(blob.containerClient, { + getBlockBlobClient: (name: string) => ({ + upload: async () => { + stored.add(name) + return { requestId: "test" } + }, + deleteIfExists: async () => { + removed.push(name) + return { succeeded: stored.delete(name) } + }, + }), + }) + + const documents = (await import("@/routers/web/documents")).default + const context = (permissions: string[]): Context => ({ + auth: { + kind: "token", + actor: { kind: "user", sub: "documents-editor", client: "admin", telegramId: null }, + scopes: new Set(["backend:admin"]), + }, + access: { + has: (_, permission) => permissions.includes(permission), + current: () => null, + subjectBySub: () => undefined, + subjectByTelegramId: () => undefined, + status: () => ({ lastSyncAt: 1, fresh: true, generation: 1, subjects: 1 }), + }, + }) + const editor = documents.createCaller(context(["admin:access", "web:content:write"])) + const viewer = documents.createCaller(context(["admin:access"])) + const website = documents.createCaller({ + auth: { kind: "token", actor: { kind: "service", client: "website" }, scopes: new Set(["backend:public:read"]) }, + }) + const pdf = (name = "file.pdf", type = "application/pdf") => new File(["%PDF-1.4 test"], name, { type }) + const form = (fields: Record) => { + const fd = new FormData() + for (const [key, value] of Object.entries(fields)) fd.append(key, value) + return fd + } + const ok = (result: T): Exclude => { + assert.ok(result && typeof result === "object" && !("error" in result), JSON.stringify(result)) + return result as Exclude + } + + assert.deepEqual(await website.getCatalog(), []) + assert.deepEqual(await editor.getAdminCatalog(), []) + await assert.rejects(website.getAdminCatalog(), { code: "FORBIDDEN" }) + await assert.rejects(website.createCategory({ slug: "x", title: "X", description: "" }), { code: "FORBIDDEN" }) + await assert.rejects(viewer.createCategory({ slug: "x", title: "X", description: "" }), { code: "FORBIDDEN" }) + assert.deepEqual(await viewer.getAdminCatalog(), []) + checked.push( + "the website reads only the public catalog; the dashboard reads with admin:access, writes need web:content:write" + ) + + const statuto = ok(await editor.createCategory({ slug: "statuto", title: "Statuto", description: "Atti" })) + const bilanci = ok(await editor.createCategory({ slug: "bilanci", title: "Bilanci", description: "" })) + const vuota = ok(await editor.createCategory({ slug: "vuota", title: "Vuota", description: "" })) + assert.deepEqual(statuto, { id: statuto.id, slug: "statuto", title: "Statuto", description: "Atti", position: 0 }) + assert.deepEqual([bilanci.position, vuota.position], [1, 2]) + assert.deepEqual(await editor.createCategory({ slug: "statuto", title: "Again", description: "" }), { + error: "DUPLICATE_SLUG", + }) + for (const slug of ["Statuto", "a b", "-a", "a--b", "a-", ""]) + await assert.rejects(editor.createCategory({ slug, title: "X", description: "" }), { code: "BAD_REQUEST" }) + assert.deepEqual(await editor.updateCategory({ id: 999_999, title: "X" }), { error: "NOT_FOUND" }) + assert.deepEqual(await editor.updateCategory({ id: bilanci.id, slug: "statuto" }), { error: "DUPLICATE_SLUG" }) + assert.deepEqual(await editor.updateCategory({ id: bilanci.id, slug: "bilanci", title: "Bilanci annuali" }), { + ...bilanci, + title: "Bilanci annuali", + }) + assert.deepEqual( + (await connection`SELECT created_by_sub, modified_by_sub FROM web_document_categories WHERE id = ${bilanci.id}`)[0], + { created_by_sub: "documents-editor", modified_by_sub: "documents-editor" } + ) + checked.push("categories: create goes last, update, duplicate slugs, kebab-case slugs and authorship") + + const atto = ok(await editor.createDocument({ categoryId: statuto.id, slug: "atto-costitutivo", title: "Atto" })) + const statutoDoc = ok( + await editor.createDocument({ categoryId: statuto.id, slug: "statuto", title: "Statuto", description: "Vigente" }) + ) + const bilancio = ok(await editor.createDocument({ categoryId: bilanci.id, slug: "bilancio-2025", title: "B 2025" })) + assert.deepEqual(atto, { + id: atto.id, + categoryId: statuto.id, + slug: "atto-costitutivo", + title: "Atto", + description: null, + position: 0, + }) + assert.deepEqual([statutoDoc.position, bilancio.position], [1, 0]) + assert.deepEqual(await editor.createDocument({ categoryId: 999_999, slug: "x", title: "X" }), { + error: "CATEGORY_NOT_FOUND", + }) + assert.deepEqual(await editor.createDocument({ categoryId: bilanci.id, slug: "statuto", title: "X" }), { + error: "DUPLICATE_SLUG", + }) + assert.deepEqual(await website.getCatalog(), []) + assert.equal(await website.getDocument({ slug: "statuto" }), null) + checked.push("documents: create goes last in its category, errors, and documents without versions stay hidden") + + const addVersion = (documentId: number, version: string, date: string, file: File = pdf()) => + editor.addVersion(form({ documentId: String(documentId), version, date, file })) + const v1 = ok(await addVersion(statutoDoc.id, "1.0", "2024-01-01")) + const v2 = ok(await addVersion(statutoDoc.id, "2.0", "2025-06-01")) + const v3 = ok(await addVersion(statutoDoc.id, "1.1", "2025-06-01")) // Same date, greater id: the latest. + assert.deepEqual(Object.keys(v1).sort(), ["date", "file", "id", "version"]) + assert.deepEqual(await addVersion(statutoDoc.id, "2.0", "2026-01-01"), { error: "DUPLICATE_VERSION" }) + assert.deepEqual(await addVersion(999_999, "1.0", "2026-01-01"), { error: "NOT_FOUND" }) + await assert.rejects(addVersion(statutoDoc.id, "3.0", "2026-01-01", pdf("x.png", "image/png")), { + code: "BAD_REQUEST", + }) + await assert.rejects(addVersion(statutoDoc.id, "3.0", "01/02/2026"), { code: "BAD_REQUEST" }) + assert.equal(stored.size, 3) + ok(await addVersion(atto.id, "2.0", "2020-01-01")) // The same label on another document is allowed. + checked.push("versions: PDF only, ISO dates, unique per document, NOT_FOUND for missing documents") + + const catalog = await website.getCatalog() + assert.deepEqual( + catalog.map((c) => [c.slug, c.documents.map((d) => [d.slug, d.latest.version])]), + [ + [ + "statuto", + [ + ["atto-costitutivo", "2.0"], + ["statuto", "1.1"], + ], + ], + ] + ) + assert.deepEqual(catalog[0].documents[1], { + id: statutoDoc.id, + slug: "statuto", + title: "Statuto", + description: "Vigente", + position: 1, + latest: v3, + }) + assert.equal("createdBySub" in catalog[0], false) + const detail = await website.getDocument({ slug: "statuto" }) + assert.deepEqual(detail, { + id: statutoDoc.id, + slug: "statuto", + title: "Statuto", + description: "Vigente", + category: { id: statuto.id, slug: "statuto", title: "Statuto" }, + latest: v3, + versions: [v3, v2, v1], + }) + assert.equal(await website.getDocument({ slug: "missing" }), null) + const adminCatalog = await editor.getAdminCatalog() + assert.deepEqual( + adminCatalog.map((c) => [c.slug, c.documents.map((d) => [d.slug, d.versions.map((v) => v.version)])]), + [ + [ + "statuto", + [ + ["atto-costitutivo", ["2.0"]], + ["statuto", ["1.1", "2.0", "1.0"]], + ], + ], + ["bilanci", [["bilancio-2025", []]]], + ["vuota", []], + ] + ) + checked.push("the public catalog shows the latest version and hides empty categories; the admin catalog shows all") + + await editor.reorderCategories({ ids: [vuota.id, bilanci.id, statuto.id] }) + await editor.reorderDocuments({ categoryId: statuto.id, ids: [statutoDoc.id, atto.id, bilancio.id] }) + await assert.rejects(editor.reorderCategories({ ids: [vuota.id, vuota.id] }), { code: "BAD_REQUEST" }) + ok(await addVersion(bilancio.id, "2025", "2026-04-30")) + assert.deepEqual( + (await website.getCatalog()).map((c) => [c.slug, c.documents.map((d) => d.slug)]), + [ + ["bilanci", ["bilancio-2025"]], + ["statuto", ["statuto", "atto-costitutivo"]], + ] + ) + // A document of another category is not moved by reordering this one. + assert.equal((await connection`SELECT position FROM web_documents WHERE id = ${bilancio.id}`)[0].position, 0) + checked.push("categories and documents follow their saved order") + + assert.deepEqual(await editor.updateDocument({ id: 999_999, title: "X" }), { error: "NOT_FOUND" }) + assert.deepEqual(await editor.updateDocument({ id: atto.id, categoryId: 999_999 }), { + error: "CATEGORY_NOT_FOUND", + }) + assert.deepEqual(await editor.updateDocument({ id: atto.id, slug: "statuto" }), { error: "DUPLICATE_SLUG" }) + assert.deepEqual(await editor.updateDocument({ id: atto.id, categoryId: bilanci.id, description: "Nuovo" }), { + ...atto, + categoryId: bilanci.id, + description: "Nuovo", + position: 1, + }) + assert.equal(ok(await editor.updateDocument({ id: atto.id, description: null })).description, null) + checked.push("documents: update, move to the end of another category, and errors") + + assert.deepEqual(await editor.deleteCategory({ id: bilanci.id }), { error: "CATEGORY_NOT_EMPTY" }) + assert.deepEqual(await editor.deleteCategory({ id: vuota.id }), { error: null }) + assert.deepEqual(await editor.deleteCategory({ id: vuota.id }), { error: "NOT_FOUND" }) + checked.push("only empty categories can be deleted") + + const before = removed.length + assert.deepEqual(await editor.deleteVersion({ id: v3.id }), { error: null }) + assert.deepEqual(removed.slice(before), [new URL(v3.file).pathname.split("/").pop()]) + assert.deepEqual(await editor.deleteVersion({ id: v3.id }), { error: "NOT_FOUND" }) + assert.deepEqual((await website.getDocument({ slug: "statuto" }))?.latest, v2) + assert.deepEqual(await editor.deleteDocument({ id: statutoDoc.id }), { error: null }) + assert.deepEqual(await editor.deleteDocument({ id: statutoDoc.id }), { error: "NOT_FOUND" }) + assert.deepEqual( + removed.slice(before + 1).sort(), + [v1.file, v2.file].map((file) => new URL(file).pathname.split("/").pop()).sort() + ) + assert.equal( + (await connection`SELECT count(*)::int AS count FROM web_document_versions WHERE document_id = ${statutoDoc.id}`)[0] + .count, + 0 + ) + assert.equal(await website.getDocument({ slug: "statuto" }), null) + checked.push("deleting a version or a document deletes its files") + + console.log(JSON.stringify({ checked })) +} finally { + await closeBackend?.() + await connection.close() + await admin.unsafe(`DROP DATABASE ${database} WITH (FORCE)`) + await admin.close() +} diff --git a/tests/documents-postgres.test.ts b/tests/documents-postgres.test.ts new file mode 100644 index 0000000..c396228 --- /dev/null +++ b/tests/documents-postgres.test.ts @@ -0,0 +1,16 @@ +import { execFile } from "node:child_process" +import { promisify } from "node:util" +import { expect, it } from "vitest" + +it.skipIf(!process.env.SEED_TEST_DB_PORT)( + "serves the website documents catalog and its admin from real PostgreSQL", + async () => { + const { stdout } = await promisify(execFile)("bun", ["--no-env-file", "tests/documents-postgres.fixture.ts"], { + env: { PATH: process.env.PATH, SEED_TEST_DB_PORT: process.env.SEED_TEST_DB_PORT }, + timeout: 60000, + }) + const result = JSON.parse(stdout.trim().split("\n").at(-1) ?? "{}") + expect(result.checked).toHaveLength(9) + }, + 65000 +) From bf8d81db55a145452b2adc3e8b90b4a5c1ddb10d Mon Sep 17 00:00:00 2001 From: Bianca Date: Fri, 13 Nov 2026 20:36:53 +0100 Subject: [PATCH 2/5] chore(seed): add sample website documents to the dev seed Seed two sample document categories with placeholder example.com file links, including a document without versions, following the guides seed. --force replaces them. Co-Authored-By: Claude Opus 5.5 --- README.md | 2 +- scripts/seed-db.ts | 70 +++++++++++++++++++++++++++++++++++++++++++ tests/seed-db.test.ts | 6 +++- 3 files changed, 76 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index 9861528..6b2e9a0 100644 --- a/README.md +++ b/README.md @@ -34,7 +34,7 @@ Requirements: ```sh bun dev ``` -5. (Optional) Fill the database with sample data: Telegram users, groups and messages, course groups and labels, projects, associations, FAQs, freshman guides, group link reports, audit log entries and grants: +5. (Optional) Fill the database with sample data: Telegram users, groups and messages, course groups and labels, projects, associations, FAQs, freshman guides, website documents (with placeholder file links), group link reports, audit log entries and grants: ```sh bun run seed:db ``` diff --git a/scripts/seed-db.ts b/scripts/seed-db.ts index f94d437..2a93359 100644 --- a/scripts/seed-db.ts +++ b/scripts/seed-db.ts @@ -722,6 +722,76 @@ await seedTable("web_guides_matricole", SCHEMA.WEB.guidesMatricole, () => ].map((g) => ({ ...g, file: `https://example.com/seed/guida-matricole-${g.version}.pdf`, ...seedAuthor })) ) +// Documents reference their categories, so the three tables are seeded (or replaced) together. +const DOCUMENT_CONTENT: { + slug: string + title: string + description: string + documents: { slug: string; title: string; description: string | null; versions: [string, string][] }[] +}[] = [ + { + slug: "esempio-statuto", + title: "Statuto e regolamenti (esempio)", + description: "Documenti di esempio per lo sviluppo locale.", + documents: [ + { + slug: "esempio-statuto-associazione", + title: "Statuto di esempio", + description: "Un documento con più versioni.", + versions: [ + ["1.0", "2023-03-01"], + ["2.0", "2025-05-20"], + ], + }, + { + slug: "esempio-regolamento", + title: "Regolamento di esempio", + description: null, + versions: [["1", "2024-10-01"]], + }, + ], + }, + { + slug: "esempio-bilanci", + title: "Bilanci (esempio)", + description: "Una categoria con un documento ancora senza versioni, nascosto dal sito.", + documents: [{ slug: "esempio-bilancio-bozza", title: "Bilancio in bozza", description: null, versions: [] }], + }, +] +const [firstDocumentCategory] = await DB.select().from(SCHEMA.WEB.webDocumentCategories).limit(1) +if (firstDocumentCategory && !force) console.log("SEED: web_document_categories already contains data, skipping") +else { + await DB.transaction(async (tx) => { + if (firstDocumentCategory) { + await tx.delete(SCHEMA.WEB.webDocuments) // Their versions are deleted with them. + await tx.delete(SCHEMA.WEB.webDocumentCategories) + } + for (const [position, { documents, ...category }] of DOCUMENT_CONTENT.entries()) { + const [{ id: categoryId }] = await tx + .insert(SCHEMA.WEB.webDocumentCategories) + .values({ ...category, position, ...seedAuthor }) + .returning({ id: SCHEMA.WEB.webDocumentCategories.id }) + for (const [documentPosition, { versions, ...document }] of documents.entries()) { + const [{ id: documentId }] = await tx + .insert(SCHEMA.WEB.webDocuments) + .values({ ...document, categoryId, position: documentPosition, ...seedAuthor }) + .returning({ id: SCHEMA.WEB.webDocuments.id }) + if (versions.length) + await tx.insert(SCHEMA.WEB.webDocumentVersions).values( + versions.map(([version, date]) => ({ + documentId, + version, + date, + file: `https://example.com/seed/${document.slug}-${version}.pdf`, + ...seedAuthor, + })) + ) + } + } + }) + console.log(`SEED: web_document_categories → ${DOCUMENT_CONTENT.length} rows, with sample documents`) +} + const waGroupIds = (await DB.select({ id: SCHEMA.WA.waGroups.id }).from(SCHEMA.WA.waGroups)).map((g) => g.id) const tgCourseGroupIds = [...tgGroupIdByLink.values()] await seedTable("web_group_link_reports", SCHEMA.WEB.groupLinkReports, () => { diff --git a/tests/seed-db.test.ts b/tests/seed-db.test.ts index cdacd6d..50607c6 100644 --- a/tests/seed-db.test.ts +++ b/tests/seed-db.test.ts @@ -133,9 +133,11 @@ describe.skipIf(!testPort)("database seed", () => { query(`SELECT 'users' AS name, count(*)::int AS count FROM tg_users UNION ALL SELECT 'messages', count(*)::int FROM tg_messages UNION ALL SELECT 'faqs', count(*)::int FROM web_faqs + UNION ALL SELECT 'document_versions', count(*)::int FROM web_document_versions UNION ALL SELECT 'grants', count(*)::int FROM tg_grants ORDER BY name`) const expected = [ + { name: "document_versions", count: 3 }, { name: "faqs", count: 9 }, { name: "grants", count: 11 }, { name: "messages", count: 60000 }, @@ -158,12 +160,14 @@ describe.skipIf(!testPort)("database seed", () => { await query(`UPDATE tg_users SET first_name = 'replace-me'; UPDATE web_faq_categories SET title_it = 'replace-me'; - UPDATE web_projects SET title = 'replace-me'`) + UPDATE web_projects SET title = 'replace-me'; + UPDATE web_document_categories SET title = 'replace-me'`) await seed(true) expect(await counts()).toEqual(expected) expect(await query("SELECT * FROM tg_users WHERE first_name = 'replace-me'")).toEqual([]) expect(await query("SELECT * FROM web_faq_categories WHERE title_it = 'replace-me'")).toEqual([]) expect(await query("SELECT * FROM web_projects WHERE title = 'replace-me'")).toEqual([]) + expect(await query("SELECT * FROM web_document_categories WHERE title = 'replace-me'")).toEqual([]) }, 30_000) }) From 45a58ed5ddad9ebbc1d66d77ad0f8b5af984856e Mon Sep 17 00:00:00 2001 From: Bianca Date: Fri, 13 Nov 2026 20:59:26 +0100 Subject: [PATCH 3/5] fix(documents): handle concurrent writes and failed blob cleanup --- src/routers/web/documents.ts | 133 ++++++++++++++++------ tests/documents-postgres.fixture.ts | 167 +++++++++++++++++++++++++++- tests/documents-postgres.test.ts | 2 +- 3 files changed, 267 insertions(+), 35 deletions(-) diff --git a/src/routers/web/documents.ts b/src/routers/web/documents.ts index 4759040..2d080bd 100644 --- a/src/routers/web/documents.ts +++ b/src/routers/web/documents.ts @@ -1,9 +1,10 @@ -import { and, asc, desc, eq, max, ne } from "drizzle-orm" +import { and, asc, desc, eq, inArray, max, ne, sql } from "drizzle-orm" import z from "zod" import { deleteBlob, uploadBlob } from "@/azure/blob" import { DB, SCHEMA } from "@/db" import { authorOf, createdByColumns, modifiedByColumns } from "@/idp/author" import { dashboard, publicData } from "@/idp/policies" +import { logger } from "@/logger" import { createTRPCRouter, policy } from "@/trpc" const CATEGORIES = SCHEMA.WEB.webDocumentCategories @@ -73,6 +74,52 @@ const newestFirst = [desc(VERSIONS.date), desc(VERSIONS.id)] type Tx = Parameters[0]>[0] +/** The unique constraint a write violated (SQLSTATE 23505), looking through the driver's error wrappers. */ +function violatedUnique(error: unknown): string | null { + for (let cause = error; cause && typeof cause === "object"; cause = (cause as { cause?: unknown }).cause) + if ("errno" in cause && cause.errno === "23505" && "constraint" in cause) return String(cause.constraint) + return null +} + +/** Maps a concurrent write that took the same slug to DUPLICATE_SLUG, rethrowing anything else. */ +function duplicateSlug(table: string) { + return (error: unknown) => { + if (violatedUnique(error) === `${table}_slug_unique`) return { error: "DUPLICATE_SLUG" as const } + throw error + } +} + +/** Deletes files whose rows are already gone; a failure is logged, not reported to the caller. */ +async function deleteBlobs(files: string[]) { + const results = await Promise.allSettled(files.map((file) => deleteBlob(file))) + for (const [index, result] of results.entries()) + if (result.status === "rejected") + logger.error({ err: result.reason, file: files[index] }, "[documents] could not delete a blob") +} + +const sameIds = (a: number[], b: number[]) => a.length === b.length && new Set([...a, ...b]).size === a.length + +/** Serialises changes to the list of categories (creation and reordering), which row locks cannot cover. */ +const lockCategoryList = (tx: Tx) => tx.execute(sql`select pg_advisory_xact_lock(hashtext('web_document_categories'))`) + +// Protects a document's category while its move/delete acquires category locks in id order. +const lockDocument = (tx: Tx, id: number) => + tx.execute(sql`select pg_advisory_xact_lock(hashtext('web_documents'), ${id})`) + +/** + * Locks categories in id order. A category's row lock guards its list of documents: creating, moving and + * reordering documents, and deleting the category, all take it first. + */ +async function lockCategories(tx: Tx, ids: number[]) { + const rows = await tx + .select({ id: CATEGORIES.id }) + .from(CATEGORIES) + .where(inArray(CATEGORIES.id, ids)) + .orderBy(asc(CATEGORIES.id)) + .for("update") + return new Set(rows.map((row) => row.id)) +} + /** Every category, document and version in display order, read from one snapshot. */ async function readCatalog() { return DB.transaction( @@ -128,12 +175,6 @@ async function nextDocumentPosition(tx: Tx, categoryId: number) { return last === null ? 0 : last + 1 } -/** Locks a category so documents cannot be added to it while it is being deleted, and vice versa. */ -async function lockCategory(tx: Tx, id: number) { - const [row] = await tx.select({ id: CATEGORIES.id }).from(CATEGORIES).where(eq(CATEGORIES.id, id)).for("share") - return !!row -} - export default createTRPCRouter({ getCatalog: policy(publicData) .output( @@ -156,7 +197,7 @@ export default createTRPCRouter({ }), getDocument: policy(publicData) - .input(z.object({ slug: z.string() })) + .input(z.object({ slug: slugSchema })) .output( documentRowSchema .omit({ categoryId: true, position: true }) @@ -209,6 +250,7 @@ export default createTRPCRouter({ .input(z.object({ slug: slugSchema, title: titleSchema, description: descriptionSchema })) .mutation(async ({ input, ctx }) => { return DB.transaction(async (tx) => { + await lockCategoryList(tx) const [{ last }] = await tx.select({ last: max(CATEGORIES.position) }).from(CATEGORIES) const [row] = await tx .insert(CATEGORIES) @@ -241,19 +283,14 @@ export default createTRPCRouter({ .returning(categoryColumns) if (!row) return { error: "NOT_FOUND" as const } return row - }) + }).catch(duplicateSlug("web_document_categories")) }), deleteCategory: policy(dashboard("web:content:write")) .input(z.object({ id: idSchema })) .mutation(async ({ input }) => { return DB.transaction(async (tx) => { - const [category] = await tx - .select({ id: CATEGORIES.id }) - .from(CATEGORIES) - .where(eq(CATEGORIES.id, input.id)) - .for("update") - if (!category) return { error: "NOT_FOUND" as const } + if (!(await lockCategories(tx, [input.id])).has(input.id)) return { error: "NOT_FOUND" as const } const [document] = await tx .select({ id: DOCUMENTS.id }) .from(DOCUMENTS) @@ -268,11 +305,24 @@ export default createTRPCRouter({ reorderCategories: policy(dashboard("web:content:write")) .input(z.object({ ids: orderSchema })) .mutation(async ({ input }) => { - await DB.transaction(async (tx) => { + return DB.transaction(async (tx) => { + await lockCategoryList(tx) + const current = await tx + .select({ id: CATEGORIES.id }) + .from(CATEGORIES) + .orderBy(asc(CATEGORIES.id)) + .for("update") + if ( + !sameIds( + current.map((row) => row.id), + input.ids + ) + ) + return { error: "INVALID_ORDER" as const } for (const [position, id] of input.ids.entries()) await tx.update(CATEGORIES).set({ position }).where(eq(CATEGORIES.id, id)) + return { error: null } }) - return { error: null } }), createDocument: policy(dashboard("web:content:write")) @@ -286,7 +336,8 @@ export default createTRPCRouter({ ) .mutation(async ({ input, ctx }) => { return DB.transaction(async (tx) => { - if (!(await lockCategory(tx, input.categoryId))) return { error: "CATEGORY_NOT_FOUND" as const } + if (!(await lockCategories(tx, [input.categoryId])).has(input.categoryId)) + return { error: "CATEGORY_NOT_FOUND" as const } const [row] = await tx .insert(DOCUMENTS) .values({ @@ -315,14 +366,15 @@ export default createTRPCRouter({ .mutation(async ({ input, ctx }) => { const { id, categoryId, description, ...fields } = input return DB.transaction(async (tx) => { + await lockDocument(tx, id) const [current] = await tx .select({ categoryId: DOCUMENTS.categoryId }) .from(DOCUMENTS) .where(eq(DOCUMENTS.id, id)) - .for("update") if (!current) return { error: "NOT_FOUND" as const } + const locked = await lockCategories(tx, [current.categoryId, categoryId ?? current.categoryId]) + if (categoryId !== undefined && !locked.has(categoryId)) return { error: "CATEGORY_NOT_FOUND" as const } const moving = categoryId !== undefined && categoryId !== current.categoryId - if (moving && !(await lockCategory(tx, categoryId))) return { error: "CATEGORY_NOT_FOUND" as const } if (fields.slug !== undefined && (await slugTaken(tx, DOCUMENTS, fields.slug, id))) return { error: "DUPLICATE_SLUG" as const } const [row] = await tx @@ -337,19 +389,22 @@ export default createTRPCRouter({ .where(eq(DOCUMENTS.id, id)) .returning(documentColumns) return row - }) + }).catch(duplicateSlug("web_documents")) }), deleteDocument: policy(dashboard("web:content:write")) .input(z.object({ id: idSchema })) .mutation(async ({ input }) => { const files = await DB.transaction(async (tx) => { + await lockDocument(tx, input.id) const [document] = await tx - .select({ id: DOCUMENTS.id }) + .select({ categoryId: DOCUMENTS.categoryId }) .from(DOCUMENTS) .where(eq(DOCUMENTS.id, input.id)) - .for("update") if (!document) return null + await lockCategories(tx, [document.categoryId]) + // Wait for in-flight version uploads before removing their document. + await tx.select({ id: DOCUMENTS.id }).from(DOCUMENTS).where(eq(DOCUMENTS.id, input.id)).for("update") const versions = await tx .delete(VERSIONS) .where(eq(VERSIONS.documentId, input.id)) @@ -358,21 +413,31 @@ export default createTRPCRouter({ return versions.map((version) => version.file) }) if (!files) return { error: "NOT_FOUND" as const } - await Promise.all(files.map((file) => deleteBlob(file))) + await deleteBlobs(files) return { error: null } }), reorderDocuments: policy(dashboard("web:content:write")) .input(z.object({ categoryId: idSchema, ids: orderSchema })) .mutation(async ({ input }) => { - await DB.transaction(async (tx) => { + return DB.transaction(async (tx) => { + if (!(await lockCategories(tx, [input.categoryId])).has(input.categoryId)) + return { error: "INVALID_ORDER" as const } + const current = await tx + .select({ id: DOCUMENTS.id }) + .from(DOCUMENTS) + .where(eq(DOCUMENTS.categoryId, input.categoryId)) + if ( + !sameIds( + current.map((row) => row.id), + input.ids + ) + ) + return { error: "INVALID_ORDER" as const } for (const [position, id] of input.ids.entries()) - await tx - .update(DOCUMENTS) - .set({ position }) - .where(and(eq(DOCUMENTS.id, id), eq(DOCUMENTS.categoryId, input.categoryId))) + await tx.update(DOCUMENTS).set({ position }).where(eq(DOCUMENTS.id, id)) + return { error: null } }) - return { error: null } }), addVersion: policy(dashboard("web:content:write")) @@ -408,8 +473,12 @@ export default createTRPCRouter({ .onConflictDoNothing({ target: [VERSIONS.documentId, VERSIONS.version] }) .returning(versionColumns) return row ?? { error: "DUPLICATE_VERSION" as const } + }).catch(async (error) => { + // No row references the file: remove it before reporting the failure. + await deleteBlobs([uploadedFile.url]) + throw error }) - if ("error" in result) await deleteBlob(uploadedFile.url) + if ("error" in result) await deleteBlobs([uploadedFile.url]) return result }), @@ -418,7 +487,7 @@ export default createTRPCRouter({ .mutation(async ({ input }) => { const [deleted] = await DB.delete(VERSIONS).where(eq(VERSIONS.id, input.id)).returning({ file: VERSIONS.file }) if (!deleted) return { error: "NOT_FOUND" as const } - await deleteBlob(deleted.file) + await deleteBlobs([deleted.file]) return { error: null } }), }) diff --git a/tests/documents-postgres.fixture.ts b/tests/documents-postgres.fixture.ts index a72cc26..315f78b 100644 --- a/tests/documents-postgres.fixture.ts +++ b/tests/documents-postgres.fixture.ts @@ -28,14 +28,20 @@ try { const blob = await import("@/azure/blob") const stored = new Set() const removed: string[] = [] + let afterUpload: (() => Promise) | undefined + let failDeletion = false Object.assign(blob.containerClient, { getBlockBlobClient: (name: string) => ({ upload: async () => { stored.add(name) + const hook = afterUpload + afterUpload = undefined + await hook?.() return { requestId: "test" } }, deleteIfExists: async () => { removed.push(name) + if (failDeletion) throw new Error("Storage unavailable") return { succeeded: stored.delete(name) } }, }), @@ -194,8 +200,17 @@ try { ) checked.push("the public catalog shows the latest version and hides empty categories; the admin catalog shows all") - await editor.reorderCategories({ ids: [vuota.id, bilanci.id, statuto.id] }) - await editor.reorderDocuments({ categoryId: statuto.id, ids: [statutoDoc.id, atto.id, bilancio.id] }) + const initialOrder = await editor.getAdminCatalog() + for (const ids of [[vuota.id], [vuota.id, bilanci.id, 999_999]]) + assert.deepEqual(await editor.reorderCategories({ ids }), { error: "INVALID_ORDER" }) + for (const ids of [[atto.id], [atto.id, bilancio.id], [atto.id, statutoDoc.id, 999_999]]) + assert.deepEqual(await editor.reorderDocuments({ categoryId: statuto.id, ids }), { error: "INVALID_ORDER" }) + assert.deepEqual(await editor.reorderDocuments({ categoryId: 999_999, ids: [atto.id] }), { error: "INVALID_ORDER" }) + assert.deepEqual(await editor.getAdminCatalog(), initialOrder) + assert.deepEqual(await editor.reorderCategories({ ids: [vuota.id, bilanci.id, statuto.id] }), { error: null }) + assert.deepEqual(await editor.reorderDocuments({ categoryId: statuto.id, ids: [statutoDoc.id, atto.id] }), { + error: null, + }) await assert.rejects(editor.reorderCategories({ ids: [vuota.id, vuota.id] }), { code: "BAD_REQUEST" }) ok(await addVersion(bilancio.id, "2025", "2026-04-30")) assert.deepEqual( @@ -247,6 +262,154 @@ try { assert.equal(await website.getDocument({ slug: "statuto" }), null) checked.push("deleting a version or a document deletes its files") + for (const slug of ["Invalid", "a b", "", "a".repeat(101)]) + await assert.rejects(website.getDocument({ slug }), { code: "BAD_REQUEST" }) + checked.push("document lookups validate the public slug") + + const uploadRace = ok( + await editor.createDocument({ categoryId: statuto.id, slug: "upload-race", title: "Upload race" }) + ) + let winner: Awaited> | undefined + afterUpload = async () => { + winner = await addVersion(uploadRace.id, "1", "2026-01-01") + } + const beforeDuplicate = stored.size + assert.deepEqual(await addVersion(uploadRace.id, "1", "2026-01-01"), { error: "DUPLICATE_VERSION" }) + assert.equal(stored.size, beforeDuplicate + 1) + assert.deepEqual((await website.getDocument({ slug: "upload-race" }))?.latest, ok(winner)) + + afterUpload = async () => { + assert.deepEqual(await editor.deleteDocument({ id: uploadRace.id }), { error: null }) + } + const beforeDeleted = stored.size + assert.deepEqual(await addVersion(uploadRace.id, "2", "2026-02-01"), { error: "NOT_FOUND" }) + assert.equal(stored.size, beforeDeleted - 1) + + const failedSave = ok( + await editor.createDocument({ categoryId: statuto.id, slug: "failed-save", title: "Failed save" }) + ) + afterUpload = async () => { + await connection.unsafe(`CREATE FUNCTION fail_document_version() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN RAISE EXCEPTION 'forced document version failure'; END $$; + CREATE TRIGGER fail_document_version BEFORE INSERT ON web_document_versions + FOR EACH ROW EXECUTE FUNCTION fail_document_version()`) + } + const beforeFailure = stored.size + await assert.rejects(addVersion(failedSave.id, "1", "2026-01-01"), { code: "INTERNAL_SERVER_ERROR" }) + assert.equal(stored.size, beforeFailure) + assert.equal(await website.getDocument({ slug: "failed-save" }), null) + await connection.unsafe( + "DROP TRIGGER fail_document_version ON web_document_versions; DROP FUNCTION fail_document_version()" + ) + checked.push("upload races and thrown database errors remove only the unreferenced uploaded file") + + const failedDelete = ok(await addVersion(failedSave.id, "2", "2026-02-01")) + const failedDocumentDelete = ok(await addVersion(failedSave.id, "3", "2026-03-01")) + failDeletion = true + assert.deepEqual(await editor.deleteVersion({ id: failedDelete.id }), { error: null }) + assert.deepEqual((await website.getDocument({ slug: "failed-save" }))?.latest, failedDocumentDelete) + assert.deepEqual(await editor.deleteDocument({ id: failedSave.id }), { error: null }) + assert.equal(await website.getDocument({ slug: "failed-save" }), null) + failDeletion = false + checked.push("blob cleanup failure after commit does not report a failed database mutation") + + const concurrentCategories = ( + await Promise.all( + ["parallel-a", "parallel-b", "parallel-c"].map((slug) => + editor.createCategory({ slug, title: slug, description: "" }) + ) + ) + ).map(ok) + assert.equal(new Set(concurrentCategories.map((category) => category.position)).size, 3) + const concurrentDocuments = ( + await Promise.all( + ["parallel-a", "parallel-b", "parallel-c"].map((slug) => + editor.createDocument({ categoryId: concurrentCategories[0].id, slug, title: slug }) + ) + ) + ).map(ok) + assert.equal(new Set(concurrentDocuments.map((document) => document.position)).size, 3) + const currentCategories = (await editor.getAdminCatalog()).map((category) => category.id) + for (const result of await Promise.all([ + editor.reorderCategories({ ids: [...currentCategories].reverse() }), + editor.reorderCategories({ ids: currentCategories }), + editor.reorderDocuments({ + categoryId: concurrentCategories[0].id, + ids: concurrentDocuments.map((document) => document.id).reverse(), + }), + editor.reorderDocuments({ + categoryId: concurrentCategories[0].id, + ids: concurrentDocuments.map((document) => document.id), + }), + ])) + assert.deepEqual(result, { error: null }) + checked.push("concurrent creations assign distinct positions and reorders finish without deadlock") + + await connection.unsafe(`CREATE FUNCTION gate_slug_update() RETURNS trigger LANGUAGE plpgsql AS $$ + BEGIN PERFORM pg_advisory_xact_lock(TG_ARGV[0]::bigint); RETURN NEW; END $$; + CREATE TRIGGER gate_category_slug BEFORE UPDATE OF slug ON web_document_categories + FOR EACH ROW WHEN (NEW.slug = 'race-category-slug') EXECUTE FUNCTION gate_slug_update('76001'); + CREATE TRIGGER gate_document_slug BEFORE UPDATE OF slug ON web_documents + FOR EACH ROW WHEN (NEW.slug = 'race-document-slug') EXECUTE FUNCTION gate_slug_update('76002')`) + const gate = await connection.reserve() + const raceSlugs = async (key: number, writes: () => Promise) => { + await gate.unsafe(`SELECT pg_advisory_lock(${key})`) + const pending = writes() + try { + // Wait until both updates passed their preflight slug checks and reached the trigger. + const deadline = Date.now() + 5_000 + let waiting = 0 + while (Date.now() < deadline) { + const [row] = await connection`SELECT count(*)::int AS count FROM pg_locks + WHERE locktype = 'advisory' AND objid = ${key} AND NOT granted` + waiting = row.count + if (waiting === 2) break + await Bun.sleep(10) + } + assert.equal(waiting, 2, "both concurrent slug updates must reach the database gate") + } finally { + await gate.unsafe(`SELECT pg_advisory_unlock(${key})`) + } + const results = await pending + assert.equal(results.filter((result) => result && typeof result === "object" && !("error" in result)).length, 1) + assert.deepEqual( + results.filter((result) => result && typeof result === "object" && "error" in result), + [{ error: "DUPLICATE_SLUG" }] + ) + } + try { + await raceSlugs(76001, () => + Promise.all([ + editor.updateCategory({ id: concurrentCategories[0].id, slug: "race-category-slug" }), + editor.updateCategory({ id: concurrentCategories[1].id, slug: "race-category-slug" }), + ]) + ) + const otherCategoryDocument = ok( + await editor.createDocument({ + categoryId: concurrentCategories[1].id, + slug: "other-category-document", + title: "Other", + }) + ) + await raceSlugs(76002, () => + Promise.all([ + editor.updateDocument({ id: concurrentDocuments[0].id, slug: "race-document-slug" }), + editor.updateDocument({ id: otherCategoryDocument.id, slug: "race-document-slug" }), + ]) + ) + // Opposite moves must acquire both parent categories in the same order. + const moves = await Promise.all([ + editor.updateDocument({ id: concurrentDocuments[1].id, categoryId: concurrentCategories[1].id }), + editor.updateDocument({ id: otherCategoryDocument.id, categoryId: concurrentCategories[0].id }), + ]) + assert.ok(moves.every((result) => !("error" in result))) + } finally { + gate.release() + await connection.unsafe(`DROP TRIGGER gate_category_slug ON web_document_categories; + DROP TRIGGER gate_document_slug ON web_documents; DROP FUNCTION gate_slug_update()`) + } + checked.push("concurrent category/document slug edits return DUPLICATE_SLUG and opposite moves do not deadlock") + console.log(JSON.stringify({ checked })) } finally { await closeBackend?.() diff --git a/tests/documents-postgres.test.ts b/tests/documents-postgres.test.ts index c396228..1af5937 100644 --- a/tests/documents-postgres.test.ts +++ b/tests/documents-postgres.test.ts @@ -10,7 +10,7 @@ it.skipIf(!process.env.SEED_TEST_DB_PORT)( timeout: 60000, }) const result = JSON.parse(stdout.trim().split("\n").at(-1) ?? "{}") - expect(result.checked).toHaveLength(9) + expect(result.checked).toHaveLength(14) }, 65000 ) From 697f6df0a6a01e1485a1318ae86bd21fb32e1b89 Mon Sep 17 00:00:00 2001 From: Tommaso Morganti Date: Fri, 13 Nov 2026 21:26:06 +0100 Subject: [PATCH 4/5] fix(documents): check that uploaded versions are real PDFs addVersion trusted the browser-supplied MIME type. It now requires a %PDF- header and a PDF that pdf-lib can load with at least one page, answering BAD_REQUEST otherwise, and stores the blob as application/pdf. Encrypted (permission-restricted) PDFs remain accepted. --- src/routers/web/documents.ts | 25 ++++++++++++++++++++++++- tests/documents-postgres.fixture.ts | 14 ++++++++++++-- 2 files changed, 36 insertions(+), 3 deletions(-) diff --git a/src/routers/web/documents.ts b/src/routers/web/documents.ts index 2d080bd..8a6a0dd 100644 --- a/src/routers/web/documents.ts +++ b/src/routers/web/documents.ts @@ -1,4 +1,6 @@ +import { TRPCError } from "@trpc/server" import { and, asc, desc, eq, inArray, max, ne, sql } from "drizzle-orm" +import { PDFDocument } from "pdf-lib" import z from "zod" import { deleteBlob, uploadBlob } from "@/azure/blob" import { DB, SCHEMA } from "@/db" @@ -97,6 +99,26 @@ async function deleteBlobs(files: string[]) { logger.error({ err: result.reason, file: files[index] }, "[documents] could not delete a blob") } +/** + * The uploaded bytes, checked to be a readable PDF with pages: the browser's MIME type is only a claim. Encrypted PDFs + * are accepted, as official documents are often permission-restricted. + */ +async function readPdf(file: File) { + const bytes = new Uint8Array(await file.arrayBuffer()) + let pages = 0 + if (Buffer.from(bytes.subarray(0, 5)).toString("latin1") === "%PDF-") + try { + const pdf = await PDFDocument.load(bytes, { + ignoreEncryption: true, + updateMetadata: false, + throwOnInvalidObject: false, + }) + pages = pdf.getPageCount() + } catch {} + if (!pages) throw new TRPCError({ code: "BAD_REQUEST", message: "The file is not a readable PDF." }) + return Buffer.from(bytes) +} + const sameIds = (a: number[], b: number[]) => a.length === b.length && new Set([...a, ...b]).size === a.length /** Serialises changes to the list of categories (creation and reordering), which row locks cannot cover. */ @@ -450,6 +472,7 @@ export default createTRPCRouter({ .mutation(async ({ input, ctx }) => { const { documentId, version, date, file } = input const author = createdByColumns(authorOf(ctx.actor)) + const bytes = await readPdf(file) const [document] = await DB.select({ id: DOCUMENTS.id }).from(DOCUMENTS).where(eq(DOCUMENTS.id, documentId)) if (!document) return { error: "NOT_FOUND" as const } @@ -458,7 +481,7 @@ export default createTRPCRouter({ .where(and(eq(VERSIONS.documentId, documentId), eq(VERSIONS.version, version))) if (existing) return { error: "DUPLICATE_VERSION" as const } - const uploadedFile = await uploadBlob(Buffer.from(await file.arrayBuffer()), "pdf", file.type) + const uploadedFile = await uploadBlob(bytes, "pdf", "application/pdf") // The document may have been deleted, or the version added, while the file was uploading. const result = await DB.transaction(async (tx) => { const [locked] = await tx diff --git a/tests/documents-postgres.fixture.ts b/tests/documents-postgres.fixture.ts index 315f78b..c1653f3 100644 --- a/tests/documents-postgres.fixture.ts +++ b/tests/documents-postgres.fixture.ts @@ -1,5 +1,6 @@ import assert from "node:assert/strict" import { SQL } from "bun" +import { PDFDocument } from "pdf-lib" import type { Context } from "@/trpc" // A disposable database on the integration server, with the fixed test credentials used in CI. @@ -67,7 +68,11 @@ try { const website = documents.createCaller({ auth: { kind: "token", actor: { kind: "service", client: "website" }, scopes: new Set(["backend:public:read"]) }, }) - const pdf = (name = "file.pdf", type = "application/pdf") => new File(["%PDF-1.4 test"], name, { type }) + const onePage = await PDFDocument.create() + onePage.addPage() + const pdfBytes = new Uint8Array(await onePage.save()) + const pdf = (name = "file.pdf", type = "application/pdf", content: BlobPart = pdfBytes) => + new File([content], name, { type }) const form = (fields: Record) => { const fd = new FormData() for (const [key, value] of Object.entries(fields)) fd.append(key, value) @@ -146,9 +151,14 @@ try { code: "BAD_REQUEST", }) await assert.rejects(addVersion(statutoDoc.id, "3.0", "01/02/2026"), { code: "BAD_REQUEST" }) + // The declared type is only a claim: the bytes must be a PDF with pages. + for (const content of ["not a pdf", "%PDF-1.4 truncated", new Uint8Array([0x89, 0x50, 0x4e, 0x47])]) + await assert.rejects(addVersion(statutoDoc.id, "3.0", "2026-01-01", pdf("x.pdf", "application/pdf", content)), { + code: "BAD_REQUEST", + }) assert.equal(stored.size, 3) ok(await addVersion(atto.id, "2.0", "2020-01-01")) // The same label on another document is allowed. - checked.push("versions: PDF only, ISO dates, unique per document, NOT_FOUND for missing documents") + checked.push("versions: PDF content only, ISO dates, unique per document, NOT_FOUND for missing documents") const catalog = await website.getCatalog() assert.deepEqual( From 9e23d4f1fdfb9417bf0810308f7b99d05b98cf08 Mon Sep 17 00:00:00 2001 From: Tommaso Morganti Date: Fri, 13 Nov 2026 21:31:30 +0100 Subject: [PATCH 5/5] fix(documents): reject ids beyond the integer columns as bad input idSchema accepted any safe integer, so an id above 2^31-1 reached PostgreSQL and failed with "integer out of range", surfacing as INTERNAL_SERVER_ERROR. Ids, including addVersion's form documentId, are now validated as positive int32 and answer BAD_REQUEST. --- src/routers/web/documents.ts | 4 ++-- tests/documents-postgres.fixture.ts | 7 ++++++- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/src/routers/web/documents.ts b/src/routers/web/documents.ts index 8a6a0dd..16f7396 100644 --- a/src/routers/web/documents.ts +++ b/src/routers/web/documents.ts @@ -19,7 +19,7 @@ const slugSchema = z .regex(/^[a-z0-9]+(?:-[a-z0-9]+)*$/, "Use lowercase kebab-case") const titleSchema = z.string().trim().min(1).max(200) const descriptionSchema = z.string().trim().max(2000) -const idSchema = z.number().int().positive() +const idSchema = z.int32().positive() // The id columns are PostgreSQL integers. const orderSchema = z .array(idSchema) .min(1) @@ -32,7 +32,7 @@ const documentFileSchema = z .max(10 * 1024 * 1024) const versionFormSchema = z.object({ - documentId: z.coerce.number().int().positive(), + documentId: z.coerce.number().pipe(idSchema), version: z.string().trim().min(1).max(50), date: z.iso.date(), file: documentFileSchema, diff --git a/tests/documents-postgres.fixture.ts b/tests/documents-postgres.fixture.ts index c1653f3..1157240 100644 --- a/tests/documents-postgres.fixture.ts +++ b/tests/documents-postgres.fixture.ts @@ -157,8 +157,13 @@ try { code: "BAD_REQUEST", }) assert.equal(stored.size, 3) + // Ids beyond the integer columns are invalid input, not a database error. + await assert.rejects(addVersion(2 ** 31, "1.0", "2026-01-01"), { code: "BAD_REQUEST" }) + await assert.rejects(editor.deleteVersion({ id: 2 ** 31 }), { code: "BAD_REQUEST" }) ok(await addVersion(atto.id, "2.0", "2020-01-01")) // The same label on another document is allowed. - checked.push("versions: PDF content only, ISO dates, unique per document, NOT_FOUND for missing documents") + checked.push( + "versions: PDF content only, ISO dates, integer ids, unique per document, NOT_FOUND for missing documents" + ) const catalog = await website.getCatalog() assert.deepEqual(