diff --git a/README.md b/README.md index 5b5ba03..d79c9d1 100644 --- a/README.md +++ b/README.md @@ -88,6 +88,28 @@ The backend checks every role change with the same rules as Auth (`src/people/ru role's permissions. A concept with no role bound in Auth, or with more than one, can't be assigned. Writes are serialized by one transaction lock. Grant `idp:people:roles` to the backend's OAuth client to let it change roles. +## Soci + +The `soci` router is the Libro Soci: one record per admission in `soci_members`, keyed on the Microsoft 365 account +(`entra_object_id`) and the member number, with the bookkeeping data the association must keep and an append-only +history in `soci_activity`. Records are never deleted, and a re-admission is a new record with a new number. +Microsoft 365 stays the source of truth for who is a socio now: a PoliNetwork account in the Soci group. The design is +the admin repository's `docs/people/soci.md`. + +- **Numbers are never reused.** `soci_numbers` keeps every number a record has held. A number is free only if no record + has ever held it and no Microsoft 365 user has it as `employeeId`. +- **One active record per codice fiscale.** Codes are validated (format, omocodia, check character) and checked + against the birth date. +- **Admitting** (`members.admit`) runs the Microsoft 365 workflow (account, `employeeId`, licences, Soci group, welcome + email to a typed address that isn't stored), then writes the record. A record that can't be written deletes the + account. +- **Registering** (`members.register`) writes a record for an account already in Soci, with its current number; personal + fields are optional. `members.unregistered` lists the Soci group's accounts without a record. +- `members.list` reports mismatches: an active record whose account isn't in Soci, or an ended one whose account is. + +Every procedure needs `admin:access` and `soci:read` (list, get, unregistered) or `soci:write` (admit, register, +update, setNumber). Writes share the in-process Microsoft 365 lock with `azure.members.*`. + ## E-signing with the CIE The `esign` router and `/esign/agent/*` endpoints let dashboard users sign PDFs with the Italian identity card diff --git a/drizzle/0033_soci_register.sql b/drizzle/0033_soci_register.sql new file mode 100644 index 0000000..867653a --- /dev/null +++ b/drizzle/0033_soci_register.sql @@ -0,0 +1,55 @@ +CREATE TABLE "soci_activity" ( + "id" integer PRIMARY KEY GENERATED ALWAYS AS IDENTITY (sequence name "soci_activity_id_seq" INCREMENT BY 1 MINVALUE 1 MAXVALUE 2147483647 START WITH 1 CACHE 1), + "member_id" integer NOT NULL, + "actor" text NOT NULL, + "text" text NOT NULL, + "at" timestamp with time zone NOT NULL +); +--> statement-breakpoint +CREATE TABLE "soci_members" ( + "id" integer PRIMARY KEY GENERATED ALWAYS AS IDENTITY (sequence name "soci_members_id_seq" INCREMENT BY 1 MINVALUE 1 MAXVALUE 2147483647 START WITH 1 CACHE 1), + "number" integer NOT NULL, + "entra_object_id" text NOT NULL, + "mailbox" text NOT NULL, + "display_name" text NOT NULL, + "first_name" text NOT NULL, + "last_name" text NOT NULL, + "alias" text, + "codice_fiscale" text, + "birth_date" date, + "birth_place" text, + "residence_street" text, + "residence_postal_code" text, + "residence_city" text, + "residence_province" text, + "residence_country" text, + "admitted_on" date NOT NULL, + "ended_on" date, + "end_reason" text, + "end_note" text, + "account_state" text DEFAULT 'active' NOT NULL, + "account_deleted_on" date, + "created_by" text NOT NULL, + "created_at" timestamp with time zone NOT NULL, + "updated_by" text NOT NULL, + "updated_at" timestamp with time zone NOT NULL, + CONSTRAINT "soci_members_number_unique" UNIQUE("number"), + CONSTRAINT "soci_members_entra_object_id_unique" UNIQUE("entra_object_id"), + CONSTRAINT "soci_members_end_check" CHECK (("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)), + CONSTRAINT "soci_members_end_reason_check" CHECK ("soci_members"."end_reason" in ('lapsed', 'resigned', 'expelled', 'deceased', 'other')), + CONSTRAINT "soci_members_account_state_check" CHECK ("soci_members"."account_state" in ('active', 'pending_deletion', 'deleted')), + CONSTRAINT "soci_members_account_deleted_check" CHECK (("soci_members"."account_state" = 'deleted') = ("soci_members"."account_deleted_on" is not null)), + CONSTRAINT "soci_members_number_check" CHECK ("soci_members"."number" > 0) +); +--> statement-breakpoint +CREATE TABLE "soci_numbers" ( + "number" integer PRIMARY KEY NOT NULL, + "member_id" integer NOT NULL, + "assigned_at" timestamp with time zone NOT NULL +); +--> statement-breakpoint +ALTER TABLE "soci_activity" ADD CONSTRAINT "soci_activity_member_id_soci_members_id_fk" FOREIGN KEY ("member_id") REFERENCES "public"."soci_members"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint +ALTER TABLE "soci_numbers" ADD CONSTRAINT "soci_numbers_member_id_soci_members_id_fk" FOREIGN KEY ("member_id") REFERENCES "public"."soci_members"("id") ON DELETE no action ON UPDATE no action;--> statement-breakpoint +CREATE INDEX "soci_activity_member_idx" ON "soci_activity" USING btree ("member_id","id");--> statement-breakpoint +CREATE UNIQUE INDEX "soci_members_active_codice_fiscale_idx" ON "soci_members" USING btree ("codice_fiscale") WHERE "soci_members"."ended_on" is null and "soci_members"."codice_fiscale" is not null;--> statement-breakpoint +CREATE INDEX "soci_numbers_member_idx" ON "soci_numbers" USING btree ("member_id"); \ No newline at end of file diff --git a/drizzle/meta/0033_snapshot.json b/drizzle/meta/0033_snapshot.json new file mode 100644 index 0000000..61776d7 --- /dev/null +++ b/drizzle/meta/0033_snapshot.json @@ -0,0 +1,3747 @@ +{ + "id": "02bd8f91-5f85-4fb8-adc2-7de85a0cf103", + "prevId": "e5e83f23-209c-4eb1-a909-bf427b65e42d", + "version": "7", + "dialect": "postgresql", + "tables": { + "public.common_group_labels": { + "name": "common_group_labels", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "common_group_labels_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "label": { + "name": "label", + "type": "varchar(128)", + "primaryKey": false, + "notNull": true + }, + "description": { + "name": "description", + "type": "varchar", + "primaryKey": false, + "notNull": false + }, + "color": { + "name": "color", + "type": "varchar(7)", + "primaryKey": false, + "notNull": true, + "default": "'#ffffff'" + }, + "legacy_created_by_tg_id": { + "name": "legacy_created_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "legacy_modified_by_tg_id": { + "name": "legacy_modified_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "created_by_sub": { + "name": "created_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "modified_by_sub": { + "name": "modified_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "common_group_labels_label_unique": { + "name": "common_group_labels_label_unique", + "nullsNotDistinct": false, + "columns": [ + "label" + ] + } + }, + "policies": {}, + "checkConstraints": { + "common_group_labels_creator_check": { + "name": "common_group_labels_creator_check", + "value": "\"common_group_labels\".\"legacy_created_by_tg_id\" IS NOT NULL OR \"common_group_labels\".\"created_by_sub\" IS NOT NULL" + } + }, + "isRLSEnabled": false + }, + "public.common_idp_state": { + "name": "common_idp_state", + "schema": "", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.esign_documents": { + "name": "esign_documents", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "request_id": { + "name": "request_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "file_name": { + "name": "file_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "content": { + "name": "content", + "type": "bytea", + "primaryKey": false, + "notNull": true + }, + "sha256": { + "name": "sha256", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "size": { + "name": "size", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "pages": { + "name": "pages", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "source": { + "name": "source", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "created_by_sub": { + "name": "created_by_sub", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "esign_documents_request_version_idx": { + "name": "esign_documents_request_version_idx", + "columns": [ + { + "expression": "request_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "version", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"esign_documents\".\"request_id\" IS NOT NULL", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "esign_documents_request_id_esign_requests_id_fk": { + "name": "esign_documents_request_id_esign_requests_id_fk", + "tableFrom": "esign_documents", + "tableTo": "esign_requests", + "columnsFrom": [ + "request_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.esign_drive_access": { + "name": "esign_drive_access", + "schema": "", + "columns": { + "drive_id": { + "name": "drive_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "request_roles": { + "name": "request_roles", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'::text[]" + }, + "request_permissions": { + "name": "request_permissions", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'::text[]" + }, + "sign_roles": { + "name": "sign_roles", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'::text[]" + }, + "sign_permissions": { + "name": "sign_permissions", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'::text[]" + }, + "updated_by_sub": { + "name": "updated_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.esign_events": { + "name": "esign_events", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "serial", + "primaryKey": true, + "notNull": true + }, + "request_id": { + "name": "request_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "at": { + "name": "at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + }, + "actor_sub": { + "name": "actor_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "data": { + "name": "data", + "type": "jsonb", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "esign_events_request_idx": { + "name": "esign_events_request_idx", + "columns": [ + { + "expression": "request_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "esign_events_request_id_esign_requests_id_fk": { + "name": "esign_events_request_id_esign_requests_id_fk", + "tableFrom": "esign_events", + "tableTo": "esign_requests", + "columnsFrom": [ + "request_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.esign_jobs": { + "name": "esign_jobs", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "ticket_hash": { + "name": "ticket_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "request_id": { + "name": "request_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "signer_id": { + "name": "signer_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "sub": { + "name": "sub", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "base_version": { + "name": "base_version", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "places": { + "name": "places", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "step": { + "name": "step", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": true + }, + "prepared": { + "name": "prepared", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "prepared_pdf": { + "name": "prepared_pdf", + "type": "bytea", + "primaryKey": false, + "notNull": false + }, + "error_code": { + "name": "error_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "error_message": { + "name": "error_message", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "seen_at": { + "name": "seen_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "esign_jobs_request_idx": { + "name": "esign_jobs_request_idx", + "columns": [ + { + "expression": "request_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "esign_jobs_request_id_esign_requests_id_fk": { + "name": "esign_jobs_request_id_esign_requests_id_fk", + "tableFrom": "esign_jobs", + "tableTo": "esign_requests", + "columnsFrom": [ + "request_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "esign_jobs_signer_id_esign_signers_id_fk": { + "name": "esign_jobs_signer_id_esign_signers_id_fk", + "tableFrom": "esign_jobs", + "tableTo": "esign_signers", + "columnsFrom": [ + "signer_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "esign_jobs_ticket_hash_unique": { + "name": "esign_jobs_ticket_hash_unique", + "nullsNotDistinct": false, + "columns": [ + "ticket_hash" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.esign_profiles": { + "name": "esign_profiles", + "schema": "", + "columns": { + "sub": { + "name": "sub", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "fiscal_code": { + "name": "fiscal_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "certificate_subject": { + "name": "certificate_subject", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.esign_requests": { + "name": "esign_requests", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'in_progress'" + }, + "ordered": { + "name": "ordered", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": true + }, + "output": { + "name": "output", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "email": { + "name": "email", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "delivery": { + "name": "delivery", + "type": "jsonb", + "primaryKey": false, + "notNull": false + }, + "drives": { + "name": "drives", + "type": "text[]", + "primaryKey": false, + "notNull": true, + "default": "'{}'::text[]" + }, + "created_by_sub": { + "name": "created_by_sub", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "completed_at": { + "name": "completed_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "cancelled_at": { + "name": "cancelled_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "esign_requests_status_idx": { + "name": "esign_requests_status_idx", + "columns": [ + { + "expression": "status", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "esign_requests_created_by_idx": { + "name": "esign_requests_created_by_idx", + "columns": [ + { + "expression": "created_by_sub", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.esign_signers": { + "name": "esign_signers", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true, + "default": "gen_random_uuid()" + }, + "request_id": { + "name": "request_id", + "type": "uuid", + "primaryKey": false, + "notNull": true + }, + "position": { + "name": "position", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "sub": { + "name": "sub", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "places": { + "name": "places", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "signatures_done": { + "name": "signatures_done", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'pending'" + }, + "signed_at": { + "name": "signed_at", + "type": "timestamp (3) with time zone", + "primaryKey": false, + "notNull": false + }, + "version": { + "name": "version", + "type": "integer", + "primaryKey": false, + "notNull": false + }, + "fiscal_code": { + "name": "fiscal_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "certificate_subject": { + "name": "certificate_subject", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "certificate_issuer": { + "name": "certificate_issuer", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "decline_reason": { + "name": "decline_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "esign_signers_request_idx": { + "name": "esign_signers_request_idx", + "columns": [ + { + "expression": "request_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "esign_signers_sub_idx": { + "name": "esign_signers_sub_idx", + "columns": [ + { + "expression": "sub", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "esign_signers_request_position_idx": { + "name": "esign_signers_request_position_idx", + "columns": [ + { + "expression": "request_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "position", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "esign_signers_request_id_esign_requests_id_fk": { + "name": "esign_signers_request_id_esign_requests_id_fk", + "tableFrom": "esign_signers", + "tableTo": "esign_requests", + "columnsFrom": [ + "request_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.people_activity": { + "name": "people_activity", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "people_activity_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "person_id": { + "name": "person_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "actor": { + "name": "actor", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "at": { + "name": "at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "people_activity_person_idx": { + "name": "people_activity_person_idx", + "columns": [ + { + "expression": "person_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "people_activity_person_id_people_persons_id_fk": { + "name": "people_activity_person_id_people_persons_id_fk", + "tableFrom": "people_activity", + "tableTo": "people_persons", + "columnsFrom": [ + "person_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.people_assignments": { + "name": "people_assignments", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "person_id": { + "name": "person_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "team": { + "name": "team", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "team_role": { + "name": "team_role", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "capo_scope": { + "name": "capo_scope", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "capo_of_reference_id": { + "name": "capo_of_reference_id", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "fields": { + "name": "fields", + "type": "jsonb", + "primaryKey": false, + "notNull": true, + "default": "'{}'::jsonb" + }, + "since": { + "name": "since", + "type": "date", + "primaryKey": false, + "notNull": true + }, + "ended_on": { + "name": "ended_on", + "type": "date", + "primaryKey": false, + "notNull": false + }, + "end_reason": { + "name": "end_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "assigned_by": { + "name": "assigned_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "change": { + "name": "change", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "refusal": { + "name": "refusal", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "command_id": { + "name": "command_id", + "type": "uuid", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "people_assignments_person_idx": { + "name": "people_assignments_person_idx", + "columns": [ + { + "expression": "person_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "people_assignments_current_idx": { + "name": "people_assignments_current_idx", + "columns": [ + { + "expression": "person_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "kind", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "coalesce(\"team\", '')", + "asc": true, + "isExpression": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"people_assignments\".\"ended_on\" is null", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "people_assignments_person_id_people_persons_id_fk": { + "name": "people_assignments_person_id_people_persons_id_fk", + "tableFrom": "people_assignments", + "tableTo": "people_persons", + "columnsFrom": [ + "person_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "people_assignments_capo_of_reference_id_people_persons_id_fk": { + "name": "people_assignments_capo_of_reference_id_people_persons_id_fk", + "tableFrom": "people_assignments", + "tableTo": "people_persons", + "columnsFrom": [ + "capo_of_reference_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + }, + "people_assignments_command_id_people_role_commands_id_fk": { + "name": "people_assignments_command_id_people_role_commands_id_fk", + "tableFrom": "people_assignments", + "tableTo": "people_role_commands", + "columnsFrom": [ + "command_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "people_assignments_kind_check": { + "name": "people_assignments_kind_check", + "value": "\"people_assignments\".\"kind\" in ('admin', 'capo', 'team')" + }, + "people_assignments_team_check": { + "name": "people_assignments_team_check", + "value": "(\"people_assignments\".\"kind\" = 'team') = (\"people_assignments\".\"team\" is not null and \"people_assignments\".\"team_role\" in ('member', 'lead'))" + }, + "people_assignments_capo_ref_check": { + "name": "people_assignments_capo_ref_check", + "value": "\"people_assignments\".\"kind\" = 'admin' or \"people_assignments\".\"capo_of_reference_id\" is null" + }, + "people_assignments_change_check": { + "name": "people_assignments_change_check", + "value": "\"people_assignments\".\"change\" in ('start', 'end')" + }, + "people_assignments_status_check": { + "name": "people_assignments_status_check", + "value": "\"people_assignments\".\"status\" in ('pending', 'sent', 'applied', 'refused')" + }, + "people_assignments_sent_check": { + "name": "people_assignments_sent_check", + "value": "(\"people_assignments\".\"status\" = 'sent') = (\"people_assignments\".\"command_id\" is not null)" + } + }, + "isRLSEnabled": false + }, + "public.people_counters": { + "name": "people_counters", + "schema": "", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "value": { + "name": "value", + "type": "bigint", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.people_invites": { + "name": "people_invites", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "person_id": { + "name": "person_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sent_by": { + "name": "sent_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "sent_at": { + "name": "sent_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "expires_at": { + "name": "expires_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "revoked_at": { + "name": "revoked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "accepted_at": { + "name": "accepted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "accepted_by": { + "name": "accepted_by", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "people_invites_person_idx": { + "name": "people_invites_person_idx", + "columns": [ + { + "expression": "person_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "people_invites_person_id_people_persons_id_fk": { + "name": "people_invites_person_id_people_persons_id_fk", + "tableFrom": "people_invites", + "tableTo": "people_persons", + "columnsFrom": [ + "person_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "people_invites_token_hash_unique": { + "name": "people_invites_token_hash_unique", + "nullsNotDistinct": false, + "columns": [ + "token_hash" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.people_mail": { + "name": "people_mail", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "person_id": { + "name": "person_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "to": { + "name": "to", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "subject": { + "name": "subject", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "attempted_at": { + "name": "attempted_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": { + "people_mail_person_id_people_persons_id_fk": { + "name": "people_mail_person_id_people_persons_id_fk", + "tableFrom": "people_mail", + "tableTo": "people_persons", + "columnsFrom": [ + "person_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.people_persons": { + "name": "people_persons", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "first_name": { + "name": "first_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "last_name": { + "name": "last_name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "contact_email": { + "name": "contact_email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "phone": { + "name": "phone", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "telegram_username": { + "name": "telegram_username", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "account_sub": { + "name": "account_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "linked_at": { + "name": "linked_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + }, + "linked_by": { + "name": "linked_by", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "link_method": { + "name": "link_method", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "updated_by": { + "name": "updated_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "people_persons_account_sub_unique": { + "name": "people_persons_account_sub_unique", + "nullsNotDistinct": false, + "columns": [ + "account_sub" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.people_role_commands": { + "name": "people_role_commands", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "uuid", + "primaryKey": true, + "notNull": true + }, + "person_id": { + "name": "person_id", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "request": { + "name": "request", + "type": "jsonb", + "primaryKey": false, + "notNull": true + }, + "purpose": { + "name": "purpose", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'roles'" + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "attempts": { + "name": "attempts", + "type": "integer", + "primaryKey": false, + "notNull": true, + "default": 0 + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "answered_at": { + "name": "answered_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": false + } + }, + "indexes": { + "people_role_commands_queued_idx": { + "name": "people_role_commands_queued_idx", + "columns": [ + { + "expression": "created_at", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "where": "\"people_role_commands\".\"status\" = 'queued'", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "people_role_commands_person_id_people_persons_id_fk": { + "name": "people_role_commands_person_id_people_persons_id_fk", + "tableFrom": "people_role_commands", + "tableTo": "people_persons", + "columnsFrom": [ + "person_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "people_role_commands_status_check": { + "name": "people_role_commands_status_check", + "value": "\"people_role_commands\".\"status\" in ('queued', 'applied', 'refused')" + }, + "people_role_commands_purpose_check": { + "name": "people_role_commands_purpose_check", + "value": "\"people_role_commands\".\"purpose\" in ('roles', 'unlink')" + } + }, + "isRLSEnabled": false + }, + "public.soci_activity": { + "name": "soci_activity", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "soci_activity_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "member_id": { + "name": "member_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "actor": { + "name": "actor", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "text": { + "name": "text", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "at": { + "name": "at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "soci_activity_member_idx": { + "name": "soci_activity_member_idx", + "columns": [ + { + "expression": "member_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "soci_activity_member_id_soci_members_id_fk": { + "name": "soci_activity_member_id_soci_members_id_fk", + "tableFrom": "soci_activity", + "tableTo": "soci_members", + "columnsFrom": [ + "member_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.soci_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_street": { + "name": "residence_street", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "residence_postal_code": { + "name": "residence_postal_code", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "residence_city": { + "name": "residence_city", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "residence_province": { + "name": "residence_province", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "residence_country": { + "name": "residence_country", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "admitted_on": { + "name": "admitted_on", + "type": "date", + "primaryKey": false, + "notNull": true + }, + "ended_on": { + "name": "ended_on", + "type": "date", + "primaryKey": false, + "notNull": false + }, + "end_reason": { + "name": "end_reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "end_note": { + "name": "end_note", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "account_state": { + "name": "account_state", + "type": "text", + "primaryKey": false, + "notNull": true, + "default": "'active'" + }, + "account_deleted_on": { + "name": "account_deleted_on", + "type": "date", + "primaryKey": false, + "notNull": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + }, + "updated_by": { + "name": "updated_by", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "soci_members_active_codice_fiscale_idx": { + "name": "soci_members_active_codice_fiscale_idx", + "columns": [ + { + "expression": "codice_fiscale", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "where": "\"soci_members\".\"ended_on\" is null and \"soci_members\".\"codice_fiscale\" is not null", + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "soci_members_number_unique": { + "name": "soci_members_number_unique", + "nullsNotDistinct": false, + "columns": [ + "number" + ] + }, + "soci_members_entra_object_id_unique": { + "name": "soci_members_entra_object_id_unique", + "nullsNotDistinct": false, + "columns": [ + "entra_object_id" + ] + } + }, + "policies": {}, + "checkConstraints": { + "soci_members_end_check": { + "name": "soci_members_end_check", + "value": "(\"soci_members\".\"ended_on\" is null) = (\"soci_members\".\"end_reason\" is null) and (\"soci_members\".\"ended_on\" is not null or \"soci_members\".\"end_note\" is null)" + }, + "soci_members_end_reason_check": { + "name": "soci_members_end_reason_check", + "value": "\"soci_members\".\"end_reason\" in ('lapsed', 'resigned', 'expelled', 'deceased', 'other')" + }, + "soci_members_account_state_check": { + "name": "soci_members_account_state_check", + "value": "\"soci_members\".\"account_state\" in ('active', 'pending_deletion', 'deleted')" + }, + "soci_members_account_deleted_check": { + "name": "soci_members_account_deleted_check", + "value": "(\"soci_members\".\"account_state\" = 'deleted') = (\"soci_members\".\"account_deleted_on\" is not null)" + }, + "soci_members_number_check": { + "name": "soci_members_number_check", + "value": "\"soci_members\".\"number\" > 0" + } + }, + "isRLSEnabled": false + }, + "public.soci_numbers": { + "name": "soci_numbers", + "schema": "", + "columns": { + "number": { + "name": "number", + "type": "integer", + "primaryKey": true, + "notNull": true + }, + "member_id": { + "name": "member_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "assigned_at": { + "name": "assigned_at", + "type": "timestamp with time zone", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "soci_numbers_member_idx": { + "name": "soci_numbers_member_idx", + "columns": [ + { + "expression": "member_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": { + "soci_numbers_member_id_soci_members_id_fk": { + "name": "soci_numbers_member_id_soci_members_id_fk", + "tableFrom": "soci_numbers", + "tableTo": "soci_members", + "columnsFrom": [ + "member_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.tg_audit_log": { + "name": "tg_audit_log", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "tg_audit_log_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "target_id": { + "name": "target_id", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "group_id": { + "name": "group_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "type": { + "name": "type", + "type": "varchar(32)", + "primaryKey": false, + "notNull": true + }, + "until": { + "name": "until", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "reason": { + "name": "reason", + "type": "varchar(256)", + "primaryKey": false, + "notNull": false + }, + "actor_sub": { + "name": "actor_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "actor_tg_id": { + "name": "actor_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "client": { + "name": "client", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "basis": { + "name": "basis", + "type": "varchar(32)", + "primaryKey": false, + "notNull": true, + "default": "'legacy'" + }, + "review": { + "name": "review", + "type": "varchar(32)", + "primaryKey": false, + "notNull": false + }, + "idempotency_key": { + "name": "idempotency_key", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "auditlog_actor_tg_id_idx": { + "name": "auditlog_actor_tg_id_idx", + "columns": [ + { + "expression": "actor_tg_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + }, + "auditlog_idempotency_key_idx": { + "name": "auditlog_idempotency_key_idx", + "columns": [ + { + "expression": "idempotency_key", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": true, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.tg_grants": { + "name": "tg_grants", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "tg_grants_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "telegram_user_id": { + "name": "telegram_user_id", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "valid_since": { + "name": "valid_since", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true + }, + "valid_until": { + "name": "valid_until", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "granted_by_sub": { + "name": "granted_by_sub", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "granted_via_client": { + "name": "granted_via_client", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "interrupted_at": { + "name": "interrupted_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "interrupted_by_sub": { + "name": "interrupted_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "interrupted_by_tg_id": { + "name": "interrupted_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "tg_grants_telegram_user_id_idx": { + "name": "tg_grants_telegram_user_id_idx", + "columns": [ + { + "expression": "telegram_user_id", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "tg_grants_validity_check": { + "name": "tg_grants_validity_check", + "value": "\"tg_grants\".\"valid_since\" < \"tg_grants\".\"valid_until\"" + } + }, + "isRLSEnabled": false + }, + "public.tg_groups": { + "name": "tg_groups", + "schema": "", + "columns": { + "telegram_id": { + "name": "telegram_id", + "type": "bigint", + "primaryKey": true, + "notNull": true + }, + "title": { + "name": "title", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "tag": { + "name": "tag", + "type": "varchar", + "primaryKey": false, + "notNull": false + }, + "link": { + "name": "link", + "type": "varchar(128)", + "primaryKey": false, + "notNull": false + }, + "hide": { + "name": "hide", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "tg_groups_link_unique": { + "name": "tg_groups_link_unique", + "nullsNotDistinct": false, + "columns": [ + "link" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.tg_group_label_relations": { + "name": "tg_group_label_relations", + "schema": "", + "columns": { + "group_id": { + "name": "group_id", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "label_id": { + "name": "label_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "tg_group_label_relations_group_id_tg_groups_telegram_id_fk": { + "name": "tg_group_label_relations_group_id_tg_groups_telegram_id_fk", + "tableFrom": "tg_group_label_relations", + "tableTo": "tg_groups", + "columnsFrom": [ + "group_id" + ], + "columnsTo": [ + "telegram_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "tg_group_label_relations_label_id_common_group_labels_id_fk": { + "name": "tg_group_label_relations_label_id_common_group_labels_id_fk", + "tableFrom": "tg_group_label_relations", + "tableTo": "common_group_labels", + "columnsFrom": [ + "label_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "tg_group_label_relations_group_id_label_id_pk": { + "name": "tg_group_label_relations_group_id_label_id_pk", + "columns": [ + "group_id", + "label_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.tg_messages": { + "name": "tg_messages", + "schema": "", + "columns": { + "chat_id": { + "name": "chat_id", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "message_id": { + "name": "message_id", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "author_id": { + "name": "author_id", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "timestamp": { + "name": "timestamp", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true + }, + "message": { + "name": "message", + "type": "varchar(8704)", + "primaryKey": false, + "notNull": true + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": { + "tg_messages_chat_author_timestamp_idx": { + "name": "tg_messages_chat_author_timestamp_idx", + "columns": [ + { + "expression": "chat_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "author_id", + "isExpression": false, + "asc": true, + "nulls": "last" + }, + { + "expression": "timestamp", + "isExpression": false, + "asc": false, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": { + "tg_messages_chat_id_message_id_pk": { + "name": "tg_messages_chat_id_message_id_pk", + "columns": [ + "chat_id", + "message_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.tg_test": { + "name": "tg_test", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "tg_test_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "text": { + "name": "text", + "type": "varchar", + "primaryKey": false, + "notNull": true + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.tg_users": { + "name": "tg_users", + "schema": "", + "columns": { + "user_id": { + "name": "user_id", + "type": "bigint", + "primaryKey": true, + "notNull": true + }, + "first_name": { + "name": "first_name", + "type": "varchar(512)", + "primaryKey": false, + "notNull": true + }, + "last_name": { + "name": "last_name", + "type": "varchar(512)", + "primaryKey": false, + "notNull": false + }, + "username": { + "name": "username", + "type": "varchar(128)", + "primaryKey": false, + "notNull": false + }, + "is_bot": { + "name": "is_bot", + "type": "boolean", + "primaryKey": false, + "notNull": true + }, + "lang_code": { + "name": "lang_code", + "type": "varchar(35)", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.wa_group_label_relations": { + "name": "wa_group_label_relations", + "schema": "", + "columns": { + "group_id": { + "name": "group_id", + "type": "bigint", + "primaryKey": false, + "notNull": true + }, + "label_id": { + "name": "label_id", + "type": "integer", + "primaryKey": false, + "notNull": true + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": { + "wa_group_label_relations_group_id_wa_groups_group_id_fk": { + "name": "wa_group_label_relations_group_id_wa_groups_group_id_fk", + "tableFrom": "wa_group_label_relations", + "tableTo": "wa_groups", + "columnsFrom": [ + "group_id" + ], + "columnsTo": [ + "group_id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + }, + "wa_group_label_relations_label_id_common_group_labels_id_fk": { + "name": "wa_group_label_relations_label_id_common_group_labels_id_fk", + "tableFrom": "wa_group_label_relations", + "tableTo": "common_group_labels", + "columnsFrom": [ + "label_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "no action", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": { + "wa_group_label_relations_group_id_label_id_pk": { + "name": "wa_group_label_relations_group_id_label_id_pk", + "columns": [ + "group_id", + "label_id" + ] + } + }, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.wa_groups": { + "name": "wa_groups", + "schema": "", + "columns": { + "group_id": { + "name": "group_id", + "type": "bigint", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "wa_groups_group_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "9223372036854775807", + "cache": "1", + "cycle": false + } + }, + "title": { + "name": "title", + "type": "varchar", + "primaryKey": false, + "notNull": true + }, + "link": { + "name": "link", + "type": "varchar(128)", + "primaryKey": false, + "notNull": false + }, + "hide": { + "name": "hide", + "type": "boolean", + "primaryKey": false, + "notNull": true, + "default": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "wa_groups_link_unique": { + "name": "wa_groups_link_unique", + "nullsNotDistinct": false, + "columns": [ + "link" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.web_associations": { + "name": "web_associations", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "identity": { + "type": "always", + "name": "web_associations_id_seq", + "schema": "public", + "increment": "1", + "startWith": "1", + "minValue": "1", + "maxValue": "2147483647", + "cache": "1", + "cycle": false + } + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description_it": { + "name": "description_it", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "description_en": { + "name": "description_en", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "logo": { + "name": "logo", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "website": { + "name": "website", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "facebook": { + "name": "facebook", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "instagram": { + "name": "instagram", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "tiktok": { + "name": "tiktok", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "x": { + "name": "x", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "youtube": { + "name": "youtube", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "telegram": { + "name": "telegram", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "linkedin": { + "name": "linkedin", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "spotify": { + "name": "spotify", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "legacy_created_by_tg_id": { + "name": "legacy_created_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "legacy_modified_by_tg_id": { + "name": "legacy_modified_by_tg_id", + "type": "bigint", + "primaryKey": false, + "notNull": false + }, + "created_by_sub": { + "name": "created_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "modified_by_sub": { + "name": "modified_by_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "updated_at": { + "name": "updated_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": false + }, + "created_at": { + "name": "created_at", + "type": "timestamp (0) with time zone", + "primaryKey": false, + "notNull": true, + "default": "now()" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "policies": {}, + "checkConstraints": { + "web_associations_creator_check": { + "name": "web_associations_creator_check", + "value": "\"web_associations\".\"legacy_created_by_tg_id\" IS NOT NULL OR \"web_associations\".\"created_by_sub\" IS NOT NULL" + } + }, + "isRLSEnabled": false + }, + "public.web_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 1fba67f..9b402a2 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -232,6 +232,13 @@ "when": 1793377749431, "tag": "0032_people_linking", "breakpoints": true + }, + { + "idx": 33, + "version": "7", + "when": 1794230950342, + "tag": "0033_soci_register", + "breakpoints": true } ] } \ No newline at end of file diff --git a/src/azure/directory.ts b/src/azure/directory.ts index 046b3c9..1d932ac 100644 --- a/src/azure/directory.ts +++ b/src/azure/directory.ts @@ -2,11 +2,15 @@ import { logger } from "@/logger" import { azureCredentials } from "./config" import { getAllGroups } from "./functions/groups" import { + addToSoci, createMember, + deleteUser, findByMail, findByMemberNumber, getMember, getMembers, + getSociMembers, + removeFromSoci, setMemberNumber, } from "./functions/members" import { createMockAzureDirectory } from "./mock-directory" @@ -20,6 +24,10 @@ const graphAzureDirectory: AzureDirectory = { setMemberNumber, createMember, getAllGroups, + getSociMembers, + addToSoci, + removeFromSoci, + deleteUser, } export const azureDirectory: AzureDirectory = azureCredentials ? graphAzureDirectory : createMockAzureDirectory() diff --git a/src/azure/functions/members.ts b/src/azure/functions/members.ts index 57dd98f..1834c2a 100644 --- a/src/azure/functions/members.ts +++ b/src/azure/functions/members.ts @@ -4,7 +4,7 @@ import { withRetry } from "@/utils/wait" import { getAzureClient } from "../client" import { IncompleteMemberError, safeErrorDetail } from "../errors" import { MAIL_DOMAIN } from "../mailbox" -import type { CreatedMember, CreateMemberInput, MemberSummary, ParsedUser, User } from "../types" +import type { CreatedMember, CreateMemberInput, MemberSummary, ParsedUser, SociGroupMember, User } from "../types" const GruppoSociID = "1c68dbb8-4ac3-4569-a886-283b5a825cbd" const Licenses = { @@ -159,13 +159,7 @@ export async function createMember({ await manageLicenses(id, ["OFFICE_365", "POWER_AUTOMATE"], []) } catch (error) { try { - await withRetry(async () => { - try { - await client.api(`/users/${id}`).delete() - } catch (cleanupError) { - if ((cleanupError as { statusCode?: number }).statusCode !== 404) throw cleanupError - } - }) + await deleteUser(id) } catch (cleanupError) { logger.error({ error: safeErrorDetail(cleanupError), memberId: id }, "[AZURE] incomplete account cleanup failed") throw new IncompleteMemberError( @@ -185,6 +179,65 @@ export async function createMember({ } } +const statusOf = (error: unknown) => (error as { statusCode?: number }).statusCode + +export async function getSociMembers(): Promise { + const client = getAzureClient() + const users = await allPages & { id: string }>( + client, + await client + .api(`/groups/${GruppoSociID}/members/microsoft.graph.user`) + .select([...SUMMARY_FIELDS, "surname", "createdDateTime"]) + .top(999) + .get() + ) + return users.map((user) => ({ + ...toSummary(user), + surname: user.surname ?? null, + createdDateTime: user.createdDateTime ?? null, + })) +} + +export async function addToSoci(userId: string) { + const client = getAzureClient() + await withRetry(async () => { + try { + await client.api(`/groups/${GruppoSociID}/members/$ref`).post({ + "@odata.id": `https://graph.microsoft.com/v1.0/directoryObjects/${encodeURIComponent(userId)}`, + }) + } catch (error) { + // Graph refuses to add a member twice. + if (statusOf(error) === 400 && /already exist/i.test((error as Error).message ?? "")) return + throw error + } + }) + logger.info({ userId }, "[Azure Graph API] added to Soci") +} + +export async function removeFromSoci(userId: string) { + const client = getAzureClient() + await withRetry(async () => { + try { + await client.api(`/groups/${GruppoSociID}/members/${encodeURIComponent(userId)}/$ref`).delete() + } catch (error) { + if (statusOf(error) !== 404) throw error + } + }) + logger.info({ userId }, "[Azure Graph API] removed from Soci") +} + +export async function deleteUser(userId: string) { + const client = getAzureClient() + await withRetry(async () => { + try { + await client.api(`/users/${encodeURIComponent(userId)}`).delete() + } catch (error) { + if (statusOf(error) !== 404) throw error + } + }) + logger.info({ userId }, "[Azure Graph API] user deleted") +} + export async function changePassword(userId: string) { const client = getAzureClient() const password = generatePassword() diff --git a/src/azure/mock-directory.ts b/src/azure/mock-directory.ts index cdd39d6..f091387 100644 --- a/src/azure/mock-directory.ts +++ b/src/azure/mock-directory.ts @@ -3,9 +3,11 @@ import { generatePassword } from "@/utils/password" import { MAIL_DOMAIN } from "./mailbox" import type { AzureDirectory, MemberSummary, ParsedGroup, ParsedUser } from "./types" +type MockUser = ParsedUser & { createdDateTime: string } + const ASSOCIATION_GROUP_ID = "mock-group-association-members" -const SEEDED_MEMBERS: ParsedUser[] = [ +const SEEDED_MEMBERS: MockUser[] = [ { id: "mock-member-ada", displayName: "Ada Lovelace", @@ -15,6 +17,7 @@ const SEEDED_MEMBERS: ParsedUser[] = [ employeeId: "1001", isMember: true, assignedLicensesIds: ["OFFICE_365", "POWER_AUTOMATE"], + createdDateTime: "2024-10-02T09:00:00Z", }, { id: "mock-member-alan", @@ -25,6 +28,7 @@ const SEEDED_MEMBERS: ParsedUser[] = [ employeeId: "1002", isMember: true, assignedLicensesIds: ["OFFICE_365"], + createdDateTime: "2025-03-14T15:30:00Z", }, { id: "mock-member-grace", @@ -35,6 +39,7 @@ const SEEDED_MEMBERS: ParsedUser[] = [ employeeId: null, isMember: false, assignedLicensesIds: [], + createdDateTime: "2025-09-01T08:00:00Z", }, ] @@ -62,10 +67,14 @@ const SEEDED_GROUPS: ParsedGroup[] = [ }, ] -function cloneMembers(members: ParsedUser[]): ParsedUser[] { +function cloneMembers(members: MockUser[]): MockUser[] { return members.map((member) => ({ ...member, assignedLicensesIds: [...member.assignedLicensesIds] })) } +function parsed({ createdDateTime: _, ...member }: MockUser): ParsedUser { + return { ...member, assignedLicensesIds: [...member.assignedLicensesIds] } +} + function summary({ id, displayName, givenName, mail, employeeId }: ParsedUser): MemberSummary { return { id, displayName, givenName, mail, employeeId } } @@ -77,10 +86,11 @@ function cloneGroups(groups: ParsedGroup[]): ParsedGroup[] { export function createMockAzureDirectory(): AzureDirectory { const members = cloneMembers(SEEDED_MEMBERS) const groups = cloneGroups(SEEDED_GROUPS) + const sociGroup = () => groups.find((group) => group.id === ASSOCIATION_GROUP_ID) as ParsedGroup return { async getMembers() { - return cloneMembers(members) + return members.map(parsed) }, async getMember(userId) { @@ -123,8 +133,9 @@ export function createMockAzureDirectory(): AzureDirectory { employeeId: assocNumber.toString(), isMember: true, assignedLicensesIds: ["OFFICE_365", "POWER_AUTOMATE"], + createdDateTime: new Date().toISOString(), }) - groups.find((group) => group.id === ASSOCIATION_GROUP_ID)?.members.push({ id, displayName }) + sociGroup().members.push({ id, displayName }) return { firstName, lastName, id, mail, password: generatePassword() } }, @@ -132,5 +143,32 @@ export function createMockAzureDirectory(): AzureDirectory { async getAllGroups() { return cloneGroups(groups) }, + + async getSociMembers() { + return members + .filter((member) => member.isMember) + .map((member) => ({ ...summary(member), surname: member.surname, createdDateTime: member.createdDateTime })) + }, + + async addToSoci(userId) { + const member = members.find((candidate) => candidate.id === userId) + if (!member) throw new Error(`Azure member ${userId} was not found in the local directory`) + if (member.isMember) return + member.isMember = true + sociGroup().members.push({ id: member.id, displayName: member.displayName ?? "" }) + }, + + async removeFromSoci(userId) { + const member = members.find((candidate) => candidate.id === userId) + if (member) member.isMember = false + const group = sociGroup() + group.members = group.members.filter((candidate) => candidate.id !== userId) + }, + + async deleteUser(userId) { + const index = members.findIndex((candidate) => candidate.id === userId) + if (index >= 0) members.splice(index, 1) + for (const group of groups) group.members = group.members.filter((candidate) => candidate.id !== userId) + }, } } diff --git a/src/azure/types.ts b/src/azure/types.ts index 3e53196..d33a5f6 100644 --- a/src/azure/types.ts +++ b/src/azure/types.ts @@ -54,6 +54,13 @@ export type CreateMemberInput = { /** The directory fields the member number workflow reads. */ export type MemberSummary = Pick +/** A user in the Soci group. */ +export type SociGroupMember = MemberSummary & { + surname: string | null + /** ISO timestamp of the account's creation. */ + createdDateTime: string | null +} + export type CreatedMember = { firstName: string lastName: string @@ -73,4 +80,12 @@ export type AzureDirectory = { setMemberNumber(userId: string, assocNumber: number): Promise<{ error: string | null }> createMember(input: CreateMemberInput): Promise getAllGroups(): Promise + /** The users in the Soci group. */ + getSociMembers(): Promise + /** Adds an existing user to the Soci group; a user already in it is left as is. */ + addToSoci(userId: string): Promise + /** Removes a user from the Soci group; a user not in it is left as is. */ + removeFromSoci(userId: string): Promise + /** Deletes a user, which releases their licences; a user already gone counts as deleted. */ + deleteUser(userId: string): Promise } diff --git a/src/db/schema/create-table.ts b/src/db/schema/create-table.ts index 260a87c..dc6bd87 100644 --- a/src/db/schema/create-table.ts +++ b/src/db/schema/create-table.ts @@ -4,6 +4,7 @@ export const createTable = { people: pgTableCreator((tableName) => `people_${tableName}`), common: pgTableCreator((tableName) => `common_${tableName}`), esign: pgTableCreator((tableName) => `esign_${tableName}`), + soci: pgTableCreator((tableName) => `soci_${tableName}`), tg: pgTableCreator((tableName) => `tg_${tableName}`), wa: pgTableCreator((tableName) => `wa_${tableName}`), web: pgTableCreator((tableName) => `web_${tableName}`), diff --git a/src/db/schema/index.ts b/src/db/schema/index.ts index 9d2d7e2..48773d5 100644 --- a/src/db/schema/index.ts +++ b/src/db/schema/index.ts @@ -1,6 +1,7 @@ import { schema as commonSchema } from "./common" import { schema as esignSchema } from "./esign" import { schema as peopleSchema } from "./people" +import { schema as sociSchema } from "./soci" import { schema as tgSchema } from "./tg" import { views } from "./views" import { schema as waSchema } from "./wa" @@ -10,6 +11,7 @@ export const schema = { ...commonSchema, ...esignSchema, ...peopleSchema, + ...sociSchema, ...tgSchema, ...waSchema, ...webSchema, diff --git a/src/db/schema/soci/index.ts b/src/db/schema/soci/index.ts new file mode 100644 index 0000000..30428e0 --- /dev/null +++ b/src/db/schema/soci/index.ts @@ -0,0 +1,97 @@ +import { sql } from "drizzle-orm" +import { check, date, index, integer, text, timestamp, uniqueIndex } from "drizzle-orm/pg-core" +import type { ACCOUNT_STATES, END_REASONS } from "@/soci/contract" +import { createTable } from "../create-table" + +const at = (name: string) => timestamp(name, { withTimezone: true, mode: "date" }) + +/** The Libro Soci: one row per admission, never deleted. A re-admission is a new row with a new number. */ +export const members = createTable.soci( + "members", + { + id: integer().primaryKey().generatedAlwaysAsIdentity(), + number: integer().notNull().unique(), + entraObjectId: text("entra_object_id").notNull().unique(), + /** Snapshots of the account, kept after it is deleted. */ + mailbox: text().notNull(), + displayName: text("display_name").notNull(), + firstName: text("first_name").notNull(), + lastName: text("last_name").notNull(), + alias: text(), + codiceFiscale: text("codice_fiscale"), + birthDate: date("birth_date", { mode: "string" }), + birthPlace: text("birth_place"), + residenceStreet: text("residence_street"), + residencePostalCode: text("residence_postal_code"), + residenceCity: text("residence_city"), + /** Only in Italy. */ + residenceProvince: text("residence_province"), + /** ISO 3166-1 alpha-2. */ + residenceCountry: text("residence_country"), + admittedOn: date("admitted_on", { mode: "string" }).notNull(), + endedOn: date("ended_on", { mode: "string" }), + endReason: text("end_reason").$type<(typeof END_REASONS)[number]>(), + endNote: text("end_note"), + accountState: text("account_state").$type<(typeof ACCOUNT_STATES)[number]>().notNull().default("active"), + accountDeletedOn: date("account_deleted_on", { mode: "string" }), + createdBy: text("created_by").notNull(), + createdAt: at("created_at").notNull(), + updatedBy: text("updated_by").notNull(), + updatedAt: at("updated_at").notNull(), + }, + (t) => [ + // At most one active record per person. + uniqueIndex("soci_members_active_codice_fiscale_idx") + .on(t.codiceFiscale) + .where(sql`${t.endedOn} is null and ${t.codiceFiscale} is not null`), + check( + "soci_members_end_check", + sql`(${t.endedOn} is null) = (${t.endReason} is null) and (${t.endedOn} is not null or ${t.endNote} is null)` + ), + check( + "soci_members_end_reason_check", + sql`${t.endReason} in ('lapsed', 'resigned', 'expelled', 'deceased', 'other')` + ), + check("soci_members_account_state_check", sql`${t.accountState} in ('active', 'pending_deletion', 'deleted')`), + check( + "soci_members_account_deleted_check", + sql`(${t.accountState} = 'deleted') = (${t.accountDeletedOn} is not null)` + ), + check("soci_members_number_check", sql`${t.number} > 0`), + ] +) + +/** Every member number a record has ever held: a number is never given to another record. */ +export const numbers = createTable.soci( + "numbers", + { + number: integer().primaryKey(), + memberId: integer("member_id") + .notNull() + .references(() => members.id), + assignedAt: at("assigned_at").notNull(), + }, + (t) => [index("soci_numbers_member_idx").on(t.memberId)] +) + +/** Append-only history of each record. */ +export const activity = createTable.soci( + "activity", + { + /** Also orders entries written in the same instant. */ + id: integer().primaryKey().generatedAlwaysAsIdentity(), + memberId: integer("member_id") + .notNull() + .references(() => members.id), + actor: text().notNull(), + text: text().notNull(), + at: at("at").notNull(), + }, + (t) => [index("soci_activity_member_idx").on(t.memberId, t.id)] +) + +export const schema = { + sociMembers: members, + sociNumbers: numbers, + sociActivity: activity, +} diff --git a/src/index.ts b/src/index.ts index 2dc356c..b6603bd 100644 --- a/src/index.ts +++ b/src/index.ts @@ -14,4 +14,19 @@ export type { TeamSummary as PeopleTeamSummary, } from "./people/contract" export type { AppRouter } from "./routers" +export type { + AdmitInput as SociAdmitInput, + AdmitResult as SociAdmitResult, + RegisterInput as SociRegisterInput, + Residence as SociResidence, + SetNumberInput as SociSetNumberInput, + SetNumberResult as SociSetNumberResult, + SociList, + SocioActivity, + SocioDetails, + SocioRecord, + SocioRow, + Unregistered as SociUnregistered, + UpdateInput as SociUpdateInput, +} from "./soci/contract" export type { TelegramSocket } from "./websocket/telegram" diff --git a/src/routers/index.ts b/src/routers/index.ts index 0be4c27..9ee7762 100644 --- a/src/routers/index.ts +++ b/src/routers/index.ts @@ -4,6 +4,7 @@ import { esignRouter } from "./esign" import { groupsRouter } from "./groups" import { meRouter } from "./me" import { peopleRouter } from "./people" +import { sociRouter } from "./soci" import { tgRouter } from "./tg" import { waRouter } from "./wa" import { webRouter } from "./web" @@ -19,6 +20,7 @@ export const appRouter = createTRPCRouter({ groups: groupsRouter, me: meRouter, people: peopleRouter, + soci: sociRouter, tg: tgRouter, wa: waRouter, web: webRouter, diff --git a/src/routers/soci.ts b/src/routers/soci.ts new file mode 100644 index 0000000..f52beac --- /dev/null +++ b/src/routers/soci.ts @@ -0,0 +1,4 @@ +import { soci } from "@/soci" +import { createSociRouter } from "@/soci/router" + +export const sociRouter = createSociRouter(soci) diff --git a/src/soci/codice-fiscale.ts b/src/soci/codice-fiscale.ts new file mode 100644 index 0000000..af483a8 --- /dev/null +++ b/src/soci/codice-fiscale.ts @@ -0,0 +1,78 @@ +/** + * The Italian codice fiscale of a natural person: format, omocodia and check character. + * + * Sixteen characters: three letters each from the surname and the name, the birth year, a month letter, the birth + * day (plus 40 for women), the Belfiore code of the birthplace, and the check character. When two people would get + * the same code (omocodia), the Agenzia delle Entrate replaces digits from the right with letters (`LMNPQRSTUV` for + * 0–9), so those seven positions may hold either. + */ + +const OMOCODIA = "LMNPQRSTUV" +const MONTHS = "ABCDEHLMPRST" +/** Positions that hold a digit, or its omocodia letter. */ +const NUMERIC = [6, 7, 9, 10, 12, 13, 14] +const FORMAT = /^[A-Z]{6}[0-9LMNPQRSTUV]{2}[ABCDEHLMPRST][0-9LMNPQRSTUV]{2}[A-Z][0-9LMNPQRSTUV]{3}[A-Z]$/ + +/** What a character in an odd position (1st, 3rd, …) adds to the check sum. */ +const ODD: Record = Object.fromEntries( + [1, 0, 5, 7, 9, 13, 15, 17, 19, 21, 2, 4, 18, 20, 11, 3, 6, 8, 12, 14, 16, 10, 22, 25, 24, 23].flatMap((value, i) => [ + [String.fromCharCode(65 + i), value], + ...(i < 10 ? [[String(i), value]] : []), + ]) +) +const even = (char: string) => (char >= "0" && char <= "9" ? Number(char) : char.charCodeAt(0) - 65) + +/** Upper case, without spaces: how the code is compared and stored. */ +export function normalizeCodiceFiscale(value: string) { + return value.replace(/\s+/g, "").toUpperCase() +} + +/** The check character the first fifteen characters call for. */ +export function checkCharacter(first15: string) { + let sum = 0 + for (let i = 0; i < 15; i++) sum += i % 2 === 0 ? (ODD[first15[i]] ?? 0) : even(first15[i]) + return String.fromCharCode(65 + (sum % 26)) +} + +/** The code with every omocodia letter turned back into its digit. */ +function withDigits(code: string) { + const chars = code.split("") + for (const i of NUMERIC) { + const digit = OMOCODIA.indexOf(chars[i]) + if (digit >= 0) chars[i] = String(digit) + } + return chars.join("") +} + +export type CodiceFiscaleProblem = "format" | "check" | "date" + +/** Why the code is not valid, or null. Expects a normalized code. */ +export function codiceFiscaleProblem(code: string): CodiceFiscaleProblem | null { + if (!FORMAT.test(code)) return "format" + if (checkCharacter(code.slice(0, 15)) !== code[15]) return "check" + const birth = encodedBirth(code) + if (!birth) return "date" + return null +} + +/** The birth data a valid code encodes: the year only to two digits. Null when the day can't exist. */ +export function encodedBirth(code: string): { yy: number; month: number; day: number; female: boolean } | null { + const plain = withDigits(code) + const yy = Number(plain.slice(6, 8)) + const month = MONTHS.indexOf(plain[8]) + 1 + const rawDay = Number(plain.slice(9, 11)) + const female = rawDay > 40 + const day = female ? rawDay - 40 : rawDay + // 29 February is allowed here: the year isn't known to the century. + const days = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31][month - 1] + if (day < 1 || day > days) return null + return { yy, month, day, female } +} + +/** Whether a valid code agrees with a birth date (`YYYY-MM-DD`). */ +export function matchesBirthDate(code: string, birthDate: string) { + const birth = encodedBirth(code) + if (!birth) return false + const [year, month, day] = birthDate.split("-").map(Number) + return birth.yy === year % 100 && birth.month === month && birth.day === day +} diff --git a/src/soci/contract.ts b/src/soci/contract.ts new file mode 100644 index 0000000..5edd0ba --- /dev/null +++ b/src/soci/contract.ts @@ -0,0 +1,262 @@ +import { z } from "zod" +import { mailboxSchema } from "@/azure/mailbox" +import { codiceFiscaleProblem, matchesBirthDate, normalizeCodiceFiscale } from "./codice-fiscale" + +/** + * Wire contract of the admin dashboard's Soci area (PoliNetworkOrg/admin): the Libro Soci, one record per admission. + * The admin parses responses against these shapes. Keep input/output changes coordinated with that repository. + */ + +/** How a socio's status ended. `lapsed` is set only by the automatic lapse. */ +export const END_REASONS = ["lapsed", "resigned", "expelled", "deceased", "other"] as const +/** The Microsoft 365 account behind the record. */ +export const ACCOUNT_STATES = ["active", "pending_deletion", "deleted"] as const + +export const memberNumberSchema = z.number().int().positive().max(999_999) + +const CODICE_FISCALE_MESSAGES = { + format: "Not a codice fiscale: 16 letters and digits in the official pattern.", + check: "The codice fiscale's last character doesn't match: check it for typos.", + date: "The codice fiscale encodes a birth date that doesn't exist.", +} as const + +/** Upper-cased and without spaces; format, omocodia and check character validated. */ +export const codiceFiscaleSchema = z + .string() + .transform(normalizeCodiceFiscale) + .superRefine((code, ctx) => { + const problem = codiceFiscaleProblem(code) + if (problem) ctx.addIssue({ code: "custom", message: CODICE_FISCALE_MESSAGES[problem] }) + }) + +const dateSchema = z.iso.date() +const text = (max: number) => z.string().trim().min(1).max(max) +/** A name as written on an identity document. */ +const legalName = text(80) +/** ISO 3166-1 alpha-2, e.g. `IT`. */ +const countrySchema = z + .string() + .trim() + .toUpperCase() + .regex(/^[A-Z]{2}$/, "A two-letter country code, e.g. IT") +/** The two-letter sigla of an Italian province, e.g. `MI`. */ +const provinceSchema = z + .string() + .trim() + .toUpperCase() + .regex(/^[A-Z]{2}$/, "The province's two-letter code, e.g. MI") + +export const residenceSchema = z.object({ + /** Street and number. */ + street: z.string().nullable(), + postalCode: z.string().nullable(), + city: z.string().nullable(), + /** Only in Italy. */ + province: z.string().nullable(), + country: z.string().nullable(), +}) +export type Residence = z.infer + +/** The bookkeeping data the association keeps. Nullable fields may be missing for a socio registered afterwards. */ +const bookkeepingFields = { + firstName: z.string(), + lastName: z.string(), + /** The name the person goes by, shown with the legal name. */ + alias: z.string().nullable(), + codiceFiscale: z.string().nullable(), + birthDate: z.string().nullable(), + /** The comune, or the city and country. */ + birthPlace: z.string().nullable(), + residence: residenceSchema, +} + +/** One row of the register. */ +export const socioRowSchema = z.object({ + number: z.number(), + entraObjectId: z.string(), + /** Snapshots taken at admission or registration, kept after the account is deleted. */ + mailbox: z.string(), + displayName: z.string(), + firstName: z.string(), + lastName: z.string(), + alias: z.string().nullable(), + /** To warn when a new admission belongs to a former socio. */ + codiceFiscale: z.string().nullable(), + admittedOn: z.string(), + /** `null` while the socio is active. */ + endedOn: z.string().nullable(), + endReason: z.enum(END_REASONS).nullable(), + accountState: z.enum(ACCOUNT_STATES), + /** Whether the account is in the Soci group now; `null` when Microsoft 365 couldn't be read. */ + inSoci: z.boolean().nullable(), + /** + * Where the record and Soci membership disagree: an active record whose account isn't in Soci, or an ended one + * whose account still is. `null` when they agree, or when Microsoft 365 couldn't be read. + */ + mismatch: z.enum(["not_in_soci", "still_in_soci"]).nullable(), +}) +export type SocioRow = z.infer + +export const sociListSchema = z.object({ + members: z.array(socioRowSchema), + /** False when Microsoft 365 couldn't be read: `inSoci` and `mismatch` are then unknown. */ + directoryAvailable: z.boolean(), +}) +export type SociList = z.infer + +export const activitySchema = z.object({ actor: z.string(), text: z.string(), at: z.string() }) +export type SocioActivity = z.infer + +export const socioRecordSchema = socioRowSchema.extend({ + ...bookkeepingFields, + endNote: z.string().nullable(), + accountDeletedOn: z.string().nullable(), + /** The account's current member number in Microsoft 365; `null` when it has none, or couldn't be read. */ + accountNumber: z.string().nullable(), + /** Newest first. */ + activity: z.array(activitySchema), + createdBy: z.string(), + createdAt: z.string(), + updatedBy: z.string(), + updatedAt: z.string(), +}) +export type SocioRecord = z.infer + +/** A member of the Soci group in Microsoft 365 without a record. */ +export const unregisteredSchema = z.object({ + entraObjectId: z.string(), + displayName: z.string().nullable(), + givenName: z.string().nullable(), + surname: z.string().nullable(), + mail: z.string().nullable(), + /** The member number Microsoft 365 holds, if any. */ + employeeId: z.string().nullable(), + /** When the account was created: the suggested admission date. */ + createdDateTime: z.string().nullable(), +}) +export type Unregistered = z.infer + +// Inputs. + +const blankToNull = (value: string | null | undefined) => (value === undefined || value === "" ? null : value) +const optional = >(schema: T) => + z + .union([z.literal(""), schema]) + .nullish() + .transform(blankToNull) + +const residenceInput = (required: R) => { + const field = (schema: z.ZodType) => (required ? schema : optional(schema)) + return z + .object({ + street: field(text(200)), + postalCode: field(text(16)), + city: field(text(120)), + province: optional(provinceSchema), + country: field(countrySchema), + }) + .superRefine((r, ctx) => { + const italy = r.country === "IT" + if (italy && r.postalCode && !/^\d{5}$/.test(r.postalCode)) + ctx.addIssue({ code: "custom", path: ["postalCode"], message: "An Italian postal code has five digits." }) + if (!italy && r.province) + ctx.addIssue({ code: "custom", path: ["province"], message: "The province is only for Italy." }) + if (required && italy && !r.province) + ctx.addIssue({ code: "custom", path: ["province"], message: "Choose the province." }) + }) +} + +function detailsInput(required: R) { + const field = (schema: z.ZodType) => (required ? schema : optional(schema)) + return z + .object({ + firstName: legalName, + lastName: legalName, + alias: optional(text(80)), + codiceFiscale: required ? codiceFiscaleSchema : optional(codiceFiscaleSchema), + birthDate: field(dateSchema), + birthPlace: field(text(120)), + residence: required + ? residenceInput(true) + : residenceInput(false).prefault({ street: null, postalCode: null, city: null, country: null }), + }) + .superRefine((d, ctx) => { + if (d.codiceFiscale && d.birthDate && !matchesBirthDate(d.codiceFiscale, d.birthDate)) + ctx.addIssue({ + code: "custom", + path: ["birthDate"], + message: "The birth date doesn't match the codice fiscale.", + }) + }) +} + +/** Everything required but the alias: for admitting a new socio. */ +export const requiredDetailsSchema = detailsInput(true) +/** Only the legal name required: for a socio registered afterwards, and for edits. Empty strings mean unknown. */ +export const optionalDetailsSchema = detailsInput(false) +export type SocioDetails = z.output + +// Becomes the Entra display name and mail nickname. +const accountName = z + .string() + .trim() + .min(1) + .max(64) + .regex(/^[\p{L}\p{M}' -]+$/u, "Only letters, spaces, apostrophes and hyphens") + +export const admitInputSchema = z.object({ + /** The Microsoft 365 account to create, as in today's form. */ + account: z.object({ + firstName: accountName, + lastName: accountName, + mailbox: mailboxSchema.default({ kind: "standard" }), + /** Where the credentials go. Not stored. */ + sendEmailTo: z.email(), + }), + number: memberNumberSchema, + details: requiredDetailsSchema, + admittedOn: dateSchema, +}) +export type AdmitInput = z.output + +export const registerInputSchema = z.object({ + /** An account already in the Soci group, without a record. */ + entraObjectId: z.string().min(1).max(128), + /** + * Required only when the account has no member number in Microsoft 365, which then gets this one. Otherwise it + * may be left out, and must match the account's. + */ + number: memberNumberSchema.optional(), + details: optionalDetailsSchema, + admittedOn: dateSchema, +}) +export type RegisterInput = z.output + +export const numberInputSchema = z.object({ number: memberNumberSchema }) +export type NumberInput = z.output + +export const updateInputSchema = z.object({ + number: memberNumberSchema, + details: optionalDetailsSchema, + admittedOn: dateSchema, +}) +export type UpdateInput = z.output + +export const setNumberInputSchema = z.object({ + number: memberNumberSchema, + newNumber: memberNumberSchema, + /** Emails the new number there, as Microsoft 365 › Members did. */ + notifyEmail: z.email().optional(), +}) +export type SetNumberInput = z.output + +export const admitResultSchema = z.object({ + number: z.number(), + entraObjectId: z.string(), + mailbox: z.string(), + welcomeMailSent: z.boolean(), +}) +export type AdmitResult = z.infer + +export const setNumberResultSchema = z.object({ number: z.number(), notificationSent: z.boolean().nullable() }) +export type SetNumberResult = z.infer diff --git a/src/soci/index.ts b/src/soci/index.ts new file mode 100644 index 0000000..a68e3d8 --- /dev/null +++ b/src/soci/index.ts @@ -0,0 +1,15 @@ +import { azureDirectory } from "@/azure/directory" +import { currentMember, numberHolder, rememberNumber, serializeMemberWrite } from "@/azure/member-writes" +import { DB } from "@/db" +import { sendMemberNumberChangedEmail, sendWelcomeEmail } from "@/emails/mailer" +import { logger } from "@/logger" +import { createSociService } from "./service" +import { createSociPgStore } from "./store-pg" + +export const soci = createSociService({ + store: createSociPgStore(DB), + directory: azureDirectory, + writes: { serialize: serializeMemberWrite, numberHolder, currentMember, rememberNumber }, + mail: { welcome: sendWelcomeEmail, numberChanged: sendMemberNumberChangedEmail }, + logger, +}) diff --git a/src/soci/router.ts b/src/soci/router.ts new file mode 100644 index 0000000..2d5693f --- /dev/null +++ b/src/soci/router.ts @@ -0,0 +1,43 @@ +import { TRPCError } from "@trpc/server" +import { dashboard } from "@/idp/policies" +import { createTRPCRouter, policy } from "@/trpc" +import * as C from "./contract" +import type { SociService } from "./service" + +/** + * The Libro Soci. Every procedure needs `admin:access` and a `soci:*` permission; the policy carries the `soci:*` + * one, so the router walk shows it. Factory keeps policy and shape tests independent of databases and Microsoft 365. + */ +export function createSociRouter(soci: SociService) { + const direttivo = (permission: string) => + policy(dashboard(permission)).use(({ ctx, next }) => { + if (ctx.actor.kind !== "user" || !ctx.can("admin:access")) + throw new TRPCError({ code: "FORBIDDEN", message: "Missing admin:access" }) + return next({ ctx: { sub: ctx.actor.sub } }) + }) + const read = direttivo("soci:read") + const write = direttivo("soci:write") + return createTRPCRouter({ + members: createTRPCRouter({ + list: read.output(C.sociListSchema).query(() => soci.list()), + get: read + .input(C.numberInputSchema) + .output(C.socioRecordSchema) + .query(({ input }) => soci.get(input)), + unregistered: read.output(C.unregisteredSchema.array()).query(() => soci.unregistered()), + admit: write + .input(C.admitInputSchema) + .output(C.admitResultSchema) + .mutation(({ ctx, input }) => soci.admit(ctx.sub, input)), + register: write + .input(C.registerInputSchema) + .output(C.numberInputSchema) + .mutation(({ ctx, input }) => soci.register(ctx.sub, input)), + update: write.input(C.updateInputSchema).mutation(({ ctx, input }) => soci.update(ctx.sub, input)), + setNumber: write + .input(C.setNumberInputSchema) + .output(C.setNumberResultSchema) + .mutation(({ ctx, input }) => soci.setNumber(ctx.sub, input)), + }), + }) +} diff --git a/src/soci/service.ts b/src/soci/service.ts new file mode 100644 index 0000000..3c13d34 --- /dev/null +++ b/src/soci/service.ts @@ -0,0 +1,431 @@ +import { TRPCError } from "@trpc/server" +import { IncompleteMemberError, safeErrorDetail } from "@/azure/errors" +import { MAIL_DOMAIN, mailboxLocalPart } from "@/azure/mailbox" +import type { AzureDirectory, CreatedMember, MemberSummary } from "@/azure/types" +import type * as C from "./contract" +import type { ActivityEntry, Socio, SocioChanges, SociStore } from "./types" + +type Logger = { + info: (obj: object, msg: string) => void + error: (obj: object, msg: string) => void +} + +export type SociOptions = { + store: SociStore + directory: Pick + /** The Entra-side lock and pending-number cache shared with Microsoft 365 › Members (`member-writes.ts`). */ + writes: { + serialize: (task: () => Promise) => Promise + numberHolder: (number: number) => Promise + currentMember: (userId: string) => Promise + rememberNumber: (member: MemberSummary, number: number, created?: boolean) => void + } + mail: { + welcome: ( + to: string, + credentials: { email: string; password: string }, + member: { firstName: string; assocNumber: number } + ) => Promise + numberChanged: ( + to: string, + member: { + firstName: string | null + assocNumber: number + previousAssocNumber: string | null + email: string | null + } + ) => Promise + } + logger: Logger + now?: () => Date +} + +export function fail( + code: "BAD_REQUEST" | "NOT_FOUND" | "CONFLICT" | "PRECONDITION_FAILED" | "INTERNAL_SERVER_ERROR", + message: string +): never { + throw new TRPCError({ code, message }) +} + +/** A member number written as Microsoft 365 holds it, when it is one. */ +function parseNumber(employeeId: string | null) { + return employeeId && /^[1-9]\d{0,5}$/.test(employeeId) ? Number(employeeId) : null +} + +const sameValue = (a: unknown, b: unknown) => JSON.stringify(a) === JSON.stringify(b) +const FIELD_LABELS: Record = { + firstName: "first name", + lastName: "last name", + alias: "alias", + codiceFiscale: "codice fiscale", + birthDate: "birth date", + birthPlace: "birth place", + residence: "residence", + admittedOn: "admission date", +} + +export function createSociService(options: SociOptions) { + const { store, directory, writes, mail, logger } = options + const now = options.now ?? (() => new Date()) + const entry = (actor: string, text: string): ActivityEntry => ({ actor, text, at: now().toISOString() }) + + async function sociGroup() { + try { + return await directory.getSociMembers() + } catch (error) { + logger.error({ error: safeErrorDetail(error) }, "[soci] could not read the Soci group") + return null + } + } + + function row(s: Socio, soci: Set | null): C.SocioRow { + const inSoci = soci ? soci.has(s.entraObjectId) : null + const mismatch = + inSoci === null ? null : !s.endedOn && !inSoci ? "not_in_soci" : s.endedOn && inSoci ? "still_in_soci" : null + return { + number: s.number, + entraObjectId: s.entraObjectId, + mailbox: s.mailbox, + displayName: s.displayName, + firstName: s.firstName, + lastName: s.lastName, + alias: s.alias, + codiceFiscale: s.codiceFiscale, + admittedOn: s.admittedOn, + endedOn: s.endedOn, + endReason: s.endReason, + accountState: s.accountState, + inSoci, + mismatch, + } + } + + async function find(number: number) { + return (await store.byNumber(number)) ?? fail("NOT_FOUND", `There is no socio with number ${number}.`) + } + + /** Free only if no record has ever held it and no Microsoft 365 user other than `self` has it. */ + async function requireFreeNumber(number: number, self: { memberId?: number; userId?: string } = {}) { + const owner = await store.numberOwner(number) + if (owner !== null && owner !== self.memberId) + fail("CONFLICT", `Member number ${number} was already given to a socio: numbers are never reused.`) + const holder = await writes.numberHolder(number) + if (holder && holder.id !== self.userId) + fail( + "CONFLICT", + `Member number ${number} is already assigned in Microsoft 365 to ${holder.displayName ?? holder.mail ?? "another user"}.` + ) + } + + async function requireUniqueCodiceFiscale(codiceFiscale: string | null, self?: number) { + if (!codiceFiscale) return + const active = await store.activeByCodiceFiscale(codiceFiscale) + if (active && active.id !== self) + fail("CONFLICT", `This codice fiscale belongs to socio ${active.number}, who is still active.`) + } + + const detailsOf = (d: C.SocioDetails) => ({ + firstName: d.firstName, + lastName: d.lastName, + alias: d.alias, + codiceFiscale: d.codiceFiscale, + birthDate: d.birthDate, + birthPlace: d.birthPlace, + residence: d.residence, + }) + + return { + async list(): Promise { + const [records, group] = await Promise.all([store.list(), sociGroup()]) + const soci = group && new Set(group.map((m) => m.id)) + return { members: records.map((s) => row(s, soci)), directoryAvailable: soci !== null } + }, + + async get(input: C.NumberInput): Promise { + const s = await find(input.number) + const deleted = s.accountState === "deleted" + const [history, group, account] = await Promise.all([ + store.activity(s.id), + deleted ? Promise.resolve([]) : sociGroup(), + deleted ? Promise.resolve(null) : writes.currentMember(s.entraObjectId).catch(() => null), + ]) + const { id: _, ...record } = s + return { + ...record, + ...row(s, group && new Set(group.map((m) => m.id))), + accountNumber: account?.employeeId ?? null, + activity: history, + } + }, + + async unregistered(): Promise { + const group = (await sociGroup()) ?? fail("PRECONDITION_FAILED", "Microsoft 365 can't be read right now.") + const registered = new Set((await store.list()).map((s) => s.entraObjectId)) + return group + .filter((m) => !registered.has(m.id)) + .map((m) => ({ + entraObjectId: m.id, + displayName: m.displayName, + givenName: m.givenName, + surname: m.surname, + mail: m.mail, + employeeId: m.employeeId, + createdDateTime: m.createdDateTime, + })) + .sort( + (a, b) => + (parseNumber(a.employeeId) ?? Number.MAX_SAFE_INTEGER) - + (parseNumber(b.employeeId) ?? Number.MAX_SAFE_INTEGER) || + (a.displayName ?? "").localeCompare(b.displayName ?? "") + ) + }, + + /** + * Today's Microsoft 365 workflow (account with `employeeId`, licences, Soci group, cleanup on failure), then the + * record. A record that can't be written deletes the new account, like any other failed setup step. + */ + async admit(actor: string, input: C.AdmitInput): Promise { + const { account, number } = input + const localPart = mailboxLocalPart(account.firstName, account.lastName, account.mailbox) + if (localPart === null) fail("BAD_REQUEST", "This name cannot form a standard address: choose a custom one.") + const address = `${localPart}@${MAIL_DOMAIN}` + if (account.sendEmailTo.toLowerCase() === address) + fail("BAD_REQUEST", "The welcome email cannot go to the address being created: it has no mailbox yet.") + + const { member, socio } = await writes.serialize(async () => { + if (await directory.findByMail(address)) fail("CONFLICT", `The address ${address} is already in use.`) + await requireFreeNumber(number) + await requireUniqueCodiceFiscale(input.details.codiceFiscale) + + const displayName = `${account.firstName} ${account.lastName}` + let member: CreatedMember + try { + member = await directory.createMember({ + firstName: account.firstName, + lastName: account.lastName, + assocNumber: number, + localPart, + }) + } catch (error) { + if (error instanceof IncompleteMemberError) { + writes.rememberNumber(error.member, number, true) + logger.error({ error: safeErrorDetail(error.cause), by: actor }, "[soci] account setup incomplete") + fail("INTERNAL_SERVER_ERROR", error.message) + } + logger.error({ error: safeErrorDetail(error), by: actor, number }, "[soci] could not create the account") + if ( + error instanceof Error && + /same value for property (userPrincipalName|proxyAddresses)/i.test(error.message) + ) + fail("CONFLICT", `The address ${address} is already in use.`) + fail("INTERNAL_SERVER_ERROR", "Microsoft 365 refused to create the account, see the backend logs.") + } + const summary: MemberSummary = { + id: member.id, + displayName, + givenName: account.firstName, + mail: member.mail, + employeeId: String(number), + } + + const at = now().toISOString() + let socio: Socio + try { + socio = await store.insert( + { + number, + entraObjectId: member.id, + mailbox: member.mail, + displayName, + ...detailsOf(input.details), + admittedOn: input.admittedOn, + endedOn: null, + endReason: null, + endNote: null, + accountState: "active", + accountDeletedOn: null, + createdBy: actor, + createdAt: at, + updatedBy: actor, + updatedAt: at, + }, + entry(actor, `Admitted with number ${number}; account ${member.mail} created`) + ) + } catch (error) { + logger.error({ error: safeErrorDetail(error), by: actor, memberId: member.id }, "[soci] record not written") + try { + await directory.deleteUser(member.id) + } catch (cleanupError) { + writes.rememberNumber(summary, number, true) + logger.error( + { error: safeErrorDetail(cleanupError), memberId: member.id }, + "[soci] could not delete the account after the record failed" + ) + fail( + "INTERNAL_SERVER_ERROR", + `Account ${member.mail} was created, but its record couldn't be saved and the account couldn't be deleted. Contact IT before trying again.` + ) + } + fail("INTERNAL_SERVER_ERROR", "The record couldn't be saved, so the new account was deleted. Try again.") + } + writes.rememberNumber(summary, number, true) + return { member, socio } + }) + logger.info({ by: actor, memberId: member.id, number }, "[soci] socio admitted") + + let welcomeMailSent = false + try { + welcomeMailSent = await mail.welcome( + account.sendEmailTo, + { email: member.mail, password: member.password }, + { firstName: account.firstName, assocNumber: number } + ) + } catch (error) { + logger.error({ error: safeErrorDetail(error), by: actor, memberId: member.id }, "[soci] welcome email failed") + } + return { number: socio.number, entraObjectId: member.id, mailbox: member.mail, welcomeMailSent } + }, + + /** + * A record for an account already in the Soci group. Its number is the account's; an account without one gets + * the number given here. + */ + async register(actor: string, input: C.RegisterInput): Promise { + const socio = await writes.serialize(async () => { + const existing = await store.byObjectId(input.entraObjectId) + if (existing) fail("CONFLICT", `This account already has a record: socio ${existing.number}.`) + const group = + (await directory.getSociMembers().catch((error) => { + logger.error({ error: safeErrorDetail(error) }, "[soci] could not read the Soci group") + return null + })) ?? fail("PRECONDITION_FAILED", "Microsoft 365 can't be read right now.") + const listed = group.find((m) => m.id === input.entraObjectId) + if (!listed) fail("PRECONDITION_FAILED", "This account isn't in the Soci group in Microsoft 365.") + const account = (await writes.currentMember(input.entraObjectId)) ?? listed + + const accountNumber = parseNumber(account.employeeId) + if (accountNumber !== null && input.number !== undefined && input.number !== accountNumber) + fail( + "BAD_REQUEST", + `The account has member number ${accountNumber}: register it with that number, then change it.` + ) + const number = + accountNumber ?? + input.number ?? + fail("BAD_REQUEST", "The account has no member number in Microsoft 365: choose one.") + await requireFreeNumber(number, { userId: account.id }) + await requireUniqueCodiceFiscale(input.details.codiceFiscale) + + if (accountNumber === null) { + const { error } = await directory.setMemberNumber(account.id, number) + if (error) { + logger.error({ error: safeErrorDetail(error), by: actor, memberId: account.id }, "[soci] number not set") + fail("INTERNAL_SERVER_ERROR", "Microsoft 365 refused the member number, see the backend logs.") + } + writes.rememberNumber(account, number) + } + + const at = now().toISOString() + // If this fails after the number was set, trying again finds the account with it and goes on. + return store.insert( + { + number, + entraObjectId: account.id, + mailbox: account.mail ?? listed.mail ?? "", + displayName: + account.displayName ?? listed.displayName ?? `${input.details.firstName} ${input.details.lastName}`, + ...detailsOf(input.details), + admittedOn: input.admittedOn, + endedOn: null, + endReason: null, + endNote: null, + accountState: "active", + accountDeletedOn: null, + createdBy: actor, + createdAt: at, + updatedBy: actor, + updatedAt: at, + }, + entry( + actor, + accountNumber === null + ? `Registered from Microsoft 365 with the new number ${number}` + : `Registered from Microsoft 365 with number ${number}` + ) + ) + }) + logger.info({ by: actor, memberId: socio.entraObjectId, number: socio.number }, "[soci] socio registered") + return { number: socio.number } + }, + + async update(actor: string, input: C.UpdateInput): Promise { + await writes.serialize(async () => { + const s = await find(input.number) + // An ended record may share its code with the person's current one. + if (!s.endedOn) await requireUniqueCodiceFiscale(input.details.codiceFiscale, s.id) + const next = { ...detailsOf(input.details), admittedOn: input.admittedOn } + const changed = (Object.keys(next) as (keyof typeof next)[]).filter((key) => !sameValue(next[key], s[key])) + if (!changed.length) return + const changes: SocioChanges = { + ...Object.fromEntries(changed.map((key) => [key, next[key]])), + updatedBy: actor, + updatedAt: now().toISOString(), + } + await store.update(s.id, changes, entry(actor, `Edited ${changed.map((key) => FIELD_LABELS[key]).join(", ")}`)) + }) + }, + + /** Changes the number on the account (`employeeId`) and on the record, optionally emailing it. */ + async setNumber(actor: string, input: C.SetNumberInput): Promise { + const { s, member } = await writes.serialize(async () => { + const s = await find(input.number) + if (input.newNumber === s.number) fail("BAD_REQUEST", `The socio already has number ${s.number}.`) + if (s.accountState === "deleted") fail("PRECONDITION_FAILED", "The socio's account has been deleted.") + const member = + (await writes.currentMember(s.entraObjectId)) ?? + fail("PRECONDITION_FAILED", "The socio's account no longer exists in Microsoft 365.") + await requireFreeNumber(input.newNumber, { memberId: s.id, userId: member.id }) + + const { error } = await directory.setMemberNumber(member.id, input.newNumber) + if (error) { + logger.error({ error: safeErrorDetail(error), by: actor, memberId: member.id }, "[soci] number not changed") + fail("INTERNAL_SERVER_ERROR", "Microsoft 365 refused the change, see the backend logs.") + } + writes.rememberNumber(member, input.newNumber) + try { + await store.changeNumber( + s.id, + input.newNumber, + entry(actor, `Member number changed from ${s.number} to ${input.newNumber}`) + ) + } catch (error) { + logger.error({ error: safeErrorDetail(error), by: actor, memberId: member.id }, "[soci] number not saved") + // Put the account back on the record's number, so the two agree. + const restored = await directory.setMemberNumber(member.id, s.number) + if (!restored.error) writes.rememberNumber({ ...member, employeeId: String(input.newNumber) }, s.number) + fail("INTERNAL_SERVER_ERROR", "The new number couldn't be saved; the account keeps the old one.") + } + return { s, member } + }) + logger.info({ by: actor, memberId: member.id, from: s.number, to: input.newNumber }, "[soci] number changed") + + let notificationSent: boolean | null = null + if (input.notifyEmail) { + try { + notificationSent = await mail.numberChanged(input.notifyEmail, { + firstName: s.alias ?? member.givenName ?? s.firstName, + assocNumber: input.newNumber, + previousAssocNumber: String(s.number), + email: member.mail, + }) + } catch (error) { + logger.error({ error: safeErrorDetail(error), by: actor, memberId: member.id }, "[soci] number email failed") + notificationSent = false + } + } + return { number: input.newNumber, notificationSent } + }, + } +} + +export type SociService = ReturnType diff --git a/src/soci/store-pg.ts b/src/soci/store-pg.ts new file mode 100644 index 0000000..dda90bb --- /dev/null +++ b/src/soci/store-pg.ts @@ -0,0 +1,124 @@ +import { and, asc, desc, eq, isNull } from "drizzle-orm" +import type { DB } from "@/db" +import { activity, members, numbers } from "@/db/schema/soci" +import type { ActivityEntry, NewSocio, Socio, SocioChanges, SociStore } from "./types" + +type Database = typeof DB +type Row = typeof members.$inferSelect +type Insert = typeof members.$inferInsert + +/** Bun's driver returns `date` columns as a `Date` at UTC midnight, whatever the column's mode. */ +const day = (value: T | Date): T => + (value instanceof Date ? value.toISOString().slice(0, 10) : value) as T + +function load(r: Row): Socio { + return { + id: r.id, + number: r.number, + entraObjectId: r.entraObjectId, + mailbox: r.mailbox, + displayName: r.displayName, + firstName: r.firstName, + lastName: r.lastName, + alias: r.alias, + codiceFiscale: r.codiceFiscale, + birthDate: day(r.birthDate), + birthPlace: r.birthPlace, + residence: { + street: r.residenceStreet, + postalCode: r.residencePostalCode, + city: r.residenceCity, + province: r.residenceProvince, + country: r.residenceCountry, + }, + admittedOn: day(r.admittedOn), + endedOn: day(r.endedOn), + endReason: r.endReason, + endNote: r.endNote, + accountState: r.accountState, + accountDeletedOn: day(r.accountDeletedOn), + createdBy: r.createdBy, + createdAt: r.createdAt.toISOString(), + updatedBy: r.updatedBy, + updatedAt: r.updatedAt.toISOString(), + } +} + +function save(s: SocioChanges): Partial { + const { residence, createdAt, updatedAt, ...rest } = s as SocioChanges & { createdAt?: string } + return { + ...rest, + ...(residence && { + residenceStreet: residence.street, + residencePostalCode: residence.postalCode, + residenceCity: residence.city, + residenceProvince: residence.province, + residenceCountry: residence.country, + }), + ...(createdAt && { createdAt: new Date(createdAt) }), + updatedAt: new Date(updatedAt), + } +} + +const entryRow = (memberId: number, e: ActivityEntry) => ({ + memberId, + actor: e.actor, + text: e.text, + at: new Date(e.at), +}) + +export function createSociPgStore(db: Database): SociStore { + const first = (rows: Row[]) => (rows[0] ? load(rows[0]) : null) + return { + async list() { + return (await db.select().from(members).orderBy(asc(members.number))).map(load) + }, + async byNumber(number) { + return first(await db.select().from(members).where(eq(members.number, number))) + }, + async byObjectId(entraObjectId) { + return first(await db.select().from(members).where(eq(members.entraObjectId, entraObjectId))) + }, + async activeByCodiceFiscale(codiceFiscale) { + return first( + await db + .select() + .from(members) + .where(and(eq(members.codiceFiscale, codiceFiscale), isNull(members.endedOn))) + ) + }, + async numberOwner(number) { + const [row] = await db.select({ memberId: numbers.memberId }).from(numbers).where(eq(numbers.number, number)) + return row?.memberId ?? null + }, + async activity(memberId) { + const rows = await db.select().from(activity).where(eq(activity.memberId, memberId)).orderBy(desc(activity.id)) + return rows.map((r) => ({ actor: r.actor, text: r.text, at: r.at.toISOString() })) + }, + insert: (socio: NewSocio, entry) => + db.transaction(async (tx) => { + const [row] = await tx + .insert(members) + .values(save(socio) as Insert) + .returning() + await tx.insert(numbers).values({ number: row.number, memberId: row.id, assignedAt: row.createdAt }) + await tx.insert(activity).values(entryRow(row.id, entry)) + return load(row) + }), + update: (memberId, changes, entry) => + db.transaction(async (tx) => { + await tx.update(members).set(save(changes)).where(eq(members.id, memberId)) + await tx.insert(activity).values(entryRow(memberId, entry)) + }), + changeNumber: (memberId, number, entry) => + db.transaction(async (tx) => { + const at = new Date(entry.at) + // Going back to a number this record held before keeps its original row. + const [held] = await tx.select().from(numbers).where(eq(numbers.number, number)) + if (held && held.memberId !== memberId) throw new Error(`Member number ${number} was given to another record`) + if (!held) await tx.insert(numbers).values({ number, memberId, assignedAt: at }) + await tx.update(members).set({ number, updatedBy: entry.actor, updatedAt: at }).where(eq(members.id, memberId)) + await tx.insert(activity).values(entryRow(memberId, entry)) + }), + } +} diff --git a/src/soci/types.ts b/src/soci/types.ts new file mode 100644 index 0000000..7aa4248 --- /dev/null +++ b/src/soci/types.ts @@ -0,0 +1,52 @@ +import type { ACCOUNT_STATES, END_REASONS, Residence } from "./contract" + +/** One admission in the Libro Soci. */ +export type Socio = { + id: number + number: number + entraObjectId: string + mailbox: string + displayName: string + firstName: string + lastName: string + alias: string | null + codiceFiscale: string | null + birthDate: string | null + birthPlace: string | null + residence: Residence + admittedOn: string + endedOn: string | null + endReason: (typeof END_REASONS)[number] | null + endNote: string | null + accountState: (typeof ACCOUNT_STATES)[number] + accountDeletedOn: string | null + createdBy: string + createdAt: string + updatedBy: string + updatedAt: string +} + +export type NewSocio = Omit +/** The fields an edit may change. */ +export type SocioChanges = Partial> & + Pick + +export type ActivityEntry = { actor: string; text: string; at: string } + +export interface SociStore { + /** Every record, by number. */ + list(): Promise + byNumber(number: number): Promise + byObjectId(entraObjectId: string): Promise + /** The active record with this codice fiscale, if any. */ + activeByCodiceFiscale(codiceFiscale: string): Promise + /** The record that holds or once held this number, if any. */ + numberOwner(number: number): Promise + /** A record's history, newest first. */ + activity(memberId: number): Promise + /** Writes a record, its number and its first history entry in one transaction. */ + insert(socio: NewSocio, entry: ActivityEntry): Promise + update(memberId: number, changes: SocioChanges, entry: ActivityEntry): Promise + /** Gives the record a new number, keeping the old one as used. */ + changeNumber(memberId: number, number: number, entry: ActivityEntry): Promise +} diff --git a/tests/idp-router.test.ts b/tests/idp-router.test.ts index 25a13b3..9df5bc4 100644 --- a/tests/idp-router.test.ts +++ b/tests/idp-router.test.ts @@ -132,6 +132,11 @@ describe("app router", () => { .filter(([name]) => name.startsWith("azure.groups.")) .map(([name]) => name) ).toEqual(["azure.groups.getAll"]) + // The Libro Soci: the policy carries the soci permission, and the router also requires admin:access. + for (const path of ["soci.members.list", "soci.members.get", "soci.members.unregistered"]) + expect(policyOf(path)?.policy, path).toEqual({ user: { scope: "backend:admin", permission: "soci:read" } }) + for (const path of ["admit", "register", "update", "setNumber"].map((name) => `soci.members.${name}`)) + expect(policyOf(path)?.policy, path).toEqual({ user: { scope: "backend:admin", permission: "soci:write" } }) expect(policyOf("tg.groups.leaveChat")?.policy).toEqual({ user: { scope: "backend:admin", permission: "tg:groups:manage" }, }) diff --git a/tests/soci-fixtures.ts b/tests/soci-fixtures.ts new file mode 100644 index 0000000..d99827d --- /dev/null +++ b/tests/soci-fixtures.ts @@ -0,0 +1,122 @@ +import { vi } from "vitest" +import { createMockAzureDirectory } from "@/azure/mock-directory" +import type { AzureDirectory } from "@/azure/types" +import type { AdmitInput, RegisterInput } from "@/soci/contract" +import { admitInputSchema, registerInputSchema } from "@/soci/contract" +import { createSociService, type SociOptions } from "@/soci/service" +import type { ActivityEntry, Socio, SociStore } from "@/soci/types" + +/** The register in memory, with the same rules the tables enforce. */ +export function memoryStore() { + const rows: Socio[] = [] + const numbers = new Map() + const history = new Map() + const log = (id: number, e: ActivityEntry) => history.set(id, [e, ...(history.get(id) ?? [])]) + const store: SociStore = { + async list() { + return structuredClone(rows).sort((a, b) => a.number - b.number) + }, + async byNumber(number) { + return structuredClone(rows.find((r) => r.number === number) ?? null) + }, + async byObjectId(id) { + return structuredClone(rows.find((r) => r.entraObjectId === id) ?? null) + }, + async activeByCodiceFiscale(code) { + return structuredClone(rows.find((r) => r.codiceFiscale === code && !r.endedOn) ?? null) + }, + async numberOwner(number) { + return numbers.get(number) ?? null + }, + async activity(id) { + return structuredClone(history.get(id) ?? []) + }, + async insert(socio, entry) { + if (numbers.has(socio.number)) throw new Error("duplicate key soci_numbers_pkey") + if (rows.some((r) => r.entraObjectId === socio.entraObjectId)) throw new Error("duplicate entra_object_id") + if (socio.codiceFiscale && rows.some((r) => r.codiceFiscale === socio.codiceFiscale && !r.endedOn)) + throw new Error("duplicate soci_members_active_codice_fiscale_idx") + const row = { ...structuredClone(socio), id: rows.length + 1 } + rows.push(row) + numbers.set(row.number, row.id) + log(row.id, entry) + return structuredClone(row) + }, + async update(id, changes, entry) { + const row = rows.find((r) => r.id === id) as Socio + Object.assign(row, structuredClone(changes)) + log(id, entry) + }, + async changeNumber(id, number, entry) { + const owner = numbers.get(number) + if (owner !== undefined && owner !== id) throw new Error("number taken") + numbers.set(number, id) + const row = rows.find((r) => r.id === id) as Socio + row.number = number + row.updatedBy = entry.actor + row.updatedAt = entry.at + log(id, entry) + }, + } + return { store, rows, numbers } +} + +export const VALID_CF = "RSSMRA80A01H501U" +export const OTHER_CF = "RSSMRA85T10A562S" + +export const details = (overrides: Record = {}) => ({ + firstName: "Mario", + lastName: "Rossi", + alias: "", + codiceFiscale: VALID_CF, + birthDate: "1980-01-01", + birthPlace: "Roma", + residence: { street: "Via Roma 1", postalCode: "20133", city: "Milano", province: "MI", country: "IT" }, + ...overrides, +}) + +export const admitInput = (overrides: Record = {}): AdmitInput => + admitInputSchema.parse({ + account: { firstName: "Mario", lastName: "Rossi", sendEmailTo: "mario@example.org" }, + number: 344, + details: details(), + admittedOn: "2026-11-09", + ...overrides, + }) + +export const registerInput = (entraObjectId: string, overrides: Record = {}): RegisterInput => + registerInputSchema.parse({ + entraObjectId, + details: { firstName: "Alan", lastName: "Turing" }, + admittedOn: "2025-03-14", + ...overrides, + }) + +/** The service over the seeded mock directory (Ada 1001 and Alan 1002 in Soci, Grace outside it). */ +export function harness(overrides: Partial = {}) { + const memory = memoryStore() + const directory: AzureDirectory = createMockAzureDirectory() + let tail: Promise = Promise.resolve() + const welcome = vi.fn().mockResolvedValue(true) + const numberChanged = vi.fn().mockResolvedValue(true) + const logger = { info: vi.fn(), error: vi.fn() } + const service = createSociService({ + store: memory.store, + directory, + writes: { + serialize(task) { + const run = tail.then(task, task) + tail = run.catch(() => undefined) + return run + }, + numberHolder: (n) => directory.findByMemberNumber(n), + currentMember: (id) => directory.getMember(id), + rememberNumber: () => {}, + }, + mail: { welcome, numberChanged }, + logger, + now: () => new Date("2026-11-09T10:00:00Z"), + ...overrides, + }) + return { service, directory, ...memory, welcome, numberChanged, logger } +} diff --git a/tests/soci-postgres.fixture.ts b/tests/soci-postgres.fixture.ts new file mode 100644 index 0000000..dfa622f --- /dev/null +++ b/tests/soci-postgres.fixture.ts @@ -0,0 +1,95 @@ +import assert from "node:assert/strict" +import { SQL } from "bun" +import { drizzle } from "drizzle-orm/bun-sql" +import { migrate } from "drizzle-orm/bun-sql/migrator" +import { schema } from "@/db/schema" +import { members } from "@/db/schema/soci" +import { createSociPgStore } from "@/soci/store-pg" +import type { NewSocio } from "@/soci/types" + +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 databaseName = `soci_test_${process.pid}` +await admin.unsafe(`CREATE DATABASE ${databaseName}`) +const client = new SQL({ ...connection, database: databaseName }) +const db = drizzle({ client, schema }) +const checked: string[] = [] +const at = "2026-11-09T10:00:00.000Z" +const entry = (text: string) => ({ actor: "usr_direttivo", text, at }) +const socio = (number: number, entraObjectId: string, codiceFiscale: string | null): NewSocio => ({ + number, + entraObjectId, + mailbox: `${entraObjectId}@polinetwork.org`, + displayName: entraObjectId, + firstName: "Mario", + lastName: "Rossi", + alias: null, + codiceFiscale, + birthDate: "1980-01-01", + birthPlace: "Roma", + residence: { street: "Via Roma 1", postalCode: "20133", city: "Milano", province: "MI", country: "IT" }, + admittedOn: "2026-11-09", + endedOn: null, + endReason: null, + endNote: null, + accountState: "active", + accountDeletedOn: null, + createdBy: "usr_direttivo", + createdAt: at, + updatedBy: "usr_direttivo", + updatedAt: at, +}) +try { + await migrate(db, { migrationsFolder: "./drizzle" }) + const store = createSociPgStore(db) + + const mario = await store.insert(socio(344, "oid-mario", "RSSMRA80A01H501U"), entry("Admitted")) + const loaded = await store.byNumber(344) + assert.deepEqual(loaded, { ...socio(344, "oid-mario", "RSSMRA80A01H501U"), id: mario.id }) + assert.equal(await store.numberOwner(344), mario.id) + assert.deepEqual(await store.activity(mario.id), [entry("Admitted")]) + checked.push("a record, its number and its history round-trip, dates included") + + await assert.rejects(store.insert(socio(345, "oid-other", "RSSMRA80A01H501U"), entry("Admitted"))) + await assert.rejects(store.insert(socio(344, "oid-other", null), entry("Admitted"))) + await assert.rejects(store.insert(socio(345, "oid-mario", null), entry("Admitted"))) + assert.equal((await store.list()).length, 1) + checked.push("one active record per codice fiscale, number and account") + + await store.changeNumber(mario.id, 350, entry("Number changed")) + assert.equal((await store.byNumber(350))?.id, mario.id) + assert.equal(await store.numberOwner(344), mario.id) + // No record may take 344, even though nobody holds it now. + await assert.rejects(store.insert(socio(344, "oid-anna", null), entry("Admitted"))) + await store.changeNumber(mario.id, 344, entry("Number changed back")) + assert.equal((await store.byNumber(344))?.id, mario.id) + checked.push("a number once held is never given to another record") + + await store.update( + mario.id, + { endedOn: "2026-12-31", endReason: "resigned", updatedBy: "usr_direttivo", updatedAt: at }, + entry("Ended") + ) + const readmitted = await store.insert(socio(351, "oid-mario-2", "RSSMRA80A01H501U"), entry("Admitted")) + assert.equal((await store.activeByCodiceFiscale("RSSMRA80A01H501U"))?.id, readmitted.id) + await assert.rejects( + db.insert(members).values({ + ...socio(352, "oid-x", null), + residenceStreet: null, + endedOn: "2026-12-31", + createdAt: new Date(at), + updatedAt: new Date(at), + } as never) + ) + checked.push("an ended record frees its code for a re-admission, and an end needs its reason") + console.log(JSON.stringify({ checked })) +} finally { + await client.close() + await admin.unsafe(`DROP DATABASE ${databaseName} WITH (FORCE)`) + await admin.close() +} diff --git a/tests/soci-postgres.test.ts b/tests/soci-postgres.test.ts new file mode 100644 index 0000000..d9f3793 --- /dev/null +++ b/tests/soci-postgres.test.ts @@ -0,0 +1,16 @@ +import { execFile } from "node:child_process" +import { promisify } from "node:util" +import { expect, it } from "vitest" + +it.skipIf(!process.env.SEED_TEST_DB_PORT)( + "persists the Libro Soci and enforces its constraints in real PostgreSQL", + async () => { + const { stdout } = await promisify(execFile)("bun", ["tests/soci-postgres.fixture.ts"], { + env: process.env, + timeout: 60000, + }) + const result = JSON.parse(stdout.trim().split("\n").at(-1) ?? "{}") + expect(result.checked).toHaveLength(4) + }, + 65000 +) diff --git a/tests/soci-router.test.ts b/tests/soci-router.test.ts new file mode 100644 index 0000000..657518d --- /dev/null +++ b/tests/soci-router.test.ts @@ -0,0 +1,82 @@ +import type { Actor } from "@polinetwork/auth-kit" +import { beforeAll, describe, expect, it } from "vitest" +import type { Context } from "@/trpc" +import { admitInput, harness } from "./soci-fixtures" + +Object.assign(process.env, { + NODE_ENV: "test", + ENCRYPTION_KEY: "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef", + DB_HOST: "localhost", + DB_USER: "postgres", + DB_PASS: "postgres", + DB_NAME: "soci_test", +}) +let makeRouter: typeof import("@/soci/router").createSociRouter +beforeAll(async () => { + makeRouter = (await import("@/soci/router")).createSociRouter +}) + +const DIRETTIVO = ["admin:access", "soci:read", "soci:write"] +const user: Actor = { kind: "user", sub: "usr_direttivo", client: "admin-dashboard", telegramId: null } + +function context(granted = DIRETTIVO, actor: Actor = user, scopes = ["backend:admin"]): Context { + return { + auth: { kind: "token", actor, scopes: new Set(scopes) }, + access: { + has: (_, p) => granted.includes(p), + current: () => null, + subjectBySub: () => undefined, + subjectByTelegramId: () => undefined, + status: () => ({ fresh: true, generation: 1, subjects: 1, lastSyncAt: 1 }), + }, + } +} + +describe("Soci tRPC contract", () => { + it("gives every procedure a dashboard policy with its soci permission", () => { + const r = makeRouter(harness().service) + const procedures = (r as unknown as { _def: { procedures: Record } })._def + .procedures + expect(Object.fromEntries(Object.entries(procedures).map(([path, p]) => [path, p._def.meta]))).toEqual({ + "members.list": { policy: { user: { scope: "backend:admin", permission: "soci:read" } } }, + "members.get": { policy: { user: { scope: "backend:admin", permission: "soci:read" } } }, + "members.unregistered": { policy: { user: { scope: "backend:admin", permission: "soci:read" } } }, + "members.admit": { policy: { user: { scope: "backend:admin", permission: "soci:write" } } }, + "members.register": { policy: { user: { scope: "backend:admin", permission: "soci:write" } } }, + "members.update": { policy: { user: { scope: "backend:admin", permission: "soci:write" } } }, + "members.setNumber": { policy: { user: { scope: "backend:admin", permission: "soci:write" } } }, + }) + }) + + it("needs admin:access as well as the soci permission", async () => { + const r = makeRouter(harness().service) + await expect(r.createCaller({}).members.list()).rejects.toMatchObject({ code: "UNAUTHORIZED" }) + await expect(r.createCaller(context(["soci:read", "soci:write"])).members.list()).rejects.toMatchObject({ + code: "FORBIDDEN", + message: "Missing admin:access", + }) + await expect( + r.createCaller(context(["admin:access", "soci:read"])).members.admit(admitInput()) + ).rejects.toMatchObject({ code: "FORBIDDEN" }) + await expect( + r.createCaller(context(DIRETTIVO, { kind: "service", client: "bot" })).members.list() + ).rejects.toMatchObject({ code: "FORBIDDEN" }) + expect(await r.createCaller(context(["admin:access", "soci:read"])).members.list()).toEqual({ + members: [], + directoryAvailable: true, + }) + }) + + it("validates the codice fiscale before reaching Microsoft 365, and takes the author from the token", async () => { + const h = harness() + const caller = makeRouter(h.service).createCaller(context()) + const input = admitInput() + await expect( + caller.members.admit({ ...input, details: { ...input.details, codiceFiscale: "RSSMRA80A01H501X" } }) + ).rejects.toMatchObject({ code: "BAD_REQUEST" }) + expect(await h.directory.findByMail("mario.rossi@polinetwork.org")).toBeNull() + + await caller.members.admit(input) + expect((await caller.members.get({ number: 344 })).createdBy).toBe("usr_direttivo") + }) +}) diff --git a/tests/soci.test.ts b/tests/soci.test.ts new file mode 100644 index 0000000..bb37de9 --- /dev/null +++ b/tests/soci.test.ts @@ -0,0 +1,316 @@ +import { describe, expect, it, vi } from "vitest" +import { checkCharacter, codiceFiscaleProblem, matchesBirthDate } from "@/soci/codice-fiscale" +import { admitInputSchema, codiceFiscaleSchema, registerInputSchema, updateInputSchema } from "@/soci/contract" +import { admitInput, details, harness, OTHER_CF, registerInput, VALID_CF } from "./soci-fixtures" + +const ACTOR = "usr_direttivo" + +/** RSSMRA80A01H501U with its last Belfiore digit replaced for omocodia (1 -> M), and the check recomputed. */ +const OMOCODIC = `RSSMRA80A01H50M${checkCharacter("RSSMRA80A01H50M")}` + +describe("codice fiscale", () => { + it("accepts valid codes, including omocodic ones, and normalizes case and spaces", () => { + expect(codiceFiscaleProblem(VALID_CF)).toBeNull() + expect(codiceFiscaleProblem(OTHER_CF)).toBeNull() + expect(codiceFiscaleProblem(OMOCODIC)).toBeNull() + expect(codiceFiscaleSchema.parse(" rssmra80a01 h501u ")).toBe(VALID_CF) + }) + + it("refuses a wrong check character, a bad format and a day that can't exist", () => { + expect(codiceFiscaleProblem("RSSMRA80A01H501X")).toBe("check") + expect(codiceFiscaleProblem("RSSMRA80A01H501")).toBe("format") + // `F` is not a month letter. + expect(codiceFiscaleProblem("RSSMRA80F01H501U")).toBe("format") + const feb30 = `RSSMRA80B30H501${checkCharacter("RSSMRA80B30H501")}` + expect(codiceFiscaleProblem(feb30)).toBe("date") + expect(codiceFiscaleSchema.safeParse("RSSMRA80A01H501X").success).toBe(false) + }) + + it("checks the birth date against the code, for men and women", () => { + expect(matchesBirthDate(VALID_CF, "1980-01-01")).toBe(true) + expect(matchesBirthDate(OMOCODIC, "1980-01-01")).toBe(true) + expect(matchesBirthDate(VALID_CF, "1980-01-02")).toBe(false) + const anna = `BNCNNA90E52F205${checkCharacter("BNCNNA90E52F205")}` + expect(matchesBirthDate(anna, "1990-05-12")).toBe(true) + const parsed = admitInputSchema.safeParse({ + ...admitInput(), + details: details({ birthDate: "1980-01-02" }), + }) + expect(parsed.success).toBe(false) + expect(JSON.stringify(parsed.error?.issues)).toContain("doesn't match the codice fiscale") + }) + + it("requires every detail but the alias to admit, and only the legal name to register", () => { + expect(admitInputSchema.safeParse({ ...admitInput(), details: details({ birthPlace: "" }) }).success).toBe(false) + expect( + admitInputSchema.safeParse({ + ...admitInput(), + details: details({ residence: { street: "Via Roma 1", postalCode: "20133", city: "Milano", country: "IT" } }), + }).success + ).toBe(false) + const abroad = admitInputSchema.parse({ + ...admitInput(), + details: details({ residence: { street: "Rue X 1", postalCode: "75001", city: "Paris", country: "fr" } }), + }) + expect(abroad.details.residence).toMatchObject({ country: "FR", province: null }) + const registered = registerInput("mock-member-alan") + expect(registered.details).toMatchObject({ codiceFiscale: null, birthDate: null, residence: { street: null } }) + expect(registerInputSchema.safeParse({ ...registered, details: { lastName: "Turing" } }).success).toBe(false) + }) +}) + +describe("soci.members.admit", () => { + it("creates the account in Soci, writes the record and sends the welcome email", async () => { + const h = harness() + const result = await h.service.admit(ACTOR, admitInput()) + expect(result).toMatchObject({ number: 344, mailbox: "mario.rossi@polinetwork.org", welcomeMailSent: true }) + expect(h.welcome).toHaveBeenCalledWith( + "mario@example.org", + expect.objectContaining({ email: "mario.rossi@polinetwork.org" }), + { firstName: "Mario", assocNumber: 344 } + ) + const record = await h.service.get({ number: 344 }) + expect(record).toMatchObject({ + entraObjectId: result.entraObjectId, + codiceFiscale: VALID_CF, + admittedOn: "2026-11-09", + accountState: "active", + inSoci: true, + mismatch: null, + accountNumber: "344", + createdBy: ACTOR, + }) + expect(record.activity.map((a) => a.text)).toEqual([ + "Admitted with number 344; account mario.rossi@polinetwork.org created", + ]) + }) + + it("refuses a number any record has held, an ended one's included, or a Microsoft 365 user has", async () => { + const h = harness() + await h.service.admit(ACTOR, admitInput()) + const again = admitInput({ + account: { firstName: "Anna", lastName: "Bianchi", sendEmailTo: "anna@example.org" }, + details: details({ codiceFiscale: OTHER_CF, birthDate: "1985-12-10" }), + }) + await expect(h.service.admit(ACTOR, again)).rejects.toMatchObject({ code: "CONFLICT" }) + + // The record ends (as the lapse issue will do) and its account goes: the number still stays used. + h.rows[0].endedOn = "2026-12-31" + h.rows[0].endReason = "resigned" + await h.directory.deleteUser(h.rows[0].entraObjectId) + await expect(h.service.admit(ACTOR, again)).rejects.toThrow(/never reused/) + + // Ada holds 1001 in Microsoft 365, without a record. + await expect(h.service.admit(ACTOR, { ...again, number: 1001 })).rejects.toThrow(/Ada Lovelace/) + expect(await h.directory.findByMail("anna.bianchi@polinetwork.org")).toBeNull() + expect(await h.service.admit(ACTOR, { ...again, number: 345 })).toMatchObject({ number: 345 }) + }) + + it("refuses a codice fiscale an active socio has, but not one of a former socio", async () => { + const h = harness() + await h.service.admit(ACTOR, admitInput()) + const sameCode = admitInput({ + account: { + firstName: "Mario", + lastName: "Rossi", + mailbox: { kind: "custom", localPart: "mario.rossi2" }, + sendEmailTo: "mario@example.org", + }, + number: 345, + }) + await expect(h.service.admit(ACTOR, sameCode)).rejects.toThrow(/socio 344, who is still active/) + expect(await h.directory.findByMail("mario.rossi2@polinetwork.org")).toBeNull() + + h.rows[0].endedOn = "2026-12-31" + h.rows[0].endReason = "resigned" + expect((await h.service.admit(ACTOR, sameCode)).number).toBe(345) + }) + + it("deletes the new account when the record can't be written, and leaves the number free", async () => { + const h = harness() + vi.spyOn(h.store, "insert").mockRejectedValueOnce(new Error("connection lost")) + await expect(h.service.admit(ACTOR, admitInput())).rejects.toMatchObject({ + code: "INTERNAL_SERVER_ERROR", + message: "The record couldn't be saved, so the new account was deleted. Try again.", + }) + expect(await h.directory.findByMail("mario.rossi@polinetwork.org")).toBeNull() + expect(await h.directory.findByMemberNumber(344)).toBeNull() + expect(h.welcome).not.toHaveBeenCalled() + expect(h.rows).toHaveLength(0) + expect(await h.service.admit(ACTOR, admitInput())).toMatchObject({ number: 344 }) + }) + + it("says so when neither the record nor the cleanup succeed", async () => { + const h = harness() + vi.spyOn(h.store, "insert").mockRejectedValueOnce(new Error("connection lost")) + vi.spyOn(h.directory, "deleteUser").mockRejectedValueOnce(new Error("Graph is down")) + await expect(h.service.admit(ACTOR, admitInput())).rejects.toThrow(/couldn't be deleted. Contact IT/) + }) + + it("refuses an address in use and a welcome email to the new address", async () => { + const h = harness() + await expect( + h.service.admit( + ACTOR, + admitInput({ account: { firstName: "Ada", lastName: "Lovelace", sendEmailTo: "ada@example.org" } }) + ) + ).rejects.toThrow(/already in use/) + await expect( + h.service.admit( + ACTOR, + admitInput({ account: { firstName: "Mario", lastName: "Rossi", sendEmailTo: "mario.rossi@polinetwork.org" } }) + ) + ).rejects.toMatchObject({ code: "BAD_REQUEST" }) + }) +}) + +describe("soci.members.register", () => { + it("registers an account already in Soci with its number, personal fields optional", async () => { + const h = harness() + expect(await h.service.register(ACTOR, registerInput("mock-member-alan"))).toEqual({ number: 1002 }) + const record = await h.service.get({ number: 1002 }) + expect(record).toMatchObject({ + mailbox: "alan.turing@polinetwork.org", + displayName: "Alan Turing", + codiceFiscale: null, + admittedOn: "2025-03-14", + inSoci: true, + mismatch: null, + }) + expect(record.activity[0].text).toBe("Registered from Microsoft 365 with number 1002") + await expect(h.service.register(ACTOR, registerInput("mock-member-alan"))).rejects.toThrow(/already has a record/) + }) + + it("refuses an account outside Soci, and a number other than the account's", async () => { + const h = harness() + await expect(h.service.register(ACTOR, registerInput("mock-member-grace"))).rejects.toThrow( + /isn't in the Soci group/ + ) + await expect(h.service.register(ACTOR, registerInput("mock-member-alan", { number: 7 }))).rejects.toThrow( + /has member number 1002/ + ) + }) + + it("gives an account without a number the one chosen, if no record ever held it", async () => { + const h = harness() + await h.service.admit(ACTOR, admitInput()) + await h.directory.addToSoci("mock-member-grace") + const grace = (n?: number) => + registerInput("mock-member-grace", { number: n, details: { firstName: "Grace", lastName: "Hopper" } }) + await expect(h.service.register(ACTOR, grace())).rejects.toThrow(/no member number/) + await expect(h.service.register(ACTOR, grace(344))).rejects.toMatchObject({ code: "CONFLICT" }) + expect(await h.service.register(ACTOR, grace(500))).toEqual({ number: 500 }) + expect((await h.directory.getMember("mock-member-grace"))?.employeeId).toBe("500") + }) + + it("refuses a codice fiscale an active socio has", async () => { + const h = harness() + await h.service.admit(ACTOR, admitInput()) + await expect( + h.service.register(ACTOR, registerInput("mock-member-alan", { details: details({ firstName: "Alan" }) })) + ).rejects.toThrow(/still active/) + }) +}) + +describe("soci.members.list and unregistered", () => { + it("lists Soci members without a record, with their number and creation date", async () => { + const h = harness() + await h.service.register(ACTOR, registerInput("mock-member-alan")) + expect(await h.service.unregistered()).toEqual([ + { + entraObjectId: "mock-member-ada", + displayName: "Ada Lovelace", + givenName: "Ada", + surname: "Lovelace", + mail: "ada.lovelace@polinetwork.org", + employeeId: "1001", + createdDateTime: "2024-10-02T09:00:00Z", + }, + ]) + }) + + it("reports active records outside Soci and ended records still in it", async () => { + const h = harness() + await h.service.register(ACTOR, registerInput("mock-member-alan")) + await h.service.register(ACTOR, registerInput("mock-member-ada", { details: { firstName: "Ada", lastName: "L" } })) + expect((await h.service.list()).members.map((m) => m.mismatch)).toEqual([null, null]) + + await h.directory.removeFromSoci("mock-member-ada") + const alan = h.rows.find((r) => r.number === 1002) + Object.assign(alan ?? {}, { endedOn: "2026-12-31", endReason: "resigned" }) + const list = await h.service.list() + expect(list.directoryAvailable).toBe(true) + expect(list.members.map((m) => [m.number, m.inSoci, m.mismatch])).toEqual([ + [1001, false, "not_in_soci"], + [1002, true, "still_in_soci"], + ]) + }) + + it("still lists the register when Microsoft 365 can't be read", async () => { + const h = harness() + await h.service.register(ACTOR, registerInput("mock-member-alan")) + vi.spyOn(h.directory, "getSociMembers").mockRejectedValue(new Error("Graph is down")) + const list = await h.service.list() + expect(list).toMatchObject({ directoryAvailable: false, members: [{ number: 1002, inSoci: null, mismatch: null }] }) + await expect(h.service.unregistered()).rejects.toMatchObject({ code: "PRECONDITION_FAILED" }) + }) +}) + +describe("soci.members.update and setNumber", () => { + it("records which fields changed, and refuses another active socio's code", async () => { + const h = harness() + await h.service.admit(ACTOR, admitInput()) + await h.service.register(ACTOR, registerInput("mock-member-alan")) + const update = (number: number, d: Record) => + updateInputSchema.parse({ number, details: d, admittedOn: number === 344 ? "2026-11-09" : "2025-03-14" }) + + await h.service.update(ACTOR, update(344, details({ alias: "Super Mario" }))) + const record = await h.service.get({ number: 344 }) + expect(record.alias).toBe("Super Mario") + expect(record.activity[0].text).toBe("Edited alias") + + await h.service.update(ACTOR, update(344, details({ alias: "Super Mario" }))) + expect((await h.service.get({ number: 344 })).activity).toHaveLength(2) + + await expect( + h.service.update(ACTOR, update(1002, details({ firstName: "Alan", lastName: "Turing" }))) + ).rejects.toThrow(/socio 344, who is still active/) + }) + + it("changes the number in Microsoft 365 and on the record, and never gives the old one again", async () => { + const h = harness() + await h.service.admit(ACTOR, admitInput()) + await expect(h.service.setNumber(ACTOR, { number: 344, newNumber: 1001 })).rejects.toThrow(/Ada Lovelace/) + expect(await h.service.setNumber(ACTOR, { number: 344, newNumber: 350, notifyEmail: "mario@example.org" })).toEqual( + { number: 350, notificationSent: true } + ) + expect(h.numberChanged).toHaveBeenCalledWith( + "mario@example.org", + expect.objectContaining({ assocNumber: 350, previousAssocNumber: "344" }) + ) + const record = await h.service.get({ number: 350 }) + expect(record.accountNumber).toBe("350") + expect(record.activity[0].text).toBe("Member number changed from 344 to 350") + await expect(h.service.get({ number: 344 })).rejects.toMatchObject({ code: "NOT_FOUND" }) + + // 344 is free in Microsoft 365 now, but a record held it. + const anna = admitInput({ + account: { firstName: "Anna", lastName: "Bianchi", sendEmailTo: "anna@example.org" }, + details: details({ codiceFiscale: OTHER_CF, birthDate: "1985-12-10" }), + }) + await expect(h.service.admit(ACTOR, anna)).rejects.toThrow(/never reused/) + // The same record may go back to it. + expect(await h.service.setNumber(ACTOR, { number: 350, newNumber: 344 })).toEqual({ + number: 344, + notificationSent: null, + }) + }) + + it("puts the account back on the old number when the record can't be saved", async () => { + const h = harness() + await h.service.admit(ACTOR, admitInput()) + vi.spyOn(h.store, "changeNumber").mockRejectedValueOnce(new Error("connection lost")) + await expect(h.service.setNumber(ACTOR, { number: 344, newNumber: 350 })).rejects.toThrow(/keeps the old one/) + expect((await h.service.get({ number: 344 })).accountNumber).toBe("344") + }) +})