diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index fc17be2..4dff737 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -28,9 +28,11 @@ export `CT_LOGINTOKEN` (and `CT_HOST`) instead. Never commit a token — see tool can have. Anything touching diffing needs a test that pins the rendered plan. - **A clean apply must round-trip to a no-op.** If applying a config and re-planning shows a diff, the resource's `managedFields` are wrong — that is a bug, not a quirk. -- **People are out of scope, permanently.** `assertNotPeople` guards every write path. - PRs that manage people will be declined regardless of quality; it is a boundary, not a - gap. +- **People are out of scope for the structure engine, permanently.** `assertNotPeople` + guards every engine write path. PRs that make `plan` / `apply` manage people will be + declined regardless of quality; it is a boundary, not a gap. The only code that touches + person records is `ct dupes` (`src/dupes/`, `src/commands/dupes.ts`): interactive, + operator-driven, with its own personal-data guard. Keep it that way. - **Live-API tests are opt-in, and writes are triple-gated.** Reads need `CT_LIVE=1`. Writes additionally need `CT_LIVE_WRITE=1` **and** `CT_LIVE_WRITE_HOST` set to exactly the authenticated host — a deliberate barrier against a live write landing on prod. diff --git a/README.md b/README.md index 9dbd397..33868b4 100644 --- a/README.md +++ b/README.md @@ -6,9 +6,13 @@ group types and roles, permissions, auto-groups — as versioned desired-state code, and reconcile it against the ChurchTools API with Terraform-style **`plan` / `apply`**. -> **People are never managed.** This tool touches only the scaffold, and only -> resources that are _explicitly_ declared or adopted. Everything else is -> invisible: never shown, never changed, never proposed for deletion. +> **The structure commands never touch people.** `plan` / `apply` / `destroy` +> work only on the scaffold, and only on resources that are _explicitly_ declared +> or adopted. Everything else is invisible: never shown, never changed, never +> proposed for deletion. The one exception is the separate, interactive-only +> [`ct dupes`](docs/handbuch/dupes.md) command family, which helps an operator +> review duplicate person records. It never runs unattended and refuses to run +> in a non-interactive session against a protected environment. > **Frozen.** The TypeScript config DSL receives bugfixes only and is removed > in ct-cli 5.0. Its successor is `terraform-provider-churchtools`, an @@ -330,7 +334,7 @@ ct apply --env prod # protected env: type the env name to confirm - Protected environments: apply/destroy always require typed confirmation of the env name — `--auto-approve` / `--force` never bypass it. - Per-env state files are host-bound: `--env prod` can never touch a dev-bound state. -- People and memberships are never touched (a hard boundary in code). +- `plan` / `apply` / `destroy` never touch people or memberships (a hard boundary in code). Only `ct dupes` does, explicitly and interactively. - Backup/export before every `apply` and `destroy`. - Rate-limit + retry on API calls (writes are never blindly re-sent on 5xx). - Tokens live in the OS keychain / `.env`, never in git. diff --git a/docs/handbuch/dupes.md b/docs/handbuch/dupes.md new file mode 100644 index 0000000..77195ab --- /dev/null +++ b/docs/handbuch/dupes.md @@ -0,0 +1,264 @@ +--- +sources_hash: 445840f5422c421c +title: Duplicate review (ct dupes) +sources: + - src/commands/dupes.ts + - src/dupes/detector.ts + - src/dupes/guard.ts + - src/dupes/store.ts + - src/dupes/actions.ts + - src/dupes/merge-model.ts + - src/dupes/groups.ts + - src/dupes/web/server.ts + - src/dupes/web/page.ts + - src/dupes/web/run.ts + - src/dupes/tui/App.tsx + - src/dupes/tui/ListScreen.tsx + - src/dupes/tui/PairScreen.tsx + - src/dupes/finance.ts + - src/dupes/redact.ts +reviewed: 2026-11-09 +--- + +# Duplicate review (`ct dupes`) + +`ct dupes` helps an operator find and merge duplicate person records. It is the one part +of ct-cli that reads and writes person data, which is why it is **interactive only** and +sits behind a personal-data guard. The structure commands (`plan`, `apply`, `destroy`) +never touch people. + +The merge itself goes through ChurchTools' merge API (`GET` and `PATCH +/persons/{original}/merge/{duplicate}`). The endpoint is marked Beta in the OpenAPI spec, so +its behaviour may change between ChurchTools releases. + +## Commands + +| Command | What it does | +| ---------------------------------------- | ------------------------------------------------------------------------------------------------- | +| `ct dupes scan [--env]` | Loads non-archived persons and ChurchTools' own duplicate suggestions, scores pairs, stores them. | +| `ct dupes review [--tui] [--no-open]` | Review the scanned pairs in the browser (or the terminal): merge, "keine Dublette", skip. | +| `ct dupes export-finance [--since DATE]` | Writes `optigem-merges-.csv` and `.json` for merges that orphaned an Optigem ID. | + +Common options: `-e, --env`, `--redact`, `--optigem-field ` (or +`CT_DUPES_OPTIGEM_FIELD`, default `optigemId`). + +## How pairs are found + +Persons are blocked by shared email, phone, name and address keys (keys with more than 40 +members are skipped), then scored. A pair gets a **match class** (`exact`, `nameswap`, +`middlename`, `firsttoken`, `shortform`, `diminutive`, `fuzzy`, or `ct` for pairs only +ChurchTools suggests) and a tier: T1 (score 85 and up), T2 (60 to 84), T3 (35 to 59). +Lower scores are discarded. + +Pairs are dropped when: + +- they are linked by any relationship other than "Dublette" (for example "keine Dublette"); +- either name is a placeholder, or four or more persons share an identical name; +- the birthdays differ, or both sex values are set and differ. + +## Review and merge + +`ct dupes review` starts a small local web server and opens a page in the browser that is +modelled on ChurchTools' own duplicate page (`/persons/duplicates`) and its "Dubletten +überprüfen" dialog, with the ct dupes additions (tiers, match class, Optigem, shared groups). +The command prints the URL and keeps running until you press "Beenden" on the page or `Ctrl-C`. +"Finance-Export" in the page header downloads the finance export (below) as CSV into the browser's +download folder; it is not offered with `--redact`. +`--no-open` only prints the URL. `--tui` uses the full-screen terminal view instead (below). + +### Browser view + +The list shows one card per pair with tier, score, match class and source, and the two persons +as **Original** and **Duplikat** (name, ID, created date, last login). Tabs filter by state +(Überprüfen, Zusammengeführt, Keine Dublette), chips by tier, and a search box by name or ID. +`⇄` swaps Original and Duplikat for that pair. + +"Vergleichen und zusammenführen" opens the dialog: the two cards on top, then a table with the +columns Original, Vorschlag für Zusammenführung and Duplikat, grouped into Sonstiges (group +counts), Adresse, Informationen, Kategorie, Bereich and Finanzen. Click the arrow next to the +Original's or the Duplikat's value (or the value itself) to take that side; the chosen arrow is +outlined, and `×` clears the field. Bereich is a list: when both persons have +different Bereiche, the result keeps both (`beide`), and an arrow takes one side only. On email rows the arrow includes the address and `×` leaves it out, and the star makes it the default address. Each email row is labelled with its +contact type from masterdata ("E-Mail (Privat)"); an address both persons have keeps the +Original's type, and the Duplikat's differing type is shown next to its value. Campus, status, sex and Bereich show +their masterdata names, and dates read as in ChurchTools (30.06.1999). "Identische Felder" also lists equal fields. The shared groups follow, one block per +group with its plan and its membership values, chosen the same way. The footer has Abbrechen, +"Keine Dublette", a pager (`→` skips to the next open pair) and Zusammenführen, which merges right +away, as in ChurchTools (the dialog itself is the review). After an action the dialog moves +on to the next open pair at the same position in the pager; the finished pair stays on screen, +dimmed, until the next one has loaded, so the dialog never blanks in between. `Esc` closes the dialog. + +The server listens on `127.0.0.1` only, on a random port. The URL carries a random token in its +fragment, and every API call must send it back in a header; requests with a `Host` other than +`127.0.0.1:` are refused (against DNS rebinding). The page itself contains no person data +and loads nothing from outside (strict Content-Security-Policy); values are inserted as text, +never as HTML. With `--redact` the page gets the same pseudonyms as the terminal, never raw ids. +Merges and dismissals go through the same code as the terminal view. + +### Terminal view (`--tui`) + +A full-screen terminal view (Ink). Ink and React load only for `--tui`, so every other `ct` +command starts as fast as before. + +#### List screen + +All candidates of the last scan with tier, score, match class, source, both names and state +(`open`, `merged`, `dismissed`). Names come from one `GET /persons` when the screen opens. + +| Key | Action | +| ----------- | ------------------------------- | +| `↑` `↓` | move; `PgUp` / `PgDn` page | +| `1` `2` `3` | show only tier T1 / T2 / T3 | +| `a` | show all | +| `Enter` | open the pair (open pairs only) | +| `q` | quit | + +#### Pair screen + +Two cards, **Original** (green) and **Duplikat** (red), show name, ID, created date and last +login. The Original is the older person (the lower id), as in ChurchTools' own merge UI. Below +them a table has the columns Feld, Original, Ergebnis and Duplikat. Only differing fields are +listed; `i` also shows identical ones. The chosen side is green, the other red. + +| Key | Action | +| ------------ | -------------------------------------------------------------------------------- | +| `↑` `↓` | move the row cursor | +| `←` | take the Duplikat's value into Ergebnis (also on group membership rows) | +| `→` | take the Original's value | +| `x` | clear Ergebnis (field rows); include or exclude the address (email rows) | +| `b` | Bereich: keep the entries of both persons | +| `Space`, `*` | email rows: include or exclude an address; make it the default address | +| `i` | show or hide identical fields | +| `t` | swap Original and Duplikat (reloads the merge preview for the new direction) | +| `m` | merge: a confirm dialog lists what changes; `y` or `Enter` sends it, `n` cancels | +| `n` | "keine Dublette" | +| `s` | skip | +| `Esc` | back to the list | + +### Choices and merge + +Defaults: the non-empty side wins, the Original wins a conflict. Only real person fields can +be chosen (names, nickname, birthday, address, phones, sex, campus, status, job, departments +and similar). System keys such as `guid`, `id`, `meta`, image and URL fields, security levels +and privacy fields are never offered and always come from the Original. Campus, status and sex +show their names from `/person/masterdata` (the ids when masterdata has no name; id `0` is a +valid campus or status id). + +Email addresses are one row per distinct address of both persons. All are included by default +and the Original's default address stays default; exactly one included address is the default +(`*`). Each address is sent as `contactLabelId`, `email` and `isDefault`, without an `id`, as +ChurchTools' own merge UI does. + +The Optigem ID is a normal row. A lone ID is preselected; with two different IDs the Original's +wins until you choose. The leading and orphaned IDs in the audit log and the finance export +follow the final choice. + +An info line shows the group counts of the merge preview (the original's groups, the +duplicate's, shared ones). ChurchTools moves memberships, relations and other related records +itself, but it refuses the merge (HTTP 403) while both persons are in a common group. So +`ct dupes` cleans up the shared groups first: + +- **dynamic (Auto) groups:** the Duplikat is removed; the group's ruleset decides about the + Original. +- **other groups:** the Original's membership is kept. Its role, status, join and end date, + comment and group member fields are listed below the person fields, one row per differing + value, with `←` / `→` like a person field. By default the earlier join date wins, empty values + are filled from the Duplikat and the Original wins a conflict. Values taken from the Duplikat + are written to the Original's membership (`PATCH /groups/{g}/members/{original}`), then the + Duplikat is removed from the group. + +The dialog shows the plan per group (the terminal view's confirm dialog too). The merge preview reports shared groups under +`both` as group ids; titles come from its `old` and `new` lists. If a group step fails, the merge +is not sent, the pair stays open and `merge-error` (stage `groups`, with the steps already done) +is logged; successful steps are logged as `groups-prepared`. The clean-up is safe to repeat: a +Duplikat that is no longer a member (404 on the `DELETE`) counts as removed. If the merge itself +fails after the groups were cleaned up, the message says so and the pair is read again, so a +retry works against the current memberships. ChurchTools offers no way to restore the +Duplikat's removed memberships, so check the refusal reasons below before merging. + +On merge the Original is re-read, your choices are applied to that fresh object and sent in +one `PATCH /persons/{original}/merge/{duplicate}`. The body has the shape ChurchTools' own merge +UI sends: a fixed list of system keys (`id`, `guid`, `meta` with its four created/modified keys, +campus, status, departments, security levels, privacy agreement and similar) plus the person +fields, each only with a value. Anything else from the `GET` is left out: the complete object is +rejected with HTTP 400, and nested objects such as `invitationStatus` make the endpoint fail with +a 500 (verified on a dev instance). + +Verified on a dev instance: the duplicate is deleted, its group memberships move to the Original, +an address that is not included disappears, and a cleared field is sent as `""` and stays empty. +The group clean-up was run end to end there with one static group (join date, comment and a +member field taken from the Duplikat) and one dynamic group. + +If the call fails, the HTTP +status, the field names ChurchTools rejected and its `messageKey` are shown (never values or +messages) and the pair +stays open. ChurchTools refuses to merge a person with permissions of their own +(`error.forbidden.merge-authorized-person`, HTTP 403); the page says so in plain words. `merge-error` is logged; if the duplicate is gone +nevertheless, the merge is recorded (`afterError: true`). When a pair later no longer loads because +the Duplikat itself is gone (404 on `GET /persons/{id}`) while the Original still loads, and its +`merge-started` was never confirmed, it is recorded as merged (`recovered: true`). Any other 404 +while loading (a membership, the merge preview) is shown as a load error naming that request. After an +action you return to the list with the cursor on the next open pair; the scan file is saved +after every decision. The audit log keeps `merge-started` (the differing fields of both +persons and the group ids of the preview) and `merge-confirmed` (what the finance export reads). + +"Keine Dublette" writes the relationship back to ChurchTools so the pair is never proposed +again. A re-scan keeps earlier decisions (dismissed, merged) for pairs that still turn up, so +a dismissal whose write-back failed does not reappear. The relationship types are found by +their function keys `noduplicate` and `openduplicate`; if the instance has none, the command +stops rather than guess an id. + +## Personal-data guard + +Against a **protected** environment (and when no `--env` is given, or for a gateway +environment) `ct dupes` runs only if stdin and stdout are both terminals and the process +is not running inside an AI coding agent session. There is no flag to bypass this. The +refusal message is deliberately neutral and prints no person data. + +The agent check is best-effort detection, not a guarantee. It looks for the environment +markers and command lines of known coding-agent tools, so an unknown or deliberately +disguised agent can slip through. If the process ancestry cannot be read (for example +`ps` is missing), the command refuses rather than guessing. Treat the guard as a safety +net and keep personal data off sessions you do not control. + +## Local store + +Scan results, the audit log and exports live outside any repository, in directories with +mode `0700` and files with mode `0600`: + +- macOS: `~/Library/Application Support/ct-cli/dupes//` +- Linux: `${XDG_DATA_HOME:-~/.local/share}/ct-cli/dupes//` +- override with `CT_DUPES_DIR`; the store refuses a path inside a git work tree. +- `export-finance --out ` follows the same rules: it refuses a git work tree, creates + a new directory with `0700`, writes files `0600`, and warns if an existing directory is + readable by group or others. + +Files: `candidates.json`, `audit.jsonl` (one JSON line per action), `redact.key`, `exports/`. + +`--redact` replaces names and ids on screen with stable pseudonyms derived from a local +secret. Error messages never include person data. + +## Finance export + +Schema `ct-cli.dupes.optigem-merges/1` (additive changes only within version 1). Rows are +taken from confirmed merges that orphaned at least one Optigem ID. + +Each row names both persons as they were before the merge (id, name, Optigem ID), the person +that survives in ChurchTools and the Optigem ID it now carries (`leading`, empty when the field was cleared) and every ID that no longer +appears in ChurchTools (`orphaned`, several joined with `; `). Finance decides which ID stays in Optigem and updates its records. Names and +per-person IDs are empty for merges logged before they were recorded. + +CSV header: `surviving_person_id,surviving_person_name,surviving_person_optigem_id,merged_person_id,merged_person_name,merged_person_optigem_id,leading_optigem_id,orphaned_optigem_id,identical_ids,merged_at,merged_by`. +The JSON file wraps the same rows as camelCase objects in `{ schema, generatedAt, host, since, merges }`. +Cells starting with a formula character are prefixed with `'`. + +The export files are derived from the audit log and can be deleted at any time: a new export +writes them again. A downloaded CSV starts with a UTF-8 byte order mark so spreadsheet tools +read names correctly. It contains names, so delete it once finance has it. + +## Testing against a dev instance + +`scripts/seed-dupes-dev.ts` creates fictitious pairs (`Zzd-` prefix) covering every match +class, a shared dynamic group and a shared static group with conflicting member fields. +`--cleanup` removes them. It refuses to run unless `CT_LIVE_WRITE_HOST` equals the +authenticated host. diff --git a/docs/handbuch/index.md b/docs/handbuch/index.md index 14e871a..bf477d4 100644 --- a/docs/handbuch/index.md +++ b/docs/handbuch/index.md @@ -47,6 +47,9 @@ each page marks explicitly what was **verified** and what is still an - **[API behaviour](api-behaviour.md)** — what ChurchTools does that its API documentation does not say: the session cookie rename, login tokens, OAuth clients, error bodies, and the traps in group membership reads and writes. +- **[Duplicate review (`ct dupes`)](dupes.md)** — the interactive, operator-only + workflow for finding, reviewing and merging duplicate person records, and the + personal-data guard around it. !!! note "Language" These pages are English while the rest of the Handbuch is German. That is a diff --git a/docs/handbuch/mkdocs.yml b/docs/handbuch/mkdocs.yml index d792c56..f31bb71 100644 --- a/docs/handbuch/mkdocs.yml +++ b/docs/handbuch/mkdocs.yml @@ -82,3 +82,4 @@ nav: - Group member fields: group-member-fields.md - Blueprints: blueprints.md - API behaviour: api-behaviour.md + - Duplicate review (ct dupes): dupes.md diff --git a/package-lock.json b/package-lock.json index 8ccde8b..e61eb13 100644 --- a/package-lock.json +++ b/package-lock.json @@ -14,10 +14,12 @@ "@smithy/protocol-http": "^5.6.2", "@smithy/signature-v4": "^5.7.5", "commander": "^12.1.0", + "ink": "^6.8.0", "jiti": "^2.4.0", "omelette": "^0.4.17", "openapi-fetch": "^0.13.0", - "picocolors": "^1.1.0" + "picocolors": "^1.1.0", + "react": "^19.2.8" }, "bin": { "ct": "dist/index.js" @@ -26,7 +28,9 @@ "@eslint/js": "^9.0.0", "@types/node": "^22.0.0", "@types/omelette": "^0.4.5", + "@types/react": "^19.2.18", "eslint": "^9.0.0", + "ink-testing-library": "^4.0.0", "openapi-typescript": "^7.4.0", "prettier": "^3.3.0", "tsup": "^8.3.0", @@ -39,6 +43,31 @@ "node": ">=20" } }, + "node_modules/@alcalzone/ansi-tokenize": { + "version": "0.2.5", + "resolved": "https://registry.npmjs.org/@alcalzone/ansi-tokenize/-/ansi-tokenize-0.2.5.tgz", + "integrity": "sha512-3NX/MpTdroi0aKz134A6RC2Gb2iXVECN4QaAXnvCIxxIm3C3AVB1mkUe8NaaiyvOpDfsrqWhYtj+Q6a62RrTsw==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.2.1", + "is-fullwidth-code-point": "^5.0.0" + }, + "engines": { + "node": ">=18" + } + }, + "node_modules/@alcalzone/ansi-tokenize/node_modules/ansi-styles": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", + "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, "node_modules/@aws-crypto/sha256-js": { "version": "5.2.0", "resolved": "https://registry.npmjs.org/@aws-crypto/sha256-js/-/sha256-js-5.2.0.tgz", @@ -1688,6 +1717,16 @@ "dev": true, "license": "MIT" }, + "node_modules/@types/react": { + "version": "19.2.18", + "resolved": "https://registry.npmjs.org/@types/react/-/react-19.2.18.tgz", + "integrity": "sha512-AnzbBERsrLKtk2XSfTbYRLjQPdy116Sty4q+T+Bp3IC4l6jNBvreVPAHmpq9qhXQM7CXZPjLVmGMw9sy+hxQ3w==", + "devOptional": true, + "license": "MIT", + "dependencies": { + "csstype": "^3.2.2" + } + }, "node_modules/@typescript-eslint/eslint-plugin": { "version": "8.63.0", "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.63.0.tgz", @@ -2157,6 +2196,33 @@ "node": ">=6" } }, + "node_modules/ansi-escapes": { + "version": "7.3.0", + "resolved": "https://registry.npmjs.org/ansi-escapes/-/ansi-escapes-7.3.0.tgz", + "integrity": "sha512-BvU8nYgGQBxcmMuEeUEmNTvrMVjJNSH7RgW24vXexN4Ven6qCvy4TntnvlnwnMLTVlcRQQdbRY8NKnaIoeWDNg==", + "license": "MIT", + "dependencies": { + "environment": "^1.0.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ansi-regex": { + "version": "6.6.0", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-6.6.0.tgz", + "integrity": "sha512-XZ5apbzreCbXSKwPjJstu8R0zOi247w3XYwWxtwBXgpZrCyc1Ka7p9/xY0A9/diMewmHbEKz+FIraWaEWjlN5g==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-regex?sponsor=1" + } + }, "node_modules/ansi-styles": { "version": "4.3.0", "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", @@ -2197,6 +2263,18 @@ "node": ">=12" } }, + "node_modules/auto-bind": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/auto-bind/-/auto-bind-5.0.1.tgz", + "integrity": "sha512-ooviqdwwgfIfNmDwo94wlshcdzfO64XV0Cg6oDsDYBJfITDz1EngD2z7DkbvCWn+XIMsIqW27sEVF6qcpJrRcg==", + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/balanced-match": { "version": "1.0.2", "resolved": "https://registry.npmjs.org/balanced-match/-/balanced-match-1.0.2.tgz", @@ -2324,6 +2402,61 @@ "url": "https://paulmillr.com/funding/" } }, + "node_modules/cli-boxes": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/cli-boxes/-/cli-boxes-3.0.0.tgz", + "integrity": "sha512-/lzGpEWL/8PfI0BmBOPRwp0c/wFNX1RdUML3jK/RcSBA9T8mZDdQpqYBKtCFTOfQbwPqWEOpjqW+Fnayc0969g==", + "license": "MIT", + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-cursor": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/cli-cursor/-/cli-cursor-4.0.0.tgz", + "integrity": "sha512-VGtlMu3x/4DOtIUwEkRezxUZ2lBacNJCHash0N0WeZDBS+7Ux1dm3XWAgWYxLJFMMdOeXMHXorshEFhbMSGelg==", + "license": "MIT", + "dependencies": { + "restore-cursor": "^4.0.0" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/cli-truncate": { + "version": "5.2.0", + "resolved": "https://registry.npmjs.org/cli-truncate/-/cli-truncate-5.2.0.tgz", + "integrity": "sha512-xRwvIOMGrfOAnM1JYtqQImuaNtDEv9v6oIYAs4LIHwTiKee8uwvIi363igssOC0O5U04i4AlENs79LQLu9tEMw==", + "license": "MIT", + "dependencies": { + "slice-ansi": "^8.0.0", + "string-width": "^8.2.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/code-excerpt": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/code-excerpt/-/code-excerpt-4.0.0.tgz", + "integrity": "sha512-xxodCmBen3iy2i0WtAK8FlFNrRzjUqjRsMfho58xT/wvZU1YTM3fCnRjcy1gJPMepaRlgm/0e6w8SpWHpn3/cA==", + "license": "MIT", + "dependencies": { + "convert-to-spaces": "^2.0.1" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + } + }, "node_modules/color-convert": { "version": "2.0.1", "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", @@ -2384,6 +2517,15 @@ "node": "^14.18.0 || >=16.10.0" } }, + "node_modules/convert-to-spaces": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/convert-to-spaces/-/convert-to-spaces-2.0.1.tgz", + "integrity": "sha512-rcQ1bsQO9799wq24uE5AM2tAILy4gXGIK/njFWcVQkGNZ96edlpY+A7bjwvzjYvLDyzmG1MmMLZhpcsb+klNMQ==", + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + } + }, "node_modules/cross-spawn": { "version": "7.0.6", "resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz", @@ -2399,6 +2541,13 @@ "node": ">= 8" } }, + "node_modules/csstype": { + "version": "3.2.3", + "resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz", + "integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==", + "devOptional": true, + "license": "MIT" + }, "node_modules/debug": { "version": "4.4.3", "resolved": "https://registry.npmjs.org/debug/-/debug-4.4.3.tgz", @@ -2434,6 +2583,24 @@ "dev": true, "license": "MIT" }, + "node_modules/emoji-regex": { + "version": "10.6.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-10.6.0.tgz", + "integrity": "sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==", + "license": "MIT" + }, + "node_modules/environment": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/environment/-/environment-1.1.0.tgz", + "integrity": "sha512-xUtoPkMggbz0MPyPiIWr1Kp4aeWJjDZ6SMvURhimjdZgsRuDplF5/s9hcgGhyXMhs+6vpnuoiZ2kFiu3FMnS8Q==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/es-module-lexer": { "version": "1.7.0", "resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-1.7.0.tgz", @@ -2441,6 +2608,18 @@ "dev": true, "license": "MIT" }, + "node_modules/es-toolkit": { + "version": "1.53.2", + "resolved": "https://registry.npmjs.org/es-toolkit/-/es-toolkit-1.53.2.tgz", + "integrity": "sha512-iUqZ+NlwH4jUgRmXZUxFBsV/9762TQEa1O4IXLFBmDEjVHScBytKuseX23I0+v9ShZ5MYxEx6WKNzm6IPnex8g==", + "license": "MIT", + "workspaces": [ + "docs", + "benchmarks", + "tests/types", + "tests/browser-compat" + ] + }, "node_modules/esbuild": { "version": "0.27.7", "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.7.tgz", @@ -2787,6 +2966,18 @@ "node": "^8.16.0 || ^10.6.0 || >=11.0.0" } }, + "node_modules/get-east-asian-width": { + "version": "1.7.0", + "resolved": "https://registry.npmjs.org/get-east-asian-width/-/get-east-asian-width-1.7.0.tgz", + "integrity": "sha512-XjH1AECxf0giL2V1aU8vKyRR2ppRUb5c0EvT7zuJTokQ74bNo52zOtghqdWIqrhUD79fo3x0WfKZdOqxF6LG1Q==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/glob-parent": { "version": "6.0.2", "resolved": "https://registry.npmjs.org/glob-parent/-/glob-parent-6.0.2.tgz", @@ -2874,6 +3065,18 @@ "node": ">=0.8.19" } }, + "node_modules/indent-string": { + "version": "5.0.0", + "resolved": "https://registry.npmjs.org/indent-string/-/indent-string-5.0.0.tgz", + "integrity": "sha512-m6FAo/spmsW2Ab2fU35JTYwtOKa2yAwXSwgjSv1TJzh4Mh7mC3lzAOVLBprb72XsTrgkEIsl7YrFNAiDiRhIGg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/index-to-position": { "version": "1.2.0", "resolved": "https://registry.npmjs.org/index-to-position/-/index-to-position-1.2.0.tgz", @@ -2887,6 +3090,112 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/ink": { + "version": "6.8.0", + "resolved": "https://registry.npmjs.org/ink/-/ink-6.8.0.tgz", + "integrity": "sha512-sbl1RdLOgkO9isK42WCZlJCFN9hb++sX9dsklOvfd1YQ3bQ2AiFu12Q6tFlr0HvEUvzraJntQCCpfEoUe9DSzA==", + "license": "MIT", + "dependencies": { + "@alcalzone/ansi-tokenize": "^0.2.4", + "ansi-escapes": "^7.3.0", + "ansi-styles": "^6.2.1", + "auto-bind": "^5.0.1", + "chalk": "^5.6.0", + "cli-boxes": "^3.0.0", + "cli-cursor": "^4.0.0", + "cli-truncate": "^5.1.1", + "code-excerpt": "^4.0.0", + "es-toolkit": "^1.39.10", + "indent-string": "^5.0.0", + "is-in-ci": "^2.0.0", + "patch-console": "^2.0.0", + "react-reconciler": "^0.33.0", + "scheduler": "^0.27.0", + "signal-exit": "^3.0.7", + "slice-ansi": "^8.0.0", + "stack-utils": "^2.0.6", + "string-width": "^8.1.1", + "terminal-size": "^4.0.1", + "type-fest": "^5.4.1", + "widest-line": "^6.0.0", + "wrap-ansi": "^9.0.0", + "ws": "^8.18.0", + "yoga-layout": "~3.2.1" + }, + "engines": { + "node": ">=20" + }, + "peerDependencies": { + "@types/react": ">=19.0.0", + "react": ">=19.0.0", + "react-devtools-core": ">=6.1.2" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + }, + "react-devtools-core": { + "optional": true + } + } + }, + "node_modules/ink-testing-library": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/ink-testing-library/-/ink-testing-library-4.0.0.tgz", + "integrity": "sha512-yF92kj3pmBvk7oKbSq5vEALO//o7Z9Ck/OaLNlkzXNeYdwfpxMQkSowGTFUCS5MSu9bWfSZMewGpp7bFc66D7Q==", + "dev": true, + "license": "MIT", + "engines": { + "node": ">=18" + }, + "peerDependencies": { + "@types/react": ">=18.0.0" + }, + "peerDependenciesMeta": { + "@types/react": { + "optional": true + } + } + }, + "node_modules/ink/node_modules/ansi-styles": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", + "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/ink/node_modules/chalk": { + "version": "5.6.2", + "resolved": "https://registry.npmjs.org/chalk/-/chalk-5.6.2.tgz", + "integrity": "sha512-7NzBL0rN6fMUW+f7A6Io4h40qQlG+xGmtMxfbnH/K7TAtt8JQWVQK+6g0UXKMeVJoyV5EkkNsErQ8pVD3bLHbA==", + "license": "MIT", + "engines": { + "node": "^12.17.0 || ^14.13 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/chalk/chalk?sponsor=1" + } + }, + "node_modules/ink/node_modules/type-fest": { + "version": "5.10.0", + "resolved": "https://registry.npmjs.org/type-fest/-/type-fest-5.10.0.tgz", + "integrity": "sha512-NoSdpq/WEiAg5sjmBkmV/hfxv6HJH4NqPNrqjtSO5CwRmpsDfaf4begxW34KdJykH/l1yHtwBWQkCRdoXO8mPA==", + "license": "(MIT OR CC0-1.0)", + "dependencies": { + "tagged-tag": "^1.0.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/is-extglob": { "version": "2.1.1", "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", @@ -2897,6 +3206,21 @@ "node": ">=0.10.0" } }, + "node_modules/is-fullwidth-code-point": { + "version": "5.1.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-5.1.0.tgz", + "integrity": "sha512-5XHYaSyiqADb4RnZ1Bdad6cPp8Toise4TzEjcOYDHZkTCbKgiUl7WTUCpNWHuxmDt91wnsZBc9xinNzopv3JMQ==", + "license": "MIT", + "dependencies": { + "get-east-asian-width": "^1.3.1" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/is-glob": { "version": "4.0.3", "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", @@ -2910,6 +3234,21 @@ "node": ">=0.10.0" } }, + "node_modules/is-in-ci": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/is-in-ci/-/is-in-ci-2.0.0.tgz", + "integrity": "sha512-cFeerHriAnhrQSbpAxL37W1wcJKUUX07HyLWZCW1URJT/ra3GyUTzBgUnh24TMVfNTV2Hij2HLxkPHFZfOZy5w==", + "license": "MIT", + "bin": { + "is-in-ci": "cli.js" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/isexe": { "version": "2.0.0", "resolved": "https://registry.npmjs.org/isexe/-/isexe-2.0.0.tgz", @@ -3091,6 +3430,15 @@ "@jridgewell/sourcemap-codec": "^1.5.5" } }, + "node_modules/mimic-fn": { + "version": "2.1.0", + "resolved": "https://registry.npmjs.org/mimic-fn/-/mimic-fn-2.1.0.tgz", + "integrity": "sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg==", + "license": "MIT", + "engines": { + "node": ">=6" + } + }, "node_modules/minimatch": { "version": "3.1.5", "resolved": "https://registry.npmjs.org/minimatch/-/minimatch-3.1.5.tgz", @@ -3180,6 +3528,21 @@ "node": ">=0.8.0" } }, + "node_modules/onetime": { + "version": "5.1.2", + "resolved": "https://registry.npmjs.org/onetime/-/onetime-5.1.2.tgz", + "integrity": "sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg==", + "license": "MIT", + "dependencies": { + "mimic-fn": "^2.1.0" + }, + "engines": { + "node": ">=6" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/openapi-fetch": { "version": "0.13.8", "resolved": "https://registry.npmjs.org/openapi-fetch/-/openapi-fetch-0.13.8.tgz", @@ -3310,6 +3673,15 @@ "url": "https://github.com/sponsors/sindresorhus" } }, + "node_modules/patch-console": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/patch-console/-/patch-console-2.0.0.tgz", + "integrity": "sha512-0YNdUceMdaQwoKce1gatDScmMo5pu/tfABfnzEqeG0gtTmd7mh/WcwgUjtAeOU7N8nFFlbQBnFK2gXW5fGvmMA==", + "license": "MIT", + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + } + }, "node_modules/path-exists": { "version": "4.0.0", "resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz", @@ -3506,6 +3878,30 @@ "node": ">=6" } }, + "node_modules/react": { + "version": "19.2.8", + "resolved": "https://registry.npmjs.org/react/-/react-19.2.8.tgz", + "integrity": "sha512-PWaYA1L/q9u2u7xYQi+Y3L3Yfnie7XyLeaJICV1MGD6LprsBxcAqGjYyr0eY3p+QdsA+x/Irkt4Qif8D63+Sbw==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/react-reconciler": { + "version": "0.33.0", + "resolved": "https://registry.npmjs.org/react-reconciler/-/react-reconciler-0.33.0.tgz", + "integrity": "sha512-KetWRytFv1epdpJc3J4G75I4WrplZE5jOL7Yq0p34+OVOKF4Se7WrdIdVC45XsSSmUTlht2FM/fM1FZb1mfQeA==", + "license": "MIT", + "dependencies": { + "scheduler": "^0.27.0" + }, + "engines": { + "node": ">=0.10.0" + }, + "peerDependencies": { + "react": "^19.2.0" + } + }, "node_modules/readdirp": { "version": "4.1.2", "resolved": "https://registry.npmjs.org/readdirp/-/readdirp-4.1.2.tgz", @@ -3540,6 +3936,22 @@ "node": ">=4" } }, + "node_modules/restore-cursor": { + "version": "4.0.0", + "resolved": "https://registry.npmjs.org/restore-cursor/-/restore-cursor-4.0.0.tgz", + "integrity": "sha512-I9fPXU9geO9bHOt9pHHOhOkYerIMsmVaWB0rA2AI9ERh/+x/i7MV5HKBNrg+ljO5eoPVgCcnFuRjJ9uH6I/3eg==", + "license": "MIT", + "dependencies": { + "onetime": "^5.1.0", + "signal-exit": "^3.0.2" + }, + "engines": { + "node": "^12.20.0 || ^14.13.1 || >=16.0.0" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/rollup": { "version": "4.62.2", "resolved": "https://registry.npmjs.org/rollup/-/rollup-4.62.2.tgz", @@ -3585,6 +3997,12 @@ "fsevents": "~2.3.2" } }, + "node_modules/scheduler": { + "version": "0.27.0", + "resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.27.0.tgz", + "integrity": "sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q==", + "license": "MIT" + }, "node_modules/semver": { "version": "7.8.5", "resolved": "https://registry.npmjs.org/semver/-/semver-7.8.5.tgz", @@ -3628,6 +4046,40 @@ "dev": true, "license": "ISC" }, + "node_modules/signal-exit": { + "version": "3.0.7", + "resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-3.0.7.tgz", + "integrity": "sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ==", + "license": "ISC" + }, + "node_modules/slice-ansi": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/slice-ansi/-/slice-ansi-8.0.0.tgz", + "integrity": "sha512-stxByr12oeeOyY2BlviTNQlYV5xOj47GirPr4yA1hE9JCtxfQN0+tVbkxwCtYDQWhEKWFHsEK48ORg5jrouCAg==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.2.3", + "is-fullwidth-code-point": "^5.1.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/chalk/slice-ansi?sponsor=1" + } + }, + "node_modules/slice-ansi/node_modules/ansi-styles": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", + "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, "node_modules/source-map": { "version": "0.7.6", "resolved": "https://registry.npmjs.org/source-map/-/source-map-0.7.6.tgz", @@ -3648,6 +4100,27 @@ "node": ">=0.10.0" } }, + "node_modules/stack-utils": { + "version": "2.0.6", + "resolved": "https://registry.npmjs.org/stack-utils/-/stack-utils-2.0.6.tgz", + "integrity": "sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ==", + "license": "MIT", + "dependencies": { + "escape-string-regexp": "^2.0.0" + }, + "engines": { + "node": ">=10" + } + }, + "node_modules/stack-utils/node_modules/escape-string-regexp": { + "version": "2.0.0", + "resolved": "https://registry.npmjs.org/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz", + "integrity": "sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w==", + "license": "MIT", + "engines": { + "node": ">=8" + } + }, "node_modules/stackback": { "version": "0.0.2", "resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz", @@ -3662,6 +4135,37 @@ "dev": true, "license": "MIT" }, + "node_modules/string-width": { + "version": "8.3.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-8.3.0.tgz", + "integrity": "sha512-ZbmZM0JCihQN91dWnxoipT2KOEyHqEyfRXUyjuRhW8b/xnqPDoq4gWEVApTVa9db2wN8mmoikgFBbjh71+cGeQ==", + "license": "MIT", + "dependencies": { + "get-east-asian-width": "^1.5.0", + "strip-ansi": "^7.1.2" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/strip-ansi": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-7.2.0.tgz", + "integrity": "sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w==", + "license": "MIT", + "dependencies": { + "ansi-regex": "^6.2.2" + }, + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/strip-ansi?sponsor=1" + } + }, "node_modules/strip-json-comments": { "version": "3.1.1", "resolved": "https://registry.npmjs.org/strip-json-comments/-/strip-json-comments-3.1.1.tgz", @@ -3721,6 +4225,30 @@ "node": ">=8" } }, + "node_modules/tagged-tag": { + "version": "1.0.0", + "resolved": "https://registry.npmjs.org/tagged-tag/-/tagged-tag-1.0.0.tgz", + "integrity": "sha512-yEFYrVhod+hdNyx7g5Bnkkb0G6si8HJurOoOEgC8B/O0uXLHlaey/65KRv6cuWBNhBgHKAROVpc7QyYqE5gFng==", + "license": "MIT", + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/terminal-size": { + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/terminal-size/-/terminal-size-4.0.1.tgz", + "integrity": "sha512-avMLDQpUI9I5XFrklECw1ZEUPJhqzcwSWsyyI8blhRLT+8N1jLJWLWWYQpB2q2xthq8xDvjZPISVh53T/+CLYQ==", + "license": "MIT", + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/thenify": { "version": "3.3.1", "resolved": "https://registry.npmjs.org/thenify/-/thenify-3.3.1.tgz", @@ -5128,6 +5656,21 @@ "node": ">=8" } }, + "node_modules/widest-line": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/widest-line/-/widest-line-6.0.0.tgz", + "integrity": "sha512-U89AsyEeAsyoF0zVJBkG9zBgekjgjK7yk9sje3F4IQpXBJ10TF6ByLlIfjMhcmHMJgHZI4KHt4rdNfktzxIAMA==", + "license": "MIT", + "dependencies": { + "string-width": "^8.1.0" + }, + "engines": { + "node": ">=20" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, "node_modules/word-wrap": { "version": "1.2.5", "resolved": "https://registry.npmjs.org/word-wrap/-/word-wrap-1.2.5.tgz", @@ -5138,6 +5681,73 @@ "node": ">=0.10.0" } }, + "node_modules/wrap-ansi": { + "version": "9.0.2", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-9.0.2.tgz", + "integrity": "sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==", + "license": "MIT", + "dependencies": { + "ansi-styles": "^6.2.1", + "string-width": "^7.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/wrap-ansi/node_modules/ansi-styles": { + "version": "6.2.3", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-6.2.3.tgz", + "integrity": "sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/wrap-ansi/node_modules/string-width": { + "version": "7.2.0", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-7.2.0.tgz", + "integrity": "sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==", + "license": "MIT", + "dependencies": { + "emoji-regex": "^10.3.0", + "get-east-asian-width": "^1.0.0", + "strip-ansi": "^7.1.0" + }, + "engines": { + "node": ">=18" + }, + "funding": { + "url": "https://github.com/sponsors/sindresorhus" + } + }, + "node_modules/ws": { + "version": "8.22.2", + "resolved": "https://registry.npmjs.org/ws/-/ws-8.22.2.tgz", + "integrity": "sha512-/rEZ2ejown2N5gxVTHUu9bVVC7ttu0/Tgzf5hbTOixR3Fs7mbbXgn2DbdbcKgJOmpQMtrIUWivtYuVMnp/W/yA==", + "license": "MIT", + "engines": { + "node": ">=10.0.0" + }, + "peerDependencies": { + "bufferutil": "^4.0.1", + "utf-8-validate": ">=5.0.2" + }, + "peerDependenciesMeta": { + "bufferutil": { + "optional": true + }, + "utf-8-validate": { + "optional": true + } + } + }, "node_modules/yaml-ast-parser": { "version": "0.0.43", "resolved": "https://registry.npmjs.org/yaml-ast-parser/-/yaml-ast-parser-0.0.43.tgz", @@ -5167,6 +5777,12 @@ "funding": { "url": "https://github.com/sponsors/sindresorhus" } + }, + "node_modules/yoga-layout": { + "version": "3.2.1", + "resolved": "https://registry.npmjs.org/yoga-layout/-/yoga-layout-3.2.1.tgz", + "integrity": "sha512-0LPOt3AxKqMdFBZA3HBAt/t/8vIKq7VaQYbuA8WxCgung+p9TVyKRYdpvCb80HcdTN2NkbIKbhNwKUfm3tQywQ==", + "license": "MIT" } } } diff --git a/package.json b/package.json index 729399d..df8a287 100644 --- a/package.json +++ b/package.json @@ -1,7 +1,7 @@ { "name": "@eqrm/ct-cli", "version": "0.1.0", - "description": "ChurchTools structure-as-code CLI — declarative plan/apply for the overarching, rights-bearing structure (campuses, groups, hierarchies, permissions, auto-groups). Never manages people.", + "description": "ChurchTools structure-as-code CLI — declarative plan/apply for the overarching, rights-bearing structure (campuses, groups, hierarchies, permissions, auto-groups). Its structure commands never manage people.", "license": "MIT", "type": "module", "repository": { @@ -41,16 +41,20 @@ "@smithy/protocol-http": "^5.6.2", "@smithy/signature-v4": "^5.7.5", "commander": "^12.1.0", + "ink": "^6.8.0", "jiti": "^2.4.0", "omelette": "^0.4.17", "openapi-fetch": "^0.13.0", - "picocolors": "^1.1.0" + "picocolors": "^1.1.0", + "react": "^19.2.8" }, "devDependencies": { "@eslint/js": "^9.0.0", "@types/node": "^22.0.0", "@types/omelette": "^0.4.5", + "@types/react": "^19.2.18", "eslint": "^9.0.0", + "ink-testing-library": "^4.0.0", "openapi-typescript": "^7.4.0", "prettier": "^3.3.0", "tsup": "^8.3.0", diff --git a/scripts/seed-dupes-dev.ts b/scripts/seed-dupes-dev.ts new file mode 100644 index 0000000..49b45b1 --- /dev/null +++ b/scripts/seed-dupes-dev.ts @@ -0,0 +1,245 @@ +/** + * Seed (or remove) fictitious duplicate persons on a DEV ChurchTools instance for `ct dupes`. + * + * CT_LIVE_WRITE_HOST=https://your-dev.church.tools npx tsx scripts/seed-dupes-dev.ts + * CT_LIVE_WRITE_HOST=https://your-dev.church.tools npx tsx scripts/seed-dupes-dev.ts --cleanup + * + * Refuses to run unless CT_LIVE_WRITE_HOST equals the authenticated host (same barrier as the live + * write tests). Everything it creates is recognisable: persons have a first or last name starting + * with `Zzd-`, groups are named `zz-dupes-*`. `--cleanup` deletes exactly those. + * + * Covers: every match class (exact, middlename, firsttoken, shortform, nameswap, diminutive, fuzzy), + * the sex veto, a placeholder cluster, digits in names, a pair suppressed by a "Keine Dublette" + * relationship, pairs where both persons carry an Optigem ID, one pair sharing a dynamic and a + * static group (with conflicting member fields). + */ +import { CtApiError } from "../src/api/ctClient.js"; +import { authedSession } from "../src/api/session.js"; +import { loadActivePersons, resolveRelationshipTypes } from "../src/dupes/ct.js"; + +const PREFIX = "Zzd-"; +const GROUP_PREFIX = "zz-dupes-"; + +interface Seed { + firstName: string; + lastName: string; + email?: string; + optigemId?: string; + sexId?: number; + birthday?: string; +} + +const { client } = await authedSession(); +const expected = process.env.CT_LIVE_WRITE_HOST?.trim(); +if (!expected || client.host !== expected) { + throw new Error("Set CT_LIVE_WRITE_HOST to exactly the authenticated (dev) host to allow writes."); +} + +async function cleanup(): Promise { + const people = await loadAll(); + for (const p of people.filter((x) => isSeed(x))) { + await client.request("DELETE", `/persons/${p.id}`); + } + const groups = await client.getAll<{ id: number; name: string }>("/groups"); + for (const g of groups.data.filter((x) => x.name.startsWith(GROUP_PREFIX))) { + await client.request("DELETE", `/groups/${g.id}`); + } + console.log("cleanup done"); +} + +interface Raw { + id: number; + firstName: string; + lastName: string; +} +async function loadAll(): Promise { + return (await client.getAll("/persons")).data; +} +function isSeed(p: Raw): boolean { + return p.firstName.startsWith(PREFIX) || p.lastName.startsWith(PREFIX); +} + +if (process.argv.includes("--cleanup")) { + await cleanup(); + process.exit(0); +} +if ((await loadAll()).some(isSeed)) throw new Error("Seed data already present; run with --cleanup first."); + +const md = await client.get<{ + campuses: Array<{ id: number }>; + departments: Array<{ id: number }>; + statuses: Array<{ id: number }>; + sexes: Array<{ id: number }>; + groupTypes: Array<{ id: number }>; +}>("/person/masterdata"); +const base = { + campusId: md.campuses[0]!.id, + departmentIds: [md.departments[0]!.id], + statusId: md.statuses[0]!.id, + privacyPolicyAgreementTypeId: 3, + privacyPolicyAgreementWhoId: 1, + privacyPolicyAgreementDate: new Date().toISOString().slice(0, 10), +}; +const [sexA, sexB] = [md.sexes[0]!.id, md.sexes[1]!.id]; + +async function create(s: Seed): Promise { + const body = { ...base, ...s }; + const created = await client.request<{ id: number }>("POST", "/persons?force=true", body); + return created.id; +} + +const ids: Record = {}; +let pairNo = 0; +async function pair(name: string, a: Seed, b: Seed): Promise { + // A shared birthday stands in for the contact data real duplicates have in common. + pairNo++; + const birthday = `1990-02-${String(pairNo).padStart(2, "0")}`; + a = { birthday, ...a }; + b = { birthday, ...b }; + ids[name] = [await create(a), await create(b)]; +} + +const mail = (n: string): string => `${n}@example.invalid`; +await pair( + "exact", + { firstName: "Erika", lastName: `${PREFIX}Alpha`, email: mail("zzd-alpha") }, + { firstName: "Erika", lastName: `${PREFIX}Alpha` }, +); +await pair( + "middlename", + { firstName: "Anna Marie", lastName: `${PREFIX}Beta` }, + { firstName: "Anna", lastName: `${PREFIX}Beta` }, +); +await pair( + "fuzzy", + { firstName: "Naomi", lastName: `${PREFIX}Gamma` }, + { firstName: "Nomi", lastName: `${PREFIX}Gamma` }, +); +await pair( + "shortform", + { firstName: "Christine", lastName: `${PREFIX}Delta` }, + { firstName: "Tine", lastName: `${PREFIX}Delta` }, +); +await pair( + "nameswap", + { firstName: "Erika", lastName: `${PREFIX}Epsilon` }, + { firstName: `${PREFIX}Epsilon`, lastName: "Erika" }, +); +await pair( + "diminutive", + { firstName: "Ursula", lastName: `${PREFIX}Zeta` }, + { firstName: "Ursi", lastName: `${PREFIX}Zeta` }, +); +await pair( + "firsttoken", + { firstName: "Maria Luise", lastName: `${PREFIX}Eta` }, + { firstName: "Maria Anna", lastName: `${PREFIX}Eta` }, +); +await pair( + "sex-veto", + { firstName: "Andreas", lastName: `${PREFIX}Theta`, sexId: sexA }, + { firstName: "Andrea", lastName: `${PREFIX}Theta`, sexId: sexB }, +); +await pair( + "digits", + { firstName: "Gruppe1", lastName: `${PREFIX}Kappa` }, + { firstName: "Gruppe2", lastName: `${PREFIX}Kappa` }, +); +await pair( + "suppressed", + { firstName: "Lena", lastName: `${PREFIX}Lambda`, email: mail("zzd-lambda") }, + { firstName: "Lena", lastName: `${PREFIX}Lambda`, email: mail("zzd-lambda") }, +); +for (let i = 0; i < 4; i++) await create({ firstName: "Gast", lastName: `${PREFIX}Iota` }); +await pair( + "optigem-different", + { firstName: "Mia", lastName: `${PREFIX}My`, optigemId: "ZZD-1001", email: mail("zzd-my") }, + { firstName: "Mia", lastName: `${PREFIX}My`, optigemId: "ZZD-1002" }, +); +await pair( + "optigem-same", + { firstName: "Noah", lastName: `${PREFIX}Ny`, optigemId: "ZZD-2001" }, + { firstName: "Noah", lastName: `${PREFIX}Ny`, optigemId: "ZZD-2001" }, +); + +// Relationship that must suppress the pair. +const types = await resolveRelationshipTypes(client); +await client.request("POST", `/persons/${ids["suppressed"]![0]}/relationships`, { + otherPersonId: ids["suppressed"]![1], + relationshipTypeId: types.noDuplicate, +}); + +// Shared groups for the first Optigem pair: one dynamic, one static with conflicting member fields. +const groupType = md.groupTypes[0]!.id; +const newGroup = async (name: string): Promise => + ( + await client.request<{ id: number }>("POST", "/groups", { + name: `${GROUP_PREFIX}${name}`, + groupTypeId: groupType, + groupStatusId: 1, + force: true, + }) + ).id; +const dynamicGroup = await newGroup("dynamic"); +const staticGroup = await newGroup("static"); +// A ruleset that matches nobody makes the group dynamic; membership is never refreshed here. +await client.request("PUT", `/dynamicgroups/${dynamicGroup}/ruleset`, { + dynamicGroupRuleSet: [ + { + description: "zz-dupes seed", + shorty: "zz-dupes", + personIdFieldName: "person.id", + importance: 0, + query: { + method: "ChurchQuery", + params: { + groupBy: ["person.id"], + filter: { "==": [{ var: "person.id" }, -1] }, + primaryEntityAlias: "person", + responseFields: ["person.id"], + }, + }, + process: { + groupOnly: { active: { handleMembership: { groupMemberStatus: "none" } } }, + queryResultOnly: { none: { handleMembership: { groupMemberStatus: "active" } } }, + groupAndQueryResult: {}, + }, + }, + ], +}); +// Only groups with an active status count as dynamic (they are what GET /dynamicgroups lists). +await client.request("PUT", `/dynamicgroups/${dynamicGroup}/status`, { dynamicGroupStatus: "active" }); +const field = async (name: string, type: string): Promise => + ( + await client.request<{ id: number }>("POST", `/groups/${staticGroup}/memberfields/group`, { + name, + fieldTypeCode: type, + securityLevel: 1, + useInRegistrationForm: false, + requiredInRegistrationForm: false, + }) + ).id; +const paid = await field("Paid", "checkbox"); +const tribe = await field("Tribe", "text"); +const [p1, p2] = ids["optigem-different"]!; +for (const g of [dynamicGroup, staticGroup]) { + for (const p of [p1, p2]) { + try { + await client.request("PUT", `/groups/${g}/members/${p}`, {}); + } catch (err) { + console.log( + `could not add a seed person to a group (HTTP ${err instanceof CtApiError ? err.status : "?"})`, + ); + } + } +} +await client.request("PATCH", `/groups/${staticGroup}/members/${p1}`, { + fields: { [paid]: true, [tribe]: "Alpha" }, +}); +await client.request("PATCH", `/groups/${staticGroup}/members/${p2}`, { fields: { [tribe]: "Beta" } }); + +const active = await loadActivePersons(client, "optigemId"); +console.log( + `seeded; ${active.filter((p) => p.firstName.startsWith(PREFIX) || p.lastName.startsWith(PREFIX)).length} seed persons active`, +); +console.log(JSON.stringify(ids)); diff --git a/src/commands/dupes.ts b/src/commands/dupes.ts new file mode 100644 index 0000000..f27b439 --- /dev/null +++ b/src/commands/dupes.ts @@ -0,0 +1,194 @@ +import { Command } from "commander"; +import { CtApiError } from "../api/ctClient.js"; +import { authedSession } from "../api/session.js"; +import { resolveConfig } from "../config.js"; +import { prepareEnvHost } from "../env/context.js"; +import { loadEnvProfile, resolveEnvsPath, type EnvProfile } from "../env/envs.js"; +import { + DEFAULT_OPTIGEM_FIELD, + buildCandidates, + loadActivePersons, + loadRelationState, + resolveRelationshipTypes, +} from "../dupes/ct.js"; +import { buildFinanceExport, financeMerges, toCsv } from "../dupes/finance.js"; +import { assertHumanSession } from "../dupes/guard.js"; +import { makeRedactor, type Redactor } from "../dupes/redact.js"; +import { DupesStore, SCAN_SCHEMA, carryStates } from "../dupes/store.js"; +import { info, success, warn } from "../ui.js"; + +interface CommonOptions { + env?: string; + redact?: boolean; + optigemField?: string; +} + +interface Session { + host: string; + store: DupesStore; + redactor: Redactor; + optigemField: string; +} + +/** Neutral one-line error text: never a response body, never a person value. */ +export function safeErrorText(err: unknown, redactor: Redactor): string { + if (err instanceof CtApiError) return `ChurchTools request failed (HTTP ${err.status}).`; + const msg = err instanceof Error ? err.message : "unknown error"; + return redactor.text(msg).slice(0, 200); +} + +async function loadProfile(env?: string): Promise { + return env ? loadEnvProfile(env, resolveEnvsPath()) : null; +} + +/** Guard first (before any network or keychain access), then wire the env. */ +async function openSession(opts: CommonOptions): Promise { + const profile = await loadProfile(opts.env); + assertHumanSession({ + profile, + stdinIsTTY: process.stdin.isTTY === true, + stdoutIsTTY: process.stdout.isTTY === true, + env: process.env, + }); + await prepareEnvHost({ env: opts.env }); + const { host } = await resolveConfig(); + const store = new DupesStore(host); + const optigemField = opts.optigemField ?? process.env.CT_DUPES_OPTIGEM_FIELD ?? DEFAULT_OPTIGEM_FIELD; + const redactor = makeRedactor(opts.redact === true, opts.redact ? store.redactSecret() : ""); + return { host, store, redactor, optigemField }; +} + +async function run(opts: CommonOptions, fn: () => Promise): Promise { + try { + await fn(); + } catch (err) { + const redactor = makeRedactor(opts.redact === true, "error-text"); + process.stderr.write(`ct dupes: ${safeErrorText(err, redactor)}\n`); + process.exitCode = 1; + } +} + +function addCommon(cmd: Command): Command { + return cmd + .option("-e, --env ", "environment profile from ct.envs.json") + .option("--redact", "replace names and ids in all output with stable pseudonyms") + .option( + "--optigem-field ", + `person property holding the Optigem ID (or CT_DUPES_OPTIGEM_FIELD; default ${DEFAULT_OPTIGEM_FIELD})`, + ); +} + +export function dupesCommand(): Command { + const dupes = new Command("dupes").description( + "Find and resolve duplicate persons (interactive; touches person data, never run by agents)", + ); + + addCommon( + dupes + .command("scan") + .description("Scan non-archived persons for duplicate candidates and store them locally"), + ).action((opts: CommonOptions) => + run(opts, async () => { + const s = await openSession(opts); + const { client } = await authedSession(); + const persons = await loadActivePersons(client, s.optigemField); + const rel = await loadRelationState(client); + const candidates = buildCandidates(persons, rel); + s.store.saveScan({ + schema: SCAN_SCHEMA, + host: s.host, + scannedAt: new Date().toISOString(), + personsScanned: persons.length, + candidates: carryStates(s.store.loadScan(), candidates), + }); + const by = (t: string): number => candidates.filter((c) => c.tier === t).length; + success( + `Scanned ${persons.length} persons: ${candidates.length} candidates ` + + `(T1 ${by("T1")}, T2 ${by("T2")}, T3 ${by("T3")}); ` + + `${rel.suppressed.size} pairs suppressed by existing relationships.`, + ); + info(`Stored in ${s.store.dir}`); + }), + ); + + addCommon( + dupes + .command("review") + .description( + "Review stored candidates in the browser (or the terminal with --tui): merge, not a duplicate, skip", + ) + .option("--tui", "use the full-screen terminal view instead of the browser") + .option("--no-open", "print the address instead of opening the browser"), + ).action((opts: CommonOptions & { tui?: boolean; open?: boolean }) => + run(opts, async () => { + const s = await openSession(opts); + const scan = s.store.loadScan(); + if (!scan) throw new Error("No scan found. Run `ct dupes scan` first."); + const { client, me } = await authedSession(); + const types = await resolveRelationshipTypes(client); + const { loadLabels } = await import("../dupes/actions.js"); + const labels = await loadLabels(client); + const deps = { + client, + store: s.store, + host: s.host, + redactor: s.redactor, + optigemField: s.optigemField, + types, + operator: { id: me.id, name: `${me.firstName ?? ""} ${me.lastName ?? ""}`.trim() }, + labels, + }; + if (opts.tui) { + // Lazy: Ink and React load only for the terminal view. + const { runReviewTui } = await import("../dupes/tui/run.js"); + await runReviewTui(deps, scan); + } else { + const { runReviewWeb } = await import("../dupes/web/run.js"); + await runReviewWeb(deps, scan, { open: opts.open !== false }); + } + const by = (st: string): number => scan.candidates.filter((c) => c.state === st).length; + info(`Done: ${by("merged")} merged, ${by("dismissed")} not duplicates, ${by("open")} still open.`); + }), + ); + + addCommon( + dupes + .command("export-finance") + .description("Write CSV and JSON of merges that orphaned an Optigem ID") + .option("--since ", "only merges on or after this date (YYYY-MM-DD)") + .option("--out ", "output directory (default: the local dupes store)"), + ).action((opts: CommonOptions & { since?: string; out?: string }) => + run(opts, async () => { + if (opts.since && !/^\d{4}-\d{2}-\d{2}$/.test(opts.since)) { + throw new Error("--since must be a date like 2026-01-31."); + } + const s = await openSession(opts); + const merges = financeMerges(s.store.readAudit(), opts.since); + const now = new Date(); + const day = now.toISOString().slice(0, 10); + const data = buildFinanceExport(merges, s.host, opts.since, now); + const csv = toCsv(merges); + const json = `${JSON.stringify(data, null, 2)}\n`; + let csvPath: string; + let jsonPath: string; + if (opts.out) { + const { writePrivateFiles } = await import("../dupes/store.js"); + const res = writePrivateFiles(opts.out, { + [`optigem-merges-${day}.csv`]: csv, + [`optigem-merges-${day}.json`]: json, + }); + if (res.warning) warn(res.warning); + [csvPath, jsonPath] = res.paths as [string, string]; + } else { + csvPath = s.store.writeExport(`optigem-merges-${day}.csv`, csv); + jsonPath = s.store.writeExport(`optigem-merges-${day}.json`, json); + } + if (merges.length === 0) warn("No merges with two Optigem IDs found; wrote empty files."); + success(`${merges.length} merge(s) exported.`); + info(csvPath); + info(jsonPath); + }), + ); + + return dupes; +} diff --git a/src/dupes/actions.ts b/src/dupes/actions.ts new file mode 100644 index 0000000..945d925 --- /dev/null +++ b/src/dupes/actions.ts @@ -0,0 +1,509 @@ +/** + * The side-effecting steps of `ct dupes review`, free of any UI: load a pair, merge, mark "no + * duplicate", recover an unrecorded merge. The TUI calls these; tests call them with a fake client. + * Error text never carries person data: only an HTTP status leaves this module. + */ +import { CtApiError } from "../api/ctClient.js"; +import { + loadMergePreview, + loadPerson, + loadRawPerson, + toPersonRecord, + markNoDuplicate, + mergePersons, + type DupesClient, + type MergePreview, + type PersonRecord, + type RelationshipTypeIds, +} from "./ct.js"; +import { MERGE_CONFIRMED } from "./finance.js"; +import { buildBody, buildModel, optigemOutcome, type EmailRow, type MergeModel } from "./merge-model.js"; +import { + loadDynamicGroupIds, + loadSharedGroups, + prepareSharedGroups, + type GroupProgress, + type GroupStep, + type SharedGroup, +} from "./groups.js"; +import type { Redactor } from "./redact.js"; +import type { DupesStore } from "./store.js"; + +/** Lookup names for id-valued person fields, keyed by field (`campusId`, `statusId`, `sexId`, ...). */ +export type Labels = Record>; + +export interface ReviewDeps { + client: DupesClient; + store: DupesStore; + host: string; + redactor: Redactor; + optigemField: string; + types: RelationshipTypeIds; + operator: { id: number; name: string }; + labels: Labels; + now?: () => Date; +} + +const LOOKUPS: Record = { + campusId: "campuses", + statusId: "statuses", + sexId: "sexes", + groupTypeRoleId: "roles", + nationalityId: "nationalities", + familyStatusId: "familyStatuses", + departmentIds: "departments", + contactLabelId: "contactLabels", +}; + +/** + * Field keys ChurchTools names in a validation error (`errors[].fieldId`). Keys only, never the + * message or args, which can echo submitted values. + */ +export function rejectedFields(err: unknown): string[] { + if (!(err instanceof CtApiError)) return []; + const errors = (err.body as { errors?: unknown } | null)?.errors; + if (!Array.isArray(errors)) return []; + const keys = errors + .map((e) => (e as { fieldId?: unknown }).fieldId) + .filter((k): k is string => typeof k === "string" && /^[A-Za-z0-9_.[\]-]{1,64}$/.test(k)); + return [...new Set(keys)]; +} + +/** + * ChurchTools' key for a refusal (`messageKey`, on older responses `translationKey`; e.g. on a 403). Only a key that looks + * like one is returned, never the message, which can echo values. + */ +export function errorKey(err: unknown): string | undefined { + if (!(err instanceof CtApiError)) return undefined; + const body = err.body as { messageKey?: unknown; translationKey?: unknown } | null; + const key = body?.messageKey ?? body?.translationKey; + return typeof key === "string" && /^[A-Za-z0-9_.-]{1,120}$/.test(key) ? key : undefined; +} + +/** Names for campus, status, sex, ... from `/person/masterdata`. Empty when unavailable. */ +export async function loadLabels(client: DupesClient): Promise { + const out: Labels = {}; + try { + const md = await client.get>("/person/masterdata"); + for (const [field, list] of Object.entries(LOOKUPS)) { + const rows = md[list]; + const map = new Map(); + if (Array.isArray(rows)) { + for (const r of rows as Array<{ id?: unknown; name?: unknown; nameTranslated?: unknown }>) { + const name = typeof r.nameTranslated === "string" && r.nameTranslated ? r.nameTranslated : r.name; + if (typeof r.id === "number" && typeof name === "string") map.set(r.id, name); + } + } + out[field] = map; + } + } catch { + /* ids are shown instead */ + } + return out; +} + +/** + * The contact label ("Privat", "Arbeit", ...) of an email row on each side, as ChurchTools shows it + * next to "E-Mail". Empty when the side has no entry or masterdata has no name for the label. + */ +export function emailTypes(row: EmailRow, labels: Labels): { original: string; duplicate: string } { + const name = (e: Record | null): string => { + const id = e?.contactLabelId; + return typeof id === "number" ? (labels.contactLabelId?.get(id) ?? "") : ""; + }; + return { original: name(row.originalEntry), duplicate: name(row.duplicateEntry) }; +} + +/** Row label for an email row: "E-Mail (Privat)", the type the merged address keeps. */ +export function emailLabel(row: EmailRow, labels: Labels): string { + const t = emailTypes(row, labels); + const type = row.originalEntry ? t.original : t.duplicate; + return type ? `E-Mail (${type})` : "E-Mail"; +} + +/** True when the value is a masterdata id (or list of them) that masterdata names: not personal data. */ +export function isMasterValue(key: string, v: unknown, labels: Labels): boolean { + const known = (x: unknown) => typeof x === "number" && labels[key]?.has(x) === true; + return Array.isArray(v) ? v.length > 0 && v.every(known) : known(v); +} + +/** Display text for a person field value. Names for ids where masterdata knows them. */ +export function formatValue(key: string, v: unknown, labels: Labels): string { + if (v === null || v === undefined || v === "") return ""; + if (Array.isArray(v)) return v.map((x) => formatValue(key, x, labels)).join(", "); + if (typeof v === "number" && labels[key]?.has(v)) return labels[key]!.get(v)!; + // Dates as ChurchTools shows them: 30.06.1999. + const date = typeof v === "string" ? /^(\d{4})-(\d{2})-(\d{2})$/.exec(v) : null; + if (date) return `${date[3]}.${date[2]}.${date[1]}`; + return typeof v === "object" ? JSON.stringify(v) : String(v); +} + +/** id -> name, created date and last login for the list: one paginated collection GET. */ +export async function loadNames( + client: DupesClient, +): Promise> { + const out = new Map(); + try { + const { data } = await client.getAll<{ + id: number; + firstName?: string; + lastName?: string; + lastLogin?: string | null; + meta?: { createdDate?: string }; + }>("/persons"); + for (const p of data) + out.set(p.id, { + first: p.firstName ?? "", + last: p.lastName ?? "", + created: p.meta?.createdDate ?? "", + login: p.lastLogin ?? "", + }); + } catch { + /* ids only */ + } + return out; +} + +export interface PairData { + original: PersonRecord; + duplicate: PersonRecord; + originalRaw: Record; + duplicateRaw: Record; + preview: MergePreview; + model: MergeModel; + /** Groups both persons are in; cleaned up before the merge (ChurchTools refuses otherwise). */ + shared: SharedGroup[]; +} + +/** Which request of `loadPair` failed. */ +export type PairLoadStep = "original" | "duplicate" | "preview" | "membership"; + +/** A pair that did not load, naming the request that failed. */ +export class PairLoadError extends Error { + constructor( + readonly step: PairLoadStep, + readonly status: number | null, + override readonly cause: unknown, + ) { + super(`pair load failed at ${step}${status ? ` (HTTP ${status})` : ""}`); + } + + /** True only when `GET /persons/{id}` itself answered 404: that person is gone. */ + get personGone(): boolean { + return (this.step === "original" || this.step === "duplicate") && this.status === 404; + } + + /** German description for the UI. No person data. */ + describe(): string { + const what = + this.step === "preview" + ? "Merge-Vorschau" + : this.step === "membership" + ? "Gruppenmitgliedschaft" + : this.step === "original" + ? "Original" + : "Duplikat"; + return `${what}${this.status ? `, HTTP ${this.status}` : ""}`; + } +} + +/** Load both persons and the merge preview for one direction (`originalId` survives). */ +export async function loadPair(deps: ReviewDeps, originalId: number, duplicateId: number): Promise { + const { client } = deps; + const statusOf = (err: unknown): number | null => (err instanceof CtApiError ? err.status : null); + // One GET per person: the record is derived from the raw object. + const settled = await Promise.allSettled([ + loadRawPerson(client, originalId), + loadRawPerson(client, duplicateId), + loadMergePreview(client, originalId, duplicateId), + ]); + const steps: PairLoadStep[] = ["original", "duplicate", "preview"]; + for (const [i, r] of settled.entries()) + if (r.status === "rejected") throw new PairLoadError(steps[i]!, statusOf(r.reason), r.reason); + const [originalRaw, duplicateRaw, preview] = settled.map( + (r) => (r as PromiseFulfilledResult).value, + ) as [Record, Record, MergePreview]; + let shared: SharedGroup[] = []; + if (preview.groupsDiff.both.length > 0) { + try { + shared = await loadSharedGroups( + client, + preview.groupsDiff.both, + originalId, + duplicateId, + await loadDynamicGroupIds(client), + ); + } catch (err) { + throw new PairLoadError("membership", statusOf(err), err); + } + } + return { + original: toPersonRecord(originalRaw, deps.optigemField), + duplicate: toPersonRecord(duplicateRaw, deps.optigemField), + originalRaw, + duplicateRaw, + preview, + model: buildModel(originalRaw, duplicateRaw, preview.personDiff, deps.optigemField), + shared, + }; +} + +export type MergeResult = + | { + kind: "merged"; + duplicateStillExists: boolean; + checkFailed: boolean; + afterError: boolean; + warnings: string[]; + } + | { + kind: "failed"; + status: number | null; + stage: "reread" | "groups" | "patch"; + fields?: string[]; + /** ChurchTools' translation key for the refusal, when it sent one. */ + reason?: string; + /** Group steps that went through before the failure (they are not rolled back). */ + groupsDone?: GroupStep[]; + /** The group whose clean-up failed (stage "groups"). */ + groupId?: number; + /** In that group the Original's membership was already rewritten before the failure. */ + groupPatched?: boolean; + /** + * The pair re-read after group steps went through, so a retry sees the groups as they are now + * (the cached `shared` list is stale). Absent when nothing changed or the re-read failed; + * then `stale` is true if groups were changed and the caller must reload the pair. + */ + fresh?: PairData; + stale?: boolean; + }; + +async function duplicateGone(deps: ReviewDeps, id: number): Promise { + try { + await loadPerson(deps.client, id, deps.optigemField); + return false; + } catch (err) { + return err instanceof CtApiError && err.status === 404 ? true : null; + } +} + +/** Both persons as they were before the merge, for the finance export (the local store is 0600). */ +type MergeParties = Record<"survivingName" | "loserName" | "survivingOptigemId" | "loserOptigemId", string>; + +function mergeParties(pair: PairData): MergeParties { + const name = (p: PersonRecord): string => `${p.firstName} ${p.lastName}`.trim(); + return { + survivingName: name(pair.original), + loserName: name(pair.duplicate), + survivingOptigemId: pair.original.optigem, + loserOptigemId: pair.duplicate.optigem, + }; +} + +function confirm( + deps: ReviewDeps, + survivingId: number, + loserId: number, + parties: Partial, + leading: string, + orphaned: string, + extra: Record, +): void { + deps.store.audit( + { + action: MERGE_CONFIRMED, + survivingId, + loserId, + ...parties, + leadingOptigemId: leading, + orphanedOptigemId: orphaned, + mergedBy: deps.operator.name, + mergedById: deps.operator.id, + ...extra, + }, + (deps.now ?? ((): Date => new Date()))(), + ); +} + +/** After a failure that left group changes behind: re-read the pair so retries start from reality. */ +async function withFresh( + deps: ReviewDeps, + pair: PairData, + res: Extract, +): Promise { + const changed = res.groupsDone && res.groupsDone.length > 0; + if (!changed && !res.groupPatched) return res; + try { + return { ...res, fresh: await loadPair(deps, pair.original.id, pair.duplicate.id) }; + } catch { + return { ...res, stale: true }; + } +} + +/** + * Merge `pair.duplicate` into `pair.original` with the model's choices. The Original is re-read + * right before the write (one GET): the operator may have taken minutes to decide and the body is + * built from that object, so a stale copy could overwrite a concurrent edit. The Duplikat comes + * from the loaded pair. + */ +export async function executeMerge( + deps: ReviewDeps, + pair: PairData, + model: MergeModel, + shared: readonly SharedGroup[] = pair.shared, +): Promise { + const now = deps.now ?? ((): Date => new Date()); + const { store } = deps; + const survivingId = pair.original.id; + const loserId = pair.duplicate.id; + const status = (err: unknown): number | null => (err instanceof CtApiError ? err.status : null); + const { leading, orphaned } = optigemOutcome(model); + const parties = mergeParties(pair); + + let built: ReturnType; + try { + built = buildBody(await loadRawPerson(deps.client, survivingId), pair.duplicateRaw, model); // fresh: see above + } catch (err) { + store.audit({ action: "merge-error", survivingId, loserId }, now()); + return { kind: "failed", status: status(err), stage: "reread" }; + } + + const gd = pair.preview.groupsDiff; + store.audit( + { + action: "merge-started", + survivingId, + loserId, + personDiff: pair.preview.personDiff.map((d) => ({ key: d.key, original: d.old, duplicate: d.new })), + groupsDiff: { + original: gd.old.map((g) => g.id), + duplicate: gd.new.map((g) => g.id), + both: gd.both.map((g) => g.id), + }, + fromDuplicate: model.fields + .filter((f) => f.choice === "duplicate" || f.choice === "both") + .map((f) => f.key), + ...parties, + leadingOptigemId: leading, + orphanedOptigemId: orphaned, + }, + now(), + ); + const groupsDone: GroupStep[] = []; + const progress: GroupProgress = {}; + try { + await prepareSharedGroups(deps.client, shared, survivingId, loserId, groupsDone, progress); + } catch (err) { + const failedGroup = progress.groupId; + store.audit( + { + action: "merge-error", + survivingId, + loserId, + stage: "groups", + groupsDone, + failedGroup, + ...(progress.patched ? { failedGroupPatched: true } : {}), + }, + now(), + ); + return withFresh(deps, pair, { + kind: "failed", + status: status(err), + stage: "groups", + groupsDone, + groupId: failedGroup, + ...(progress.patched ? { groupPatched: true } : {}), + }); + } + if (groupsDone.length > 0) + store.audit({ action: "groups-prepared", survivingId, loserId, groupsDone }, now()); + try { + await mergePersons(deps.client, survivingId, loserId, built.body); + } catch (err) { + store.audit({ action: "merge-error", survivingId, loserId }, now()); + if ((await duplicateGone(deps, loserId)) === true) { + confirm(deps, survivingId, loserId, parties, leading, orphaned, { afterError: true }); + return { + kind: "merged", + duplicateStillExists: false, + checkFailed: false, + afterError: true, + warnings: built.warnings, + }; + } + return withFresh(deps, pair, { + kind: "failed", + status: status(err), + stage: "patch", + fields: rejectedFields(err), + reason: errorKey(err), + groupsDone, + }); + } + const gone = await duplicateGone(deps, loserId); + confirm(deps, survivingId, loserId, parties, leading, orphaned, { + ...(gone === false ? { duplicateStillExists: true } : {}), + ...(gone === null ? { duplicateCheckFailed: true } : {}), + }); + return { + kind: "merged", + duplicateStillExists: gone === false, + checkFailed: gone === null, + afterError: false, + warnings: built.warnings, + }; +} + +/** Tag the pair "Keine Dublette". The decision is logged either way; `ok` says whether CT took it. */ +export async function markNotDuplicate( + deps: ReviewDeps, + a: number, + b: number, +): Promise<{ ok: boolean; status: number | null }> { + const now = deps.now ?? ((): Date => new Date()); + try { + await markNoDuplicate(deps.client, a, b, deps.types); + deps.store.audit({ action: "no-duplicate", a, b, writeBack: "ok" }, now()); + return { ok: true, status: null }; + } catch (err) { + deps.store.audit({ action: "no-duplicate", a, b, writeBack: "failed" }, now()); + return { ok: false, status: err instanceof CtApiError ? err.status : null }; + } +} + +/** + * A pair that no longer loads (404): if the audit holds a `merge-started` without `merge-confirmed` + * and the duplicate is gone, record the merge as recovered. Returns true when recorded. + */ +export async function recoverUnrecordedMerge(deps: ReviewDeps, a: number, b: number): Promise { + const same = (e: Record): boolean => + (e.survivingId === a && e.loserId === b) || (e.survivingId === b && e.loserId === a); + let started: Record | null = null; + for (const e of deps.store.readAudit()) { + if (!same(e)) continue; + if (e.action === "merge-started") started = e; + if (e.action === MERGE_CONFIRMED) started = null; + } + if (!started || (await duplicateGone(deps, Number(started.loserId))) !== true) return false; + // Only a recovered merge when the surviving person is still there: otherwise the 404 says nothing. + try { + await loadRawPerson(deps.client, Number(started.survivingId)); + } catch { + return false; + } + confirm( + deps, + Number(started.survivingId), + Number(started.loserId), + Object.fromEntries( + (["survivingName", "loserName", "survivingOptigemId", "loserOptigemId"] as const) + .filter((k) => typeof started[k] === "string") + .map((k) => [k, started[k] as string]), + ), + typeof started.leadingOptigemId === "string" ? started.leadingOptigemId : "", + typeof started.orphanedOptigemId === "string" ? started.orphanedOptigemId : "", + { recovered: true }, + ); + return true; +} diff --git a/src/dupes/ct.ts b/src/dupes/ct.ts new file mode 100644 index 0000000..62313f5 --- /dev/null +++ b/src/dupes/ct.ts @@ -0,0 +1,282 @@ +/** + * ChurchTools access for `ct dupes`. All person data enters the process here. + * Takes a narrow client interface so tests can substitute a fake. + */ +import type { CtClient } from "../api/ctClient.js"; +import { type Candidate, type DupePerson, detect, pairKey, pairScorer, tierOf } from "./detector.js"; + +export type DupesClient = Pick; + +/** Person fields shown side by side in review. */ +export interface PersonRecord { + id: number; + firstName: string; + lastName: string; + nickname: string; + email: string; + mobile: string; + phonePrivate: string; + birthday: string | null; + street: string; + zip: string; + city: string; + sexId: number | null; + campusId: number | null; + statusId: number | null; + isArchived: boolean; + createdDate: string; + lastEditedDate: string; + lastLogin: string; + optigem: string; +} + +export const DEFAULT_OPTIGEM_FIELD = "optigemId"; + +export function toPersonRecord(raw: Record, optigemField: string): PersonRecord { + const s = (k: string): string => (raw[k] === null || raw[k] === undefined ? "" : String(raw[k])); + const meta = (raw.meta ?? {}) as { createdDate?: string }; + return { + id: Number(raw.id), + firstName: s("firstName"), + lastName: s("lastName"), + nickname: s("nickname"), + email: s("email"), + mobile: s("mobile"), + phonePrivate: s("phonePrivate"), + birthday: (raw.birthday as string | null) ?? null, + street: s("street"), + zip: s("zip"), + city: s("city"), + sexId: (raw.sexId as number | null) ?? null, + campusId: (raw.campusId as number | null) ?? null, + statusId: (raw.statusId as number | null) ?? null, + isArchived: raw.isArchived === true, + createdDate: meta.createdDate ?? "", + lastEditedDate: s("lastEditedDate"), + lastLogin: s("lastLogin"), + optigem: s(optigemField), + }; +} + +export function toDupePerson(r: PersonRecord): DupePerson { + return { ...r, optigem: r.optigem }; +} + +/** All non-archived persons. */ +export async function loadActivePersons(client: DupesClient, optigemField: string): Promise { + const { data } = await client.getAll>("/persons"); + return data.map((p) => toPersonRecord(p, optigemField)).filter((p) => !p.isArchived); +} + +export async function loadPerson( + client: DupesClient, + id: number, + optigemField: string, +): Promise { + const raw = await client.get>(`/persons/${id}`); + return toPersonRecord(raw, optigemField); +} + +export interface RelationshipTypeIds { + noDuplicate: number; + duplicate: number; +} + +interface RelType { + id: number; + functionKeys?: string[]; +} + +/** Resolve the two duplicate-related relationship types by function key (ids differ per instance). */ +export async function resolveRelationshipTypes(client: DupesClient): Promise { + const md = await client.get<{ relationshipTypes?: RelType[] }>("/person/masterdata"); + const types = md.relationshipTypes ?? []; + const noDuplicate = types.find((t) => t.functionKeys?.includes("noduplicate"))?.id; + const duplicate = types.find((t) => t.functionKeys?.includes("openduplicate"))?.id; + // No fallback ids: they differ per instance, and a wrong guess writes a wrong relationship. + if (noDuplicate === undefined || duplicate === undefined) { + throw new Error( + "ChurchTools masterdata has no relationship types with the function keys noduplicate/openduplicate.", + ); + } + return { noDuplicate, duplicate }; +} + +export interface RelationState { + types: RelationshipTypeIds; + /** Pairs with any relationship other than "Dublette": the detector never proposes them. */ + suppressed: Set; + /** Pairs CT itself proposes (untagged). */ + ctCandidates: Array<[number, number]>; + /** Pairs tagged "Dublette" but not merged yet. */ + markedDuplicates: Array<[number, number]>; +} + +interface RelRow { + personAId: number; + personBId: number; + relationshipType?: { id?: number }; + relationshipTypeId?: number; +} + +export async function loadRelationState(client: DupesClient): Promise { + const types = await resolveRelationshipTypes(client); + const rels = await client.getAll("/persons/relationships"); + const suppressed = new Set(); + const marked = new Map(); + for (const r of rels.data) { + const typeId = r.relationshipType?.id ?? r.relationshipTypeId; + const key = pairKey(r.personAId, r.personBId); + if (typeId === types.duplicate) marked.set(key, [r.personAId, r.personBId]); + else suppressed.add(key); + } + const groups = await client.get< + Array<{ + relationshipTypeId: number | null; + relationships: Array<{ p1: { id: number }; p2: { id: number } }>; + }> + >("/persons/duplicates"); + const ct = new Map(); + for (const g of groups) { + for (const rel of g.relationships ?? []) { + const key = pairKey(rel.p1.id, rel.p2.id); + if (g.relationshipTypeId === null) ct.set(key, [rel.p1.id, rel.p2.id]); + else if (g.relationshipTypeId === types.duplicate) marked.set(key, [rel.p1.id, rel.p2.id]); + else suppressed.add(key); + } + } + for (const key of suppressed) { + ct.delete(key); + marked.delete(key); + } + return { types, suppressed, ctCandidates: [...ct.values()], markedDuplicates: [...marked.values()] }; +} + +/** Run the detector, merge in CT's own suggestions, drop suppressed pairs. */ +export function buildCandidates(persons: readonly PersonRecord[], rel: RelationState): Candidate[] { + const dupes = persons.map(toDupePerson); + const byId = new Map(dupes.map((p) => [p.id, p])); + const found = new Map(detect(dupes, { suppressed: rel.suppressed }).map((c) => [pairKey(c.a, c.b), c])); + const scorePair = pairScorer(dupes); + const addExternal = (pair: [number, number], marked: boolean): void => { + const [x, y] = pair; + const key = pairKey(x, y); + const pa = byId.get(x); + const pb = byId.get(y); + if (!pa || !pb || rel.suppressed.has(key)) return; // archived or unknown + const hit = found.get(key); + if (hit) { + hit.source = "both"; + if (marked) hit.markedDuplicate = true; + return; + } + const res = scorePair(pa, pb); + if (res.veto === "placeholder" && !marked) return; + const score = Math.max(res.veto ? 0 : res.score, 35); + found.set(key, { + a: Math.min(x, y), + b: Math.max(x, y), + score, + tier: tierOf(score) ?? "T3", + matchClass: "ct", + signals: res.veto ? [`veto:${res.veto}`] : res.signals, + source: "ct", + ...(marked ? { markedDuplicate: true } : {}), + }); + }; + for (const pair of rel.ctCandidates) addExternal(pair, false); + for (const pair of rel.markedDuplicates) addExternal(pair, true); + return [...found.values()].sort((p, q) => q.score - p.score || p.a - q.a || p.b - q.b); +} + +export interface MergeDiffEntry { + key: string | null; + name: string; + old: string; + new: string; + printDiff: boolean; +} + +export interface MergeGroup { + id: number; + title?: string; + type?: string; + role?: string; + roleId?: number; + groupMemberStatus?: string; +} + +export interface MergePreview { + personDiff: MergeDiffEntry[]; + groupsDiff: { old: MergeGroup[]; new: MergeGroup[]; both: MergeGroup[] }; +} + +/** The raw person object, exactly as `GET /persons/{id}` returns it (the merge PATCH body starts from it). */ +export async function loadRawPerson(client: DupesClient, id: number): Promise> { + return client.get>(`/persons/${id}`); +} + +/** Beta endpoint. `old` is the original's value, `new` the duplicate's. */ +export async function loadMergePreview( + client: DupesClient, + original: number, + duplicate: number, +): Promise { + const raw = await client.get<{ + personDiff?: MergeDiffEntry[]; + groupsDiff?: { old?: MergeGroup[]; new?: MergeGroup[]; both?: Array }; + }>(`/persons/${original}/merge/${duplicate}`); + const g = raw.groupsDiff ?? {}; + const oldG = g.old ?? []; + const newG = g.new ?? []; + // Verified on a dev instance: `both` is a list of group ids; the groups themselves (title, role) + // are in `old` and `new`, which include the shared ones. + const both = (g.both ?? []).map((x) => { + const id = typeof x === "number" ? x : x.id; + return oldG.find((o) => o.id === id) ?? newG.find((n) => n.id === id) ?? { id }; + }); + return { personDiff: raw.personDiff ?? [], groupsDiff: { old: oldG, new: newG, both } }; +} + +/** Merge `duplicate` into `original` in one ChurchTools transaction (memberships and records move over). */ +export async function mergePersons( + client: DupesClient, + original: number, + duplicate: number, + body: Record, +): Promise { + await client.request("PATCH", `/persons/${original}/merge/${duplicate}`, body); +} + +interface PersonRel { + id: number; + relationshipTypeId?: number; + relationshipType?: { id?: number }; + /** The other person, as `GET /persons/{id}/relationships` returns it. */ + relative?: { domainIdentifier?: string }; + relativeId?: number; +} + +/** + * Tag a pair "Keine Dublette". An existing "Dublette" tag between the same two persons is removed + * first so the two statuses never coexist. + */ +export async function markNoDuplicate( + client: DupesClient, + a: number, + b: number, + types: RelationshipTypeIds, +): Promise { + const rels = await client.get(`/persons/${a}/relationships`); + for (const r of rels) { + const typeId = r.relationshipType?.id ?? r.relationshipTypeId; + const other = Number(r.relative?.domainIdentifier ?? r.relativeId); + if (typeId === types.duplicate && other === b) { + await client.request("DELETE", `/persons/${a}/relationships/${r.id}`); + } + } + await client.request("POST", `/persons/${a}/relationships`, { + otherPersonId: b, + relationshipTypeId: types.noDuplicate, + }); +} diff --git a/src/dupes/detector.ts b/src/dupes/detector.ts new file mode 100644 index 0000000..087c14b --- /dev/null +++ b/src/dupes/detector.ts @@ -0,0 +1,330 @@ +/** + * Duplicate-person detector for `ct dupes`. Deterministic, no ML, no I/O. + * + * Blocking keys limit which pairs are scored; vetoes reject outright; signals add up to a score; + * the score maps to a tier (T1 >= 85, T2 60-84, T3 35-59, below 35 is discarded). + */ +import { + cleanName, + diminutiveStem, + isPlaceholderName, + levenshtein, + nameTokens, + normalizeDate, + normalizePhone, +} from "./normalize.js"; + +/** The person fields the detector reads. */ +export interface DupePerson { + id: number; + firstName?: string | null; + lastName?: string | null; + nickname?: string | null; + email?: string | null; + mobile?: string | null; + phonePrivate?: string | null; + birthday?: string | null; + zip?: string | null; + street?: string | null; + sexId?: number | null; + /** Value of the configured Optigem field (see `--optigem-field`). */ + optigem?: string | null; +} + +export type MatchClass = + "exact" | "nameswap" | "middlename" | "firsttoken" | "shortform" | "diminutive" | "fuzzy" | "none"; + +export type Tier = "T1" | "T2" | "T3"; + +export interface Candidate { + /** Smaller person id first. */ + a: number; + b: number; + score: number; + tier: Tier; + /** Best first-name evidence; `none` when the pair matched on contact data only. */ + matchClass: MatchClass | "ct"; + signals: string[]; + /** Where the pair came from. */ + source: "detector" | "ct" | "both"; + /** ChurchTools already tagged this pair as a confirmed duplicate. */ + markedDuplicate?: boolean; +} + +export const FIRST_NAME_WEIGHTS: Record, number> = { + exact: 35, + nameswap: 33, + middlename: 30, + firsttoken: 28, + shortform: 24, + diminutive: 24, + fuzzy: 20, +}; + +export function pairKey(a: number, b: number): string { + return a < b ? `${a}:${b}` : `${b}:${a}`; +} + +export function tierOf(score: number): Tier | null { + if (score >= 85) return "T1"; + if (score >= 60) return "T2"; + if (score >= 35) return "T3"; + return null; +} + +interface Prep { + id: number; + fn: string; + ft: string[]; + ln: string; + lt: string[]; + nick: string; + email: string; + phones: string[]; + birthday: string | null; + zip: string; + street: string; + sex: number | null; + optigem: string; + full: string; +} + +function prep(p: DupePerson): Prep { + const fn = cleanName(p.firstName); + const ln = cleanName(p.lastName); + const phones = [normalizePhone(p.mobile), normalizePhone(p.phonePrivate)].filter( + (x, i, arr): x is string => x !== null && arr.indexOf(x) === i, + ); + return { + id: p.id, + fn, + ft: nameTokens(fn), + ln, + lt: nameTokens(ln), + nick: cleanName(p.nickname), + email: (p.email ?? "").trim().toLowerCase(), + phones, + birthday: normalizeDate(p.birthday), + zip: (p.zip ?? "").trim(), + street: cleanName(p.street), + sex: p.sexId ? p.sexId : null, + optigem: (p.optigem ?? "").trim(), + full: `${fn} ${ln}`.trim(), + }; +} + +function subset(a: string[], b: string[]): boolean { + return a.length > 0 && a.every((t) => b.includes(t)); +} + +function surnameCompatible(a: Prep, b: Prep): boolean { + if (a.ln === "" || b.ln === "") return false; + if (a.ln === b.ln) return true; + return subset(a.lt, b.lt) || subset(b.lt, a.lt); +} + +const ns = (s: string): string => s.replace(/[\s-]/g, ""); + +function classifyFirstName(a: Prep, b: Prep): { cls: MatchClass; viaNickname: boolean } { + const none = { cls: "none" as MatchClass, viaNickname: false }; + if (a.fn === "" || b.fn === "") return none; + const surnameOk = surnameCompatible(a, b); + if (a.fn === b.ln && a.ln === b.fn && a.fn !== a.ln) return { cls: "nameswap", viaNickname: false }; + if (!surnameOk) return none; + if (a.fn === b.fn) return { cls: "exact", viaNickname: false }; + if ((a.nick !== "" && (a.nick === b.fn || a.nick === b.nick)) || (b.nick !== "" && b.nick === a.fn)) { + return { cls: "exact", viaNickname: true }; + } + // Digits in a first name: only an exact match counts (Kids1 vs Kids2 must not match). + if (/\d/.test(a.fn) || /\d/.test(b.fn)) return none; + const [short, long] = ns(a.fn).length <= ns(b.fn).length ? [a, b] : [b, a]; + if (subset(short.ft, long.ft) || subset(long.ft, short.ft)) + return { cls: "middlename", viaNickname: false }; + if (a.ft[0] === b.ft[0]) return { cls: "firsttoken", viaNickname: false }; + const s = ns(short.fn); + const l = ns(long.fn); + if (s.length >= 3 && (l.startsWith(s) || l.endsWith(s))) return { cls: "shortform", viaNickname: false }; + const sa = diminutiveStem(ns(a.fn)); + const sb = diminutiveStem(ns(b.fn)); + if (sa === sb && sa.length >= 3) return { cls: "diminutive", viaNickname: false }; + const x = ns(a.fn); + const y = ns(b.fn); + if ((sa !== x && sa.length >= 3 && y.startsWith(sa)) || (sb !== y && sb.length >= 3 && x.startsWith(sb))) { + return { cls: "diminutive", viaNickname: false }; + } + if (Math.min(x.length, y.length) >= 4 && levenshtein(x, y) <= 2) + return { cls: "fuzzy", viaNickname: false }; + return none; +} + +interface Context { + emailCount: Map; + phoneCount: Map; + nameCount: Map; +} + +export interface PairScore { + score: number; + matchClass: MatchClass; + signals: string[]; + veto?: string; +} + +function placeholderVeto(p: Prep, ctx: Context): boolean { + return ( + isPlaceholderName(p.fn) || + isPlaceholderName(p.ln) || + isPlaceholderName(p.full) || + (ctx.nameCount.get(p.full) ?? 0) >= 4 + ); +} + +function scorePrepared(a: Prep, b: Prep, ctx: Context): PairScore { + const signals: string[] = []; + const veto = (reason: string): PairScore => ({ score: 0, matchClass: "none", signals, veto: reason }); + if (placeholderVeto(a, ctx) || placeholderVeto(b, ctx)) return veto("placeholder"); + if (a.birthday && b.birthday && a.birthday !== b.birthday) return veto("birthday"); + if (a.sex !== null && b.sex !== null && a.sex !== b.sex) return veto("sex"); + + let score = 0; + if (a.email !== "" && a.email === b.email) { + const n = ctx.emailCount.get(a.email) ?? 0; + if (n <= 2) { + score += 45; + signals.push("email-unique"); + } else if (n < 8) { + score += 12; + signals.push("email-shared"); + } + } + const sharedPhone = a.phones.find((p) => b.phones.includes(p)); + if (sharedPhone !== undefined) { + const n = ctx.phoneCount.get(sharedPhone) ?? 0; + if (n <= 2) { + score += 40; + signals.push("phone-unique"); + } else if (n < 8) { + score += 12; + signals.push("phone-shared"); + } + } + if (a.optigem !== "" && a.optigem === b.optigem) { + score += 30; + signals.push("optigem"); + } + if (a.birthday && a.birthday === b.birthday) { + score += 28; + signals.push("birthday"); + } + if (a.zip !== "" && a.zip === b.zip && a.street !== "" && a.street === b.street) { + score += 18; + signals.push("address"); + } + const { cls, viaNickname } = classifyFirstName(a, b); + if (cls !== "none") { + score += FIRST_NAME_WEIGHTS[cls]; + signals.push(viaNickname ? "name:nickname" : `name:${cls}`); + } else if (surnameCompatible(a, b)) { + score += 6; + signals.push("surname-only"); + } else { + score -= 10; + signals.push("no-name-evidence"); + } + return { score, matchClass: cls, signals }; +} + +/** + * Scorer for pairs outside the detector (used to rate pairs ChurchTools itself suggested). + * The population context is built once, so scoring many pairs stays linear. + */ +export function pairScorer(all: readonly DupePerson[]): (pa: DupePerson, pb: DupePerson) => PairScore { + const ctx = buildContext(all.map(prep)); + return (pa, pb) => scorePrepared(prep(pa), prep(pb), ctx); +} + +/** Score one pair outside the detector. Prefer {@link pairScorer} for more than one pair. */ +export function scorePair(pa: DupePerson, pb: DupePerson, all: readonly DupePerson[]): PairScore { + return pairScorer(all)(pa, pb); +} + +function buildContext(preps: Prep[]): Context { + const emailCount = new Map(); + const phoneCount = new Map(); + const nameCount = new Map(); + for (const p of preps) { + if (p.email !== "") emailCount.set(p.email, (emailCount.get(p.email) ?? 0) + 1); + for (const ph of p.phones) phoneCount.set(ph, (phoneCount.get(ph) ?? 0) + 1); + if (p.full !== "") nameCount.set(p.full, (nameCount.get(p.full) ?? 0) + 1); + } + return { emailCount, phoneCount, nameCount }; +} + +export interface DetectOptions { + /** Pair keys (see {@link pairKey}) that carry a suppressing relationship. */ + suppressed?: ReadonlySet; +} + +/** Blocking keys of one person. */ +function blockingKeys(p: Prep, ctx: Context, surnameCount: Map): string[] { + const keys: string[] = []; + if (p.email !== "" && (ctx.emailCount.get(p.email) ?? 0) < 8) keys.push(`em:${p.email}`); + for (const ph of p.phones) if ((ctx.phoneCount.get(ph) ?? 0) < 8) keys.push(`mo:${ph}`); + if (p.fn !== "" && p.ln !== "") { + keys.push(`nn:${p.fn}|${p.ln}`); + keys.push(`sw:${[p.fn, p.ln].sort().join("|")}`); + } + if (p.ln !== "" && p.birthday) keys.push(`lb:${p.ln}:${p.birthday}`); + if (p.ln !== "" && (surnameCount.get(p.ln) ?? 0) <= 40) keys.push(`ln:${p.ln}`); + // Compound surnames also block on each part, so "Muster Beispiel" meets "Beispiel". + if (p.lt.length > 1) { + for (const t of p.lt) if ((surnameCount.get(t) ?? 0) <= 40) keys.push(`ln:${t}`); + } + if (p.zip !== "" && p.street !== "") keys.push(`ad:${p.zip}:${p.street}`); + return keys; +} + +/** Find duplicate candidates among `persons` (callers pass active persons only). */ +export function detect(persons: readonly DupePerson[], options: DetectOptions = {}): Candidate[] { + const preps = persons.map(prep); + const byId = new Map(preps.map((p) => [p.id, p])); + const ctx = buildContext(preps); + const surnameCount = new Map(); + for (const p of preps) if (p.ln !== "") surnameCount.set(p.ln, (surnameCount.get(p.ln) ?? 0) + 1); + + const blocks = new Map(); + for (const p of preps) { + for (const k of blockingKeys(p, ctx, surnameCount)) { + const list = blocks.get(k); + if (list) list.push(p.id); + else blocks.set(k, [p.id]); + } + } + const seen = new Set(); + const out: Candidate[] = []; + for (const ids of blocks.values()) { + if (ids.length > 40) continue; + for (let i = 0; i < ids.length; i++) { + for (let j = i + 1; j < ids.length; j++) { + const key = pairKey(ids[i]!, ids[j]!); + if (seen.has(key)) continue; + seen.add(key); + if (options.suppressed?.has(key)) continue; + const res = scorePrepared(byId.get(ids[i]!)!, byId.get(ids[j]!)!, ctx); + if (res.veto) continue; + const tier = tierOf(res.score); + if (!tier) continue; + out.push({ + a: Math.min(ids[i]!, ids[j]!), + b: Math.max(ids[i]!, ids[j]!), + score: res.score, + tier, + matchClass: res.matchClass, + signals: res.signals, + source: "detector", + }); + } + } + } + return out.sort((x, y) => y.score - x.score || x.a - y.a || x.b - y.b); +} diff --git a/src/dupes/finance.ts b/src/dupes/finance.ts new file mode 100644 index 0000000..d73f978 --- /dev/null +++ b/src/dupes/finance.ts @@ -0,0 +1,143 @@ +/** + * Finance export: merges where both persons carried an Optigem ID. Each row names both persons + * (ids, names and Optigem IDs as they were before the merge), the surviving person in ChurchTools + * and the Optigem ID it now carries. Finance decides which ID stays in Optigem and updates it. + * + * JSON schema `ct-cli.dupes.optigem-merges/1` (stable; additive changes only within version 1): + * + * ```json + * { + * "schema": "ct-cli.dupes.optigem-merges/1", + * "generatedAt": "2026-01-31T09:00:00.000Z", + * "host": "https://example.church.tools", + * "since": "2026-01-01" | null, + * "merges": [ + * { + * "survivingPersonId": 123, + * "survivingPersonName": "Erika Muster", + * "survivingPersonOptigemId": "10001", + * "mergedPersonId": 456, + * "mergedPersonName": "Erika Beispiel", + * "mergedPersonOptigemId": "10002", + * "leadingOptigemId": "10001", + * "orphanedOptigemId": "10002", + * "identicalIds": false, + * "mergedAt": "2026-01-30T14:12:00.000Z", + * "mergedBy": "Erika Muster" + * } + * ] + * } + * ``` + * + * The CSV has the same rows with the header + * `surviving_person_id,surviving_person_name,surviving_person_optigem_id,merged_person_id,merged_person_name,merged_person_optigem_id,leading_optigem_id,orphaned_optigem_id,identical_ids,merged_at,merged_by`. + * + * `leadingOptigemId` is the ID the surviving person carries in ChurchTools after the merge, + * `orphanedOptigemId` the other one. Names and per-person IDs are empty for merges logged before + * they were recorded. + */ +export const FINANCE_SCHEMA = "ct-cli.dupes.optigem-merges/1"; + +export interface FinanceMerge { + survivingPersonId: number; + survivingPersonName: string; + survivingPersonOptigemId: string; + mergedPersonId: number | null; + mergedPersonName: string; + mergedPersonOptigemId: string; + leadingOptigemId: string; + orphanedOptigemId: string; + identicalIds: boolean; + mergedAt: string; + mergedBy: string; +} + +export interface FinanceExport { + schema: typeof FINANCE_SCHEMA; + generatedAt: string; + host: string; + since: string | null; + merges: FinanceMerge[]; +} + +/** Audit action written when the operator confirms CT's merge page is done. */ +export const MERGE_CONFIRMED = "merge-confirmed"; + +/** Extract finance rows from audit lines. */ +export function financeMerges(audit: ReadonlyArray>, since?: string): FinanceMerge[] { + const out: FinanceMerge[] = []; + for (const e of audit) { + if (e.action !== MERGE_CONFIRMED) continue; + const leading = typeof e.leadingOptigemId === "string" ? e.leadingOptigemId : ""; + const orphaned = typeof e.orphanedOptigemId === "string" ? e.orphanedOptigemId : ""; + // Leading may be empty (the field was cleared); a merge that orphaned no ID is not for finance. + if (orphaned === "") continue; + const ts = String(e.ts); + if (since && ts.slice(0, 10) < since) continue; + const str = (v: unknown): string => (typeof v === "string" ? v : ""); + out.push({ + survivingPersonId: Number(e.survivingId), + survivingPersonName: str(e.survivingName), + survivingPersonOptigemId: str(e.survivingOptigemId), + mergedPersonId: typeof e.loserId === "number" ? e.loserId : null, + mergedPersonName: str(e.loserName), + mergedPersonOptigemId: str(e.loserOptigemId), + leadingOptigemId: leading, + orphanedOptigemId: orphaned, + identicalIds: leading === orphaned, + mergedAt: ts, + mergedBy: typeof e.mergedBy === "string" ? e.mergedBy : "", + }); + } + return out; +} + +function csvCell(v: string | number | boolean | null): string { + const s = v === null ? "" : String(v); + // Neutralise spreadsheet formula injection as well as CSV metacharacters. + const safe = /^[=+\-@\t\r]/.test(s) ? `'${s}` : s; + return /[",\n\r]/.test(safe) ? `"${safe.replace(/"/g, '""')}"` : safe; +} + +export function toCsv(merges: readonly FinanceMerge[]): string { + const header = [ + "surviving_person_id", + "surviving_person_name", + "surviving_person_optigem_id", + "merged_person_id", + "merged_person_name", + "merged_person_optigem_id", + "leading_optigem_id", + "orphaned_optigem_id", + "identical_ids", + "merged_at", + "merged_by", + ].join(","); + const rows = merges.map((m) => + [ + m.survivingPersonId, + m.survivingPersonName, + m.survivingPersonOptigemId, + m.mergedPersonId, + m.mergedPersonName, + m.mergedPersonOptigemId, + m.leadingOptigemId, + m.orphanedOptigemId, + m.identicalIds, + m.mergedAt, + m.mergedBy, + ] + .map(csvCell) + .join(","), + ); + return `${[header, ...rows].join("\n")}\n`; +} + +export function buildFinanceExport( + merges: FinanceMerge[], + host: string, + since: string | undefined, + now: Date, +): FinanceExport { + return { schema: FINANCE_SCHEMA, generatedAt: now.toISOString(), host, since: since ?? null, merges }; +} diff --git a/src/dupes/groups.ts b/src/dupes/groups.ts new file mode 100644 index 0000000..65a4062 --- /dev/null +++ b/src/dupes/groups.ts @@ -0,0 +1,211 @@ +/** + * Groups both persons of a pair belong to. ChurchTools refuses a merge while such a group exists + * (HTTP 403 "error.forbidden.merge-persons-having-common-groups"), so these are cleaned up first: + * + * - dynamic ("Auto") groups: the Duplikat is removed; the group's ruleset decides about the + * Original anyway. + * - other groups: the Original's membership is kept and updated with the operator's choices (the + * earlier join date by default, empty values filled from the Duplikat), then the Duplikat is + * removed. + * + * Verified on a dev instance: `GET /groups/{g}/members/{p}` reads one membership, `PATCH` on it sets + * `memberStartDate`, `comment` and `fields`, and `DELETE` removes a member from a dynamic group too. + */ +import { fetchDynamicGroupIds } from "../api/dynamicGroups.js"; +import { CtApiError } from "../api/ctClient.js"; +import type { DupesClient, MergeGroup } from "./ct.js"; +import { canon, isEmpty, type Side } from "./merge-model.js"; + +interface RawField { + id: number; + name?: string; + value?: unknown; +} + +export interface RawMembership { + groupTypeRoleId?: number | null; + groupMemberStatus?: string | null; + memberStartDate?: string | null; + memberEndDate?: string | null; + comment?: string | null; + fields?: RawField[]; +} + +export interface MemberItem { + /** `groupTypeRoleId`, `groupMemberStatus`, `memberStartDate`, `memberEndDate`, `comment` or `field:`. */ + key: string; + label: string; + original: unknown; + duplicate: unknown; + choice: Side; +} + +export interface SharedGroup { + id: number; + title: string; + dynamic: boolean; + /** Empty for dynamic groups: nothing to choose, the Duplikat is just removed. */ + items: MemberItem[]; +} + +const BASE_ITEMS: ReadonlyArray<{ key: keyof RawMembership; label: string }> = [ + { key: "groupTypeRoleId", label: "Rolle" }, + { key: "groupMemberStatus", label: "Status" }, + { key: "memberStartDate", label: "Beitritt" }, + { key: "memberEndDate", label: "Ende" }, + { key: "comment", label: "Kommentar" }, +]; + +/** Non-empty side wins, the Original wins a conflict; for the join date the earlier one wins. */ +function itemDefault(key: string, o: unknown, d: unknown): Side { + if (isEmpty(o)) return isEmpty(d) ? "original" : "duplicate"; + if (isEmpty(d)) return "original"; + if (key === "memberStartDate") + return String(d).slice(0, 10) < String(o).slice(0, 10) ? "duplicate" : "original"; + return "original"; +} + +export function buildItems(original: RawMembership, duplicate: RawMembership): MemberItem[] { + const items: MemberItem[] = []; + for (const b of BASE_ITEMS) { + const o = original[b.key] ?? null; + const d = duplicate[b.key] ?? null; + if (isEmpty(o) && isEmpty(d)) continue; + items.push({ key: b.key, label: b.label, original: o, duplicate: d, choice: itemDefault(b.key, o, d) }); + } + const fields = new Map(); + for (const f of original.fields ?? []) + fields.set(f.id, { name: f.name ?? `Feld ${f.id}`, o: f.value ?? null, d: null }); + for (const f of duplicate.fields ?? []) { + const e = fields.get(f.id) ?? { name: f.name ?? `Feld ${f.id}`, o: null, d: null }; + e.d = f.value ?? null; + fields.set(f.id, e); + } + for (const [id, f] of fields) { + if (isEmpty(f.o) && isEmpty(f.d)) continue; + items.push({ + key: `field:${id}`, + label: f.name, + original: f.o, + duplicate: f.d, + choice: itemDefault("", f.o, f.d), + }); + } + return items; +} + +export const itemDiffers = (i: MemberItem): boolean => canon(i.original) !== canon(i.duplicate); + +const dynamicIdCache = new WeakMap>(); + +/** + * Ids of all dynamic groups (one GET per client, cached: the set hardly changes during a session; + * empty and not cached when the endpoint is unavailable). + */ +export async function loadDynamicGroupIds(client: DupesClient): Promise> { + const hit = dynamicIdCache.get(client); + if (hit) return hit; + try { + const ids = await fetchDynamicGroupIds(client); + dynamicIdCache.set(client, ids); + return ids; + } catch { + return new Set(); + } +} + +/** Both memberships for every shared group of the merge preview. */ +export async function loadSharedGroups( + client: DupesClient, + both: readonly MergeGroup[], + originalId: number, + duplicateId: number, + dynamicIds: ReadonlySet, +): Promise { + const out: SharedGroup[] = []; + for (const g of both) { + const title = g.title ?? `#${g.id}`; + if (dynamicIds.has(g.id)) { + out.push({ id: g.id, title, dynamic: true, items: [] }); + continue; + } + const [o, d] = await Promise.all([ + client.get(`/groups/${g.id}/members/${originalId}`), + client.get(`/groups/${g.id}/members/${duplicateId}`), + ]); + out.push({ id: g.id, title, dynamic: false, items: buildItems(o, d) }); + } + return out; +} + +export function setItemChoice( + groups: SharedGroup[], + groupId: number, + key: string, + choice: Side, +): SharedGroup[] { + return groups.map((g) => + g.id !== groupId ? g : { ...g, items: g.items.map((i) => (i.key === key ? { ...i, choice } : i)) }, + ); +} + +/** The PATCH for the Original's membership: only values taken from the Duplikat. Null when unchanged. */ +export function membershipPatch(g: SharedGroup): Record | null { + const patch: Record = {}; + const fields: Record = {}; + for (const i of g.items) { + if (i.choice !== "duplicate" || !itemDiffers(i)) continue; + if (i.key.startsWith("field:")) fields[i.key.slice(6)] = i.duplicate; + else patch[i.key] = i.duplicate; + } + if (Object.keys(fields).length > 0) patch.fields = fields; + return Object.keys(patch).length > 0 ? patch : null; +} + +export interface GroupStep { + groupId: number; + dynamic: boolean; + /** Keys taken over from the Duplikat's membership. */ + updated: string[]; +} + +/** Where `prepareSharedGroups` stopped, so the caller can say what was already changed. */ +export interface GroupProgress { + /** The group being worked on when it threw. */ + groupId?: number; + /** The Original's membership in that group was already rewritten. */ + patched?: boolean; +} + +/** + * Update the Original's memberships, then remove the Duplikat from every shared group. Stops at the + * first failure and throws; `done` holds the steps that went through (for the audit). Idempotent for a + * retry: a Duplikat that is no longer a member (404 on the DELETE) counts as removed. + */ +export async function prepareSharedGroups( + client: DupesClient, + groups: readonly SharedGroup[], + originalId: number, + duplicateId: number, + done: GroupStep[], + progress: GroupProgress = {}, +): Promise { + for (const g of groups) { + progress.groupId = g.id; + progress.patched = false; + const patch = g.dynamic ? null : membershipPatch(g); + if (patch) { + await client.request("PATCH", `/groups/${g.id}/members/${originalId}`, patch); + progress.patched = true; + } + try { + await client.request("DELETE", `/groups/${g.id}/members/${duplicateId}`); + } catch (err) { + if (!(err instanceof CtApiError && err.status === 404)) throw err; + } + const updated = patch + ? g.items.filter((i) => i.choice === "duplicate" && itemDiffers(i)).map((i) => i.key) + : []; + done.push({ groupId: g.id, dynamic: g.dynamic, updated }); + } +} diff --git a/src/dupes/guard.ts b/src/dupes/guard.ts new file mode 100644 index 0000000..294b5d2 --- /dev/null +++ b/src/dupes/guard.ts @@ -0,0 +1,114 @@ +/** + * Personal-data guard for `ct dupes`. + * + * Against a protected (or unknown) environment the command only runs for a human at a terminal: + * stdin and stdout must be TTYs, no coding-agent marker may be in the environment, and no + * ancestor process may be a coding-agent CLI. If the ancestors cannot be read, the command + * refuses (fail closed). This is best-effort detection of known tools, not a guarantee. + * There is deliberately no flag or variable that skips it. + */ +import { execFileSync } from "node:child_process"; +import type { EnvProfile } from "../env/envs.js"; + +export interface GuardInput { + /** The selected profile, or null when no `--env` was given. */ + profile: Pick | null; + stdinIsTTY: boolean; + stdoutIsTTY: boolean; + env: NodeJS.ProcessEnv; + /** Command lines (or names) of this process's ancestors, nearest first; throws when unavailable. */ + ancestors?: () => string[]; +} + +/** + * Exact variable names that coding-agent CLIs set inside the shells they run. + * Only runtime markers belong here: configuration variables a person may export in their + * own shell profile (CODEX_HOME, AIDER_MODEL, editor-terminal CURSOR_* ids) would lock + * humans out, so tool prefixes are deliberately not matched. + */ +const AGENT_ENV_NAMES = new Set([ + "CLAUDECODE", + "AI_AGENT", + "CURSOR_AGENT", + "GEMINI_CLI", + "CODEX_SANDBOX", + "CODEX_SANDBOX_NETWORK_DISABLED", + "OPENCODE", +]); + +/** Variable name prefixes used by coding-agent CLIs (kept from the original Claude Code check). */ +const AGENT_ENV_PREFIXES = ["CLAUDE_CODE_"]; + +/** Environment markers set by coding-agent CLIs (a list of known tools). */ +export function agentMarkers(env: NodeJS.ProcessEnv): string[] { + return Object.keys(env).filter( + (k) => + env[k] !== undefined && (AGENT_ENV_NAMES.has(k) || AGENT_ENV_PREFIXES.some((p) => k.startsWith(p))), + ); +} + +/** Whether this env holds data the guard protects. Unknown (no `--env`) counts as protected. */ +export function needsGuard(profile: GuardInput["profile"]): boolean { + return profile === null || profile.protected || profile.gateway !== undefined; +} + +/** + * Full command lines of this process's ancestors, nearest first, via `ps`. + * Throws when `ps` cannot be run or yields nothing, so the guard fails closed. + */ +export function processAncestors(startPid: number = process.pid, maxDepth = 16): string[] { + const ps = (pid: number, fields: string): string => + execFileSync("ps", ["-o", fields, "-p", String(pid)], { + encoding: "utf8", + stdio: ["ignore", "pipe", "ignore"], + }).trim(); + const lines: string[] = []; + let pid = Number(ps(startPid, "ppid=")); // throws when ps is missing or fails + if (!Number.isInteger(pid)) throw new Error("process check unavailable"); + for (let i = 0; i < maxDepth && pid > 1; i++) { + const m = /^(\d+)\s+(.*)$/.exec(ps(pid, "ppid=,args=")); + if (!m) break; + lines.push(m[2] ?? ""); + pid = Number(m[1]); + } + if (lines.length === 0) throw new Error("process check unavailable"); + return lines; +} + +const AGENT_NAMES = new Set([ + "claude", + "claude-code", + "codex", + "gemini", + "gemini-cli", + "cursor-agent", + "aider", + "cline", + "opencode", + "goose", +]); + +/** Whether a process command line (or bare name) looks like a coding-agent CLI. */ +export function isAgentProcess(commandLine: string): boolean { + return commandLine + .split(/[\s/\\]+/) + .filter((t) => t !== "") + .some((t) => AGENT_NAMES.has(t.toLowerCase().replace(/\.(c|m)?js$/, ""))); +} + +/** Throws a neutral error when the session may not read personal data. */ +export function assertHumanSession(input: GuardInput): void { + if (!needsGuard(input.profile)) return; + const refuse = (detail = ""): never => { + throw new Error(`This command is not available in this session.${detail}`); + }; + if (!input.stdinIsTTY || !input.stdoutIsTTY) refuse(); + if (agentMarkers(input.env).length > 0) refuse(); + let ancestors: string[]; + try { + ancestors = (input.ancestors ?? (() => processAncestors()))(); + } catch { + return refuse(" The process check could not run."); + } + if (ancestors.some(isAgentProcess)) refuse(); +} diff --git a/src/dupes/merge-model.ts b/src/dupes/merge-model.ts new file mode 100644 index 0000000..cce58be --- /dev/null +++ b/src/dupes/merge-model.ts @@ -0,0 +1,324 @@ +/** + * Pure merge logic for `ct dupes review`: which person fields can be chosen, the defaults, the email + * rows and the PATCH body. No I/O and no UI, so it is unit-tested on its own. + */ +import type { MergeDiffEntry } from "./ct.js"; + +/** `both` (the union of both lists) exists only for list fields a person can have several of. */ +export type Side = "original" | "duplicate" | "none" | "both"; + +/** Fields that hold a list (a person can be in several Bereiche); `both` merges the two lists. */ +const LIST_FIELDS = new Set(["departmentIds"]); +export const canMergeBoth = (key: string): boolean => LIST_FIELDS.has(key); + +/** Both lists, the Original's items first, without repeats. */ +export function unionOf(original: unknown, duplicate: unknown): unknown[] { + const out: unknown[] = []; + for (const v of [original, duplicate]) { + for (const x of Array.isArray(v) ? v : []) if (!out.includes(x)) out.push(x); + } + return out; +} + +/** + * The only person fields an operator can choose between. Everything else in a merge preview + * (guid, id, meta, domainType, image and url fields, security levels, privacy*, ...) is a system + * key and always comes from the Original. `email` is handled by the email rows, not here. + */ +export const CHOOSABLE_FIELDS: ReadonlyArray<{ key: string; label: string }> = [ + { key: "title", label: "Title" }, + { key: "firstName", label: "First name" }, + { key: "lastName", label: "Last name" }, + { key: "nickname", label: "Nickname" }, + { key: "birthName", label: "Birth name" }, + { key: "sexId", label: "Sex" }, + { key: "birthday", label: "Birthday" }, + { key: "birthplace", label: "Birthplace" }, + { key: "nationalityId", label: "Nationality" }, + { key: "familyStatusId", label: "Family status" }, + { key: "weddingDate", label: "Wedding date" }, + { key: "job", label: "Job" }, + { key: "street", label: "Street" }, + { key: "addition", label: "Address addition" }, + { key: "zip", label: "ZIP" }, + { key: "city", label: "City" }, + { key: "country", label: "Country" }, + { key: "phonePrivate", label: "Phone (private)" }, + { key: "phoneWork", label: "Phone (work)" }, + { key: "mobile", label: "Mobile" }, + { key: "fax", label: "Fax" }, + { key: "campusId", label: "Campus" }, + { key: "statusId", label: "Status" }, + { key: "departmentIds", label: "Departments" }, +]; + +export interface FieldRow { + key: string; + label: string; + original: unknown; + duplicate: unknown; + choice: Side; + /** True for the Optigem ID row (drives the finance audit). */ + optigem: boolean; +} + +export interface EmailRow { + address: string; + /** The original's entry (kept with its id) when the address exists there. */ + originalEntry: Record | null; + /** The duplicate's entry when it exists there. */ + duplicateEntry: Record | null; + include: boolean; + isDefault: boolean; +} + +export interface MergeModel { + fields: FieldRow[]; + emails: EmailRow[]; + optigemField: string; +} + +export const isEmpty = (v: unknown): boolean => + v === null || v === undefined || v === "" || (Array.isArray(v) && v.length === 0); + +/** Canonical string form, for comparing and displaying. */ +export function canon(v: unknown): string { + if (isEmpty(v)) return ""; + if (Array.isArray(v)) return v.map(String).join(", "); + return typeof v === "object" ? JSON.stringify(v) : String(v); +} + +/** Non-empty side wins; the Original wins a conflict. */ +export function defaultChoice(original: unknown, duplicate: unknown): Side { + if (!isEmpty(original)) return "original"; + return isEmpty(duplicate) ? "none" : "duplicate"; +} + +const addrKey = (e: Record): string => String(e.email ?? "").toLowerCase(); + +function emailList(raw: unknown): Array> { + return Array.isArray(raw) ? (raw as Array>).filter((e) => addrKey(e) !== "") : []; +} + +/** One row per distinct address of both persons; all included, the Original's default stays default. */ +export function buildEmailRows( + originalRaw: Record, + duplicateRaw: Record, +): EmailRow[] { + const rows = new Map(); + for (const e of emailList(originalRaw.emails)) { + rows.set(addrKey(e), { + address: String(e.email), + originalEntry: e, + duplicateEntry: null, + include: true, + isDefault: e.isDefault === true, + }); + } + const dup = emailList(duplicateRaw.emails); + for (const e of dup) { + const row = rows.get(addrKey(e)); + if (row) row.duplicateEntry = e; + else { + rows.set(addrKey(e), { + address: String(e.email), + originalEntry: null, + duplicateEntry: e, + include: true, + isDefault: false, + }); + } + } + const list = [...rows.values()]; + if (!list.some((r) => r.isDefault) && list.length > 0) { + const dupDefault = list.find((r) => r.duplicateEntry?.isDefault === true); + (dupDefault ?? list[0]!).isDefault = true; + } + // exactly one default + let seen = false; + for (const r of list) { + if (r.isDefault && seen) r.isDefault = false; + if (r.isDefault) seen = true; + } + return list; +} + +/** Field rows: every choosable field either person has a value for (differing or not), plus Optigem. */ +export function buildModel( + originalRaw: Record, + duplicateRaw: Record, + personDiff: readonly MergeDiffEntry[], + optigemField: string, +): MergeModel { + const diffNames = new Map(personDiff.filter((d) => d.key !== null).map((d) => [d.key as string, d.name])); + const specs = [ + ...CHOOSABLE_FIELDS.filter((f) => f.key !== optigemField), + { key: optigemField, label: "Optigem ID" }, + ]; + const fields: FieldRow[] = []; + for (const s of specs) { + const o = originalRaw[s.key]; + const d = duplicateRaw[s.key]; + if (isEmpty(o) && isEmpty(d)) continue; + // A list field keeps the entries of both persons when both have some and they differ. + const both = canMergeBoth(s.key) && !isEmpty(o) && !isEmpty(d) && canon(unionOf(o, d)) !== canon(o); + fields.push({ + key: s.key, + label: s.key === optigemField ? s.label : (diffNames.get(s.key) ?? s.label), + original: o, + duplicate: d, + choice: both ? "both" : defaultChoice(o, d), + optigem: s.key === optigemField, + }); + } + return { fields, emails: buildEmailRows(originalRaw, duplicateRaw), optigemField }; +} + +export const differs = (r: FieldRow): boolean => canon(r.original) !== canon(r.duplicate); + +export function setChoice(m: MergeModel, key: string, choice: Side): MergeModel { + if (choice === "both" && !canMergeBoth(key)) return m; + return { ...m, fields: m.fields.map((f) => (f.key === key ? { ...f, choice } : f)) }; +} + +export function toggleEmail(m: MergeModel, address: string): MergeModel { + const emails = m.emails.map((e) => (e.address === address ? { ...e, include: !e.include } : e)); + return { ...m, emails: ensureDefault(emails) }; +} + +export function setDefaultEmail(m: MergeModel, address: string): MergeModel { + const emails = m.emails.map((e) => + e.address === address ? { ...e, include: true, isDefault: true } : { ...e, isDefault: false }, + ); + return { ...m, emails }; +} + +/** Keep exactly one default among the included addresses. */ +function ensureDefault(emails: EmailRow[]): EmailRow[] { + const included = emails.filter((e) => e.include); + if (included.length === 0) return emails.map((e) => ({ ...e, isDefault: false })); + const keep = included.find((e) => e.isDefault) ?? included[0]!; + return emails.map((e) => ({ ...e, isDefault: e === keep })); +} + +/** Value written to the body for a cleared field. */ +function cleared(sample: unknown): unknown { + if (Array.isArray(sample)) return []; + return typeof sample === "string" ? "" : null; +} + +export interface OptigemOutcome { + leading: string; + orphaned: string; +} + +/** + * Leading ID follows the choice. The orphaned ID(s) are every ID that no longer sits on the merged + * person: the other side's ID, or both when the field is cleared. Several are joined with "; ". + * Empty when no ID is lost (a lone ID that is kept). + */ +export function optigemOutcome(m: MergeModel): OptigemOutcome { + const row = m.fields.find((f) => f.optigem); + if (!row) return { leading: "", orphaned: "" }; + const o = canon(row.original); + const d = canon(row.duplicate); + const chosen = row.choice === "original" ? o : row.choice === "duplicate" ? d : ""; + const lost = row.choice === "original" ? [d] : row.choice === "duplicate" ? [o] : [o, d]; + const orphaned = [...new Set(lost.filter((x) => x !== ""))].join("; "); + return { leading: chosen, orphaned }; +} + +/** + * The PATCH body: the (freshly read) original with the chosen values applied. Duplicate addresses + * are copied without their id. A chosen duplicate value the duplicate object does not carry is + * skipped and reported in `warnings`. + */ +/** + * System keys ChurchTools' own merge UI sends in the PATCH body (observed in a HAR of the web UI). + * Everything else the GET returns is left out: sending the full GET object is rejected (400), and + * nested objects such as `invitationStatus` or `privacyPolicyAgreement` make the endpoint fail + * with a 500 (verified on a dev instance). + */ +export const SYSTEM_KEYS = [ + "id", + "guid", + "domainType", + "meta", + "campusId", + "statusId", + "departmentIds", + "canChat", + "chatActive", + "isArchived", + "isDead", + "firstContact", + "lastEditedDate", + "visibility", + "securityLevelForPerson", + "editSecurityLevelForPerson", + "privacyPolicyAgreementDate", + "privacyPolicyAgreementTypeId", + "privacyPolicyAgreementWhoId", +] as const; + +const META_KEYS = ["createdDate", "createdPerson", "modifiedDate", "modifiedPerson"]; + +/** + * The Original as ChurchTools' merge UI sends it: the system keys above plus the person fields + * (`personKeys`), each only when it has a value. + */ +export function writableBody( + raw: Record, + personKeys: Iterable, +): Record { + const out: Record = {}; + for (const k of new Set([...SYSTEM_KEYS, ...personKeys])) { + if (k in raw && !isEmpty(raw[k])) out[k] = raw[k]; + } + if (out.meta && typeof out.meta === "object") { + const m = out.meta as Record; + out.meta = Object.fromEntries(META_KEYS.filter((k) => k in m).map((k) => [k, m[k]])); + } + return out; +} + +export function buildBody( + freshOriginal: Record, + duplicateRaw: Record, + m: MergeModel, +): { body: Record; warnings: string[] } { + const body = writableBody(freshOriginal, [ + ...CHOOSABLE_FIELDS.map((f) => f.key), + ...m.fields.map((f) => f.key), + ]); + const warnings: string[] = []; + for (const f of m.fields) { + if (f.choice === "original") continue; + if (f.choice === "none") { + body[f.key] = cleared(freshOriginal[f.key] ?? f.original); + } else if (f.choice === "both") { + body[f.key] = unionOf(freshOriginal[f.key] ?? f.original, duplicateRaw[f.key] ?? f.duplicate); + } else if (f.key in duplicateRaw) { + body[f.key] = duplicateRaw[f.key]; + } else { + warnings.push(`${f.label}: value cannot be carried over automatically, set it in ChurchTools.`); + } + } + if (m.emails.length > 0 || "emails" in freshOriginal) { + const included = ensureDefault(m.emails).filter((e) => e.include); + const fresh = new Map(emailList(freshOriginal.emails).map((e) => [addrKey(e), e])); + const emails = included.map((e) => { + const live = fresh.get(e.address.toLowerCase()) ?? e.originalEntry; + const base = (live ?? e.duplicateEntry ?? {}) as Record; + // ChurchTools' merge UI sends exactly these three keys per address (no id). + return { contactLabelId: base.contactLabelId ?? null, email: e.address, isDefault: e.isDefault }; + }); + body.emails = emails; + } + return { body, warnings }; +} + +/** ChurchTools' merge UI proposes the person with the lower id as the Original. */ +export function olderFirst(a: T, b: T): [T, T] { + return a.id <= b.id ? [a, b] : [b, a]; +} diff --git a/src/dupes/normalize.ts b/src/dupes/normalize.ts new file mode 100644 index 0000000..abe2e4e --- /dev/null +++ b/src/dupes/normalize.ts @@ -0,0 +1,75 @@ +/** + * Name, phone and date normalisation for the duplicate detector (`ct dupes`). + * + * Pure functions only; no I/O. Digits are KEPT in names on purpose: `Kids1 Muster` and + * `Kids2 Muster` are different records, and stripping digits collapsed both to `kids`. + */ + +/** Lower-case, expand German umlauts, then strip remaining diacritics. */ +export function deaccent(input: string): string { + return input + .toLowerCase() + .replace(/ä/g, "ae") + .replace(/ö/g, "oe") + .replace(/ü/g, "ue") + .replace(/ß/g, "ss") + .normalize("NFD") + .replace(/[̀-ͯ]/g, ""); +} + +/** Deaccented name with everything but letters (any script), digits, space and `-` removed. */ +export function cleanName(input: string | null | undefined): string { + return deaccent(input ?? "") + .replace(/[^\p{L}\p{N} -]/gu, "") + .replace(/\s+/g, " ") + .trim(); +} + +/** Split a cleaned name into tokens on whitespace and hyphens. */ +export function nameTokens(clean: string): string[] { + return clean.split(/[\s-]+/).filter((t) => t !== ""); +} + +const PLACEHOLDER = /^(kids?|test|gast|guest|dummy|platzhalter|seat|person)\s*\d*$/i; + +/** True for names such as `Kids 3`, `Test`, `Gast2`. */ +export function isPlaceholderName(clean: string): boolean { + return PLACEHOLDER.test(clean); +} + +/** Strip a German diminutive ending. */ +export function diminutiveStem(word: string): string { + return word.replace(/(chen|lein|ie|i|y)$/, ""); +} + +/** Normalised phone key (last 9 digits, at least 7), or null when unusable. */ +export function normalizePhone(input: string | null | undefined): string | null { + let digits = (input ?? "").replace(/\D/g, ""); + digits = digits.replace(/^(00)?49/, ""); + digits = digits.replace(/^0/, ""); + if (digits.length < 7) return null; + return digits.slice(-9); +} + +/** `YYYY-MM-DD` prefix of a date string, or null. */ +export function normalizeDate(input: string | null | undefined): string | null { + const m = /\d{4}-\d{2}-\d{2}/.exec(input ?? ""); + return m ? m[0] : null; +} + +/** Plain Levenshtein distance. */ +export function levenshtein(a: string, b: string): number { + if (a === b) return 0; + if (a.length === 0) return b.length; + if (b.length === 0) return a.length; + let prev = Array.from({ length: b.length + 1 }, (_, i) => i); + for (let i = 1; i <= a.length; i++) { + const cur = [i]; + for (let j = 1; j <= b.length; j++) { + const cost = a[i - 1] === b[j - 1] ? 0 : 1; + cur[j] = Math.min(prev[j]! + 1, cur[j - 1]! + 1, prev[j - 1]! + cost); + } + prev = cur; + } + return prev[b.length]!; +} diff --git a/src/dupes/redact.ts b/src/dupes/redact.ts new file mode 100644 index 0000000..eed5206 --- /dev/null +++ b/src/dupes/redact.ts @@ -0,0 +1,38 @@ +/** + * Stable pseudonyms for `--redact`. The same value always maps to the same short tag within one + * machine (keyed with a local secret), so equal values stay visibly equal, but nothing can be + * reversed or guessed from the output. + */ +import { createHmac } from "node:crypto"; + +export interface Redactor { + readonly enabled: boolean; + /** A person id, as shown to the operator. */ + id(id: number | string): string; + /** Any personal value (name, email, optigem id, ...). Empty stays empty. */ + value(v: string | null | undefined): string; + /** A "First Last" display name. */ + name(first: string | null | undefined, last: string | null | undefined): string; + /** An ids-in-text mask for error text (digit runs become `#`). */ + text(s: string): string; +} + +export function makeRedactor(enabled: boolean, secret: string): Redactor { + const tag = (kind: string, v: string): string => + createHmac("sha256", secret).update(`${kind}\0${v}`).digest("hex").slice(0, 4); + return { + enabled, + id: (id) => (enabled ? `P-${tag("id", String(id))}` : String(id)), + value: (v) => { + const s = v ?? ""; + if (!enabled || s === "") return s; + return `~${tag("v", s)}`; + }, + name: (first, last) => { + const s = `${first ?? ""} ${last ?? ""}`.trim(); + if (!enabled || s === "") return s; + return `Name-${tag("n", s)}`; + }, + text: (s) => (enabled ? s.replace(/\d+/g, "#") : s), + }; +} diff --git a/src/dupes/store.ts b/src/dupes/store.ts new file mode 100644 index 0000000..751ae42 --- /dev/null +++ b/src/dupes/store.ts @@ -0,0 +1,192 @@ +/** + * Local store for `ct dupes`: scan results, audit log, redaction key, exports. + * + * Lives in the user's data directory, never in a repository: directories 0700, files 0600. + * macOS ~/Library/Application Support/ct-cli/dupes// + * other $XDG_DATA_HOME (default ~/.local/share)/ct-cli/dupes// + * `CT_DUPES_DIR` overrides the base directory (tests); it may not point into a git work tree. + */ +import { randomBytes } from "node:crypto"; +import { + appendFileSync, + chmodSync, + existsSync, + mkdirSync, + readFileSync, + renameSync, + statSync, + writeFileSync, +} from "node:fs"; +import { homedir } from "node:os"; +import { dirname, join, resolve } from "node:path"; +import type { Candidate } from "./detector.js"; + +export const SCAN_SCHEMA = "ct-cli.dupes.scan/1"; + +export type CandidateState = "open" | "dismissed" | "merged"; + +export interface StoredCandidate extends Candidate { + state: CandidateState; +} + +/** + * States for a fresh scan: a pair decided earlier (dismissed or merged) keeps its decision, so a + * dismissal whose write-back failed, or a merge recorded with both persons still present, does not + * come back as open. + */ +export function carryStates(previous: ScanFile | null, candidates: readonly Candidate[]): StoredCandidate[] { + const prior = new Map(); + for (const c of previous?.candidates ?? []) if (c.state !== "open") prior.set(`${c.a}:${c.b}`, c.state); + return candidates.map((c) => ({ ...c, state: prior.get(`${c.a}:${c.b}`) ?? "open" })); +} + +export interface ScanFile { + schema: typeof SCAN_SCHEMA; + host: string; + scannedAt: string; + personsScanned: number; + candidates: StoredCandidate[]; +} + +/** Lower-case host name with everything but `a-z0-9` collapsed to `-`. */ +export function hostSlug(host: string): string { + let name = host; + try { + name = new URL(host).host; + } catch { + /* keep raw */ + } + return name + .toLowerCase() + .replace(/[^a-z0-9]+/g, "-") + .replace(/^-+|-+$/g, ""); +} + +export function baseDir(env: NodeJS.ProcessEnv = process.env, platform: string = process.platform): string { + if (env.CT_DUPES_DIR?.trim()) return resolve(env.CT_DUPES_DIR.trim()); + if (platform === "darwin") return join(homedir(), "Library", "Application Support", "ct-cli", "dupes"); + const data = env.XDG_DATA_HOME?.trim() || join(homedir(), ".local", "share"); + return join(data, "ct-cli", "dupes"); +} + +/** Whether `dir` or any ancestor holds a `.git` entry. */ +export function insideGitWorkTree(dir: string): boolean { + let cur = resolve(dir); + for (;;) { + if (existsSync(join(cur, ".git"))) return true; + const up = dirname(cur); + if (up === cur) return false; + cur = up; + } +} + +/** + * Write export files into a user-chosen directory with the store's protections: refuses a + * git work tree, creates a new dir 0700 (an existing dir is left alone, with a warning if it + * is group/world accessible), and writes files 0600 via temp file + rename. + */ +export function writePrivateFiles( + dir: string, + files: Record, +): { paths: string[]; warning?: string } { + const target = resolve(dir); + if (insideGitWorkTree(target)) throw new Error("The export directory must not be inside a repository."); + let warning: string | undefined; + if (existsSync(target)) { + if ((statSync(target).mode & 0o077) !== 0) { + warning = "The export directory is readable by other users; consider restricting it (chmod 700)."; + } + } else { + mkdirSync(target, { recursive: true, mode: 0o700 }); + chmodSync(target, 0o700); + } + const paths: string[] = []; + for (const [name, content] of Object.entries(files)) { + const path = join(target, name); + const tmp = join(target, `.${name}.${randomBytes(4).toString("hex")}.tmp`); + writeFileSync(tmp, content, { mode: 0o600 }); + chmodSync(tmp, 0o600); + renameSync(tmp, path); + paths.push(path); + } + return warning ? { paths, warning } : { paths }; +} + +export class DupesStore { + readonly dir: string; + constructor(host: string, env: NodeJS.ProcessEnv = process.env, platform: string = process.platform) { + this.dir = join(baseDir(env, platform), hostSlug(host)); + if (insideGitWorkTree(this.dir)) { + throw new Error("The dupes store must not be inside a repository."); + } + } + + get scanPath(): string { + return join(this.dir, "candidates.json"); + } + get auditPath(): string { + return join(this.dir, "audit.jsonl"); + } + get exportDir(): string { + return join(this.dir, "exports"); + } + private get keyPath(): string { + return join(this.dir, "redact.key"); + } + + /** Create `dir` (and parents inside the store) with mode 0700. */ + ensureDir(dir: string = this.dir): void { + mkdirSync(dir, { recursive: true, mode: 0o700 }); + // mkdir's mode is masked by umask; enforce it on the store dir and the target. + chmodSync(this.dir, 0o700); + chmodSync(dir, 0o700); + } + + private writePrivate(path: string, content: string): void { + this.ensureDir(dirname(path)); + writeFileSync(path, content, { mode: 0o600 }); + chmodSync(path, 0o600); + } + + /** Local secret for stable pseudonyms; created on first use. */ + redactSecret(): string { + if (existsSync(this.keyPath)) return readFileSync(this.keyPath, "utf8").trim(); + const secret = randomBytes(32).toString("hex"); + this.writePrivate(this.keyPath, `${secret}\n`); + return secret; + } + + saveScan(scan: ScanFile): void { + this.writePrivate(this.scanPath, `${JSON.stringify(scan, null, 2)}\n`); + } + + loadScan(): ScanFile | null { + if (!existsSync(this.scanPath)) return null; + const parsed = JSON.parse(readFileSync(this.scanPath, "utf8")) as ScanFile; + if (parsed.schema !== SCAN_SCHEMA) throw new Error("Unsupported scan file version."); + return parsed; + } + + /** Append one audit line (`ts` is added). */ + audit(entry: Record, now: Date = new Date()): void { + this.ensureDir(); + const line = `${JSON.stringify({ ts: now.toISOString(), ...entry })}\n`; + const fresh = !existsSync(this.auditPath); + appendFileSync(this.auditPath, line, { mode: 0o600 }); + if (fresh) chmodSync(this.auditPath, 0o600); + } + + readAudit(): Array> { + if (!existsSync(this.auditPath)) return []; + return readFileSync(this.auditPath, "utf8") + .split("\n") + .filter((l) => l.trim() !== "") + .map((l) => JSON.parse(l) as Record); + } + + writeExport(name: string, content: string): string { + const path = join(this.exportDir, name); + this.writePrivate(path, content); + return path; + } +} diff --git a/src/dupes/tui/App.tsx b/src/dupes/tui/App.tsx new file mode 100644 index 0000000..51827fe --- /dev/null +++ b/src/dupes/tui/App.tsx @@ -0,0 +1,51 @@ +import { useApp } from "ink"; +import { useState, type ReactElement } from "react"; +import type { ReviewDeps } from "../actions.js"; +import type { ScanFile, StoredCandidate } from "../store.js"; +import { ListScreen, type Names } from "./ListScreen.js"; +import { PairScreen, type PairOutcome } from "./PairScreen.js"; + +export function App(props: { deps: ReviewDeps; scan: ScanFile; names: Names }): ReactElement { + const { deps, scan, names } = props; + const app = useApp(); + const [current, setCurrent] = useState(null); + const [focus, setFocus] = useState(() => + Math.max( + 0, + scan.candidates.findIndex((c) => c.state === "open"), + ), + ); + const [, bump] = useState(0); + + const done = (cand: StoredCandidate, outcome: PairOutcome): void => { + if (outcome === "merged") cand.state = "merged"; + if (outcome === "dismissed") cand.state = "dismissed"; + if (outcome === "merged" || outcome === "dismissed") deps.store.saveScan(scan); + const idx = scan.candidates.indexOf(cand); + const next = scan.candidates.findIndex((c, i) => i > idx && c.state === "open"); + setFocus(outcome === "back" ? idx : next >= 0 ? next : idx); + setCurrent(null); + bump((n) => n + 1); + }; + + if (current) { + return ( + done(current, o)} + /> + ); + } + return ( + app.exit()} + /> + ); +} diff --git a/src/dupes/tui/ListScreen.tsx b/src/dupes/tui/ListScreen.tsx new file mode 100644 index 0000000..6be67a5 --- /dev/null +++ b/src/dupes/tui/ListScreen.tsx @@ -0,0 +1,74 @@ +/** List screen: all candidates of the last scan. */ +import { Box, Text, useInput, useStdout } from "ink"; +import { useState, type ReactElement } from "react"; +import type { Redactor } from "../redact.js"; +import type { StoredCandidate } from "../store.js"; + +export type Names = Map; + +export function filterCandidates(all: readonly StoredCandidate[], tier: string | null): StoredCandidate[] { + return tier === null ? [...all] : all.filter((c) => c.tier === tier); +} + +export function ListScreen(props: { + candidates: readonly StoredCandidate[]; + names: Names; + redactor: Redactor; + /** Index into the unfiltered list to put the cursor on. */ + focus: number; + onOpen: (c: StoredCandidate) => void; + onQuit: () => void; +}): ReactElement { + const { candidates, names, redactor: r } = props; + const { stdout } = useStdout(); + const height = Math.max(5, (stdout.rows ?? 30) - 8); + const [tier, setTier] = useState(null); + const [cursor, setCursor] = useState(() => Math.max(0, props.focus)); + + const list = filterCandidates(candidates, tier); + const at = Math.min(cursor, Math.max(0, list.length - 1)); + const open = candidates.filter((c) => c.state === "open").length; + + useInput((input, key) => { + if (input === "q") return props.onQuit(); + if (key.upArrow) setCursor(Math.max(0, at - 1)); + else if (key.downArrow) setCursor(Math.min(list.length - 1, at + 1)); + else if (key.pageUp) setCursor(Math.max(0, at - height)); + else if (key.pageDown) setCursor(Math.min(list.length - 1, at + height)); + else if (input === "1" || input === "2" || input === "3") { + setTier(`T${input}`); + setCursor(0); + } else if (input === "a") { + setTier(null); + setCursor(0); + } else if (key.return) { + const c = list[at]; + if (c && c.state === "open") props.onOpen(c); + } + }); + + const start = Math.min(Math.max(0, at - height + 1), Math.max(0, list.length - height)); + const name = (id: number): string => { + const n = names.get(id); + return n ? r.name(n.first, n.last) : `#${r.id(id)}`; + }; + return ( + + + Duplikate prüfen: {open} offen von {candidates.length} Filter: {tier ?? "alle"} + + Tier Score Klasse Quelle Original / Duplikat + {list.slice(start, start + height).map((c, i) => { + const selected = start + i === at; + return ( + + {selected ? "›" : " "} {c.tier} {String(c.score).padEnd(5)} {c.matchClass.padEnd(11)}{" "} + {c.source.padEnd(8)} {name(c.a)} / {name(c.b)} [{c.state}] + + ); + })} + {list.length === 0 ? Keine Paare in diesem Filter. : null} + ↑/↓ PgUp/PgDn bewegen Enter öffnen 1/2/3 Tier a alle q beenden + + ); +} diff --git a/src/dupes/tui/PairScreen.tsx b/src/dupes/tui/PairScreen.tsx new file mode 100644 index 0000000..ed62f07 --- /dev/null +++ b/src/dupes/tui/PairScreen.tsx @@ -0,0 +1,492 @@ +/** Pair screen: modelled on ChurchTools' "Dubletten überprüfen" dialog. */ +import { Box, Text, useInput, useStdout } from "ink"; +import { useEffect, useState, type ReactElement } from "react"; +import { CtApiError } from "../../api/ctClient.js"; +import { + executeMerge, + formatValue, + emailLabel, + isMasterValue, + loadPair, + markNotDuplicate, + PairLoadError, + recoverUnrecordedMerge, + type PairData, + type ReviewDeps, +} from "../actions.js"; +import { + differs, + setChoice, + unionOf, + setDefaultEmail, + toggleEmail, + type EmailRow, + type FieldRow, + type MergeModel, + type Side, +} from "../merge-model.js"; +import { itemDiffers, setItemChoice, type MemberItem, type SharedGroup } from "../groups.js"; +import type { StoredCandidate } from "../store.js"; + +export type PairOutcome = "merged" | "dismissed" | "skipped" | "back"; + +type Entry = + | { kind: "field"; row: FieldRow } + | { kind: "email"; row: EmailRow } + | { kind: "group"; group: SharedGroup } + | { kind: "member"; group: SharedGroup; row: MemberItem }; + +const entryId = (e: Entry): string => + e.kind === "field" + ? `f:${e.row.key}` + : e.kind === "email" + ? `e:${e.row.address}` + : e.kind === "group" + ? `g:${e.group.id}` + : `m:${e.group.id}:${e.row.key}`; + +export function visibleEntries( + model: MergeModel, + showIdentical: boolean, + shared: readonly SharedGroup[] = [], +): Entry[] { + const out: Entry[] = []; + for (const f of model.fields) if (showIdentical || differs(f)) out.push({ kind: "field", row: f }); + const emailsDiffer = model.emails.some((e) => !e.originalEntry || !e.duplicateEntry); + if (showIdentical || emailsDiffer) for (const e of model.emails) out.push({ kind: "email", row: e }); + for (const g of shared) { + out.push({ kind: "group", group: g }); + for (const i of g.items) + if (showIdentical || itemDiffers(i)) out.push({ kind: "member", group: g, row: i }); + } + return out; +} + +/** What happens to a shared group, in one line. */ +export function groupPlan(g: SharedGroup): string { + if (g.dynamic) return `Auto-Gruppe: Duplikat wird entfernt`; + const taken = g.items.filter((i) => i.choice === "duplicate" && itemDiffers(i)).map((i) => i.label); + return taken.length === 0 + ? "Mitgliedschaft des Originals bleibt, Duplikat wird entfernt" + : `Original übernimmt ${taken.join(", ")} vom Duplikat; Duplikat wird entfernt`; +} + +const clip = (s: string, n: number): string => + s.length <= n ? s.padEnd(n) : `${s.slice(0, Math.max(0, n - 1))}…`; + +function PersonCard(props: { + title: string; + color: "green" | "red"; + name: string; + id: string; + created: string; + login: string; +}): ReactElement { + return ( + + + {props.title} + + {props.name || "(no name)"} + ID: {props.id} + Erstellt am: {props.created || "-"} + Letzter Login: {props.login || "nie"} + + ); +} + +export function PairScreen(props: { + deps: ReviewDeps; + cand: StoredCandidate; + onDone: (o: PairOutcome, note?: string) => void; +}): ReactElement { + const { deps, cand, onDone } = props; + const r = deps.redactor; + const { stdout } = useStdout(); + const cols = stdout.columns ?? 100; + const rowsAvail = stdout.rows ?? 30; + + const [dir, setDir] = useState<[number, number]>([Math.min(cand.a, cand.b), Math.max(cand.a, cand.b)]); + const [pair, setPair] = useState(null); + const [model, setModel] = useState(null); + const [shared, setShared] = useState([]); + const [error, setError] = useState(null); + const [cursor, setCursor] = useState(0); + const [showIdentical, setShowIdentical] = useState(false); + const [mode, setMode] = useState<"table" | "confirm" | "busy" | "result">("table"); + const [message, setMessage] = useState([]); + const [outcome, setOutcome] = useState("back"); + + useEffect(() => { + let live = true; + setPair(null); + setError(null); + loadPair(deps, dir[0], dir[1]).then( + (p) => { + if (!live) return; + setPair(p); + setModel(p.model); + setShared(p.shared); + setCursor(0); + }, + async (err: unknown) => { + if (!live) return; + if (err instanceof PairLoadError && err.personGone) { + if (await recoverUnrecordedMerge(deps, cand.a, cand.b)) { + setOutcome("merged"); + setMessage(["An earlier merge of this pair had not been recorded; recorded it now."]); + } else { + setOutcome("skipped"); + setMessage(["One of the two persons no longer exists."]); + } + setMode("result"); + return; + } + setError( + `Could not load the pair (${ + err instanceof PairLoadError + ? `${err.step === "preview" ? "merge preview" : err.step === "membership" ? "group membership" : err.step}${err.status ? `, HTTP ${err.status}` : ""}` + : err instanceof CtApiError + ? `HTTP ${err.status}` + : "error" + }).`, + ); + }, + ); + return () => { + live = false; + }; + }, [dir]); + + const entries = pair && model ? visibleEntries(model, showIdentical, shared) : []; + const current = entries[Math.min(cursor, Math.max(0, entries.length - 1))]; + + const update = (f: (m: MergeModel) => MergeModel): void => setModel((m) => (m ? f(m) : m)); + + useInput((input, key) => { + if (mode === "busy") return; + if (mode === "result") { + onDone(outcome, message[0]); + return; + } + if (mode === "confirm") { + if (input === "y" || key.return) void doMerge(); + else if (input === "n" || key.escape) setMode("table"); + return; + } + if (key.escape) return onDone("back"); + if (error) return; + if (!pair || !model) return; + if (key.upArrow) setCursor((c) => Math.max(0, c - 1)); + else if (key.downArrow) setCursor((c) => Math.min(entries.length - 1, c + 1)); + else if (key.pageUp) setCursor((c) => Math.max(0, c - 10)); + else if (key.pageDown) setCursor((c) => Math.min(entries.length - 1, c + 10)); + else if (input === "i") setShowIdentical((v) => !v); + else if (input === "t") setDir(([a, b]) => [b, a]); + else if (input === "s") onDone("skipped"); + else if (input === "n") void doNoDuplicate(); + else if (input === "m") setMode("confirm"); + else if ( + current?.kind === "field" && + (key.leftArrow || key.rightArrow || input === "x" || input === "b") + ) { + const side: Side = key.leftArrow + ? "duplicate" + : key.rightArrow + ? "original" + : input === "b" + ? "both" + : "none"; + update((m) => setChoice(m, current.row.key, side)); + } else if (current?.kind === "member" && (key.leftArrow || key.rightArrow)) { + const side: Side = key.leftArrow ? "duplicate" : "original"; + const g = current.group.id; + const k = current.row.key; + setShared((gs) => setItemChoice(gs, g, k, side)); + } else if (current?.kind === "email" && (input === " " || input === "x")) { + update((m) => toggleEmail(m, current.row.address)); + } else if (current?.kind === "email" && input === "*") { + update((m) => setDefaultEmail(m, current.row.address)); + } + }); + + async function doNoDuplicate(): Promise { + setMode("busy"); + const res = await markNotDuplicate(deps, dir[0], dir[1]); + setOutcome("dismissed"); + setMessage([ + res.ok + ? "Marked as not a duplicate in ChurchTools." + : `The decision is saved locally, but ChurchTools did not accept the write-back${res.status ? ` (HTTP ${res.status})` : ""}.`, + ]); + setMode("result"); + } + + async function doMerge(): Promise { + if (!pair || !model) return; + setMode("busy"); + const res = await executeMerge(deps, pair, model, shared); + if (res.kind === "failed") { + // Group steps went through: take the re-read pair so a retry sees the groups as they are now. + if (res.fresh) { + setPair(res.fresh); + setShared(res.fresh.shared); + } + setOutcome("back"); + setMessage([ + res.stage === "reread" + ? `Could not re-read the Original${res.status ? ` (HTTP ${res.status})` : ""}; nothing was changed.` + : res.stage === "groups" + ? `Gruppe ${res.groupId ?? "?"} konnte nicht vorbereitet werden${res.status ? ` (HTTP ${res.status})` : ""}; nicht zusammengeführt.${ + res.groupsDone && res.groupsDone.length > 0 + ? ` Bereits erledigt (nicht zurückgenommen): Gruppen ${res.groupsDone.map((g) => g.groupId).join(", ")}.` + : "" + }${res.groupPatched ? ` In Gruppe ${res.groupId ?? "?"} wurde die Mitgliedschaft des Originals schon angepasst.` : ""}${ + res.stale ? " Bitte das Paar neu laden, bevor du es erneut versuchst." : "" + }` + : `Merge failed${res.status ? ` (HTTP ${res.status})` : ""}${ + res.fields && res.fields.length > 0 ? `; ChurchTools rejected: ${res.fields.join(", ")}` : "" + }${res.reason ? `; reason: ${res.reason}` : ""}.${ + res.groupsDone && res.groupsDone.length > 0 + ? ` Gruppen ${res.groupsDone.map((g) => g.groupId).join(", ")} wurden schon vorbereitet (Duplikat entfernt).` + : " Nothing was changed." + }`, + ]); + } else { + setOutcome("merged"); + setMessage([ + res.duplicateStillExists + ? "Merged. ChurchTools kept the duplicate record (it was not deleted); the merge is recorded." + : res.checkFailed + ? "Merged, but could not check whether the duplicate record still exists." + : res.afterError + ? "The request reported an error, but the duplicate is gone; the merge is recorded." + : "Merged.", + ...res.warnings, + ]); + } + setMode("result"); + } + + // --- render --- + if (mode === "result") { + return ( + + {message.map((l, i) => ( + + {l} + + ))} + Press any key to return to the list. + + ); + } + if (error) { + return ( + + {error} + Esc: back + + ); + } + if (!pair || !model) return Loading pair…; + + const labels = deps.labels; + const show = (key: string, v: unknown): string => { + const text = formatValue(key, v, labels); + return isMasterValue(key, v, labels) ? text : r.value(text); + }; + const nameOf = (p: PairData["original"]): string => r.name(p.firstName, p.lastName); + const date = (s: string): string => s.slice(0, 10); + + const labelW = 18; + const colW = Math.max(10, Math.floor((cols - labelW - 8) / 3)); + const height = Math.max(5, rowsAvail - 16 - shared.length); + const start = Math.min(Math.max(0, cursor - height + 1), Math.max(0, entries.length - height)); + const window = entries.slice(start, start + height); + const gd = pair.preview.groupsDiff; + + const cell = (text: string, color?: "green" | "red", bold?: boolean): ReactElement => ( + + {clip(text, colW)} + + ); + + if (mode === "confirm") { + const changed = model.fields.filter( + (f) => f.choice !== "original" && (differs(f) || f.choice === "none"), + ); + const included = model.emails.filter((e) => e.include); + return ( + + Zusammenführen? + + Duplikat {r.id(pair.duplicate.id)} wird in Original {r.id(pair.original.id)} zusammengeführt. + + + ChurchTools verschiebt Gruppenmitgliedschaften und verknüpfte Daten und löscht das Duplikat. + + {shared.map((g) => ( + + Gruppe {g.title}: {groupPlan(g)} + + ))} + {changed.length === 0 ? ( + Alle Felder bleiben beim Original. + ) : ( + changed.map((f) => ( + + {f.label}: {show(f.key, f.original) || "(leer)"} →{" "} + {f.choice === "none" + ? "(leer)" + : f.choice === "both" + ? show(f.key, unionOf(f.original, f.duplicate)) + : show(f.key, f.duplicate)} + + )) + )} + + E-Mail-Adressen: {included.length} von {model.emails.length} übernommen + + [y/Enter] ja [n/Esc] abbrechen + + ); + } + + return ( + + + + + + + {clip("Feld", labelW)} {clip("Original", colW)} {clip("Ergebnis", colW)} {clip("Duplikat", colW)} + {showIdentical ? " (inkl. identische Felder)" : ""} + + {window.map((e) => { + const selected = current !== undefined && entryId(e) === entryId(current); + const pointer = selected ? "›" : " "; + if (e.kind === "field") { + const f = e.row; + const diff = differs(f); + const oText = show(f.key, f.original); + const dText = show(f.key, f.duplicate); + const both = f.choice === "both"; + const result = + f.choice === "original" + ? oText + : f.choice === "duplicate" + ? dText + : both + ? show(f.key, unionOf(f.original, f.duplicate)) + : ""; + const oColor = diff ? (f.choice === "original" || both ? "green" : "red") : undefined; + const dColor = diff ? (f.choice === "duplicate" || both ? "green" : "red") : undefined; + return ( + + + {pointer} + {clip(f.label, labelW - 1)} + + + {cell(oText, oColor)} + + {cell(f.choice === "none" ? "(leer)" : result, "green", true)} + + {cell(dText, dColor)} + + ); + } + if (e.kind === "group") { + return ( + + + {pointer} + {clip(`Gruppe ${e.group.title}`, labelW + colW * 3 + 2)} + + + ); + } + if (e.kind === "member") { + const i = e.row; + const diff = itemDiffers(i); + const oText = show(i.key, i.original); + const dText = show(i.key, i.duplicate); + const oColor = diff ? (i.choice === "original" ? "green" : "red") : undefined; + const dColor = diff ? (i.choice === "duplicate" ? "green" : "red") : undefined; + return ( + + + {pointer} + {clip(` ${i.label}`, labelW - 1)} + + + {cell(oText, oColor)} + + {cell(i.choice === "original" ? oText : dText, "green", true)} + + {cell(dText, dColor)} + + ); + } + const m = e.row; + return ( + + + {pointer} + {clip(emailLabel(m, labels), labelW - 1)} + + + {cell(m.originalEntry ? r.value(m.address) : "", m.include ? "green" : "red")} + + {cell( + `[${m.include ? "x" : " "}] ${r.value(m.address)}${m.isDefault && m.include ? " *" : ""}`, + "green", + true, + )} + + {cell(m.duplicateEntry ? r.value(m.address) : "", m.include ? "green" : "red")} + + ); + })} + {entries.length === 0 ? ( + Keine abweichenden Felder. (i: identische Felder zeigen) + ) : null} + + Gruppen: {gd.old.length} (Duplikat: {gd.new.length}), gemeinsam: {gd.both.length}. ChurchTools + verschiebt die übrigen Mitgliedschaften beim Zusammenführen. + + {shared.map((g) => ( + + {clip(`Gruppe ${g.title}: ${groupPlan(g)}`, Math.max(20, cols - 1))} + + ))} + + m Zusammenführen t Tauschen n Keine Dublette s Überspringen Esc Liste i Identische ←/→ Wert x + leeren/umschalten * Standard-Adresse + + {mode === "busy" ? Working… : null} + + ); +} diff --git a/src/dupes/tui/run.tsx b/src/dupes/tui/run.tsx new file mode 100644 index 0000000..6aacb02 --- /dev/null +++ b/src/dupes/tui/run.tsx @@ -0,0 +1,11 @@ +/** Entry point, imported lazily by `ct dupes review` so other commands never load Ink or React. */ +import { render } from "ink"; +import { loadNames, type ReviewDeps } from "../actions.js"; +import type { ScanFile } from "../store.js"; +import { App } from "./App.js"; + +export async function runReviewTui(deps: ReviewDeps, scan: ScanFile): Promise { + const names = await loadNames(deps.client); + const instance = render(); + await instance.waitUntilExit(); +} diff --git a/src/dupes/web/page.ts b/src/dupes/web/page.ts new file mode 100644 index 0000000..385cef3 --- /dev/null +++ b/src/dupes/web/page.ts @@ -0,0 +1,502 @@ +/** + * The single page of the `ct dupes review` browser UI, modelled on ChurchTools' "Dubletten + * überprüfen" page and its "Welche Daten sollen übernommen werden?" dialog. Plain DOM, no + * framework, no external requests. Every value from ChurchTools is inserted as text, never as + * HTML. The API token comes from the URL fragment and is sent as a header. + */ +export const PAGE_HTML = String.raw` + + + + +Dubletten überprüfen · ct dupes + + + +
+ ct dupes + + + +
+

