From c441d9d10412eb789a41e7fe99dbdc8ba911306e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gabriele=20Vigan=C3=B2?= Date: Tue, 17 Nov 2026 15:41:44 +0100 Subject: [PATCH 1/5] feat(associations)!: add reviewed association registry and self service --- drizzle/0040_association_portal.sql | 33 + drizzle/meta/0040_snapshot.json | 6671 +++++++++++++++++++++++ drizzle/meta/_journal.json | 7 + src/associations/contract.ts | 151 + src/associations/index.ts | 51 + src/associations/router.ts | 94 + src/associations/service.ts | 436 ++ src/associations/store-pg.ts | 97 + src/cron.ts | 8 + src/db/schema/web/association-portal.ts | 17 + src/db/schema/web/index.ts | 2 + src/emails/mailer.tsx | 16 + src/routers/index.ts | 3 + src/routers/web/associations.ts | 192 +- tests/associations-fixture.ts | 67 + tests/associations-postgres.fixture.ts | 145 + tests/associations-postgres.test.ts | 15 + tests/associations-preview.fixture.ts | 57 + tests/associations-router.test.ts | 58 + tests/associations.test.ts | 201 + 20 files changed, 8175 insertions(+), 146 deletions(-) create mode 100644 drizzle/0040_association_portal.sql create mode 100644 drizzle/meta/0040_snapshot.json create mode 100644 src/associations/contract.ts create mode 100644 src/associations/index.ts create mode 100644 src/associations/router.ts create mode 100644 src/associations/service.ts create mode 100644 src/associations/store-pg.ts create mode 100644 src/db/schema/web/association-portal.ts create mode 100644 tests/associations-fixture.ts create mode 100644 tests/associations-postgres.fixture.ts create mode 100644 tests/associations-postgres.test.ts create mode 100644 tests/associations-preview.fixture.ts create mode 100644 tests/associations-router.test.ts create mode 100644 tests/associations.test.ts diff --git a/drizzle/0040_association_portal.sql b/drizzle/0040_association_portal.sql new file mode 100644 index 0000000..d43fb84 --- /dev/null +++ b/drizzle/0040_association_portal.sql @@ -0,0 +1,33 @@ +CREATE TABLE "web_association_mail" ( + "id" uuid PRIMARY KEY NOT NULL, + "mail" jsonb NOT NULL, + "attempts" integer DEFAULT 0 NOT NULL, + "next_attempt" timestamp with time zone DEFAULT now() NOT NULL, + "sent_at" timestamp with time zone +); +--> statement-breakpoint +CREATE TABLE "web_association_registry" ( + "id" uuid PRIMARY KEY NOT NULL, + "state" jsonb NOT NULL, + "creation_key" text NOT NULL, + CONSTRAINT "web_association_registry_creation_key_unique" UNIQUE("creation_key") +); + +--> statement-breakpoint +-- Existing public records remain published, but no one is automatically made their representative. +INSERT INTO "web_association_registry" (id, state, creation_key) +SELECT rid, jsonb_build_object( + 'id', rid, 'legacyId', a.id, 'revision', 0, 'creator', 'system', 'registered', true, 'status', 'active', + 'profile', profile, 'published', profile, 'members', '[]'::jsonb, 'requests', '[]'::jsonb, + 'events', '[]'::jsonb, 'invitations', '[]'::jsonb, 'notes', '', 'commands', '[]'::jsonb +), 'legacy:' || a.id +FROM web_associations a +CROSS JOIN LATERAL (SELECT gen_random_uuid() AS rid WHERE a.id IS NOT NULL) ids +CROSS JOIN LATERAL (SELECT jsonb_build_object( + 'name', a.name, 'acronym', '', 'descriptionIt', a.description_it, 'descriptionEn', a.description_en, + 'logo', a.logo, 'email', coalesce(a.email, ''), + 'links', coalesce((SELECT jsonb_agg(jsonb_build_object('platform', key, 'label', key, 'url', value)) + FROM jsonb_each_text(jsonb_build_object('website', a.website, 'facebook', a.facebook, 'instagram', a.instagram, + 'tiktok', a.tiktok, 'x', a.x, 'youtube', a.youtube, 'telegram', a.telegram, 'linkedin', a.linkedin, 'spotify', a.spotify)) + WHERE value IS NOT NULL AND value <> ''), '[]'::jsonb) +) AS profile) profiles; diff --git a/drizzle/meta/0040_snapshot.json b/drizzle/meta/0040_snapshot.json new file mode 100644 index 0000000..6d42df6 --- /dev/null +++ b/drizzle/meta/0040_snapshot.json @@ -0,0 +1,6671 @@ +{ + "id": "97f92c69-f4e6-4bb8-ae10-87da48dbaa46", + "prevId": "81933ec6-6410-441f-8f8d-77f4baeedae8", + "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.common_webhook_deliveries": { + "name": "common_webhook_deliveries", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "event": { + "name": "event", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "received_at": { + "name": "received_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "common_webhook_deliveries_received_idx": { + "name": "common_webhook_deliveries_received_idx", + "columns": [ + { + "expression": "received_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "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.regulations_assignments": { + "name": "regulations_assignments", + "schema": "", + "columns": { + "draft_id": { + "name": "draft_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user_sub": { + "name": "user_sub", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user": { + "name": "user", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "assigned_by": { + "name": "assigned_by", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "assigned_at": { + "name": "assigned_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "regulations_assignments_user_idx": { + "name": "regulations_assignments_user_idx", + "columns": [ + { + "expression": "user_sub", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "regulations_assignments_draft_id_regulations_drafts_id_fk": { + "name": "regulations_assignments_draft_id_regulations_drafts_id_fk", + "tableFrom": "regulations_assignments", + "tableTo": "regulations_drafts", + "columnsFrom": [ + "draft_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "regulations_assignments_draft_id_user_sub_pk": { + "name": "regulations_assignments_draft_id_user_sub_pk", + "columns": [ + "draft_id", + "user_sub" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "regulations_assignments_role_check": { + "name": "regulations_assignments_role_check", + "value": "\"regulations_assignments\".\"role\" in ('editor', 'commenter', 'viewer')" + } + }, + "isRLSEnabled": false + }, + "public.regulations_blobs": { + "name": "regulations_blobs", + "schema": "", + "columns": { + "hash": { + "name": "hash", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "content_type": { + "name": "content_type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "content": { + "name": "content", + "type": "bytea", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.regulations_collab_tickets": { + "name": "regulations_collab_tickets", + "schema": "", + "columns": { + "hash": { + "name": "hash", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "draft_id": { + "name": "draft_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "user": { + "name": "user", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "read_only": { + "name": "read_only", + "type": "boolean", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true + }, + "used_at": { + "name": "used_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "regulations_collab_tickets_expiry_idx": { + "name": "regulations_collab_tickets_expiry_idx", + "columns": [ + { + "expression": "expires_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "regulations_collab_tickets_draft_id_regulations_drafts_id_fk": { + "name": "regulations_collab_tickets_draft_id_regulations_drafts_id_fk", + "tableFrom": "regulations_collab_tickets", + "tableTo": "regulations_drafts", + "columnsFrom": [ + "draft_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.regulations_comments": { + "name": "regulations_comments", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "draft_id": { + "name": "draft_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "parent_id": { + "name": "parent_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "file": { + "name": "file", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "anchor_start": { + "name": "anchor_start", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "anchor_end": { + "name": "anchor_end", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "quote": { + "name": "quote", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "body": { + "name": "body", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "author": { + "name": "author", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true + }, + "edited_at": { + "name": "edited_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "resolved_at": { + "name": "resolved_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "resolved_by": { + "name": "resolved_by", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "regulations_comments_draft_idx": { + "name": "regulations_comments_draft_idx", + "columns": [ + { + "expression": "draft_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "regulations_comments_draft_id_regulations_drafts_id_fk": { + "name": "regulations_comments_draft_id_regulations_drafts_id_fk", + "tableFrom": "regulations_comments", + "tableTo": "regulations_drafts", + "columnsFrom": [ + "draft_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "regulations_comments_parent_id_regulations_comments_id_fk": { + "name": "regulations_comments_parent_id_regulations_comments_id_fk", + "tableFrom": "regulations_comments", + "tableTo": "regulations_comments", + "columnsFrom": [ + "parent_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "regulations_comments_anchor_check": { + "name": "regulations_comments_anchor_check", + "value": "(\"regulations_comments\".\"parent_id\" is null) = (\"regulations_comments\".\"file\" is not null and \"regulations_comments\".\"anchor_start\" is not null and \"regulations_comments\".\"anchor_end\" is not null)" + } + }, + "isRLSEnabled": false + }, + "public.regulations_compile_refs": { + "name": "regulations_compile_refs", + "schema": "", + "columns": { + "draft_id": { + "name": "draft_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "hash": { + "name": "hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "regulations_compile_refs_draft_id_regulations_drafts_id_fk": { + "name": "regulations_compile_refs_draft_id_regulations_drafts_id_fk", + "tableFrom": "regulations_compile_refs", + "tableTo": "regulations_drafts", + "columnsFrom": [ + "draft_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "regulations_compile_refs_draft_id_hash_pk": { + "name": "regulations_compile_refs_draft_id_hash_pk", + "columns": [ + "draft_id", + "hash" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.regulations_compiles": { + "name": "regulations_compiles", + "schema": "", + "columns": { + "hash": { + "name": "hash", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "ok": { + "name": "ok", + "type": "boolean", + "primaryKey": false, + "notNull": true + }, + "pdf_blob": { + "name": "pdf_blob", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "errors": { + "name": "errors", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "log": { + "name": "log", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "duration_ms": { + "name": "duration_ms", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.regulations_deleghe": { + "name": "regulations_deleghe", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "grantee_sub": { + "name": "grantee_sub", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "grantee": { + "name": "grantee", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "document_key": { + "name": "document_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "note": { + "name": "note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "granted_by": { + "name": "granted_by", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "revoked_by": { + "name": "revoked_by", + "type": "jsonb", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "regulations_deleghe_grantee_idx": { + "name": "regulations_deleghe_grantee_idx", + "columns": [ + { + "expression": "grantee_sub", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "regulations_deleghe_document_key_regulations_documents_key_fk": { + "name": "regulations_deleghe_document_key_regulations_documents_key_fk", + "tableFrom": "regulations_deleghe", + "tableTo": "regulations_documents", + "columnsFrom": [ + "document_key" + ], + "columnsTo": [ + "key" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.regulations_delibere": { + "name": "regulations_delibere", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "draft_id": { + "name": "draft_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "body": { + "name": "body", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "date": { + "name": "date", + "type": "date", + "primaryKey": false, + "notNull": true + }, + "verbale_url": { + "name": "verbale_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "recorded_by": { + "name": "recorded_by", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "recorded_at": { + "name": "recorded_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true + }, + "delega_id": { + "name": "delega_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "on_behalf_of": { + "name": "on_behalf_of", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "withdrawn_at": { + "name": "withdrawn_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "withdrawn_by": { + "name": "withdrawn_by", + "type": "jsonb", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "regulations_delibere_current_idx": { + "name": "regulations_delibere_current_idx", + "columns": [ + { + "expression": "draft_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"regulations_delibere\".\"withdrawn_at\" is null", + "concurrently": false, + "method": "btree", + "with": {} + }, + "regulations_delibere_draft_idx": { + "name": "regulations_delibere_draft_idx", + "columns": [ + { + "expression": "draft_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "regulations_delibere_draft_id_regulations_drafts_id_fk": { + "name": "regulations_delibere_draft_id_regulations_drafts_id_fk", + "tableFrom": "regulations_delibere", + "tableTo": "regulations_drafts", + "columnsFrom": [ + "draft_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "regulations_delibere_delega_id_regulations_deleghe_id_fk": { + "name": "regulations_delibere_delega_id_regulations_deleghe_id_fk", + "tableFrom": "regulations_delibere", + "tableTo": "regulations_deleghe", + "columnsFrom": [ + "delega_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "regulations_delibere_kind_check": { + "name": "regulations_delibere_kind_check", + "value": "\"regulations_delibere\".\"kind\" in ('approvazione', 'rettifica')" + }, + "regulations_delibere_body_check": { + "name": "regulations_delibere_body_check", + "value": "(\"regulations_delibere\".\"kind\" = 'approvazione') = (\"regulations_delibere\".\"body\" in ('consiglio_direttivo', 'assemblea'))" + } + }, + "isRLSEnabled": false + }, + "public.regulations_diffs": { + "name": "regulations_diffs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "draft_id": { + "name": "draft_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "generation": { + "name": "generation", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "base_label": { + "name": "base_label", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "articles": { + "name": "articles", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "other_changes": { + "name": "other_changes", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "categories": { + "name": "categories", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "provider": { + "name": "provider", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "pdf_blob": { + "name": "pdf_blob", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "requested_by": { + "name": "requested_by", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true + }, + "finished_at": { + "name": "finished_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "regulations_diffs_generation_idx": { + "name": "regulations_diffs_generation_idx", + "columns": [ + { + "expression": "draft_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "generation", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "regulations_diffs_draft_id_regulations_drafts_id_fk": { + "name": "regulations_diffs_draft_id_regulations_drafts_id_fk", + "tableFrom": "regulations_diffs", + "tableTo": "regulations_drafts", + "columnsFrom": [ + "draft_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "regulations_diffs_status_check": { + "name": "regulations_diffs_status_check", + "value": "\"regulations_diffs\".\"status\" in ('pending', 'ready', 'failed')" + } + }, + "isRLSEnabled": false + }, + "public.regulations_documents": { + "name": "regulations_documents", + "schema": "", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "dir": { + "name": "dir", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "entry": { + "name": "entry", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sources": { + "name": "sources", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "outputs": { + "name": "outputs", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "tag_prefix": { + "name": "tag_prefix", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "procedure": { + "name": "procedure", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.regulations_draft_compiles": { + "name": "regulations_draft_compiles", + "schema": "", + "columns": { + "draft_id": { + "name": "draft_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "hash": { + "name": "hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "last_good_hash": { + "name": "last_good_hash", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "compiled_at": { + "name": "compiled_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "regulations_draft_compiles_draft_id_regulations_drafts_id_fk": { + "name": "regulations_draft_compiles_draft_id_regulations_drafts_id_fk", + "tableFrom": "regulations_draft_compiles", + "tableTo": "regulations_drafts", + "columnsFrom": [ + "draft_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.regulations_drafts": { + "name": "regulations_drafts", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "document_key": { + "name": "document_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "state": { + "name": "state", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "base_version_id": { + "name": "base_version_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "base_draft_id": { + "name": "base_draft_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "base_files": { + "name": "base_files", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "frozen_files": { + "name": "frozen_files", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "parses": { + "name": "parses", + "type": "boolean", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true + }, + "state_changed_at": { + "name": "state_changed_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true + }, + "approved_at": { + "name": "approved_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "emanated_at": { + "name": "emanated_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "notified_at": { + "name": "notified_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "deleted_at": { + "name": "deleted_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "deleted_by": { + "name": "deleted_by", + "type": "jsonb", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "regulations_drafts_document_idx": { + "name": "regulations_drafts_document_idx", + "columns": [ + { + "expression": "document_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "regulations_drafts_in_approval_idx": { + "name": "regulations_drafts_in_approval_idx", + "columns": [ + { + "expression": "document_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"regulations_drafts\".\"state\" = 'in_approvazione' and \"regulations_drafts\".\"deleted_at\" is null", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "regulations_drafts_document_key_regulations_documents_key_fk": { + "name": "regulations_drafts_document_key_regulations_documents_key_fk", + "tableFrom": "regulations_drafts", + "tableTo": "regulations_documents", + "columnsFrom": [ + "document_key" + ], + "columnsTo": [ + "key" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "regulations_drafts_base_version_id_regulations_versions_id_fk": { + "name": "regulations_drafts_base_version_id_regulations_versions_id_fk", + "tableFrom": "regulations_drafts", + "tableTo": "regulations_versions", + "columnsFrom": [ + "base_version_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "regulations_drafts_base_draft_id_regulations_drafts_id_fk": { + "name": "regulations_drafts_base_draft_id_regulations_drafts_id_fk", + "tableFrom": "regulations_drafts", + "tableTo": "regulations_drafts", + "columnsFrom": [ + "base_draft_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "regulations_drafts_kind_check": { + "name": "regulations_drafts_kind_check", + "value": "\"regulations_drafts\".\"kind\" in ('modifica', 'rettifica')" + }, + "regulations_drafts_state_check": { + "name": "regulations_drafts_state_check", + "value": "\"regulations_drafts\".\"state\" in ('bozza', 'in_approvazione', 'approvata', 'emanata')" + }, + "regulations_drafts_base_check": { + "name": "regulations_drafts_base_check", + "value": "(\"regulations_drafts\".\"base_version_id\" is null) <> (\"regulations_drafts\".\"base_draft_id\" is null)" + } + }, + "isRLSEnabled": false + }, + "public.regulations_emanations": { + "name": "regulations_emanations", + "schema": "", + "columns": { + "draft_id": { + "name": "draft_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "files": { + "name": "files", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "tag": { + "name": "tag", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "branch": { + "name": "branch", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "pr_number": { + "name": "pr_number", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "merge_sha": { + "name": "merge_sha", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "release_id": { + "name": "release_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "version_id": { + "name": "version_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "steps": { + "name": "steps", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "started_by": { + "name": "started_by", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "started_at": { + "name": "started_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true + }, + "next_check_at": { + "name": "next_check_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "finished_at": { + "name": "finished_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "regulations_emanations_draft_id_regulations_drafts_id_fk": { + "name": "regulations_emanations_draft_id_regulations_drafts_id_fk", + "tableFrom": "regulations_emanations", + "tableTo": "regulations_drafts", + "columnsFrom": [ + "draft_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "regulations_emanations_version_id_regulations_versions_id_fk": { + "name": "regulations_emanations_version_id_regulations_versions_id_fk", + "tableFrom": "regulations_emanations", + "tableTo": "regulations_versions", + "columnsFrom": [ + "version_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "regulations_emanations_status_check": { + "name": "regulations_emanations_status_check", + "value": "\"regulations_emanations\".\"status\" in ('running', 'waiting', 'done', 'failed')" + } + }, + "isRLSEnabled": false + }, + "public.regulations_merges": { + "name": "regulations_merges", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "target_draft_id": { + "name": "target_draft_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_kind": { + "name": "source_kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_id": { + "name": "source_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "source_files": { + "name": "source_files", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "resolutions": { + "name": "resolutions", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "merged_by": { + "name": "merged_by", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "merged_at": { + "name": "merged_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "regulations_merges_pair_idx": { + "name": "regulations_merges_pair_idx", + "columns": [ + { + "expression": "target_draft_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source_kind", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "source_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "merged_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "regulations_merges_target_draft_id_regulations_drafts_id_fk": { + "name": "regulations_merges_target_draft_id_regulations_drafts_id_fk", + "tableFrom": "regulations_merges", + "tableTo": "regulations_drafts", + "columnsFrom": [ + "target_draft_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.regulations_notifications": { + "name": "regulations_notifications", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "draft_id": { + "name": "draft_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "delega_id": { + "name": "delega_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "channel": { + "name": "channel", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "recipients": { + "name": "recipients", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "subject": { + "name": "subject", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "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 (3) with time zone", + "primaryKey": false, + "notNull": true + }, + "sent_at": { + "name": "sent_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "regulations_notifications_draft_idx": { + "name": "regulations_notifications_draft_idx", + "columns": [ + { + "expression": "draft_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "regulations_notifications_draft_id_regulations_drafts_id_fk": { + "name": "regulations_notifications_draft_id_regulations_drafts_id_fk", + "tableFrom": "regulations_notifications", + "tableTo": "regulations_drafts", + "columnsFrom": [ + "draft_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "regulations_notifications_delega_id_regulations_deleghe_id_fk": { + "name": "regulations_notifications_delega_id_regulations_deleghe_id_fk", + "tableFrom": "regulations_notifications", + "tableTo": "regulations_deleghe", + "columnsFrom": [ + "delega_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "regulations_notifications_key_unique": { + "name": "regulations_notifications_key_unique", + "nullsNotDistinct": false, + "columns": [ + "key" + ] + } + }, + "policies": {}, + "checkConstraints": { + "regulations_notifications_channel_check": { + "name": "regulations_notifications_channel_check", + "value": "\"regulations_notifications\".\"channel\" in ('email', 'telegram')" + }, + "regulations_notifications_status_check": { + "name": "regulations_notifications_status_check", + "value": "\"regulations_notifications\".\"status\" in ('pending', 'sent', 'failed')" + } + }, + "isRLSEnabled": false + }, + "public.regulations_snapshots": { + "name": "regulations_snapshots", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "draft_id": { + "name": "draft_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "files": { + "name": "files", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "source_hash": { + "name": "source_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_by": { + "name": "created_by", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "regulations_snapshots_draft_idx": { + "name": "regulations_snapshots_draft_idx", + "columns": [ + { + "expression": "draft_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "regulations_snapshots_draft_id_regulations_drafts_id_fk": { + "name": "regulations_snapshots_draft_id_regulations_drafts_id_fk", + "tableFrom": "regulations_snapshots", + "tableTo": "regulations_drafts", + "columnsFrom": [ + "draft_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "regulations_snapshots_kind_check": { + "name": "regulations_snapshots_kind_check", + "value": "\"regulations_snapshots\".\"kind\" in ('base', 'auto', 'named', 'state', 'restore', 'merge')" + } + }, + "isRLSEnabled": false + }, + "public.regulations_versions": { + "name": "regulations_versions", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "document_key": { + "name": "document_key", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "tag": { + "name": "tag", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "files": { + "name": "files", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "source_hash": { + "name": "source_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "commit_sha": { + "name": "commit_sha", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "draft_id": { + "name": "draft_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "published_at": { + "name": "published_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true + }, + "release_url": { + "name": "release_url", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "pdf_blob": { + "name": "pdf_blob", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "assets_blob": { + "name": "assets_blob", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "regulations_versions_document_idx": { + "name": "regulations_versions_document_idx", + "columns": [ + { + "expression": "document_key", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "published_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "regulations_versions_tag_idx": { + "name": "regulations_versions_tag_idx", + "columns": [ + { + "expression": "document_key", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "tag", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "regulations_versions_document_key_regulations_documents_key_fk": { + "name": "regulations_versions_document_key_regulations_documents_key_fk", + "tableFrom": "regulations_versions", + "tableTo": "regulations_documents", + "columnsFrom": [ + "document_key" + ], + "columnsTo": [ + "key" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "regulations_versions_draft_id_regulations_drafts_id_fk": { + "name": "regulations_versions_draft_id_regulations_drafts_id_fk", + "tableFrom": "regulations_versions", + "tableTo": "regulations_drafts", + "columnsFrom": [ + "draft_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.regulations_ydocs": { + "name": "regulations_ydocs", + "schema": "", + "columns": { + "draft_id": { + "name": "draft_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "state": { + "name": "state", + "type": "bytea", + "primaryKey": false, + "notNull": true + }, + "compacted_through": { + "name": "compacted_through", + "type": "bigint", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": { + "regulations_ydocs_draft_id_regulations_drafts_id_fk": { + "name": "regulations_ydocs_draft_id_regulations_drafts_id_fk", + "tableFrom": "regulations_ydocs", + "tableTo": "regulations_drafts", + "columnsFrom": [ + "draft_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.regulations_yupdates": { + "name": "regulations_yupdates", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "bigint", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "regulations_yupdates_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "9223372036854775807", + "cache": "1", + "cycle": false + } + }, + "draft_id": { + "name": "draft_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "update": { + "name": "update", + "type": "bytea", + "primaryKey": false, + "notNull": true + }, + "actor_sub": { + "name": "actor_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "regulations_yupdates_draft_idx": { + "name": "regulations_yupdates_draft_idx", + "columns": [ + { + "expression": "draft_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "regulations_yupdates_draft_id_regulations_drafts_id_fk": { + "name": "regulations_yupdates_draft_id_regulations_drafts_id_fk", + "tableFrom": "regulations_yupdates", + "tableTo": "regulations_drafts", + "columnsFrom": [ + "draft_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "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_association_mail": { + "name": "web_association_mail", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "mail": { + "name": "mail", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "next_attempt": { + "name": "next_attempt", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "sent_at": { + "name": "sent_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.web_association_registry": { + "name": "web_association_registry", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "state": { + "name": "state", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "creation_key": { + "name": "creation_key", + "type": "text", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "web_association_registry_creation_key_unique": { + "name": "web_association_registry_creation_key_unique", + "nullsNotDistinct": false, + "columns": [ + "creation_key" + ] + } + }, + "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 ec61f80..7599d38 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -281,6 +281,13 @@ "when": 1794708980775, "tag": "0039_webhook_deliveries", "breakpoints": true + }, + { + "idx": 40, + "version": "7", + "when": 1794926488991, + "tag": "0040_association_portal", + "breakpoints": true } ] } \ No newline at end of file diff --git a/src/associations/contract.ts b/src/associations/contract.ts new file mode 100644 index 0000000..ad5fa9c --- /dev/null +++ b/src/associations/contract.ts @@ -0,0 +1,151 @@ +import { z } from "zod" + +const text = z.string().trim().max(20000) +const reason = z.string().trim().min(1).max(4000) +export const httpUrl = z + .url() + .max(2048) + .refine((s) => /^https?:\/\//i.test(s), "Use an HTTP or HTTPS link") +export const linkSchema = z.object({ + platform: z.enum([ + "website", + "facebook", + "instagram", + "tiktok", + "x", + "youtube", + "telegram", + "linkedin", + "spotify", + "twitch", + "other", + ]), + label: z.string().trim().min(1).max(100), + url: httpUrl, +}) +export const profileSchema = z.object({ + name: z.string().trim().min(1).max(200), + acronym: z.string().trim().max(50), + descriptionIt: text, + descriptionEn: text, + logo: httpUrl.nullable(), + email: z.union([z.literal(""), z.email().max(320)]), + links: z.array(linkSchema).max(30), +}) +export const requestStatus = z.enum(["draft", "submitted", "changes", "approved", "rejected", "withdrawn"]) +export const roleSchema = z.enum(["responsible", "collaborator"]) +export const memberSchema = z.object({ sub: z.string(), name: z.string(), role: roleSchema, active: z.boolean() }) +export const requestSchema = z.object({ + id: z.uuid(), + redirectId: z.uuid().nullable().default(null), + kind: z.enum(["registration", "access", "membership", "content"]), + status: requestStatus, + by: z.string(), + byName: z.string(), + explanation: z.string(), + response: z.string(), + profile: profileSchema.nullable(), + targetSub: z.string().nullable(), + targetName: z.string().nullable(), + role: roleSchema, + email: z.string(), + remove: z.boolean(), + accepted: z.boolean(), + createdAt: z.string(), + updatedAt: z.string(), + decidedBy: z.string().nullable(), +}) +export const eventSchema = z.object({ + requestId: z.uuid().optional(), + id: z.uuid(), + at: z.string(), + actor: z.string(), + action: z.string(), + detail: z.string(), +}) +export const summarySchema = z.object({ + id: z.uuid(), + name: z.string(), + status: z.enum(["pending", "active", "suspended", "archived"]), + registered: z.boolean(), + published: z.boolean(), + role: roleSchema.nullable(), + pending: z.number(), + unrepresented: z.boolean(), +}) +export const detailSchema = summarySchema.extend({ + revision: z.number().int(), + profile: profileSchema, + publishedProfile: profileSchema.nullable(), + members: z.array(memberSchema), + requests: z.array(requestSchema), + events: z.array(eventSchema), + notes: z.string().nullable(), + canEdit: z.boolean(), + canSubmit: z.boolean(), + canManage: z.boolean(), + operator: z.boolean(), +}) +export const dashboardSchema = z.object({ + operator: z.boolean(), + associations: z.array(summarySchema), + requests: z.array(requestSchema.extend({ associationId: z.uuid(), associationName: z.string() })), +}) +export const directorySchema = z.array(z.object({ id: z.uuid(), name: z.string(), revision: z.number() })) +export const refSchema = z.object({ id: z.uuid() }) +export const createSchema = z.object({ + profile: profileSchema, + explanation: reason, + submit: z.boolean(), + commandId: z.uuid(), +}) +const base = { id: z.uuid(), revision: z.number().int().nonnegative(), commandId: z.uuid() } +export const commandSchema = z.discriminatedUnion("action", [ + z.object({ + ...base, + action: z.literal("save"), + requestId: z.uuid().nullable(), + profile: profileSchema, + explanation: text, + }), + z.object({ ...base, action: z.literal("submit"), requestId: z.uuid() }), + z.object({ ...base, action: z.literal("reply"), requestId: z.uuid(), explanation: reason }), + z.object({ ...base, action: z.literal("withdraw"), requestId: z.uuid() }), + z.object({ ...base, action: z.literal("access"), explanation: reason }), + z.object({ ...base, action: z.literal("invite"), email: z.email().max(320), role: roleSchema, explanation: reason }), + z.object({ + ...base, + action: z.literal("membership"), + sub: z.string().min(1).max(200), + role: roleSchema, + remove: z.boolean(), + explanation: reason, + }), + z.object({ ...base, action: z.literal("redirect"), requestId: z.uuid(), destinationId: z.uuid(), reason }), + z.object({ + ...base, + action: z.literal("review"), + requestId: z.uuid(), + decision: z.enum(["approve", "changes", "reject"]), + reason, + }), + z.object({ + ...base, + action: z.literal("status"), + status: z.enum(["active", "suspended", "archived"]), + hide: z.boolean(), + reason, + }), + z.object({ ...base, action: z.literal("unpublish"), reason }), + z.object({ ...base, action: z.literal("note"), note: text }), + z.object({ ...base, action: z.literal("leave"), reason }), + z.object({ ...base, action: z.literal("revoke"), sub: z.string().min(1).max(200), reason }), +]) +export const inviteSchema = z.object({ token: z.string().min(32).max(128) }) +export const invitationSchema = z.object({ associationName: z.string(), role: roleSchema, expiresAt: z.string() }) +export type Profile = z.infer +export type Request = z.infer +export type Detail = z.infer +export type Command = z.infer +export type Member = z.infer +export type Event = z.infer diff --git a/src/associations/index.ts b/src/associations/index.ts new file mode 100644 index 0000000..99f84fe --- /dev/null +++ b/src/associations/index.ts @@ -0,0 +1,51 @@ +import { and, eq, isNull, lte, sql } from "drizzle-orm" +import { DB } from "@/db" +import { associationMail } from "@/db/schema/web/association-portal" +import { sendAssociationEmail } from "@/emails/mailer" +import { env } from "@/env" +import { idp } from "@/idp" +import { logger } from "@/logger" +import { createAssociationService } from "./service" +import { createAssociationStore } from "./store-pg" + +export const associationStore = createAssociationStore(DB) +export const associationPortal = createAssociationService(associationStore, env.ESIGN_DASHBOARD_URL.replace(/\/$/, "")) + +/** Durable retries, SKIP LOCKED across replicas. Delivery is at-least-once, with a stable Message-ID. */ +export async function deliverAssociationMail() { + for (let n = 0; n < 20; n++) { + const done = await DB.transaction(async (tx) => { + const [row] = await tx + .select() + .from(associationMail) + .where(and(isNull(associationMail.sentAt), lte(associationMail.nextAttempt, new Date()))) + .limit(1) + .for("update", { skipLocked: true }) + if (!row) return true + try { + await sendAssociationEmail(row.mail) + // Erase the invitation URL from the outbox after delivery; only the hash remains in the registry. + await tx + .update(associationMail) + .set({ sentAt: new Date(), mail: { ...row.mail, text: "Delivered" } }) + .where(eq(associationMail.id, row.id)) + } catch (error) { + logger.error({ error, mailId: row.id }, "Association notification delivery failed") + await tx + .update(associationMail) + .set({ + attempts: sql`${associationMail.attempts} + 1`, + nextAttempt: new Date(Date.now() + Math.min(3600, 60 * 2 ** Math.min(row.attempts, 6)) * 1000), + }) + .where(eq(associationMail.id, row.id)) + } + return false + }) + if (done) break + } +} + +export async function associationIdentity(sub: string) { + const account = (await idp?.directory?.())?.find((account) => account.sub === sub) + return { name: account?.name ?? sub, email: account?.email ?? undefined } +} diff --git a/src/associations/router.ts b/src/associations/router.ts new file mode 100644 index 0000000..eb516c0 --- /dev/null +++ b/src/associations/router.ts @@ -0,0 +1,94 @@ +import { TRPCError } from "@trpc/server" +import { z } from "zod" +import { uploadBlob } from "@/azure/blob" +import { SCOPE } from "@/idp/policies" +import { createTRPCRouter, policy } from "@/trpc" +import * as C from "./contract" +import type { createAssociationService } from "./service" + +export function createAssociationRouter( + service: ReturnType, + identity: (sub: string) => Promise<{ name: string; email?: string }> = async (sub) => ({ name: sub }) +) { + // Being authenticated admits an applicant; membership is checked afresh by the service, never trusted from input. + const user = policy({ user: { scope: SCOPE.admin } }).use(async ({ ctx, next }) => { + if (ctx.actor.kind !== "user") throw new TRPCError({ code: "FORBIDDEN" }) + const subject = await identity(ctx.actor.sub) + return next({ + ctx: { + viewer: { + sub: ctx.actor.sub, + name: subject.name, + email: subject.email, + operator: ctx.can("admin:access") && ctx.can("web:content:write"), + }, + }, + }) + }) + return createTRPCRouter({ + uploadLogo: user + .input( + z + .instanceof(FormData) + .transform((fd) => ({ id: fd.get("id"), file: fd.get("file") })) + .pipe( + z.object({ + id: z.uuid(), + file: z + .file() + .min(1) + .max(1024 * 1024) + .mime(["image/png", "image/jpeg"]), + }) + ) + ) + .output(z.object({ url: C.httpUrl })) + .mutation(async ({ ctx, input }) => { + const record = await service.get(ctx.viewer, input.id) + if ( + !record.canEdit && + !record.requests.some( + (q) => q.kind === "registration" && q.by === ctx.viewer.sub && ["draft", "changes"].includes(q.status) + ) + ) + throw new TRPCError({ code: "FORBIDDEN" }) + const bytes = Buffer.from(await input.file.arrayBuffer()) + const png = bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])) + const jpeg = bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255 + if ((!png && !jpeg) || (png ? input.file.type !== "image/png" : input.file.type !== "image/jpeg")) + throw new TRPCError({ code: "BAD_REQUEST", message: "Choose a valid PNG or JPEG logo" }) + const uploaded = await uploadBlob(bytes, png ? "png" : "jpg", png ? "image/png" : "image/jpeg") + return { url: uploaded.url } + }), + list: user.output(C.dashboardSchema).query(({ ctx }) => service.list(ctx.viewer)), + directory: user.output(C.directorySchema).query(() => service.directory()), + get: user + .input(C.refSchema) + .output(C.detailSchema) + .query(({ ctx, input }) => service.get(ctx.viewer, input.id)), + create: user + .input(C.createSchema) + .output(C.refSchema) + .mutation(({ ctx, input }) => service.create(ctx.viewer, input)), + command: user + .input(C.commandSchema) + .output(C.refSchema) + .mutation(({ ctx, input }) => service.command(ctx.viewer, input)), + invitation: user + .input(C.inviteSchema) + .output(C.invitationSchema) + .query(({ input }) => service.invitation(input.token)), + accept: user + .input(C.inviteSchema) + .output(C.refSchema) + .mutation(({ ctx, input }) => service.accept(ctx.viewer, input.token)), + lookup: user + .input(C.refSchema) + .output(z.object({ id: z.uuid(), name: z.string(), revision: z.number() })) + .query(async ({ input }) => { + const item = (await service.directory()).find((r) => r.id === input.id) + if (!item) throw new TRPCError({ code: "NOT_FOUND" }) + return item + }), + }) +} diff --git a/src/associations/service.ts b/src/associations/service.ts new file mode 100644 index 0000000..95e83ce --- /dev/null +++ b/src/associations/service.ts @@ -0,0 +1,436 @@ +import { createHash, randomBytes, randomUUID } from "node:crypto" +import { TRPCError } from "@trpc/server" +import type { z } from "zod" +import type { Command, createSchema, Event, Member, Profile, Request } from "./contract" + +export type Viewer = { sub: string; name: string; operator: boolean; email?: string } +export type Invitation = { requestId: string; hash: string; expiresAt: string } +export type Record = { + id: string + legacyId: number | null + revision: number + creator: string + registered: boolean + status: "pending" | "active" | "suspended" | "archived" + profile: Profile + published: Profile | null + members: Member[] + requests: Request[] + events: Event[] + invitations: Invitation[] + notes: string + commands: string[] +} +export type Mail = { id: string; to: string; subject: string; text: string } +export type Store = { + list(): Promise + create(record: Record, commandId: string, actor: string): Promise + transfer(from: string, to: string, operation: (source: Record, destination: Record) => T): Promise + change(id: string, operation: (record: Record, mail: Mail[]) => T): Promise +} +function fail( + code: "FORBIDDEN" | "NOT_FOUND" | "CONFLICT" | "BAD_REQUEST" | "TOO_MANY_REQUESTS", + message: string +): never { + throw new TRPCError({ code, message }) +} +const hash = (token: string) => createHash("sha256").update(token).digest("hex") +const activeMember = (r: Record, v: Viewer) => r.members.find((m) => m.sub === v.sub && m.active) +const accessible = (r: Record, v: Viewer) => + v.operator || + !!activeMember(r, v) || + r.creator === v.sub || + r.requests.some((q) => q.by === v.sub || q.targetSub === v.sub) +const writable = (r: Record, v: Viewer) => v.operator || (r.status === "active" && !!activeMember(r, v)) +const responsible = (r: Record, v: Viewer) => + v.operator || (r.status === "active" && activeMember(r, v)?.role === "responsible") +const operator = (v: Viewer) => { + if (!v.operator) fail("FORBIDDEN", "PoliNetwork approval is required") +} +const event = (r: Record, v: Viewer, action: string, detail = "", requestId?: string) => + r.events.push({ id: randomUUID(), at: new Date().toISOString(), actor: v.name, action, detail, requestId }) +function request(v: Viewer, kind: Request["kind"], explanation: string, profile: Profile | null = null): Request { + const now = new Date().toISOString() + return { + id: randomUUID(), + redirectId: null, + kind, + status: "draft", + by: v.sub, + byName: v.name, + explanation, + response: "", + profile, + targetSub: null, + targetName: null, + role: "responsible", + email: v.email ?? "", + remove: false, + accepted: false, + createdAt: now, + updatedAt: now, + decidedBy: null, + } +} +function validatePublication(p: Profile) { + if (!p.descriptionIt.trim() || !p.descriptionEn.trim()) + fail("BAD_REQUEST", "Complete both descriptions before submitting the public profile") +} +function summary(r: Record, v: Viewer) { + return { + id: r.id, + name: r.profile.name, + status: r.status, + registered: r.registered, + published: !!r.published, + role: activeMember(r, v)?.role ?? null, + pending: r.requests.filter((q) => q.status === "submitted" && (v.operator || q.by === v.sub)).length, + unrepresented: !r.members.some((m) => m.active && m.role === "responsible"), + } +} +export function present(r: Record, v: Viewer) { + if (!accessible(r, v)) fail("NOT_FOUND", "Association not found") + const member = !!activeMember(r, v) + // A claimant sees their own application, never another claimant's evidence or the private working profile. + const requests = r.requests.filter( + (q) => v.operator || q.by === v.sub || q.targetSub === v.sub || (member && q.kind === "content") + ) + return { + ...summary(r, v), + revision: r.revision, + profile: + v.operator || member || (!r.registered && r.creator === v.sub) + ? r.profile + : (r.published ?? { ...r.profile, descriptionIt: "", descriptionEn: "", email: "", links: [], logo: null }), + publishedProfile: r.published, + members: v.operator || member ? r.members : [], + requests, + events: r.events.filter( + (e) => + v.operator || + (e.requestId ? requests.some((q) => q.id === e.requestId) : member && e.action !== "Internal note updated") + ), + notes: v.operator ? r.notes : null, + canEdit: writable(r, v), + canSubmit: responsible(r, v), + canManage: responsible(r, v), + operator: v.operator, + } +} +export function createAssociationService(store: Store, dashboardUrl: string) { + return { + async list(v: Viewer) { + const records = (await store.list()).filter((r) => accessible(r, v)) + return { + operator: v.operator, + associations: records.map((r) => summary(r, v)), + requests: records.flatMap((r) => + present(r, v).requests.map((q) => ({ ...q, associationId: r.id, associationName: r.profile.name })) + ), + } + }, + async directory() { + return (await store.list()) + .filter((r) => r.registered && r.status === "active") + .map((r) => ({ id: r.id, name: r.profile.name, revision: r.revision })) + }, + async get(v: Viewer, id: string) { + const r = (await store.list()).find((r) => r.id === id) + if (!r) return fail("NOT_FOUND", "Association not found") + return present(r, v) + }, + async create(v: Viewer, input: z.infer) { + const q = request(v, "registration", input.explanation, input.profile) + q.status = input.submit ? "submitted" : "draft" + q.targetSub = v.sub + q.targetName = v.name + q.accepted = true + const r: Record = { + id: randomUUID(), + legacyId: null, + revision: 0, + creator: v.sub, + registered: false, + status: "pending", + profile: input.profile, + published: null, + members: [], + requests: [q], + events: [], + invitations: [], + notes: "", + commands: [], + } + if (v.operator && input.submit) { + r.registered = true + r.status = "active" + r.requests = [] + } + event( + r, + v, + v.operator && input.submit + ? "Association registered by PoliNetwork" + : input.submit + ? "Registration submitted" + : "Registration draft saved" + ) + return { id: await store.create(r, input.commandId, v.sub) } + }, + async command(v: Viewer, c: Command) { + if (c.action === "redirect") { + operator(v) + if (c.id === c.destinationId) fail("BAD_REQUEST", "Choose a different association") + return store.transfer(c.id, c.destinationId, (source, destination) => { + const key = `${v.sub}:${c.commandId}` + if (source.commands.includes(key)) return { id: destination.id } + if (source.revision !== c.revision) fail("CONFLICT", "Reload the request before continuing") + const q = source.requests.find( + (q) => q.id === c.requestId && q.kind === "registration" && q.status === "submitted" + ) + if (!q || source.registered || !destination.registered || destination.status !== "active") + fail("CONFLICT", "Only an unapproved registration can be redirected to an active association") + const forwarded = { + ...q, + id: randomUUID(), + kind: "access" as const, + profile: null, + response: "", + decidedBy: null, + } + if (destination.members.some((m) => m.sub === q.targetSub && m.active)) + fail("CONFLICT", "The applicant already has access") + destination.requests.push(forwarded) + q.status = "withdrawn" + q.response = c.reason + q.decidedBy = v.name + q.redirectId = destination.id + source.status = "archived" + source.commands.push(key) + source.revision++ + destination.revision++ + event(source, v, "Registration redirected", c.reason) + event(destination, v, "Access request received from an existing application") + return { id: destination.id } + }) + } + return store.change(c.id, (r, mail) => { + // Recheck authorization before idempotency: a former representative cannot reuse commands to read the record. + if (c.action !== "access" && !accessible(r, v)) fail("NOT_FOUND", "Association not found") + const commandKey = `${v.sub}:${c.commandId}` + if (r.commands.includes(commandKey)) return { id: r.id } + if (r.revision !== c.revision) fail("CONFLICT", "The association changed. Reload before continuing.") + if ( + ["access", "invite", "membership"].includes(c.action) && + !v.operator && + r.requests.filter((q) => q.by === v.sub && Date.parse(q.createdAt) > Date.now() - 86400000).length >= 20 + ) + fail("TOO_MANY_REQUESTS", "Too many requests today. Contact PoliNetwork.") + if (c.action === "save") { + let q = c.requestId ? r.requests.find((q) => q.id === c.requestId) : undefined + if (q && q.kind !== "registration" && q.kind !== "content") + fail("BAD_REQUEST", "This request has no editable profile") + if (q?.kind === "registration") { + if (q.by !== v.sub || r.registered) fail("FORBIDDEN", "Only the applicant can edit this request") + } else if (!writable(r, v)) fail("FORBIDDEN", "You cannot edit this association") + if (q && !["draft", "changes"].includes(q.status)) + fail("CONFLICT", "Withdraw the submitted request before editing") + if (!q) { + if (c.requestId) fail("NOT_FOUND", "Request not found") + if (r.requests.some((q) => q.kind === "content" && ["draft", "changes", "submitted"].includes(q.status))) + fail("CONFLICT", "There is already a working profile") + q = request(v, "content", c.explanation, c.profile) + r.requests.push(q) + } + q.profile = c.profile + q.explanation = c.explanation + q.updatedAt = new Date().toISOString() + if (!r.registered) r.profile = c.profile + event(r, v, "Draft saved") + } else if (c.action === "reply") { + const q = r.requests.find((q) => q.id === c.requestId) + if (!q || q.by !== v.sub || q.status !== "changes") + fail("FORBIDDEN", "Only the applicant can answer a request for information") + q.explanation = c.explanation + q.status = "submitted" + q.updatedAt = new Date().toISOString() + event(r, v, "Requested information supplied") + } else if (c.action === "submit" || c.action === "withdraw") { + const q = r.requests.find((q) => q.id === c.requestId) + if (!q) fail("NOT_FOUND", "Request not found") + if (q.kind === "content" ? !responsible(r, v) : q.by !== v.sub && !v.operator) + fail("FORBIDDEN", "You cannot submit this request") + if (c.action === "submit") { + if (!["draft", "changes"].includes(q.status)) fail("CONFLICT", "This request cannot be submitted") + if (!q.explanation.trim()) fail("BAD_REQUEST", "Explain the request before submitting") + if (q.kind === "content" && q.profile) validatePublication(q.profile) + q.status = "submitted" + } else { + if (!["draft", "changes", "submitted"].includes(q.status)) + fail("CONFLICT", "This request is already closed") + q.status = "withdrawn" + r.invitations = r.invitations.filter((i) => i.requestId !== q.id) + } + q.updatedAt = new Date().toISOString() + event(r, v, c.action === "submit" ? "Request submitted" : "Request withdrawn") + } else if (c.action === "access") { + if (!r.registered || r.status !== "active" || activeMember(r, v)) + fail("FORBIDDEN", "This association is not available for an access request") + if ( + r.requests.some((q) => q.by === v.sub && q.kind === "access" && ["submitted", "changes"].includes(q.status)) + ) + fail("CONFLICT", "You already have an open access request") + const q = request(v, "access", c.explanation) + q.status = "submitted" + q.targetSub = v.sub + q.targetName = v.name + q.accepted = true + r.requests.push(q) + event(r, v, "Access requested") + } else if (c.action === "invite" || c.action === "membership") { + if (!responsible(r, v) || !r.registered) fail("FORBIDDEN", "Only a responsible can propose representatives") + const q = request(v, "membership", c.explanation) + q.status = "submitted" + q.role = c.role + if (c.action === "invite") { + if ( + r.requests.some( + (q) => + q.email.toLowerCase() === c.email.toLowerCase() && q.kind === "membership" && q.status === "submitted" + ) + ) + fail("CONFLICT", "An invitation is already pending for this address") + q.email = c.email + const token = randomBytes(32).toString("base64url") + r.invitations.push({ + requestId: q.id, + hash: hash(token), + expiresAt: new Date(Date.now() + 14 * 86400000).toISOString(), + }) + mail.push({ + id: randomUUID(), + to: c.email, + subject: `Invito — ${r.profile.name}`, + text: `Sei stato invitato come referente di ${r.profile.name}. Accetta con il tuo account personale; PoliNetwork dovrà poi approvare il collegamento. L'invito scade fra 14 giorni.\n${dashboardUrl}/associations/invite?token=${token}`, + }) + } else { + const member = r.members.find((m) => m.sub === c.sub && m.active) + if (!member) fail("NOT_FOUND", "Representative not found") + q.targetSub = member.sub + q.targetName = member.name + q.accepted = true + q.remove = c.remove + } + r.requests.push(q) + event(r, v, "Representative change requested") + } else if (c.action === "review") { + operator(v) + const q = r.requests.find((q) => q.id === c.requestId) + if (!q || q.status !== "submitted") fail("CONFLICT", "The request is not awaiting review") + if (c.decision === "approve") { + if (r.status === "archived" || r.status === "suspended") + fail("CONFLICT", "Reactivate the association before approving changes") + if (q.kind === "content") { + if (!r.registered || !q.profile) fail("BAD_REQUEST", "Register the association first") + validatePublication(q.profile) + r.profile = q.profile + r.published = q.profile + } else { + if (!q.accepted || !q.targetSub) fail("BAD_REQUEST", "The invited person must accept before approval") + if (q.kind === "registration") { + if (r.registered) fail("CONFLICT", "Already registered") + r.registered = true + r.status = "active" + if (q.profile) r.profile = q.profile + } + const target = r.members.find((m) => m.sub === q.targetSub) + if ( + (q.remove || q.role !== "responsible") && + target?.active && + target.role === "responsible" && + !r.members.some((m) => m.active && m.role === "responsible" && m.sub !== target.sub) + ) + fail("CONFLICT", "Approve a replacement responsible first; use explicit revocation for urgent removal") + if (target) { + target.role = q.role + target.active = !q.remove + } else r.members.push({ sub: q.targetSub, name: q.targetName ?? q.targetSub, role: q.role, active: true }) + } + } + q.status = c.decision === "approve" ? "approved" : c.decision === "changes" ? "changes" : "rejected" + q.response = c.reason + q.decidedBy = v.name + q.updatedAt = new Date().toISOString() + if (q.status !== "changes") r.invitations = r.invitations.filter((i) => i.requestId !== q.id) + if (q.email) + mail.push({ + id: randomUUID(), + to: q.email, + subject: `Aggiornamento richiesta — ${r.profile.name}`, + text: `La richiesta per ${r.profile.name} è stata aggiornata: ${q.status}. Accedi con il tuo account per leggere la risposta di PoliNetwork.\n${dashboardUrl}/dashboard/associations/${r.id}`, + }) + event(r, v, `Request ${q.status}`, c.reason, q.id) + } else if (c.action === "status") { + operator(v) + if (!r.registered) fail("BAD_REQUEST", "Review registration first") + r.status = c.status + if (c.hide || c.status === "archived") r.published = null + event(r, v, `Association ${c.status}`, c.reason) + } else if (c.action === "unpublish") { + operator(v) + r.published = null + event(r, v, "Profile unpublished", c.reason) + } else if (c.action === "note") { + operator(v) + r.notes = c.note + event(r, v, "Internal note updated") + } else if (c.action === "leave" || c.action === "revoke") { + if (c.action === "revoke") operator(v) + const member = r.members.find((m) => m.sub === (c.action === "leave" ? v.sub : c.sub) && m.active) + if (!member) fail("NOT_FOUND", "Active representative not found") + member.active = false + event(r, v, c.action === "leave" ? "Representative left" : "Representative revoked", c.reason) + } + r.commands.push(commandKey) + r.revision++ + return { id: r.id } + }) + }, + async invitation(token: string) { + const r = (await store.list()).find((r) => + r.invitations.some((i) => i.hash === hash(token) && i.expiresAt > new Date().toISOString()) + ) + const i = r?.invitations.find((i) => i.hash === hash(token)) + const q = r?.requests.find((q) => q.id === i?.requestId) + if (!r || !i || !q || !["submitted", "changes"].includes(q.status) || r.status !== "active") + fail("NOT_FOUND", "Invitation expired or revoked") + return { associationName: r.profile.name, role: q.role, expiresAt: i.expiresAt } + }, + async accept(v: Viewer, token: string) { + const r = (await store.list()).find((r) => r.invitations.some((i) => i.hash === hash(token))) + if (!r) fail("NOT_FOUND", "Invitation expired or revoked") + return store.change(r.id, (r) => { + const i = r.invitations.find((i) => i.hash === hash(token)) + const q = r.requests.find((q) => q.id === i?.requestId) + if ( + !i || + !q || + i.expiresAt <= new Date().toISOString() || + !["submitted", "changes"].includes(q.status) || + r.status !== "active" + ) + fail("NOT_FOUND", "Invitation expired or revoked") + if (activeMember(r, v)) fail("CONFLICT", "You already represent this association") + q.targetSub = v.sub + q.targetName = v.name + q.accepted = true + q.status = "submitted" + q.updatedAt = new Date().toISOString() + r.invitations = r.invitations.filter((candidate) => candidate !== i) + r.revision++ + event(r, v, "Invitation accepted; awaiting PoliNetwork") + return { id: r.id } + }) + }, + } +} diff --git a/src/associations/store-pg.ts b/src/associations/store-pg.ts new file mode 100644 index 0000000..1dec326 --- /dev/null +++ b/src/associations/store-pg.ts @@ -0,0 +1,97 @@ +import { TRPCError } from "@trpc/server" +import { eq, inArray, sql } from "drizzle-orm" +import type { DB } from "@/db" +import { associationMail, associationRegistry } from "@/db/schema/web/association-portal" +import { associations } from "@/db/schema/web/associations" +import type { Mail, Record, Store } from "./service" + +export function createAssociationStore(db: typeof DB): Store { + return { + async list() { + return (await db.select().from(associationRegistry)).map((row) => row.state) + }, + async create(state, commandId, actor) { + const creationKey = `${actor}:${commandId}` + return db.transaction(async (tx) => { + // Per-account lock bounds abandoned submissions and concurrent retries without blocking other applicants. + await tx.execute(sql`select pg_advisory_xact_lock(hashtextextended(${actor}, 0))`) + const existing = await tx + .select() + .from(associationRegistry) + .where(eq(associationRegistry.creationKey, creationKey)) + if (existing[0]) return existing[0].id + const [{ count }] = await tx + .select({ count: sql`count(*)::int` }) + .from(associationRegistry) + .where( + sql`${associationRegistry.state}->>'creator' = ${actor} AND (${associationRegistry.state}->>'registered')::boolean = false` + ) + if (count >= 10) + throw new TRPCError({ + code: "TOO_MANY_REQUESTS", + message: "You already have ten registration drafts or requests. Contact PoliNetwork.", + }) + await tx.insert(associationRegistry).values({ id: state.id, state, creationKey }) + return state.id + }) + }, + async transfer(from: string, to: string, operation: (source: Record, destination: Record) => T) { + return db.transaction(async (tx) => { + const rows = await tx + .select() + .from(associationRegistry) + .where(inArray(associationRegistry.id, [from, to])) + .orderBy(associationRegistry.id) + .for("update") + const source = rows.find((r) => r.id === from)?.state + const destination = rows.find((r) => r.id === to)?.state + if (!source || !destination) throw new TRPCError({ code: "NOT_FOUND" }) + const result = operation(source, destination) + for (const state of [source, destination]) + await tx.update(associationRegistry).set({ state }).where(eq(associationRegistry.id, state.id)) + return result + }) + }, + async change(id: string, operation: (record: Record, mail: Mail[]) => T) { + return db.transaction(async (tx) => { + const [row] = await tx.select().from(associationRegistry).where(eq(associationRegistry.id, id)).for("update") + if (!row) throw new TRPCError({ code: "NOT_FOUND", message: "Association not found" }) + const state = row.state + const mail: Mail[] = [] + const result = operation(state, mail) + // Preserve the old numeric public IDs and API shape. Only an approved version is copied into the old catalog. + if (state.published) { + const p = state.published + const links = Object.fromEntries(p.links.map((link) => [link.platform, link.url])) + const values = { + name: p.name, + descriptionIt: p.descriptionIt, + descriptionEn: p.descriptionEn, + logo: p.logo, + email: p.email || null, + website: links.website ?? null, + facebook: links.facebook ?? null, + instagram: links.instagram ?? null, + tiktok: links.tiktok ?? null, + x: links.x ?? null, + youtube: links.youtube ?? null, + telegram: links.telegram ?? null, + linkedin: links.linkedin ?? null, + spotify: links.spotify ?? null, + } + if (state.legacyId) await tx.update(associations).set(values).where(eq(associations.id, state.legacyId)) + else { + const [created] = await tx + .insert(associations) + .values({ ...values, createdBySub: state.creator }) + .returning({ id: associations.id }) + state.legacyId = created.id + } + } + await tx.update(associationRegistry).set({ state }).where(eq(associationRegistry.id, id)) + if (mail.length) await tx.insert(associationMail).values(mail.map((m) => ({ id: m.id, mail: m }))) + return result + }) + }, + } +} diff --git a/src/cron.ts b/src/cron.ts index 7c78586..2f3d31e 100644 --- a/src/cron.ts +++ b/src/cron.ts @@ -43,6 +43,14 @@ export function cron() { } }) + new Cron("0 * * * * *", { protect: true }, async () => { + try { + const { deliverAssociationMail } = await import("./associations") + await deliverAssociationMail() + } catch (error) { + logger.error(error, "[CRON] Association mail outbox") + } + }) logger.info("[CRON] scheduled") new Cron("0 * * * * *", async () => { try { diff --git a/src/db/schema/web/association-portal.ts b/src/db/schema/web/association-portal.ts new file mode 100644 index 0000000..21e7d66 --- /dev/null +++ b/src/db/schema/web/association-portal.ts @@ -0,0 +1,17 @@ +import { integer, jsonb, text, timestamp, uuid } from "drizzle-orm/pg-core" +import type { Mail, Record } from "@/associations/service" +import { createTable } from "../create-table" + +// One locked aggregate per association: requests, membership and publication change atomically. +export const associationRegistry = createTable.web("association_registry", { + id: uuid().primaryKey(), + state: jsonb().$type().notNull(), + creationKey: text("creation_key").notNull().unique(), +}) +export const associationMail = createTable.web("association_mail", { + id: uuid().primaryKey(), + mail: jsonb().$type().notNull(), + attempts: integer().notNull().default(0), + nextAttempt: timestamp("next_attempt", { withTimezone: true }).notNull().defaultNow(), + sentAt: timestamp("sent_at", { withTimezone: true }), +}) diff --git a/src/db/schema/web/index.ts b/src/db/schema/web/index.ts index 15d73c3..96855b5 100644 --- a/src/db/schema/web/index.ts +++ b/src/db/schema/web/index.ts @@ -1,3 +1,4 @@ +import * as associationPortal from "./association-portal" import * as associations from "./associations" import * as documents from "./documents" import * as faqs from "./faqs" @@ -9,6 +10,7 @@ import * as test from "./test" export const schema = { ...associations, + ...associationPortal, ...test, ...faqs, ...freshman, diff --git a/src/emails/mailer.tsx b/src/emails/mailer.tsx index d90571c..b7b6782 100644 --- a/src/emails/mailer.tsx +++ b/src/emails/mailer.tsx @@ -239,3 +239,19 @@ export async function sendRegulationDelegaEmail( messageId: input.messageId, }) } + +export async function sendAssociationEmail(mail: { id: string; to: string; subject: string; text: string }) { + return sendEmail( + mail.to, + makeSubject(mail.subject), +
+

{mail.subject}

+

{mail.text}

+
, + [], + { + throwOnError: true, + messageId: ``, + } + ) +} diff --git a/src/routers/index.ts b/src/routers/index.ts index b89d038..80071e0 100644 --- a/src/routers/index.ts +++ b/src/routers/index.ts @@ -1,3 +1,5 @@ +import { associationIdentity, associationPortal } from "@/associations" +import { createAssociationRouter } from "@/associations/router" import { createTRPCRouter } from "@/trpc" import { azureRouter } from "./azure" import { esignRouter } from "./esign" @@ -16,6 +18,7 @@ import { webRouter } from "./web" * All routers added in /api/routers should be manually added here. */ export const appRouter = createTRPCRouter({ + associationPortal: createAssociationRouter(associationPortal, associationIdentity), azure: azureRouter, esign: esignRouter, groups: groupsRouter, diff --git a/src/routers/web/associations.ts b/src/routers/web/associations.ts index bdfd2c1..b446dbf 100644 --- a/src/routers/web/associations.ts +++ b/src/routers/web/associations.ts @@ -1,19 +1,9 @@ -import { asc, eq } from "drizzle-orm" +import { TRPCError } from "@trpc/server" import z from "zod" -import { uploadBlob } from "@/azure/blob" -import { DB, SCHEMA } from "@/db" -import { authorOf, createdByColumns, modifiedByColumns } from "@/idp/author" +import { associationStore } from "@/associations" +import { linkSchema } from "@/associations/contract" import { dashboard, publicData } from "@/idp/policies" import { createTRPCRouter, policy } from "@/trpc" -import { getImageExtension } from "@/utils/web" - -const ASSOCIATIONS = SCHEMA.WEB.associations - -const logoFileSchema = z - .file() - .mime(["image/png", "image/jpeg", "image/svg+xml"]) - .min(1) - .max(1024 * 1024) const associationLinksSchema = z.object({ email: z.email().nullable(), @@ -28,13 +18,6 @@ const associationLinksSchema = z.object({ spotify: z.url().nullable(), }) -const associationFormSchema = z.object({ - name: z.string(), - descriptionIt: z.string(), - descriptionEn: z.string(), - logo: logoFileSchema.optional(), -}) - const associationSchema = z.object({ id: z.number(), name: z.string(), @@ -42,142 +25,59 @@ const associationSchema = z.object({ descriptionEn: z.string(), logo: z.string().nullable(), links: associationLinksSchema, + extraLinks: z.array(linkSchema).optional(), }) -function formatAssociation(association: typeof ASSOCIATIONS.$inferSelect): z.infer { - return { - id: association.id, - name: association.name, - descriptionIt: association.descriptionIt, - descriptionEn: association.descriptionEn, - logo: association.logo, - links: { - email: association.email, - website: association.website, - facebook: association.facebook, - instagram: association.instagram, - tiktok: association.tiktok, - x: association.x, - youtube: association.youtube, - telegram: association.telegram, - linkedin: association.linkedin, - spotify: association.spotify, - }, - } -} - export default createTRPCRouter({ getAllAssociations: policy(publicData) .output(z.array(associationSchema)) .query(async () => { - const associations = await DB.select().from(ASSOCIATIONS).orderBy(asc(ASSOCIATIONS.id)) - - return associations.map(formatAssociation) - }), - - addAssociation: policy(dashboard("web:content:write")) - .input( - z - .instanceof(FormData) - .transform((fd): Record => Object.fromEntries(fd.entries())) - .pipe(associationFormSchema) - ) - .mutation(async ({ input, ctx }) => { - const { name, descriptionIt, descriptionEn, logo } = input - - const uploadedLogo = logo - ? await uploadBlob(Buffer.from(await logo.arrayBuffer()), getImageExtension(logo), logo.type) - : null - - const [res] = await DB.insert(ASSOCIATIONS) - .values({ - name, - descriptionIt, - descriptionEn, - logo: uploadedLogo?.url ?? null, - ...createdByColumns(authorOf(ctx.actor)), + const records = await associationStore.list() + return records + .filter((r) => r.registered && r.published && r.status !== "archived" && r.legacyId !== null) + .map((r) => { + const p = r.published! + const first = (key: string) => p.links.find((l) => l.platform === key)?.url ?? null + return { + id: r.legacyId!, + name: p.name, + descriptionIt: p.descriptionIt, + descriptionEn: p.descriptionEn, + logo: p.logo, + links: { + email: p.email || null, + website: first("website"), + facebook: first("facebook"), + instagram: first("instagram"), + tiktok: first("tiktok"), + x: first("x"), + youtube: first("youtube"), + telegram: first("telegram"), + linkedin: first("linkedin"), + spotify: first("spotify"), + }, + extraLinks: p.links, + } }) - .returning() - - return formatAssociation(res) }), + addAssociation: policy(dashboard("web:content:write")) + .input(z.unknown()) + .mutation(() => retired()), editAssociation: policy(dashboard("web:content:write")) - .input( - z - .instanceof(FormData) - .transform((fd): Record => Object.fromEntries(fd.entries())) - .pipe( - associationFormSchema.extend({ - id: z.coerce.number(), - }) - ) - ) - .mutation(async ({ input, ctx }) => { - const { id, name, descriptionIt, descriptionEn, logo } = input - - const uploadedLogo = logo - ? await uploadBlob(Buffer.from(await logo.arrayBuffer()), getImageExtension(logo), logo.type) - : undefined - - const [res] = await DB.update(ASSOCIATIONS) - .set({ - name, - descriptionIt, - descriptionEn, - ...(uploadedLogo ? { logo: uploadedLogo.url } : {}), - ...modifiedByColumns(authorOf(ctx.actor)), - }) - .where(eq(ASSOCIATIONS.id, id)) - .returning() - - if (!res) return { error: "NOT_FOUND" } - return formatAssociation(res) - }), - + .input(z.unknown()) + .mutation(() => retired()), editAssociationLinks: policy(dashboard("web:content:write")) - .input( - z.object({ - id: z.number(), - links: associationLinksSchema, - }) - ) - .mutation(async ({ input, ctx }) => { - const { id, links } = input - const { email, website, facebook, instagram, tiktok, x, youtube, telegram, linkedin, spotify } = links - - const [res] = await DB.update(ASSOCIATIONS) - .set({ - email, - website, - facebook, - instagram, - tiktok, - x, - youtube, - telegram, - linkedin, - spotify, - ...modifiedByColumns(authorOf(ctx.actor)), - }) - .where(eq(ASSOCIATIONS.id, id)) - .returning() - - if (!res) return { error: "NOT_FOUND" } - return formatAssociation(res) - }), - + .input(z.unknown()) + .mutation(() => retired()), deleteAssociation: policy(dashboard("web:content:write")) - .input( - z.object({ - id: z.number(), - }) - ) - .mutation(async ({ input }) => { - const { id } = input - const deleted = await DB.delete(ASSOCIATIONS).where(eq(ASSOCIATIONS.id, id)).returning() - - if (deleted.length === 0) return { error: "NOT_FOUND" } - return { error: null } - }), + .input(z.unknown()) + .mutation(() => retired()), }) + +function retired(): never { + throw new TRPCError({ + code: "PRECONDITION_FAILED", + message: "Use the Associations registry to review and publish changes. The legacy editor is retired.", + }) +} diff --git a/tests/associations-fixture.ts b/tests/associations-fixture.ts new file mode 100644 index 0000000..64ba797 --- /dev/null +++ b/tests/associations-fixture.ts @@ -0,0 +1,67 @@ +import { randomUUID } from "node:crypto" +import type { Command, Profile } from "@/associations/contract" +import { createAssociationService, type Mail, type Record, type Store, type Viewer } from "@/associations/service" + +export const owner: Viewer = { sub: "owner", name: "Owner", email: "owner@example.org", operator: false } +export const staff: Viewer = { sub: "staff", name: "Staff", operator: true } +export const outsider: Viewer = { sub: "outsider", name: "Outsider", operator: false } +export const profile: Profile = { + name: "Association", + acronym: "A", + descriptionIt: "Descrizione", + descriptionEn: "Description", + email: "info@example.org", + logo: null, + links: [{ platform: "telegram", label: "Canale", url: "https://t.me/example" }], +} +export function harness() { + const rows = new Map() + const creation = new Map() + const mails: Mail[] = [] + const store: Store = { + list: async () => structuredClone([...rows.values()]), + async create(r, command, actor) { + const key = `${actor}:${command}` + if (creation.has(key)) return creation.get(key)! + rows.set(r.id, structuredClone(r)) + creation.set(key, r.id) + return r.id + }, + async change(id, fn) { + const r = structuredClone(rows.get(id)!) + const mail: Mail[] = [] + const result = fn(r, mail) + rows.set(id, r) + mails.push(...mail) + return result + }, + async transfer(from, to, fn) { + const a = structuredClone(rows.get(from)!) + const b = structuredClone(rows.get(to)!) + const result = fn(a, b) + rows.set(from, a) + rows.set(to, b) + return result + }, + } + const service = createAssociationService(store, "https://admin.example.org") + async function command( + v: Viewer, + id: string, + action: Command extends infer T ? (T extends Command ? Omit : never) : never + ) { + return service.command(v, { ...action, id, revision: rows.get(id)!.revision, commandId: randomUUID() } as Command) + } + async function registered() { + const { id } = await service.create(owner, { + profile, + explanation: "I represent this association", + submit: true, + commandId: randomUUID(), + }) + const requestId = rows.get(id)!.requests[0].id + await command(staff, id, { action: "review", requestId, decision: "approve", reason: "Verified official contact" }) + return id + } + return { service, rows, mails, command, registered } +} diff --git a/tests/associations-postgres.fixture.ts b/tests/associations-postgres.fixture.ts new file mode 100644 index 0000000..c0ce38f --- /dev/null +++ b/tests/associations-postgres.fixture.ts @@ -0,0 +1,145 @@ +import assert from "node:assert/strict" +import { randomUUID } from "node:crypto" +import { cp, mkdtemp, readFile, rm, writeFile } from "node:fs/promises" +import { tmpdir } from "node:os" +import { join } from "node:path" +import { SQL } from "bun" +import { drizzle } from "drizzle-orm/bun-sql" +import { migrate } from "drizzle-orm/bun-sql/migrator" +import { createAssociationService } from "@/associations/service" +import { createAssociationStore } from "@/associations/store-pg" +import { schema } from "@/db/schema" +import { associationRegistry } from "@/db/schema/web/association-portal" +import { associations } from "@/db/schema/web/associations" + +const connection = { + hostname: "127.0.0.1", + port: Number(process.env.SEED_TEST_DB_PORT), + username: "seed_test", + password: "seed_test", +} +const admin = new SQL({ ...connection, database: "postgres" }) +const name = `association_test_${process.pid}` +await admin.unsafe(`CREATE DATABASE ${name}`) +const client = new SQL({ ...connection, database: name }) +const db = drizzle({ client, schema }) +const folder = await mkdtemp(join(tmpdir(), "association-migrations-")) +try { + await cp("drizzle", folder, { recursive: true }) + const journalPath = join(folder, "meta/_journal.json") + const journal = JSON.parse(await readFile(journalPath, "utf8")) + journal.entries = journal.entries.filter((e: { idx: number }) => e.idx < 40) + await writeFile(journalPath, JSON.stringify(journal)) + await migrate(db, { migrationsFolder: folder }) + await db + .insert(associations) + .values( + ["One", "Two"].map((name) => ({ + name, + descriptionIt: "Italiano", + descriptionEn: "English", + createdBySub: "legacy", + telegram: "https://t.me/test", + })) + ) + await migrate(db, { migrationsFolder: "./drizzle" }) + const store = createAssociationStore(db) + const service = createAssociationService(store, "https://admin.example.org") + const staff = { sub: "staff", name: "Staff", operator: true } + const user = { sub: "new", name: "New", operator: false } + const migrated = await store.list() + assert.equal(migrated.length, 2) + assert.equal(new Set(migrated.map((r) => r.id)).size, 2) + assert(migrated.every((r) => r.published && r.members.length === 0 && r.legacyId)) + const profile = { + name: "New", + acronym: "", + descriptionIt: "IT", + descriptionEn: "EN", + email: "", + logo: null, + links: [], + } + const commandId = randomUUID() + const [a, b] = await Promise.all([ + service.create(user, { profile, explanation: "Test", submit: true, commandId }), + service.create(user, { profile, explanation: "Test", submit: true, commandId }), + ]) + assert.equal(a.id, b.id) + const record = await service.get(staff, a.id) + const review = { + id: a.id, + revision: record.revision, + commandId: randomUUID(), + action: "review" as const, + requestId: record.requests[0].id, + decision: "approve" as const, + reason: "Verified", + } + const results = await Promise.allSettled([ + service.command(staff, review), + service.command(staff, { ...review, commandId: randomUUID() }), + ]) + assert.equal(results.filter((r) => r.status === "fulfilled").length, 1) + const current = await service.get(staff, a.id) + await service.command(user, { + id: a.id, + revision: current.revision, + commandId: randomUUID(), + action: "save", + requestId: null, + profile, + explanation: "Publish", + }) + let next = await service.get(staff, a.id) + await service.command(user, { + id: a.id, + revision: next.revision, + commandId: randomUUID(), + action: "submit", + requestId: next.requests.at(-1)!.id, + }) + next = await service.get(staff, a.id) + await service.command(staff, { + id: a.id, + revision: next.revision, + commandId: randomUUID(), + action: "review", + requestId: next.requests.at(-1)!.id, + decision: "approve", + reason: "Approved", + }) + assert.equal((await db.select().from(associations)).length, 3) + // A new service instance sees persisted publication, roles and history. + const restarted = createAssociationService(createAssociationStore(db), "https://admin.example.org") + const persisted = await restarted.get(user, a.id) + assert(persisted.published) + assert.equal(persisted.role, "responsible") + await restarted.command(staff, { + id: a.id, + revision: persisted.revision, + commandId: randomUUID(), + action: "unpublish", + reason: "Hide", + }) + assert.equal((await restarted.get(user, a.id)).published, false) + assert.equal((await db.select().from(associationRegistry)).length, 3) + console.log( + JSON.stringify({ + checked: [ + "legacy backfill", + "stable IDs", + "concurrent create", + "concurrent review", + "publication", + "restart", + "unpublish without deletion", + ], + }) + ) +} finally { + await client.close() + await admin.unsafe(`DROP DATABASE ${name}`) + await admin.close() + await rm(folder, { recursive: true, force: true }) +} diff --git a/tests/associations-postgres.test.ts b/tests/associations-postgres.test.ts new file mode 100644 index 0000000..97c5957 --- /dev/null +++ b/tests/associations-postgres.test.ts @@ -0,0 +1,15 @@ +import { execFile } from "node:child_process" +import { promisify } from "node:util" +import { expect, it } from "vitest" + +it.skipIf(!process.env.SEED_TEST_DB_PORT)( + "persists publication and serializes concurrent association approvals in PostgreSQL", + async () => { + const { stdout } = await promisify(execFile)("bun", ["tests/associations-postgres.fixture.ts"], { + env: process.env, + timeout: 60000, + }) + expect(JSON.parse(stdout.trim().split("\n").at(-1) ?? "{}").checked).toHaveLength(7) + }, + 65000 +) diff --git a/tests/associations-preview.fixture.ts b/tests/associations-preview.fixture.ts new file mode 100644 index 0000000..0490247 --- /dev/null +++ b/tests/associations-preview.fixture.ts @@ -0,0 +1,57 @@ +// Local-only browser harness. Never imported by the application server. +import { fetchRequestHandler } from "@trpc/server/adapters/fetch" +import { createAssociationRouter } from "@/associations/router" +import { createTRPCRouter, policy } from "@/trpc" +import { harness } from "./associations-fixture" + +const h = harness() +await h.registered() +const router = createTRPCRouter({ + associationPortal: createAssociationRouter(h.service, async (sub) => ({ + name: sub === "owner" ? "Anna Referente" : "Operatore PoliNetwork", + email: `${sub}@example.org`, + })), + me: createTRPCRouter({ + access: policy({ user: { scope: "backend:admin" } }).query(({ ctx }) => ({ + sub: ctx.actor.kind === "user" ? ctx.actor.sub : "", + telegramId: null, + permissions: ctx.can("admin:access") ? ["admin:access", "web:content:write"] : [], + stale: false, + })), + }), + regulations: createTRPCRouter({ + me: createTRPCRouter({ + get: policy({ user: { scope: "backend:admin" } }).query(() => ({ assignedDrafts: 0, deleghe: 0 })), + }), + }), +}) +Bun.serve({ + port: 15491, + hostname: "127.0.0.1", + fetch(req) { + return fetchRequestHandler({ + endpoint: "/api/trpc", + req, + router, + createContext: () => { + const raw = req.headers.get("authorization")?.replace("Bearer ", "") ?? "" + const sub = JSON.parse(Buffer.from(raw.split(".")[1] ?? "", "base64url").toString()).sub + return { + auth: { + kind: "token" as const, + actor: { kind: "user" as const, sub, client: "preview", telegramId: null }, + scopes: new Set(["backend:admin"]), + }, + access: { + has: () => sub === "staff", + current: () => null, + subjectBySub: () => undefined, + subjectByTelegramId: () => undefined, + status: () => ({ fresh: true, generation: 1, subjects: 2, lastSyncAt: 1 }), + }, + } + }, + }) + }, +}) +console.log("Association test backend ready on 15491") diff --git a/tests/associations-router.test.ts b/tests/associations-router.test.ts new file mode 100644 index 0000000..fe20d29 --- /dev/null +++ b/tests/associations-router.test.ts @@ -0,0 +1,58 @@ +import type { Actor } from "@polinetwork/auth-kit" +import { beforeAll, describe, expect, it } from "vitest" +import type { Context } from "@/trpc" +import { harness, owner } from "./associations-fixture" + +Object.assign(process.env, { + NODE_ENV: "test", + ENCRYPTION_KEY: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", + DB_HOST: "localhost", + DB_USER: "postgres", + DB_PASS: "postgres", + DB_NAME: "test", +}) +let makeRouter: typeof import("@/associations/router").createAssociationRouter +beforeAll(async () => { + makeRouter = (await import("@/associations/router")).createAssociationRouter +}) +function context( + permissions: string[] = [], + actor: Actor = { kind: "user", sub: owner.sub, client: "admin", telegramId: null }, + scopes = ["backend:admin"] +): Context { + return { + auth: { kind: "token", actor, scopes: new Set(scopes) }, + access: { + has: (_, permission) => permissions.includes(permission), + current: () => null, + subjectBySub: () => undefined, + subjectByTelegramId: () => undefined, + status: () => ({ fresh: true, generation: 1, subjects: 1, lastSyncAt: 1 }), + }, + } +} +describe("Association API policies", () => { + it("rejects missing tokens, service actors and wrong audience scope", async () => { + const router = makeRouter(harness().service) + await expect(router.createCaller({}).list()).rejects.toMatchObject({ code: "UNAUTHORIZED" }) + await expect( + router.createCaller(context([], { kind: "service", client: "web" }, ["backend:public:read"])).list() + ).rejects.toMatchObject({ code: "FORBIDDEN" }) + await expect(router.createCaller(context([], undefined, ["backend:public:read"])).list()).rejects.toMatchObject({ + code: "FORBIDDEN", + }) + }) + it("admits authenticated applicants without admin or People grants, scopes records and exposes no directory of personal accounts", async () => { + const h = harness() + const id = await h.registered() + const router = makeRouter(h.service) + expect((await router.createCaller(context()).get({ id })).role).toBe("responsible") + const stranger = router.createCaller( + context([], { kind: "user", sub: "stranger", client: "admin", telegramId: null }) + ) + await expect(stranger.get({ id })).rejects.toMatchObject({ code: "NOT_FOUND" }) + expect(await stranger.directory()).toEqual([{ id, name: "Association", revision: 1 }]) + expect((await router.createCaller(context(["web:content:write"])).list()).operator).toBe(false) + expect((await router.createCaller(context(["admin:access", "web:content:write"])).list()).operator).toBe(true) + }) +}) diff --git a/tests/associations.test.ts b/tests/associations.test.ts new file mode 100644 index 0000000..8123182 --- /dev/null +++ b/tests/associations.test.ts @@ -0,0 +1,201 @@ +import { randomUUID } from "node:crypto" +import { describe, expect, it } from "vitest" +import { commandSchema, profileSchema } from "@/associations/contract" +import { harness, outsider, owner, profile, staff } from "./associations-fixture" + +describe("Association registry and scoped review", () => { + it("registers an applicant without publishing or granting global permissions", async () => { + const h = harness() + const id = await h.registered() + expect(await h.service.get(owner, id)).toMatchObject({ + registered: true, + published: false, + role: "responsible", + operator: false, + }) + await expect(h.service.get(outsider, id)).rejects.toMatchObject({ code: "NOT_FOUND" }) + expect((await h.service.list(outsider)).associations).toEqual([]) + }) + it("registers an operator-created association without making the operator a representative", async () => { + const h = harness() + const { id } = await h.service.create(staff, { + profile, + explanation: "Register", + submit: true, + commandId: randomUUID(), + }) + expect(await h.service.get(staff, id)).toMatchObject({ + registered: true, + members: [], + published: false, + unrepresented: true, + }) + }) + it("keeps the published version stable until a complete proposal is approved", async () => { + const h = harness() + const id = await h.registered() + await h.command(owner, id, { action: "save", requestId: null, profile, explanation: "First publication" }) + const q = h.rows.get(id)!.requests.at(-1)! + await h.command(owner, id, { action: "submit", requestId: q.id }) + await expect( + h.command(owner, id, { action: "review", requestId: q.id, decision: "approve", reason: "Self approval" }) + ).rejects.toMatchObject({ code: "FORBIDDEN" }) + await h.command(staff, id, { action: "review", requestId: q.id, decision: "approve", reason: "Approved" }) + await h.command(owner, id, { + action: "save", + requestId: null, + profile: { ...profile, name: "Unapproved name" }, + explanation: "Rename", + }) + expect((await h.service.get(owner, id)).publishedProfile?.name).toBe(profile.name) + const next = h.rows.get(id)!.requests.at(-1)! + await h.command(owner, id, { action: "submit", requestId: next.id }) + await h.command(staff, id, { action: "review", requestId: next.id, decision: "reject", reason: "Check the name" }) + expect((await h.service.get(owner, id)).publishedProfile?.name).toBe(profile.name) + }) + it("requires acceptance and approval of the exact account, with single-use expiring invitations", async () => { + const h = harness() + const id = await h.registered() + await h.command(owner, id, { + action: "invite", + role: "collaborator", + email: "other@example.org", + explanation: "New colleague", + }) + const q = h.rows.get(id)!.requests.at(-1)! + await expect( + h.command(staff, id, { action: "review", requestId: q.id, decision: "approve", reason: "Not yet accepted" }) + ).rejects.toMatchObject({ code: "BAD_REQUEST" }) + const token = h.mails.at(-1)!.text.match(/token=([\w-]+)/)![1] + expect(JSON.stringify(h.rows.get(id))).not.toContain(token) + await h.service.accept(outsider, token) + await expect(h.service.accept(owner, token)).rejects.toMatchObject({ code: "NOT_FOUND" }) + expect((await h.service.get(outsider, id)).role).toBeNull() + await h.command(staff, id, { action: "review", requestId: q.id, decision: "approve", reason: "Identity verified" }) + expect((await h.service.get(outsider, id)).role).toBe("collaborator") + await h.command(outsider, id, { action: "save", requestId: null, profile, explanation: "Edit" }) + await expect( + h.command(outsider, id, { action: "submit", requestId: h.rows.get(id)!.requests.at(-1)!.id }) + ).rejects.toMatchObject({ code: "FORBIDDEN" }) + await expect( + h.command(outsider, id, { + action: "invite", + role: "responsible", + email: "x@example.org", + explanation: "Escalate", + }) + ).rejects.toMatchObject({ code: "FORBIDDEN" }) + }) + it("rejects expired and withdrawn invitations", async () => { + const h = harness() + const id = await h.registered() + await h.command(owner, id, { + action: "invite", + email: "x@example.org", + role: "responsible", + explanation: "Successor", + }) + const token = h.mails.at(-1)!.text.match(/token=([\w-]+)/)![1] + h.rows.get(id)!.invitations[0].expiresAt = "2000-01-01T00:00:00Z" + await expect(h.service.accept(outsider, token)).rejects.toMatchObject({ code: "NOT_FOUND" }) + await h.command(owner, id, { action: "withdraw", requestId: h.rows.get(id)!.requests.at(-1)!.id }) + expect(h.rows.get(id)!.invitations).toEqual([]) + }) + it("hides internal notes and other applicants' evidence", async () => { + const h = harness() + const id = await h.registered() + await h.command(staff, id, { action: "note", note: "PRIVATE" }) + await h.command(outsider, id, { action: "access", explanation: "SECRET EVIDENCE" }) + const own = JSON.stringify(await h.service.get(owner, id)) + const other = JSON.stringify(await h.service.get(outsider, id)) + expect(own).not.toContain("SECRET EVIDENCE") + expect(own).not.toContain("PRIVATE") + expect(other).not.toContain("PRIVATE") + expect(JSON.parse(other).members).toEqual([]) + expect(JSON.stringify(await h.service.get(staff, id))).toContain("SECRET EVIDENCE") + }) + it("requires a replacement before demoting the last responsible but allows explicit departure/revocation", async () => { + const h = harness() + const id = await h.registered() + await h.command(owner, id, { + action: "membership", + sub: owner.sub, + role: "collaborator", + remove: false, + explanation: "Hand over", + }) + const requestId = h.rows.get(id)!.requests.at(-1)!.id + await expect( + h.command(staff, id, { action: "review", requestId, decision: "approve", reason: "Check" }) + ).rejects.toMatchObject({ code: "CONFLICT" }) + await h.command(staff, id, { action: "revoke", sub: owner.sub, reason: "Disputed representation" }) + expect((await h.service.get(staff, id)).unrepresented).toBe(true) + await expect( + h.command(owner, id, { action: "save", requestId: null, profile, explanation: "After revocation" }) + ).rejects.toMatchObject({ code: "FORBIDDEN" }) + }) + it("suspends writes and archives publication without erasing history", async () => { + const h = harness() + const id = await h.registered() + await h.command(staff, id, { action: "status", status: "suspended", hide: false, reason: "Check" }) + await expect( + h.command(owner, id, { action: "save", requestId: null, profile, explanation: "Edit" }) + ).rejects.toMatchObject({ code: "FORBIDDEN" }) + await h.command(staff, id, { action: "status", status: "archived", hide: true, reason: "Closed" }) + expect((await h.service.get(staff, id)).events.length).toBeGreaterThan(2) + expect(await h.service.directory()).toEqual([]) + }) + it("rejects stale writes and makes retried commands idempotent", async () => { + const h = harness() + const id = await h.registered() + const command = { + id, + revision: h.rows.get(id)!.revision, + commandId: randomUUID(), + action: "note" as const, + note: "A", + } + await h.service.command(staff, command) + await h.service.command(staff, command) + expect(h.rows.get(id)!.revision).toBe(command.revision + 1) + await expect(h.service.command(staff, { ...command, commandId: randomUUID(), note: "B" })).rejects.toMatchObject({ + code: "CONFLICT", + }) + }) + it("redirects duplicate registrations to a scoped access request without merging identities or granting roles", async () => { + const h = harness() + const destinationId = await h.registered() + const { id } = await h.service.create(outsider, { + profile, + explanation: "Duplicate application", + submit: true, + commandId: randomUUID(), + }) + await h.command(staff, id, { + action: "redirect", + requestId: h.rows.get(id)!.requests[0].id, + destinationId, + reason: "Already registered", + }) + expect((await h.service.get(outsider, id)).requests[0].redirectId).toBe(destinationId) + expect((await h.service.get(outsider, destinationId)).role).toBeNull() + expect((await h.service.get(outsider, destinationId)).requests[0].kind).toBe("access") + }) + it("validates safe links and bounded inputs", () => { + expect( + profileSchema.safeParse({ ...profile, links: [{ platform: "website", label: "X", url: "javascript:alert(1)" }] }) + .success + ).toBe(false) + expect( + commandSchema.safeParse({ + action: "review", + id: randomUUID(), + revision: 0, + commandId: randomUUID(), + requestId: randomUUID(), + decision: "approve", + reason: "", + }).success + ).toBe(false) + }) +}) From 3c35b087a81a95a5d3955a92346e099118637c80 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gabriele=20Vigan=C3=B2?= Date: Tue, 17 Nov 2026 15:50:22 +0100 Subject: [PATCH 2/5] fix(associations): harden review transitions and document rollout --- docs/associations/README.md | 25 ++++++++++++++++++++ src/associations/service.ts | 32 ++++++++++++++------------ tests/associations-postgres.fixture.ts | 20 ++++++++-------- tests/associations-preview.fixture.ts | 9 ++++++-- tests/associations.test.ts | 31 +++++++++++++++++++++++++ 5 files changed, 89 insertions(+), 28 deletions(-) create mode 100644 docs/associations/README.md diff --git a/docs/associations/README.md b/docs/associations/README.md new file mode 100644 index 0000000..cf95584 --- /dev/null +++ b/docs/associations/README.md @@ -0,0 +1,25 @@ +# Association registry API and release + +`associationPortal.*` is a user-only `backend:admin` API. Any authenticated user can apply; per-record membership is checked server-side on every mutation. Operators need both `admin:access` and `web:content:write`. No global permissions are granted to representatives. + +The registry separates association identity, active membership, review requests and the approved public profile. Registration and access approval do not publish content. Content approval atomically changes the published profile. Invitations are single-use, expire after 14 days and store only token hashes in registry state; accepting binds the actual account but requires operator approval. Notes and other applicants' evidence are filtered from scoped responses. Explicit withdrawal revokes invitation tokens. + +Migration `0040_association_portal.sql` backfills existing public associations with distinct UUIDs and preserves numeric catalog IDs, profiles and publication. All imported entries start without representatives. JSON state and its mail outbox are updated within PostgreSQL transactions; row locks serialize decisions, revisions detect stale edits, and per-account command keys support retries. Duplicate registrations can be redirected atomically to access requests on an existing association. No destructive record deletion is exposed. + +`web.associations.getAllAssociations` retains the existing public response and adds `extraLinks` for repeated platform links (including Twitch). It reads only published registry snapshots, never private working profiles, notes, membership or evidence. Legacy mutation procedures now return `PRECONDITION_FAILED`; callers must use the reviewed registry. + +## Deployment + +Coordinate the backend and admin PRs: migrate/deploy backend, then deploy admin. The old admin editor cannot write during the interval. The web PR can precede either because it supports responses without `extraLinks`. Use the normal migration procedure and database backup; these changes do not deploy or migrate production automatically. Rolling back just the application requires care: legacy public rows retain the last approved content even after a registry unpublish, so old readers could expose hidden entries. Restore the coordinated version, not an old reader in isolation. + +Keep `ESIGN_DASHBOARD_URL` at `https://admin.polinetwork.org` (shared existing dashboard setting), configure the existing mail transport and Azure Blob storage. The existing cron worker drains the durable outbox every minute; failed messages retry with capped backoff and a stable Message-ID. Sent invite URL bodies are scrubbed. Delivery is at least once. Invites are addressed to the supplied email; approval still targets the account that explicitly accepted. + +The admin's `docs/associations/README.md` describes the operator and representative workflow. No Auth repository changes are required: existing OIDC personal accounts and operator permissions are reused. + +## Verification + +Run `bun run check`, `bun run typecheck`, `bun run test`, `bun run build`. Unit/router tests cover scopes, account isolation, registration versus publication, invitation acceptance, revocation, last-responsible handling, duplicate redirection, revisions and idempotency. + +For integration, provide a disposable PostgreSQL server with user/password `seed_test` and `SEED_TEST_DB_PORT`, then run `bun run test tests/associations-postgres.test.ts`. The fixture creates and drops only its own random test database and checks backfill, stable IDs, concurrent create/review, persistence, publication and non-destructive unpublish. + +`tests/associations-preview.fixture.ts` is a local browser harness, not an application entrypoint: it trusts synthetic test identities and must never be deployed. Real login, email delivery and Blob upload require a staging smoke test with configured external services. diff --git a/src/associations/service.ts b/src/associations/service.ts index 95e83ce..725ccdc 100644 --- a/src/associations/service.ts +++ b/src/associations/service.ts @@ -142,9 +142,9 @@ export function createAssociationService(store: Store, dashboardUrl: string) { async create(v: Viewer, input: z.infer) { const q = request(v, "registration", input.explanation, input.profile) q.status = input.submit ? "submitted" : "draft" - q.targetSub = v.sub - q.targetName = v.name - q.accepted = true + q.targetSub = v.operator ? null : v.sub + q.targetName = v.operator ? null : v.name + q.accepted = !v.operator const r: Record = { id: randomUUID(), legacyId: null, @@ -209,8 +209,8 @@ export function createAssociationService(store: Store, dashboardUrl: string) { source.commands.push(key) source.revision++ destination.revision++ - event(source, v, "Registration redirected", c.reason) - event(destination, v, "Access request received from an existing application") + event(source, v, "Registration redirected", c.reason, q.id) + event(destination, v, "Access request received from an existing application", "", forwarded.id) return { id: destination.id } }) } @@ -246,15 +246,15 @@ export function createAssociationService(store: Store, dashboardUrl: string) { q.explanation = c.explanation q.updatedAt = new Date().toISOString() if (!r.registered) r.profile = c.profile - event(r, v, "Draft saved") + event(r, v, "Draft saved", "", q.id) } else if (c.action === "reply") { const q = r.requests.find((q) => q.id === c.requestId) - if (!q || q.by !== v.sub || q.status !== "changes") + if (!q || q.by !== v.sub || q.status !== "changes" || q.profile !== null) fail("FORBIDDEN", "Only the applicant can answer a request for information") q.explanation = c.explanation q.status = "submitted" q.updatedAt = new Date().toISOString() - event(r, v, "Requested information supplied") + event(r, v, "Requested information supplied", "", q.id) } else if (c.action === "submit" || c.action === "withdraw") { const q = r.requests.find((q) => q.id === c.requestId) if (!q) fail("NOT_FOUND", "Request not found") @@ -272,7 +272,7 @@ export function createAssociationService(store: Store, dashboardUrl: string) { r.invitations = r.invitations.filter((i) => i.requestId !== q.id) } q.updatedAt = new Date().toISOString() - event(r, v, c.action === "submit" ? "Request submitted" : "Request withdrawn") + event(r, v, c.action === "submit" ? "Request submitted" : "Request withdrawn", "", q.id) } else if (c.action === "access") { if (!r.registered || r.status !== "active" || activeMember(r, v)) fail("FORBIDDEN", "This association is not available for an access request") @@ -286,7 +286,7 @@ export function createAssociationService(store: Store, dashboardUrl: string) { q.targetName = v.name q.accepted = true r.requests.push(q) - event(r, v, "Access requested") + event(r, v, "Access requested", "", q.id) } else if (c.action === "invite" || c.action === "membership") { if (!responsible(r, v) || !r.registered) fail("FORBIDDEN", "Only a responsible can propose representatives") const q = request(v, "membership", c.explanation) @@ -322,7 +322,7 @@ export function createAssociationService(store: Store, dashboardUrl: string) { q.remove = c.remove } r.requests.push(q) - event(r, v, "Representative change requested") + event(r, v, "Representative change requested", "", q.id) } else if (c.action === "review") { operator(v) const q = r.requests.find((q) => q.id === c.requestId) @@ -336,7 +336,8 @@ export function createAssociationService(store: Store, dashboardUrl: string) { r.profile = q.profile r.published = q.profile } else { - if (!q.accepted || !q.targetSub) fail("BAD_REQUEST", "The invited person must accept before approval") + if (q.kind !== "registration" && (!q.accepted || !q.targetSub)) + fail("BAD_REQUEST", "The invited person must accept before approval") if (q.kind === "registration") { if (r.registered) fail("CONFLICT", "Already registered") r.registered = true @@ -351,10 +352,11 @@ export function createAssociationService(store: Store, dashboardUrl: string) { !r.members.some((m) => m.active && m.role === "responsible" && m.sub !== target.sub) ) fail("CONFLICT", "Approve a replacement responsible first; use explicit revocation for urgent removal") - if (target) { + if (q.targetSub && target) { target.role = q.role target.active = !q.remove - } else r.members.push({ sub: q.targetSub, name: q.targetName ?? q.targetSub, role: q.role, active: true }) + } else if (q.targetSub) + r.members.push({ sub: q.targetSub, name: q.targetName ?? q.targetSub, role: q.role, active: true }) } } q.status = c.decision === "approve" ? "approved" : c.decision === "changes" ? "changes" : "rejected" @@ -428,7 +430,7 @@ export function createAssociationService(store: Store, dashboardUrl: string) { q.updatedAt = new Date().toISOString() r.invitations = r.invitations.filter((candidate) => candidate !== i) r.revision++ - event(r, v, "Invitation accepted; awaiting PoliNetwork") + event(r, v, "Invitation accepted; awaiting PoliNetwork", "", q.id) return { id: r.id } }) }, diff --git a/tests/associations-postgres.fixture.ts b/tests/associations-postgres.fixture.ts index c0ce38f..9e9cf89 100644 --- a/tests/associations-postgres.fixture.ts +++ b/tests/associations-postgres.fixture.ts @@ -31,17 +31,15 @@ try { journal.entries = journal.entries.filter((e: { idx: number }) => e.idx < 40) await writeFile(journalPath, JSON.stringify(journal)) await migrate(db, { migrationsFolder: folder }) - await db - .insert(associations) - .values( - ["One", "Two"].map((name) => ({ - name, - descriptionIt: "Italiano", - descriptionEn: "English", - createdBySub: "legacy", - telegram: "https://t.me/test", - })) - ) + await db.insert(associations).values( + ["One", "Two"].map((name) => ({ + name, + descriptionIt: "Italiano", + descriptionEn: "English", + createdBySub: "legacy", + telegram: "https://t.me/test", + })) + ) await migrate(db, { migrationsFolder: "./drizzle" }) const store = createAssociationStore(db) const service = createAssociationService(store, "https://admin.example.org") diff --git a/tests/associations-preview.fixture.ts b/tests/associations-preview.fixture.ts index 0490247..dbc5dde 100644 --- a/tests/associations-preview.fixture.ts +++ b/tests/associations-preview.fixture.ts @@ -21,13 +21,18 @@ const router = createTRPCRouter({ }), regulations: createTRPCRouter({ me: createTRPCRouter({ - get: policy({ user: { scope: "backend:admin" } }).query(() => ({ assignedDrafts: 0, deleghe: 0 })), + get: policy({ user: { scope: "backend:admin" } }).query(() => ({ + assignedDrafts: 0, + deleghe: 0, + permissions: { read: false, write: false, manage: false, rectify: false }, + rectifiable: [], + })), }), }), }) Bun.serve({ - port: 15491, hostname: "127.0.0.1", + port: 15491, fetch(req) { return fetchRequestHandler({ endpoint: "/api/trpc", diff --git a/tests/associations.test.ts b/tests/associations.test.ts index 8123182..b586d75 100644 --- a/tests/associations.test.ts +++ b/tests/associations.test.ts @@ -181,6 +181,37 @@ describe("Association registry and scoped review", () => { expect((await h.service.get(outsider, destinationId)).role).toBeNull() expect((await h.service.get(outsider, destinationId)).requests[0].kind).toBe("access") }) + it("requires the submit workflow for profile integrations", async () => { + const h = harness() + const id = await h.registered() + await h.command(owner, id, { action: "save", requestId: null, profile, explanation: "Publish" }) + const q = (await h.service.get(owner, id)).requests.at(-1) + if (!q) throw new Error("Missing proposal") + await h.command(owner, id, { action: "submit", requestId: q.id }) + await h.command(staff, id, { action: "review", requestId: q.id, decision: "changes", reason: "Add details" }) + await expect( + h.command(owner, id, { action: "reply", requestId: q.id, explanation: "Bypass profile workflow" }) + ).rejects.toMatchObject({ code: "FORBIDDEN" }) + await h.command(owner, id, { action: "save", requestId: q.id, profile, explanation: "Details checked" }) + await h.command(owner, id, { action: "submit", requestId: q.id }) + expect((await h.service.get(owner, id)).requests.at(-1)?.status).toBe("submitted") + }) + it("does not make a staff draft author a representative on approval", async () => { + const h = harness() + const { id } = await h.service.create(staff, { + profile, + explanation: "Internal registry entry", + submit: false, + commandId: randomUUID(), + }) + const q = (await h.service.get(staff, id)).requests[0] + await h.command(staff, id, { action: "submit", requestId: q.id }) + await h.command(staff, id, { action: "review", requestId: q.id, decision: "approve", reason: "Checked" }) + const record = await h.service.get(staff, id) + expect(record.registered).toBe(true) + expect(record.members).toEqual([]) + expect(record.published).toBe(false) + }) it("validates safe links and bounded inputs", () => { expect( profileSchema.safeParse({ ...profile, links: [{ platform: "website", label: "X", url: "javascript:alert(1)" }] }) From 896c4003affee8c0fa77af0595ef7abf806f081e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gabriele=20Vigan=C3=B2?= Date: Tue, 17 Nov 2026 15:26:28 +0000 Subject: [PATCH 3/5] fix(associations): normalise legacy data and harden registry reads, outbox and limits - migration: keep only http(s) links/logos and valid emails, deterministic link order - public list: stable id order, resilient to odd stored values - store: indexed get/byInvitation/published instead of full scans, cap idempotency keys - identity directory cached with fallback; outbox leases rows, no tx during send, max attempts, retention - revoke/leave cancels pending approvals; accepted-account email recorded for review - registration cap counts only open applications; global access-request and logo-upload limits Co-Authored-By: Claude Sonnet 5.5 --- docs/associations/README.md | 4 +- drizzle/0040_association_portal.sql | 16 +++--- src/associations/contract.ts | 1 + src/associations/index.ts | 68 +++++++++++++++++++------- src/associations/router.ts | 10 ++++ src/associations/service.ts | 44 ++++++++++++++--- src/associations/store-pg.ts | 38 +++++++++++++- src/routers/web/associations.ts | 21 ++++---- tests/associations-fixture.ts | 8 +++ tests/associations-postgres.fixture.ts | 30 ++++++++++-- tests/associations.test.ts | 48 ++++++++++++++++++ 11 files changed, 239 insertions(+), 49 deletions(-) diff --git a/docs/associations/README.md b/docs/associations/README.md index cf95584..83984b3 100644 --- a/docs/associations/README.md +++ b/docs/associations/README.md @@ -10,9 +10,9 @@ Migration `0040_association_portal.sql` backfills existing public associations w ## Deployment -Coordinate the backend and admin PRs: migrate/deploy backend, then deploy admin. The old admin editor cannot write during the interval. The web PR can precede either because it supports responses without `extraLinks`. Use the normal migration procedure and database backup; these changes do not deploy or migrate production automatically. Rolling back just the application requires care: legacy public rows retain the last approved content even after a registry unpublish, so old readers could expose hidden entries. Restore the coordinated version, not an old reader in isolation. +Coordinate the backend and admin PRs: migrate/deploy backend, then deploy admin. The old admin editor cannot write during the interval. The web PR can precede either because it supports responses without `extraLinks`. Use the normal migration procedure and database backup; these changes do not deploy or migrate production automatically. The migration normalises legacy values to the registry contract (only http(s) links and logos, valid emails). Stop all old backend instances before migrating: writes they make to `web_associations` afterwards are not seen by the registry. Representative names and emails come from the IdP directory, cached for one minute with a fallback to the bare subject. Revoking or leaving cancels that account's pending requests. Rolling back just the application requires care: legacy public rows retain the last approved content even after a registry unpublish, so old readers could expose hidden entries. Restore the coordinated version, not an old reader in isolation. -Keep `ESIGN_DASHBOARD_URL` at `https://admin.polinetwork.org` (shared existing dashboard setting), configure the existing mail transport and Azure Blob storage. The existing cron worker drains the durable outbox every minute; failed messages retry with capped backoff and a stable Message-ID. Sent invite URL bodies are scrubbed. Delivery is at least once. Invites are addressed to the supplied email; approval still targets the account that explicitly accepted. +Keep `ESIGN_DASHBOARD_URL` at `https://admin.polinetwork.org` (shared existing dashboard setting), configure the existing mail transport and Azure Blob storage. The existing cron worker drains the durable outbox every minute; failed messages retry with capped backoff and a stable Message-ID. Sent invite URL bodies are scrubbed. Delivery is at least once: a row is leased briefly, sent outside any transaction, closed as undeliverable (text scrubbed) after 20 attempts, and purged 30 days after delivery. Invites are addressed to the supplied email; approval still targets the account that explicitly accepted. The admin's `docs/associations/README.md` describes the operator and representative workflow. No Auth repository changes are required: existing OIDC personal accounts and operator permissions are reused. diff --git a/drizzle/0040_association_portal.sql b/drizzle/0040_association_portal.sql index d43fb84..5d3d947 100644 --- a/drizzle/0040_association_portal.sql +++ b/drizzle/0040_association_portal.sql @@ -24,10 +24,14 @@ SELECT rid, jsonb_build_object( FROM web_associations a CROSS JOIN LATERAL (SELECT gen_random_uuid() AS rid WHERE a.id IS NOT NULL) ids CROSS JOIN LATERAL (SELECT jsonb_build_object( - 'name', a.name, 'acronym', '', 'descriptionIt', a.description_it, 'descriptionEn', a.description_en, - 'logo', a.logo, 'email', coalesce(a.email, ''), - 'links', coalesce((SELECT jsonb_agg(jsonb_build_object('platform', key, 'label', key, 'url', value)) - FROM jsonb_each_text(jsonb_build_object('website', a.website, 'facebook', a.facebook, 'instagram', a.instagram, - 'tiktok', a.tiktok, 'x', a.x, 'youtube', a.youtube, 'telegram', a.telegram, 'linkedin', a.linkedin, 'spotify', a.spotify)) - WHERE value IS NOT NULL AND value <> ''), '[]'::jsonb) + -- Legacy values are normalised to what the registry contract accepts: only http(s) links and logos, valid emails. + 'name', left(coalesce(nullif(btrim(a.name), ''), 'Association'), 200), 'acronym', '', + 'descriptionIt', left(a.description_it, 20000), 'descriptionEn', left(a.description_en, 20000), + 'logo', CASE WHEN a.logo ~* '^https?://[^[:space:]]+$' AND length(a.logo) <= 2048 THEN to_jsonb(a.logo) ELSE 'null'::jsonb END, + 'email', CASE WHEN a.email ~ '^[^@[:space:]]+@[^@[:space:]]+\.[^@[:space:]]+$' AND length(a.email) <= 320 THEN a.email ELSE '' END, + 'links', coalesce((SELECT jsonb_agg(jsonb_build_object('platform', v.k, 'label', v.k, 'url', v.u) ORDER BY v.ord) + FROM (VALUES (1, 'website', a.website), (2, 'facebook', a.facebook), (3, 'instagram', a.instagram), + (4, 'tiktok', a.tiktok), (5, 'x', a.x), (6, 'youtube', a.youtube), (7, 'telegram', a.telegram), + (8, 'linkedin', a.linkedin), (9, 'spotify', a.spotify)) AS v(ord, k, u) + WHERE v.u ~* '^https?://[^[:space:]]+$' AND length(v.u) <= 2048), '[]'::jsonb) ) AS profile) profiles; diff --git a/src/associations/contract.ts b/src/associations/contract.ts index ad5fa9c..d760fb1 100644 --- a/src/associations/contract.ts +++ b/src/associations/contract.ts @@ -47,6 +47,7 @@ export const requestSchema = z.object({ profile: profileSchema.nullable(), targetSub: z.string().nullable(), targetName: z.string().nullable(), + targetEmail: z.string().default(""), role: roleSchema, email: z.string(), remove: z.boolean(), diff --git a/src/associations/index.ts b/src/associations/index.ts index 99f84fe..66ab5d5 100644 --- a/src/associations/index.ts +++ b/src/associations/index.ts @@ -1,4 +1,4 @@ -import { and, eq, isNull, lte, sql } from "drizzle-orm" +import { and, eq, isNotNull, isNull, lte, sql } from "drizzle-orm" import { DB } from "@/db" import { associationMail } from "@/db/schema/web/association-portal" import { sendAssociationEmail } from "@/emails/mailer" @@ -11,41 +11,73 @@ import { createAssociationStore } from "./store-pg" export const associationStore = createAssociationStore(DB) export const associationPortal = createAssociationService(associationStore, env.ESIGN_DASHBOARD_URL.replace(/\/$/, "")) -/** Durable retries, SKIP LOCKED across replicas. Delivery is at-least-once, with a stable Message-ID. */ +const LEASE_MS = 5 * 60_000 +const MAX_ATTEMPTS = 20 +const RETENTION_MS = 30 * 86_400_000 + +/** + * Durable retries across replicas. A row is leased in a short transaction (nextAttempt pushed forward), then sent + * outside any transaction, so no connection or row lock is held during delivery. Delivery is at-least-once, with a + * stable Message-ID. Rows that keep failing are scrubbed and closed; delivered rows are purged after a retention period. + */ export async function deliverAssociationMail() { + await DB.delete(associationMail).where( + and(isNotNull(associationMail.sentAt), lte(associationMail.sentAt, new Date(Date.now() - RETENTION_MS))) + ) for (let n = 0; n < 20; n++) { - const done = await DB.transaction(async (tx) => { - const [row] = await tx + const row = await DB.transaction(async (tx) => { + const [claimed] = await tx .select() .from(associationMail) .where(and(isNull(associationMail.sentAt), lte(associationMail.nextAttempt, new Date()))) .limit(1) .for("update", { skipLocked: true }) - if (!row) return true - try { - await sendAssociationEmail(row.mail) - // Erase the invitation URL from the outbox after delivery; only the hash remains in the registry. + if (claimed) await tx .update(associationMail) - .set({ sentAt: new Date(), mail: { ...row.mail, text: "Delivered" } }) + .set({ nextAttempt: new Date(Date.now() + LEASE_MS) }) + .where(eq(associationMail.id, claimed.id)) + return claimed + }) + if (!row) break + try { + await sendAssociationEmail(row.mail) + // Erase the invitation URL from the outbox after delivery; only the hash remains in the registry. + await DB.update(associationMail) + .set({ sentAt: new Date(), mail: { ...row.mail, text: "Delivered" } }) + .where(eq(associationMail.id, row.id)) + } catch (error) { + logger.error({ error, mailId: row.id }, "Association notification delivery failed") + if (row.attempts + 1 >= MAX_ATTEMPTS) + await DB.update(associationMail) + .set({ sentAt: new Date(), attempts: row.attempts + 1, mail: { ...row.mail, text: "Undeliverable" } }) .where(eq(associationMail.id, row.id)) - } catch (error) { - logger.error({ error, mailId: row.id }, "Association notification delivery failed") - await tx - .update(associationMail) + else + await DB.update(associationMail) .set({ attempts: sql`${associationMail.attempts} + 1`, nextAttempt: new Date(Date.now() + Math.min(3600, 60 * 2 ** Math.min(row.attempts, 6)) * 1000), }) .where(eq(associationMail.id, row.id)) - } - return false - }) - if (done) break + } } } +const IDENTITY_TTL_MS = 60_000 +let directoryCache: { at: number; accounts: { sub: string; name?: string | null; email?: string | null }[] } | null = + null + export async function associationIdentity(sub: string) { - const account = (await idp?.directory?.())?.find((account) => account.sub === sub) + if (!idp?.directory) return { name: sub, email: undefined } + if (!directoryCache || Date.now() - directoryCache.at > IDENTITY_TTL_MS) { + try { + directoryCache = { at: Date.now(), accounts: await idp.directory() } + } catch (error) { + // A directory outage must not lock every representative out; fall back to stale data or the bare subject. + logger.warn({ error }, "Association identity directory unavailable") + directoryCache = directoryCache ? { ...directoryCache, at: Date.now() - IDENTITY_TTL_MS + 10_000 } : null + } + } + const account = directoryCache?.accounts.find((account) => account.sub === sub) return { name: account?.name ?? sub, email: account?.email ?? undefined } } diff --git a/src/associations/router.ts b/src/associations/router.ts index eb516c0..5f5c155 100644 --- a/src/associations/router.ts +++ b/src/associations/router.ts @@ -6,6 +6,15 @@ import { createTRPCRouter, policy } from "@/trpc" import * as C from "./contract" import type { createAssociationService } from "./service" +const uploads = new Map() +function limitUploads(sub: string) { + const now = Date.now() + const recent = (uploads.get(sub) ?? []).filter((t) => t > now - 3600_000) + if (recent.length >= 20) + throw new TRPCError({ code: "TOO_MANY_REQUESTS", message: "Too many logo uploads. Try later." }) + uploads.set(sub, [...recent, now]) +} + export function createAssociationRouter( service: ReturnType, identity: (sub: string) => Promise<{ name: string; email?: string }> = async (sub) => ({ name: sub }) @@ -52,6 +61,7 @@ export function createAssociationRouter( ) ) throw new TRPCError({ code: "FORBIDDEN" }) + limitUploads(ctx.viewer.sub) const bytes = Buffer.from(await input.file.arrayBuffer()) const png = bytes.subarray(0, 8).equals(Buffer.from([137, 80, 78, 71, 13, 10, 26, 10])) const jpeg = bytes[0] === 255 && bytes[1] === 216 && bytes[2] === 255 diff --git a/src/associations/service.ts b/src/associations/service.ts index 725ccdc..6ed5335 100644 --- a/src/associations/service.ts +++ b/src/associations/service.ts @@ -24,6 +24,10 @@ export type Record = { export type Mail = { id: string; to: string; subject: string; text: string } export type Store = { list(): Promise + get(id: string): Promise + byInvitation(hash: string): Promise + published(): Promise + recentAccessRequests(sub: string, since: string): Promise create(record: Record, commandId: string, actor: string): Promise transfer(from: string, to: string, operation: (source: Record, destination: Record) => T): Promise change(id: string, operation: (record: Record, mail: Mail[]) => T): Promise @@ -34,6 +38,7 @@ function fail( ): never { throw new TRPCError({ code, message }) } +const MAX_COMMAND_KEYS = 200 const hash = (token: string) => createHash("sha256").update(token).digest("hex") const activeMember = (r: Record, v: Viewer) => r.members.find((m) => m.sub === v.sub && m.active) const accessible = (r: Record, v: Viewer) => @@ -63,6 +68,7 @@ function request(v: Viewer, kind: Request["kind"], explanation: string, profile: profile, targetSub: null, targetName: null, + targetEmail: "", role: "responsible", email: v.email ?? "", remove: false, @@ -135,7 +141,7 @@ export function createAssociationService(store: Store, dashboardUrl: string) { .map((r) => ({ id: r.id, name: r.profile.name, revision: r.revision })) }, async get(v: Viewer, id: string) { - const r = (await store.list()).find((r) => r.id === id) + const r = await store.get(id) if (!r) return fail("NOT_FOUND", "Association not found") return present(r, v) }, @@ -214,6 +220,11 @@ export function createAssociationService(store: Store, dashboardUrl: string) { return { id: destination.id } }) } + if (c.action === "access" && !v.operator) { + const since = new Date(Date.now() - 86400000).toISOString() + if ((await store.recentAccessRequests(v.sub, since)) >= 20) + fail("TOO_MANY_REQUESTS", "Too many access requests today. Contact PoliNetwork.") + } return store.change(c.id, (r, mail) => { // Recheck authorization before idempotency: a former representative cannot reuse commands to read the record. if (c.action !== "access" && !accessible(r, v)) fail("NOT_FOUND", "Association not found") @@ -391,25 +402,37 @@ export function createAssociationService(store: Store, dashboardUrl: string) { const member = r.members.find((m) => m.sub === (c.action === "leave" ? v.sub : c.sub) && m.active) if (!member) fail("NOT_FOUND", "Active representative not found") member.active = false + // A pending approval must not silently bring a removed representative back. + for (const pending of r.requests) + if ( + pending.targetSub === member.sub && + (pending.kind === "membership" || pending.kind === "access") && + ["submitted", "changes"].includes(pending.status) + ) { + pending.status = "withdrawn" + pending.response = "Representative removed" + pending.updatedAt = new Date().toISOString() + r.invitations = r.invitations.filter((i) => i.requestId !== pending.id) + } event(r, v, c.action === "leave" ? "Representative left" : "Representative revoked", c.reason) } r.commands.push(commandKey) + // Retries only matter for a short window; keep the aggregate from growing without bound. + if (r.commands.length > MAX_COMMAND_KEYS) r.commands.splice(0, r.commands.length - MAX_COMMAND_KEYS) r.revision++ return { id: r.id } }) }, async invitation(token: string) { - const r = (await store.list()).find((r) => - r.invitations.some((i) => i.hash === hash(token) && i.expiresAt > new Date().toISOString()) - ) - const i = r?.invitations.find((i) => i.hash === hash(token)) + const r = await store.byInvitation(hash(token)) + const i = r?.invitations.find((i) => i.hash === hash(token) && i.expiresAt > new Date().toISOString()) const q = r?.requests.find((q) => q.id === i?.requestId) if (!r || !i || !q || !["submitted", "changes"].includes(q.status) || r.status !== "active") fail("NOT_FOUND", "Invitation expired or revoked") return { associationName: r.profile.name, role: q.role, expiresAt: i.expiresAt } }, async accept(v: Viewer, token: string) { - const r = (await store.list()).find((r) => r.invitations.some((i) => i.hash === hash(token))) + const r = await store.byInvitation(hash(token)) if (!r) fail("NOT_FOUND", "Invitation expired or revoked") return store.change(r.id, (r) => { const i = r.invitations.find((i) => i.hash === hash(token)) @@ -430,7 +453,14 @@ export function createAssociationService(store: Store, dashboardUrl: string) { q.updatedAt = new Date().toISOString() r.invitations = r.invitations.filter((candidate) => candidate !== i) r.revision++ - event(r, v, "Invitation accepted; awaiting PoliNetwork", "", q.id) + q.targetEmail = v.email ?? "" + event( + r, + v, + "Invitation accepted; awaiting PoliNetwork", + `Invited address: ${q.email}; accepting account: ${v.email ?? "unknown"}`, + q.id + ) return { id: r.id } }) }, diff --git a/src/associations/store-pg.ts b/src/associations/store-pg.ts index 1dec326..bb41356 100644 --- a/src/associations/store-pg.ts +++ b/src/associations/store-pg.ts @@ -8,7 +8,38 @@ import type { Mail, Record, Store } from "./service" export function createAssociationStore(db: typeof DB): Store { return { async list() { - return (await db.select().from(associationRegistry)).map((row) => row.state) + return (await db.select().from(associationRegistry).orderBy(associationRegistry.id)).map((row) => row.state) + }, + async get(id) { + const [row] = await db.select().from(associationRegistry).where(eq(associationRegistry.id, id)) + return row?.state ?? null + }, + async byInvitation(hash) { + const [row] = await db + .select() + .from(associationRegistry) + .where(sql`${associationRegistry.state}->'invitations' @> ${JSON.stringify([{ hash }])}::jsonb`) + return row?.state ?? null + }, + async published() { + const rows = await db + .select() + .from(associationRegistry) + .where( + sql`(${associationRegistry.state}->>'registered')::boolean AND jsonb_typeof(${associationRegistry.state}->'published') = 'object'` + ) + return rows.map((row) => row.state) + }, + async recentAccessRequests(sub, since) { + const [{ count }] = await db + .select({ count: sql`count(*)::int` }) + .from(associationRegistry) + .where( + sql`EXISTS (SELECT 1 FROM jsonb_array_elements(${associationRegistry.state}->'requests') q + WHERE q->>'by' = ${sub} AND q->>'kind' = 'access' AND q->>'createdAt' > ${since})` + ) + // Counts association records holding a recent request, a close lower bound of the requests themselves. + return count }, async create(state, commandId, actor) { const creationKey = `${actor}:${commandId}` @@ -20,11 +51,14 @@ export function createAssociationStore(db: typeof DB): Store { .from(associationRegistry) .where(eq(associationRegistry.creationKey, creationKey)) if (existing[0]) return existing[0].id + // Only open applications count: rejected, withdrawn and redirected ones must not lock a user out for good. const [{ count }] = await tx .select({ count: sql`count(*)::int` }) .from(associationRegistry) .where( - sql`${associationRegistry.state}->>'creator' = ${actor} AND (${associationRegistry.state}->>'registered')::boolean = false` + sql`${associationRegistry.state}->>'creator' = ${actor} AND (${associationRegistry.state}->>'registered')::boolean = false AND EXISTS ( + SELECT 1 FROM jsonb_array_elements(${associationRegistry.state}->'requests') q + WHERE q->>'kind' = 'registration' AND q->>'by' = ${actor} AND q->>'status' IN ('draft', 'submitted', 'changes'))` ) if (count >= 10) throw new TRPCError({ diff --git a/src/routers/web/associations.ts b/src/routers/web/associations.ts index b446dbf..c19aaa1 100644 --- a/src/routers/web/associations.ts +++ b/src/routers/web/associations.ts @@ -1,7 +1,7 @@ import { TRPCError } from "@trpc/server" import z from "zod" import { associationStore } from "@/associations" -import { linkSchema } from "@/associations/contract" +import { httpUrl, linkSchema } from "@/associations/contract" import { dashboard, publicData } from "@/idp/policies" import { createTRPCRouter, policy } from "@/trpc" @@ -32,20 +32,23 @@ export default createTRPCRouter({ getAllAssociations: policy(publicData) .output(z.array(associationSchema)) .query(async () => { - const records = await associationStore.list() + const records = await associationStore.published() return records - .filter((r) => r.registered && r.published && r.status !== "archived" && r.legacyId !== null) + .filter((r) => r.status !== "archived" && r.legacyId !== null) + .sort((a, b) => (a.legacyId ?? 0) - (b.legacyId ?? 0)) .map((r) => { - const p = r.published! - const first = (key: string) => p.links.find((l) => l.platform === key)?.url ?? null + const p = r.published as NonNullable + // Public output must never fail for the whole list because of one odd stored value. + const links = p.links.filter((l) => linkSchema.safeParse(l).success) + const first = (key: string) => links.find((l) => l.platform === key)?.url ?? null return { - id: r.legacyId!, + id: r.legacyId as number, name: p.name, descriptionIt: p.descriptionIt, descriptionEn: p.descriptionEn, - logo: p.logo, + logo: p.logo && httpUrl.safeParse(p.logo).success ? p.logo : null, links: { - email: p.email || null, + email: p.email && z.email().safeParse(p.email).success ? p.email : null, website: first("website"), facebook: first("facebook"), instagram: first("instagram"), @@ -56,7 +59,7 @@ export default createTRPCRouter({ linkedin: first("linkedin"), spotify: first("spotify"), }, - extraLinks: p.links, + extraLinks: links, } }) }), diff --git a/tests/associations-fixture.ts b/tests/associations-fixture.ts index 64ba797..89b4733 100644 --- a/tests/associations-fixture.ts +++ b/tests/associations-fixture.ts @@ -20,6 +20,14 @@ export function harness() { const mails: Mail[] = [] const store: Store = { list: async () => structuredClone([...rows.values()]), + get: async (id) => structuredClone(rows.get(id) ?? null), + byInvitation: async (hash) => + structuredClone([...rows.values()].find((r) => r.invitations.some((i) => i.hash === hash)) ?? null), + published: async () => structuredClone([...rows.values()].filter((r) => r.registered && r.published)), + recentAccessRequests: async (sub, since) => + [...rows.values()] + .flatMap((r) => r.requests) + .filter((q) => q.by === sub && q.kind === "access" && q.createdAt > since).length, async create(r, command, actor) { const key = `${actor}:${command}` if (creation.has(key)) return creation.get(key)! diff --git a/tests/associations-postgres.fixture.ts b/tests/associations-postgres.fixture.ts index 9e9cf89..0d8c03e 100644 --- a/tests/associations-postgres.fixture.ts +++ b/tests/associations-postgres.fixture.ts @@ -32,12 +32,21 @@ try { await writeFile(journalPath, JSON.stringify(journal)) await migrate(db, { migrationsFolder: folder }) await db.insert(associations).values( - ["One", "Two"].map((name) => ({ + ["One", "Two", "Messy"].map((name) => ({ name, descriptionIt: "Italiano", descriptionEn: "English", createdBySub: "legacy", telegram: "https://t.me/test", + ...(name === "Messy" + ? { + telegram: "t.me/foo", + website: "ftp://x.org", + email: "nope", + logo: "/relative.png", + facebook: "https://fb.com/x", + } + : {}), })) ) await migrate(db, { migrationsFolder: "./drizzle" }) @@ -46,8 +55,19 @@ try { const staff = { sub: "staff", name: "Staff", operator: true } const user = { sub: "new", name: "New", operator: false } const migrated = await store.list() - assert.equal(migrated.length, 2) - assert.equal(new Set(migrated.map((r) => r.id)).size, 2) + assert.equal(migrated.length, 3) + assert.equal(new Set(migrated.map((r) => r.id)).size, 3) + const messy = migrated.find((r) => r.profile.name === "Messy")! + assert.equal(messy.profile.logo, null) + assert.equal(messy.profile.email, "") + assert.deepEqual( + messy.profile.links.map((l) => l.url), + ["https://fb.com/x"] + ) + assert((await service.get(staff, messy.id)).profile.links.length === 1) + assert.deepEqual((await store.published()).map((r) => r.legacyId).sort(), [1, 2, 3]) + assert((await store.byInvitation("missing")) === null) + assert.equal(await store.recentAccessRequests("nobody", new Date(0).toISOString()), 0) assert(migrated.every((r) => r.published && r.members.length === 0 && r.legacyId)) const profile = { name: "New", @@ -107,7 +127,7 @@ try { decision: "approve", reason: "Approved", }) - assert.equal((await db.select().from(associations)).length, 3) + assert.equal((await db.select().from(associations)).length, 4) // A new service instance sees persisted publication, roles and history. const restarted = createAssociationService(createAssociationStore(db), "https://admin.example.org") const persisted = await restarted.get(user, a.id) @@ -121,7 +141,7 @@ try { reason: "Hide", }) assert.equal((await restarted.get(user, a.id)).published, false) - assert.equal((await db.select().from(associationRegistry)).length, 3) + assert.equal((await db.select().from(associationRegistry)).length, 4) console.log( JSON.stringify({ checked: [ diff --git a/tests/associations.test.ts b/tests/associations.test.ts index b586d75..259dbbb 100644 --- a/tests/associations.test.ts +++ b/tests/associations.test.ts @@ -229,4 +229,52 @@ describe("Association registry and scoped review", () => { }).success ).toBe(false) }) + it("records invited and accepting emails, and revocation cancels pending approvals for that account", async () => { + const h = harness() + const id = await h.registered() + const other = { ...outsider, email: "other@example.org" } + await h.command(owner, id, { + action: "invite", + role: "collaborator", + email: "invited@example.org", + explanation: "Colleague", + }) + const q = h.rows.get(id)!.requests.at(-1)! + await h.service.accept(other, h.mails.at(-1)!.text.match(/token=([\w-]+)/)![1]) + const stored = h.rows.get(id)! + expect(stored.requests.at(-1)!.targetEmail).toBe("other@example.org") + expect(stored.events.at(-1)!.detail).toContain("invited@example.org") + await h.command(staff, id, { action: "review", requestId: q.id, decision: "approve", reason: "ok" }) + await h.command(owner, id, { + action: "membership", + sub: other.sub, + role: "responsible", + remove: false, + explanation: "Promote", + }) + const pending = h.rows.get(id)!.requests.at(-1)! + await h.command(staff, id, { action: "revoke", sub: other.sub, reason: "Urgent" }) + expect(h.rows.get(id)!.requests.find((r) => r.id === pending.id)!.status).toBe("withdrawn") + await expect( + h.command(staff, id, { action: "review", requestId: pending.id, decision: "approve", reason: "stale" }) + ).rejects.toMatchObject({ code: "CONFLICT" }) + expect((await h.service.get(staff, id)).members.find((m) => m.sub === other.sub)!.active).toBe(false) + }) + it("limits access requests per account across associations and bounds stored command keys", async () => { + const h = harness() + const a = await h.registered() + for (let i = 0; i < 205; i++) await h.command(staff, a, { action: "note", note: String(i) }) + expect(h.rows.get(a)!.commands.length).toBeLessThanOrEqual(200) + const ids = [a] + for (let i = 0; i < 20; i++) ids.push(await h.registered()) + let failure: unknown + for (const id of ids) { + try { + await h.command(outsider, id, { action: "access", explanation: "please" }) + } catch (error) { + failure = error + } + } + expect(failure).toMatchObject({ code: "TOO_MANY_REQUESTS" }) + }) }) From 5c0ff7288792e1ab67b7f0f52405e3202c3a9b87 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gabriele=20Vigan=C3=B2?= Date: Tue, 17 Nov 2026 16:41:53 +0100 Subject: [PATCH 4/5] fix(associations): back off identity lookups during a directory outage Without a cached directory every portal call retried the IdP and could wait for its timeout. Cache the failure for 10 seconds instead. --- src/associations/index.ts | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/associations/index.ts b/src/associations/index.ts index 66ab5d5..d120bc4 100644 --- a/src/associations/index.ts +++ b/src/associations/index.ts @@ -75,7 +75,8 @@ export async function associationIdentity(sub: string) { } catch (error) { // A directory outage must not lock every representative out; fall back to stale data or the bare subject. logger.warn({ error }, "Association identity directory unavailable") - directoryCache = directoryCache ? { ...directoryCache, at: Date.now() - IDENTITY_TTL_MS + 10_000 } : null + // Retry in 10 seconds, not on every call: each failed lookup can wait for the IdP timeout. + directoryCache = { accounts: directoryCache?.accounts ?? [], at: Date.now() - IDENTITY_TTL_MS + 10_000 } } } const account = directoryCache?.accounts.find((account) => account.sub === sub) From 424aea0cc8318970a283ad2900d80e73024f221a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gabriele=20Vigan=C3=B2?= Date: Tue, 17 Nov 2026 19:56:12 +0100 Subject: [PATCH 5/5] fix(associations): write the accept and removal notes in Italian The invitation-accepted detail and the response on requests withdrawn by a removal are shown verbatim in the Italian portal. --- src/associations/service.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/associations/service.ts b/src/associations/service.ts index 6ed5335..2845e4b 100644 --- a/src/associations/service.ts +++ b/src/associations/service.ts @@ -410,7 +410,7 @@ export function createAssociationService(store: Store, dashboardUrl: string) { ["submitted", "changes"].includes(pending.status) ) { pending.status = "withdrawn" - pending.response = "Representative removed" + pending.response = "Referente rimosso" pending.updatedAt = new Date().toISOString() r.invitations = r.invitations.filter((i) => i.requestId !== pending.id) } @@ -458,7 +458,7 @@ export function createAssociationService(store: Store, dashboardUrl: string) { r, v, "Invitation accepted; awaiting PoliNetwork", - `Invited address: ${q.email}; accepting account: ${v.email ?? "unknown"}`, + `Indirizzo invitato: ${q.email}; account che ha accettato: ${v.email ?? "sconosciuto"}`, q.id ) return { id: r.id }