diff --git a/bun.lock b/bun.lock index 1563cf0..73a8601 100644 --- a/bun.lock +++ b/bun.lock @@ -17,8 +17,6 @@ "@trpc/server": "11.5.1", "croner": "^9.1.0", "drizzle-orm": "^0.44.7", - "fast-xml-parser": "^5.11.2", - "fflate": "^0.8.3", "hono": "^4.11.6", "nanoid": "^5.1.6", "node-html-parser": "^7.0.2", @@ -338,7 +336,7 @@ "@next/swc-win32-x64-msvc": ["@next/swc-win32-x64-msvc@16.0.10", "", { "os": "win32", "cpu": "x64" }, "sha512-E+njfCoFLb01RAFEnGZn6ERoOqhK1Gl3Lfz1Kjnj0Ulfu7oJbuMyvBKNj/bw8XZnenHDASlygTjZICQW+rYW1Q=="], - "@nodable/entities": ["@nodable/entities@3.1.0", "", {}, "sha512-LsS/DjHr+uDM647Gru/cA8+J3a3HfhttwCKLyuoyN7yXTFCxKBtSgMQBvrW9yNPa2/zDRUNuGPaH5QUFoa4arQ=="], + "@nodable/entities": ["@nodable/entities@2.1.1", "", {}, "sha512-Pig3HxDIoMgjdEH8OCf/dkcTmLFjJRjWuq8jSnklu284/TKOPibSRERmOykiwmyXTtv61mP+44f3GMx0tLAyjg=="], "@nodelib/fs.scandir": ["@nodelib/fs.scandir@2.1.5", "", { "dependencies": { "@nodelib/fs.stat": "2.0.5", "run-parallel": "^1.1.9" } }, "sha512-vq24Bq3ym5HEQm2NKCr3yXDwjc7vTsEThRDnkp2DK9p1uqLR+DHurm/NOTo0KG7HYHU7eppKZj3MyqYuMBf62g=="], @@ -662,8 +660,6 @@ "any-promise": ["any-promise@1.3.0", "", {}, "sha512-7UvmKalWRt1wgjL1RrGxoSJW/0QZFIegpeGvZG9kjp8vrRu55XTHbwnqq2GpXm9uLbcuhxm3IqX9OB4MZR1b2A=="], - "anynum": ["anynum@1.0.1", "", {}, "sha512-N6//FLET/tXYNM/F6ABca1oH6fWB+KlTt909Le28WMDBk8oaT4vY17DCrwg2MvmuqUKt3Ni4N5dGJ/EoBgcO6A=="], - "array-ify": ["array-ify@1.0.0", "", {}, "sha512-c5AMf34bKdvPhQ7tBGhqkgKNUzMr4WUs+WDtC2ZUGOUncbxKMTvqxYctiseW3+L4bA8ec+GcZ6/A/FW4m8ukng=="], "asn1js": ["asn1js@3.1.0", "", { "dependencies": { "pvtsutils": "^1.3.6", "pvutils": "^1.2.0", "tslib": "^2.8.1" } }, "sha512-HWYi1THkOqguCiO+vwj09ZkQFD2kKEsejYHAYCtX0D80WVdoDnvRc9IukXX/jeb0T9NRWJnRtqwdbHltnFjwXA=="], @@ -832,14 +828,12 @@ "fast-xml-builder": ["fast-xml-builder@1.2.0", "", { "dependencies": { "path-expression-matcher": "^1.5.0", "xml-naming": "^0.1.0" } }, "sha512-00aAWieqff+ZJhsXA4g1g7M8k+7AYoMUUHF+/zFb5U6Uv/P0Vl4QZo84/IcufzYalLuEj9928bXN9PbbFzMF0Q=="], - "fast-xml-parser": ["fast-xml-parser@5.11.2", "", { "dependencies": { "@nodable/entities": "^3.0.1", "fast-xml-builder": "^1.2.0", "is-unsafe": "^2.0.0", "path-expression-matcher": "^1.6.2", "strnum": "^2.4.2", "xml-naming": "^0.3.0" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-R9iDuNrQYeQut46cn2r2wHKn4HYzVDvDm5J1wW+koZewykv0yuO2HChTYeZtrULyHIDM9cj9TUXloCsueCQUog=="], + "fast-xml-parser": ["fast-xml-parser@5.8.0", "", { "dependencies": { "@nodable/entities": "^2.1.0", "fast-xml-builder": "^1.2.0", "path-expression-matcher": "^1.5.0", "strnum": "^2.3.0", "xml-naming": "^0.1.0" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-6bIM7fsJxeo3uXv7OncQYsBAMPJ7V16Slahl/6M98C/i2q+vB1+4a0MtrvYwDFEUrwDSbAmeLDRXsOBwrL7yAg=="], "fastq": ["fastq@1.20.1", "", { "dependencies": { "reusify": "^1.0.4" } }, "sha512-GGToxJ/w1x32s/D2EKND7kTil4n8OVk/9mycTc4VDza13lOvpUZTGX3mFSCtV9ksdGBVzvsyAVLM6mHFThxXxw=="], "fdir": ["fdir@6.5.0", "", { "optionalDependencies": { "picomatch": "4.0.3" } }, "sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg=="], - "fflate": ["fflate@0.8.3", "", {}, "sha512-tbZNuJrLwGUp3zshBtdy4W+ORxZuIh8a5ilyIEQDC5rY1f3U20JMry0Ll3WBzU58EZKsEuJFXhb5gwv8CsPvgA=="], - "fill-range": ["fill-range@7.1.1", "", { "dependencies": { "to-regex-range": "^5.0.1" } }, "sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg=="], "fix-dts-default-cjs-exports": ["fix-dts-default-cjs-exports@1.0.1", "", { "dependencies": { "magic-string": "0.30.19", "mlly": "1.8.0", "rollup": "4.52.2" } }, "sha512-pVIECanWFC61Hzl2+oOCtoJ3F17kglZC/6N94eRWycFgBH35hHx0Li604ZIzhseh97mf2p0cv7vVrOZGoqhlEg=="], @@ -900,8 +894,6 @@ "is-unicode-supported": ["is-unicode-supported@2.1.0", "", {}, "sha512-mE00Gnza5EEB3Ds0HfMyllZzbBrmLOX3vfWoj9A9PEnTfratQ/BcaJOuMhnkhjXvb2+FkY3VuHqtAGpTPmglFQ=="], - "is-unsafe": ["is-unsafe@2.0.2", "", {}, "sha512-HgbIHPBH0KHHCcjLfGsCvhtPTVxjaAZlXjwdz7/GQC40SjSe4sfQsar8J5VFo8JOSbarkpV0OLG95bbaNd9aAQ=="], - "is-what": ["is-what@5.5.0", "", {}, "sha512-oG7cgbmg5kLYae2N5IVd3jm2s+vldjxJzK1pcu9LfpGuQ93MQSzo0okvRna+7y5ifrD+20FE8FvjusyGaz14fw=="], "is-wsl": ["is-wsl@3.1.0", "", { "dependencies": { "is-inside-container": "1.0.0" } }, "sha512-UcVfVfaK4Sc4m7X3dUSoHoozQGBEFeDC+zVo06t98xe8CzHSZZBekNXH+tu0NalHolcJ/QAGqS46Hef7QXBIMw=="], @@ -1052,7 +1044,7 @@ "parseley": ["parseley@0.12.1", "", { "dependencies": { "leac": "0.6.0", "peberminta": "0.9.0" } }, "sha512-e6qHKe3a9HWr0oMRVDTRhKce+bRO8VGQR3NyVwcjwrbhMmFCX9KszEV35+rn4AdilFAq9VPxP/Fe1wC9Qjd2lw=="], - "path-expression-matcher": ["path-expression-matcher@1.6.2", "", {}, "sha512-enSlaiat05iasnzmgNxRj8reFdj3puY2QpNgP1aPIaVfT6nn9ICuPoFlKHk8EN22HcwewshO+mN2DGbkCEOtqQ=="], + "path-expression-matcher": ["path-expression-matcher@1.5.0", "", {}, "sha512-cbrerZV+6rvdQrrD+iGMcZFEiiSrbv9Tfdkvnusy6y0x0GKBXREFg/Y65GhIfm0tnLntThhzCnfKwp1WRjeCyQ=="], "path-key": ["path-key@3.1.1", "", {}, "sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q=="], @@ -1206,7 +1198,7 @@ "strip-json-comments": ["strip-json-comments@5.0.3", "", {}, "sha512-1tB5mhVo7U+ETBKNf92xT4hrQa3pm0MZ0PQvuDnWgAAGHDsfp4lPSpiS6psrSiet87wyGPh9ft6wmhOMQ0hDiw=="], - "strnum": ["strnum@2.5.1", "", { "dependencies": { "anynum": "^1.0.1" } }, "sha512-UM4nTLWzQiDBseVxUGxN0wJzIk0UU89Qi7pKXz9qISo+lhviJikTuikBsK/oFRlpvYHvSdz0TVoLyQ+sEpYwxA=="], + "strnum": ["strnum@2.3.0", "", {}, "sha512-ums3KNd42PGyx5xaoVTO1mjU1bH3NpY4vsrVlnv9PNGqQj8wd7rJ6nEypLrJ7z5vxK5RP0yMLo6J/Gsm62DI5Q=="], "stubborn-fs": ["stubborn-fs@2.0.0", "", { "dependencies": { "stubborn-utils": "1.0.2" } }, "sha512-Y0AvSwDw8y+nlSNFXMm2g6L51rBGdAQT20J3YSOqxC53Lo3bjWRtr2BKcfYoAf352WYpsZSTURrA0tqhfgudPA=="], @@ -1288,7 +1280,7 @@ "wsl-utils": ["wsl-utils@0.1.0", "", { "dependencies": { "is-wsl": "3.1.0" } }, "sha512-h3Fbisa2nKGPxCpm89Hk33lBLsnaGBvctQopaBSOW/uIs6FTe1ATyAnKFJrzVs9vpGdsTe73WF3V4lIsk4Gacw=="], - "xml-naming": ["xml-naming@0.3.0", "", {}, "sha512-ghig2TBE/H11aOVgmahA3MhimvkBr6JIYknH/Dhdk10nXwdbIqBJsbfMxpvFPG8bAw77gN29aQWvKpmVoPlvPQ=="], + "xml-naming": ["xml-naming@0.1.0", "", {}, "sha512-k8KO9hrMyNk6tUWqUfkTEZbezRRpONVOzUTnc97VnCvyj6Tf9lyUR9EDAIeiVLv56jsMcoXEwjW8Kv5yPY52lw=="], "xmlhttprequest-ssl": ["xmlhttprequest-ssl@2.1.2", "", {}, "sha512-TEU+nJVUUnA4CYJFLvK5X9AOeH4KvDvhIfm0vV1GaQRtchnG0hgK5p8hw/xjv8cunWYCsiPCSDzObPyhEwq3KQ=="], @@ -1304,8 +1296,6 @@ "@aws-sdk/xml-builder/fast-xml-parser": ["fast-xml-parser@5.2.5", "", { "dependencies": { "strnum": "2.1.1" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-pfX9uG9Ki0yekDHx2SiuRIyFdyAr1kMIMitPvb0YBo8SUfKvia7w7FIyd/l6av85pFYRhZscS75MwMnbvY+hcQ=="], - "@azure/core-xml/fast-xml-parser": ["fast-xml-parser@5.8.0", "", { "dependencies": { "@nodable/entities": "^2.1.0", "fast-xml-builder": "^1.2.0", "path-expression-matcher": "^1.5.0", "strnum": "^2.3.0", "xml-naming": "^0.1.0" }, "bin": { "fxparser": "src/cli/cli.js" } }, "sha512-6bIM7fsJxeo3uXv7OncQYsBAMPJ7V16Slahl/6M98C/i2q+vB1+4a0MtrvYwDFEUrwDSbAmeLDRXsOBwrL7yAg=="], - "@esbuild-kit/core-utils/esbuild": ["esbuild@0.18.20", "", { "optionalDependencies": { "@esbuild/android-arm": "0.18.20", "@esbuild/android-arm64": "0.18.20", "@esbuild/android-x64": "0.18.20", "@esbuild/darwin-arm64": "0.18.20", "@esbuild/darwin-x64": "0.18.20", "@esbuild/freebsd-arm64": "0.18.20", "@esbuild/freebsd-x64": "0.18.20", "@esbuild/linux-arm": "0.18.20", "@esbuild/linux-arm64": "0.18.20", "@esbuild/linux-ia32": "0.18.20", "@esbuild/linux-loong64": "0.18.20", "@esbuild/linux-mips64el": "0.18.20", "@esbuild/linux-ppc64": "0.18.20", "@esbuild/linux-riscv64": "0.18.20", "@esbuild/linux-s390x": "0.18.20", "@esbuild/linux-x64": "0.18.20", "@esbuild/netbsd-x64": "0.18.20", "@esbuild/openbsd-x64": "0.18.20", "@esbuild/sunos-x64": "0.18.20", "@esbuild/win32-arm64": "0.18.20", "@esbuild/win32-ia32": "0.18.20", "@esbuild/win32-x64": "0.18.20" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-ceqxoedUrcayh7Y7ZX6NdbbDzGROiyVBgC4PriJThBKSVPWnnFHZAkfI1lJT8QFkOwH4qOS2SJkS4wvpGl8BpA=="], "@isaacs/cliui/string-width": ["string-width@5.1.2", "", { "dependencies": { "eastasianwidth": "0.2.0", "emoji-regex": "9.2.2", "strip-ansi": "7.1.2" } }, "sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA=="], @@ -1332,10 +1322,6 @@ "execa/signal-exit": ["signal-exit@3.0.7", "", {}, "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ=="], - "fast-xml-builder/path-expression-matcher": ["path-expression-matcher@1.5.0", "", {}, "sha512-cbrerZV+6rvdQrrD+iGMcZFEiiSrbv9Tfdkvnusy6y0x0GKBXREFg/Y65GhIfm0tnLntThhzCnfKwp1WRjeCyQ=="], - - "fast-xml-builder/xml-naming": ["xml-naming@0.1.0", "", {}, "sha512-k8KO9hrMyNk6tUWqUfkTEZbezRRpONVOzUTnc97VnCvyj6Tf9lyUR9EDAIeiVLv56jsMcoXEwjW8Kv5yPY52lw=="], - "fix-dts-default-cjs-exports/magic-string": ["magic-string@0.30.19", "", { "dependencies": { "@jridgewell/sourcemap-codec": "1.5.5" } }, "sha512-2N21sPY9Ws53PZvsEpVtNuSW+ScYbQdp4b9qUaL+9QkHUrGFKo56Lg9Emg5s9V/qrtNBmiR01sYhUOwu3H+VOw=="], "micromatch/picomatch": ["picomatch@2.3.1", "", {}, "sha512-JU3teHTNjmE2VCGFzuY8EXzCDVwEqB2a8fsIvwaStHhAWJEeVd1o1QD80CU6+ZdEXXSLbSsuLwJjkCBWqRQUVA=="], @@ -1396,14 +1382,6 @@ "@aws-sdk/xml-builder/fast-xml-parser/strnum": ["strnum@2.1.1", "", {}, "sha512-7ZvoFTiCnGxBtDqJ//Cu6fWtZtc7Y3x+QOirG15wztbdngGSkht27o2pyGWrVy0b4WAy3jbKmnoK6g5VlVNUUw=="], - "@azure/core-xml/fast-xml-parser/@nodable/entities": ["@nodable/entities@2.1.1", "", {}, "sha512-Pig3HxDIoMgjdEH8OCf/dkcTmLFjJRjWuq8jSnklu284/TKOPibSRERmOykiwmyXTtv61mP+44f3GMx0tLAyjg=="], - - "@azure/core-xml/fast-xml-parser/path-expression-matcher": ["path-expression-matcher@1.5.0", "", {}, "sha512-cbrerZV+6rvdQrrD+iGMcZFEiiSrbv9Tfdkvnusy6y0x0GKBXREFg/Y65GhIfm0tnLntThhzCnfKwp1WRjeCyQ=="], - - "@azure/core-xml/fast-xml-parser/strnum": ["strnum@2.3.0", "", {}, "sha512-ums3KNd42PGyx5xaoVTO1mjU1bH3NpY4vsrVlnv9PNGqQj8wd7rJ6nEypLrJ7z5vxK5RP0yMLo6J/Gsm62DI5Q=="], - - "@azure/core-xml/fast-xml-parser/xml-naming": ["xml-naming@0.1.0", "", {}, "sha512-k8KO9hrMyNk6tUWqUfkTEZbezRRpONVOzUTnc97VnCvyj6Tf9lyUR9EDAIeiVLv56jsMcoXEwjW8Kv5yPY52lw=="], - "@esbuild-kit/core-utils/esbuild/@esbuild/android-arm": ["@esbuild/android-arm@0.18.20", "", { "os": "android", "cpu": "arm" }, "sha512-fyi7TDI/ijKKNZTUJAQqiG5T7YjJXgnzkURqmGj13C6dCqckZBLdl4h7bkhHt/t0WP+zO9/zwroDvANaOqO5Sw=="], "@esbuild-kit/core-utils/esbuild/@esbuild/android-arm64": ["@esbuild/android-arm64@0.18.20", "", { "os": "android", "cpu": "arm64" }, "sha512-Nz4rJcchGDtENV0eMKUNa6L12zz2zBDXuhj/Vjh18zGqB44Bi7MBMSXjgunJgjRhCmKOjnPuZp4Mb6OKqtMHLQ=="], diff --git a/drizzle/0030_people_cleanup.sql b/drizzle/0030_people_cleanup.sql new file mode 100644 index 0000000..cffe06e --- /dev/null +++ b/drizzle/0030_people_cleanup.sql @@ -0,0 +1,11 @@ +ALTER TABLE "people_files" DISABLE ROW LEVEL SECURITY;--> statement-breakpoint +ALTER TABLE "people_receipt_requests" DISABLE ROW LEVEL SECURITY;--> statement-breakpoint +ALTER TABLE "people_receipts" DISABLE ROW LEVEL SECURITY;--> statement-breakpoint +DROP TABLE "people_files" CASCADE;--> statement-breakpoint +DROP TABLE "people_receipt_requests" CASCADE;--> statement-breakpoint +DROP TABLE "people_receipts" CASCADE;--> statement-breakpoint +ALTER TABLE "people_identities" DROP CONSTRAINT "people_identities_member_number_unique";--> statement-breakpoint +ALTER TABLE "people_identities" DROP COLUMN "member_number";--> statement-breakpoint +-- The People records hold only test data shaped for the removed features (PoliNetworkOrg/backend#100): start empty. +DELETE FROM "people_identities";--> statement-breakpoint +DELETE FROM "people_records"; \ No newline at end of file diff --git a/drizzle/meta/0030_snapshot.json b/drizzle/meta/0030_snapshot.json new file mode 100644 index 0000000..eb24f93 --- /dev/null +++ b/drizzle/meta/0030_snapshot.json @@ -0,0 +1,2715 @@ +{ + "id": "306ccd97-46c8-4260-93ca-f992b9fed731", + "prevId": "78ed20e8-993e-4903-b11d-50c1be0e7cdb", + "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_identities": { + "name": "people_identities", + "schema": "", + "columns": { + "person_id": { + "name": "person_id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "account_sub": { + "name": "account_sub", + "type": "text", + "primaryKey": false, + "notNull": false + }, + "telegram_id": { + "name": "telegram_id", + "type": "text", + "primaryKey": false, + "notNull": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": { + "people_identities_account_sub_unique": { + "name": "people_identities_account_sub_unique", + "nullsNotDistinct": false, + "columns": [ + "account_sub" + ] + }, + "people_identities_telegram_id_unique": { + "name": "people_identities_telegram_id_unique", + "nullsNotDistinct": false, + "columns": [ + "telegram_id" + ] + } + }, + "policies": {}, + "checkConstraints": {}, + "isRLSEnabled": false + }, + "public.people_records": { + "name": "people_records", + "schema": "", + "columns": { + "id": { + "name": "id", + "type": "text", + "primaryKey": true, + "notNull": true + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true + }, + "data": { + "name": "data", + "type": "jsonb", + "primaryKey": false, + "notNull": true + } + }, + "indexes": { + "people_records_kind_idx": { + "name": "people_records_kind_idx", + "columns": [ + { + "expression": "kind", + "isExpression": false, + "asc": true, + "nulls": "last" + } + ], + "isUnique": false, + "concurrently": false, + "method": "btree", + "with": {} + } + }, + "foreignKeys": {}, + "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 1a84cc5..c438380 100644 --- a/drizzle/meta/_journal.json +++ b/drizzle/meta/_journal.json @@ -211,6 +211,13 @@ "when": 1793043027659, "tag": "0029_remove_audit_admin_id", "breakpoints": true + }, + { + "idx": 30, + "version": "7", + "when": 1793284579739, + "tag": "0030_people_cleanup", + "breakpoints": true } ] } \ No newline at end of file diff --git a/package.json b/package.json index e1659e4..169f800 100644 --- a/package.json +++ b/package.json @@ -56,8 +56,6 @@ "@trpc/server": "11.5.1", "croner": "^9.1.0", "drizzle-orm": "^0.44.7", - "fast-xml-parser": "^5.11.2", - "fflate": "^0.8.3", "hono": "^4.11.6", "nanoid": "^5.1.6", "node-html-parser": "^7.0.2", diff --git a/src/cron.ts b/src/cron.ts index 816e0ae..9d01bb6 100644 --- a/src/cron.ts +++ b/src/cron.ts @@ -28,9 +28,9 @@ export function cron() { new Cron("0 * * * * *", async () => { try { const { people } = await import("./people") - await people.sweep() + await people.deliverPending() } catch (err) { - logger.error(err, "[CRON] People sweep") + logger.error(err, "[CRON] People mail outbox") } }) } diff --git a/src/db/schema/people/index.ts b/src/db/schema/people/index.ts index 6fc7adc..cf8cc24 100644 --- a/src/db/schema/people/index.ts +++ b/src/db/schema/people/index.ts @@ -1,15 +1,8 @@ -import { customType, index, jsonb, text, timestamp, uniqueIndex, uuid } from "drizzle-orm/pg-core" -import type { PeopleState, StoredReceipt } from "@/people/types" +import { index, jsonb, text } from "drizzle-orm/pg-core" +import type { PeopleState } from "@/people/types" import { createTable } from "../create-table" -import { requests } from "../esign/esign" -const bytea = customType<{ data: Uint8Array; driverData: Buffer }>({ - dataType: () => "bytea", - toDriver: (value) => Buffer.from(value), - fromDriver: (value) => new Uint8Array(value), -}) - -/** Small association metadata; files are separate so reading a roster never loads document bytes. */ +/** Small association metadata: one JSON row per person, outbox message or counter. */ export const records = createTable.people( "records", { @@ -20,51 +13,14 @@ export const records = createTable.people( (t) => [index("people_records_kind_idx").on(t.kind)] ) -/** Unique identity and register constraints are relational, independent of the JSON projection. */ +/** Unique identity constraints are relational, independent of the JSON projection. */ export const identities = createTable.people("identities", { personId: text("person_id").primaryKey(), accountSub: text("account_sub").unique(), - memberNumber: text("member_number").unique(), telegramId: text("telegram_id").unique(), }) -export const files = createTable.people("files", { - id: text().primaryKey(), - fileName: text("file_name").notNull(), - contentType: text("content_type").notNull(), - content: bytea().notNull(), - expiresAt: timestamp("expires_at", { withTimezone: true }), -}) - -/** Receipt numbers and active request associations survive retries, decline and voiding. */ -export const receipts = createTable.people("receipts", { - id: text().primaryKey(), - number: text().notNull().unique(), - requestId: uuid("request_id") - .references(() => requests.id, { onDelete: "restrict" }) - .unique(), - data: jsonb().$type().notNull(), -}) - -export const receiptRequests = createTable.people( - "receipt_requests", - { - requestId: uuid("request_id") - .primaryKey() - .references(() => requests.id, { onDelete: "restrict" }), - receiptId: text("receipt_id") - .notNull() - .references(() => receipts.id, { onDelete: "restrict" }), - officerSub: text("officer_sub").notNull(), - originalHash: text("original_hash").notNull(), - }, - (t) => [uniqueIndex("people_receipt_request_identity_idx").on(t.receiptId, t.requestId)] -) - export const schema = { peopleRecords: records, peopleIdentities: identities, - peopleFiles: files, - peopleReceipts: receipts, - peopleReceiptRequests: receiptRequests, } diff --git a/src/emails/mailer.tsx b/src/emails/mailer.tsx index f85d993..9211439 100644 --- a/src/emails/mailer.tsx +++ b/src/emails/mailer.tsx @@ -121,27 +121,12 @@ export async function sendSignedDocumentEmail( } /** People retains the provider's error and records a stable Message-ID for delivery reconciliation. */ -export async function sendPeopleEmail(input: { - id: string - to: string - subject: string - text: string - attachment: { fileName: string; contentType: string; content: Uint8Array } | null -}) { +export async function sendPeopleEmail(input: { id: string; to: string; subject: string; text: string }) { const component =
{input.text}
- const attachments = input.attachment - ? [ - { - filename: input.attachment.fileName, - contentType: input.attachment.contentType, - content: input.attachment.content, - }, - ] - : [] if (env.NODE_ENV === "development" && env.USE_DEV_MAILER) { - await devSendMail(input.to, input.subject, component, attachments) + await devSendMail(input.to, input.subject, component) } else { - await azureSendEmail(input.to, input.subject, component, attachments, { + await azureSendEmail(input.to, input.subject, component, [], { throwOnError: true, messageId: ``, }) diff --git a/src/env.ts b/src/env.ts index 7eea5a0..4c002ae 100644 --- a/src/env.ts +++ b/src/env.ts @@ -1,6 +1,5 @@ import { createEnv } from "@t3-oss/env-core" import { z } from "zod" -import { isValidIban } from "./people/iban" const PORT = 3000 const NODE_ENV = z.enum(["development", "production", "test"]) @@ -79,29 +78,6 @@ export const env = createEnv({ /** OCSP for CIE certificates: require (refuse when unknown), prefer (refuse only revoked), off. */ ESIGN_REVOCATION: z.enum(["require", "prefer", "off"]).default("prefer"), - // People configuration is backend-owned; no browser can choose officers, bank details or receipt identity. - PEOPLE_PRESIDENT_ID: z - .string() - .regex(/^P-\d{4}$/) - .optional(), - PEOPLE_VICE_PRESIDENT_ID: z - .string() - .regex(/^P-\d{4}$/) - .optional(), - PEOPLE_FEE_CENTS: z.coerce.number().int().min(1).max(100_000).default(1000), - PEOPLE_BENEFICIARY: z.string().max(200).default("PoliNetwork APS"), - PEOPLE_IBAN: z - .string() - .regex(/^[A-Z]{2}\d{2}[A-Z0-9]{11,30}$/) - .refine(isValidIban, "PEOPLE_IBAN must have a valid country length and checksum") - .optional(), - PEOPLE_LEGAL_NAME: z.string().max(200).optional(), - PEOPLE_ADDRESS: z.string().max(300).optional(), - PEOPLE_TAX_CODE: z - .string() - .regex(/^\d{11}$/) - .optional(), - // PoliNetwork IdP (RFC v3 §6, §12). Token authentication is enabled when IDP_PUBLIC_URL and // OAUTH_BACKEND_RESOURCE_URI are set; snapshot pulls also need the internal resource and the // backend client's credentials. Without them every permission check denies. diff --git a/src/esign/index.ts b/src/esign/index.ts index eb580bc..e3970a4 100644 --- a/src/esign/index.ts +++ b/src/esign/index.ts @@ -5,8 +5,6 @@ import { sendRequestUpdateEmail, sendSignatureRequestEmail, sendSignedDocumentEm import { env } from "@/env" import { idp } from "@/idp" import { logger } from "@/logger" -import { eligibleAtCommit, receiptEligibility, receiptVisibility } from "@/people" -import { completeReceiptSignature, guardReceiptSignature } from "@/people/store-pg" import { createGraphDrive } from "./drive/graph" import { createMockDrive } from "./drive/mock" import { type Access, type AccessCatalog, createEsignService } from "./service" @@ -42,12 +40,7 @@ function catalog(): AccessCatalog { } export const esign = createEsignService({ - store: createPgStore(DB, { - beforeSignature: (tx, commit) => guardReceiptSignature(tx, commit, eligibleAtCommit), - afterSignature: completeReceiptSignature, - }), - receiptEligible: receiptEligibility, - receiptCanView: receiptVisibility, + store: createPgStore(DB), directory: idp?.directory ?? undefined, drives: resolveDrives(), mailer: { diff --git a/src/esign/service.ts b/src/esign/service.ts index 95c58c4..0ec0630 100644 --- a/src/esign/service.ts +++ b/src/esign/service.ts @@ -3,6 +3,7 @@ import { outdatedAgent } from "./agent-version" import { type Drive, DriveError, MAX_PDF_BYTES } from "./drive/types" import { EsignError } from "./errors" import { identityOf, titleCase } from "./identity" +import { assertSignatureOnlyUpdate } from "./pdf/diff" import { PdfError } from "./pdf/incremental" import { inspectPdf, type PdfInfo } from "./pdf/inspect" import { finalizeSignature, type PreparedSignature, prepareSignature, SignatureError } from "./pdf/pades" @@ -24,10 +25,9 @@ import type { } from "./store" import { cieChain } from "./trust" import { checkRevocation, type RevocationResult } from "./trust/ocsp" -import { inspectSignedUpload, validateUploadedRevision } from "./upload" /** Who is calling, and what the IdP lets them do. */ -export type Caller = { sub: string; canManage: boolean; canManageDrives?: boolean; peopleManual?: boolean } +export type Caller = { sub: string; canManage: boolean; canManageDrives?: boolean } /** A dashboard user's roles and permissions, as the IdP reports them. */ export type Access = { roles: string[]; permissions: string[] } @@ -92,9 +92,6 @@ type Logger = { } export type ServiceOptions = { - /** Rechecked from People and the live permission snapshot, including agent completion without a browser. */ - receiptEligible?: (requestId: string, sub: string, requireEsign: boolean) => Promise - receiptCanView?: (receiptId: string, sub: string) => Promise store: EsignStore /** Registered IdP users, including people who have not opened Signatures yet. */ directory?: () => Promise<{ sub: string; name: string; email: string | null }[]> @@ -323,16 +320,14 @@ export function createEsignService(options: ServiceOptions) { } /** Its creator and signers, and managers allowed on every drive it uses. */ - async function canView(rules: Rules, caller: Caller, request: SigningRequest) { - if (request.peopleReceipt) - return (await options.receiptCanView?.(request.peopleReceipt.receiptId, caller.sub)) === true + function canView(rules: Rules, caller: Caller, request: SigningRequest) { if (request.createdBySub === caller.sub || request.signers.some((s) => s.sub === caller.sub)) return true return caller.canManage && request.drives.every((d) => mayRequest(rules, caller, d)) } async function requestFor(caller: Caller, id: string): Promise { const request = await store.getRequest(id) - if (!request || !(await canView(await accessRules(), caller, request))) + if (!request || !canView(await accessRules(), caller, request)) throw new EsignError("not_found", "Request not found") return request } @@ -374,10 +369,7 @@ export function createEsignService(options: ServiceOptions) { ...request, signers, turn, - myTurn: - turn.includes(caller.sub) && - !signers.some((s) => s.sub === caller.sub && s.lostAccess) && - (!request.peopleReceipt || (await options.receiptEligible?.(request.id, caller.sub, true)) === true), + myTurn: turn.includes(caller.sub) && !signers.some((s) => s.sub === caller.sub && s.lostAccess), signedCount: request.signers.filter((s) => s.status === "signed").length, createdByName: await profileName(request.createdBySub), } @@ -458,17 +450,16 @@ export function createEsignService(options: ServiceOptions) { accessRules(), options.directory ? options.directory() : store.listProfiles(), ]) - const allowed = await Promise.all( - people.map(async (p) => { - const held = options.access?.(p.sub)?.permissions ?? [] - return ( - held.includes(SIGN) && - held.includes(MANAGE) && - (await canView(rules, { sub: p.sub, canManage: true }, request)) - ) - }) + return new Map( + people + .filter((p) => { + const held = options.access?.(p.sub)?.permissions ?? [] + return ( + held.includes(SIGN) && held.includes(MANAGE) && canView(rules, { sub: p.sub, canManage: true }, request) + ) + }) + .map((p) => [p.sub, { name: p.name, email: p.email }]) ) - return new Map(people.filter((_, i) => allowed[i]).map((p) => [p.sub, { name: p.name, email: p.email }])) } catch (error) { logger.error({ error, requestId: request.id }, "[ESIGN] cannot list who may retry a delivery") return new Map() @@ -571,11 +562,6 @@ export function createEsignService(options: ServiceOptions) { for (const item of items) { const request = await requestFor(caller, item.requestId) assertInProgress(request) - if (request.peopleReceipt) { - if (item.places !== undefined) throw new EsignError("forbidden", "Receipt signature placement is fixed") - if (!(await options.receiptEligible?.(request.id, caller.sub, true))) - throw new EsignError("forbidden", "This receipt is not assigned to you") - } const signer = turnOf(request).find((s) => s.sub === caller.sub) if (!signer) throw new EsignError("forbidden", `It is not your turn to sign “${request.title}”`) const denied = request.drives.find((d) => !maySign(rules, caller.sub, d)) @@ -713,8 +699,6 @@ export function createEsignService(options: ServiceOptions) { const request = await store.getRequest(job.requestId) const signer = request?.signers.find((s) => s.id === job.signerId) if (!request || !signer) throw new EsignError("ticket_invalid", "This signing link is not valid") - if (request.peopleReceipt && !(await options.receiptEligible?.(request.id, job.sub, true))) - throw new EsignError("forbidden", "This receipt is no longer assigned to you") if (request.status !== "in_progress" || signer.status !== "pending") throw new EsignError("job_done", "This request no longer needs your signature") const current = await store.latestDocument(request.id) @@ -804,8 +788,6 @@ export function createEsignService(options: ServiceOptions) { identity: ReturnType method: "agent" | "upload" revocation: RevocationResult | null - receiptEnvelope?: { content: Uint8Array; fileName: string } - receiptManual?: boolean /** The signer's last place: the signer is done. Otherwise the job moves on to the next place. */ final: boolean }) { @@ -813,8 +795,6 @@ export function createEsignService(options: ServiceOptions) { const remaining = request.signers.filter((s) => s.status === "pending" && (s.id !== signer.id || !final)).length const inTurnBefore = new Set(turnOf(request).map((s) => s.sub)) const result = await store.commitSignature({ - receiptEnvelope: input.receiptEnvelope, - receiptManual: input.receiptManual, jobId: job.id, requestId: request.id, baseVersion: job.baseVersion, @@ -874,48 +854,7 @@ export function createEsignService(options: ServiceOptions) { return { status: "completed" as const, request: { status: updated?.status ?? request.status, remaining } } } - async function validateUploadIdentity(sub: string, cert: X509Certificate) { - const at = now() - if (at < new Date(cert.validFrom) || at > new Date(cert.validTo)) - throw new EsignError("certificate_invalid", "The CIE certificate is expired") - const uploadTrust = (options.trust ?? cieChain)(cert, at) - if (!uploadTrust.trusted && !options.allowTestCertificates) - throw new EsignError("certificate_invalid", "The file was not signed with a CIE") - const identity = identityOf(cert) - if (!identity.fiscalCode && !options.allowTestCertificates) - throw new EsignError("certificate_invalid", "The certificate carries no fiscal code") - const revocation = await revocationOf(cert, uploadTrust.issuer) - const profile = await store.getProfile(sub) - if (profile?.fiscalCode && identity.fiscalCode && profile.fiscalCode !== identity.fiscalCode) - throw new EsignError("signer_mismatch", `This CIE does not belong to ${profile?.name ?? sub}`) - - return { identity, revocation } - } - - async function verifyUpload(caller: Caller, requestId: string, bytes: Uint8Array) { - const request = await requestFor(caller, requestId) - if (!turnOf(request).some((s) => s.sub === caller.sub)) - throw new EsignError("forbidden", "It is not your turn to sign") - if (request.peopleReceipt && !(await options.receiptEligible?.(request.id, caller.sub, !caller.peopleManual))) - throw new EsignError("forbidden", "This receipt is not assigned to you") - const current = await store.latestDocument(requestId) - if (!current) throw new EsignError("not_found", "Document not found") - if (bytes.length > MAX_PDF_BYTES) throw new EsignError("pdf_invalid", "The file is larger than 30 MB") - const checked = await validateUploadedRevision(current.content, bytes, !!request.peopleReceipt) - return { ...checked, ...(await validateUploadIdentity(caller.sub, checked.certificate)) } - } - return { - async inspectUpload(sub: string, bytes: Uint8Array) { - if (bytes.length > MAX_PDF_BYTES) throw new EsignError("pdf_invalid", "The file is too large") - const inspected = await inspectSignedUpload(bytes) - const verified = await validateUploadIdentity(sub, inspected.certificate) - return { signer: verified.identity.name } - }, - async verifyUpload(caller: Caller, requestId: string, bytes: Uint8Array) { - const result = await verifyUpload(caller, requestId, bytes) - return { signer: result.identity.name, content: bytes } - }, /** The drives the caller may request signatures with. */ async drivesFor(caller: Caller) { const rules = await accessRules() @@ -1172,8 +1111,7 @@ export function createEsignService(options: ServiceOptions) { scope === "inbox" ? { awaiting: caller.sub } : { involving: scope === "all" ? undefined : caller.sub } ) const rules = await accessRules() - const allowed = await Promise.all(requests.map((r) => canView(rules, caller, r))) - const visible = requests.filter((_, i) => allowed[i]) + const visible = requests.filter((r) => canView(rules, caller, r)) const views = await Promise.all(visible.map((r) => view(caller, r, rules))) // A signer who may no longer sign a drive's documents can't act on them: they stay under Requests only. return scope === "inbox" ? views.filter((r) => r.myTurn) : views @@ -1206,8 +1144,7 @@ export function createEsignService(options: ServiceOptions) { }, async cancelRequest(caller: Caller, id: string) { - const request = await requestFor(caller, id) - if (request.peopleReceipt) throw new EsignError("forbidden", "Void receipts through People") + await requestFor(caller, id) if (!caller.canManage) throw new EsignError("forbidden", "Only managers can cancel requests") const result = await store.cancelRequest( id, @@ -1223,7 +1160,6 @@ export function createEsignService(options: ServiceOptions) { /** Deletes a finished request and everything recorded about it, signed documents included. */ async deleteRequest(caller: Caller, id: string) { const request = await requestFor(caller, id) - if (request.peopleReceipt) throw new EsignError("forbidden", "Receipt requests are retained permanently") if (!caller.canManage) throw new EsignError("forbidden", "Only managers can delete requests") if (request.status === "in_progress") throw new EsignError("conflict", "Cancel the request before deleting it") const result = await store.deleteRequest(id) @@ -1256,7 +1192,6 @@ export function createEsignService(options: ServiceOptions) { async retryDelivery(caller: Caller, id: string) { const request = await requestFor(caller, id) - if (request.peopleReceipt) throw new EsignError("forbidden", "Retry receipt delivery through People") if (!caller.canManage) throw new EsignError("forbidden", "Only managers can retry the delivery") if (request.status !== "completed" || request.delivery?.status !== "failed") throw new EsignError("conflict", "Nothing to retry") @@ -1473,11 +1408,49 @@ export function createEsignService(options: ServiceOptions) { throw new EsignError("conflict", "Someone is signing right now. Try again in a few minutes.") const current = await store.latestDocument(requestId) if (!current) throw new EsignError("not_found", "Document not found") - const verified = await verifyUpload(caller, requestId, bytes) - const { identity, revocation: uploadRevocation } = verified + if (bytes.length > MAX_PDF_BYTES) throw new EsignError("pdf_invalid", "The PDF is larger than 30 MB") + const mismatch = + "This file isn't the current version with your signature added. Download the PDF again, sign it, then upload it." + if ( + bytes.length <= current.size || + !Buffer.from(bytes.subarray(0, current.size)).equals(Buffer.from(current.content)) + ) + throw new EsignError("pdf_invalid", mismatch) + const sha256 = sha256Hex(bytes) + let check: PdfInfo + let before: PdfInfo + try { + ;[check, before] = await Promise.all([info(sha256, bytes), info(current.sha256, current.content)]) + } catch (error) { + if (error instanceof PdfError) throw new EsignError("pdf_invalid", error.message) + throw error + } + const last = check.signatures.at(-1) + if (check.signatures.length !== before.signatures.length + 1 || !last) + throw new EsignError("pdf_invalid", "The file must add exactly one signature") + if (!last.intact || !last.verified || !last.coversWholeDocument || !check.lastCertificate || !check.lastSignature) + throw new EsignError("signature_invalid", "The signature in the file is not valid") + try { + await assertSignatureOnlyUpdate(current.content, bytes, check.lastSignature) + } catch (error) { + if (error instanceof PdfError) throw new EsignError("pdf_invalid", error.message) + throw error + } + const cert = check.lastCertificate const at = now() - const signedPdf = verified.pdf - const sha256 = sha256Hex(signedPdf) + if (at < new Date(cert.validFrom) || at > new Date(cert.validTo)) + throw new EsignError("certificate_invalid", "The CIE certificate is expired") + const uploadTrust = (options.trust ?? cieChain)(cert, at) + if (!uploadTrust.trusted && !options.allowTestCertificates) + throw new EsignError("certificate_invalid", "The file was not signed with a CIE") + const identity = identityOf(cert) + if (!identity.fiscalCode && !options.allowTestCertificates) + throw new EsignError("certificate_invalid", "The certificate carries no fiscal code") + const uploadRevocation = await revocationOf(cert, uploadTrust.issuer) + const profile = await store.getProfile(signer.sub) + if (profile?.fiscalCode && identity.fiscalCode && profile.fiscalCode !== identity.fiscalCode) + throw new EsignError("signer_mismatch", `This CIE does not belong to ${signer.name}`) + // A one-off job carries the upload through the same atomic commit as the agent's signatures. for (const job of await store.openJobs(requestId)) await store.transitionJob(job.id, ["pending", "prepared"], { status: "cancelled" }) @@ -1497,9 +1470,7 @@ export function createEsignService(options: ServiceOptions) { signer, current, job, - signed: signedPdf, - receiptManual: caller.peopleManual === true, - receiptEnvelope: verified.envelope ? { content: bytes, fileName: `${current.fileName}.p7m` } : undefined, + signed: bytes, sha256, identity, method: "upload", diff --git a/src/esign/store-pg.ts b/src/esign/store-pg.ts index 25ba182..cf4cd68 100644 --- a/src/esign/store-pg.ts +++ b/src/esign/store-pg.ts @@ -2,8 +2,6 @@ import { and, asc, desc, eq, exists, inArray, isNull, lt, notExists, or, sql } f import { alias } from "drizzle-orm/pg-core" import type { DB as Database } from "@/db" import { schema } from "@/db/schema/esign" -import { receiptRequests, receipts } from "@/db/schema/people" -import type { Transaction } from "@/people/store-pg" import type { DocumentMeta, DocumentRecord, @@ -11,7 +9,6 @@ import type { Job, Profile, RequestEvent, - SignatureCommit, Signer, SigningRequest, } from "./store" @@ -85,13 +82,7 @@ const toSigner = (row: typeof signers.$inferSelect): Signer => ({ }) /** The e-signing store over the backend's Postgres. */ -export function createPgStore( - db: Db, - hooks: { - beforeSignature?: (tx: Transaction, commit: SignatureCommit) => Promise - afterSignature?: (tx: Transaction, commit: SignatureCommit) => Promise - } = {} -): EsignStore { +export function createPgStore(db: Db): EsignStore { async function attachSigners(rows: (typeof requests.$inferSelect)[]): Promise { if (rows.length === 0) return [] const all = await db @@ -104,21 +95,7 @@ export function createPgStore( ) ) .orderBy(asc(signers.position)) - const sources = await db - .select({ requestId: receiptRequests.requestId, receipt: receipts.data }) - .from(receiptRequests) - .innerJoin(receipts, eq(receipts.id, receiptRequests.receiptId)) - .where( - inArray( - receiptRequests.requestId, - rows.map((r) => r.id) - ) - ) return rows.map((r) => ({ - peopleReceipt: (() => { - const source = sources.find((s) => s.requestId === r.id)?.receipt - return source ? { receiptId: source.id, number: source.number, year: source.year } : null - })(), id: r.id, title: r.title, status: r.status, @@ -380,8 +357,6 @@ export function createPgStore( const [request] = await tx.select().from(requests).where(eq(requests.id, id)).for("update") if (!request || request.status === "in_progress" || request.delivery?.status === "pending") return "conflict" as const - const [receipt] = await tx.select().from(receiptRequests).where(eq(receiptRequests.requestId, id)).limit(1) - if (receipt) return "conflict" as const await tx.delete(requests).where(eq(requests.id, id)) return "ok" as const }) @@ -450,7 +425,6 @@ export function createPgStore( }, async commitSignature(commit) { return db.transaction(async (tx) => { - await hooks.beforeSignature?.(tx, commit) // Serializes signatures on one request. const [request] = await tx.select().from(requests).where(eq(requests.id, commit.requestId)).for("update") if (!request || request.status !== "in_progress") return "conflict" as const @@ -512,7 +486,6 @@ export function createPgStore( await tx.insert(events).values({ requestId: commit.requestId, actorSub: null, type: "completed" }) if (profile && !profile.fiscalCode && fiscalCode) await tx.update(profiles).set({ fiscalCode, certificateSubject }).where(eq(profiles.sub, commit.identity.sub)) - await hooks.afterSignature?.(tx, commit) return "ok" as const }) }, diff --git a/src/esign/store.ts b/src/esign/store.ts index 087513d..92a60a1 100644 --- a/src/esign/store.ts +++ b/src/esign/store.ts @@ -58,8 +58,6 @@ export type Signer = { } export type SigningRequest = { - /** Set only by the backend's persistent People receipt association. */ - peopleReceipt?: { receiptId: string; number: string; year: string } | null id: string title: string status: RequestStatus @@ -141,9 +139,6 @@ export type RequestFilter = { /** The signature commit: a new document version, the signer's and the job's new state, atomically. */ export type SignatureCommit = { - /** Original CAdES envelope, retained by People; the eSign revision shows its encapsulated PDF. */ - receiptEnvelope?: { content: Uint8Array; fileName: string } - receiptManual?: boolean jobId: string requestId: string baseVersion: number diff --git a/src/esign/upload.ts b/src/esign/upload.ts deleted file mode 100644 index f030974..0000000 --- a/src/esign/upload.ts +++ /dev/null @@ -1,80 +0,0 @@ -import type { X509Certificate } from "node:crypto" -import { EsignError } from "./errors" -import { CMS_OID, parseSignedData, sha256, verifyAttributesSignature } from "./pdf/cms" -import { children, oidString, read } from "./pdf/der" -import { assertSignatureOnlyUpdate } from "./pdf/diff" -import { PdfError } from "./pdf/incremental" -import { inspectPdf } from "./pdf/inspect" - -export type SignedUpload = { pdf: Uint8Array; certificate: X509Certificate; envelope: boolean } - -/** Cryptographic inspection shared by People previews and eSign's final manual-upload validation. */ -export async function inspectSignedUpload(bytes: Uint8Array): Promise { - if (Buffer.from(bytes.subarray(0, 5)).toString() === "%PDF-") { - const pdf = await inspectPdf(bytes) - const signature = pdf.signatures.at(-1) - if (!signature?.intact || !signature.verified || !signature.coversWholeDocument || !pdf.lastCertificate) - throw new EsignError("signature_invalid", "The file does not have a valid signature covering the entire PDF") - return { pdf: bytes, certificate: pdf.lastCertificate, envelope: false } - } - try { - const outer = read(bytes) - if (outer.raw.length !== bytes.length) throw new Error("Trailing data") - const signedData = children(children(children(outer)[1])[0]) - const encapsulated = children(signedData[2]) - if (oidString(encapsulated[0]) !== CMS_OID.data || encapsulated.length !== 2) - throw new Error("Missing encapsulated PDF") - const content = children(encapsulated[1]) - if (content.length !== 1 || content[0].tag !== 0x04) throw new Error("Expected DER octet string") - const pdf = content[0].value - if (Buffer.from(pdf.subarray(0, 5)).toString() !== "%PDF-") throw new Error("Envelope does not contain a PDF") - const cms = parseSignedData(bytes) - if ( - !cms.certificate || - !cms.signedAttrs || - !cms.messageDigest || - cms.digestAlgorithm !== CMS_OID.sha256 || - ![CMS_OID.rsaEncryption, CMS_OID.sha256WithRSA].includes(cms.signatureAlgorithm as typeof CMS_OID.rsaEncryption) - ) - throw new Error("Unsupported CMS signature") - if ( - !Buffer.from(cms.messageDigest).equals(Buffer.from(sha256(pdf))) || - !verifyAttributesSignature(cms.signedAttrs, cms.signature, new Uint8Array(cms.certificate.raw)) - ) - throw new Error("CMS signature mismatch") - return { pdf, certificate: cms.certificate, envelope: true } - } catch (error) { - throw new EsignError("signature_invalid", error instanceof Error ? error.message : "Invalid CMS envelope") - } -} - -export async function validateUploadedRevision( - original: Uint8Array, - bytes: Uint8Array, - allowEnvelope: boolean -): Promise { - const isPdf = Buffer.from(bytes.subarray(0, 5)).toString() === "%PDF-" - if ( - isPdf && - (bytes.length <= original.length || !Buffer.from(bytes.subarray(0, original.length)).equals(Buffer.from(original))) - ) - throw new EsignError("pdf_invalid", "The file is not the issued PDF with a signature added") - const signed = await inspectSignedUpload(bytes) - if (signed.envelope) { - if (!allowEnvelope || !Buffer.from(signed.pdf).equals(Buffer.from(original))) - throw new EsignError("pdf_invalid", "The signed envelope does not contain this issued receipt") - return signed - } - if (bytes.length <= original.length || !Buffer.from(bytes.subarray(0, original.length)).equals(Buffer.from(original))) - throw new EsignError("pdf_invalid", "The file is not the issued PDF with a signature added") - const [before, after] = await Promise.all([inspectPdf(original), inspectPdf(bytes)]) - if (after.signatures.length !== before.signatures.length + 1 || !after.lastSignature) - throw new EsignError("pdf_invalid", "The file must add exactly one signature") - try { - await assertSignatureOnlyUpdate(original, bytes, after.lastSignature) - } catch (error) { - if (error instanceof PdfError) throw new EsignError("pdf_invalid", error.message) - throw error - } - return signed -} diff --git a/src/idp/index.ts b/src/idp/index.ts index 48d1069..3f3dde5 100644 --- a/src/idp/index.ts +++ b/src/idp/index.ts @@ -17,9 +17,7 @@ import { dbPersistence } from "./persistence" /** The projection this backend reads from the IdP (RFC v3 §5.2). */ const PROJECTION = "backend" -const signerDirectory = z.array( - z.object({ sub: z.string(), name: z.string(), email: z.string().nullable(), emailVerified: z.boolean().optional() }) -) +const signerDirectory = z.array(z.object({ sub: z.string(), name: z.string(), email: z.string().nullable() })) function report(component: string) { return (error: unknown) => { diff --git a/src/people/azure-members.ts b/src/people/azure-members.ts deleted file mode 100644 index 5d94885..0000000 --- a/src/people/azure-members.ts +++ /dev/null @@ -1,78 +0,0 @@ -import { azureCredentials } from "@/azure/config" -import { azureDirectory } from "@/azure/directory" -import { IncompleteMemberError } from "@/azure/errors" -import { MAIL_DOMAIN, standardLocalPart } from "@/azure/mailbox" -import { currentMember, numberHolder, rememberNumber, serializeMemberWrite } from "@/azure/member-writes" -import type { CreatedMember } from "@/azure/types" -import { sendWelcomeEmail } from "@/emails/mailer" -import { env } from "@/env" -import { fail } from "./model" -import type { Person } from "./types" - -export async function provisionMember(person: Person, number: string) { - if (!azureCredentials && env.NODE_ENV === "production") - fail("PRECONDITION_FAILED", "Microsoft 365 provisioning is not configured") - const assocNumber = Number(number) - const created = await serializeMemberWrite(async () => { - const prior = await numberHolder(assocNumber) - if (prior) { - if (prior.id !== person.azureId || !prior.mail) - fail("CONFLICT", "Member number already belongs to a different Microsoft 365 account") - return { id: prior.id, mail: prior.mail, password: null } - } - if (person.azureId) fail("CONFLICT", "The linked Microsoft 365 account has a different member number") - const localPart = standardLocalPart(person.profile.firstName, person.profile.lastName) - if (!localPart) fail("BAD_REQUEST", "This name cannot form a standard Microsoft 365 address") - if (await azureDirectory.findByMail(`${localPart}@${MAIL_DOMAIN}`)) - fail("CONFLICT", "The Microsoft 365 address is already in use") - let member: CreatedMember - try { - member = await azureDirectory.createMember({ - firstName: person.profile.firstName, - lastName: person.profile.lastName, - assocNumber, - localPart, - }) - } catch (error) { - if (error instanceof IncompleteMemberError) rememberNumber(error.member, assocNumber, true) - throw error - } - rememberNumber( - { - id: member.id, - displayName: `${person.profile.firstName} ${person.profile.lastName}`, - givenName: person.profile.firstName, - mail: member.mail, - employeeId: number, - }, - assocNumber, - true - ) - return member - }) - if (created.password && person.profile.personalEmail) - await sendWelcomeEmail( - person.profile.personalEmail, - { email: created.mail, password: created.password }, - { firstName: person.profile.firstName, assocNumber } - ) - return { id: created.id, email: created.mail } -} - -export async function setMemberNumber(person: Person, number: string) { - const userId = person.azureId - if (!userId) fail("PRECONDITION_FAILED", "Microsoft 365 account is missing") - if (!azureCredentials && env.NODE_ENV === "production") fail("PRECONDITION_FAILED", "Microsoft 365 is not configured") - await serializeMemberWrite(async () => { - const member = await currentMember(userId) - if (!member) fail("PRECONDITION_FAILED", "The Microsoft 365 account no longer exists") - const assocNumber = Number(number) - const holder = await numberHolder(assocNumber) - if (holder && holder.id !== userId) - fail("CONFLICT", "Member number already belongs to another Microsoft 365 account") - if (member.employeeId === assocNumber.toString()) return - const result = await azureDirectory.setMemberNumber(userId, assocNumber) - if (result.error) fail("PRECONDITION_FAILED", result.error) - rememberNumber(member, assocNumber) - }) -} diff --git a/src/people/config.ts b/src/people/config.ts deleted file mode 100644 index 92f02cb..0000000 --- a/src/people/config.ts +++ /dev/null @@ -1,16 +0,0 @@ -import { env } from "@/env" -import type { PeopleConfig } from "./types" - -if (env.PEOPLE_PRESIDENT_ID && env.PEOPLE_PRESIDENT_ID === env.PEOPLE_VICE_PRESIDENT_ID) - throw new Error("The President and Vice-president must be different People records") - -export const peopleConfig: PeopleConfig = { - officers: { president: env.PEOPLE_PRESIDENT_ID ?? null, vicePresident: env.PEOPLE_VICE_PRESIDENT_ID ?? null }, - feeCents: env.PEOPLE_FEE_CENTS, - beneficiary: env.PEOPLE_BENEFICIARY, - iban: env.PEOPLE_IBAN ?? "", - legalName: env.PEOPLE_LEGAL_NAME ?? "", - address: env.PEOPLE_ADDRESS ?? "", - taxCode: env.PEOPLE_TAX_CODE ?? "", - dashboardUrl: env.ESIGN_DASHBOARD_URL.replace(/\/$/, ""), -} diff --git a/src/people/contract.ts b/src/people/contract.ts index f948ffd..df928dd 100644 --- a/src/people/contract.ts +++ b/src/people/contract.ts @@ -1,7 +1,7 @@ import { z } from "zod" /** - * Wire contract copied from PoliNetworkOrg/admin PR #100, commit 9d0c60b3ea7b57b9e4d97a8e2d53dadd7b098e89. + * Wire contract of the admin dashboard's People area (PoliNetworkOrg/admin). * The admin parses responses against these shapes. Keep input/output changes coordinated with that repository. */ @@ -28,38 +28,16 @@ export const COURSES = [ "Architettura", "Urbanistica", ] as const -export const MEMBER_STATUSES = ["active", "suspended", "expired", "former"] as const -export const FEE_STATUSES = ["due", "receipt", "paid", "unpaid"] as const -export const ACCOUNT_STATUSES = ["none", "invite", "linked", "review"] as const -export const CENSUS_ANSWERS = ["continues", "leaving"] as const -export const REVIEW_KINDS = ["telegram-conflict", "ask-to-be-added", "two-records", "not-me", "name-only"] as const -/** A receipt's pipeline: issued unsigned, signed by an officer, emailed to the member; or the email failed, or voided. */ -export const RECEIPT_STATUSES = ["toSign", "signed", "sent", "failed", "voided"] as const -export const PAYMENT_METHODS = ["transfer", "cash"] as const export const PHOTO_CONSENTS = ["granted", "denied", "revoked"] as const -/** Who signs a receipt: the President, or the Vice-president for the President's own. */ -export const SIGNERS = ["president", "vicePresident"] as const export const teamIdSchema = z.enum(TEAM_IDS) export const campusSchema = z.enum(CAMPUSES) -export const memberStatusSchema = z.enum(MEMBER_STATUSES) -export const feeStatusSchema = z.enum(FEE_STATUSES) -export const censusAnswerSchema = z.enum(CENSUS_ANSWERS) export type TeamId = z.infer export type Campus = z.infer -export type MemberStatus = z.infer -export type FeeStatus = z.infer -export type CensusAnswer = z.infer -export type AccountStatus = (typeof ACCOUNT_STATUSES)[number] -export type ReviewKind = (typeof REVIEW_KINDS)[number] -export type ReceiptStatus = (typeof RECEIPT_STATUSES)[number] -export type PaymentMethod = (typeof PAYMENT_METHODS)[number] export type PhotoConsent = (typeof PHOTO_CONSENTS)[number] -export type Signer = (typeof SIGNERS)[number] const personRefSchema = z.object({ id: z.string(), name: z.string() }) -const groupSchema = z.object({ chatId: z.string(), title: z.string() }) export const profileSchema = z.object({ firstName: z.string(), @@ -77,23 +55,11 @@ export const profileSchema = z.object({ studentRepresentative: z.string().nullable(), }) -export const membershipSchema = z.object({ - number: z.string(), - status: memberStatusSchema, - admittedOn: z.string(), - /** The current academic year's fee; `null` for former members. */ - fee: feeStatusSchema.nullable(), - m365Email: z.string(), -}) - export const adminRoleSchema = z.object({ status: z.enum(["active", "former"]), since: z.string(), endedOn: z.string().nullable(), endReason: z.string().nullable(), - /** Detected by the bot. */ - groups: z.array(groupSchema), - requested: z.array(groupSchema.extend({ requestedOn: z.string() })), availableAsCapo: z.boolean(), capoOfReference: personRefSchema.nullable(), /** Set when this person is a Capo Admin, e.g. "Ingegneria Informatica". */ @@ -115,16 +81,6 @@ export const teamMembershipSchema = z.object({ fields: teamFieldsSchema, }) -export const censusEntrySchema = z.object({ - year: z.string(), - /** `null`: expected, no answer yet. */ - answer: censusAnswerSchema.nullable(), - answeredOn: z.string().nullable(), - source: z.enum(["forms", "dashboard"]).nullable(), - declaredMember: z.boolean().nullable(), - reminders: z.number().int(), -}) - export const accountSchema = z.discriminatedUnion("status", [ z.object({ status: z.literal("none") }), z.object({ @@ -135,7 +91,6 @@ export const accountSchema = z.discriminatedUnion("status", [ sentBy: z.string(), }), z.object({ status: z.literal("linked"), email: z.string(), via: z.string(), linkedOn: z.string(), how: z.string() }), - z.object({ status: z.literal("review"), reviewId: z.string(), issue: z.string() }), ]) export const consentsSchema = z.object({ @@ -147,128 +102,36 @@ export const consentsSchema = z.object({ export const personRowSchema = z.object({ id: z.string(), profile: profileSchema, - /** `null` without `people:members:read`, except on the viewer's own record: `isMember` still says whether they are one. */ - member: membershipSchema.nullable(), - /** A current member: `member` set and not former. Always present. */ - isMember: z.boolean(), admin: adminRoleSchema.nullable(), teams: z.array(teamMembershipSchema), - census: z.array(censusEntrySchema), consents: consentsSchema, account: accountSchema, }) export const discrepancySchema = z.object({ - kind: z.enum(["declared-member", "telegram-mismatch", "needs-review", "admin-removal"]), + kind: z.enum(["telegram-mismatch", "needs-review"]), message: z.string(), suggestedTelegram: z.string().nullable(), }) export const activitySchema = z.object({ actor: z.string(), text: z.string(), at: z.string() }) -/** A transfer receipt the member uploaded, waiting for an admin. */ -export const feeUploadSchema = z.object({ - fileName: z.string(), - size: z.number().int(), - uploadedAt: z.string(), - /** As the member declared it. */ - transferDate: z.string(), - amountCents: z.number().int(), -}) - -/** The current fee year of one member: what is due, what was uploaded, rejected or paid. */ -export const feeDetailSchema = z.object({ - year: z.string(), - status: feeStatusSchema, - amountCents: z.number().int(), - dueOn: z.string(), - upload: feeUploadSchema.nullable(), - /** The last rejection, kept until the member uploads again. */ - rejection: z.object({ reason: z.string(), by: z.string(), at: z.string() }).nullable(), - payment: z - .object({ - paidOn: z.string(), - method: z.enum(PAYMENT_METHODS), - amountCents: z.number().int(), - transferDate: z.string().nullable(), - }) - .nullable(), - /** The last reminder email, automatic or sent by hand. */ - lastReminder: z.string().nullable(), -}) - -/** Returned as `request.peopleReceipt` by eSign list/get for a system-owned fee receipt. */ -export const receiptRequestSourceSchema = z.object({ - receiptId: z.string().min(1).max(128), - number: z.string().min(1).max(40), - year: z.string().regex(/^\d{4}\/\d{2}$/), -}) -export type ReceiptRequestSource = z.infer - -export const receiptSchema = z.object({ - id: z.string(), - /** "2026/042": the fee year's first calendar year and a sequence never reused. */ - number: z.string(), - /** The fee year, "2026/27". */ - year: z.string(), - person: personRefSchema, - memberNumber: z.string(), - amountCents: z.number().int(), - issuedOn: z.string(), - paidOn: z.string(), - method: z.enum(PAYMENT_METHODS), - transferDate: z.string().nullable(), - status: z.enum(RECEIPT_STATUSES), - signer: z.enum(SIGNERS), - signedBy: z.string().nullable(), - signedOn: z.string().nullable(), - sentAt: z.string().nullable(), - sentTo: z.string().nullable(), - /** Why the last email failed, while `failed`. */ - failure: z.string().nullable(), - voided: z.object({ reason: z.string(), by: z.string(), on: z.string() }).nullable(), -}) - -export const feesSchema = z.object({ - /** The current fee year; `null` for former members. */ - current: feeDetailSchema.nullable(), - /** Every receipt issued to the person, newest first. Receipts are never deleted, only voided. */ - receipts: z.array(receiptSchema), -}) - export const personRecordSchema = personRowSchema.extend({ /** `null` without `people:read`. */ notes: z.string().nullable(), discrepancies: z.array(discrepancySchema), activity: z.array(activitySchema), - /** `null` when the person was never a member, or without `people:members:read` (except on their own record). */ - fees: feesSchema.nullable(), }) export type Profile = z.infer -export type Membership = z.infer export type AdminRole = z.infer export type TeamFields = z.infer export type TeamMembership = z.infer -export type CensusEntry = z.infer export type Account = z.infer export type Consents = z.infer export type PersonRow = z.infer export type PersonRecord = z.infer export type Discrepancy = z.infer -export type FeeUpload = z.infer -export type FeeDetail = z.infer -export type Receipt = z.infer -export type Fees = z.infer - -/** Register rows and admission candidates, without volunteer, census or account-link details. */ -export const memberRegisterRowSchema = z.object({ - id: z.string(), - profile: profileSchema.pick({ firstName: true, lastName: true, personalEmail: true }), - member: membershipSchema.nullable(), - account: z.object({ status: z.enum(ACCOUNT_STATUSES) }), -}) -export type MemberRegisterRow = z.infer export const teamSummarySchema = z.object({ id: teamIdSchema, @@ -278,36 +141,6 @@ export const teamSummarySchema = z.object({ }) export type TeamSummary = z.infer -export const campaignSchema = z.object({ - id: z.string(), - year: z.string(), - status: z.enum(["open", "closed"]), - openedOn: z.string(), - closesOn: z.string(), - source: z.string(), - expected: z.number().int(), - continuing: z.number().int(), - leaving: z.number().int(), - noAnswer: z.number().int(), -}) -export type Campaign = z.infer - -export const campaignDetailSchema = z.object({ campaign: campaignSchema, people: z.array(personRowSchema) }) -export type CampaignDetail = z.infer - -export const censusAnswersSchema = z.array(z.object({ question: z.string(), answer: z.string() })) - -export const reviewSchema = z.object({ - id: z.string(), - kind: z.enum(REVIEW_KINDS), - since: z.string(), - account: z.object({ name: z.string(), email: z.string(), telegram: z.string().nullable(), via: z.string() }), - record: personRefSchema.nullable(), - other: personRefSchema.nullable(), - message: z.string().nullable(), -}) -export type Review = z.infer - export const inviteSchema = z.object({ personId: z.string(), name: z.string(), @@ -329,67 +162,9 @@ export const accountMatchSchema = z.object({ }) export type AccountMatch = z.infer -const importRowSchema = z.object({ - row: z.number().int(), - name: z.string(), - detail: z.string(), - answer: censusAnswerSchema.nullable(), -}) -export const IMPORT_TABS = [ - "newPeople", - "updates", - "duplicates", - "invalid", - "discrepancies", - "alreadyImported", -] as const -export type ImportTab = (typeof IMPORT_TABS)[number] - -export const importPreviewSchema = z.object({ - importId: z.string(), - fileName: z.string(), - rows: z.number().int(), - counts: z.object({ - newPeople: z.number().int(), - updates: z.number().int(), - duplicates: z.number().int(), - invalid: z.number().int(), - discrepancies: z.number().int(), - alreadyImported: z.number().int(), - leaving: z.number().int(), - }), - tabs: z.object({ - newPeople: z.array(importRowSchema), - updates: z.array(importRowSchema), - duplicates: z.array(importRowSchema), - invalid: z.array(importRowSchema), - discrepancies: z.array(importRowSchema), - alreadyImported: z.array(importRowSchema), - }), - duplicates: z.array( - z.object({ - pairId: z.string(), - row: z.number().int(), - recordId: z.string(), - fields: z.array(z.object({ label: z.string(), file: z.string(), record: z.string(), mono: z.boolean() })), - }) - ), - telegram: z.array( - z.object({ - rowId: z.string(), - name: z.string(), - username: z.string(), - suggestion: z.object({ telegramId: z.string(), name: z.string(), info: z.string() }).nullable(), - }) - ), -}) -export type ImportPreview = z.infer - export const capoAreaSchema = z.object({ scope: z.string(), - groups: z.array(groupSchema.extend({ admins: z.number().int().nullable() })), admins: z.array(personRowSchema), - requests: z.array(z.object({ id: z.string(), person: personRefSchema, group: groupSchema, requestedOn: z.string() })), }) export type CapoArea = z.infer @@ -405,25 +180,13 @@ const contactSchema = z.object({ role: z.enum(["capo", "lead", "hr"]), name: z.string(), telegram: z.string().nullable(), - email: z.string().nullable(), team: teamIdSchema.nullable(), }) -/** How a member pays: the bank details and the reference to write on the transfer. */ -export const feeInstructionsSchema = z.object({ - beneficiary: z.string(), - iban: z.string(), - reference: z.string(), -}) -export type FeeInstructions = z.infer - export const myAreaSchema = z.discriminatedUnion("state", [ z.object({ state: z.literal("linked"), person: personRecordSchema, - /** Set while the signed-in person is a current member. */ - feeInstructions: feeInstructionsSchema.nullable(), - campaign: z.object({ id: z.string(), year: z.string(), closesOn: z.string() }).nullable(), contacts: z.array(contactSchema), roster: z .object({ @@ -434,77 +197,15 @@ export const myAreaSchema = z.discriminatedUnion("state", [ name: z.string(), role: z.enum(["member", "lead"]), telegram: z.string().nullable(), - email: z.string().nullable(), }) ), }) .nullable(), }), - z.object({ - state: z.literal("match"), - candidate: z.object({ - id: z.string(), - name: z.string(), - course: z.string(), - year: z.string(), - campus: campusSchema, - roles: z.array(z.string()), - }), - reason: z.string(), - }), - z.object({ state: z.literal("none"), request: z.object({ sentOn: z.string() }).nullable() }), + z.object({ state: z.literal("none") }), ]) export type MyArea = z.infer -/** People › Receipts: one fee year's receipts and who signs them. */ -export const receiptsPageSchema = z.object({ - year: z.string(), - /** Fee years with receipts, newest first. */ - years: z.array(z.string()), - /** The signed-in person's office, when they hold `people:receipts:sign`; `null` otherwise. */ - viewerSigner: z.enum(SIGNERS).nullable(), - officers: z.object({ president: personRefSchema.nullable(), vicePresident: personRefSchema.nullable() }), - receipts: z.array(receiptSchema), -}) -export type ReceiptsPage = z.infer - -/** What Review receipt shows: the member and their current fee year. */ -export const feeReviewSchema = z.object({ - person: personRefSchema, - memberNumber: z.string(), - m365Email: z.string(), - fee: feeDetailSchema, - /** Earlier rejections this fee year, newest first. */ - rejections: z.array(z.object({ reason: z.string(), by: z.string(), at: z.string() })), - /** The number approving would issue. */ - nextReceipt: z.string(), -}) -export type FeeReview = z.infer - -/** A file passed through JSON: an uploaded transfer receipt, a receipt PDF or a ZIP of them. */ -export const fileSchema = z.object({ fileName: z.string(), contentType: z.string(), base64: z.string() }) -export type FilePayload = z.infer - -/** Signed files read by the backend, before anything is saved or sent. */ -export const signedUploadSchema = z.object({ - uploadId: z.string(), - files: z.array( - z.object({ - fileId: z.string(), - fileName: z.string(), - size: z.number().int(), - /** Matched by the receipt number in the file name; `null` when there is none, or no such receipt. */ - receiptId: z.string().nullable(), - /** A valid digital signature (PAdES in the PDF, or a CAdES .p7m envelope) and the name on its certificate. */ - signature: z.object({ valid: z.boolean(), signer: z.string().nullable() }), - }) - ), -}) -export type SignedUpload = z.infer - -export const sendResultSchema = z.object({ sent: z.number().int(), failed: z.number().int() }) -export const issuedSchema = z.object({ receipt: z.string() }) - /** The team-specific fields, in display order. */ export type TeamField = { key: string; label: string; kind: "text" | "multi"; mono?: boolean; options?: string[] } @@ -563,7 +264,6 @@ export const TEAMS = { export const personIdSchema = z.string().regex(/^P-\d{4}$/) const dateSchema = z.iso.date() const opaqueIdSchema = z.string().min(1).max(128) -const academicYearSchema = z.string().regex(/^\d{4}\/\d{2}$/) const reasonSchema = z.string().trim().min(1).max(500) /** Telegram's own rule: 5–32 letters, digits or underscores. Empty when unknown; a leading @ is dropped. */ export const TELEGRAM_USERNAME_PATTERN = /^@?[A-Za-z0-9_]{5,32}$/ @@ -572,9 +272,6 @@ const telegramUsernameSchema = z .trim() .refine((value) => value === "" || TELEGRAM_USERNAME_PATTERN.test(value), "Enter a valid Telegram username.") .transform((value) => value.replace(/^@/, "")) -/** Import decisions are keyed by the preview's own row and pair IDs. */ -const importDecisionKey = z.string().min(1).max(64) -const MAX_IMPORT_ROWS = 5000 export const personInputSchema = z.object({ firstName: z.string().trim().min(1).max(80), @@ -590,19 +287,6 @@ export const createPersonInputSchema = personInputSchema.extend({ admin: z.boole export const updatePersonInputSchema = personInputSchema.extend({ id: personIdSchema }) export const setNoteInputSchema = z.object({ id: personIdSchema, note: z.string().trim().max(2000) }) -export const createMemberInputSchema = z.object({ - personId: personIdSchema, - number: z.string().regex(/^\d{4}$/), - admittedOn: dateSchema, - fee: z.enum(["due", "paid"]), -}) -export const memberStatusInputSchema = z.object({ - personId: personIdSchema, - status: memberStatusSchema, - reason: z.string().trim().max(500), -}) -export const memberNumberInputSchema = z.object({ personId: personIdSchema, number: z.string().regex(/^\d{4}$/) }) - export const endAdminInputSchema = z.object({ personId: personIdSchema, reason: reasonSchema }) export const capoScopeInputSchema = z.object({ personId: personIdSchema, scope: z.string().trim().max(120).nullable() }) export const capoRefInputSchema = z.object({ personId: personIdSchema, capoId: personIdSchema.nullable() }) @@ -630,25 +314,6 @@ export const endTeamInputSchema = z.object({ note: z.string().trim().max(500), }) -export const campaignInputSchema = z.object({ campaignId: opaqueIdSchema }) -export const remindInputSchema = z.object({ campaignId: opaqueIdSchema, personId: personIdSchema.nullable() }) -export const answersInputSchema = z.object({ personId: personIdSchema, year: academicYearSchema }) -export const importCommitInputSchema = z.object({ - importId: opaqueIdSchema, - duplicates: z - .record(importDecisionKey, z.enum(["same", "different"])) - .refine((choices) => Object.keys(choices).length <= MAX_IMPORT_ROWS, "Too many decisions."), - telegram: z - .record(importDecisionKey, z.string().max(64).nullable()) - .refine((choices) => Object.keys(choices).length <= MAX_IMPORT_ROWS, "Too many decisions."), -}) - -export const resolveReviewInputSchema = z.object({ - reviewId: opaqueIdSchema, - resolution: z.string().min(1).max(64), - reason: reasonSchema, -}) -export const reviewInputSchema = z.object({ reviewId: opaqueIdSchema }) export const personRefInputSchema = z.object({ personId: personIdSchema }) export const searchAccountsInputSchema = z.object({ personId: personIdSchema, query: z.string().trim().max(120) }) export const linkAccountInputSchema = z.object({ @@ -657,108 +322,9 @@ export const linkAccountInputSchema = z.object({ reason: reasonSchema, }) -export const joinRequestInputSchema = z.object({ requestId: opaqueIdSchema }) - -export const askToBeAddedInputSchema = z.object({ - roles: z - .array(z.enum(["admin", "team", "member"])) - .min(1) - .max(3), - groupsOrTeam: z.string().trim().max(200), - telegramUsername: telegramUsernameSchema, -}) -export const answerCensusInputSchema = z.object({ - answer: censusAnswerSchema, - course: z.string().trim().min(1).max(120), - year: z.enum(YEARS), - campus: campusSchema, - keepGroups: z.array(z.string().max(120)).max(100), - keepTeams: z.array(teamIdSchema).max(TEAM_IDS.length), - reason: z.string().trim().max(200), - note: z.string().trim().max(500), -}) -export const CORRECTION_FIELDS = [ - "Personal email", - "Phone", - "Telegram username", - "Course", - "Year", - "Campus", - "Something else", -] as const -export type CorrectionField = (typeof CORRECTION_FIELDS)[number] -export const correctionInputSchema = z.object({ - field: z.enum(CORRECTION_FIELDS), - value: z.string().trim().min(1).max(200), - note: z.string().trim().max(500), -}) - -export const feePersonInputSchema = z.object({ personId: personIdSchema }) -export const rejectFeeInputSchema = z.object({ personId: personIdSchema, reason: reasonSchema }) -/** Amounts in cents: the fee is small, so anything above €1,000 is a typo. */ -const amountCentsSchema = z.number().int().min(1).max(100_000) -export const markPaidInputSchema = z.object({ - personId: personIdSchema, - paidOn: dateSchema, - amountCents: amountCentsSchema, - method: z.enum(PAYMENT_METHODS), - note: z.string().trim().max(500), -}) -export const feeRemindInputSchema = z.object({ personId: personIdSchema.nullable() }) -const receiptIdSchema = z.string().min(1).max(40) -/** The existing eSign agent accepts at most ten documents with one PIN. */ -export const RECEIPT_SIGN_BATCH = 10 -export const prepareReceiptSignaturesInputSchema = z.object({ - receiptIds: z - .array(receiptIdSchema) - .min(1) - .max(RECEIPT_SIGN_BATCH) - .refine((ids) => new Set(ids).size === ids.length, "Choose each receipt once."), -}) -export const receiptSignaturesSchema = z - .array( - z.object({ - receiptId: receiptIdSchema, - requestId: z.uuid(), - title: z.string().min(1).max(300), - }) - ) - .min(1) - .max(RECEIPT_SIGN_BATCH) - .refine( - (items) => - new Set(items.map((item) => item.receiptId)).size === items.length && - new Set(items.map((item) => item.requestId)).size === items.length, - "Each receipt must have its own signature request." - ) -export type PrepareReceiptSignaturesInput = z.infer -export type ReceiptSignature = z.infer[number] - -export const receiptInputSchema = z.object({ receiptId: receiptIdSchema }) -export const voidReceiptInputSchema = z.object({ receiptId: receiptIdSchema, reason: reasonSchema }) -export const receiptsInputSchema = z.object({ - year: z - .string() - .regex(/^\d{4}\/\d{2}$/) - .nullable(), -}) -/** At most one batch of signed files per upload. */ -export const MAX_SIGNED_FILES = 100 -export const sendSignedInputSchema = z.object({ - uploadId: z.string().min(1).max(64), - /** File → receipt, after the matches were checked and corrected. */ - assignments: z - .record(z.string().min(1).max(64), receiptIdSchema) - .refine((choices) => Object.keys(choices).length <= MAX_SIGNED_FILES, "Too many files."), -}) -export const transferInputSchema = z.object({ transferDate: dateSchema, amountCents: amountCentsSchema }) - export type CreatePersonInput = z.infer export type UpdatePersonInput = z.infer export type SetNoteInput = z.infer -export type CreateMemberInput = z.infer -export type MemberStatusInput = z.infer -export type MemberNumberInput = z.infer export type EndAdminInput = z.infer export type CapoScopeInput = z.infer export type CapoRefInput = z.infer @@ -766,26 +332,10 @@ export type AddTeamMemberInput = z.infer export type TeamFieldsInput = z.infer export type TeamCandidatesInput = z.infer export type EndTeamInput = z.infer -export type RemindInput = z.infer -export type AnswersInput = z.infer -export type ImportCommitInput = z.infer -export type ResolveReviewInput = z.infer export type SearchAccountsInput = z.infer export type LinkAccountInput = z.infer -export type AskToBeAddedInput = z.infer -export type AnswerCensusInput = z.infer -export type CorrectionInput = z.infer -export type RejectFeeInput = z.infer -export type MarkPaidInput = z.infer -export type FeeRemindInput = z.infer -export type VoidReceiptInput = z.infer -export type SendSignedInput = z.infer -export type TransferInput = z.infer - -export const remindResultSchema = z.object({ sent: z.number().int(), skipped: z.number().int() }) -export const exportResultSchema = z.object({ filename: z.string(), csv: z.string() }) + export const createdSchema = z.object({ id: z.string() }) -export const importedSchema = z.object({ imported: z.number().int() }) /** A team's fields in display order, typed for rendering and forms. */ export function teamFields(team: TeamId): TeamField[] { diff --git a/src/people/files.ts b/src/people/files.ts deleted file mode 100644 index 99a0c14..0000000 --- a/src/people/files.ts +++ /dev/null @@ -1,49 +0,0 @@ -import { PDFDocument } from "pdf-lib" -import { inspectPdf } from "@/esign/pdf/inspect" -import { fail } from "./model" - -/** Detect actual content, then parse it. Image dimensions are bounded before raster decompression. */ -export async function transferType(bytes: Uint8Array): Promise { - try { - if (Buffer.from(bytes.subarray(0, 5)).toString() === "%PDF-") { - const pdf = await inspectPdf(bytes) - if (!pdf.pages.length) fail("BAD_REQUEST", "The PDF has no pages") - return "application/pdf" - } - const doc = await PDFDocument.create() - if ( - bytes[0] === 0x89 && - Buffer.from(bytes.subarray(1, 8)).toString("hex") === "504e470d0a1a0a" && - bytes.length >= 33 - ) { - const width = Buffer.from(bytes).readUInt32BE(16) - const height = Buffer.from(bytes).readUInt32BE(20) - if (!width || !height || width * height > 20_000_000) fail("BAD_REQUEST", "Image exceeds 20 megapixels") - const idat: Buffer[] = [] - const buffer = Buffer.from(bytes) - let position = 8 - while (position + 12 <= bytes.length) { - const length = buffer.readUInt32BE(position) - if (position + length + 12 > bytes.length) fail("BAD_REQUEST", "Truncated PNG chunk") - if (buffer.toString("ascii", position + 4, position + 8) === "IDAT") - idat.push(buffer.subarray(position + 8, position + 8 + length)) - position += length + 12 - } - if (!idat.length) fail("BAD_REQUEST", "PNG has no image data") - inflateSync(Buffer.concat(idat), { maxOutputLength: Math.min(160_000_000, width * height * 8 + height * 8) }) - await doc.embedPng(bytes) - return "image/png" - } - if (bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff) { - const image = await doc.embedJpg(bytes) - if (image.width * image.height > 20_000_000 || bytes.at(-2) !== 0xff || bytes.at(-1) !== 0xd9) - fail("BAD_REQUEST", "Invalid or oversized JPEG") - return "image/jpeg" - } - } catch { - fail("BAD_REQUEST", "Cannot read this PDF, JPEG or PNG") - } - fail("BAD_REQUEST", "Upload a PDF, JPEG or PNG by content") -} - -import { inflateSync } from "node:zlib" diff --git a/src/people/iban.ts b/src/people/iban.ts deleted file mode 100644 index 6019381..0000000 --- a/src/people/iban.ts +++ /dev/null @@ -1,96 +0,0 @@ -const IBAN_LENGTHS: Record = { - AD: 24, - AE: 23, - AL: 28, - AT: 20, - AZ: 28, - BA: 20, - BE: 16, - BG: 22, - BH: 22, - BI: 27, - BR: 29, - BY: 28, - CH: 21, - CR: 22, - CY: 28, - CZ: 24, - DE: 22, - DJ: 27, - DK: 18, - DO: 28, - EE: 20, - EG: 29, - ES: 24, - FI: 18, - FK: 18, - FO: 18, - FR: 27, - GB: 22, - GE: 22, - GI: 23, - GL: 18, - GR: 27, - GT: 28, - HR: 21, - HU: 28, - IE: 22, - IL: 23, - IQ: 23, - IS: 26, - IT: 27, - JO: 30, - KW: 30, - KZ: 20, - LB: 28, - LC: 32, - LI: 21, - LT: 20, - LU: 20, - LV: 21, - LY: 25, - MC: 27, - MD: 24, - ME: 22, - MK: 19, - MN: 20, - MR: 27, - MT: 31, - MU: 30, - NL: 18, - NO: 15, - PK: 24, - PL: 28, - PS: 29, - PT: 25, - QA: 29, - RO: 24, - RS: 22, - SA: 24, - SC: 31, - SD: 18, - SE: 24, - SI: 19, - SK: 24, - SM: 27, - SO: 23, - ST: 25, - SV: 28, - TL: 23, - TN: 24, - TR: 26, - UA: 29, - VA: 22, - VG: 24, - XK: 20, -} - -export function isValidIban(iban: string): boolean { - if (!/^[A-Z]{2}\d{2}[A-Z0-9]+$/.test(iban) || IBAN_LENGTHS[iban.slice(0, 2)] !== iban.length) return false - let remainder = 0 - for (const char of `${iban.slice(4)}${iban.slice(0, 4)}`) { - const value = char >= "A" ? String(char.charCodeAt(0) - 55) : char - for (const digit of value) remainder = (remainder * 10 + Number(digit)) % 97 - } - return remainder === 1 -} diff --git a/src/people/imports.ts b/src/people/imports.ts deleted file mode 100644 index f3deefc..0000000 --- a/src/people/imports.ts +++ /dev/null @@ -1,254 +0,0 @@ -import { TRPCError } from "@trpc/server" -import { XMLParser, XMLValidator } from "fast-xml-parser" -import { Unzip, UnzipInflate } from "fflate" -import { z } from "zod" -import { type CensusAnswer, createPersonInputSchema, teamIdSchema } from "./contract" -import { fail, hash } from "./model" - -export const MAX_FILE_BYTES = 10 * 1024 * 1024 -const MAX_EXPANDED_BYTES = 50 * 1024 * 1024 -const MAX_ROWS = 5000 - -/** Stream inflation enforces actual output sizes, including ZIPs with forged size headers. No files reach disk. */ -export function unzipBounded(bytes: Uint8Array): Record { - const output: Record = Object.create(null) - let count = 0 - let total = 0 - const archive = new Unzip((entry) => { - if (++count > 1000 || (entry.originalSize && entry.originalSize > MAX_EXPANDED_BYTES)) - fail("BAD_REQUEST", "Archive exceeds import limits") - if (entry.name.includes("..") || entry.name.startsWith("/") || entry.name in output) - fail("BAD_REQUEST", "Invalid archive entry") - const parts: Uint8Array[] = [] - let length = 0 - entry.ondata = (error, chunk, final) => { - if (error) throw error - total += chunk.length - length += chunk.length - if (total > MAX_EXPANDED_BYTES) { - entry.terminate() - fail("BAD_REQUEST", "Expanded import exceeds 50 MB") - } - parts.push(chunk) - if (final) { - const value = new Uint8Array(length) - let offset = 0 - for (const part of parts) { - value.set(part, offset) - offset += part.length - } - output[entry.name] = value - } - } - entry.start() - }) - archive.register(UnzipInflate) - // Bound the amount inflated before ondata can enforce the actual-output budget, even with forged ZIP sizes. - for (let offset = 0; offset < bytes.length; offset += 1024) - archive.push(bytes.subarray(offset, offset + 1024), offset + 1024 >= bytes.length) - if (!count) fail("BAD_REQUEST", "Empty or invalid archive") - return output -} - -export function parseCsv(text: string): string[][] { - const firstLine = text.split(/\r?\n/, 1)[0] - const delimiter = (firstLine.match(/;/g)?.length ?? 0) > (firstLine.match(/,/g)?.length ?? 0) ? ";" : "," - const rows: string[][] = [] - let row: string[] = [] - let cell = "" - let quoted = false - for (let i = 0; i < text.length; i++) { - const char = text[i] - if (char === '"' && quoted && text[i + 1] === '"') { - cell += '"' - i++ - continue - } - if (char === '"') { - if (!quoted && cell) fail("BAD_REQUEST", "Malformed CSV quoting") - quoted = !quoted - continue - } - if (!quoted && (char === delimiter || char === "\n" || char === "\r")) { - row.push(cell) - cell = "" - if (char !== delimiter) { - if (char === "\r" && text[i + 1] === "\n") i++ - if (row.some(Boolean)) rows.push(row) - row = [] - if (rows.length > MAX_ROWS + 1) fail("BAD_REQUEST", "Import exceeds 5,000 responses") - } - } else cell += char - if (cell.length > 10000 || row.length > 200) fail("BAD_REQUEST", "Import cell or column limit exceeded") - } - if (quoted) fail("BAD_REQUEST", "Unclosed CSV quote") - row.push(cell) - if (row.some(Boolean)) rows.push(row) - return rows -} - -type Xml = { [key: string]: Xml | Xml[] | string | number } -const decoder = new TextDecoder("utf-8", { fatal: true }) -function xml(bytes?: Uint8Array): Xml { - if (!bytes) return {} - const text = decoder.decode(bytes) - if (/ ["si", "row", "c", "r"].includes(name), - }).parse(text) -} -function richText(value: unknown): string { - if (typeof value === "string" || typeof value === "number") return String(value) - if (!value || typeof value !== "object") return "" - const obj = value as { t?: unknown; r?: unknown[]; "#text"?: string } - return obj.t !== undefined ? richText(obj.t) : obj.r ? obj.r.map(richText).join("") : (obj["#text"] ?? "") -} -function parseXlsx(bytes: Uint8Array): string[][] { - const zip = unzipBounded(bytes) - if (!zip["[Content_Types].xml"] || !zip["xl/workbook.xml"]) fail("BAD_REQUEST", "This ZIP is not an XLSX workbook") - const sheet = Object.keys(zip) - .filter((key) => /^xl\/worksheets\/sheet\d+\.xml$/.test(key)) - .sort()[0] - if (!sheet) fail("BAD_REQUEST", "Workbook has no worksheet") - const sharedRoot = xml(zip["xl/sharedStrings.xml"]) as unknown as { sst?: { si?: unknown[] } } - const shared = (sharedRoot.sst?.si ?? []).map(richText) - const root = xml(zip[sheet]) as unknown as { - worksheet?: { - sheetData?: { row?: { c?: { "@_r"?: string; "@_t"?: string; v?: string; is?: unknown; f?: unknown }[] }[] } - } - } - const rows: string[][] = [] - for (const source of root.worksheet?.sheetData?.row ?? []) { - const row: string[] = [] - for (const cell of source.c ?? []) { - if (cell.f !== undefined) fail("BAD_REQUEST", "Formula cells are not accepted in census imports") - const letters = /^([A-Z]+)/.exec(cell["@_r"] ?? "")?.[1] - const column = letters ? [...letters].reduce((n, c) => n * 26 + c.charCodeAt(0) - 64, 0) - 1 : row.length - if (column >= 200) fail("BAD_REQUEST", "Import exceeds 200 columns") - const value = - cell["@_t"] === "s" - ? (shared[Number(cell.v)] ?? "") - : cell["@_t"] === "inlineStr" - ? richText(cell.is) - : (cell.v ?? "") - if (value.length > 10000) fail("BAD_REQUEST", "Import cell is too long") - row[column] = value - } - rows.push(Array.from({ length: row.length }, (_, i) => row[i] ?? "")) - if (rows.length > MAX_ROWS + 1) fail("BAD_REQUEST", "Import exceeds 5,000 responses") - } - return rows -} - -const normalize = (s: string) => - s - .normalize("NFKD") - .replace(/[\u0300-\u036f]/g, "") - .toLowerCase() - .replace(/[^a-z0-9]/g, "") -const aliases: Record = { - firstName: ["firstName", "nome"], - lastName: ["lastName", "cognome"], - personalEmail: ["personalEmail", "email", "emailpersonale", "indirizzodipostaelettronica"], - phone: ["phone", "telefono", "numeroditelefono"], - telegramUsername: ["telegramUsername", "telegram", "usernametelegram"], - course: ["course", "corso", "corsodilaurea"], - year: ["year", "annodicorso"], - campus: ["campus", "sede"], - answer: ["answer", "continui", "continuare", "continues"], - declaredMember: ["declaredMember", "socio"], - answeredOn: ["answeredOn", "completiontime", "oradicompletamento"], - admin: ["admin", "amministratore"], - teams: ["teams", "team"], - requestedGroups: ["requestedGroups", "gruppirichiesti"], - availableAsCapo: ["availableAsCapo", "disponibilecomecapo"], - otherAssociations: ["otherAssociations", "altreassociazioni"], - studentRepresentative: ["studentRepresentative", "rappresentantestudenti"], - privacyVersion: ["privacyVersion"], - privacyAcceptedOn: ["privacyAcceptedOn"], - photoConsent: ["photoConsent", "consensofoto"], -} -const volunteerInput = z.object({ - admin: z.boolean(), - teams: z.array(teamIdSchema).max(5), - requestedGroups: z.array(z.string().regex(/^-\d{1,16}$/)).max(100), - availableAsCapo: z.boolean(), - otherAssociations: z.array(z.string().max(100)).max(20).optional(), - studentRepresentative: z.string().max(200).optional(), - privacyVersion: z.string().max(80), - privacyAcceptedOn: z.iso.date().nullable(), - photoConsent: z.enum(["granted", "denied"]).nullable(), -}) -export async function parseImport(file: File) { - if (!file.size || file.size > MAX_FILE_BYTES) fail("BAD_REQUEST", "Import must be between 1 byte and 10 MB") - const bytes = new Uint8Array(await file.arrayBuffer()) - let rows: string[][] - try { - rows = - bytes[0] === 0x50 && bytes[1] === 0x4b ? parseXlsx(bytes) : parseCsv(decoder.decode(bytes).replace(/^\ufeff/, "")) - } catch (error) { - if (error instanceof TRPCError) throw error - fail("BAD_REQUEST", "Cannot read a UTF-8 CSV or XLSX workbook") - } - if (rows.length < 2 || rows.length > MAX_ROWS + 1) fail("BAD_REQUEST", "Import must contain 1–5,000 responses") - const headers = rows[0].map(normalize) - const indexes = Object.fromEntries( - Object.entries(aliases).map(([key, values]) => [key, headers.findIndex((h) => values.map(normalize).includes(h))]) - ) - for (const required of ["firstName", "lastName", "personalEmail", "course", "year", "campus", "answer"]) - if (indexes[required] < 0) fail("BAD_REQUEST", `Missing census column: ${required}`) - return rows.slice(1).map((cells, i) => { - const get = (key: string) => cells[indexes[key]]?.trim() ?? "" - const profile = createPersonInputSchema.safeParse({ - ...Object.fromEntries(Object.keys(aliases).map((key) => [key, get(key)])), - admin: false, - }) - const answer: CensusAnswer | null = ["yes", "si", "continues"].includes(normalize(get("answer"))) - ? "continues" - : ["no", "leaving"].includes(normalize(get("answer"))) - ? "leaving" - : null - const answered = get("answeredOn") - const answeredOn = /^\d{4}-\d{2}-\d{2}/.test(answered) ? answered.slice(0, 10) : null - const split = (key: string) => - get(key) - .split(/[;|]/) - .map((s) => s.trim()) - .filter(Boolean) - const yes = (key: string) => ["yes", "si", "true", "1"].includes(normalize(get(key))) - const volunteer = volunteerInput.safeParse({ - admin: yes("admin"), - teams: split("teams").map((t) => t.toLowerCase()), - requestedGroups: split("requestedGroups"), - availableAsCapo: yes("availableAsCapo"), - otherAssociations: indexes.otherAssociations >= 0 ? split("otherAssociations") : undefined, - studentRepresentative: indexes.studentRepresentative >= 0 ? get("studentRepresentative") : undefined, - privacyVersion: get("privacyVersion"), - privacyAcceptedOn: get("privacyAcceptedOn") || null, - photoConsent: get("photoConsent") || null, - }) - return { - row: i + 2, - fingerprint: hash(JSON.stringify(cells)), - profile: profile.success ? profile.data : null, - answer, - answeredOn, - volunteer: volunteer.success ? volunteer.data : null, - declaredMember: get("declaredMember") - ? ["yes", "si", "true", "1"].includes(normalize(get("declaredMember"))) - : null, - answers: cells.map((value, index) => ({ question: rows[0][index], answer: value })), - error: !volunteer.success - ? (volunteer.error.issues[0]?.message ?? "Invalid volunteer fields") - : !profile.success - ? (profile.error.issues[0]?.message ?? "Invalid profile") - : !answer - ? "Answer must be continues/leaving or yes/no" - : null, - } - }) -} diff --git a/src/people/index.ts b/src/people/index.ts index 9d363a2..0568f81 100644 --- a/src/people/index.ts +++ b/src/people/index.ts @@ -1,74 +1,20 @@ -import { DB, SCHEMA } from "@/db" +import { DB } from "@/db" import { sendPeopleEmail } from "@/emails/mailer" +import { env } from "@/env" import { idp } from "@/idp" -import { decryptUser } from "@/utils/users" -import { provisionMember, setMemberNumber } from "./azure-members" -import { peopleConfig } from "./config" -import { transferType } from "./files" -import { fail, receiptEligible } from "./model" +import { fail } from "./model" import { createPeopleService } from "./service" import { createPeoplePgStore } from "./store-pg" -export function permissionsFor(sub: string) { - return (permission: string) => { - const index = idp?.snapshot?.current() - return index?.has(index.bySub(sub), permission) ?? false - } -} export const people = createPeopleService({ store: createPeoplePgStore(DB), - config: peopleConfig, + dashboardUrl: env.ESIGN_DASHBOARD_URL.replace(/\/$/, ""), async directory() { if (!idp?.directory) fail("PRECONDITION_FAILED", "The IdP account directory is not configured") return (await idp.directory()).map((a) => ({ ...a, - emailVerified: a.emailVerified === true, telegramId: idp?.snapshot?.current()?.bySub(a.sub)?.telegramId ?? null, })) }, - // Group admins are native Telegram status (RFC v3 decision 2), which the backend does not store. - async telegramGroups() { - const groups = await DB.select().from(SCHEMA.TG.groups) - return groups.map((g) => ({ chatId: String(g.telegramId), title: g.title, admins: null })) - }, - async telegramUsers() { - const users = await DB.select().from(SCHEMA.TG.users) - return Promise.all( - users.map(async (u) => { - const p = await decryptUser(u) - return { - id: String(p.id), - name: [p.firstName, p.lastName].filter(Boolean).join(" "), - username: p.username ?? null, - } - }) - ) - }, - provisionMember, - setMemberNumber, sendMail: sendPeopleEmail, - async inspectSigned(sub, bytes) { - const { esign } = await import("@/esign") - return esign.inspectUpload(sub, bytes) - }, - async verifySigned(sub, requestId, bytes) { - const { esign } = await import("@/esign") - return esign.verifyUpload({ sub, canManage: false, peopleManual: true }, requestId, bytes) - }, - async completeSigned(sub, requestId, bytes) { - const { esign } = await import("@/esign") - await esign.uploadSigned({ sub, canManage: false, peopleManual: true }, requestId, bytes) - }, - transferType, }) - -export const receiptEligibility = (requestId: string, sub: string, requireEsign = true) => - people.eligibleReceipt(requestId, sub, permissionsFor(sub), requireEsign) -export const receiptVisibility = (receiptId: string, sub: string) => - people.canViewReceipt(receiptId, sub, permissionsFor(sub)) -export const eligibleAtCommit = ( - receipt: Parameters[1], - sub: string, - state: Parameters[0], - requireEsign: boolean -) => receiptEligible(state, receipt, { sub, telegramId: null, can: permissionsFor(sub) }, peopleConfig, requireEsign) diff --git a/src/people/merge.ts b/src/people/merge.ts deleted file mode 100644 index 7bb795e..0000000 --- a/src/people/merge.ts +++ /dev/null @@ -1,109 +0,0 @@ -import { fail, leads, log, requireGeneral } from "./model" -import type { PeopleConfig, PeopleState, Person, Viewer } from "./types" - -/** Merge reviewed duplicates; the caller archives the complete second record in the resolved review. */ -export function mergePeople( - s: PeopleState, - first: Person, - second: Person, - viewer: Viewer, - config: PeopleConfig, - now: Date -): Person { - if (first.id === second.id) fail("CONFLICT", "Choose two different records") - if (Object.values(config.officers).includes(second.id)) - fail("PRECONDITION_FAILED", "Retain the configured officer's record when merging") - if (first.member && second.member) - fail("CONFLICT", "Both records have memberships; resolve the register conflict before merging") - if (first.profile.telegramId && second.profile.telegramId && first.profile.telegramId !== second.profile.telegramId) - fail("CONFLICT", "Resolve the Telegram identity conflict before merging") - if (leads(first).length || leads(second).length || first.admin?.capoScope || second.admin?.capoScope) - requireGeneral(viewer, "people:appoint") - if (first.admin?.capoScope && second.admin?.capoScope && first.admin.capoScope !== second.admin.capoScope) - fail("CONFLICT", "Resolve the Capo Admin scopes before merging") - if ( - first.admin?.capoOfReference && - second.admin?.capoOfReference && - first.admin.capoOfReference.id !== second.admin.capoOfReference.id - ) - fail("CONFLICT", "Resolve the Capo Admin references before merging") - for (const other of second.teams) { - const active = first.teams.find((t) => t.team === other.team && !t.endedOn && !other.endedOn) - if (active) { - if (JSON.stringify(active.fields) !== JSON.stringify(other.fields)) - fail("CONFLICT", "Resolve conflicting team fields before merging") - if (other.since < active.since) active.since = other.since - if (other.role === "lead") active.role = "lead" - } else first.teams.push(structuredClone(other)) - } - if (!first.admin) first.admin = structuredClone(second.admin) - else if (second.admin) { - if (second.admin.status === "active") first.admin.status = "active" - if (first.admin.status === "active") { - first.admin.endedOn = null - first.admin.endReason = null - } - first.admin.since = [first.admin.since, second.admin.since].sort()[0] - first.admin.capoScope ??= second.admin.capoScope - first.admin.capoOfReference ??= second.admin.capoOfReference - first.admin.availableAsCapo ||= second.admin.availableAsCapo - for (const g of second.admin.groups) - if (!first.admin.groups.some((t) => t.chatId === g.chatId)) first.admin.groups.push(g) - for (const g of second.admin.requested) - if (!first.admin.requested.some((t) => t.chatId === g.chatId)) first.admin.requested.push(g) - } - first.profile.telegramId ??= second.profile.telegramId - first.profile.phone ||= second.profile.phone - first.profile.personalEmail ||= second.profile.personalEmail - first.profile.telegramUsername ||= second.profile.telegramUsername - first.profile.otherAssociations = [ - ...new Set([...first.profile.otherAssociations, ...second.profile.otherAssociations]), - ] - first.profile.studentRepresentative ||= second.profile.studentRepresentative - if (!first.member) { - first.member = structuredClone(second.member) - first.azureId = second.azureId - first.feeYears = structuredClone(second.feeYears) - } - first.accountSub ??= second.accountSub - if (second.accountSub && first.account.status !== "linked") first.account = structuredClone(second.account) - first.invite = null - for (const entry of second.census) { - const existing = first.census.find((e) => e.year === entry.year) - if (!existing || !existing.answer || (entry.answeredOn ?? "") > (existing.answeredOn ?? "")) { - first.census = [...first.census.filter((e) => e.year !== entry.year), structuredClone(entry)] - first.answers[entry.year] = structuredClone(second.answers[entry.year] ?? []) - } else if (entry.answer && existing.answer !== entry.answer && existing.answeredOn === entry.answeredOn) - fail("CONFLICT", "Resolve conflicting census answers before merging") - } - if ( - second.consents.privacy && - (!first.consents.privacy || second.consents.privacy.acceptedOn > first.consents.privacy.acceptedOn) - ) - first.consents.privacy = structuredClone(second.consents.privacy) - const restrictive = { granted: 0, denied: 1, revoked: 2 } - if ( - second.consents.photo && - (!first.consents.photo || - second.consents.photo.on > first.consents.photo.on || - (second.consents.photo.on === first.consents.photo.on && - restrictive[second.consents.photo.status] > restrictive[first.consents.photo.status])) - ) - first.consents.photo = structuredClone(second.consents.photo) - if (second.notes) first.notes = [first.notes, `${second.id}: ${second.notes}`].filter(Boolean).join("\n") - first.activity = [...first.activity, ...second.activity].sort((a, b) => b.at.localeCompare(a.at)) - first.discrepancies.push(...second.discrepancies) - first.pendingGroupRemovals = [...(first.pendingGroupRemovals ?? []), ...(second.pendingGroupRemovals ?? [])] - for (const p of Object.values(s.persons)) - if (p.admin?.capoOfReference?.id === second.id) - p.admin.capoOfReference = { id: first.id, name: `${first.profile.firstName} ${first.profile.lastName}` } - for (const r of Object.values(s.receipts)) if (r.person.id === second.id) r.person.id = first.id - for (const mail of Object.values(s.outbox)) if (mail.personId === second.id) mail.personId = first.id - for (const r of Object.values(s.reviews)) { - if (r.record?.id === second.id) r.record.id = first.id - if (r.other?.id === second.id) r.other.id = first.id - } - delete s.persons[second.id] - log(first, viewer.sub, `Merged duplicate ${second.id}; original retained in the linking review`, now) - return first -} diff --git a/src/people/model.ts b/src/people/model.ts index 6f4456e..abdbebe 100644 --- a/src/people/model.ts +++ b/src/people/model.ts @@ -1,7 +1,7 @@ -import { createHash, randomUUID } from "node:crypto" +import { createHash } from "node:crypto" import { TRPCError } from "@trpc/server" import * as C from "./contract" -import type { Officer, PeopleConfig, PeopleState, Person, StoredReceipt, UnitOfWork, Viewer } from "./types" +import type { PeopleState, Person, Viewer } from "./types" export function fail( code: "BAD_REQUEST" | "FORBIDDEN" | "NOT_FOUND" | "CONFLICT" | "PRECONDITION_FAILED", @@ -11,9 +11,6 @@ export function fail( } export const nameOf = (p: Person) => `${p.profile.firstName} ${p.profile.lastName}` export const ref = (p: Person) => ({ id: p.id, name: nameOf(p) }) -export const newestReceipts = (a: { number: string }, b: { number: string }) => - Number(b.number.split("/")[0]) - Number(a.number.split("/")[0]) || - Number(b.number.split("/")[1]) - Number(a.number.split("/")[1]) export const hash = (v: Uint8Array | string) => createHash("sha256").update(v).digest("hex") export const today = (now: Date) => new Intl.DateTimeFormat("en-CA", { @@ -22,11 +19,6 @@ export const today = (now: Date) => month: "2-digit", day: "2-digit", }).format(now) -export function academicYear(date: string) { - const y = Number(date.slice(0, 4)) - (Number(date.slice(5, 7)) < 9 ? 1 : 0) - return `${y}/${String(y + 1).slice(-2)}` -} -export const dueDate = (year: string) => `${year.slice(0, 4)}-10-31` export function find(state: PeopleState, id: string) { return state.persons[id] ?? fail("NOT_FOUND", "Person not found") } @@ -54,35 +46,7 @@ export function teamAccess(s: PeopleState, v: Viewer, team: C.TeamId, write: boo export function log(p: Person, actor: string, text: string, now: Date) { p.activity.unshift({ actor, text, at: now.toISOString() }) } -export function fee(p: Person, config: PeopleConfig, date: string) { - if (!p.member || p.member.status === "former") return null - const year = academicYear(date) - p.feeYears[year] ??= { - year, - status: "due", - amountCents: config.feeCents, - dueOn: dueDate(year), - upload: null, - rejection: null, - payment: null, - lastReminder: null, - rejections: [], - fileId: null, - } - const f = p.feeYears[year] - if (f.status === "due" || f.status === "unpaid") f.status = date > f.dueOn ? "unpaid" : "due" - p.member.fee = f.status - return f -} -export function row( - s: PeopleState, - p: Person, - v: Viewer, - config: PeopleConfig, - date: string, - scopedContacts = false -): C.PersonRow { - fee(p, config, date) +export function row(s: PeopleState, p: Person, v: Viewer, scopedContacts = false): C.PersonRow { const self = own(s, v)?.id === p.id const contacts = self || general(v, "people:read") || scopedContacts return C.personRowSchema.parse({ @@ -92,37 +56,16 @@ export function row( personalEmail: contacts ? p.profile.personalEmail : null, phone: contacts ? p.profile.phone : null, }, - member: self || general(v, "people:members:read") ? p.member : null, - isMember: !!p.member && p.member.status !== "former", account: self || general(v, "people:read") ? p.account : { status: "none" }, }) } -export function record(s: PeopleState, p: Person, v: Viewer, config: PeopleConfig, date: string): C.PersonRecord { - const self = own(s, v)?.id === p.id +export function record(s: PeopleState, p: Person, v: Viewer): C.PersonRecord { const read = general(v, "people:read") - const pendingMessages = new Set(p.pendingGroupRemovals?.map((pending) => pending.message)) - const discrepancies: C.Discrepancy[] = p.discrepancies.map((item) => - pendingMessages.has(item.message) ? { ...item, kind: "admin-removal" } : item - ) return C.personRecordSchema.parse({ - ...row(s, p, v, config, date), + ...row(s, p, v), notes: read ? p.notes : null, - discrepancies: read ? discrepancies : self ? discrepancies.filter((d) => pendingMessages.has(d.message)) : [], - activity: read - ? p.activity - : self - ? p.activity.filter((a) => /fee|receipt|payment|consent|census/i.test(a.text)) - : [], - fees: - p.member && (self || general(v, "people:members:read")) - ? { - current: fee(p, config, date), - receipts: Object.values(s.receipts) - .filter((r) => r.person.id === p.id) - .sort(newestReceipts) - .map((r) => C.receiptSchema.parse(r)), - } - : null, + discrepancies: read ? p.discrepancies : [], + activity: read ? p.activity : [], }) } export function newPerson(s: PeopleState, input: C.CreatePersonInput, date: string): Person { @@ -139,74 +82,30 @@ export function newPerson(s: PeopleState, input: C.CreatePersonInput, date: stri otherAssociations: [], studentRepresentative: null, }, - member: null, admin: input.admin ? { status: "active", since: date, endedOn: null, endReason: null, - groups: [], - requested: [], availableAsCapo: false, capoOfReference: null, capoScope: null, } : null, teams: [], - census: [], consents: { privacy: null, photo: null }, account: { status: "none" }, notes: null, discrepancies: [], activity: [], accountSub: null, - azureId: null, - feeYears: {}, - answers: {}, - reminders: {}, invite: null, } s.persons[p.id] = p return p } -export function office(s: PeopleState, v: Viewer, config: PeopleConfig): Officer | null { - if (!general(v, "people:receipts:sign")) return null - const p = own(s, v) - if (!p) return null - return config.officers.president === p.id - ? "president" - : config.officers.vicePresident === p.id - ? "vicePresident" - : null -} -export function receiptEligible( - s: PeopleState, - r: StoredReceipt, - v: Viewer, - config: PeopleConfig, - requireEsign = true -) { - return ( - r.status === "toSign" && - office(s, v, config) === r.signer && - config.officers[r.signer] === r.officerPersonId && - (!requireEsign || v.can("esign:sign")) - ) -} -export function findReceipt(s: PeopleState, id: string) { - return s.receipts[id] ?? fail("NOT_FOUND", "Receipt not found") -} -export function queue( - s: PeopleState, - p: Person, - id: string, - to: string, - subject: string, - text: string, - fileId: string | null = null, - receiptId: string | null = null -) { +export function queue(s: PeopleState, p: Person, id: string, to: string, subject: string, text: string) { if (s.outbox[id]?.status === "failed") { s.outbox[id].status = "pending" s.outbox[id].attemptedAt = null @@ -218,23 +117,11 @@ export function queue( to, subject, text, - fileId, - receiptId, status: "pending", attemptedAt: null, error: null, } } -export async function filePayload(u: UnitOfWork, id: string) { - const file = await u.getFile(id) - if (!file) fail("NOT_FOUND", "File not found") - return { - fileName: file.fileName, - contentType: file.contentType, - base64: Buffer.from(file.content).toString("base64"), - } -} -export const csvCell = (v: string) => `"${(/^[=+\-@\t\r]/.test(v) ? `'${v}` : v).replaceAll('"', '""')}"` export function validateFields(team: C.TeamId, fields: C.TeamFields) { for (const [key, value] of Object.entries(fields)) { const spec = C.TEAMS[team].fields.find((f) => f.key === key) @@ -249,6 +136,3 @@ export function validateFields(team: C.TeamId, fields: C.TeamFields) { fail("BAD_REQUEST", "Invalid team option") } } -export function newFileId() { - return randomUUID() -} diff --git a/src/people/pdf.ts b/src/people/pdf.ts deleted file mode 100644 index a0683ea..0000000 --- a/src/people/pdf.ts +++ /dev/null @@ -1,93 +0,0 @@ -import { PDFDocument, rgb, StandardFonts } from "pdf-lib" -import { fail } from "./model" -import type { PeopleConfig, StoredReceipt } from "./types" - -const units = [ - "zero", - "uno", - "due", - "tre", - "quattro", - "cinque", - "sei", - "sette", - "otto", - "nove", - "dieci", - "undici", - "dodici", - "tredici", - "quattordici", - "quindici", - "sedici", - "diciassette", - "diciotto", - "diciannove", -] -function words(n: number): string { - if (n < 20) return units[n] - if (n < 100) { - const tens = ["", "", "venti", "trenta", "quaranta", "cinquanta", "sessanta", "settanta", "ottanta", "novanta"][ - Math.floor(n / 10) - ] - return `${n % 10 === 1 || n % 10 === 8 ? tens.slice(0, -1) : tens}${n % 10 ? words(n % 10) : ""}` - } - if (n < 1000) - return `${n < 200 ? "" : words(Math.floor(n / 100))}cent${Math.floor((n % 100) / 10) === 8 ? "" : "o"}${n % 100 ? words(n % 100) : ""}` - return "mille" -} -export async function receiptPdf( - receipt: StoredReceipt, - config: PeopleConfig, - officerName: string -): Promise { - if (!config.legalName || !config.address || !config.taxCode) - fail( - "PRECONDITION_FAILED", - "Configure PEOPLE_LEGAL_NAME, PEOPLE_ADDRESS and PEOPLE_TAX_CODE before issuing receipts" - ) - const doc = await PDFDocument.create() - const page = doc.addPage([595.28, 841.89]) - const regular = await doc.embedFont(StandardFonts.Helvetica) - const bold = await doc.embedFont(StandardFonts.HelveticaBold) - // Standard PDF fonts cover Italian; unrepresentable profile characters are transliterated explicitly. - const latin = (s: string) => - s - .normalize("NFKD") - .replace(/[\u0300-\u036f]/g, "") - .replace(/[^\x20-\x7e\xa0-\xff€]/g, "?") - const draw = (text: string, y: number, size = 11, strong = false, x = 48) => - page.drawText(latin(text), { - x, - y, - size, - font: strong ? bold : regular, - color: rgb(0.1, 0.1, 0.1), - maxWidth: 490, - lineHeight: 16, - }) - draw(config.legalName, 785, 19, true) - draw(config.address, 760, 10) - draw(`Codice fiscale: ${config.taxCode}`, 744, 10) - draw(`Ricevuta n. ${receipt.number}`, 697, 13, true) - draw(`Milano, ${receipt.issuedOn}`, 676) - draw("Ricevuta di pagamento della quota associativa", 626, 15, true) - draw(`Ricevuto da: ${receipt.person.name}`, 580) - draw(`Numero socio: ${receipt.memberNumber}`, 555) - const euros = Math.floor(receipt.amountCents / 100) - const cents = String(receipt.amountCents % 100).padStart(2, "0") - draw(`La somma di: € ${euros},${cents} (${words(euros)}/${cents} euro)`, 515) - draw(`A titolo di: quota associativa per l'anno sociale ${receipt.year}`, 475) - draw(`Modalita: ${receipt.method === "transfer" ? "Bonifico bancario" : "Contanti"}`, 435) - draw( - `Data pagamento: ${receipt.paidOn}${receipt.transferDate ? ` - Data bonifico: ${receipt.transferDate}` : ""}`, - 410 - ) - draw(receipt.signer === "president" ? "Il Presidente" : "Il Vicepresidente", 290, 11, true, 334) - draw(officerName, 273, 11, false, 334) - // Fixed eSign box is immediately below the printed office and name. - page.drawLine({ start: { x: 334, y: 180 }, end: { x: 542, y: 180 }, thickness: 0.5 }) - draw(`${config.legalName} - C.F. ${config.taxCode}`, 73, 9) - draw(`Ricevuta ${receipt.number} - pagina 1 di 1`, 55, 9) - return doc.save({ useObjectStreams: false }) -} diff --git a/src/people/router.ts b/src/people/router.ts index adeeb14..bf84206 100644 --- a/src/people/router.ts +++ b/src/people/router.ts @@ -1,10 +1,8 @@ import { TRPCError } from "@trpc/server" import { z } from "zod" -import { EsignError } from "@/esign/errors" import { SCOPE } from "@/idp/policies" import { createTRPCRouter, policy } from "@/trpc" import * as C from "./contract" -import { MAX_FILE_BYTES } from "./imports" import { requireGeneral } from "./model" import type { PeopleService } from "./service" import type { Viewer } from "./types" @@ -14,23 +12,7 @@ export function createPeopleRouter(people: PeopleService) { const user = policy({ user: { scope: SCOPE.admin } }).use(async ({ ctx, next }) => { if (ctx.actor.kind !== "user") throw new TRPCError({ code: "FORBIDDEN" }) const viewer: Viewer = { sub: ctx.actor.sub, telegramId: ctx.actor.telegramId, can: ctx.can } - const result = await next({ ctx: { viewer } }) - if (!result.ok && result.error.cause instanceof EsignError) { - const err = result.error.cause - throw new TRPCError({ - code: - err.code === "forbidden" || err.code === "signer_mismatch" - ? "FORBIDDEN" - : err.code === "not_found" - ? "NOT_FOUND" - : err.code === "conflict" || err.code === "document_changed" - ? "CONFLICT" - : "BAD_REQUEST", - message: err.message, - cause: err, - }) - } - return result + return next({ ctx: { viewer } }) }) const admin = (permission: string) => user.use(({ ctx, next }) => { @@ -43,23 +25,6 @@ export function createPeopleRouter(people: PeopleService) { }) const read = admin("people:read") const write = admin("people:write") - const members = admin("people:members:write") - const fees = admin("people:fees:write") - const sign = admin("people:receipts:sign") - const file = z - .instanceof(File) - .refine( - (f) => f.size > 0 && f.size <= MAX_FILE_BYTES && f.name.length <= 200, - "File must be 1 byte–10 MB and have a name of at most 200 characters" - ) - const transfer = z - .instanceof(FormData) - .transform((fd) => ({ - file: fd.get("file"), - transferDate: fd.get("transferDate"), - amountCents: Number(fd.get("amountCents")), - })) - .pipe(C.transferInputSchema.extend({ file })) return createTRPCRouter({ persons: createTRPCRouter({ list: read.output(C.personRowSchema.array()).query(({ ctx }) => people.listPeople(ctx.viewer)), @@ -76,21 +41,6 @@ export function createPeopleRouter(people: PeopleService) { .mutation(({ ctx, input }) => people.updatePerson(ctx.viewer, input)), setNote: write.input(C.setNoteInputSchema).mutation(({ ctx, input }) => people.setNote(ctx.viewer, input)), }), - members: createTRPCRouter({ - list: admin("people:members:read") - .output(C.memberRegisterRowSchema.array()) - .query(({ ctx }) => people.listMembers(ctx.viewer)), - create: members - .input(C.createMemberInputSchema) - .mutation(({ ctx, input }) => people.createMember(ctx.viewer, input)), - setStatus: members - .input(C.memberStatusInputSchema) - .mutation(({ ctx, input }) => people.setMemberStatus(ctx.viewer, input)), - setNumber: members - .input(C.memberNumberInputSchema) - .mutation(({ ctx, input }) => people.setMemberNumber(ctx.viewer, input)), - export: members.output(C.exportResultSchema).mutation(({ ctx }) => people.exportMembers(ctx.viewer)), - }), admins: createTRPCRouter({ end: write.input(C.endAdminInputSchema).mutation(({ ctx, input }) => people.endAdmin(ctx.viewer, input)), setCapoScope: admin("people:appoint") @@ -116,41 +66,7 @@ export function createPeopleRouter(people: PeopleService) { .input(C.endTeamInputSchema) .mutation(({ ctx, input }) => people.endTeamMembership(ctx.viewer, input)), }), - census: createTRPCRouter({ - campaigns: read.output(C.campaignSchema.array()).query(({ ctx }) => people.listCampaigns(ctx.viewer)), - campaign: read - .input(z.object({ id: z.string().min(1).max(128) })) - .output(C.campaignDetailSchema) - .query(({ ctx, input }) => people.getCampaign(ctx.viewer, input)), - answers: read - .input(C.answersInputSchema) - .output(C.censusAnswersSchema) - .query(({ ctx, input }) => people.getAnswers(ctx.viewer, input)), - remind: write - .input(C.remindInputSchema) - .output(C.remindResultSchema) - .mutation(({ ctx, input }) => people.remind(ctx.viewer, input)), - close: write.input(C.campaignInputSchema).mutation(({ ctx, input }) => people.closeCampaign(ctx.viewer, input)), - importPreview: write - .input( - z - .instanceof(FormData) - .transform((fd) => ({ campaignId: fd.get("campaignId"), file: fd.get("file") })) - .pipe(C.campaignInputSchema.extend({ file })) - ) - .output(C.importPreviewSchema) - .mutation(({ ctx, input }) => people.importPreview(ctx.viewer, input)), - importCommit: write - .input(C.importCommitInputSchema) - .output(C.importedSchema) - .mutation(({ ctx, input }) => people.importCommit(ctx.viewer, input)), - }), linking: createTRPCRouter({ - reviews: read.output(C.reviewSchema.array()).query(({ ctx }) => people.listReviews(ctx.viewer)), - resolve: write - .input(C.resolveReviewInputSchema) - .mutation(({ ctx, input }) => people.resolveReview(ctx.viewer, input)), - dismiss: write.input(C.reviewInputSchema).mutation(({ ctx, input }) => people.dismissReview(ctx.viewer, input)), invites: read.output(C.inviteSchema.array()).query(({ ctx }) => people.listInvites(ctx.viewer)), sendInvite: write .input(C.personRefInputSchema) @@ -167,91 +83,13 @@ export function createPeopleRouter(people: PeopleService) { }), capo: createTRPCRouter({ get: self.output(C.capoAreaSchema).query(({ ctx }) => people.getCapoArea(ctx.viewer)), - approve: self - .input(C.joinRequestInputSchema) - .mutation(({ ctx, input }) => people.handleJoinRequest(ctx.viewer, input, true)), - decline: self - .input(C.joinRequestInputSchema) - .mutation(({ ctx, input }) => people.handleJoinRequest(ctx.viewer, input, false)), }), me: createTRPCRouter({ roles: self.output(C.myRolesSchema).query(({ ctx }) => people.getMyRoles(ctx.viewer)), get: self.output(C.myAreaSchema).query(({ ctx }) => people.getMyArea(ctx.viewer)), - confirmMatch: self.mutation(({ ctx }) => people.confirmMatch(ctx.viewer)), - rejectMatch: self.mutation(({ ctx }) => people.rejectMatch(ctx.viewer)), acceptInvite: self .input(z.object({ token: z.string().regex(/^[A-Za-z0-9_-]{43}$/) })) .mutation(({ ctx, input }) => people.acceptInvite(ctx.viewer, input)), - askToBeAdded: self - .input(C.askToBeAddedInputSchema) - .mutation(({ ctx, input }) => people.askToBeAdded(ctx.viewer, input)), - answerCensus: self - .input(C.answerCensusInputSchema) - .mutation(({ ctx, input }) => people.answerCensus(ctx.viewer, input)), - requestCorrection: self - .input(C.correctionInputSchema) - .mutation(({ ctx, input }) => people.requestCorrection(ctx.viewer, input)), - revokePhotoConsent: self.mutation(({ ctx }) => people.revokePhotoConsent(ctx.viewer)), - uploadTransferReceipt: self - .input(transfer) - .mutation(({ ctx, input }) => people.uploadTransferReceipt(ctx.viewer, input)), - receipt: self - .input(C.receiptInputSchema) - .output(C.fileSchema) - .query(({ ctx, input }) => people.downloadMyReceipt(ctx.viewer, input)), - }), - fees: createTRPCRouter({ - review: fees - .input(C.feePersonInputSchema) - .output(C.feeReviewSchema) - .query(({ ctx, input }) => people.getFeeReview(ctx.viewer, input)), - upload: fees - .input(C.feePersonInputSchema) - .output(C.fileSchema) - .query(({ ctx, input }) => people.getFeeUpload(ctx.viewer, input)), - approve: fees - .input(C.feePersonInputSchema) - .output(C.issuedSchema) - .mutation(({ ctx, input }) => people.approveFee(ctx.viewer, input)), - reject: fees.input(C.rejectFeeInputSchema).mutation(({ ctx, input }) => people.rejectFee(ctx.viewer, input)), - markPaid: fees - .input(C.markPaidInputSchema) - .output(C.issuedSchema) - .mutation(({ ctx, input }) => people.markFeePaid(ctx.viewer, input)), - remind: fees - .input(C.feeRemindInputSchema) - .output(C.remindResultSchema) - .mutation(({ ctx, input }) => people.remindFees(ctx.viewer, input)), - }), - receipts: createTRPCRouter({ - list: admin("people:members:read") - .input(C.receiptsInputSchema) - .output(C.receiptsPageSchema) - .query(({ ctx, input }) => people.listReceipts(ctx.viewer, input)), - download: admin("people:members:read") - .input(C.receiptInputSchema) - .output(C.fileSchema) - .query(({ ctx, input }) => people.downloadReceipt(ctx.viewer, input)), - prepareSignatures: sign - .input(C.prepareReceiptSignaturesInputSchema) - .output(C.receiptSignaturesSchema) - .mutation(({ ctx, input }) => people.prepareReceiptSignatures(ctx.viewer, input)), - toSign: sign.output(C.fileSchema).mutation(({ ctx }) => people.downloadReceiptsToSign(ctx.viewer)), - previewSigned: sign - .input( - z - .instanceof(FormData) - .transform((fd) => ({ files: fd.getAll("files") })) - .pipe(z.object({ files: z.array(file).min(1).max(C.MAX_SIGNED_FILES) })) - ) - .output(C.signedUploadSchema) - .mutation(({ ctx, input }) => people.previewSignedReceipts(ctx.viewer, input)), - sendSigned: sign - .input(C.sendSignedInputSchema) - .output(C.sendResultSchema) - .mutation(({ ctx, input }) => people.sendSignedReceipts(ctx.viewer, input)), - retry: fees.input(C.receiptInputSchema).mutation(({ ctx, input }) => people.retryReceipt(ctx.viewer, input)), - void: fees.input(C.voidReceiptInputSchema).mutation(({ ctx, input }) => people.voidReceipt(ctx.viewer, input)), }), }) } diff --git a/src/people/service.ts b/src/people/service.ts index a06bfbf..9d1b9be 100644 --- a/src/people/service.ts +++ b/src/people/service.ts @@ -1,27 +1,16 @@ -import { randomBytes, randomUUID } from "node:crypto" -import { zipSync } from "fflate" +import { randomBytes } from "node:crypto" import * as C from "./contract" -import { MAX_FILE_BYTES, parseImport } from "./imports" -import { mergePeople } from "./merge" import { - academicYear, - csvCell, fail, - fee, - filePayload, find, - findReceipt, general, hash, leads, log, nameOf, - newestReceipts, newPerson, - office, own, queue, - receiptEligible, record, ref, requireGeneral, @@ -32,187 +21,22 @@ import { today, validateFields, } from "./model" -import { receiptPdf } from "./pdf" -import type { - Account, - ImportRow, - PeopleConfig, - PeopleState, - PeopleStore, - Person, - StoredReceipt, - TelegramGroup, - TelegramUser, - UnitOfWork, - Viewer, -} from "./types" +import type { Account, PeopleState, PeopleStore, Person, UnitOfWork, Viewer } from "./types" export type PeopleOptions = { store: PeopleStore - config: PeopleConfig + /** Dashboard origin, for links in emails. */ + dashboardUrl: string now?: () => Date directory: () => Promise - telegramGroups: () => Promise - telegramUsers: () => Promise - provisionMember: (person: Person, number: string) => Promise<{ id: string; email: string }> - setMemberNumber: (person: Person, number: string) => Promise - sendMail: (mail: { - id: string - to: string - subject: string - text: string - attachment: { fileName: string; contentType: string; content: Uint8Array } | null - }) => Promise - verifySigned: (sub: string, requestId: string, bytes: Uint8Array) => Promise<{ signer: string; content: Uint8Array }> - inspectSigned: (sub: string, bytes: Uint8Array) => Promise<{ signer: string }> - completeSigned: (sub: string, requestId: string, bytes: Uint8Array) => Promise - transferType: (bytes: Uint8Array) => Promise + sendMail: (mail: { id: string; to: string; subject: string; text: string }) => Promise } export function createPeopleService(options: PeopleOptions) { - const { store, config } = options + const { store, dashboardUrl } = options const now = options.now ?? (() => new Date()) const date = () => today(now()) - const year = () => academicYear(date()) const tx = (fn: (u: UnitOfWork) => Promise | T) => store.transaction(async (u) => fn(u)) - const currentFee = (p: Person) => fee(p, config, date()) ?? fail("CONFLICT", "This person is not a current member") - function hydrateGroups(s: PeopleState, groups: TelegramGroup[]) { - for (const p of Object.values(s.persons)) - if (p.admin && p.profile.telegramId) { - const telegramId = p.profile.telegramId - const known = new Set(groups.filter((g) => g.admins).map((g) => g.chatId)) - p.admin.groups = [ - ...p.admin.groups.filter((g) => !known.has(g.chatId)), - ...groups.filter((g) => g.admins?.includes(telegramId)).map(({ chatId, title }) => ({ chatId, title })), - ] - p.pendingGroupRemovals = p.pendingGroupRemovals?.filter((pending) => { - if (!known.has(pending.chatId) || p.admin?.groups.some((g) => g.chatId === pending.chatId)) return true - p.discrepancies = p.discrepancies.filter((d) => d.message !== pending.message) - log(p, "system", `Telegram confirmed admin removal from ${pending.chatId}`, now()) - return false - }) - } - } - function assertReceiptConfig(s: PeopleState) { - if (!config.legalName || !config.address || !config.taxCode) - fail("PRECONDITION_FAILED", "Configure receipt legal details before recording a paid fee") - for (const id of Object.values(config.officers)) - if (!id || !s.persons[id]?.accountSub || s.persons[id].account.status !== "linked") - fail( - "PRECONDITION_FAILED", - "Configure confirmed President and Vice-president records before recording a paid fee" - ) - } - const activeCampaign = (s: PeopleState) => { - const y = year() - s.campaigns[y] ??= { - id: y, - year: y, - status: "open", - openedOn: `${y.slice(0, 4)}-09-01`, - closesOn: `${y.slice(0, 4)}-10-31`, - source: "Forms / Dashboard", - expected: 0, - continuing: 0, - leaving: 0, - noAnswer: 0, - } - const c = s.campaigns[y] - for (const p of Object.values(s.persons)) { - if ((p.admin?.status === "active" || p.teams.some((t) => !t.endedOn)) && !p.census.some((e) => e.year === y)) - p.census.unshift({ year: y, answer: null, answeredOn: null, source: null, declaredMember: null, reminders: 0 }) - } - return c - } - const campaign = (s: PeopleState, id: string) => s.campaigns[id] ?? fail("NOT_FOUND", "Campaign not found") - const campaignView = (s: PeopleState, id: string): C.Campaign => { - const c = campaign(s, id) - const entries = Object.values(s.persons).flatMap((p) => p.census.filter((e) => e.year === c.year)) - return { - ...c, - expected: entries.length, - continuing: entries.filter((e) => e.answer === "continues").length, - leaving: entries.filter((e) => e.answer === "leaving").length, - noAnswer: entries.filter((e) => !e.answer).length, - } - } - function endRoles(p: Person, reason: string, actor: string, lastDay = date()) { - if (p.admin?.status === "active") - Object.assign(p.admin, { status: "former", endedOn: lastDay, endReason: reason, capoScope: null }) - for (const t of p.teams) if (!t.endedOn) Object.assign(t, { endedOn: lastDay, endReason: reason }) - log(p, actor, `Ended volunteer roles: ${reason}`, now()) - } - async function issue( - u: UnitOfWork, - p: Person, - payment: NonNullable, - actor: string, - note: string - ) { - assertReceiptConfig(u.state) - const f = currentFee(p) - if ( - f.status === "paid" || - Object.values(u.state.receipts).some((r) => r.person.id === p.id && r.year === f.year && r.status !== "voided") - ) - fail("CONFLICT", "This fee already has a receipt") - if (payment.paidOn > date()) fail("BAD_REQUEST", "Payment date is in the future") - const seq = (u.state.counters[`receipt:${f.year}`] ?? 0) + 1 - u.state.counters[`receipt:${f.year}`] = seq - const id = randomUUID() - const signer = p.id === config.officers.president ? "vicePresident" : "president" - const officerId = config.officers[signer] - const officer = officerId ? u.state.persons[officerId] : null - if (!officer?.accountSub || officer.account.status !== "linked") - fail("PRECONDITION_FAILED", "Configure a confirmed President and Vice-president before issuing receipts") - const receipt: StoredReceipt = { - id, - number: `${f.year.slice(0, 4)}/${String(seq).padStart(3, "0")}`, - year: f.year, - person: ref(p), - memberNumber: p.member?.number ?? "", - amountCents: payment.amountCents, - issuedOn: date(), - paidOn: payment.paidOn, - method: payment.method, - transferDate: payment.transferDate, - status: "toSign", - signer, - officerPersonId: officer.id, - signedBy: null, - signedOn: null, - sentAt: null, - sentTo: null, - failure: null, - voided: null, - originalFileId: `original:${id}`, - signedFileId: null, - sha256: "", - requestId: null, - recipient: p.member?.m365Email ?? "", - } - if (!receipt.recipient) fail("PRECONDITION_FAILED", "The member has no Microsoft 365 email") - const bytes = await receiptPdf(receipt, config, nameOf(officer)) - receipt.sha256 = hash(bytes) - await u.putFile({ - id: receipt.originalFileId, - fileName: `Ricevuta_${receipt.number.replace("/", "-")}.pdf`, - contentType: "application/pdf", - content: bytes, - expiresAt: null, - }) - u.state.receipts[id] = receipt - f.status = "paid" - f.payment = payment - f.rejection = null - f.upload = null - if (f.fileId) await u.deleteFile(f.fileId) - f.fileId = null - if (p.member) p.member.fee = "paid" - log(p, actor, `Recorded payment for ${f.year}${note ? `: ${note}` : ""}`, now()) - log(p, actor, `Issued receipt ${receipt.number}`, now()) - return { receipt: receipt.number } - } function link(s: PeopleState, p: Person, account: Account, actor: string, reason: string) { if (Object.values(s.persons).some((other) => other.id !== p.id && other.accountSub === account.sub)) fail("CONFLICT", "This account is already linked to another person") @@ -222,126 +46,21 @@ export function createPeopleService(options: PeopleOptions) { p.invite = null log(p, actor, `Linked account ${account.sub}: ${reason}`, now()) } - function candidate(s: PeopleState, v: Viewer, account: Account | undefined) { - if (!account) return null - const rejected = new Set( - Object.values(s.reviews) - .filter((r) => r.sub === v.sub) - .flatMap((r) => r.rejectedPersonIds) - ) - const emailMatches = - account.emailVerified && account.email - ? Object.values(s.persons).filter( - (p) => p.profile.personalEmail?.toLowerCase() === account.email?.toLowerCase() - ) - : [] - const telegramMatch = v.telegramId - ? Object.values(s.persons).find((p) => p.profile.telegramId === v.telegramId) - : null - if (emailMatches.length > 1) { - const r = review(s, v, account, "two-records", emailMatches[0], "Several records use the same verified email") - r.other = ref(emailMatches[1]) - return null - } - if ( - emailMatches[0] && - ((telegramMatch && telegramMatch.id !== emailMatches[0].id) || - (v.telegramId && emailMatches[0].profile.telegramId && emailMatches[0].profile.telegramId !== v.telegramId)) - ) { - const r = review( - s, - v, - account, - "telegram-conflict", - emailMatches[0], - "Verified email and Telegram identity disagree" - ) - r.other = telegramMatch ? ref(telegramMatch) : null - return null - } - const candidates = Object.values(s.persons).filter( - (p) => - !p.accountSub && - !rejected.has(p.id) && - ((v.telegramId && p.profile.telegramId === v.telegramId) || - (account.emailVerified && - account.email && - p.profile.personalEmail?.toLowerCase() === account.email.toLowerCase())) - ) - if (candidates.length === 1) return candidates[0] - const nameMatch = Object.values(s.persons).find( - (p) => nameOf(p).toLowerCase() === account.name.toLowerCase() && !rejected.has(p.id) - ) - if (nameMatch) review(s, v, account, "name-only", nameMatch, "Name-only matches require HR review") - return null - } - function review(s: PeopleState, v: Viewer, account: Account, kind: C.ReviewKind, p: Person | null, message: string) { - const existing = Object.values(s.reviews).find((r) => r.sub === v.sub && r.kind === kind && !r.resolved) - if (existing) return existing - const id = randomUUID() - s.reviews[id] = { - id, - kind, - since: date(), - account: { name: account.name, email: account.email ?? "", telegram: account.telegramId, via: "IdP" }, - record: p ? ref(p) : null, - other: null, - message, - sub: v.sub, - resolved: false, - rejectedPersonIds: [], - } - return s.reviews[id] - } - const receiptForOfficer = (s: PeopleState, v: Viewer, id: string, cie: boolean) => { - requireGeneral(v, "people:receipts:sign") - const r = findReceipt(s, id) - if ( - r.status !== "toSign" || - office(s, v, config) !== r.signer || - config.officers[r.signer] !== r.officerPersonId || - (cie && !v.can("esign:sign")) - ) - fail("FORBIDDEN", "This receipt is not waiting for your signature") - return r - } - const addCensusAnswer = ( - p: Person, - y: string, - entry: C.CensusEntry, - answers: { question: string; answer: string }[], - actor: string - ) => { - p.census = [entry, ...p.census.filter((e) => e.year !== y)] - p.answers[y] = answers - if (entry.answer === "leaving") endRoles(p, `Census ${y}: leaving`, actor) - log(p, actor, `Answered census ${y}: ${entry.answer}`, now()) - } return { async listPeople(v: Viewer) { requireGeneral(v, "people:read") - const telegramGroups = await options.telegramGroups() - return tx((u) => { - hydrateGroups(u.state, telegramGroups) - activeCampaign(u.state) - return Object.values(u.state.persons).map((p) => row(u.state, p, v, config, date())) - }) + return tx((u) => Object.values(u.state.persons).map((p) => row(u.state, p, v))) }, async getPerson(v: Viewer, input: { id: string }) { requireGeneral(v, "people:read") - const telegramGroups = await options.telegramGroups() - return tx((u) => { - hydrateGroups(u.state, telegramGroups) - return record(u.state, find(u.state, input.id), v, config, date()) - }) + return tx((u) => record(u.state, find(u.state, input.id), v)) }, async createPerson(v: Viewer, input: C.CreatePersonInput) { requireGeneral(v, "people:write") return tx((u) => { const p = newPerson(u.state, input, date()) log(p, v.sub, "Created person", now()) - activeCampaign(u.state) return { id: p.id } }) }, @@ -362,96 +81,6 @@ export function createPeopleService(options: PeopleOptions) { log(p, v.sub, "Updated HR note", now()) }) }, - async listMembers(v: Viewer) { - requireGeneral(v, "people:members:read") - return tx((u) => - Object.values(u.state.persons).map((p) => { - fee(p, config, date()) - return C.memberRegisterRowSchema.parse({ - ...p, - profile: { ...p.profile, personalEmail: general(v, "people:read") ? p.profile.personalEmail : null }, - }) - }) - ) - }, - async createMember(v: Viewer, input: C.CreateMemberInput) { - requireGeneral(v, "people:members:write") - return tx(async (u) => { - const p = find(u.state, input.personId) - if (p.member) fail("CONFLICT", "This person already has a membership; update its status instead") - if (Object.values(u.state.persons).some((other) => other.member?.number === input.number)) - fail("CONFLICT", "Member number already used") - if (input.admittedOn > date()) fail("BAD_REQUEST", "Admission date is in the future") - // Issuing a receipt is a payment operation; membership write alone cannot authorize it. - if (input.fee === "paid") { - requireGeneral(v, "people:fees:write") - assertReceiptConfig(u.state) - } - const azure = await options.provisionMember(p, input.number) - p.azureId = azure.id - p.member = { - number: input.number, - status: "active", - admittedOn: input.admittedOn, - fee: "due", - m365Email: azure.email, - } - currentFee(p) - log(p, v.sub, `Admitted member ${input.number}`, now()) - if (input.fee === "paid") - await issue( - u, - p, - { paidOn: input.admittedOn, method: "cash", amountCents: config.feeCents, transferDate: null }, - v.sub, - "Paid on admission" - ) - }) - }, - async setMemberStatus(v: Viewer, input: C.MemberStatusInput) { - requireGeneral(v, "people:members:write") - return tx((u) => { - const p = find(u.state, input.personId) - if (!p.member) fail("CONFLICT", "Not a member") - if (input.status !== "active" && !input.reason) fail("BAD_REQUEST", "A reason is required") - p.member.status = input.status - if (input.status === "former") p.member.fee = null - else currentFee(p) - log(p, v.sub, `Membership ${input.status}: ${input.reason}`, now()) - }) - }, - async setMemberNumber(v: Viewer, input: C.MemberNumberInput) { - requireGeneral(v, "people:members:write") - return tx(async (u) => { - const p = find(u.state, input.personId) - if (!p.member) fail("CONFLICT", "Not a member") - if (Object.values(u.state.persons).some((o) => o.id !== p.id && o.member?.number === input.number)) - fail("CONFLICT", "Member number already used") - await options.setMemberNumber(p, input.number) - p.member.number = input.number - log(p, v.sub, `Changed member number to ${input.number}`, now()) - }) - }, - async exportMembers(v: Viewer) { - requireGeneral(v, "people:members:write") - return tx((u) => ({ - filename: `members-${date()}.csv`, - csv: [ - ["Number", "Name", "Status", "Admitted on", "Microsoft 365 email"], - ...Object.values(u.state.persons) - .filter((p) => p.member) - .map((p) => [ - p.member?.number ?? "", - nameOf(p), - p.member?.status ?? "", - p.member?.admittedOn ?? "", - p.member?.m365Email ?? "", - ]), - ] - .map((r) => r.map(csvCell).join(",")) - .join("\r\n"), - })) - }, async endAdmin(v: Viewer, input: C.EndAdminInput) { requireGeneral(v, "people:write") return tx((u) => { @@ -498,7 +127,7 @@ export function createPeopleService(options: PeopleOptions) { name: C.TEAMS[id].name, lead: lead ? ref(lead) : null, members: people.map((p) => { - const result = row(u.state, p, v, config, date(), true) + const result = row(u.state, p, v, true) if (!general(v, "people:read")) result.teams = result.teams.filter((t) => t.team === id) return result }), @@ -533,7 +162,6 @@ export function createPeopleService(options: PeopleOptions) { fields: input.fields, }) log(p, v.sub, `Joined ${input.teamId} as ${input.role}`, now()) - activeCampaign(u.state) }) }, async updateTeamFields(v: Viewer, input: C.TeamFieldsInput) { @@ -559,458 +187,6 @@ export function createPeopleService(options: PeopleOptions) { log(p, v.sub, `Ended ${input.teamId}: ${input.reason}${input.note ? `; ${input.note}` : ""}`, now()) }) }, - async listCampaigns(v: Viewer) { - requireGeneral(v, "people:read") - return tx((u) => { - activeCampaign(u.state) - return Object.keys(u.state.campaigns) - .sort() - .reverse() - .map((id) => campaignView(u.state, id)) - }) - }, - async getCampaign(v: Viewer, input: { id: string }) { - requireGeneral(v, "people:read") - return tx((u) => { - activeCampaign(u.state) - const c = campaignView(u.state, input.id) - return { - campaign: c, - people: Object.values(u.state.persons) - .filter((p) => p.census.some((e) => e.year === c.year)) - .map((p) => row(u.state, p, v, config, date())), - } - }) - }, - async getAnswers(v: Viewer, input: C.AnswersInput) { - requireGeneral(v, "people:read") - return tx((u) => find(u.state, input.personId).answers[input.year] ?? []) - }, - async closeCampaign(v: Viewer, input: { campaignId: string }) { - requireGeneral(v, "people:write") - return tx((u) => { - const c = campaign(u.state, input.campaignId) - if (c.status === "closed") fail("CONFLICT", "Campaign already closed") - c.status = "closed" - for (const p of Object.values(u.state.persons)) - if (p.census.some((e) => e.year === c.year)) log(p, v.sub, `Closed census ${c.year}`, now()) - }) - }, - async remind(v: Viewer, input: C.RemindInput) { - requireGeneral(v, "people:write") - const result = await tx((u) => { - const c = campaign(u.state, input.campaignId) - if (c.status !== "open") fail("CONFLICT", "Campaign is closed") - const ids: string[] = [] - let skipped = 0 - for (const p of Object.values(u.state.persons).filter((p) => !input.personId || p.id === input.personId)) { - const entry = p.census.find((e) => e.year === c.year) - const last = p.reminders[c.id] - if ( - !entry || - entry.answer || - !p.profile.personalEmail || - (last && now().getTime() - Date.parse(last) < 3 * 86400000) - ) { - skipped++ - continue - } - const id = `census:${c.id}:${p.id}:${date()}` - queue( - u.state, - p, - id, - p.profile.personalEmail, - `Censimento PoliNetwork ${c.year}`, - `Conferma la tua partecipazione: ${config.dashboardUrl}/dashboard/account/me` - ) - p.reminders[c.id] = now().toISOString() - entry.reminders++ - ids.push(id) - log(p, v.sub, `Queued census ${c.year} reminder`, now()) - } - return { ids, skipped } - }) - await this.deliverPending(result.ids) - return tx((u) => { - const sent = result.ids.filter((id) => u.state.outbox[id].status === "sent").length - return { sent, skipped: result.skipped + result.ids.length - sent } - }) - }, - - async importPreview(v: Viewer, input: { campaignId: string; file: File }) { - requireGeneral(v, "people:write") - const parsed = await parseImport(input.file) - const telegramUsers = await options.telegramUsers() - return tx((u) => { - const c = campaign(u.state, input.campaignId) - if (c.status !== "open") fail("CONFLICT", "Campaign is closed") - const preview: C.ImportPreview = { - importId: randomUUID(), - fileName: input.file.name, - rows: parsed.length, - counts: { - newPeople: 0, - updates: 0, - duplicates: 0, - invalid: 0, - discrepancies: 0, - alreadyImported: 0, - leaving: 0, - }, - tabs: { newPeople: [], updates: [], duplicates: [], invalid: [], discrepancies: [], alreadyImported: [] }, - duplicates: [], - telegram: [], - } - const rows: ImportRow[] = [] - const seen = new Set() - const seenEmails = new Set() - for (const source of parsed) { - const fp = `${c.year}:${source.fingerprint}` - const display = { - row: source.row, - name: source.profile ? `${source.profile.firstName} ${source.profile.lastName}` : `Row ${source.row}`, - detail: source.error ?? "", - answer: source.answer, - } - if (u.state.fingerprints[fp] || seen.has(fp)) { - preview.tabs.alreadyImported.push(display) - continue - } - seen.add(fp) - if (source.error || !source.profile || !source.answer || !source.volunteer) { - preview.tabs.invalid.push(display) - continue - } - const inputProfile = source.profile - const emailKey = inputProfile.personalEmail.toLowerCase() - if (seenEmails.has(emailKey)) { - preview.tabs.invalid.push({ ...display, detail: "Another response in this file uses the same email" }) - continue - } - seenEmails.add(emailKey) - const emailMatches = Object.values(u.state.persons).filter( - (p) => p.profile.personalEmail?.toLowerCase() === inputProfile.personalEmail.toLowerCase() - ) - const exact = emailMatches.length === 1 ? emailMatches[0] : null - const possible = - exact ?? Object.values(u.state.persons).find((p) => nameOf(p).toLowerCase() === display.name.toLowerCase()) - const duplicateId = !exact && possible ? `pair-${source.row}` : null - const suggestion = telegramUsers.find( - (t) => t.username?.toLowerCase() === inputProfile.telegramUsername.toLowerCase() - ) - const entry: C.CensusEntry = { - year: c.year, - answer: source.answer, - answeredOn: source.answeredOn ?? date(), - source: "forms", - declaredMember: source.declaredMember, - reminders: 0, - } - rows.push({ - volunteer: source.volunteer, - row: source.row, - fingerprint: fp, - profile: { - ...inputProfile, - phone: inputProfile.phone || null, - telegramUsername: inputProfile.telegramUsername || null, - telegramId: null, - otherAssociations: [], - studentRepresentative: null, - }, - entry, - answers: source.answers, - personId: possible?.id ?? null, - duplicateId, - telegramSuggestion: suggestion?.id ?? null, - }) - const tab = duplicateId ? "duplicates" : exact ? "updates" : "newPeople" - preview.tabs[tab].push({ ...display, detail: possible ? possible.id : "New person" }) - if (duplicateId && possible) - preview.duplicates.push({ - pairId: duplicateId, - row: source.row, - recordId: possible.id, - fields: ["firstName", "lastName", "personalEmail", "course", "year"].map((key) => ({ - label: key, - file: String(inputProfile[key as keyof typeof inputProfile]), - record: String(possible.profile[key as keyof typeof possible.profile]), - mono: key === "personalEmail", - })), - }) - if (inputProfile.telegramUsername) - preview.telegram.push({ - rowId: String(source.row), - name: display.name, - username: inputProfile.telegramUsername, - suggestion: suggestion - ? { - telegramId: suggestion.id, - name: suggestion.name, - info: "Matching bot username; confirmation required", - } - : null, - }) - if (source.declaredMember && !possible?.member) - preview.tabs.discrepancies.push({ ...display, detail: "Declared member but absent from register" }) - if (source.answer === "leaving") preview.counts.leaving++ - } - for (const key of C.IMPORT_TABS) preview.counts[key] = preview.tabs[key].length - u.state.imports[preview.importId] = { - id: preview.importId, - owner: v.sub, - campaignId: c.id, - expiresAt: new Date(now().getTime() + 86400000).toISOString(), - committed: false, - rows, - preview, - } - return preview - }) - }, - async importCommit(v: Viewer, input: C.ImportCommitInput) { - requireGeneral(v, "people:write") - const telegramGroups = await options.telegramGroups() - return tx((u) => { - const batch = u.state.imports[input.importId] - if (!batch || batch.owner !== v.sub || batch.expiresAt < now().toISOString()) - fail("NOT_FOUND", "Import preview expired") - if (batch.committed) return { imported: 0 } - const c = campaign(u.state, batch.campaignId) - if (c.status !== "open") fail("CONFLICT", "Campaign is closed") - const pairs = new Set(batch.rows.flatMap((r) => (r.duplicateId ? [r.duplicateId] : []))) - const telegramRows = new Set(batch.preview.telegram.map((r) => r.rowId)) - if ( - Object.keys(input.duplicates).some((id) => !pairs.has(id)) || - [...pairs].some((id) => !input.duplicates[id]) || - Object.keys(input.telegram).some((id) => !telegramRows.has(id)) - ) - fail("BAD_REQUEST", "Import decisions do not match this preview") - let imported = 0 - for (const r of batch.rows) { - if (u.state.fingerprints[r.fingerprint]) continue - let p = - r.personId && (!r.duplicateId || input.duplicates[r.duplicateId] === "same") - ? find(u.state, r.personId) - : null - if (!p) - p = newPerson( - u.state, - { - ...r.profile, - personalEmail: r.profile.personalEmail ?? "", - phone: r.profile.phone ?? "", - telegramUsername: r.profile.telegramUsername ?? "", - year: C.personInputSchema.shape.year.parse(r.profile.year), - admin: false, - }, - date() - ) - // A Forms import never changes account links or membership; only reviewed volunteer/profile data. - const selected = input.telegram[String(r.row)] - if (selected && selected !== r.telegramSuggestion) - fail("BAD_REQUEST", "Confirm only the Telegram suggestion in this preview") - if ( - selected && - Object.values(u.state.persons).some((other) => other.id !== p.id && other.profile.telegramId === selected) - ) - fail("CONFLICT", "Telegram identity already belongs to another person") - if (p.census.some((e) => e.year === c.year && e.answer)) - fail("CONFLICT", "A census answer changed after the preview; import again") - Object.assign(p.profile, { - firstName: r.profile.firstName, - lastName: r.profile.lastName, - personalEmail: r.profile.personalEmail, - phone: r.profile.phone, - course: r.profile.course, - year: r.profile.year, - campus: r.profile.campus, - telegramUsername: r.profile.telegramUsername, - telegramId: selected || p.profile.telegramId, - }) - if (r.volunteer.otherAssociations) p.profile.otherAssociations = r.volunteer.otherAssociations - if (r.volunteer.studentRepresentative !== undefined) - p.profile.studentRepresentative = r.volunteer.studentRepresentative || null - if (r.entry.answer === "continues") { - if (r.volunteer.admin && p.admin?.status !== "active") - p.admin = { - status: "active", - since: r.entry.answeredOn ?? date(), - endedOn: null, - endReason: null, - groups: [], - requested: [], - availableAsCapo: false, - capoOfReference: null, - capoScope: null, - } - if (p.admin) { - p.admin.availableAsCapo = r.volunteer.availableAsCapo - for (const id of r.volunteer.requestedGroups) { - const group = telegramGroups.find((g) => g.chatId === id) - if (!group) fail("BAD_REQUEST", `Unknown requested Telegram group: ${id}`) - if (!p.admin.requested.some((g) => g.chatId === id)) - p.admin.requested.push({ - chatId: group.chatId, - title: group.title, - requestedOn: r.entry.answeredOn ?? date(), - }) - } - } - for (const team of r.volunteer.teams) - if (!p.teams.some((t) => t.team === team && !t.endedOn)) - p.teams.push({ - team, - role: "member", - since: r.entry.answeredOn ?? date(), - endedOn: null, - endReason: null, - fields: {}, - }) - } - if ( - r.volunteer.privacyVersion && - r.volunteer.privacyAcceptedOn && - (!p.consents.privacy || p.consents.privacy.acceptedOn < r.volunteer.privacyAcceptedOn) - ) - p.consents.privacy = { version: r.volunteer.privacyVersion, acceptedOn: r.volunteer.privacyAcceptedOn } - if ( - r.volunteer.photoConsent && - r.entry.answeredOn && - (!p.consents.photo || p.consents.photo.on < r.entry.answeredOn) - ) - p.consents.photo = { status: r.volunteer.photoConsent, on: r.entry.answeredOn } - addCensusAnswer(p, c.year, r.entry, r.answers, v.sub) - if (r.entry.declaredMember && !p.member) - p.discrepancies.push({ - kind: "declared-member", - message: `Declared membership in census ${c.year}`, - suggestedTelegram: null, - }) - u.state.fingerprints[r.fingerprint] = true - imported++ - } - batch.committed = true - return { imported } - }) - }, - - async listReviews(v: Viewer) { - requireGeneral(v, "people:read") - return tx((u) => - Object.values(u.state.reviews) - .filter((r) => !r.resolved) - .map((r) => C.reviewSchema.parse(r)) - ) - }, - async dismissReview(v: Viewer, input: { reviewId: string }) { - requireGeneral(v, "people:write") - return tx((u) => { - const r = u.state.reviews[input.reviewId] - if (!r || r.resolved) fail("CONFLICT", "Review already handled") - r.resolved = true - if (r.record) { - const p = find(u.state, r.record.id) - if (p.account.status === "review") p.account = { status: "none" } - log(p, v.sub, `Dismissed review ${r.id}`, now()) - } - }) - }, - async resolveReview(v: Viewer, input: C.ResolveReviewInput) { - requireGeneral(v, "people:write") - const accounts = await options.directory() - return tx((u) => { - const r = u.state.reviews[input.reviewId] - if (!r || r.resolved) fail("CONFLICT", "Review already handled") - const linkChoices = ["move-telegram", "link-other", "link-first", "link-second", "link-anyway"] - const allowed: Record = { - "telegram-conflict": ["move-telegram", "ask-details", "link-other"], - "ask-to-be-added": ["add-new", "decline"], - "two-records": ["link-first", "link-second", "merge-first"], - "not-me": ["link-anyway", "add-new", "decline"], - "name-only": ["link-anyway", "add-new", "decline"], - } - if (!allowed[r.kind].includes(input.resolution)) fail("BAD_REQUEST", "Resolution does not apply to this review") - const account = accounts.find((a) => a.sub === r.sub) - if (linkChoices.includes(input.resolution)) { - const target = ["link-other", "link-second"].includes(input.resolution) ? r.other : r.record - if (!target || !account) fail("CONFLICT", "No confirmed account or target record") - if (input.resolution === "move-telegram") { - if (!account.telegramId) fail("CONFLICT", "This account has no verified Telegram identity") - const previous = Object.values(u.state.persons).find( - (p) => p.profile.telegramId === account.telegramId && p.id !== target.id - ) - if (previous) { - previous.profile.telegramId = null - log(previous, v.sub, `Moved Telegram identity to ${target.id}: ${input.reason}`, now()) - } - find(u.state, target.id).profile.telegramId = account.telegramId - } - link(u.state, find(u.state, target.id), account, v.sub, input.reason) - } else if (input.resolution === "add-new") { - if (!account) fail("CONFLICT", "IdP account no longer exists") - const parts = account.name.trim().split(/\s+/) - const p = newPerson( - u.state, - { - firstName: parts.shift() || "Unknown", - lastName: parts.join(" ") || "Unknown", - personalEmail: account.email ?? "", - phone: "", - telegramUsername: "", - course: "To be completed by HR", - year: "Graduated", - campus: "External", - admin: false, - }, - date() - ) - p.discrepancies.push({ - kind: "needs-review", - message: "Created from sign-in; HR must complete the profile and assign requested roles", - suggestedTelegram: null, - }) - if ( - account.telegramId && - !Object.values(u.state.persons).some( - (other) => other.id !== p.id && other.profile.telegramId === account.telegramId - ) - ) - p.profile.telegramId = account.telegramId - link(u.state, p, account, v.sub, input.reason) - } else if (input.resolution === "ask-details") { - if (!account?.email || !r.record) fail("CONFLICT", "No contact address") - queue( - u.state, - find(u.state, r.record.id), - `review-details:${r.id}:${randomUUID()}`, - account.email, - "PoliNetwork · verifica anagrafica", - input.reason - ) - } else if (input.resolution === "merge-first") { - if (!r.record || !r.other || !account) fail("CONFLICT", "Two records and a registered account are required") - const first = find(u.state, r.record.id) - const second = find(u.state, r.other.id) - if ([first.accountSub, second.accountSub].some((sub) => sub && sub !== account.sub)) - fail("CONFLICT", "Unlink the other account before merging") - r.mergedRecord = structuredClone(second) - mergePeople(u.state, first, second, v, config, now()) - link(u.state, first, account, v.sub, input.reason) - } else if (input.resolution === "unlink" && r.record) { - const p = find(u.state, r.record.id) - if (p.accountSub === r.sub) { - p.accountSub = null - p.account = { status: "none" } - log(p, v.sub, `Unlinked account: ${input.reason}`, now()) - } - } - r.resolved = true - if (r.record) - log(find(u.state, r.record.id), v.sub, `Resolved ${r.kind}: ${input.resolution}; ${input.reason}`, now()) - }) - }, async listInvites(v: Viewer) { requireGeneral(v, "people:read") return tx((u) => @@ -1040,7 +216,7 @@ export function createPeopleService(options: PeopleOptions) { `invite:${p.id}:${p.invite.hash}`, p.profile.personalEmail, "PoliNetwork · collega il tuo account", - `${config.dashboardUrl}/dashboard/account/me?peopleInvite=${token}` + `${dashboardUrl}/dashboard/account/me?peopleInvite=${token}` ) log(p, v.sub, "Queued account invitation", now()) }) @@ -1122,691 +298,60 @@ export function createPeopleService(options: PeopleOptions) { }, async getMyArea(v: Viewer): Promise { requireSelf(v) - const linked = await tx((u) => !!own(u.state, v)) - const accounts = linked ? [] : await options.directory() return tx((u) => { const p = own(u.state, v) - if (!p) { - const match = candidate( - u.state, - v, - accounts.find((a) => a.sub === v.sub) - ) - if (match) - return { - state: "match", - candidate: { - ...ref(match), - course: match.profile.course, - year: match.profile.year, - campus: match.profile.campus, - roles: [ - ...(match.admin?.status === "active" ? ["Admin"] : []), - ...match.teams.filter((t) => !t.endedOn).map((t) => C.TEAMS[t.team].name), - ], - }, - reason: - v.telegramId && match.profile.telegramId === v.telegramId - ? "Same verified Telegram account" - : "Same verified email address", - } - const asked = Object.values(u.state.reviews).find( - (r) => r.sub === v.sub && r.kind === "ask-to-be-added" && !r.resolved - ) - return { state: "none", request: asked ? { sentOn: asked.since } : null } - } - const c = activeCampaign(u.state) + if (!p) return { state: "none" } const team = p.teams.find((t) => !t.endedOn)?.team const contacts: Extract["contacts"] = [] const capoId = p.admin?.capoOfReference?.id const capo = capoId ? u.state.persons[capoId] : null if (capo) - contacts.push({ - role: "capo", - name: nameOf(capo), - telegram: capo.profile.telegramUsername, - email: null, - team: null, - }) + contacts.push({ role: "capo", name: nameOf(capo), telegram: capo.profile.telegramUsername, team: null }) for (const other of Object.values(u.state.persons)) { for (const t of other.teams.filter( (t) => !t.endedOn && t.role === "lead" && p.teams.some((mine) => !mine.endedOn && mine.team === t.team) )) - contacts.push({ - role: "lead", - name: nameOf(other), - telegram: other.profile.telegramUsername, - email: other.member?.m365Email ?? null, - team: t.team, - }) + contacts.push({ role: "lead", name: nameOf(other), telegram: other.profile.telegramUsername, team: t.team }) if (other.teams.some((t) => t.team === "hr" && !t.endedOn)) - contacts.push({ - role: "hr", - name: nameOf(other), - telegram: other.profile.telegramUsername, - email: other.member?.m365Email ?? null, - team: "hr", - }) + contacts.push({ role: "hr", name: nameOf(other), telegram: other.profile.telegramUsername, team: "hr" }) } return { state: "linked", - person: record(u.state, p, v, config, date()), - feeInstructions: - p.member && p.member.status !== "former" && config.iban - ? { - beneficiary: config.beneficiary, - iban: config.iban, - reference: `Quota ${year()} ${p.member.number} ${nameOf(p)}`, - } - : null, - campaign: - c.status === "open" && p.census.some((e) => e.year === c.year) - ? { id: c.id, year: c.year, closesOn: c.closesOn } - : null, + person: record(u.state, p, v), contacts, roster: team ? { team, members: Object.values(u.state.persons).flatMap((other) => { const t = other.teams.find((t) => t.team === team && !t.endedOn) - return t - ? [ - { - ...ref(other), - role: t.role, - telegram: other.profile.telegramUsername, - email: other.member?.m365Email ?? null, - }, - ] - : [] + return t ? [{ ...ref(other), role: t.role, telegram: other.profile.telegramUsername }] : [] }), } : null, } }) }, - async confirmMatch(v: Viewer) { - requireSelf(v) - const account = (await options.directory()).find((a) => a.sub === v.sub) - return tx((u) => { - if (own(u.state, v)) return - const p = candidate(u.state, v, account) - if (!p || !account) fail("CONFLICT", "No unique verified match to confirm") - link(u.state, p, account, v.sub, "Confirmed verified identity match") - }) - }, - async rejectMatch(v: Viewer) { - requireSelf(v) - const account = (await options.directory()).find((a) => a.sub === v.sub) - return tx((u) => { - const p = candidate(u.state, v, account) - if (!p || !account) fail("CONFLICT", "No match to reject") - const r = review(u.state, v, account, "not-me", p, "The account holder rejected this match") - r.rejectedPersonIds.push(p.id) - }) - }, - async askToBeAdded(v: Viewer, input: C.AskToBeAddedInput) { - requireSelf(v) - const account = (await options.directory()).find((a) => a.sub === v.sub) - if (!account) fail("PRECONDITION_FAILED", "IdP account unavailable") - return tx((u) => { - if (own(u.state, v)) fail("CONFLICT", "Already linked to a person") - review(u.state, v, account, "ask-to-be-added", null, JSON.stringify(input)) - }) - }, - async answerCensus(v: Viewer, input: C.AnswerCensusInput) { - return tx((u) => { - const p = requireOwn(u.state, v) - const c = activeCampaign(u.state) - if (c.status !== "open" || c.closesOn < date()) fail("CONFLICT", "Census is closed") - if (!p.census.some((e) => e.year === c.year)) fail("FORBIDDEN", "Not expected in this campaign") - if (p.census.some((e) => e.year === c.year && e.answer)) fail("CONFLICT", "Census already answered") - if ( - input.keepTeams.some((id) => !p.teams.some((t) => t.team === id && !t.endedOn)) || - input.keepGroups.some((id) => !p.admin?.groups.some((g) => g.chatId === id)) - ) - fail("BAD_REQUEST", "You can only retain your own roles and groups") - if (input.answer === "leaving" && !input.reason) fail("BAD_REQUEST", "A leaving reason is required") - for (const group of p.admin?.groups ?? []) { - if (input.answer === "continues" && input.keepGroups.includes(group.chatId)) continue - p.pendingGroupRemovals ??= [] - const pending = p.pendingGroupRemovals - if (pending.some((g) => g.chatId === group.chatId)) continue - const message = `Telegram admin removal pending: ${group.title} (${group.chatId}). HR must remove the admin rights; requested in census ${c.year}.` - pending.push({ chatId: group.chatId, message }) - p.discrepancies.push({ kind: "admin-removal", message, suggestedTelegram: null }) - log(p, v.sub, message, now()) - } - Object.assign(p.profile, { course: input.course, year: input.year, campus: input.campus }) - if (input.answer === "continues") { - for (const t of p.teams) - if (!t.endedOn && !input.keepTeams.includes(t.team)) - Object.assign(t, { endedOn: date(), endReason: input.reason || `Census ${c.year}` }) - } - addCensusAnswer( - p, - c.year, - { - year: c.year, - answer: input.answer, - answeredOn: date(), - source: "dashboard", - declaredMember: !!p.member && p.member.status !== "former", - reminders: 0, - }, - Object.entries(input).map(([question, value]) => ({ - question, - answer: Array.isArray(value) ? value.join(", ") : value, - })), - v.sub - ) - }) - }, - async requestCorrection(v: Viewer, input: C.CorrectionInput) { - const account = (await options.directory()).find((a) => a.sub === v.sub) - return tx((u) => { - const p = requireOwn(u.state, v) - if (!account) fail("PRECONDITION_FAILED", "IdP account unavailable") - const text = `Correction: ${input.field} → ${input.value}; ${input.note}` - const r = review(u.state, v, account, "name-only", p, text) - if (!r.message?.includes(text)) r.message = [r.message, text].filter(Boolean).join("\n") - log(p, v.sub, `Requested correction: ${input.field}`, now()) - }) - }, - async revokePhotoConsent(v: Viewer) { - return tx((u) => { - const p = requireOwn(u.state, v) - if (p.consents.photo?.status !== "granted") fail("CONFLICT", "No photo consent to revoke") - p.consents.photo = { status: "revoked", on: date() } - log(p, v.sub, "Revoked photo consent", now()) - }) - }, async getCapoArea(v: Viewer): Promise { requireSelf(v) - const telegramGroups = await options.telegramGroups() return tx((u) => { - hydrateGroups(u.state, telegramGroups) const p = requireOwn(u.state, v) const scope = p.admin?.status === "active" ? p.admin.capoScope : null if (!scope) fail("FORBIDDEN", "No active Capo Admin scope") - const scoped = Object.values(u.state.persons).filter( - (other) => other.admin?.status === "active" && other.admin.capoOfReference?.id === p.id - ) - const ids = new Set( - [...(p.admin?.groups ?? []), ...scoped.flatMap((p) => p.admin?.groups ?? [])].map((g) => g.chatId) - ) - const groups = telegramGroups.filter((g) => ids.has(g.chatId)) - const allowed = new Set(groups.map((g) => g.chatId)) return { scope, - groups: groups.map((g) => ({ chatId: g.chatId, title: g.title, admins: g.admins?.length ?? null })), - admins: scoped.map((p) => { - const r = row(u.state, p, v, config, date(), true) - r.profile.personalEmail = null - return r - }), - requests: scoped.flatMap( - (p) => - p.admin?.requested - .filter((g) => allowed.has(g.chatId)) - .map((g) => ({ - id: `${p.id}:${g.chatId}`, - person: ref(p), - group: { chatId: g.chatId, title: g.title }, - requestedOn: g.requestedOn, - })) ?? [] - ), - } - }) - }, - async handleJoinRequest(v: Viewer, input: { requestId: string }, approve: boolean) { - requireSelf(v) - const telegramGroups = await options.telegramGroups() - return tx((u) => { - hydrateGroups(u.state, telegramGroups) - const me = requireOwn(u.state, v) - if (me.admin?.status !== "active" || !me.admin.capoScope) fail("FORBIDDEN", "No active Capo Admin scope") - const p = Object.values(u.state.persons).find( - (p) => - p.admin?.status === "active" && - p.admin.capoOfReference?.id === me.id && - p.admin.requested.some((g) => `${p.id}:${g.chatId}` === input.requestId) - ) - const g = p?.admin?.requested.find((g) => `${p.id}:${g.chatId}` === input.requestId) - const groupIds = new Set( - [ - ...me.admin.groups, - ...Object.values(u.state.persons) - .filter((p) => p.admin?.status === "active" && p.admin.capoOfReference?.id === me.id) - .flatMap((p) => p.admin?.groups ?? []), - ].map((g) => g.chatId) - ) - if (!p?.admin || !g || !groupIds.has(g.chatId)) fail("CONFLICT", "Request already handled") - p.admin.requested = p.admin.requested.filter((r) => r !== g) - if (approve) - p.discrepancies.push({ - kind: "needs-review", - message: `Approved for ${g.title}; awaiting bot confirmation of Telegram administration`, - suggestedTelegram: null, - }) - log(p, v.sub, `${approve ? "Approved" : "Declined"} request to join ${g.title}`, now()) - }) - }, - - async getFeeReview(v: Viewer, input: { personId: string }) { - requireGeneral(v, "people:fees:write") - return tx((u) => { - const p = find(u.state, input.personId) - const f = currentFee(p) - return { - person: ref(p), - memberNumber: p.member?.number ?? "", - m365Email: p.member?.m365Email ?? "", - fee: C.feeDetailSchema.parse(f), - rejections: f.rejections, - nextReceipt: `${f.year.slice(0, 4)}/${String((u.state.counters[`receipt:${f.year}`] ?? 0) + 1).padStart(3, "0")}`, - } - }) - }, - async getFeeUpload(v: Viewer, input: { personId: string }) { - requireGeneral(v, "people:fees:write") - return tx((u) => { - const f = currentFee(find(u.state, input.personId)) - if (!f.fileId) fail("NOT_FOUND", "No transfer receipt uploaded") - return filePayload(u, f.fileId) - }) - }, - async approveFee(v: Viewer, input: { personId: string }) { - requireGeneral(v, "people:fees:write") - return tx(async (u) => { - const p = find(u.state, input.personId) - const f = currentFee(p) - if (f.status !== "receipt" || !f.upload || !f.fileId) fail("CONFLICT", "No transfer receipt to review") - log(p, v.sub, `Approved fee ${f.year}`, now()) - return issue( - u, - p, - { - paidOn: f.upload.transferDate, - amountCents: f.upload.amountCents, - transferDate: f.upload.transferDate, - method: "transfer", - }, - v.sub, - "Approved transfer receipt" - ) - }) - }, - async rejectFee(v: Viewer, input: C.RejectFeeInput) { - requireGeneral(v, "people:fees:write") - return tx(async (u) => { - const p = find(u.state, input.personId) - const f = currentFee(p) - if (f.status !== "receipt" || !f.fileId) fail("CONFLICT", "No transfer receipt to reject") - await u.deleteFile(f.fileId) - f.fileId = null - f.upload = null - f.rejection = { reason: input.reason, by: v.sub, at: now().toISOString() } - f.rejections.unshift(f.rejection) - f.status = date() > f.dueOn ? "unpaid" : "due" - if (p.member) p.member.fee = f.status - if (p.profile.personalEmail) - queue( - u.state, - p, - `fee-rejection:${randomUUID()}`, - p.profile.personalEmail, - "PoliNetwork · verifica del bonifico", - input.reason - ) - log(p, v.sub, `Rejected fee receipt: ${input.reason}`, now()) - }) - }, - async markFeePaid(v: Viewer, input: C.MarkPaidInput) { - requireGeneral(v, "people:fees:write") - return tx(async (u) => { - const p = find(u.state, input.personId) - const f = currentFee(p) - if (f.status === "receipt") fail("CONFLICT", "Review the uploaded transfer instead") - return issue( - u, - p, - { - paidOn: input.paidOn, - amountCents: input.amountCents, - method: input.method, - transferDate: input.method === "transfer" ? input.paidOn : null, - }, - v.sub, - input.note - ) - }) - }, - async remindFees(v: Viewer, input: C.FeeRemindInput) { - requireGeneral(v, "people:fees:write") - const result = await tx((u) => { - const ids: string[] = [] - let skipped = 0 - for (const p of Object.values(u.state.persons).filter( - (p) => p.member && p.member.status !== "former" && (!input.personId || p.id === input.personId) - )) { - const f = fee(p, config, date()) - if ( - !f || - !["due", "unpaid"].includes(f.status) || - !p.member?.m365Email || - (f.lastReminder && now().getTime() - Date.parse(f.lastReminder) < 3 * 86400000) - ) { - skipped++ - continue - } - const id = `fee-reminder:${p.id}:${f.year}:${date()}` - queue( - u.state, - p, - id, - p.member.m365Email, - `PoliNetwork · quota ${f.year}`, - `Quota associativa da versare entro il ${f.dueOn}: ${config.dashboardUrl}/dashboard/account/me` - ) - f.lastReminder = now().toISOString() - ids.push(id) - log(p, v.sub, `Queued fee reminder ${f.year}`, now()) - } - return { ids, skipped } - }) - await this.deliverPending(result.ids) - return tx((u) => { - const sent = result.ids.filter((id) => u.state.outbox[id].status === "sent").length - return { sent, skipped: result.skipped + result.ids.length - sent } - }) - }, - async listReceipts(v: Viewer, input: { year: string | null }): Promise { - requireGeneral(v, "people:members:read") - return tx((u) => { - const y = input.year ?? year() - const officerRef = (id: string | null) => (id && u.state.persons[id] ? ref(u.state.persons[id]) : null) - return { - year: y, - years: [...new Set([year(), ...Object.values(u.state.receipts).map((r) => r.year)])].sort().reverse(), - viewerSigner: office(u.state, v, config), - officers: { - president: officerRef(config.officers.president), - vicePresident: officerRef(config.officers.vicePresident), - }, - receipts: Object.values(u.state.receipts) - .filter((r) => r.year === y) - .sort(newestReceipts) - .map((r) => C.receiptSchema.parse(r)), - } - }) - }, - async downloadReceipt(v: Viewer, input: { receiptId: string }) { - requireGeneral(v, "people:members:read") - return tx((u) => { - const r = findReceipt(u.state, input.receiptId) - return filePayload(u, r.signedFileId ?? r.originalFileId) - }) - }, - async downloadMyReceipt(v: Viewer, input: { receiptId: string }) { - return tx((u) => { - const p = requireOwn(u.state, v) - const r = u.state.receipts[input.receiptId] - if (!r || r.person.id !== p.id || !["signed", "sent", "failed"].includes(r.status) || !r.signedFileId) - fail("NOT_FOUND", "Signed receipt not found") - return filePayload(u, r.signedFileId) - }) - }, - async prepareReceiptSignatures(v: Viewer, input: C.PrepareReceiptSignaturesInput) { - C.prepareReceiptSignaturesInputSchema.parse(input) - return tx(async (u) => { - const selected = input.receiptIds.map((id) => receiptForOfficer(u.state, v, id, true)) - const signer = own(u.state, v) ?? fail("FORBIDDEN", "Confirmed officer required") - const result: C.ReceiptSignature[] = [] - for (const r of selected) - result.push({ receiptId: r.id, ...(await u.prepareRequest(r, v.sub, nameOf(signer))) }) - return result - }) - }, - async downloadReceiptsToSign(v: Viewer) { - requireGeneral(v, "people:receipts:sign") - return tx(async (u) => { - const signer = office(u.state, v, config) - if (!signer) fail("FORBIDDEN", "Only a confirmed officer can sign receipts") - const selected = Object.values(u.state.receipts).filter((r) => r.status === "toSign" && r.signer === signer) - if (!selected.length) fail("CONFLICT", "No receipts waiting for you") - const zip: Record = {} - for (const r of selected) { - await u.prepareRequest(r, v.sub, nameOf(own(u.state, v) ?? fail("FORBIDDEN", "Confirmed officer required"))) - const file = await u.getFile(r.originalFileId) - if (!file) fail("NOT_FOUND", "Receipt PDF missing") - zip[file.fileName] = file.content - } - return { - fileName: `ricevute-${year().replace("/", "-")}.zip`, - contentType: "application/zip", - base64: Buffer.from(zipSync(zip)).toString("base64"), - } - }) - }, - async previewSignedReceipts(v: Viewer, input: { files: File[] }) { - requireGeneral(v, "people:receipts:sign") - if ( - !input.files.length || - input.files.length > C.MAX_SIGNED_FILES || - input.files.some((f) => !f.size || f.size > MAX_FILE_BYTES) || - input.files.reduce((n, f) => n + f.size, 0) > 50 * 1024 * 1024 - ) - fail("BAD_REQUEST", "Upload 1–100 files, 10 MB each and 50 MB in total") - const prepared = await tx(async (u) => { - const signer = office(u.state, v, config) - if (!signer) fail("FORBIDDEN", "Only a confirmed officer can upload receipts") - const selected = Object.values(u.state.receipts).filter((r) => r.status === "toSign" && r.signer === signer) - return Promise.all( - selected.map(async (r) => ({ - receipt: r, - request: await u.prepareRequest( - r, - v.sub, - nameOf(own(u.state, v) ?? fail("FORBIDDEN", "Confirmed officer required")) - ), - })) - ) - }) - const id = randomUUID() - const files: { - id: string - fileName: string - size: number - receiptId: string | null - valid: boolean - signer: string | null - bytes: Uint8Array - }[] = [] - for (const file of input.files) { - const match = prepared.find(({ receipt: r }) => - new RegExp(`${r.number.replace("/", "[-_ /]")}(?![0-9])`).test(file.name) - ) - const bytes = new Uint8Array(await file.arrayBuffer()) - let valid = false - let signer: string | null = null - const content = bytes - try { - const verified = await options.inspectSigned(v.sub, bytes) - valid = true - signer = verified.signer - } catch { - /* Invalid files stay visible in the preview and cannot be sent. */ - } - files.push({ - id: randomUUID(), - fileName: file.name, - size: bytes.length, - receiptId: match?.receipt.id ?? null, - valid, - signer, - bytes: content, - }) - } - return tx(async (u) => { - const expiresAt = new Date(now().getTime() + 86400000).toISOString() - const batch = { id, owner: v.sub, expiresAt, consumed: false, files: files.map(({ bytes: _, ...f }) => f) } - u.state.batches[id] = batch - for (const f of files) - await u.putFile({ - id: f.id, - fileName: f.fileName, - contentType: "application/pdf", - content: f.bytes, - expiresAt, - }) - return { - uploadId: id, - files: batch.files.map((f) => ({ - fileId: f.id, - fileName: f.fileName, - size: f.size, - receiptId: f.receiptId, - signature: { valid: f.valid, signer: f.signer }, - })), - } - }) - }, - async sendSignedReceipts(v: Viewer, input: C.SendSignedInput) { - requireGeneral(v, "people:receipts:sign") - const planned = await tx(async (u) => { - const b = u.state.batches[input.uploadId] - if (!b || b.owner !== v.sub || b.consumed || b.expiresAt < now().toISOString()) - fail("NOT_FOUND", "Signed upload expired or already used") - const assignments = Object.entries(input.assignments) - if (!assignments.length || new Set(assignments.map(([, r]) => r)).size !== assignments.length) - fail("BAD_REQUEST", "Choose distinct receipts") - const result: { fileId: string; receiptId: string; requestId: string; content: Uint8Array }[] = [] - for (const [fileId, receiptId] of assignments) { - const f = b.files.find((f) => f.id === fileId) - if (!f?.valid) fail("BAD_REQUEST", "Every assigned file must contain a verified signature") - const r = receiptForOfficer(u.state, v, receiptId, false) - const file = await u.getFile(fileId) - if (!file || !r.requestId) fail("NOT_FOUND", "Signed file or signature request missing") - result.push({ fileId, receiptId, requestId: r.requestId, content: file.content }) - } - return result - }) - // Validate every corrected assignment before committing any signature. - for (const p of planned) await options.verifySigned(v.sub, p.requestId, p.content) - let failed = 0 - for (const p of planned) { - try { - await options.completeSigned(v.sub, p.requestId, p.content) - } catch { - failed++ - } - } - await tx(async (u) => { - const b = u.state.batches[input.uploadId] - b.consumed = true - for (const f of b.files) await u.deleteFile(f.id) - }) - await this.deliverPending(planned.map((p) => `receipt:${p.receiptId}`)) - // Count actual delivery results, rather than reporting a queued email as sent. - return tx((u) => { - const receipts = planned.map((p) => u.state.receipts[p.receiptId]) - return { - sent: receipts.filter((r) => r.status === "sent").length, - failed: receipts.filter((r) => r.status !== "sent").length || failed, - } - }) - }, - async retryReceipt(v: Viewer, input: { receiptId: string }) { - requireGeneral(v, "people:fees:write") - await tx((u) => { - const r = findReceipt(u.state, input.receiptId) - if (r.status !== "failed") fail("CONFLICT", "No failed delivery to retry") - const mail = u.state.outbox[`receipt:${r.id}`] - if (!mail || mail.status !== "failed") fail("CONFLICT", "Delivery is already running") - mail.status = "pending" - mail.attemptedAt = null - mail.error = null - r.status = "signed" - r.failure = null - log(find(u.state, r.person.id), v.sub, `Retrying receipt ${r.number}`, now()) - }) - await this.deliverPending([`receipt:${input.receiptId}`]) - }, - async voidReceipt(v: Viewer, input: C.VoidReceiptInput) { - requireGeneral(v, "people:fees:write") - return tx(async (u) => { - const r = findReceipt(u.state, input.receiptId) - if (r.status === "voided") fail("CONFLICT", "Already voided") - const mail = u.state.outbox[`receipt:${r.id}`] - if (mail?.status === "sending") fail("CONFLICT", "Delivery is running; wait for its outcome") - await u.invalidateRequest(r, v.sub) - r.status = "voided" - r.voided = { reason: input.reason, by: v.sub, on: date() } - if (mail?.status === "pending") { - mail.status = "failed" - mail.error = "Receipt voided" - } - const p = find(u.state, r.person.id) - if ( - r.year === year() && - !Object.values(u.state.receipts).some( - (other) => other.person.id === p.id && other.year === r.year && other.status !== "voided" - ) - ) { - const f = fee(p, config, date()) - if (f) { - f.status = date() > f.dueOn ? "unpaid" : "due" - f.payment = null - if (p.member) p.member.fee = f.status - } - } - log(p, v.sub, `Voided receipt ${r.number}: ${input.reason}`, now()) - }) - }, - async uploadTransferReceipt(v: Viewer, input: { file: File; transferDate: string; amountCents: number }) { - requireSelf(v) - if (!input.file.size || input.file.size > MAX_FILE_BYTES) - fail("BAD_REQUEST", "Transfer receipt must be at most 10 MB") - if (input.transferDate > date()) fail("BAD_REQUEST", "Transfer date is in the future") - const bytes = new Uint8Array(await input.file.arrayBuffer()) - const contentType = await options.transferType(bytes) - return tx(async (u) => { - const p = requireOwn(u.state, v) - const f = currentFee(p) - if (!["due", "unpaid"].includes(f.status)) fail("CONFLICT", "This fee is already paid or awaiting review") - const id = randomUUID() - if (f.fileId) await u.deleteFile(f.fileId) - await u.putFile({ id, fileName: input.file.name.slice(0, 200), contentType, content: bytes, expiresAt: null }) - f.fileId = id - f.upload = { - fileName: input.file.name.slice(0, 200), - size: bytes.length, - uploadedAt: now().toISOString(), - transferDate: input.transferDate, - amountCents: input.amountCents, + admins: Object.values(u.state.persons) + .filter((other) => other.admin?.status === "active" && other.admin.capoOfReference?.id === p.id) + .map((other) => { + const r = row(u.state, other, v, true) + r.profile.personalEmail = null + return r + }), } - f.status = "receipt" - f.rejection = null - if (p.member) p.member.fee = "receipt" - log(p, v.sub, `Uploaded fee transfer receipt ${f.year}`, now()) }) }, - async eligibleReceipt(requestId: string, sub: string, can: Viewer["can"], requireEsign = true) { - return tx((u) => { - const r = Object.values(u.state.receipts).find((r) => r.requestId === requestId) - return !!r && receiptEligible(u.state, r, { sub, telegramId: null, can }, config, requireEsign) - }) - }, - async canViewReceipt(receiptId: string, sub: string, can: Viewer["can"]) { - return tx((u) => { - const r = u.state.receipts[receiptId] - const v = { sub, telegramId: null, can } - return !!r && (general(v, "people:members:read") || office(u.state, v, config) === r.signer) - }) - }, - async deliverPending(onlyIds?: readonly string[]) { + /** Sends queued mail; the cron calls it every minute. */ + async deliverPending() { // Claim and record intent before network I/O. Unknown outcomes require an explicit retry. const claimed = await tx((u) => { for (const mail of Object.values(u.state.outbox)) @@ -1817,17 +362,10 @@ export function createPeopleService(options: PeopleOptions) { ) { mail.status = "failed" mail.error = "Delivery outcome unknown after interruption; check the mailbox before retrying" - if (mail.receiptId) { - const r = u.state.receipts[mail.receiptId] - if (r.status !== "voided") { - r.status = "failed" - r.failure = mail.error - } - } } const pending = Object.values(u.state.outbox) - .filter((m) => m.status === "pending" && (!onlyIds || onlyIds.includes(m.id))) - .slice(0, onlyIds?.length ?? 20) + .filter((m) => m.status === "pending") + .slice(0, 20) for (const mail of pending) { mail.status = "sending" mail.attemptedAt = now().toISOString() @@ -1837,10 +375,7 @@ export function createPeopleService(options: PeopleOptions) { for (const mail of claimed) { let error: string | null = null try { - const fileId = mail.fileId - const file = fileId ? await tx((u) => u.getFile(fileId)) : null - if (mail.fileId && !file) throw new Error("Attachment is missing") - await options.sendMail({ id: mail.id, to: mail.to, subject: mail.subject, text: mail.text, attachment: file }) + await options.sendMail({ id: mail.id, to: mail.to, subject: mail.subject, text: mail.text }) } catch (err) { error = err instanceof Error ? err.message : String(err) } @@ -1850,67 +385,10 @@ export function createPeopleService(options: PeopleOptions) { current.status = error ? "failed" : "sent" current.error = error const p = u.state.persons[mail.personId] - if (error && mail.id.startsWith("fee-reminder:")) { - const year = mail.id.split(":")[2] - if (p.feeYears[year]) p.feeYears[year].lastReminder = null - } - if (error && mail.id.startsWith("census:")) { - const campaignId = mail.id.split(":")[1] - delete p.reminders[campaignId] - const entry = p.census.find((e) => e.year === u.state.campaigns[campaignId]?.year) - if (entry) entry.reminders = Math.max(0, entry.reminders - 1) - } - if (mail.receiptId) { - const r = u.state.receipts[mail.receiptId] - if (r.status !== "voided") { - r.status = error ? "failed" : "sent" - r.failure = error - if (!error) { - r.sentAt = now().toISOString() - r.sentTo = mail.to - } - } - log( - p, - "system", - error ? `Receipt ${r.number} email failed: ${error}` : `Emailed receipt ${r.number}`, - now() - ) - } else log(p, "system", error ? `Email failed: ${error}` : `Sent email: ${mail.subject}`, now()) + log(p, "system", error ? `Email failed: ${error}` : `Sent email: ${mail.subject}`, now()) }) } }, - async sweep() { - await tx(async (u) => { - activeCampaign(u.state) - for (const [id, batch] of Object.entries(u.state.batches)) - if (batch.expiresAt < now().toISOString()) { - for (const f of batch.files) await u.deleteFile(f.id) - delete u.state.batches[id] - } - for (const [id, batch] of Object.entries(u.state.imports)) - if (batch.expiresAt < now().toISOString()) delete u.state.imports[id] - for (const p of Object.values(u.state.persons)) { - const f = fee(p, config, date()) - if (!f || f.status !== "due" || !p.member?.m365Email) continue - const days = Math.round((Date.parse(f.dueOn) - Date.parse(date())) / 86400000) - if (![14, 3].includes(days)) continue - const id = `fee-auto:${p.id}:${f.year}:${days}` - if (u.state.outbox[id]) continue - queue( - u.state, - p, - id, - p.member.m365Email, - `PoliNetwork · quota ${f.year}`, - `Scadenza quota associativa: ${f.dueOn}. ${config.dashboardUrl}/dashboard/account/me` - ) - f.lastReminder = now().toISOString() - log(p, "system", `Queued automatic fee reminder ${f.year} (${days} days)`, now()) - } - }) - await this.deliverPending() - }, } } export type PeopleService = ReturnType diff --git a/src/people/store-pg.ts b/src/people/store-pg.ts index d775ee0..9580d33 100644 --- a/src/people/store-pg.ts +++ b/src/people/store-pg.ts @@ -1,30 +1,24 @@ -import { createHash, randomUUID } from "node:crypto" -import { and, eq, inArray, sql } from "drizzle-orm" +import { eq, inArray, sql } from "drizzle-orm" import type { DB } from "@/db" -import { documents, events, jobs, profiles, requests, signers } from "@/db/schema/esign/esign" -import { files, identities, receiptRequests, receipts, records } from "@/db/schema/people" -import { EsignError } from "@/esign/errors" -import type { SignatureCommit } from "@/esign/store" -import { emptyState, type PeopleState, type PeopleStore, type StoredReceipt, type UnitOfWork } from "./types" +import { identities, records } from "@/db/schema/people" +import { emptyState, type PeopleState, type PeopleStore } from "./types" -export type Database = typeof DB -export type Transaction = Parameters[0]>[0] -/** Lock order: People metadata, eSign request, eSign profile. Shared by void, preparation and completion. */ -export const lockPeople = (tx: Transaction) => tx.execute(sql`select pg_advisory_xact_lock(198074, 1)`) +type Database = typeof DB +type Transaction = Parameters[0]>[0] +/** Serializes every People transaction. */ +const lockPeople = (tx: Transaction) => tx.execute(sql`select pg_advisory_xact_lock(198074, 1)`) -export async function loadState(tx: Transaction): Promise { +async function loadState(tx: Transaction): Promise { const state = emptyState() for (const row of await tx.select().from(records)) { const separator = row.id.indexOf(":") Object.assign(state[row.kind], { [row.id.slice(separator + 1)]: row.data }) } - for (const row of await tx.select().from(receipts)) state.receipts[row.id] = row.data return state } -export async function saveState(tx: Transaction, state: PeopleState, before: PeopleState) { +async function saveState(tx: Transaction, state: PeopleState, before: PeopleState) { for (const kind of Object.keys(state) as (keyof PeopleState)[]) { - if (kind === "receipts") continue for (const [id, data] of Object.entries(state[kind])) { if (JSON.stringify(data) === JSON.stringify(before[kind][id])) continue await tx @@ -36,7 +30,7 @@ export async function saveState(tx: Transaction, state: PeopleState, before: Peo if (!(id in state[kind])) await tx.delete(records).where(eq(records.id, `${kind}:${id}`)) } } - // Clear changed and removed unique values first so moving an identity between records (or merging them) is atomic. + // Clear changed and removed unique values first so moving an identity between records is atomic. const changed = Object.values(state.persons).filter((p) => JSON.stringify(p) !== JSON.stringify(before.persons[p.id])) const removed = Object.keys(before.persons).filter((id) => !(id in state.persons)) if (changed.length || removed.length) @@ -45,106 +39,8 @@ export async function saveState(tx: Transaction, state: PeopleState, before: Peo await tx.insert(identities).values({ personId: p.id, accountSub: p.accountSub, - memberNumber: p.member?.number, telegramId: p.profile.telegramId, }) - for (const receipt of Object.values(state.receipts)) { - if (JSON.stringify(receipt) === JSON.stringify(before.receipts[receipt.id])) continue - await tx - .insert(receipts) - .values({ id: receipt.id, number: receipt.number, requestId: receipt.requestId, data: receipt }) - .onConflictDoUpdate({ target: receipts.id, set: { requestId: receipt.requestId, data: receipt } }) - } -} - -export function unitOfWork(tx: Transaction, state: PeopleState): UnitOfWork { - return { - state, - async getFile(id) { - const [file] = await tx.select().from(files).where(eq(files.id, id)) - return file ? { ...file, expiresAt: file.expiresAt?.toISOString() ?? null } : null - }, - async putFile(file) { - await tx - .insert(files) - .values({ ...file, expiresAt: file.expiresAt ? new Date(file.expiresAt) : null }) - .onConflictDoUpdate({ target: files.id, set: { expiresAt: file.expiresAt ? new Date(file.expiresAt) : null } }) - }, - async deleteFile(id) { - await tx.delete(files).where(eq(files.id, id)) - }, - async prepareRequest(receipt, sub, signerName) { - const title = `Receipt ${receipt.number} · ${receipt.person.name}` - if (receipt.requestId) { - const [existing] = await tx.select().from(requests).where(eq(requests.id, receipt.requestId)) - const [mapping] = await tx - .select() - .from(receiptRequests) - .where(eq(receiptRequests.requestId, receipt.requestId)) - if ( - existing?.status === "in_progress" && - mapping?.officerSub === sub && - mapping.originalHash === receipt.sha256 - ) - return { requestId: receipt.requestId, title } - await this.invalidateRequest(receipt, sub) - } - const original = await this.getFile(receipt.originalFileId) - if (!original || createHash("sha256").update(original.content).digest("hex") !== receipt.sha256) - throw new EsignError("conflict", "The issued receipt changed") - const id = randomUUID() - await tx.insert(profiles).values({ sub, name: signerName }).onConflictDoNothing() - await tx - .insert(requests) - .values({ id, title, ordered: true, createdBySub: sub, drives: [], output: null, email: null }) - await tx.insert(documents).values({ - requestId: id, - version: 0, - fileName: original.fileName, - content: original.content, - sha256: receipt.sha256, - size: original.content.length, - pages: 1, - source: { kind: "upload" }, - createdBySub: sub, - }) - await tx.insert(signers).values({ - requestId: id, - position: 0, - sub, - name: signerName, - role: receipt.signer === "president" ? "Presidente" : "Vicepresidente", - places: [{ kind: "signature", page: 0, x: 0.56, y: 0.69, width: 0.35, height: 0.09 }], - }) - receipt.requestId = id - await tx - .insert(receipts) - .values({ id: receipt.id, number: receipt.number, requestId: id, data: receipt }) - .onConflictDoUpdate({ target: receipts.id, set: { requestId: id, data: receipt } }) - await tx - .insert(receiptRequests) - .values({ requestId: id, receiptId: receipt.id, officerSub: sub, originalHash: receipt.sha256 }) - await tx - .insert(events) - .values({ requestId: id, actorSub: sub, type: "created", data: { peopleReceipt: receipt.id } }) - return { requestId: id, title } - }, - async invalidateRequest(receipt, actor) { - if (!receipt.requestId) return - const [request] = await tx.select().from(requests).where(eq(requests.id, receipt.requestId)).for("update") - if (request?.status === "in_progress") { - await tx - .update(requests) - .set({ status: "cancelled", cancelledAt: new Date() }) - .where(eq(requests.id, request.id)) - await tx - .update(jobs) - .set({ status: "cancelled", preparedPdf: null }) - .where(and(eq(jobs.requestId, request.id), inArray(jobs.status, ["pending", "prepared"]))) - await tx.insert(events).values({ requestId: request.id, actorSub: actor, type: "people_invalidated" }) - } - }, - } } export function createPeoplePgStore(db: Database): PeopleStore { @@ -154,74 +50,9 @@ export function createPeoplePgStore(db: Database): PeopleStore { await lockPeople(tx) const state = await loadState(tx) const before = structuredClone(state) - const result = await fn(unitOfWork(tx, state)) + const result = await fn({ state }) await saveState(tx, state, before) return result }), } } - -/** Called inside eSign's transaction before it locks the request. */ -export async function guardReceiptSignature( - tx: Transaction, - commit: SignatureCommit, - eligible: (receipt: StoredReceipt, sub: string, state: PeopleState, requireEsign: boolean) => boolean -) { - const [mapping] = await tx.select().from(receiptRequests).where(eq(receiptRequests.requestId, commit.requestId)) - if (!mapping) return - await lockPeople(tx) - const state = await loadState(tx) - const receipt = state.receipts[mapping.receiptId] - if ( - !receipt || - receipt.requestId !== commit.requestId || - receipt.status !== "toSign" || - receipt.sha256 !== mapping.originalHash || - mapping.officerSub !== commit.identity.sub || - commit.baseVersion !== 0 || - !eligible(receipt, commit.identity.sub, state, !commit.receiptManual) - ) - throw new EsignError("forbidden", "This receipt is no longer assigned to you") -} - -/** Signature, retained PDF, activity and a unique delivery intent commit together. */ -export async function completeReceiptSignature(tx: Transaction, commit: SignatureCommit) { - if (!commit.complete) return - const [mapping] = await tx.select().from(receiptRequests).where(eq(receiptRequests.requestId, commit.requestId)) - if (!mapping) return - const state = await loadState(tx) - const before = structuredClone(state) - const receipt = state.receipts[mapping.receiptId] - const fileId = `signed:${receipt.id}` - await unitOfWork(tx, state).putFile({ - id: fileId, - fileName: commit.receiptEnvelope?.fileName ?? commit.document.fileName, - contentType: commit.receiptEnvelope ? "application/pkcs7-mime" : "application/pdf", - content: commit.receiptEnvelope?.content ?? commit.document.content, - expiresAt: null, - }) - receipt.signedFileId = fileId - receipt.status = "signed" - receipt.signedBy = - typeof commit.event.data?.name === "string" ? commit.event.data.name : commit.identity.certificateSubject - receipt.signedOn = new Date().toISOString() - state.persons[receipt.person.id].activity.unshift({ - actor: commit.identity.sub, - text: `Signed receipt ${receipt.number}`, - at: receipt.signedOn, - }) - const id = `receipt:${receipt.id}` - state.outbox[id] ??= { - id, - personId: receipt.person.id, - receiptId: receipt.id, - to: receipt.recipient, - subject: `Ricevuta ${receipt.number} · PoliNetwork`, - text: `Quota associativa ${receipt.year}. In allegato la ricevuta firmata.`, - fileId, - status: "pending", - attemptedAt: null, - error: null, - } - await saveState(tx, state, before) -} diff --git a/src/people/types.ts b/src/people/types.ts index 6ac15ab..03435dc 100644 --- a/src/people/types.ts +++ b/src/people/types.ts @@ -1,132 +1,32 @@ -import type { Campaign, CensusEntry, FeeDetail, ImportPreview, PersonRecord, Receipt, Review } from "./contract" +import type { PersonRecord } from "./contract" export type Viewer = { sub: string; telegramId: string | null; can: (permission: string) => boolean } -export type Person = Omit & { +export type Person = PersonRecord & { accountSub: string | null - azureId: string | null - feeYears: Record[]; fileId: string | null }> - answers: Record - reminders: Record invite: { hash: string; expiresAt: string } | null - pendingGroupRemovals?: { chatId: string; message: string }[] -} -export type StoredReceipt = Receipt & { - officerPersonId: string - originalFileId: string - signedFileId: string | null - sha256: string - requestId: string | null - recipient: string -} -export type StoredReview = Review & { - sub: string - resolved: boolean - rejectedPersonIds: string[] - mergedRecord?: Person -} -export type ImportRow = { - volunteer: { - admin: boolean - teams: import("./contract").TeamId[] - requestedGroups: string[] - availableAsCapo: boolean - otherAssociations?: string[] - studentRepresentative?: string - privacyVersion: string - privacyAcceptedOn: string | null - photoConsent: "granted" | "denied" | null - } - row: number - fingerprint: string - profile: Person["profile"] - entry: CensusEntry - answers: { question: string; answer: string }[] - personId: string | null - duplicateId: string | null - telegramSuggestion: string | null -} -export type StoredImport = { - id: string - owner: string - campaignId: string - expiresAt: string - committed: boolean - rows: ImportRow[] - preview: ImportPreview -} -export type SignedBatch = { - id: string - owner: string - expiresAt: string - consumed: boolean - files: { - id: string - fileName: string - size: number - receiptId: string | null - valid: boolean - signer: string | null - }[] } export type Outbox = { id: string personId: string - receiptId: string | null to: string subject: string text: string - fileId: string | null status: "pending" | "sending" | "sent" | "failed" attemptedAt: string | null error: string | null } export type PeopleState = { persons: Record - receipts: Record - campaigns: Record - reviews: Record - imports: Record - batches: Record outbox: Record counters: Record - fingerprints: Record } export const emptyState = (): PeopleState => ({ persons: {}, - receipts: {}, - campaigns: {}, - reviews: {}, - imports: {}, - batches: {}, outbox: {}, counters: {}, - fingerprints: {}, }) -export type StoredFile = { - id: string - fileName: string - contentType: string - content: Uint8Array - expiresAt: string | null -} -export type Officer = "president" | "vicePresident" -export type PeopleConfig = { - officers: Record - feeCents: number - beneficiary: string - iban: string - legalName: string - address: string - taxCode: string - dashboardUrl: string -} export type UnitOfWork = { state: PeopleState - getFile(id: string): Promise - putFile(file: StoredFile): Promise - deleteFile(id: string): Promise - prepareRequest(receipt: StoredReceipt, sub: string, signerName: string): Promise<{ requestId: string; title: string }> - invalidateRequest(receipt: StoredReceipt, actor: string): Promise } export interface PeopleStore { transaction(fn: (uow: UnitOfWork) => Promise): Promise @@ -136,8 +36,4 @@ export type Account = { name: string email: string | null telegramId: string | null - emailVerified?: boolean } -export type TelegramUser = { id: string; name: string; username: string | null } -/** `admins` is null while the group's admin list is unknown: People then keeps the groups it last knew. */ -export type TelegramGroup = { chatId: string; title: string; admins: string[] | null } diff --git a/tests/people-azure.test.ts b/tests/people-azure.test.ts deleted file mode 100644 index da9878d..0000000 --- a/tests/people-azure.test.ts +++ /dev/null @@ -1,40 +0,0 @@ -import { beforeEach, expect, it, vi } from "vitest" -import { newPerson } from "@/people/model" -import { emptyState } from "@/people/types" -import { profile } from "./people-fixtures" - -vi.mock("@/azure/config", () => ({ azureCredentials: null })) -vi.mock("@/env", () => ({ env: { NODE_ENV: "test" } })) -vi.mock("@/emails/mailer", () => ({ sendWelcomeEmail: vi.fn().mockResolvedValue(true) })) -vi.mock("@/azure/directory", async () => ({ - azureDirectory: (await import("@/azure/mock-directory")).createMockAzureDirectory(), -})) -beforeEach(() => { - vi.resetModules() - vi.restoreAllMocks() -}) - -it("refuses a People number change held by another Microsoft 365 account", async () => { - const { setMemberNumber } = await import("@/people/azure-members") - const person = newPerson(emptyState(), profile(), "2026-10-22") - person.azureId = "mock-member-alan" - await expect(setMemberNumber(person, "1001")).rejects.toMatchObject({ code: "CONFLICT" }) - const { azureDirectory } = await import("@/azure/directory") - expect((await azureDirectory.getMember(person.azureId))?.employeeId).toBe("1002") -}) - -it("reserves People writes for the legacy Azure workflow while Graph searches lag", async () => { - const { provisionMember } = await import("@/people/azure-members") - const { numberHolder } = await import("@/azure/member-writes") - const { azureDirectory } = await import("@/azure/directory") - vi.spyOn(azureDirectory, "findByMemberNumber").mockResolvedValue(null) - const person = newPerson(emptyState(), profile(), "2026-10-22") - const created = await provisionMember(person, "2042") - expect(await numberHolder(2042)).toMatchObject({ id: created.id, employeeId: "2042" }) -}) - -it("does not take over an unrelated same-name Microsoft 365 account", async () => { - const { provisionMember } = await import("@/people/azure-members") - const person = newPerson(emptyState(), profile("Ada", "Lovelace"), "2026-10-22") - await expect(provisionMember(person, "1001")).rejects.toMatchObject({ code: "CONFLICT" }) -}) diff --git a/tests/people-fixtures.ts b/tests/people-fixtures.ts index 6ca83d9..190934b 100644 --- a/tests/people-fixtures.ts +++ b/tests/people-fixtures.ts @@ -1,27 +1,8 @@ -import { randomUUID } from "node:crypto" import { vi } from "vitest" -import { transferType } from "@/people/files" import { newPerson } from "@/people/model" import { createPeopleService, type PeopleOptions } from "@/people/service" -import { - type Account, - emptyState, - type PeopleConfig, - type PeopleState, - type StoredFile, - type Viewer, -} from "@/people/types" +import { type Account, emptyState, type Viewer } from "@/people/types" -export const config: PeopleConfig = { - officers: { president: "P-0001", vicePresident: "P-0002" }, - feeCents: 1000, - beneficiary: "PoliNetwork APS", - iban: "IT60X0542811101000000123456", - legalName: "PoliNetwork APS", - address: "Via di prova 1, Milano", - taxCode: "12345678901", - dashboardUrl: "https://admin.example.org", -} export const profile = (firstName = "Mario", lastName = "Rossi") => ({ firstName, lastName, @@ -38,68 +19,25 @@ export const viewer = (sub: string, permissions: string[], telegramId: string | telegramId, can: (key) => permissions.includes(key), }) -export const permissions = [ - "admin:access", - "people:self", - "people:read", - "people:write", - "people:members:read", - "people:members:write", - "people:fees:write", - "people:receipts:sign", - "people:appoint", - "esign:sign", -] +export const permissions = ["admin:access", "people:self", "people:read", "people:write", "people:appoint"] export const master = viewer("president", permissions) -export const vice = viewer("vice", permissions) /** A rollback-capable serialized unit of work; production concurrency is tested separately against PostgreSQL. */ export function harness(overrides: Partial = {}) { let state = emptyState() - let files = new Map() let tail: Promise = Promise.resolve() let clock = new Date("2026-10-18T10:00:00Z") - const requests = new Map() const accounts: Account[] = [ - { sub: "president", name: "Mario Rossi", email: "mario@example.org", emailVerified: true, telegramId: "101" }, - { sub: "vice", name: "Anna Bianchi", email: "anna@example.org", emailVerified: true, telegramId: "102" }, - { sub: "member", name: "Luca Verdi", email: "luca@example.org", emailVerified: true, telegramId: "103" }, + { sub: "president", name: "Mario Rossi", email: "mario@example.org", telegramId: "101" }, + { sub: "vice", name: "Anna Bianchi", email: "anna@example.org", telegramId: "102" }, + { sub: "member", name: "Luca Verdi", email: "luca@example.org", telegramId: "103" }, ] const store: PeopleOptions["store"] = { transaction(fn) { const run = tail.then(async () => { const draft = structuredClone(state) - const nextFiles = structuredClone(files) - const nextRequests = structuredClone(requests) - const result = await fn({ - state: draft, - getFile: async (id) => nextFiles.get(id) ?? null, - putFile: async (file) => { - nextFiles.set(file.id, file) - }, - deleteFile: async (id) => { - nextFiles.delete(id) - }, - async prepareRequest(receipt) { - const prior = receipt.requestId ? nextRequests.get(receipt.requestId) : null - if (!prior || prior.status !== "in_progress") { - receipt.requestId = randomUUID() - nextRequests.set(receipt.requestId, { id: receipt.requestId, status: "in_progress" }) - } - return { - requestId: receipt.requestId as string, - title: `Receipt ${receipt.number} · ${receipt.person.name}`, - } - }, - async invalidateRequest(receipt) { - const r = receipt.requestId ? nextRequests.get(receipt.requestId) : null - if (r) r.status = "cancelled" - }, - }) + const result = await fn({ state: draft }) state = draft - files = nextFiles - requests.clear() - for (const [id, request] of nextRequests) requests.set(id, request) return result }) tail = run.catch(() => {}) @@ -107,31 +45,12 @@ export function harness(overrides: Partial = {}) { }, } const sendMail = vi.fn().mockResolvedValue(undefined) - const provisionMember = vi.fn().mockImplementation(async (p) => ({ - id: `azure-${p.id}`, - email: `${p.profile.firstName.toLowerCase()}@polinetwork.org`, - })) - const setMemberNumber = vi.fn().mockResolvedValue(undefined) const service = createPeopleService({ store, - config, + dashboardUrl: "https://admin.example.org", now: () => clock, directory: async () => accounts, - telegramGroups: async () => [], - telegramUsers: async () => [], - provisionMember, - setMemberNumber, sendMail, - verifySigned: async () => { - throw new Error("No signing fixture") - }, - inspectSigned: async () => { - throw new Error("No signing fixture") - }, - completeSigned: async () => { - throw new Error("No signing fixture") - }, - transferType, ...overrides, }) async function seed() { @@ -158,32 +77,11 @@ export function harness(overrides: Partial = {}) { service, store, state: () => structuredClone(state), - files: () => structuredClone(files), - requests, accounts, sendMail, - provisionMember, - setMemberNumber, seed, advance: (ms: number) => { clock = new Date(clock.getTime() + ms) }, - setDate: (d: string) => { - clock = new Date(d) - }, } } - -export async function admit(h: ReturnType, id = "P-0003", number = "0003") { - await h.service.createMember(master, { personId: id, number, admittedOn: "2026-10-01", fee: "due" }) -} -export async function issue(h: ReturnType, id = "P-0003") { - await h.service.markFeePaid(master, { - personId: id, - amountCents: 1000, - paidOn: "2026-10-17", - method: "cash", - note: "At the event", - }) - return Object.values(h.state().receipts).at(-1) as PeopleState["receipts"][string] -} diff --git a/tests/people-imports.test.ts b/tests/people-imports.test.ts deleted file mode 100644 index 5ac3541..0000000 --- a/tests/people-imports.test.ts +++ /dev/null @@ -1,167 +0,0 @@ -import { strToU8, zipSync } from "fflate" -import { describe, expect, it } from "vitest" -import { transferType } from "@/people/files" -import { parseImport, unzipBounded } from "@/people/imports" -import { harness, master, profile, viewer } from "./people-fixtures" - -const header = "firstName,lastName,personalEmail,phone,telegramUsername,course,year,campus,answer" -const csv = `${header}\nSara,Neri,sara@example.org,,sara_test,Informatica,2nd year,Leonardo,continues\n` -const csvFile = (text = csv) => new File([text], "export.csv") - -describe("People census imports", () => { - it("previews, commits and deduplicates real CSV responses without touching membership", async () => { - const h = harness() - await h.seed() - await h.service.listCampaigns(master) - const preview = await h.service.importPreview(master, { campaignId: "2026/27", file: csvFile() }) - expect(preview.counts).toMatchObject({ newPeople: 1, invalid: 0, duplicates: 0 }) - expect(await h.service.importCommit(master, { importId: preview.importId, duplicates: {}, telegram: {} })).toEqual({ - imported: 1, - }) - expect(await h.service.importCommit(master, { importId: preview.importId, duplicates: {}, telegram: {} })).toEqual({ - imported: 0, - }) - const again = await h.service.importPreview(master, { campaignId: "2026/27", file: csvFile() }) - expect(again.counts.alreadyImported).toBe(1) - const p = h.state().persons["P-0004"] - expect(p).toMatchObject({ member: null, accountSub: null, census: [{ answer: "continues", source: "forms" }] }) - }) - it("keeps only the first response for a person in one census file", async () => { - const h = harness() - await h.seed() - await h.service.listCampaigns(master) - const file = csvFile( - `${header}\nSara,Neri,sara@example.org,,sara_test,Informatica,2nd year,Leonardo,continues\nSara,Neri,SARA@example.org,,sara_test,Informatica,2nd year,Leonardo,leaving\n` - ) - const preview = await h.service.importPreview(master, { campaignId: "2026/27", file }) - expect(preview.counts).toMatchObject({ newPeople: 1, invalid: 1 }) - expect(preview.tabs.invalid[0].detail).toContain("same email") - expect(await h.service.importCommit(master, { importId: preview.importId, duplicates: {}, telegram: {} })).toEqual({ - imported: 1, - }) - expect( - Object.values(h.state().persons).filter((p) => p.profile.personalEmail?.toLowerCase() === "sara@example.org") - ).toHaveLength(1) - }) - it("requires the preview's exact duplicate decisions and isolates previews by owner", async () => { - const h = harness() - await h.seed() - await h.service.createPerson(master, { ...profile("Sara", "Neri"), personalEmail: "other@example.org" }) - await h.service.listCampaigns(master) - const preview = await h.service.importPreview(master, { campaignId: "2026/27", file: csvFile() }) - expect(preview.counts.duplicates).toBe(1) - await expect( - h.service.importCommit(master, { importId: preview.importId, duplicates: {}, telegram: {} }) - ).rejects.toMatchObject({ code: "BAD_REQUEST" }) - await expect( - h.service.importCommit(viewer("someone-else", ["admin:access", "people:write"]), { - importId: preview.importId, - duplicates: { [preview.duplicates[0].pairId]: "same" }, - telegram: {}, - }) - ).rejects.toMatchObject({ code: "NOT_FOUND" }) - expect( - await h.service.importCommit(master, { - importId: preview.importId, - duplicates: { [preview.duplicates[0].pairId]: "different" }, - telegram: {}, - }) - ).toEqual({ imported: 1 }) - expect(Object.values(h.state().persons)).toHaveLength(5) - }) - it("ends volunteer roles on leaving while preserving association membership", async () => { - const h = harness() - await h.seed() - await h.service.listCampaigns(master) - await h.service.createMember(master, { personId: "P-0003", number: "0003", admittedOn: "2026-10-01", fee: "due" }) - const file = csvFile(`${header}\nLuca,Verdi,luca@example.org,,,Informatica,2nd year,Leonardo,leaving\n`) - const preview = await h.service.importPreview(master, { campaignId: "2026/27", file }) - await h.service.importCommit(master, { importId: preview.importId, duplicates: {}, telegram: {} }) - expect(h.state().persons["P-0003"]).toMatchObject({ - admin: { status: "former" }, - member: { status: "active", number: "0003" }, - accountSub: "member", - }) - }) - it("rejects a stale preview rather than overwriting a newer dashboard answer", async () => { - const h = harness() - await h.seed() - await h.service.listCampaigns(master) - const file = csvFile(`${header}\nLuca,Verdi,luca@example.org,,,Informatica,2nd year,Leonardo,continues\n`) - const preview = await h.service.importPreview(master, { campaignId: "2026/27", file }) - await h.service.answerCensus(viewer("member", ["people:self"]), { - answer: "continues", - course: "New course", - year: "3rd year", - campus: "Bovisa", - keepGroups: [], - keepTeams: [], - reason: "", - note: "", - }) - await expect( - h.service.importCommit(master, { importId: preview.importId, duplicates: {}, telegram: {} }) - ).rejects.toMatchObject({ code: "CONFLICT" }) - expect(h.state().persons["P-0003"].profile.course).toBe("New course") - }) - it("parses a real XLSX container, shared strings and inline values", async () => { - const headers = header.split(",") - const values = [ - "Sara", - "Neri", - "sara@example.org", - "", - "sara_test", - "Informatica", - "2nd year", - "Leonardo", - "continues", - ] - const cells = (values: string[], row: number) => - `${values.map((v, i) => `${v}`).join("")}` - const bytes = zipSync({ - "[Content_Types].xml": strToU8(""), - "xl/workbook.xml": strToU8(""), - "xl/worksheets/sheet1.xml": strToU8( - `${cells(headers, 1)}${cells(values, 2)}` - ), - }) - const parsed = await parseImport(new File([new Uint8Array(bytes)], "actually-a-workbook.csv")) - expect(parsed[0]).toMatchObject({ - answer: "continues", - profile: { firstName: "Sara", campus: "Leonardo" }, - error: null, - }) - }) - it("checks content, archive budgets, row bounds and CSV quoting", async () => { - await expect(parseImport(new File(["not a workbook"], "fake.xlsx"))).rejects.toMatchObject({ code: "BAD_REQUEST" }) - await expect(parseImport(new File([new Uint8Array([0xff, 0xfe])], "invalid-utf8.csv"))).rejects.toMatchObject({ - code: "BAD_REQUEST", - }) - await expect( - parseImport(new File([zipSync({ "file.txt": strToU8("text") })], "archive.xlsx")) - ).rejects.toMatchObject({ code: "BAD_REQUEST" }) - await expect(parseImport(csvFile(`${header}\n"unclosed`))).rejects.toMatchObject({ code: "BAD_REQUEST" }) - await expect( - parseImport(csvFile(`${header}\n${"Sara,Neri,sara@example.org,,,IT,2nd year,Leonardo,continues\n".repeat(5001)}`)) - ).rejects.toMatchObject({ code: "BAD_REQUEST" }) - const many = Object.fromEntries(Array.from({ length: 1001 }, (_, i) => [`f${i}`, new Uint8Array()])) - expect(() => unzipBounded(zipSync(many))).toThrow() - expect(() => unzipBounded(zipSync({ "large.xml": new Uint8Array(51 * 1024 * 1024) }))).toThrow() - }) - it("rejects fake or corrupt transfer images even with a matching extension", async () => { - await expect(transferType(new TextEncoder().encode("not an image.png"))).rejects.toMatchObject({ - code: "BAD_REQUEST", - }) - await expect(transferType(new Uint8Array([0xff, 0xd8, 0xff, 0, 0xff, 0xd9]))).rejects.toMatchObject({ - code: "BAD_REQUEST", - }) - const png = new Uint8Array( - Buffer.from( - "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+jRZkAAAAASUVORK5CYII=", - "base64" - ) - ) - expect(await transferType(png)).toBe("image/png") - }) -}) diff --git a/tests/people-postgres.fixture.ts b/tests/people-postgres.fixture.ts index b80028f..200d4ab 100644 --- a/tests/people-postgres.fixture.ts +++ b/tests/people-postgres.fixture.ts @@ -1,23 +1,13 @@ import assert from "node:assert/strict" import { SQL } from "bun" -import { eq } from "drizzle-orm" import { drizzle } from "drizzle-orm/bun-sql" import { migrate } from "drizzle-orm/bun-sql/migrator" import { schema } from "@/db/schema" -import { jobs, requests as requestTable } from "@/db/schema/esign/esign" -import { identities, receiptRequests, receipts } from "@/db/schema/people" -import { buildSignedData, CMS_OID, dataToBeSigned, sha256, signedAttributes } from "@/esign/pdf/cms" -import { children, contextTag, octetString, oid, read, sequence } from "@/esign/pdf/der" -import { inspectPdf } from "@/esign/pdf/inspect" -import { finalizeSignature, prepareSignature } from "@/esign/pdf/pades" -import { createEsignService } from "@/esign/service" -import { createPgStore } from "@/esign/store-pg" -import { transferType } from "@/people/files" -import { newPerson, receiptEligible } from "@/people/model" +import { identities } from "@/db/schema/people" +import { newPerson } from "@/people/model" import { createPeopleService } from "@/people/service" -import { completeReceiptSignature, createPeoplePgStore, guardReceiptSignature } from "@/people/store-pg" -import type { PeopleConfig, PeopleState, Viewer } from "@/people/types" -import { cardSign, createTestCa } from "./esign-fixtures" +import { createPeoplePgStore } from "@/people/store-pg" +import type { Viewer } from "@/people/types" const connection = { hostname: "127.0.0.1", @@ -34,82 +24,22 @@ const checked: string[] = [] try { await migrate(db, { migrationsFolder: "./drizzle" }) const store = createPeoplePgStore(db) - const config: PeopleConfig = { - officers: { president: "P-0001", vicePresident: "P-0002" }, - feeCents: 1000, - beneficiary: "PoliNetwork APS", - iban: "IT60X0542811101000000123456", - legalName: "PoliNetwork APS", - address: "Via Test 1, Milano", - taxCode: "12345678901", - dashboardUrl: "https://admin.example.org", - } - const permissionSet = new Set([ - "admin:access", - "people:self", - "people:read", - "people:write", - "people:members:read", - "people:members:write", - "people:fees:write", - "people:receipts:sign", - "people:appoint", - "esign:sign", - ]) + const permissionSet = new Set(["admin:access", "people:self", "people:read", "people:write", "people:appoint"]) const viewer = (sub: string): Viewer => ({ sub, telegramId: null, can: (p) => permissionSet.has(p) }) - const president = viewer("president") - const vice = viewer("vice") + const hr = viewer("hr") const directory = [ - { sub: "president", name: "Mario Rossi", email: "president@example.org", emailVerified: true, telegramId: "101" }, - { sub: "vice", name: "Anna Bianchi", email: "vice@example.org", emailVerified: true, telegramId: "102" }, - { sub: "member", name: "Luca Verdi", email: "member@example.org", emailVerified: true, telegramId: "103" }, + { sub: "mario", name: "Mario Rossi", email: "mario@example.org", telegramId: "101" }, + { sub: "anna", name: "Anna Bianchi", email: "anna@example.org", telegramId: "102" }, + { sub: "luca", name: "Luca Verdi", email: "luca@example.org", telegramId: "103" }, ] - const outboxCalls: string[] = [] - const eligible = (r: PeopleState["receipts"][string], sub: string, state: PeopleState, requireEsign: boolean) => - receiptEligible(state, r, viewer(sub), config, requireEsign) - const esignStore = createPgStore(db, { - beforeSignature: (tx, commit) => guardReceiptSignature(tx, commit, eligible), - afterSignature: completeReceiptSignature, - }) - const esign = createEsignService({ - store: esignStore, - drives: [], - directory: async () => directory, - access: () => ({ roles: [], permissions: [...permissionSet] }), - receiptCanView: (receiptId, sub) => people.canViewReceipt(receiptId, sub, viewer(sub).can), - receiptEligible: async (id, sub, requireEsign) => people.eligibleReceipt(id, sub, viewer(sub).can, requireEsign), - mailer: { - signatureRequest: async () => true, - signedDocument: async () => { - throw new Error("eSign must never send receipt email") - }, - requestUpdate: async () => true, - }, - logger: { info() {}, warn() {}, error() {} }, - dashboardUrl: config.dashboardUrl, - allowTestCertificates: true, - revocation: "off", - }) + const sent: string[] = [] const people = createPeopleService({ store, - config, + dashboardUrl: "https://admin.example.org", directory: async () => directory, - telegramGroups: async () => [], - telegramUsers: async () => [], - provisionMember: async (p) => ({ - id: `azure-${p.id}`, - email: `${p.profile.firstName.toLowerCase()}@polinetwork.org`, - }), - setMemberNumber: async () => {}, sendMail: async (m) => { - outboxCalls.push(m.id) - }, - inspectSigned: (sub, bytes) => esign.inspectUpload(sub, bytes), - verifySigned: (sub, id, bytes) => esign.verifyUpload({ sub, canManage: false, peopleManual: true }, id, bytes), - completeSigned: async (sub, id, bytes) => { - await esign.uploadSigned({ sub, canManage: false, peopleManual: true }, id, bytes) + sent.push(m.id) }, - transferType, }) await store.transaction(async ({ state }) => { for (const a of directory) { @@ -129,198 +59,49 @@ try { }, "2026-10-01" ) - p.accountSub = a.sub p.profile.telegramId = a.telegramId - p.account = { status: "linked", email: a.email, via: "IdP", linkedOn: "2026-10-01", how: "fixture" } } }) - assert.equal((await people.listPeople(president)).length, 3) + assert.equal((await people.listPeople(hr)).length, 3) checked.push("migrations and PostgreSQL metadata round-trip") - await people.createMember(president, { personId: "P-0003", number: "0003", admittedOn: "2026-10-01", fee: "due" }) - const payment = { - personId: "P-0003", - paidOn: "2026-10-17", - amountCents: 1000, - method: "cash" as const, - note: "Integration test", - } - const issueResults = await Promise.allSettled([ - people.markFeePaid(president, payment), - people.markFeePaid(president, payment), - ]) - assert.equal(issueResults.filter((r) => r.status === "fulfilled").length, 1) - let [receipt] = await db.select().from(receipts) - assert.equal(receipt.number, "2026/001") - const [a, b] = await Promise.all([ - people.prepareReceiptSignatures(president, { receiptIds: [receipt.id] }), - people.prepareReceiptSignatures(president, { receiptIds: [receipt.id] }), - ]) - assert.equal(a[0].requestId, b[0].requestId) - assert.equal((await db.select().from(receiptRequests)).length, 1) - checked.push("concurrent issue and idempotent receipt/request uniqueness") - const requestId = a[0].requestId - const caller = { sub: "president", canManage: true } - assert.deepEqual((await esign.getRequest(caller, requestId)).request.peopleReceipt, { - receiptId: receipt.id, - number: receipt.number, - year: "2026/27", - }) - assert.equal((await esign.listRequests(caller, "inbox"))[0].myTurn, true) - await assert.rejects(esign.cancelRequest(caller, requestId), /Void receipts/) - await assert.rejects(esign.deleteRequest(caller, requestId), /retained/) - await assert.rejects( - esign.createJob(caller, requestId, [{ page: 0, x: 0.1, y: 0.1, width: 0.1, height: 0.1 }]), - /fixed/ - ) - checked.push("eSign provenance, fixed placement and permanent receipt retention") - const ca = await createTestCa() - const signer = await ca.issue("ROSSI MARIO", "RSSMRA80A01F205X") - const { ticket } = await esign.createJob(caller, requestId) - await esign.agentJob(ticket) - const prepared = await esign.agentPrepare(ticket, Buffer.from(signer.cert).toString("base64"), [], 2) - const signature = await cardSign(signer, new Uint8Array(Buffer.from(prepared.toBeSigned, "base64"))) - permissionSet.delete("people:receipts:sign") - assert.equal((await esign.getRequest(caller, requestId)).request.myTurn, false) - await assert.rejects(esign.agentComplete(ticket, Buffer.from(signature).toString("base64")), /assigned/) - permissionSet.add("people:receipts:sign") - await esign.agentComplete(ticket, Buffer.from(signature).toString("base64")) - ;[receipt] = await db.select().from(receipts) - assert.equal(receipt.data.status, "signed") - assert.equal((await store.transaction(async ({ state }) => Object.keys(state.outbox))).length, 1) - // No browser callbacks: a fresh service worker drains the persistent outbox. - await Promise.all([people.deliverPending(), people.deliverPending()]) - assert.equal(outboxCalls.length, 1) - ;[receipt] = await db.select().from(receipts) - assert.equal(receipt.data.status, "sent") - const own = await people.downloadMyReceipt(viewer("member"), { receiptId: receipt.id }) - assert.equal((await inspectPdf(new Uint8Array(Buffer.from(own.base64, "base64")))).signatures[0].verified, true) - checked.push("real RSA/CIE job, permission revocation, atomic completion and one durable email") - await assert.rejects(people.downloadMyReceipt(vice, { receiptId: receipt.id }), /not found/) - await people.voidReceipt(president, { receiptId: receipt.id, reason: "Test replacement" }) - await people.markFeePaid(president, payment) - const all = await db.select().from(receipts) - const replacement = all.find((r) => r.number === "2026/002") - assert.ok(replacement) - const [replacementRequest] = await people.prepareReceiptSignatures(president, { receiptIds: [replacement.id] }) - const replacementOriginal = await esignStore.latestDocument(replacementRequest.requestId) - assert.ok(replacementOriginal) - const external = await prepareSignature(replacementOriginal.content, signer.cert, { - placement: { page: 0, x: 0.56, y: 0.69, width: 0.35, height: 0.09 }, - signerName: "Mario Rossi", - fieldName: "Firma", - signingTime: new Date(), - reason: "Membership fee", - appearance: { lines: [{ text: "Mario Rossi" }] }, - }) - const signedPdf = finalizeSignature(external, await cardSign(signer, external.toBeSigned)) - const pendingJob = await esign.createJob(caller, replacementRequest.requestId) - // The manual path commits through exactly the same transaction and cancels the agent's older job. - const upload = await people.previewSignedReceipts(president, { - files: [new File([new Uint8Array(signedPdf)], "unmatched.pdf")], - }) - assert.equal(upload.files[0].signature.valid, true) - assert.equal(upload.files[0].receiptId, null) - assert.deepEqual( - await people.sendSignedReceipts(president, { - uploadId: upload.uploadId, - assignments: { [upload.files[0].fileId]: replacement.id }, - }), - { sent: 1, failed: 0 } + + const created = await Promise.all( + ["Sara", "Paolo"].map((firstName) => + people.createPerson(hr, { + firstName, + lastName: "Neri", + personalEmail: `${firstName.toLowerCase()}@example.org`, + phone: "", + telegramUsername: "", + course: "Informatica", + year: "1st year", + campus: "Leonardo", + admin: false, + }) + ) ) - assert.equal((await esignStore.getJob(pendingJob.jobId))?.status, "cancelled") + assert.deepEqual(created.map((c) => c.id).sort(), ["P-0004", "P-0005"]) + checked.push("concurrent writes are serialized") + + await people.linkAccount(hr, { personId: "P-0001", accountId: "mario", reason: "Checked in person" }) await assert.rejects( - esign.agentPrepare(pendingJob.ticket, Buffer.from(signer.cert).toString("base64"), [], 2), - /cancelled|no longer|already signed/ - ) - checked.push("manual PAdES correction, shared completion, race invalidation and non-reused numbers") - await people.voidReceipt(president, { receiptId: replacement.id, reason: "Voided after signing" }) - assert.equal( - (await db.select().from(requestTable).where(eq(requestTable.id, replacementRequest.requestId)))[0].status, - "completed" - ) - assert.equal( - (await db.select().from(jobs)).filter((j) => j.status === "prepared" || j.status === "pending").length, - 0 + people.linkAccount(hr, { personId: "P-0002", accountId: "mario", reason: "Wrong person" }), + /already linked/ ) - assert.equal((await db.select().from(receiptRequests)).length, 2) - checked.push("voiding preserves signed files, association history and finished eSign requests") - await people.markFeePaid(president, payment) - const third = (await db.select().from(receipts)).find((r) => r.number === "2026/003") - assert.ok(third) - const [thirdRequest] = await people.prepareReceiptSignatures(president, { receiptIds: [third.id] }) - const thirdOriginal = await esignStore.latestDocument(thirdRequest.requestId) - assert.ok(thirdOriginal) - const attrs = signedAttributes(sha256(thirdOriginal.content), signer.cert) - const detached = buildSignedData({ - signedAttrs: attrs, - signature: await cardSign(signer, dataToBeSigned(attrs)), - certDer: signer.cert, - }) - const sd = children(children(children(read(detached))[1])[0]) - const envelope = sequence( - oid(CMS_OID.signedData), - contextTag( - 0, - sequence( - ...sd.map((part, index) => - index === 2 ? sequence(oid(CMS_OID.data), contextTag(0, octetString(thirdOriginal.content))) : part.raw - ) - ) - ) - ) - const cmsUpload = await people.previewSignedReceipts(president, { - files: [new File([new Uint8Array(envelope)], "Ricevuta_2026-003.pdf.p7m")], - }) - assert.equal(cmsUpload.files[0].signature.valid, true) + await people.unlinkAccount(hr, { personId: "P-0001" }) + await people.linkAccount(hr, { personId: "P-0002", accountId: "mario", reason: "Moved" }) + const rows = await db.select().from(identities) assert.deepEqual( - await people.sendSignedReceipts(president, { - uploadId: cmsUpload.uploadId, - assignments: { [cmsUpload.files[0].fileId]: third.id }, - }), - { sent: 1, failed: 0 } + rows.filter((i) => i.accountSub).map((i) => [i.personId, i.accountSub]), + [["P-0002", "mario"]] ) - const signedEnvelope = await people.downloadMyReceipt(viewer("member"), { receiptId: third.id }) - assert.equal(signedEnvelope.contentType, "application/pkcs7-mime") - assert.deepEqual(Buffer.from(signedEnvelope.base64, "base64"), Buffer.from(envelope)) - checked.push("CAdES envelope verifies the exact issued PDF and retains the original cryptographic evidence") - const duplicates = await store.transaction(async ({ state }) => - ["104", null].map((telegramId) => { - const p = newPerson( - state, - { - firstName: "Sara", - lastName: "Neri", - personalEmail: "sara@example.org", - phone: "", - telegramUsername: "", - course: "Informatica", - year: "1st year", - campus: "Leonardo", - admin: false, - }, - "2026-10-01" - ) - p.profile.telegramId = telegramId - return p.id - }) - ) - await people.createMember(president, { - personId: duplicates[1], - number: "0042", - admittedOn: "2026-10-01", - fee: "due", - }) - directory.push({ sub: "sara", name: "Sara Neri", email: "sara@example.org", emailVerified: true, telegramId: "104" }) - await people.getMyArea(viewer("sara")) - const review = (await people.listReviews(president)).find((r) => r.kind === "two-records") - assert.ok(review) - await people.resolveReview(president, { reviewId: review.id, resolution: "merge-first", reason: "Same student" }) - // The removed record's unique identities are released before the retained record takes them over. - const merged = (await db.select().from(identities)).find((i) => i.personId === duplicates[0]) - assert.deepEqual(merged, { personId: duplicates[0], accountSub: "sara", memberNumber: "0042", telegramId: "104" }) - assert.equal((await db.select().from(identities)).filter((i) => i.personId === duplicates[1]).length, 0) - assert.equal((await people.getMyArea(viewer("sara"))).state, "linked") - checked.push("merging duplicates moves membership and identities without unique violations") + checked.push("an account moves between records without unique violations") + + await people.sendInvite(hr, { personId: "P-0003" }) + await Promise.all([people.deliverPending(), people.deliverPending()]) + assert.equal(sent.length, 1) + assert.equal((await people.listInvites(hr))[0].personId, "P-0003") + checked.push("an invitation is delivered once from the durable outbox") console.log(JSON.stringify({ checked })) } finally { await client.close() diff --git a/tests/people-postgres.test.ts b/tests/people-postgres.test.ts index 6a9b2f2..46a5a3f 100644 --- a/tests/people-postgres.test.ts +++ b/tests/people-postgres.test.ts @@ -3,14 +3,14 @@ import { promisify } from "node:util" import { expect, it } from "vitest" it.skipIf(!process.env.SEED_TEST_DB_PORT)( - "commits receipt signatures and delivery against real PostgreSQL", + "persists People records, identities and the mail outbox in real PostgreSQL", async () => { const { stdout } = await promisify(execFile)("bun", ["tests/people-postgres.fixture.ts"], { env: process.env, timeout: 60000, }) const result = JSON.parse(stdout.trim().split("\n").at(-1) ?? "{}") - expect(result.checked).toHaveLength(8) + expect(result.checked).toHaveLength(4) }, 65000 ) diff --git a/tests/people-router.test.ts b/tests/people-router.test.ts index c0abeb2..8ed7597 100644 --- a/tests/people-router.test.ts +++ b/tests/people-router.test.ts @@ -49,36 +49,45 @@ describe("People tRPC contract", () => { r.createCaller(context(permissions, undefined, ["backend:public:read"])).me.get() ).rejects.toMatchObject({ code: "FORBIDDEN" }) }) - it("validates profiles and returns only the register projection", async () => { + it("validates profiles before reaching People", async () => { const h = harness() await h.seed() const r = makeRouter(h.service) await expect( r.createCaller(context()).persons.create({ ...profile(), firstName: "X".repeat(81) }) ).rejects.toMatchObject({ code: "BAD_REQUEST" }) - const rows = await r.createCaller(context(["admin:access", "people:members:read"])).members.list() - expect(Object.keys(rows[0]).sort()).toEqual(["account", "id", "member", "profile"]) - expect(rows[0].profile.personalEmail).toBeNull() + expect(h.state().counters.person).toBe(3) }) - it("mounts every procedure used by admin #100 with a dashboard policy", () => { + it("mounts every People procedure with a dashboard policy", () => { const r = makeRouter(harness().service) const procedures = (r as unknown as { _def: { procedures: Record } })._def .procedures const defs = Object.entries(procedures) - expect(defs.length).toBe(62) for (const [, proc] of defs) expect(proc._def.meta).toMatchObject({ policy: { user: { scope: "backend:admin" } } }) - for (const path of [ + expect(Object.keys(procedures).sort()).toEqual([ + "admins.end", + "admins.setCapoOfReference", + "admins.setCapoScope", + "capo.get", + "linking.invites", + "linking.link", + "linking.revokeInvite", + "linking.searchAccounts", + "linking.sendInvite", + "linking.unlink", + "me.acceptInvite", + "me.get", + "me.roles", + "persons.create", + "persons.get", "persons.list", - "members.list", + "persons.setNote", + "persons.update", + "teams.addMember", "teams.candidates", - "census.importPreview", - "linking.resolve", - "capo.approve", - "me.roles", - "fees.review", - "receipts.prepareSignatures", - "receipts.sendSigned", + "teams.endMembership", + "teams.list", + "teams.updateFields", ]) - expect(procedures[path]).toBeDefined() }) }) diff --git a/tests/people.test.ts b/tests/people.test.ts index df779a5..ff6d1b5 100644 --- a/tests/people.test.ts +++ b/tests/people.test.ts @@ -1,58 +1,19 @@ -import { describe, expect, it, vi } from "vitest" +import { describe, expect, it } from "vitest" import { myAreaSchema } from "@/people/contract" -import { isValidIban } from "@/people/iban" -import { academicYear, csvCell, today } from "@/people/model" -import { samplePdf } from "./esign-fixtures" -import { admit, harness, issue, master, permissions, vice, viewer } from "./people-fixtures" +import { harness, master, viewer } from "./people-fixtures" describe("People authorization and projections", () => { - it("validates the configured IBAN country length and mod-97 checksum", () => { - expect(isValidIban("IT60X0542811101000000123456")).toBe(true) - expect(isValidIban("IT61X0542811101000000123456")).toBe(false) - expect(isValidIban("IT60X054281110100000012345")).toBe(false) - expect(isValidIban("ZZ60X0542811101000000123456")).toBe(false) - }) - it("does not load Telegram users for ordinary People reads", async () => { - const telegramUsers = vi.fn(async () => []) - const h = harness({ telegramUsers }) - await h.seed() - await h.service.listPeople(master) - expect(telegramUsers).not.toHaveBeenCalled() - }) - it("keeps the member register independent of general read access", async () => { - const h = harness() - await h.seed() - await admit(h) - const v = viewer("register", ["admin:access", "people:members:read"]) - const rows = await h.service.listMembers(v) - expect(rows[2]).toEqual({ - id: "P-0003", - profile: { firstName: "Luca", lastName: "Verdi", personalEmail: null }, - member: expect.objectContaining({ number: "0003" }), - account: { status: "linked" }, - }) - expect(rows[0].member).toBeNull() - await expect(h.service.listPeople(v)).rejects.toMatchObject({ code: "FORBIDDEN" }) - await expect(h.service.listMembers(viewer("stray", ["people:members:read"]))).rejects.toMatchObject({ - code: "FORBIDDEN", - }) - await expect( - h.service.listMembers(viewer("write-only", ["admin:access", "people:members:write"])) - ).rejects.toMatchObject({ code: "FORBIDDEN" }) - }) - it("redacts member details from People reads but keeps own membership in My area", async () => { + it("shows the signed-in person their own record without HR notes or activity", async () => { const h = harness() await h.seed() - await admit(h) - const read = viewer("reader", ["admin:access", "people:read"]) - const p = await h.service.getPerson(read, { id: "P-0003" }) - expect(p).toMatchObject({ isMember: true, member: null, fees: null }) + await h.service.setNote(master, { id: "P-0003", note: "HR only" }) const mine = await h.service.getMyArea(viewer("member", ["people:self"])) expect(myAreaSchema.parse(mine)).toMatchObject({ state: "linked", - person: { member: { number: "0003" }, notes: null, fees: { current: { status: "due" } } }, + person: { id: "P-0003", notes: null, activity: [], profile: { personalEmail: "luca@example.org" } }, }) expect(JSON.stringify(mine)).not.toContain("accountSub") + expect(await h.service.getPerson(master, { id: "P-0003" })).toMatchObject({ notes: "HR only" }) }) it("scopes Leads to their confirmed teams and requires appointment rights to end another Lead", async () => { const h = harness() @@ -119,25 +80,20 @@ describe("People authorization and projections", () => { const teams = await h.service.listTeams(viewer("president", ["people:self"])) expect(teams[0].members.map((p) => p.id)).toEqual(["P-0001"]) }) - it("preserves every correction when an open name review already exists", async () => { + it("shows a Capo Admin only the admins they are the reference for, without personal emails", async () => { const h = harness() await h.seed() - const member = viewer("member", ["people:self"]) - await h.service.requestCorrection(member, { field: "Something else", value: "Luca Maria", note: "Updated name" }) - await h.service.requestCorrection(member, { - field: "Personal email", - value: "luca.new@example.org", - note: "New address", + await h.service.setCapoScope(master, { personId: "P-0001", scope: "Ingegneria Informatica" }) + await h.service.setCapoOfReference(master, { personId: "P-0003", capoId: "P-0001" }) + const capo = await h.service.getCapoArea(viewer("president", ["people:self"])) + expect(capo.scope).toBe("Ingegneria Informatica") + expect(capo.admins.map((p) => p.id)).toEqual(["P-0003"]) + expect(capo.admins[0].profile.personalEmail).toBeNull() + await expect(h.service.getCapoArea(viewer("member", ["people:self"]))).rejects.toMatchObject({ + code: "FORBIDDEN", }) - expect(Object.values(h.state().reviews)).toHaveLength(1) - expect(Object.values(h.state().reviews)[0].message).toContain( - "Correction: Something else → Luca Maria; Updated name" - ) - expect(Object.values(h.state().reviews)[0].message).toContain( - "Correction: Personal email → luca.new@example.org; New address" - ) }) - it("does not grant record roles or mutation rights to an unconfirmed match", async () => { + it("grants no record roles to an account that is not linked", async () => { const h = harness() await h.seed() await h.store.transaction(async ({ state }) => { @@ -148,25 +104,9 @@ describe("People authorization and projections", () => { p.teams.push({ team: "it", role: "lead", since: "2026-10-01", endedOn: null, endReason: null, fields: {} }) }) const v = viewer("president", ["people:self"], "101") - expect(await h.service.getMyArea(v)).toMatchObject({ state: "match", candidate: { id: "P-0001" } }) + expect(await h.service.getMyArea(v)).toEqual({ state: "none" }) expect(await h.service.getMyRoles(v)).toEqual({ capoScope: null, leads: [] }) await expect(h.service.getCapoArea(v)).rejects.toMatchObject({ code: "FORBIDDEN" }) - await expect(h.service.revokePhotoConsent(v)).rejects.toMatchObject({ code: "FORBIDDEN" }) - await h.service.rejectMatch(v) - expect(await h.service.getMyArea(v)).toMatchObject({ state: "none" }) - await expect(h.service.confirmMatch(v)).rejects.toMatchObject({ code: "CONFLICT" }) - }) - it("does not trust an unverified directory email for self matching", async () => { - const h = harness() - await h.seed() - await h.store.transaction(async ({ state }) => { - state.persons["P-0003"].accountSub = null - state.persons["P-0003"].account = { status: "none" } - }) - h.accounts[2].emailVerified = false - expect(await h.service.getMyArea(viewer("member", ["people:self"]))).toMatchObject({ state: "none" }) - h.accounts[2].emailVerified = true - expect(await h.service.getMyArea(viewer("member", ["people:self"]))).toMatchObject({ state: "match" }) }) it("prevents account takeover and invalidates old invitation tokens", async () => { const h = harness() @@ -190,302 +130,47 @@ describe("People authorization and projections", () => { }) }) -describe("People payments, receipt ownership and delivery", () => { - it("cannot replace a membership or claim a non-uploaded transfer", async () => { - const h = harness() - await h.seed() - await admit(h) - await expect(admit(h)).rejects.toMatchObject({ code: "CONFLICT" }) - expect(h.provisionMember).toHaveBeenCalledTimes(1) - await expect(h.service.approveFee(master, { personId: "P-0003" })).rejects.toMatchObject({ code: "CONFLICT" }) - await expect( - h.service.createMember(viewer("membership", ["admin:access", "people:members:write"]), { - personId: "P-0002", - number: "0002", - admittedOn: "2026-10-01", - fee: "paid", - }) - ).rejects.toMatchObject({ code: "FORBIDDEN" }) - }) - it("reviews actual uploads, keeps rejection history and issues one receipt atomically", async () => { - const h = harness() - await h.seed() - await admit(h) - const me = viewer("member", ["people:self"]) - const file = new File([new Uint8Array(await samplePdf())], "transfer.pdf") - await h.service.uploadTransferReceipt(me, { file, transferDate: "2026-10-16", amountCents: 1000 }) - await expect( - h.service.markFeePaid(master, { - personId: "P-0003", - amountCents: 1000, - paidOn: "2026-10-16", - method: "cash", - note: "", - }) - ).rejects.toMatchObject({ code: "CONFLICT" }) - await h.service.rejectFee(master, { personId: "P-0003", reason: "Wrong beneficiary" }) - expect(h.state().persons["P-0003"].feeYears["2026/27"]).toMatchObject({ - status: "due", - rejection: { reason: "Wrong beneficiary" }, - fileId: null, - }) - await h.service.uploadTransferReceipt(me, { file, transferDate: "2026-10-17", amountCents: 1000 }) - const result = await Promise.allSettled([ - h.service.approveFee(master, { personId: "P-0003" }), - h.service.approveFee(master, { personId: "P-0003" }), - ]) - expect(result.map((r) => r.status).sort()).toEqual(["fulfilled", "rejected"]) - expect(Object.values(h.state().receipts)).toHaveLength(1) - expect((await h.service.getFeeReview(master, { personId: "P-0003" })).rejections).toHaveLength(1) - }) - it("keeps receipt numbering after void and assigns the President's own receipt to the Vice-president", async () => { - const h = harness() - await h.seed() - await admit(h, "P-0001", "0001") - const receipt = await issue(h, "P-0001") - expect(receipt).toMatchObject({ number: "2026/001", signer: "vicePresident" }) - await expect(h.service.prepareReceiptSignatures(master, { receiptIds: [receipt.id] })).rejects.toMatchObject({ - code: "FORBIDDEN", - }) - const prepared = await h.service.prepareReceiptSignatures(vice, { receiptIds: [receipt.id] }) - expect(await h.service.prepareReceiptSignatures(vice, { receiptIds: [receipt.id] })).toEqual(prepared) - await h.service.voidReceipt(master, { receiptId: receipt.id, reason: "Wrong amount" }) - expect(h.requests.get(prepared[0].requestId)?.status).toBe("cancelled") - expect((await issue(h, "P-0001")).number).toBe("2026/002") - expect(Object.values(h.state().receipts)).toHaveLength(2) - }) - it("validates a full preparation batch before creating requests and requires both CIE permissions", async () => { - const h = harness() - await h.seed() - await admit(h) - const r = await issue(h) - await admit(h, "P-0001", "0001") - const other = await issue(h, "P-0001") - await expect(h.service.prepareReceiptSignatures(master, { receiptIds: [r.id, other.id] })).rejects.toMatchObject({ - code: "FORBIDDEN", - }) - expect(h.requests.size).toBe(0) - await expect( - h.service.prepareReceiptSignatures( - viewer( - "president", - permissions.filter((p) => p !== "esign:sign") - ), - { receiptIds: [r.id] } - ) - ).rejects.toMatchObject({ code: "FORBIDDEN" }) - await expect(h.service.prepareReceiptSignatures(master, { receiptIds: [r.id, r.id] })).rejects.toThrow() - const [prepared] = await h.service.prepareReceiptSignatures(master, { receiptIds: [r.id] }) - expect(await h.service.eligibleReceipt(prepared.requestId, "president", master.can)).toBe(true) - expect(await h.service.eligibleReceipt(prepared.requestId, "vice", vice.can)).toBe(false) - await h.service.unlinkAccount(master, { personId: "P-0001" }) - expect(await h.service.eligibleReceipt(prepared.requestId, "president", master.can)).toBe(false) - }) - it("hides unsigned, another member's and voided receipts from self downloads", async () => { +describe("People mail outbox", () => { + async function invited() { const h = harness() await h.seed() - await admit(h) - const r = await issue(h) - await expect( - h.service.downloadMyReceipt(viewer("member", ["people:self"]), { receiptId: r.id }) - ).rejects.toMatchObject({ code: "NOT_FOUND" }) - await expect( - h.service.downloadMyReceipt(viewer("vice", ["people:self"]), { receiptId: r.id }) - ).rejects.toMatchObject({ code: "NOT_FOUND" }) - expect(await h.service.downloadReceipt(master, { receiptId: r.id })).toMatchObject({ - contentType: "application/pdf", + await h.service.unlinkAccount(master, { personId: "P-0003" }) + await h.service.sendInvite(master, { personId: "P-0003" }) + const [mail] = Object.values(h.state().outbox) + return { h, mail } + } + it("sends a queued invitation once across concurrent workers", async () => { + const { h, mail } = await invited() + await Promise.all([h.service.deliverPending(), h.service.deliverPending()]) + expect(h.sendMail).toHaveBeenCalledTimes(1) + expect(h.sendMail).toHaveBeenCalledWith({ + id: mail.id, + to: "luca@example.org", + subject: mail.subject, + text: expect.stringContaining("https://admin.example.org/dashboard/account/me?peopleInvite="), }) + expect(h.state().outbox[mail.id]).toMatchObject({ status: "sent", error: null }) + await h.service.deliverPending() + expect(h.sendMail).toHaveBeenCalledTimes(1) }) - it("sends a durable outbox item once across concurrent workers and exposes failures for retry", async () => { - const h = harness() - await h.seed() - await admit(h) - const r = await issue(h) - await h.store.transaction(async ({ state, putFile }) => { - const receipt = state.receipts[r.id] - receipt.status = "signed" - receipt.signedFileId = "signed" - await putFile({ - id: "signed", - content: new Uint8Array([1]), - fileName: "signed.pdf", - contentType: "application/pdf", - expiresAt: null, - }) - state.outbox[`receipt:${r.id}`] = { - id: `receipt:${r.id}`, - personId: r.person.id, - receiptId: r.id, - to: r.recipient, - subject: "Receipt", - text: "Receipt", - fileId: "signed", - status: "pending", - attemptedAt: null, - error: null, - } - }) + it("records a failed send and does not retry it on its own", async () => { + const { h, mail } = await invited() h.sendMail.mockRejectedValueOnce(new Error("Mailbox unavailable")) - await Promise.all([h.service.deliverPending(), h.service.deliverPending()]) - expect(h.sendMail).toHaveBeenCalledTimes(1) - expect(h.state().receipts[r.id]).toMatchObject({ status: "failed", failure: "Mailbox unavailable" }) - await h.service.retryReceipt(master, { receiptId: r.id }) - expect(h.sendMail).toHaveBeenCalledTimes(2) - expect(h.state().receipts[r.id]).toMatchObject({ status: "sent", sentTo: "luca@polinetwork.org" }) await h.service.deliverPending() - expect(h.sendMail).toHaveBeenCalledTimes(2) + expect(h.state().outbox[mail.id]).toMatchObject({ status: "failed", error: "Mailbox unavailable" }) + await h.service.deliverPending() + expect(h.sendMail).toHaveBeenCalledTimes(1) }) it("does not resend mail whose outcome is unknown after a crash", async () => { - const h = harness() - await h.seed() - await admit(h) - const r = await issue(h) + const { h, mail } = await invited() await h.store.transaction(async ({ state }) => { - state.receipts[r.id].status = "signed" - state.outbox[`receipt:${r.id}`] = { - id: `receipt:${r.id}`, - personId: r.person.id, - receiptId: r.id, - to: r.recipient, - subject: "Receipt", - text: "Receipt", - fileId: null, - status: "sending", - attemptedAt: "2026-10-18T09:00:00Z", - error: null, - } + Object.assign(state.outbox[mail.id], { status: "sending", attemptedAt: "2026-10-18T09:00:00Z" }) }) await h.service.deliverPending() expect(h.sendMail).not.toHaveBeenCalled() - expect(h.state().receipts[r.id]).toMatchObject({ + expect(h.state().outbox[mail.id]).toMatchObject({ status: "failed", - failure: expect.stringContaining("outcome unknown"), - }) - }) - it("rolls fee years and automatic reminders using dates in Rome", async () => { - const h = harness() - await h.seed() - await admit(h) - h.setDate("2026-10-17T10:00:00Z") - await h.service.sweep() - await h.service.sweep() - expect(h.sendMail).toHaveBeenCalledTimes(1) - h.setDate("2026-10-28T10:00:00Z") - await h.service.sweep() - expect(h.sendMail).toHaveBeenCalledTimes(2) - h.setDate("2026-11-01T10:00:00Z") - expect((await h.service.getFeeReview(master, { personId: "P-0003" })).fee.status).toBe("unpaid") - h.setDate("2027-09-01T10:00:00Z") - expect((await h.service.getFeeReview(master, { personId: "P-0003" })).fee).toMatchObject({ - year: "2027/28", - status: "due", + error: expect.stringContaining("outcome unknown"), }) - expect(today(new Date("2026-08-31T22:30:00Z"))).toBe("2026-09-01") - expect(academicYear("2026-08-31")).toBe("2025/26") - }) - it("quotes and neutralizes every CSV cell", () => { - for (const text of ["=A1", "+x", "-x", "@x", "\tX", "\rX"]) expect(csvCell(text)).toBe(`"'${text}"`) - expect(csvCell('a,"b"')).toBe('"a,""b"""') - }) - it("counts delivered reminders, releases failed sends and enforces the three-day cooldown", async () => { - const h = harness() - await h.seed() - await admit(h) - h.sendMail.mockRejectedValueOnce(new Error("Mailbox temporarily unavailable")) - expect(await h.service.remindFees(master, { personId: "P-0003" })).toEqual({ sent: 0, skipped: 1 }) - expect(await h.service.remindFees(master, { personId: "P-0003" })).toEqual({ sent: 1, skipped: 0 }) - expect(await h.service.remindFees(master, { personId: "P-0003" })).toEqual({ sent: 0, skipped: 1 }) - expect(h.sendMail).toHaveBeenCalledTimes(2) - }) - it("does not change a member number when Microsoft 365 refuses the update", async () => { - const h = harness() - await h.seed() - await admit(h) - h.setMemberNumber.mockRejectedValueOnce(new Error("Microsoft 365 unavailable")) - await expect(h.service.setMemberNumber(master, { personId: "P-0003", number: "0042" })).rejects.toThrow( - "unavailable" - ) - expect(h.state().persons["P-0003"].member?.number).toBe("0003") - }) -}) - -it("retains deselected census groups as pending HR work until Telegram confirms removal", async () => { - const groups = [{ chatId: "-1001", title: "Test group", admins: ["103"] }] - const h = harness({ telegramGroups: async () => groups }) - await h.seed() - await h.service.listPeople(master) - await h.service.answerCensus(viewer("member", ["people:self"], "103"), { - answer: "continues", - course: "Computer science", - year: "2nd year", - campus: "Leonardo", - keepGroups: [], - keepTeams: [], - reason: "", - note: "", - }) - let person = await h.service.getPerson(master, { id: "P-0003" }) - expect(person.admin?.groups).toHaveLength(1) - expect(person.discrepancies).toContainEqual( - expect.objectContaining({ - kind: "admin-removal", - message: expect.stringContaining("Telegram admin removal pending: Test group (-1001)"), - }) - ) - expect(h.state().persons["P-0003"].pendingGroupRemovals).toHaveLength(1) - await h.store.transaction(async ({ state }) => { - state.persons["P-0003"].discrepancies[0].kind = "needs-review" - state.persons["P-0003"].discrepancies.push({ - kind: "needs-review", - message: "HR-only identity review", - suggestedTelegram: null, - }) - }) - const ownArea = await h.service.getMyArea(viewer("member", ["people:self"], "103")) - expect(ownArea).toMatchObject({ - state: "linked", - person: { - discrepancies: [ - expect.objectContaining({ - kind: "admin-removal", - message: expect.stringContaining("Telegram admin removal pending:"), - }), - ], - }, - }) - groups[0].admins = [] - person = await h.service.getPerson(master, { id: "P-0003" }) - expect(person.admin?.groups).toHaveLength(0) - expect(person.discrepancies).not.toContainEqual( - expect.objectContaining({ message: expect.stringContaining("Telegram admin removal pending:") }) - ) - expect(h.state().persons["P-0003"].pendingGroupRemovals).toHaveLength(0) - expect(await h.service.getMyArea(viewer("member", ["people:self"], "103"))).toMatchObject({ - state: "linked", - person: { discrepancies: [] }, - }) -}) - -it("keeps groups and pending removals while Telegram group admins are unknown", async () => { - const groups: { chatId: string; title: string; admins: string[] | null }[] = [ - { chatId: "-1001", title: "Test group", admins: ["103"] }, - ] - const h = harness({ telegramGroups: async () => groups }) - await h.seed() - await h.service.listPeople(master) - await h.service.answerCensus(viewer("member", ["people:self"], "103"), { - answer: "continues", - course: "Computer science", - year: "2nd year", - campus: "Leonardo", - keepGroups: [], - keepTeams: [], - reason: "", - note: "", }) - groups[0].admins = null - const person = await h.service.getPerson(master, { id: "P-0003" }) - expect(person.admin?.groups).toEqual([{ chatId: "-1001", title: "Test group" }]) - expect(person.discrepancies).toContainEqual(expect.objectContaining({ kind: "admin-removal" })) - expect(h.state().persons["P-0003"].pendingGroupRemovals).toHaveLength(1) })