Lade…

+
+ + + +`; diff --git a/src/dupes/web/run.ts b/src/dupes/web/run.ts new file mode 100644 index 0000000..bbf1138 --- /dev/null +++ b/src/dupes/web/run.ts @@ -0,0 +1,37 @@ +/** Entry point of the browser review, imported lazily by `ct dupes review`. */ +import { spawn } from "node:child_process"; +import { loadNames, type ReviewDeps } from "../actions.js"; +import type { ScanFile } from "../store.js"; +import { info } from "../../ui.js"; +import { startReviewServer } from "./server.js"; + +function openBrowser(url: string): void { + const [cmd, args] = + process.platform === "darwin" + ? ["open", [url]] + : process.platform === "win32" + ? ["cmd", ["/c", "start", "", url]] + : ["xdg-open", [url]]; + try { + const child = spawn(cmd, args, { stdio: "ignore", detached: true }); + child.on("error", () => undefined); + child.unref(); + } catch { + /* the address is printed anyway */ + } +} + +export async function runReviewWeb(deps: ReviewDeps, scan: ScanFile, opts: { open: boolean }): Promise { + const names = await loadNames(deps.client); + const server = await startReviewServer(deps, scan, names); + info(`Review läuft im Browser: ${server.url}`); + info("Beenden mit dem Button oben rechts oder Ctrl-C."); + if (opts.open) openBrowser(server.url); + const stop = (): void => server.close(); + process.once("SIGINT", stop); + try { + await server.closed; + } finally { + process.off("SIGINT", stop); + } +} diff --git a/src/dupes/web/server.ts b/src/dupes/web/server.ts new file mode 100644 index 0000000..949904f --- /dev/null +++ b/src/dupes/web/server.ts @@ -0,0 +1,511 @@ +/** + * Browser UI for `ct dupes review`: a local HTTP server modelled on ChurchTools' "Dubletten + * überprüfen" page, with the extras of ct dupes (shared group clean-up, Optigem, audit). + * + * The server listens on 127.0.0.1 only, on a random port. Every API call must carry a random + * per-run token in the `X-Ct-Dupes-Token` header (the browser gets it in the URL fragment, which + * is never sent to a server) and a `Host` header naming that exact address, so other pages in the + * browser can neither read the data (no CORS headers, a custom header needs a preflight) nor drive + * a merge, and DNS rebinding fails. The page itself carries no data. + */ +import { randomBytes, timingSafeEqual } from "node:crypto"; +import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http"; +import type { AddressInfo } from "node:net"; +import { CtApiError } from "../../api/ctClient.js"; +import { + executeMerge, + formatValue, + emailLabel, + emailTypes, + isMasterValue, + loadPair, + markNotDuplicate, + PairLoadError, + recoverUnrecordedMerge, + type MergeResult, + type PairData, + type ReviewDeps, +} from "../actions.js"; +import { financeMerges, toCsv } from "../finance.js"; +import { itemDiffers, setItemChoice, type SharedGroup } from "../groups.js"; +import { + canMergeBoth, + differs, + optigemOutcome, + setChoice, + unionOf, + type MergeModel, + type Side, +} from "../merge-model.js"; +import type { ScanFile, StoredCandidate } from "../store.js"; +import { PAGE_HTML } from "./page.js"; + +export interface PersonSummary { + first: string; + last: string; + created?: string; + login?: string; +} + +/** ChurchTools' German field names; the merge preview sometimes reports only the key. */ +const LABEL: Record = { + title: "Titel", + firstName: "Vorname", + lastName: "Nachname", + nickname: "Spitzname", + birthName: "Geburtsname", + sexId: "Geschlecht", + birthday: "Geburtstag", + birthplace: "Geburtsort", + nationalityId: "Nationalität", + familyStatusId: "Familienstand", + weddingDate: "Hochzeitstag", + job: "Beruf", + street: "Straße", + addition: "Adresszusatz", + zip: "PLZ", + city: "Ort", + country: "Land", + phonePrivate: "Telefon privat", + phoneWork: "Telefon geschäftlich", + mobile: "Mobil", + fax: "Fax", + campusId: "Campus", + statusId: "Status", + departmentIds: "Bereich", +}; + +const SECTION: Record = { + sexId: "Informationen", + birthday: "Informationen", + birthplace: "Informationen", + nationalityId: "Informationen", + familyStatusId: "Informationen", + weddingDate: "Informationen", + job: "Informationen", + campusId: "Kategorie", + statusId: "Kategorie", + departmentIds: "Bereich", +}; + +const SIDES: readonly Side[] = ["original", "duplicate", "none", "both"]; + +interface Card { + id: string; + name: string; + created: string; + login: string; +} + +/** What the page needs for one direction of a pair; display strings only, already redacted. */ +export interface PairView { + key: string; + original: Card; + duplicate: Card; + groupCounts: { original: number; duplicate: number; both: number }; + fields: Array<{ + key: string; + label: string; + section: string; + original: string; + duplicate: string; + /** The union of both lists, for list fields (Bereich); empty otherwise. */ + both: string; + choice: Side; + differs: boolean; + optigem: boolean; + }>; + emails: Array<{ + index: number; + label: string; + address: string; + /** The Duplikat's contact label when it differs from the Original's (same address). */ + duplicateType: string; + inOriginal: boolean; + inDuplicate: boolean; + include: boolean; + isDefault: boolean; + }>; + groups: Array<{ + id: number; + title: string; + dynamic: boolean; + items: Array<{ + key: string; + label: string; + original: string; + duplicate: string; + choice: Side; + differs: boolean; + }>; + }>; +} + +/** The choices the page sends with a merge. Anything not named keeps the server's default. */ +export interface MergeChoices { + fields?: Record; + emails?: Array<{ index: number; include: boolean; isDefault: boolean }>; + groups?: Record>; +} + +const day = (s: string | undefined): string => (s ? s.slice(0, 10) : ""); + +export function pairView(deps: ReviewDeps, p: PairData): PairView { + const r = deps.redactor; + const show = (key: string, v: unknown): string => { + const text = formatValue(key, v, deps.labels); + return isMasterValue(key, v, deps.labels) ? text : r.value(text); + }; + const card = (x: PairData["original"]): Card => ({ + id: r.id(x.id), + name: r.name(x.firstName, x.lastName), + created: day(x.createdDate), + login: day(x.lastLogin), + }); + const gd = p.preview.groupsDiff; + return { + key: `${p.original.id}:${p.duplicate.id}`, + original: card(p.original), + duplicate: card(p.duplicate), + groupCounts: { original: gd.old.length, duplicate: gd.new.length, both: gd.both.length }, + fields: p.model.fields.map((f) => ({ + key: f.key, + label: f.optigem ? f.label : (LABEL[f.key] ?? f.label), + section: f.optigem ? "Finanzen" : (SECTION[f.key] ?? "Adresse"), + original: show(f.key, f.original), + duplicate: show(f.key, f.duplicate), + both: canMergeBoth(f.key) ? show(f.key, unionOf(f.original, f.duplicate)) : "", + choice: f.choice, + differs: differs(f), + optigem: f.optigem, + })), + emails: p.model.emails.map((e, index) => { + const t = emailTypes(e, deps.labels); + return { + index, + label: emailLabel(e, deps.labels), + address: r.value(e.address), + duplicateType: e.originalEntry && e.duplicateEntry && t.duplicate !== t.original ? t.duplicate : "", + inOriginal: e.originalEntry !== null, + inDuplicate: e.duplicateEntry !== null, + include: e.include, + isDefault: e.isDefault, + }; + }), + groups: p.shared.map((g) => ({ + id: g.id, + title: g.title, + dynamic: g.dynamic, + items: g.items.map((i) => ({ + key: i.key, + label: i.label, + original: show(i.key, i.original), + duplicate: show(i.key, i.duplicate), + choice: i.choice, + differs: itemDiffers(i), + })), + })), + }; +} + +/** Apply the page's choices to the loaded model. Unknown keys and sides are ignored. */ +export function applyChoices(p: PairData, c: MergeChoices): { model: MergeModel; shared: SharedGroup[] } { + let model = p.model; + for (const [key, side] of Object.entries(c.fields ?? {})) { + if (!SIDES.includes(side as Side) || !model.fields.some((f) => f.key === key)) continue; + model = setChoice(model, key, side as Side); + } + if (Array.isArray(c.emails)) { + const byIndex = new Map(c.emails.map((e) => [e.index, e])); + model = { + ...model, + emails: model.emails.map((e, i) => { + const ch = byIndex.get(i); + return ch ? { ...e, include: ch.include === true, isDefault: ch.isDefault === true } : e; + }), + }; + } + let shared = p.shared; + for (const [gid, items] of Object.entries(c.groups ?? {})) { + const g = shared.find((x) => String(x.id) === gid); + if (!g || g.dynamic) continue; + for (const [key, side] of Object.entries(items)) { + if ((side !== "original" && side !== "duplicate") || !g.items.some((i) => i.key === key)) continue; + shared = setItemChoice(shared, g.id, key, side); + } + } + return { model, shared }; +} + +/** Result text for the page, in German like the rest of the UI. No person data. */ +export function mergeMessages(res: MergeResult): string[] { + const http = (s: number | null): string => (s ? ` (HTTP ${s})` : ""); + if (res.kind === "merged") { + return [ + res.duplicateStillExists + ? "Zusammengeführt. ChurchTools hat das Duplikat aber nicht gelöscht; der Merge ist protokolliert." + : res.checkFailed + ? "Zusammengeführt, aber es ließ sich nicht prüfen, ob das Duplikat noch existiert." + : res.afterError + ? "Die Anfrage meldete einen Fehler, das Duplikat ist aber weg; der Merge ist protokolliert." + : "Zusammengeführt.", + ...res.warnings, + ]; + } + const done = + (res.groupsDone && res.groupsDone.length > 0 + ? ` Bereits erledigt (nicht zurückgenommen): Gruppen ${res.groupsDone.map((g) => g.groupId).join(", ")}.` + : "") + + (res.groupPatched + ? ` In Gruppe ${res.groupId ?? "?"} wurde die Mitgliedschaft des Originals schon angepasst.` + : "") + + (res.stale ? " Das Paar bitte neu laden, bevor du es erneut versuchst." : ""); + if (res.stage === "reread") + return [`Das Original ließ sich nicht neu laden${http(res.status)}. Nichts geändert.`]; + if (res.stage === "groups") + return [ + `Gruppe ${res.groupId ?? "?"} ließ sich nicht vorbereiten${http(res.status)}. Nicht zusammengeführt.${done || " Nichts geändert."}`, + ]; + const fields = + res.fields && res.fields.length > 0 ? ` ChurchTools lehnt ab: ${res.fields.join(", ")}.` : ""; + const reason = + res.reason === "error.forbidden.merge-authorized-person" + ? " ChurchTools führt keine Person zusammen, die eigene Berechtigungen hat (Login mit Rechten). Erst die Berechtigungen entfernen oder das Paar als „Keine Dublette“ markieren." + : res.reason + ? ` Grund laut ChurchTools: ${res.reason}.` + : ""; + return [ + `Zusammenführen fehlgeschlagen${http(res.status)}.${fields}${reason}${done || " Nichts geändert."}`, + ]; +} + +class HttpError extends Error { + constructor( + readonly status: number, + message: string, + ) { + super(message); + } +} + +async function readJson(req: IncomingMessage): Promise> { + const chunks: Buffer[] = []; + let size = 0; + for await (const chunk of req) { + size += (chunk as Buffer).length; + if (size > 256 * 1024) throw new HttpError(413, "too large"); + chunks.push(chunk as Buffer); + } + try { + const v: unknown = JSON.parse(Buffer.concat(chunks).toString("utf8") || "{}"); + if (v && typeof v === "object" && !Array.isArray(v)) return v as Record; + } catch { + /* fallthrough */ + } + throw new HttpError(400, "bad json"); +} + +export interface ReviewServer { + /** The address to open, with the token in the fragment. */ + url: string; + /** Resolves when the page says it is done or `close()` is called. */ + closed: Promise; + close(): void; +} + +export async function startReviewServer( + deps: ReviewDeps, + scan: ScanFile, + names: Map, + opts: { port?: number } = {}, +): Promise { + const token = randomBytes(24).toString("base64url"); + const tokenBuf = Buffer.from(token); + const r = deps.redactor; + const pairs = new Map(); + let busy = false; + let host = ""; + + const candidate = (i: unknown): StoredCandidate => { + const c = typeof i === "number" ? scan.candidates[i] : undefined; + if (!c) throw new HttpError(404, "no such pair"); + return c; + }; + /** The older person (lower id) is the Original unless the page swapped the pair. */ + const direction = (c: StoredCandidate, swapped: unknown): [number, number] => { + const lo = Math.min(c.a, c.b); + const hi = Math.max(c.a, c.b); + return swapped === true ? [hi, lo] : [lo, hi]; + }; + const summary = (id: number): Card => { + const n = names.get(id); + return { + id: r.id(id), + name: n ? r.name(n.first, n.last) : "", + created: day(n?.created), + login: day(n?.login), + }; + }; + const listView = (): unknown => ({ + host: deps.host, + operator: deps.operator.name, + redacted: r.enabled, + candidates: scan.candidates.map((c, i) => { + const [o, d] = direction(c, false); + return { + index: i, + tier: c.tier, + score: c.score, + matchClass: c.matchClass, + source: c.source, + state: c.state, + original: summary(o), + duplicate: summary(d), + }; + }), + }); + + async function api(method: string, path: string, body: Record): Promise { + if (method === "GET" && path === "/api/list") return listView(); + if (method === "POST" && path === "/api/pair") { + const c = candidate(body.index); + const [o, d] = direction(c, body.swapped); + try { + const p = await loadPair(deps, o, d); + pairs.set(`${o}:${d}`, p); + return { pair: pairView(deps, p) }; + } catch (err) { + if (err instanceof PairLoadError && err.personGone) { + // recoverUnrecordedMerge re-checks from the audit: the recorded loser 404s and the survivor loads. + if (await recoverUnrecordedMerge(deps, c.a, c.b)) { + c.state = "merged"; + deps.store.saveScan(scan); + return { + gone: true, + message: "Ein früherer Merge dieses Paars war nicht protokolliert; jetzt nachgetragen.", + }; + } + return { gone: true, message: "Eine der beiden Personen existiert nicht mehr." }; + } + throw new HttpError( + 502, + err instanceof PairLoadError + ? `Paar ließ sich nicht laden (${err.describe()}).` + : `Paar ließ sich nicht laden${err instanceof CtApiError ? ` (HTTP ${err.status})` : ""}.`, + ); + } + } + if (method === "POST" && path === "/api/merge") { + const c = candidate(body.index); + if (c.state !== "open") throw new HttpError(409, "Dieses Paar ist schon entschieden."); + const [o, d] = direction(c, body.swapped); + const p = pairs.get(`${o}:${d}`); + if (!p) throw new HttpError(409, "Paar zuerst laden."); + const { model, shared } = applyChoices(p, (body.choices ?? {}) as MergeChoices); + const res = await executeMerge(deps, p, model, shared); + if (res.kind === "merged") { + c.state = "merged"; + deps.store.saveScan(scan); + pairs.delete(`${o}:${d}`); + } else if (res.fresh) { + pairs.set(`${o}:${d}`, res.fresh); // group steps went through: retry against reality + } else if (res.stale) { + pairs.delete(`${o}:${d}`); + } + return { + ok: res.kind === "merged", + // Group steps already went through: the dialog must show the pair as it is now. + reload: res.kind !== "merged" && Boolean(res.fresh || res.stale), + messages: mergeMessages(res), + optigem: optigemOutcome(model), + }; + } + if (method === "POST" && path === "/api/dismiss") { + const c = candidate(body.index); + if (c.state !== "open") throw new HttpError(409, "Dieses Paar ist schon entschieden."); + const res = await markNotDuplicate(deps, c.a, c.b); + c.state = "dismissed"; + deps.store.saveScan(scan); + return { + ok: true, + messages: [ + res.ok + ? 'In ChurchTools als "Keine Dublette" markiert.' + : `Lokal gespeichert, aber ChurchTools hat das Zurückschreiben abgelehnt${res.status ? ` (HTTP ${res.status})` : ""}.`, + ], + }; + } + if (method === "POST" && path === "/api/finance-export") { + // The one deliberate real-data output; pseudonyms would make it useless to finance. + if (r.enabled) + throw new HttpError(409, "Mit --redact nicht verfügbar. Bitte ct dupes export-finance verwenden."); + const merges = financeMerges(deps.store.readAudit()); + return { + count: merges.length, + filename: `optigem-merges-${new Date().toISOString().slice(0, 10)}.csv`, + csv: toCsv(merges), + }; + } + if (method === "POST" && path === "/api/quit") { + setImmediate(close); + return { ok: true }; + } + throw new HttpError(404, "not found"); + } + + const send = (res: ServerResponse, status: number, type: string, body: string): void => { + res.writeHead(status, { + "Content-Type": type, + "Cache-Control": "no-store", + "X-Content-Type-Options": "nosniff", + "Referrer-Policy": "no-referrer", + "X-Frame-Options": "DENY", + "Content-Security-Policy": + "default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'", + }); + res.end(body); + }; + + const server: Server = createServer((req, res) => { + void (async () => { + if (req.headers.host !== host) return send(res, 421, "text/plain", "wrong host"); + const path = (req.url ?? "/").split("?")[0]!; + if (req.method === "GET" && path === "/") return send(res, 200, "text/html; charset=utf-8", PAGE_HTML); + if (!path.startsWith("/api/")) return send(res, 404, "text/plain", "not found"); + const given = Buffer.from(String(req.headers["x-ct-dupes-token"] ?? "")); + if (given.length !== tokenBuf.length || !timingSafeEqual(given, tokenBuf)) + return send(res, 403, "text/plain", "forbidden"); + const method = req.method ?? "GET"; + const write = method === "POST"; + if (write && busy) + return send(res, 409, "application/json", JSON.stringify({ error: "Eine Aktion läuft noch." })); + if (write) busy = true; + try { + const body = write ? await readJson(req) : {}; + const out = await api(method, path, body); + send(res, 200, "application/json", JSON.stringify(out)); + } catch (err) { + const status = err instanceof HttpError ? err.status : 500; + const msg = err instanceof HttpError ? err.message : "Interner Fehler."; + send(res, status, "application/json", JSON.stringify({ error: msg })); + } finally { + if (write) busy = false; + } + })(); + }); + + let resolveClosed!: () => void; + const closed = new Promise((res) => (resolveClosed = res)); + function close(): void { + server.close(() => resolveClosed()); + server.closeAllConnections(); + } + + await new Promise((resolve, reject) => { + server.once("error", reject); + server.listen(opts.port ?? 0, "127.0.0.1", () => resolve()); + }); + const { port } = server.address() as AddressInfo; + host = `127.0.0.1:${port}`; + return { url: `http://${host}/#${token}`, closed, close }; +} diff --git a/src/index.ts b/src/index.ts index e046cc8..51f8933 100644 --- a/src/index.ts +++ b/src/index.ts @@ -13,6 +13,7 @@ import { refreshCommand } from "./commands/refresh.js"; import { planCommand } from "./commands/plan.js"; import { applyCommand } from "./commands/apply.js"; import { destroyCommand } from "./commands/destroy.js"; +import { dupesCommand } from "./commands/dupes.js"; import { gatewayCommand } from "./commands/gateway.js"; import { initCommand } from "./commands/init.js"; import { completionCommand } from "./commands/completion.js"; @@ -28,7 +29,8 @@ export function buildProgram(): Command { .name("ct") .description( "ChurchTools structure-as-code CLI — declarative plan/apply for the overarching, " + - "rights-bearing structure. Never manages people.", + "rights-bearing structure. Structure commands never touch people; `ct dupes` does, " + + "explicitly and only interactively.", ) .version(versionLine(import.meta.url)); @@ -47,6 +49,7 @@ export function buildProgram(): Command { program.addCommand(planCommand()); program.addCommand(applyCommand()); program.addCommand(destroyCommand()); + program.addCommand(dupesCommand()); program.addCommand(completionCommand()); for (const cmd of plannedCommands()) { program.addCommand(cmd); diff --git a/tests/dupes-actions.test.ts b/tests/dupes-actions.test.ts new file mode 100644 index 0000000..c7e9fc7 --- /dev/null +++ b/tests/dupes-actions.test.ts @@ -0,0 +1,237 @@ +import { afterEach, describe, expect, it } from "vitest"; +import { + executeMerge, + loadPair, + markNotDuplicate, + recoverUnrecordedMerge, + type ReviewDeps, +} from "../src/dupes/actions.js"; +import { financeMerges } from "../src/dupes/finance.js"; +import { setChoice } from "../src/dupes/merge-model.js"; +import { cleanDirs, fakeClient, patches, raw, setup, type Call } from "./dupes-fixtures.js"; + +afterEach(cleanDirs); + +describe("merge actions", () => { + it("PATCHes the Original's object with chosen duplicate values; system keys stay", async () => { + const t = setup(); + const pair = await loadPair(t.deps, 1, 2); + expect(pair.model.fields.map((f) => f.key)).not.toContain("guid"); + const model = setChoice(pair.model, "lastName", "duplicate"); + const res = await executeMerge(t.deps, pair, model); + expect(res).toMatchObject({ kind: "merged", duplicateStillExists: false }); + const [p] = patches(t.calls); + expect(p!.path).toBe("/persons/1/merge/2"); + expect(p!.body).toMatchObject({ guid: "guid-1", lastName: "Beispiel", mobile: "0151" }); + expect(p!.body).not.toHaveProperty("null"); + const audit = t.store.readAudit(); + expect(audit.map((e) => e.action)).toEqual(["merge-started", "merge-confirmed"]); + expect(audit[0]).toMatchObject({ groupsDiff: { original: [10], duplicate: [11, 12], both: [] } }); + }); + + it("merges in the swapped direction", async () => { + const t = setup(); + const pair = await loadPair(t.deps, 2, 1); + await executeMerge(t.deps, pair, pair.model); + expect(patches(t.calls)[0]!.path).toBe("/persons/2/merge/1"); + expect(t.store.readAudit().at(-1)).toMatchObject({ survivingId: 2, loserId: 1 }); + }); + + it("records the merge with a flag when ChurchTools kept the duplicate", async () => { + const t = setup({ stays: true }); + const pair = await loadPair(t.deps, 1, 2); + const res = await executeMerge(t.deps, pair, pair.model); + expect(res).toMatchObject({ kind: "merged", duplicateStillExists: true }); + expect(t.store.readAudit().at(-1)).toMatchObject({ duplicateStillExists: true }); + expect(t.calls.filter((c) => c.method === "DELETE")).toEqual([]); + }); + + it("returns failed with only the HTTP status on PATCH 500, no merge-confirmed", async () => { + const t = setup({ patchFails: true }); + const pair = await loadPair(t.deps, 1, 2); + const res = await executeMerge(t.deps, pair, pair.model); + expect(res).toEqual({ kind: "failed", status: 500, stage: "patch", fields: [], groupsDone: [] }); + expect(t.store.readAudit().map((e) => e.action)).toEqual(["merge-started", "merge-error"]); + }); + + it("records the merge when the PATCH errors but the duplicate is gone", async () => { + const t = setup({ patchFails: true, goneAfterError: true }); + const pair = await loadPair(t.deps, 1, 2); + const res = await executeMerge(t.deps, pair, pair.model); + expect(res).toMatchObject({ kind: "merged", afterError: true }); + expect(t.store.readAudit().at(-1)).toMatchObject({ action: "merge-confirmed", afterError: true }); + }); + + it("recovers an unrecorded merge once the duplicate is gone", async () => { + const t = setup({ patchFails: true }); + const pair = await loadPair(t.deps, 1, 2); + await executeMerge(t.deps, pair, pair.model); + expect(await recoverUnrecordedMerge(t.deps, 1, 2)).toBe(false); + const later: ReviewDeps = { ...t.deps, client: fakeClient([], { gone: [2] }) }; + expect(await recoverUnrecordedMerge(later, 1, 2)).toBe(true); + expect(t.store.readAudit().at(-1)).toMatchObject({ action: "merge-confirmed", recovered: true }); + expect(await recoverUnrecordedMerge(later, 1, 2)).toBe(false); + }); + + it("feeds the finance export from the Optigem choice, not for a lone ID", async () => { + const persons = { + 1: raw(1, { optigemId: "10001" }), + 2: raw(2, { optigemId: "10002" }), + }; + const t = setup({ persons }); + const pair = await loadPair(t.deps, 1, 2); + await executeMerge(t.deps, pair, setChoice(pair.model, "optigemId", "duplicate")); + expect(patches(t.calls)[0]!.body).toMatchObject({ optigemId: "10002" }); + expect(financeMerges(t.store.readAudit())).toMatchObject([ + { + survivingPersonId: 1, + survivingPersonOptigemId: "10001", + mergedPersonId: 2, + mergedPersonOptigemId: "10002", + leadingOptigemId: "10002", + orphanedOptigemId: "10001", + }, + ]); + expect(financeMerges(t.store.readAudit())[0]!.survivingPersonName).not.toBe(""); + const lone = setup({ persons: { 1: raw(1), 2: raw(2, { optigemId: "7" }) } }); + const p2 = await loadPair(lone.deps, 1, 2); + await executeMerge(lone.deps, p2, p2.model); + expect(patches(lone.calls)[0]!.body).toMatchObject({ optigemId: "7" }); + expect(lone.store.readAudit().at(-1)).toMatchObject({ leadingOptigemId: "7", orphanedOptigemId: "" }); + expect(financeMerges(lone.store.readAudit())).toEqual([]); + }); + + it("re-reads the original right before writing", async () => { + const calls: Call[] = []; + const t = setup(); + const pair = await loadPair(t.deps, 1, 2); + const fresh = raw(1, { job: "edited meanwhile" }); + const deps: ReviewDeps = { ...t.deps, client: fakeClient(calls, { persons: { 1: fresh, 2: raw(2) } }) }; + await executeMerge(deps, pair, pair.model); + expect(patches(calls)[0]!.body).toMatchObject({ job: "edited meanwhile" }); + }); + + it("marks 'keine Dublette' and writes the relationship back", async () => { + const t = setup(); + expect(await markNotDuplicate(t.deps, 1, 2)).toEqual({ ok: true, status: null }); + expect(t.calls).toEqual([ + { method: "POST", path: "/persons/1/relationships", body: { otherPersonId: 2, relationshipTypeId: 4 } }, + ]); + }); +}); + +describe("rejectedFields", () => { + it("returns only well-formed field ids from a ChurchTools validation error, never messages or args", async () => { + const { rejectedFields } = await import("../src/dupes/actions.js"); + const { CtApiError } = await import("../src/api/ctClient.js"); + const err = new CtApiError("bad", 400, { + message: "Validation failed", + errors: [ + { fieldId: "emails[0].contactLabelId", message: "x", args: { value: "secret@example.org" } }, + { fieldId: "birthday", message: "y" }, + { fieldId: "birthday" }, + { fieldId: "not a key; secret@example.org" }, + { message: "no field" }, + ], + }); + expect(rejectedFields(err)).toEqual(["emails[0].contactLabelId", "birthday"]); + expect(rejectedFields(new Error("x"))).toEqual([]); + expect(rejectedFields(new CtApiError("x", 400, null))).toEqual([]); + }); + + it("passes on ChurchTools' message key for a refusal, never the message", async () => { + const { errorKey } = await import("../src/dupes/actions.js"); + const { CtApiError } = await import("../src/api/ctClient.js"); + const err = new CtApiError("x", 403, { + message: "secret@example.org", + translatedMessage: "secret@example.org", + messageKey: "error.merge.example", + }); + expect(errorKey(err)).toBe("error.merge.example"); + expect(errorKey(new CtApiError("x", 403, { translationKey: "error.old" }))).toBe("error.old"); + expect( + errorKey(new CtApiError("x", 403, { translationKey: "has spaces secret@example.org" })), + ).toBeUndefined(); + expect(errorKey(new Error("x"))).toBeUndefined(); + }); +}); + +describe("shared groups", () => { + const memberships = { + "13:1": { + groupTypeRoleId: 1, + groupMemberStatus: "active", + memberStartDate: "2024-01-01", + comment: null, + fields: [ + { id: 5, name: "Paid", value: true }, + { id: 6, name: "Team", value: null }, + ], + }, + "13:2": { + groupTypeRoleId: 2, + groupMemberStatus: "active", + memberStartDate: "2015-03-01", + comment: "seit Gründung", + fields: [ + { id: 5, name: "Paid", value: false }, + { id: 6, name: "Team", value: "Beta" }, + ], + }, + }; + const both = [ + { id: 13, title: "Hauskreis" }, + { id: 14, title: "Auto" }, + ]; + + it("defaults: earlier join date and empty values from the Duplikat, conflicts stay with the Original", async () => { + const t = setup({ both, dynamicGroupIds: [14], memberships }); + const pair = await loadPair(t.deps, 1, 2); + const [st, dy] = pair.shared; + expect(dy).toMatchObject({ id: 14, dynamic: true, items: [] }); + const choice = Object.fromEntries(st!.items.map((i) => [i.key, i.choice])); + expect(choice).toEqual({ + groupTypeRoleId: "original", + groupMemberStatus: "original", + memberStartDate: "duplicate", + comment: "duplicate", + "field:5": "original", + "field:6": "duplicate", + }); + }); + + it("updates the Original's membership, removes the Duplikat from every shared group, then merges", async () => { + const t = setup({ both, dynamicGroupIds: [14], memberships }); + const pair = await loadPair(t.deps, 1, 2); + const res = await executeMerge(t.deps, pair, pair.model); + expect(res).toMatchObject({ kind: "merged" }); + const writes = t.calls.map((c) => `${c.method} ${c.path}`); + expect(writes).toEqual([ + "PATCH /groups/13/members/1", + "DELETE /groups/13/members/2", + "DELETE /groups/14/members/2", + "PATCH /persons/1/merge/2", + ]); + expect(t.calls[0]!.body).toEqual({ + memberStartDate: "2015-03-01", + comment: "seit Gründung", + fields: { "6": "Beta" }, + }); + const prepared = t.store.readAudit().find((e) => e.action === "groups-prepared"); + expect(prepared).toMatchObject({ + groupsDone: [ + { groupId: 13, dynamic: false, updated: ["memberStartDate", "comment", "field:6"] }, + { groupId: 14, dynamic: true, updated: [] }, + ], + }); + }); + + it("stops before the merge when a group step fails", async () => { + const t = setup({ both, dynamicGroupIds: [14], memberships, groupWriteFails: 403 }); + const pair = await loadPair(t.deps, 1, 2); + const res = await executeMerge(t.deps, pair, pair.model); + expect(res).toMatchObject({ kind: "failed", stage: "groups", status: 403, groupId: 13, groupsDone: [] }); + expect(t.calls.some((c) => c.path.includes("/merge/"))).toBe(false); + expect(t.store.readAudit().some((e) => e.action === "merge-confirmed")).toBe(false); + }); +}); diff --git a/tests/dupes-data.test.ts b/tests/dupes-data.test.ts new file mode 100644 index 0000000..db36c8c --- /dev/null +++ b/tests/dupes-data.test.ts @@ -0,0 +1,148 @@ +import { describe, expect, it } from "vitest"; +import { buildCandidates, loadRelationState, toPersonRecord, type DupesClient } from "../src/dupes/ct.js"; +import { FINANCE_SCHEMA, buildFinanceExport, financeMerges, toCsv } from "../src/dupes/finance.js"; + +const rec = (id: number, first: string, last: string, extra: Record = {}) => + toPersonRecord({ id, firstName: first, lastName: last, birthday: "1990-05-05", ...extra }, "optigemId"); + +function fakeClient(rels: unknown[], groups: unknown[]): DupesClient { + return { + get: async (path: string) => + path === "/person/masterdata" + ? { + relationshipTypes: [ + { id: 61, functionKeys: ["noduplicate"] }, + { id: 91, functionKeys: ["openduplicate"] }, + ], + } + : groups, + getAll: async () => ({ data: rels }), + request: async () => ({}), + } as unknown as DupesClient; +} + +describe("relation state and candidates", () => { + it("resolves relationship type ids by function key", async () => { + const st = await loadRelationState(fakeClient([], [])); + expect(st.types).toEqual({ noDuplicate: 61, duplicate: 91 }); + }); + + it("suppresses pairs with a non-duplicate relationship", async () => { + const st = await loadRelationState( + fakeClient([{ personAId: 1, personBId: 2, relationshipTypeId: 61 }], []), + ); + const out = buildCandidates([rec(1, "Erika", "Muster"), rec(2, "Erika", "Muster")], st); + expect(out).toEqual([]); + }); + + it("keeps a pair tagged as open duplicate and flags it", async () => { + const st = await loadRelationState( + fakeClient([{ personAId: 1, personBId: 2, relationshipTypeId: 91 }], []), + ); + const out = buildCandidates([rec(1, "Erika", "Muster"), rec(2, "Erika", "Muster")], st); + expect(out).toHaveLength(1); + expect(out[0]).toMatchObject({ source: "both", markedDuplicate: true }); + }); + + it("adds CT-only suggestions and drops unknown persons", async () => { + const groups = [ + { + relationshipTypeId: null, + relationships: [ + { p1: { id: 1 }, p2: { id: 2 } }, + { p1: { id: 1 }, p2: { id: 99 } }, + ], + }, + ]; + const st = await loadRelationState(fakeClient([], groups)); + const out = buildCandidates([rec(1, "Anna", "Beispiel"), rec(2, "Berta", "Zufall")], st); + expect(out).toHaveLength(1); + expect(out[0]).toMatchObject({ source: "ct", matchClass: "ct" }); + expect(out[0]!.score).toBeGreaterThanOrEqual(35); + }); +}); + +describe("finance export", () => { + const audit = [ + { + action: "merge-confirmed", + ts: "2026-02-01T10:00:00.000Z", + survivingId: 5, + loserId: 9, + survivingName: "Erika Muster", + loserName: "Erika Beispiel", + survivingOptigemId: "10002", + loserOptigemId: "10001", + leadingOptigemId: "10001", + orphanedOptigemId: "10002", + mergedBy: "Erika Muster", + }, + { + action: "merge-confirmed", + ts: "2026-02-02T10:00:00.000Z", + survivingId: 6, + leadingOptigemId: "10003", + orphanedOptigemId: "", + }, + { + action: "merge-confirmed", + ts: "2026-03-01T10:00:00.000Z", + survivingId: 7, + leadingOptigemId: "10005", + orphanedOptigemId: "10005", + mergedBy: "=cmd", + }, + { + action: "merge-started", + ts: "2026-03-01T10:00:00.000Z", + survivingId: 8, + leadingOptigemId: "1", + orphanedOptigemId: "2", + }, + ]; + + it("keeps only confirmed merges with both ids", () => { + const m = financeMerges(audit); + expect(m.map((x) => x.survivingPersonId)).toEqual([5, 7]); + expect(m[1]!.identicalIds).toBe(true); + }); + + it("filters by --since", () => { + expect(financeMerges(audit, "2026-02-15").map((x) => x.survivingPersonId)).toEqual([7]); + }); + + it("writes a stable CSV and neutralises formulas", () => { + const csv = toCsv(financeMerges(audit)).split("\n"); + expect(csv[0]).toBe( + "surviving_person_id,surviving_person_name,surviving_person_optigem_id,merged_person_id,merged_person_name,merged_person_optigem_id,leading_optigem_id,orphaned_optigem_id,identical_ids,merged_at,merged_by", + ); + expect(csv[1]).toBe( + "5,Erika Muster,10002,9,Erika Beispiel,10001,10001,10002,false,2026-02-01T10:00:00.000Z,Erika Muster", + ); + // A line logged before names were recorded leaves those cells empty. + expect(csv[2]).toBe("7,,,,,,10005,10005,true,2026-03-01T10:00:00.000Z,'=cmd"); + }); + + it("builds the documented JSON envelope", () => { + const j = buildFinanceExport( + financeMerges(audit), + "https://example.church.tools", + undefined, + new Date("2026-04-01T00:00:00Z"), + ); + expect(j).toMatchObject({ schema: FINANCE_SCHEMA, since: null, host: "https://example.church.tools" }); + expect(Object.keys(j.merges[0]!)).toEqual([ + "survivingPersonId", + "survivingPersonName", + "survivingPersonOptigemId", + "mergedPersonId", + "mergedPersonName", + "mergedPersonOptigemId", + "leadingOptigemId", + "orphanedOptigemId", + "identicalIds", + "mergedAt", + "mergedBy", + ]); + }); +}); diff --git a/tests/dupes-detector.test.ts b/tests/dupes-detector.test.ts new file mode 100644 index 0000000..624aed6 --- /dev/null +++ b/tests/dupes-detector.test.ts @@ -0,0 +1,117 @@ +import { describe, expect, it } from "vitest"; +import { detect, pairKey, type DupePerson } from "../src/dupes/detector.js"; +import { cleanName, normalizePhone } from "../src/dupes/normalize.js"; + +let nextId = 1; +function p(first: string, last: string, extra: Partial = {}): DupePerson { + return { id: nextId++, firstName: first, lastName: last, birthday: "1990-05-05", ...extra }; +} + +/** Detect over exactly two persons and return the single candidate (or undefined). */ +function pairResult(a: DupePerson, b: DupePerson) { + return detect([a, b])[0]; +} + +describe("normalisation", () => { + it("expands umlauts, strips accents, keeps digits", () => { + expect(cleanName("Jürgen Müßig 2")).toBe("juergen muessig 2"); + expect(cleanName("Kids1")).toBe("kids1"); + expect(cleanName("José (Pepe)")).toBe("jose pepe"); + }); + it("normalises phone numbers across country prefixes", () => { + expect(normalizePhone("+49 151 2345678")).toBe(normalizePhone("0151/2345678")); + expect(normalizePhone("123")).toBeNull(); + }); +}); + +describe("match classes", () => { + it.each([ + ["exact", p("Erika", "Muster"), p("Erika", "Muster")], + ["middlename", p("Anna Marie", "Muster"), p("Anna", "Muster")], + ["fuzzy", p("Naomi", "Muster"), p("Nomi", "Muster")], + ["shortform", p("Christine", "Muster"), p("Tine", "Muster")], + ["shortform", p("Christoph", "Muster Beispiel"), p("Chris", "Beispiel")], + ["shortform", p("Seung Hun (Isaak)", "Muster"), p("Seunghun", "Muster")], + ["nameswap", p("Erika", "Muster"), p("Muster", "Erika")], + ["diminutive", p("Ursula", "Muster"), p("Ursi", "Muster")], + ["diminutive", p("Gabriele", "Muster"), p("Gabi", "Muster")], + ["diminutive", p("Peny", "Muster"), p("Penial", "Muster")], + ["firsttoken", p("Maria Luise", "Muster"), p("Maria Anna", "Muster")], + ])("classifies %s", (cls, a, b) => { + const c = pairResult(a, b); + expect(c?.matchClass).toBe(cls); + expect(c?.source).toBe("detector"); + }); + + it("treats a nickname equal to the other first name as exact evidence", () => { + const c = pairResult(p("Katharina", "Muster", { nickname: "Kathi" }), p("Kathi", "Muster")); + expect(c?.matchClass).toBe("exact"); + expect(c?.signals).toContain("name:nickname"); + }); + + it("does not match different digits in names (Kids1 vs Kids2 style)", () => { + expect(pairResult(p("Gruppe1", "Muster"), p("Gruppe2", "Muster"))).toBeUndefined(); + }); + + it("scores unique email and phone above name-only evidence", () => { + const a = p("Erika", "Muster", { email: "e@example.invalid", mobile: "0151 2345678" }); + const b = p("Erika", "Muster", { email: "e@example.invalid", mobile: "+49 151 2345678" }); + const c = pairResult(a, b)!; + expect(c.tier).toBe("T1"); + expect(c.signals).toEqual(expect.arrayContaining(["email-unique", "phone-unique"])); + }); +}); + +describe("vetoes", () => { + it("rejects a sex conflict, which also stops Andreas / Andrea", () => { + const a = p("Andreas", "Muster", { sexId: 1 }); + const b = p("Andrea", "Muster", { sexId: 2 }); + expect(pairResult(a, b)).toBeUndefined(); + }); + + it("does not treat an unset sex id (0 or null) as a value", () => { + const a = p("Erika", "Muster", { sexId: 0 }); + const b = p("Erika", "Muster", { sexId: 2 }); + expect(pairResult(a, b)).toBeDefined(); + }); + + it("rejects conflicting birthdays", () => { + expect( + pairResult(p("Erika", "Muster"), p("Erika", "Muster", { birthday: "1991-05-05" })), + ).toBeUndefined(); + }); + + it("rejects placeholder names and clusters of identical names", () => { + expect(pairResult(p("Gast", "Muster"), p("Gast", "Muster"))).toBeUndefined(); + const cluster = Array.from({ length: 4 }, () => p("Testgruppe", "Ort 1")); + expect(detect(cluster)).toEqual([]); + }); + + it("rejects pairs with a suppressing relationship", () => { + const a = p("Erika", "Muster"); + const b = p("Erika", "Muster"); + expect(detect([a, b], { suppressed: new Set([pairKey(a.id, b.id)]) })).toEqual([]); + expect(detect([a, b])).toHaveLength(1); + }); +}); + +describe("blocking and tiers", () => { + it("finds pairs through a shared surname block only when scored >= 35", () => { + const weak = pairResult( + p("Erika", "Muster", { birthday: null }), + p("Hans", "Muster", { birthday: null }), + ); + expect(weak).toBeUndefined(); + }); + + it("sorts best first and puts the smaller id in `a`", () => { + const list = detect([ + p("Erika", "Muster"), + p("Erika", "Muster"), + p("Anna Marie", "Beispiel"), + p("Anna", "Beispiel"), + ]); + expect(list[0]!.score).toBeGreaterThanOrEqual(list[1]!.score); + for (const c of list) expect(c.a).toBeLessThan(c.b); + }); +}); diff --git a/tests/dupes-fixtures.ts b/tests/dupes-fixtures.ts new file mode 100644 index 0000000..d42eab3 --- /dev/null +++ b/tests/dupes-fixtures.ts @@ -0,0 +1,196 @@ +/** Shared fictitious fixtures for the `ct dupes` review tests. */ +import { mkdtempSync, rmSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { CtApiError } from "../src/api/ctClient.js"; +import type { ReviewDeps } from "../src/dupes/actions.js"; +import type { DupesClient } from "../src/dupes/ct.js"; +import { makeRedactor } from "../src/dupes/redact.js"; +import { DupesStore, SCAN_SCHEMA, type ScanFile } from "../src/dupes/store.js"; + +export const dirs: string[] = []; +export function cleanDirs(): void { + for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }); +} + +export const raw = (id: number, over: Record = {}): Record => ({ + id, + guid: `guid-${id}`, + firstName: "Erika", + lastName: "Muster", + birthday: "1990-05-05", + optigemId: "", + emails: [{ id: id * 10, email: `p${id}@example.org`, isDefault: true }], + campusId: 0, + statusId: 0, + meta: { createdDate: `2020-01-0${id}T00:00:00Z` }, + lastLogin: null, + ...over, +}); + +export interface Call { + method: string; + path: string; + body?: unknown; +} + +export interface FakeOpts { + persons?: Record>; + patchFails?: boolean; + stays?: boolean; + personDiff?: unknown[]; + previewFails?: boolean; + goneAfterError?: boolean; + /** Ids that answer 404 from the start. */ + gone?: number[]; + /** Shared groups of the preview (default: none). */ + both?: Array<{ id: number; title?: string }>; + dynamicGroupIds?: number[]; + /** Memberships by `${groupId}:${personId}`. */ + memberships?: Record>; + /** Group member writes that fail with this status. */ + groupWriteFails?: number; +} + +export interface FakeState { + merged: Set; +} + +/** Fake ChurchTools for persons 1 and 2 (and optionally more). */ +export function fakeClient( + calls: Call[], + opts: FakeOpts = {}, + state: FakeState = { merged: new Set() }, +): DupesClient { + const persons: Record> = opts.persons ?? { + 1: raw(1), + 2: raw(2, { lastName: "Beispiel", mobile: "0151" }), + }; + return { + get: async (path: string) => { + const m = /^\/persons\/(\d+)$/.exec(path); + if (m) { + const id = Number(m[1]); + if (opts.gone?.includes(id) || state.merged.has(id)) { + if (!(opts.stays && state.merged.has(id))) throw new CtApiError("gone", 404, {}); + } + return persons[id]; + } + if (/^\/persons\/(\d+)\/merge\/(\d+)$/.test(path)) { + if (opts.previewFails) throw new CtApiError("nope", 500, {}); + return { + personDiff: opts.personDiff ?? [ + { key: "lastName", name: "Nachname", old: "Muster", new: "Beispiel", printDiff: true }, + { key: "guid", name: "GUID", old: "guid-1", new: "guid-2", printDiff: false }, + { key: null, name: "Something", old: "x", new: "y", printDiff: true }, + ], + groupsDiff: { + // ChurchTools sends `both` as group ids; the groups themselves are in old/new. + old: [{ id: 10 }, ...(opts.both ?? [])], + new: [{ id: 11 }, { id: 12 }, ...(opts.both ?? [])], + both: (opts.both ?? []).map((g) => g.id), + }, + }; + } + if (path === "/person/masterdata") { + return { + campuses: [{ id: 0, name: "Hauptcampus" }], + statuses: [{ id: 0, name: "Mitglied" }], + sexes: [], + }; + } + if (/^\/persons\/\d+\/relationships$/.test(path)) return []; + const gm = /^\/groups\/(\d+)\/members\/(\d+)$/.exec(path); + if (gm) { + return ( + opts.memberships?.[`${gm[1]}:${gm[2]}`] ?? { + groupTypeRoleId: 1, + groupMemberStatus: "active", + memberStartDate: "2024-01-01", + fields: [], + } + ); + } + throw new Error(`unexpected GET ${path}`); + }, + getAll: async (path: string) => { + if (path === "/dynamicgroups") + return { data: (opts.dynamicGroupIds ?? []).map((id) => ({ groupId: id })) }; + if (path === "/persons") { + return { + data: Object.values(persons).map((p) => ({ + id: p.id, + firstName: p.firstName, + lastName: p.lastName, + })), + }; + } + throw new Error(`unexpected getAll ${path}`); + }, + request: async (method: string, path: string, body?: unknown) => { + calls.push({ method, path, body }); + if (opts.groupWriteFails && /^\/groups\/\d+\/members\/\d+$/.test(path)) { + throw new CtApiError("group", opts.groupWriteFails, {}); + } + const m = /^\/persons\/(\d+)\/merge\/(\d+)$/.exec(path); + if (method === "PATCH" && m) { + if (opts.patchFails) { + if (opts.goneAfterError) state.merged.add(Number(m[2])); + throw new CtApiError("boom", 500, {}); + } + state.merged.add(Number(m[2])); + } + return {}; + }, + } as unknown as DupesClient; +} + +export function setup(opts: FakeOpts = {}, redact = false) { + const base = mkdtempSync(join(tmpdir(), "ct-dupes-review-")); + dirs.push(base); + const store = new DupesStore("https://example.church.tools", { CT_DUPES_DIR: base }); + const scan: ScanFile = { + schema: SCAN_SCHEMA, + host: "https://example.church.tools", + scannedAt: "2026-01-01T00:00:00.000Z", + personsScanned: 2, + candidates: [ + { + a: 1, + b: 2, + score: 90, + tier: "T1", + matchClass: "exact", + signals: [], + source: "detector", + state: "open", + }, + { + a: 3, + b: 4, + score: 50, + tier: "T3", + matchClass: "fuzzy", + signals: [], + source: "detector", + state: "open", + }, + ], + }; + const calls: Call[] = []; + const state: FakeState = { merged: new Set() }; + const deps: ReviewDeps = { + client: fakeClient(calls, opts, state), + store, + host: "https://example.church.tools", + redactor: makeRedactor(redact, "secret"), + optigemField: "optigemId", + types: { noDuplicate: 4, duplicate: 7 }, + operator: { id: 99, name: "Op Erator" }, + labels: { campusId: new Map([[0, "Hauptcampus"]]), statusId: new Map([[0, "Mitglied"]]) }, + now: () => new Date("2026-02-01T10:00:00.000Z"), + }; + return { deps, scan, store, calls, state }; +} + +export const patches = (calls: Call[]): Call[] => calls.filter((c) => c.method === "PATCH"); diff --git a/tests/dupes-guard-store.test.ts b/tests/dupes-guard-store.test.ts new file mode 100644 index 0000000..f758cdd --- /dev/null +++ b/tests/dupes-guard-store.test.ts @@ -0,0 +1,219 @@ +import { chmodSync, mkdirSync, mkdtempSync, rmSync, statSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import { afterEach, describe, expect, it } from "vitest"; +import { safeErrorText } from "../src/commands/dupes.js"; +import { CtApiError } from "../src/api/ctClient.js"; +import { + agentMarkers, + assertHumanSession, + isAgentProcess, + needsGuard, + type GuardInput, +} from "../src/dupes/guard.js"; +import { makeRedactor } from "../src/dupes/redact.js"; +import { DupesStore, hostSlug, writePrivateFiles } from "../src/dupes/store.js"; + +const prod = { protected: true } as const; +const dev = { protected: false } as const; +const human = (over: Partial = {}): GuardInput => ({ + profile: prod, + stdinIsTTY: true, + stdoutIsTTY: true, + env: {}, + ancestors: () => ["zsh", "login"], + ...over, +}); + +describe("personal-data guard", () => { + it("lets a human at a terminal through", () => { + expect(() => assertHumanSession(human())).not.toThrow(); + }); + + it.each([ + ["stdin is not a TTY", { stdinIsTTY: false }], + ["stdout is not a TTY", { stdoutIsTTY: false }], + ["CLAUDECODE is set", { env: { CLAUDECODE: "1" } }], + ["a CLAUDE_CODE_ variable is set", { env: { CLAUDE_CODE_ENTRYPOINT: "cli" } }], + ["AI_AGENT is set", { env: { AI_AGENT: "claude" } }], + ["an ancestor process is the agent CLI", { ancestors: () => ["zsh", "claude"] }], + ])("refuses a protected env when %s", (_name, over) => { + expect(() => assertHumanSession(human(over as Partial))).toThrow( + "This command is not available in this session.", + ); + }); + + it("refuses with a neutral message that names no marker", () => { + try { + assertHumanSession(human({ env: { CLAUDECODE: "1" } })); + } catch (e) { + expect((e as Error).message).not.toMatch(/claude|agent|tty/i); + } + }); + + it("treats no --env and read-only gateway envs as protected", () => { + expect(needsGuard(null)).toBe(true); + expect(needsGuard({ protected: false, gateway: { url: "https://x", region: "r", profile: "p" } })).toBe( + true, + ); + expect(() => assertHumanSession(human({ profile: null, stdinIsTTY: false }))).toThrow(); + }); + + it("leaves an explicitly unprotected env alone", () => { + expect(() => + assertHumanSession(human({ profile: dev, stdinIsTTY: false, env: { CLAUDECODE: "1" } })), + ).not.toThrow(); + }); + + it("detects agent markers in the environment", () => { + expect(agentMarkers({ CLAUDECODE: "1", PATH: "/bin" })).toEqual(["CLAUDECODE"]); + }); +}); + +describe("guard breadth and fail-closed", () => { + it.each([{ CODEX_SANDBOX: "1" }, { CURSOR_AGENT: "1" }, { GEMINI_CLI: "1" }, { OPENCODE: "1" }])( + "refuses env marker %j", + (env) => { + expect(() => assertHumanSession(human({ env }))).toThrow("not available"); + }, + ); + + it.each([{ CURSOR_TRACE_ID: "x" }, { AIDER_MODEL: "x" }, { CODEX_HOME: "/tmp/codex" }])( + "lets a human with agent config in their shell through %j", + (env) => { + expect(() => assertHumanSession(human({ env }))).not.toThrow(); + }, + ); + + it.each([ + "node /usr/lib/node_modules/@anthropic-ai/claude-code/cli.js --resume", + "node /opt/lib/@openai/codex/bin/codex.js", + "/usr/bin/python3 /usr/local/bin/aider", + "claude", + ])("recognises agent command line %s", (line) => { + expect(isAgentProcess(line)).toBe(true); + expect(() => assertHumanSession(human({ ancestors: () => ["-zsh", line] }))).toThrow(); + }); + + it("does not flag ordinary shells or .claude paths", () => { + expect(isAgentProcess("-zsh")).toBe(false); + expect(isAgentProcess("/bin/zsh -c cd /Users/x/.claude/foo")).toBe(false); + }); + + it("refuses when the ancestor walk cannot run", () => { + const ancestors = (): string[] => { + throw new Error("ps: not found"); + }; + expect(() => assertHumanSession(human({ ancestors }))).toThrow(/process check could not run/); + }); +}); + +describe("writePrivateFiles", () => { + const dirs: string[] = []; + afterEach(() => { + for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }); + }); + const tmp = (): string => { + const d = mkdtempSync(join(tmpdir(), "ct-dupes-out-")); + dirs.push(d); + return d; + }; + + it("refuses a git work tree", () => { + const repo = tmp(); + mkdirSync(join(repo, ".git")); + expect(() => writePrivateFiles(join(repo, "out"), { "a.csv": "x" })).toThrow(/repository/); + }); + + it("creates a new dir 0700 and files 0600", () => { + const out = join(tmp(), "new"); + const res = writePrivateFiles(out, { "a.csv": "x" }); + expect(statSync(out).mode & 0o777).toBe(0o700); + expect(statSync(res.paths[0] as string).mode & 0o777).toBe(0o600); + expect(res.warning).toBeUndefined(); + }); + + it("warns about, but does not change, an open existing dir", () => { + const out = tmp(); + chmodSync(out, 0o755); + const res = writePrivateFiles(out, { "a.csv": "x" }); + expect(res.warning).toMatch(/readable by other users/); + expect(statSync(out).mode & 0o777).toBe(0o755); + }); +}); + +describe("redaction", () => { + const r = makeRedactor(true, "secret"); + it("gives stable pseudonyms that hide the value", () => { + expect(r.id(4711)).toBe(r.id(4711)); + expect(r.id(4711)).not.toContain("4711"); + expect(r.value("Erika")).toBe(r.value("Erika")); + expect(r.value("Erika")).not.toBe(r.value("Anna")); + expect(r.value("Erika")).not.toContain("Erika"); + expect(r.value("")).toBe(""); + }); + it("is keyed: another secret gives other pseudonyms", () => { + expect(makeRedactor(true, "other").id(1)).not.toBe(r.id(1)); + }); + it("passes values through when disabled", () => { + const off = makeRedactor(false, ""); + expect(off.id(7)).toBe("7"); + expect(off.value("Erika")).toBe("Erika"); + }); + it("masks digit runs in error text", () => { + expect(r.text("failed for 4711")).toBe("failed for #"); + }); +}); + +describe("error text", () => { + it("never echoes a response body or request path", () => { + const err = new CtApiError("GET /persons/4711 failed", 500, { message: "Erika Muster" }); + const text = safeErrorText(err, makeRedactor(false, "")); + expect(text).toBe("ChurchTools request failed (HTTP 500)."); + }); +}); + +describe("local store", () => { + const dirs: string[] = []; + afterEach(() => { + for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true }); + }); + const env = (): NodeJS.ProcessEnv => { + const d = mkdtempSync(join(tmpdir(), "ct-dupes-")); + dirs.push(d); + return { CT_DUPES_DIR: d }; + }; + + it("slugs hosts", () => { + expect(hostSlug("https://Example.church.tools/")).toBe("example-church-tools"); + }); + + it("writes dirs 0700 and files 0600", () => { + const store = new DupesStore("https://example.church.tools", env()); + store.audit({ action: "x" }); + store.redactSecret(); + const path = store.writeExport("a.csv", "x"); + expect(statSync(store.dir).mode & 0o777).toBe(0o700); + expect(statSync(store.exportDir).mode & 0o777).toBe(0o700); + expect(statSync(store.auditPath).mode & 0o777).toBe(0o600); + expect(statSync(path).mode & 0o777).toBe(0o600); + expect(store.readAudit()[0]).toMatchObject({ action: "x" }); + }); + + it("refuses to live inside a git work tree", () => { + const repo = mkdtempSync(join(tmpdir(), "ct-dupes-repo-")); + dirs.push(repo); + // `.git` as a plain directory is enough for the check. + mkdirSync(join(repo, ".git")); + expect(() => new DupesStore("https://example.church.tools", { CT_DUPES_DIR: join(repo, "x") })).toThrow( + /repository/, + ); + }); + + it("uses Application Support on macOS and XDG elsewhere", () => { + const mac = new DupesStore("https://a.example", {}, "darwin"); + expect(mac.dir).toContain(join("Library", "Application Support", "ct-cli", "dupes", "a-example")); + const lin = new DupesStore("https://a.example", { XDG_DATA_HOME: "/tmp/xdg-test" }, "linux"); + expect(lin.dir).toBe(join("/tmp/xdg-test", "ct-cli", "dupes", "a-example")); + }); +}); diff --git a/tests/dupes-merge-model.test.ts b/tests/dupes-merge-model.test.ts new file mode 100644 index 0000000..d27c6cf --- /dev/null +++ b/tests/dupes-merge-model.test.ts @@ -0,0 +1,245 @@ +import { describe, expect, it } from "vitest"; +import { emailLabel, emailTypes, formatValue, isMasterValue } from "../src/dupes/actions.js"; +import { toPersonRecord } from "../src/dupes/ct.js"; +import { + buildBody, + buildEmailRows, + buildModel, + defaultChoice, + olderFirst, + optigemOutcome, + setChoice, + setDefaultEmail, + toggleEmail, + type MergeModel, +} from "../src/dupes/merge-model.js"; +import { raw } from "./dupes-fixtures.js"; + +const model = (o: Record, d: Record): MergeModel => + buildModel(o, d, [], "optigemId"); + +describe("merge model", () => { + it("only offers whitelisted person fields; system keys are never choosable", () => { + const m = model(raw(1), raw(2, { lastName: "Beispiel", domainType: "person", imageUrl: "x" })); + const keys = m.fields.map((f) => f.key); + expect(keys).toContain("lastName"); + for (const k of [ + "guid", + "id", + "meta", + "domainType", + "imageUrl", + "securityLevelForPerson", + "emails", + "email", + ]) { + expect(keys).not.toContain(k); + } + }); + + it("skips fields that are empty on both sides and defaults to the non-empty side", () => { + const m = model(raw(1, { mobile: "" }), raw(2, { mobile: "0151", job: "" })); + expect(m.fields.find((f) => f.key === "job")).toBeUndefined(); + expect(m.fields.find((f) => f.key === "mobile")!.choice).toBe("duplicate"); + expect(m.fields.find((f) => f.key === "firstName")!.choice).toBe("original"); + expect(defaultChoice("a", "b")).toBe("original"); + expect(defaultChoice("", "")).toBe("none"); + }); + + it("keeps the Original's values by default and applies chosen duplicate values", () => { + const o = raw(1); + const d = raw(2, { lastName: "Beispiel" }); + let m = model(o, d); + expect(buildBody(o, d, m).body.lastName).toBe("Muster"); + m = setChoice(m, "lastName", "duplicate"); + expect(buildBody(o, d, m).body.lastName).toBe("Beispiel"); + m = setChoice(m, "lastName", "none"); + expect(buildBody(o, d, m).body.lastName).toBe(""); + }); + + it("keeps the Bereiche of both persons by default and can still pick one side", () => { + const o = raw(1, { departmentIds: [1] }); + const d = raw(2, { departmentIds: [2, 1] }); + let m = model(o, d); + expect(m.fields.find((f) => f.key === "departmentIds")!.choice).toBe("both"); + expect(buildBody(o, d, m).body.departmentIds).toEqual([1, 2]); + m = setChoice(m, "departmentIds", "duplicate"); + expect(buildBody(o, d, m).body.departmentIds).toEqual([2, 1]); + expect(setChoice(m, "lastName", "both")).toBe(m); + const same = model(raw(1, { departmentIds: [1, 2] }), raw(2, { departmentIds: [2] })); + expect(same.fields.find((f) => f.key === "departmentIds")!.choice).toBe("original"); + }); + + it("unions emails: duplicate addresses without id, original ids kept, one default", () => { + const o = raw(1, { + email: "a@example.org", + emails: [ + { id: 1, email: "a@example.org", isDefault: true }, + { id: 2, email: "a2@example.org", isDefault: false }, + ], + }); + const d = raw(2, { + emails: [ + { id: 9, email: "B@example.org", isDefault: true }, + { id: 8, email: "A@example.org" }, + ], + }); + const m = model(o, d); + expect(m.emails.map((e) => [e.address, e.isDefault])).toEqual([ + ["a@example.org", true], + ["a2@example.org", false], + ["B@example.org", false], + ]); + const body = buildBody(o, d, m).body; + expect(body.emails).toEqual([ + { contactLabelId: null, email: "a@example.org", isDefault: true }, + { contactLabelId: null, email: "a2@example.org", isDefault: false }, + { contactLabelId: null, email: "B@example.org", isDefault: false }, + ]); + expect("email" in body).toBe(false); + }); + + it("sends the body in the shape ChurchTools' own merge UI sends (no read-only or empty keys)", () => { + const o = raw(1, { + email: "a@example.org", + emails: [{ id: 1, email: "a@example.org", isDefault: true, contactLabelId: 2, extra: "x" }], + createdDate: "2020-01-01", + imageUrl: "https://example.org/i.png", + parents: [], + isActive: true, + lastLogin: "2024-01-01", + nickname: "", + job: null, + isDead: false, + invitationStatus: { status: "accepted" }, + privacyPolicyAgreement: { date: "2020-01-01" }, + meta: { + createdDate: "c", + createdPerson: { id: 1 }, + modifiedDate: "m", + modifiedPerson: { id: 1 }, + other: 1, + }, + }); + const d = raw(2, { nickname: "Nick", emails: [] }); + const body = buildBody(o, d, model(o, d)).body; + for (const k of [ + "email", + "createdDate", + "imageUrl", + "parents", + "isActive", + "lastLogin", + "job", + "invitationStatus", + "privacyPolicyAgreement", + ]) { + expect(body, k).not.toHaveProperty(k); + } + expect(body.isDead).toBe(false); + expect(body.nickname).toBe("Nick"); + expect(Object.keys(body.meta as object).sort()).toEqual([ + "createdDate", + "createdPerson", + "modifiedDate", + "modifiedPerson", + ]); + expect(body.emails).toEqual([{ contactLabelId: 2, email: "a@example.org", isDefault: true }]); + }); + + it("toggling and default selection keep exactly one default among included addresses", () => { + const o = raw(1, { emails: [{ id: 1, email: "a@example.org", isDefault: true }] }); + const d = raw(2, { emails: [{ id: 9, email: "b@example.org", isDefault: true }] }); + let m = model(o, d); + m = setDefaultEmail(m, "b@example.org"); + expect(buildBody(o, d, m).body.emails).toEqual([ + { contactLabelId: null, email: "a@example.org", isDefault: false }, + { contactLabelId: null, email: "b@example.org", isDefault: true }, + ]); + m = toggleEmail(m, "b@example.org"); + expect(buildBody(o, d, m).body.emails).toEqual([ + { contactLabelId: null, email: "a@example.org", isDefault: true }, + ]); + }); + + it("Optigem: lone ID is preselected; both IDs follow the choice", () => { + expect(optigemOutcome(model(raw(1), raw(2, { optigemId: "7" })))).toEqual({ leading: "7", orphaned: "" }); + const o = raw(1, { optigemId: "1" }); + const d = raw(2, { optigemId: "2" }); + let m = model(o, d); + expect(optigemOutcome(m)).toEqual({ leading: "1", orphaned: "2" }); + m = setChoice(m, "optigemId", "duplicate"); + expect(optigemOutcome(m)).toEqual({ leading: "2", orphaned: "1" }); + expect(buildBody(o, d, m).body.optigemId).toBe("2"); + }); + + it("warns instead of writing a display string when the duplicate lacks the key", () => { + const o = raw(1, { job: "x" }); + const d = raw(2); + let m = model(o, d); + m = { + ...m, + fields: [ + ...m.fields, + { key: "job", label: "Job", original: "x", duplicate: "y", choice: "duplicate", optigem: false }, + ], + }; + const res = buildBody(o, d, m); + expect(res.warnings[0]).toContain("cannot be carried over automatically"); + expect(res.body.job).toBe("x"); + }); + + it("the older person (lower id) is the default Original", () => { + expect(olderFirst({ id: 5 }, { id: 3 }).map((p) => p.id)).toEqual([3, 5]); + }); +}); + +describe("campus and status ids", () => { + it("keeps id 0 (a valid campus/status id) and shows names where masterdata has them", () => { + const rec = toPersonRecord(raw(1), "optigemId"); + expect(rec.campusId).toBe(0); + expect(rec.statusId).toBe(0); + const labels = { campusId: new Map([[0, "Hauptcampus"]]) }; + expect(formatValue("campusId", 0, labels)).toBe("Hauptcampus"); + expect(formatValue("statusId", 0, labels)).toBe("0"); + expect(formatValue("campusId", null, labels)).toBe(""); + expect(formatValue("birthday", "1999-06-30", labels)).toBe("30.06.1999"); + expect(formatValue("job", "1999-06-30 Umzug", labels)).toBe("1999-06-30 Umzug"); + }); + + it("names each department of a list and treats a fully named list as masterdata", () => { + const labels = { + departmentIds: new Map([ + [1, "Bereich A"], + [2, "Bereich B"], + ]), + }; + expect(formatValue("departmentIds", [1, 2], labels)).toBe("Bereich A, Bereich B"); + expect(formatValue("departmentIds", [1, 9], labels)).toBe("Bereich A, 9"); + expect(formatValue("departmentIds", [], labels)).toBe(""); + expect(isMasterValue("departmentIds", [1, 2], labels)).toBe(true); + expect(isMasterValue("departmentIds", [1, 9], labels)).toBe(false); + }); + + it("labels email rows with their contact type, the Original's when both have the address", () => { + const labels = { + contactLabelId: new Map([ + [1, "Privat"], + [4, "Arbeit"], + ]), + }; + const rows = buildEmailRows( + { emails: [{ email: "a@example.org", contactLabelId: 1, isDefault: true }] }, + { + emails: [ + { email: "A@example.org", contactLabelId: 4, isDefault: true }, + { email: "b@example.org", contactLabelId: 4, isDefault: false }, + { email: "c@example.org", contactLabelId: 99, isDefault: false }, + ], + }, + ); + expect(rows.map((r) => emailLabel(r, labels))).toEqual(["E-Mail (Privat)", "E-Mail (Arbeit)", "E-Mail"]); + expect(emailTypes(rows[0]!, labels)).toEqual({ original: "Privat", duplicate: "Arbeit" }); + expect(emailLabel(rows[0]!, {})).toBe("E-Mail"); + }); +}); diff --git a/tests/dupes-page.test.ts b/tests/dupes-page.test.ts new file mode 100644 index 0000000..90b80d9 --- /dev/null +++ b/tests/dupes-page.test.ts @@ -0,0 +1,53 @@ +import { describe, expect, it } from "vitest"; +import { PAGE_HTML } from "../src/dupes/web/page.js"; + +// No DOM library is a dependency, so these check the inline script's structure and syntax. +const script = /