From ca4446b09f8f9ad954efab7742f5070de9d2205e Mon Sep 17 00:00:00 2001 From: LaBani Said Date: Sun, 8 Nov 2026 19:51:11 +0100 Subject: [PATCH 1/3] Plan roadmap 1.21: Reference corporate and officer references as checked entry ids with party-type rules Co-Authored-By: Claude Opus 5.5 --- .../plan.md | 58 +++++++++ .../requirements.md | 123 ++++++++++++++++++ .../validation.md | 53 ++++++++ 3 files changed, 234 insertions(+) create mode 100644 specs/2026-11-08-reference-corporate-officer-refs/plan.md create mode 100644 specs/2026-11-08-reference-corporate-officer-refs/requirements.md create mode 100644 specs/2026-11-08-reference-corporate-officer-refs/validation.md diff --git a/specs/2026-11-08-reference-corporate-officer-refs/plan.md b/specs/2026-11-08-reference-corporate-officer-refs/plan.md new file mode 100644 index 0000000..3404803 --- /dev/null +++ b/specs/2026-11-08-reference-corporate-officer-refs/plan.md @@ -0,0 +1,58 @@ +# Plan: Reference BQ (corporate and officer references) + +Inside-out and test first (chosen in the interview), in the same order as 1.19 and 1.20. The solution builds and every test passes after each group. + +## 1. Value objects (core `Reference/`) +- [ ] `CompanyOfficerRole`, an `IPartyReferenceText` with Max35Text that is trimmed and not blank, serialized through `PartyReferenceTextJsonConverter`. Tests first in `tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Reference/CompanyOfficerRoleTests.cs`. +- [ ] `PartyCorporateReferences` (`CorporateCustomer`, `LegalEntity`, `CompanyOfficer`, all `PartyReferenceDataDirectoryEntryId?`, plus `CompanyOfficerRole?`), with `IsEmpty` and `ReferencedEntries` (the ids that are set). Tests: `PartyCorporateReferencesTests`. +- [ ] Add the new member to `PartyReferenceDetails`: `CorporateReferences`, nullable and `[JsonIgnore]`-computed, with a `CurrentCorporateReferences` accessor. Extend `PartyReferenceDetailsTests` with a check that pre-1.21 JSON still deserialises. + +## 2. Changes, decisions, handler, entry guard, projection and HTTP (one commit) +- [ ] `PartyReferenceFields`: + - add constants for the four paths and their `.PartyReference` parts; + - empty `Staged`; + - list `….InvolvementReference` (all three) and object-shaped `CompanyOfficerRole` parts as not recorded. +- [ ] `PartyReferenceInput` and `PartyReferenceChanges`: + - read the three ids as Guid v7 entry ids (`party.reference-invalid` naming `….PartyReference`); + - read the role; + - blank clears, omitted keeps. +- [ ] Update `PartyReferenceChangesTests`: the staged pin goes 4 → 0, and add the new unsupported parts. +- [ ] **Decide (`PartyReferenceDataDirectoryEntry` Reference decision):** + - `UpdatePartyReferenceDetails` gains `ReferencedParties` (an id → `PartyType?` lookup, where `null` means not registered); + - the checks run in this order: self-reference → not registered → type mismatch → the entry is not an Organisation (on the resulting Reference) → role without an officer (on the result); + - add the errors to `PartyReferenceErrors`: `SelfReference`, `ReferencedPartyNotRegistered`, `ReferencedPartyTypeMismatch`, `CorporateReferencesNeedOrganisation`. + - Given/When/Then tests go in `UpdatePartyReferenceTests`. +- [ ] **Handler (`UpdatePartyReferenceHandler`):** + - after the entry, version and BQ checks, load each id in the given changes through `directory.LoadEntryAsync`; + - fold each one with `Evolve` into `(IsRegistered, PartyType)`; + - build `ReferencedParties`, then call `Decide`. + - Tests in `UpdatePartyReferenceHandlerTests` with the in-memory port: + - an unregistered id, an association id and a self id; + - a Person given as the corporate customer, and an Organisation given as the officer; + - a Person owner; + - a kept reference is not reloaded. +- [ ] **Entry Update guard:** in the entry `Decide` for `UpdatePartyReferenceDataDirectoryEntryDetails`, refuse `PartyType = Person` when `CurrentReference.CurrentCorporateReferences` is not empty (`CorporateReferencesNeedOrganisation`). Add tests to the entry Update decision tests and the entry decider laws. +- [ ] **Projection:** `PartyReferenceDataDirectoryEntryViewProjection` carries `CorporateReferences` in the view's Reference section. Extend the projection test (Given events → Then view), including a pre-1.21 event. +- [ ] **HTTP (`src/RimBank.Api/Party/PartyReferenceDataDirectory/Reference/`):** + - add `InvolvedPartyModel`; + - add the four fields to the Update request and the Update/Retrieve response; + - leave empty values out of the response; + - report `InvolvementReference` and object-shaped role parts as unsupported; + - map the new 422 codes through the existing `error.ToHttpResult()`. + - Extend `PartyReferenceRequestTests` and `PartyReferenceResponseTests`. + +## 3. Integration (Definition of done: adapters touched, read model rebuildable) +- [ ] In `UpdatePartyReferenceEndpointTests` and `RetrievePartyReferenceEndpointTests` (Alba): + - a happy path that links an Organisation to an Organisation and a Person, and reads them back; + - one 422 Problem Details (`party.referenced-party-not-registered`); + - one 400 (`party.reference-field-not-supported` for `InvolvementReference`). +- [ ] Add a short `ReferenceScenarios` helper to register the referenced entries. +- [ ] In `PartyReferenceRoundTripTests` (Testcontainers): one case that appends the new event, rebuilds the inline view with `RebuildViewAsync`, and reads the references back. Also check that a stored pre-1.21 event still folds. + +## 4. Demo, privacy and docs +- [ ] `src/RimBank.Host/RimBank.Host.http`: register an Organisation and a Person, run the Reference Update that links them, run the Retrieve, and show a 422 request (a Person as the corporate customer). +- [ ] `ReferenceLogPrivacyTests`: add the new fields to the submitted payload, and assert that no referenced id or role is logged. +- [ ] Write ADR 0034, and amend ADR 0029, ADR 0024 and ADR 0032. +- [ ] Update the `Reference/` tree in tech-stack §3.4. +- [ ] Roadmap: tick 1.21 and reword it to name the party-type rules. +- [ ] Run `dotnet build`, `dotnet test` and `dotnet format --verify-no-changes` locally before opening the PR (with the open-phase-pr skill). diff --git a/specs/2026-11-08-reference-corporate-officer-refs/requirements.md b/specs/2026-11-08-reference-corporate-officer-refs/requirements.md new file mode 100644 index 0000000..25deb84 --- /dev/null +++ b/specs/2026-11-08-reference-corporate-officer-refs/requirements.md @@ -0,0 +1,123 @@ +# Party Reference Data Directory: Reference BQ (corporate and officer references) + +Roadmap phase: 1.21 +Branch: plan/1.21-reference-corporate-officer-refs + +## Context +1.10, 1.18, 1.19 and 1.20 record every BIAN Reference field except four, which are still refused with `party.reference-field-not-supported` and tagged `1.21` in `PartyReferenceFields.Staged` ([ADR 0029](../../docs/adr/0029-reference-fields-in-stages.md), [ADR 0032](../../docs/adr/0032-reference-legal-standing-and-documents.md)). These are the four references to other parties, all in the [BIAN OpenAPI](../../doc-0/release14.0.0/apis-iso20022_ext-ddd/oas3/yamls/PartyReferenceDataDirectory.yaml) (`UpdateReference`, `RetrieveReference`): + +- `CorporateCustomerReference` ("the corporate entity, Company for company customers"), an `Involvedparty` (`PartyReference`, `InvolvementReference`, both strings); +- `CorporateCustomerLegalEntityReference` ("the legal entity reference, for company customers"), an `Involvedparty`; +- `CompanyOfficerReference` ("one or more identified company officers for a corporate customer"), an `Involvedparty`; +- `CompanyOfficerRole` ("the specific role played by the identified officer", ISO 20022 `Party/Role/PartyRole`), typed as BIAN `Party`. That schema has **no role property** (ContactPoint, Identification, MoneyLaunderingCheck, …). + +They were held back until after the Associations BQ (1.11, [ADR 0033](../../docs/adr/0033-party-associations.md)). ADR 0033 set the rule for a party link: the referenced party is a **directory entry id, checked on the write side**. It rejected unchecked party links next to checked ones. This phase applies the same guarantee to the Reference fields. **Chosen in the interview:** it adds party-type rules, because BIAN describes all four fields as "for company customers". + +The Reference record stays in the entry aggregate (ADR 0024). The phase reuses the routes, the `PartyReferenceUpdated` event, `ETag` / `If-Match` and the inline view. It adds **no new operation, port, route or view**. It also changes one decision outside the Reference BQ: the entry's `Update` (1.8), so that the party-type rule cannot be broken from that side. + +It depends on 1.8, 1.10, 1.11, 1.18, 1.19 and 1.20, all done. It completes the Reference BQ, leaving zero staged fields, which unblocks the Reference MCP tools (1.17) and the published language (1.13). + +Drivers: +- Mission principles: + - 3: typed ids and value objects, no primitive obsession; + - 5: decisions use only write-side state, never a view; + - 7: no reference outside this directory is resolved; + - 8: Problem Details; + - 10: one small phase. +- Tech-stack: + - §3.4: value objects live in `Reference/` (ADR 0026); + - §4 CQRS: the command handler uses only the write port `IPartyDirectory`; + - §5: routes, `If-Match`, `Idempotency-Key`; + - §8.1: the cross-aggregate check is done on write-side loads, as in Associations; + - §8.3: inline view, rebuildable. + +**CQRS split:** +- **Command side:** + - `UpdatePartyReference`: + - the handler loads the entry as today; + - **it also loads, through `IPartyDirectory.LoadEntryAsync`, each entry referenced in the request**, at most three, folding each to "registered, and of which party type"; + - it passes those facts to the pure `Decide`, as `RegisterPartyAssociationHandler` does. + - `UpdatePartyReferenceDataDirectoryEntry`: its `Decide` refuses a change of party type to `Person` while corporate references are recorded. +- **Query side:** `RetrievePartyReference` reads the same **inline** `PartyReferenceDataDirectoryEntryView`, whose Reference section gains the four fields. There is no async projection. + +## Scope +### In scope +- **Recorded fields (core `Reference/`):** + + | BIAN path | Recorded as | Rule | + |---|---|---| + | `CorporateCustomerReference.PartyReference` | `PartyReferenceDataDirectoryEntryId` | A Guid v7 entry id. Registered, not the entry itself, and an **Organisation** entry | + | `CorporateCustomerLegalEntityReference.PartyReference` | `PartyReferenceDataDirectoryEntryId` | Same as above | + | `CompanyOfficerReference.PartyReference` | `PartyReferenceDataDirectoryEntryId` | Registered, not the entry itself, and a **Person** entry. One officer, because BIAN gives a single object | + | `CompanyOfficerRole` | `CompanyOfficerRole` (Max35Text) | Plain string, trimmed, not blank, at most 35 characters (for example `Director`). It is recorded only together with an officer | + + - **A new record, `PartyCorporateReferences`** (corporate customer, legal entity, officer and role), is added to `PartyReferenceDetails` as a nullable `[JsonIgnore]`-computed member with a `CurrentCorporateReferences` accessor, as in 1.18 to 1.20. Events and view documents from 1.10 to 1.20 still load and fold. + - The corporate customer and the legal entity may be the same entry. +- **Refused parts:** `InvolvementReference`, at any of the three references, is refused with `party.reference-field-not-supported` and no phase. The role is carried by `CompanyOfficerRole`, as ADR 0033 did for `AssociateType`. A `CompanyOfficerRole` sent as an object (BIAN's `Party` shape) is refused the same way. +- **Party-type rules (chosen in the interview):** + 1. The four fields are recorded only on an **Organisation** entry. Recording one on a Person entry is `party.corporate-references-need-organisation` (422). This rule is checked in `Decide` on the resulting Reference. + 2. The corporate customer and legal entity references point at Organisation entries, and the officer at a Person entry. Otherwise the result is `party.referenced-party-type-mismatch` (422), and `errors` names the path. + 3. **The entry's `Update` (1.8) refuses a change of party type to `Person` while any corporate reference is recorded**, with the same `party.corporate-references-need-organisation`. The client clears the references first. Without this, rule 1 could be broken from the other side. +- **Cross-aggregate checks (handler loads, `Decide` decides):** + - a reference to the entry itself is `party.self-reference` (422); + - a reference that is not a registered entry is `party.referenced-party-not-registered` (422), naming the path. An association id sent as an entry id loads no events, so it fails the same way and is never a cast error (ADR 0033); + - only the references **given in this request** are loaded and checked. Kept ones were checked when they were recorded. +- **Partial update (as in 1.18 to 1.20):** + - an omitted field keeps its value, a given one replaces it, and a blank `PartyReference` or role clears it; + - a role with no resulting officer is `party.reference-invalid` naming `CompanyOfficerRole`. This is checked in `Decide` on the result, as for the PEP description in 1.20, so clearing the officer while a role is kept is refused unless the same request clears the role; + - every accepted Update appends `PartyReferenceUpdated` with the full resulting Reference. +- **Malformed input:** an id that is not a Guid v7, or a role that is blank or too long, goes into `party.reference-invalid` (400), and `errors` names each path. The unsupported-field check still runs first, then the input reading, then the handler loads, then `Decide`. +- **Staged table:** the four fields leave `PartyReferenceFields.Staged`, which becomes empty. The `PartyReferenceChangesTests` pin goes from 4 to 0. +- **HTTP (`RimBank.Api/Party/PartyReferenceDataDirectory/Reference/`):** + - an `InvolvedPartyModel` (`PartyReference`, plus `InvolvementReference` read only to report it as unsupported); + - the Update request and the shared Update/Retrieve response gain the four fields, and empty values are left out of the response; + - the new error codes are mapped through `RimBank.Problems` (`Error.BusinessRule` → 422). +- **Demo:** requests in `src/RimBank.Host/RimBank.Host.http` that register an Organisation and a Person, link them through the Reference Update, and show one 422. +- **Docs:** + - new ADR 0034; + - ADR 0029 amended (the staged table is empty); + - ADR 0024 amended (the Reference paragraph, and the entry Update rule); + - ADR 0032 amended (a Consequences note that 1.21 is done); + - tech-stack §3.4 updated (the `Reference/` tree). +- **Roadmap:** the 1.21 row is ticked and reworded to name the party-type rules. + +### Out of scope +- **More than one officer, or officer history.** BIAN gives a single object, so one officer is recorded, as with the single document in 1.20. No phase is planned. +- **Keeping the rule in step when a *referenced* entry later changes its party type.** That would need a cross-stream index on the write side (ADR 0033 refused one for uniqueness). The rule holds when a reference is recorded. Later drift is documented in ADR 0034 as accepted staleness. +- **Deriving Associations from these references, or the reverse.** The two stay independent records. A client that wants both registers both. +- **A role code list.** BIAN gives none, so the role is free text. No phase is planned. +- **MCP tools (1.17), per-operation scopes (1.15), the Reference channels (after 7.2), and masking and encryption at rest (7.2).** +- **Checks not chosen in the interview:** extending the FsCheck partial-update law to the new fields, and a dedicated Testcontainers round-trip beyond the minimum that the Definition of done requires (see validation.md). + +## Decisions +| Decision | Choice | Rationale | +|---|---|---| +| Shape of a party reference | A checked directory entry id (`PartyReferenceDataDirectoryEntryId`) | Same guarantee as the Associations associate. ADR 0033 refused two kinds of party link with different guarantees | +| Party-type rules | The fields go only on Organisation entries. The corporate and legal entity references point at Organisations, and the officer at a Person | Chosen in the interview. BIAN describes all four as "for company customers". This is the first party-type rule in the Reference BQ, and ADR 0034 records why it departs from 1.18 and 1.20: those fields are the party's own, while these are links whose meaning depends on the party types | +| Entry Update guard | The entry `Update` refuses a change to `Person` while corporate references are recorded | Keeps rule 1 true on the write side. An invariant must not depend on the order in which commands arrive | +| Drift of the referenced entry | Not guarded, and documented | Guarding it would need a cross-stream index, which costs more than the harm (same reasoning as ADR 0033 on uniqueness) | +| Number of officers | One | BIAN gives a single object. Same choice as the document in 1.20 | +| `CompanyOfficerRole` | A plain Max35Text string, needing an officer | BIAN's `Party` schema has no role property, so the field is read as the role text it describes (mission "Source of truth" 3) | +| `InvolvementReference` | Refused, no phase | The role is carried by `CompanyOfficerRole`. Same reasoning as ADR 0033 | +| Which references are loaded | Only those given in the request | Kept ones were checked when they were recorded, and this keeps the handler to at most three loads | +| Error codes | New: `party.self-reference`, `party.referenced-party-not-registered`, `party.referenced-party-type-mismatch`, `party.corporate-references-need-organisation` (all 422 BusinessRule). Reused: `party.reference-invalid`, `party.reference-field-not-supported` | Business rules are 422, malformed input is 400, as in ADR 0033. The Associations codes are not reused, so each error names what failed | +| Event | `PartyReferenceUpdated`, with the same name and a larger `Details` | The new member is nullable, so earlier events still fold | +| Work order | Inside-out, test first: value objects → changes, decision, handler loads, entry Update guard, projection and HTTP (one commit) → PostgreSQL / rebuild → demo, log check and docs | Chosen in the interview. Same order as 1.19 and 1.20, so no commit drops fields silently | + +## ADRs to write +- **ADR 0034 (new): Reference BQ corporate and officer references.** It records: + - the checked entry ids, and why opaque text and "retire to Associations" were rejected; + - the three party-type rules, and why the Reference BQ now has one when 1.18 and 1.20 had none; + - the entry Update guard; + - the accepted drift when a referenced entry changes its party type; + - one officer, the role as Max35Text text, and `InvolvementReference` refused; + - the four new error codes. + + Options considered: checked ids without party-type rules; retiring the fields to Associations; opaque references. +- **Amend ADR 0029:** a "Recorded (1.21)" table, an empty staged table, and the pin count. +- **Amend ADR 0024:** the Reference paragraph, and the new rule in the entry Update. +- **Amend ADR 0032:** a Consequences note that the 1.21 split is done. +- **Tech-stack §3.4:** the `Reference/` tree gains `PartyCorporateReferences.cs` and `CompanyOfficerRole.cs`. + +## Open questions +- None. diff --git a/specs/2026-11-08-reference-corporate-officer-refs/validation.md b/specs/2026-11-08-reference-corporate-officer-refs/validation.md new file mode 100644 index 0000000..0745af7 --- /dev/null +++ b/specs/2026-11-08-reference-corporate-officer-refs/validation.md @@ -0,0 +1,53 @@ +# Validation: Reference BQ (corporate and officer references) + +## Done when (from roadmap) +> **1.21 Reference BQ: corporate and officer references:** `CorporateCustomerReference`, `CorporateCustomerLegalEntityReference`, `CompanyOfficerReference` and `CompanyOfficerRole`, references to other parties, added to the Reference Update and Retrieve after the Associations BQ (ADR 0032). +> + Definition of done (roadmap.md) + +## Automated checks +Chosen in the interview: core and handler tests, and the log-capture check. +- [ ] **Core (`RimBank.Core.Tests`, `…/Reference/`):** + - `CompanyOfficerRoleTests`: trims the role, and refuses a blank one or one over 35 characters; + - `PartyCorporateReferencesTests`; + - `PartyReferenceDetailsTests`: pre-1.21 JSON still loads; + - `PartyReferenceChangesTests`: + - **the staged pin is 0**; + - `InvolvementReference` and an object-shaped role are refused as unsupported; + - a malformed id is `party.reference-invalid` naming `….PartyReference`. +- [ ] **Decision tests (Given/When/Then, `UpdatePartyReferenceTests` and the entry decision tests):** + - a self-reference gives `party.self-reference`; + - an unregistered reference gives `party.referenced-party-not-registered`; + - a Person as the corporate customer or legal entity, or an Organisation as the officer, gives `party.referenced-party-type-mismatch`; + - corporate references on a Person entry give `party.corporate-references-need-organisation`; + - a role with no officer, including clearing the officer while the role is kept, gives `party.reference-invalid`; + - the entry `Update` to `Person` while references are recorded gives `party.corporate-references-need-organisation`. The entry decider laws still hold. +- [ ] **Handler tests (`UpdatePartyReferenceHandlerTests`, in-memory port):** + - the referenced entries are loaded through the write port; + - an association id gives `party.referenced-party-not-registered`, never an exception; + - a reference that is kept is not reloaded; + - the acknowledgement carries the references, built from the decided state. +- [ ] **Projection test:** events → the view's Reference section holds the references, and a pre-1.21 event folds to empty references. +- [ ] **Definition of done minimum, because the HTTP adapter and the read model change:** + - Alba: a happy PUT and GET, one 422 and one 400, each `application/problem+json` with `errorCode`; + - Testcontainers: `PartyReferenceRoundTripTests` rebuilds the inline view with the new fields. +- [ ] **Log capture (`ReferenceLogPrivacyTests`):** no submitted referenced id or role appears in the logs. +- [ ] `RimBank.Architecture.Tests` stays green. In particular the CQRS rule: the Reference command handler uses only `IPartyDirectory`, never `IPartyDirectoryEnquiry` or a view. +- [ ] The existing BIAN conformance tests stay green (no new route). +- [ ] `dotnet format --verify-no-changes`, and the CI build, test and CodeQL jobs, are green. + +## Manual / demo checks +Run in `src/RimBank.Host/RimBank.Host.http` against `dotnet run --project src/RimBank.AppHost`, with a dev-realm token: +- [ ] `POST /PartyReferenceDataDirectory/Register` for an Organisation (A), another Organisation (B) and a Person (P) gives three 201 responses, each with an `ETag`. +- [ ] `PUT /PartyReferenceDataDirectory/{A}/Reference/{refId}/Update` with `If-Match` and an `Idempotency-Key`, and the body `{"CorporateCustomerReference":{"PartyReference":""},"CorporateCustomerLegalEntityReference":{"PartyReference":""},"CompanyOfficerReference":{"PartyReference":"

"},"CompanyOfficerRole":"Director"}`, gives a 200 that echoes the four fields and a new `ETag`. +- [ ] `GET /PartyReferenceDataDirectory/{A}/Reference/{refId}/Retrieve` returns the same four fields. +- [ ] The same Update with `"CorporateCustomerReference":{"PartyReference":"

"}` gives a **422** `application/problem+json` with `errorCode: party.referenced-party-type-mismatch` and `errors` naming `CorporateCustomerReference.PartyReference`. +- [ ] An Update with `"CompanyOfficerReference":{"PartyReference":"

","InvolvementReference":"x"}` gives a **400** `party.reference-field-not-supported`. +- [ ] `PUT /PartyReferenceDataDirectory/{A}/Update` with `PartyType: Person` gives a **422** `party.corporate-references-need-organisation`. + +## Merge criteria +- [ ] All checks above pass in CI +- [ ] Roadmap checkbox 1.21 ticked in the same PR +- [ ] ADR 0034 written, and ADRs 0029, 0024 and 0032 and tech-stack §3.4 amended +- [ ] No referenced id or role in the logs (log-capture test) +- [ ] Every new error path returns Problem Details with a documented code +- [ ] The PR is opened with the open-phase-pr skill (labels, milestone, board, `Closes #<1.21 issue>`) From d3bc668918d45c9eea000635eac31c8bb75f6351 Mon Sep 17 00:00:00 2001 From: LaBani Said Date: Sun, 8 Nov 2026 20:25:40 +0100 Subject: [PATCH 2/3] Record the Reference corporate and officer references as checked directory entries, on organisations only (roadmap 1.21) CorporateCustomerReference, CorporateCustomerLegalEntityReference and CompanyOfficerReference are other registered entries, loaded by the Reference Update handler through the write port; the corporate customer and legal entity are organisations, the officer a person, and only an organisation's entry holds them. CompanyOfficerRole is a Max35Text that needs an officer. The entry Update refuses to make such an organisation a person. Co-Authored-By: Claude Opus 5.5 --- .../Associations/InvolvedPartyModel.cs | 7 +- .../Reference/PartyReferenceResponse.cs | 24 +++- .../Reference/UpdatePartyReferenceRequest.cs | 71 +++++++++- .../Decisions.cs | 58 +++++++- .../Reference/CompanyOfficerRole.cs | 29 ++++ .../Reference/PartyCorporateReferences.cs | 41 ++++++ .../Reference/PartyReferenceChanges.cs | 63 ++++++++- .../Reference/PartyReferenceDetails.cs | 18 ++- .../Reference/PartyReferenceErrors.cs | 48 ++++++- .../Reference/PartyReferenceFields.cs | 39 ++++-- .../Reference/PartyReferenceInput.cs | 13 +- .../Reference/UpdatePartyReferenceHandler.cs | 39 +++++- src/RimBank.Host/RimBank.Host.http | 47 ++++++- .../PartyReferenceRoundTripTests.cs | 33 +++++ .../Demographics/DemographicsScenarios.cs | 4 +- .../CorporateReferencesEndpointTests.cs | 128 +++++++++++++++++ .../Reference/PartyReferenceRequestTests.cs | 45 +++++- .../Reference/ReferenceLogPrivacyTests.cs | 39 ++++++ .../UpdatePartyReferenceEndpointTests.cs | 12 +- .../EntryExamples.cs | 45 +++++- .../CorporateReferencesDecisionTests.cs | 132 ++++++++++++++++++ .../PartyCorporateReferencesTests.cs | 91 ++++++++++++ .../Reference/PartyReferenceChangesTests.cs | 120 +++++++++++----- .../PartyReferencePartialUpdateProperties.cs | 8 +- .../Reference/ReferenceArbitraries.cs | 30 +++- .../UpdatePartyReferenceHandlerTests.cs | 94 +++++++++++++ ...ceDataDirectoryEntryViewProjectionTests.cs | 32 +++++ 27 files changed, 1226 insertions(+), 84 deletions(-) create mode 100644 src/RimBank.Core/Party/PartyReferenceDataDirectory/Reference/CompanyOfficerRole.cs create mode 100644 src/RimBank.Core/Party/PartyReferenceDataDirectory/Reference/PartyCorporateReferences.cs create mode 100644 tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/Reference/CorporateReferencesEndpointTests.cs create mode 100644 tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Reference/CorporateReferencesDecisionTests.cs create mode 100644 tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Reference/PartyCorporateReferencesTests.cs diff --git a/src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/InvolvedPartyModel.cs b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/InvolvedPartyModel.cs index 40fcf7c..9825561 100644 --- a/src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/InvolvedPartyModel.cs +++ b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/InvolvedPartyModel.cs @@ -4,9 +4,10 @@ namespace RimBank.Party.PartyReferenceDataDirectory.Api; ///

-/// BIAN's Involvedparty as the Associations AssociateReference, in requests and responses (roadmap 1.11, -/// ADR 0033). RimBank records its PartyReference, the associate's directory entry id; a request that sends any -/// other part of it (such as InvolvementReference) is refused. +/// BIAN's Involvedparty, in requests and responses: the Associations AssociateReference (roadmap 1.11, +/// ADR 0033) and the Reference CorporateCustomerReference, CorporateCustomerLegalEntityReference and +/// CompanyOfficerReference (roadmap 1.21, ADR 0034). RimBank records its PartyReference, the id of a +/// directory entry; a request that sends any other part of it (such as InvolvementReference) is refused. /// public sealed record InvolvedPartyModel { diff --git a/src/RimBank.Api/Party/PartyReferenceDataDirectory/Reference/PartyReferenceResponse.cs b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Reference/PartyReferenceResponse.cs index 4ccb02b..065362f 100644 --- a/src/RimBank.Api/Party/PartyReferenceDataDirectory/Reference/PartyReferenceResponse.cs +++ b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Reference/PartyReferenceResponse.cs @@ -31,6 +31,10 @@ namespace RimBank.Party.PartyReferenceDataDirectory.Api; /// BIAN CustomerSinceDate, as an ISO 8601 date (YYYY-MM-DD, ADR 0032). /// BIAN GovernmentIssuedDocumentDetails. /// BIAN DocumentDirectoryEntryInstanceReference. +/// BIAN CorporateCustomerReference, with the entry id in its PartyReference. +/// BIAN CorporateCustomerLegalEntityReference. +/// BIAN CompanyOfficerReference. +/// BIAN CompanyOfficerRole, as the role text (ADR 0034). public sealed record PartyReferenceResponse( [property: JsonPropertyName("PartyReferenceDataDirectoryEntryId")] Guid PartyReferenceDataDirectoryEntryId, [property: JsonPropertyName("ReferenceId")] Guid ReferenceId, @@ -53,7 +57,11 @@ public sealed record PartyReferenceResponse( [property: JsonPropertyName("PoliticalExposureDescriptionRecord"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? PoliticalExposureDescriptionRecord = null, [property: JsonPropertyName("CustomerSinceDate"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? CustomerSinceDate = null, [property: JsonPropertyName("GovernmentIssuedDocumentDetails"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] PartyDocumentModel? GovernmentIssuedDocumentDetails = null, - [property: JsonPropertyName("DocumentDirectoryEntryInstanceReference"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] DocumentDirectoryEntryModel? DocumentDirectoryEntryInstanceReference = null) + [property: JsonPropertyName("DocumentDirectoryEntryInstanceReference"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] DocumentDirectoryEntryModel? DocumentDirectoryEntryInstanceReference = null, + [property: JsonPropertyName("CorporateCustomerReference"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] InvolvedPartyModel? CorporateCustomerReference = null, + [property: JsonPropertyName("CorporateCustomerLegalEntityReference"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] InvolvedPartyModel? CorporateCustomerLegalEntityReference = null, + [property: JsonPropertyName("CompanyOfficerReference"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] InvolvedPartyModel? CompanyOfficerReference = null, + [property: JsonPropertyName("CompanyOfficerRole"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] string? CompanyOfficerRole = null) { /// The response for an Update's acknowledgement. /// The outcome of . @@ -85,6 +93,7 @@ private static PartyReferenceResponse From( var contactPoints = reference.CurrentContactPoints; var legalStanding = reference.CurrentLegalStanding; var documents = reference.CurrentDocuments; + var corporate = reference.CurrentCorporateReferences; return new PartyReferenceResponse( entryId.Value, referenceId.Value, @@ -129,9 +138,20 @@ private static PartyReferenceResponse From( PartyDocumentModel.From(documents.GovernmentIssuedDocument), documents.DocumentDirectoryEntry is { } directory ? new DocumentDirectoryEntryModel { DocumentDirectoryEntryIdentification = directory.Value } - : null); + : null, + InvolvedPartyOf(corporate.CorporateCustomer), + InvolvedPartyOf(corporate.LegalEntity), + InvolvedPartyOf(corporate.CompanyOfficer), + corporate.CompanyOfficerRole?.Value); } + private static InvolvedPartyModel? InvolvedPartyOf(PartyReferenceDataDirectoryEntryId? entryId) => + entryId switch + { + null => null, + { } referenced => new InvolvedPartyModel { PartyReference = referenced.ToString() }, + }; + private static CountryModel? CountryOf(SharedKernel.CountryCode? country) => country switch { diff --git a/src/RimBank.Api/Party/PartyReferenceDataDirectory/Reference/UpdatePartyReferenceRequest.cs b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Reference/UpdatePartyReferenceRequest.cs index 679e106..e92a79d 100644 --- a/src/RimBank.Api/Party/PartyReferenceDataDirectory/Reference/UpdatePartyReferenceRequest.cs +++ b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Reference/UpdatePartyReferenceRequest.cs @@ -7,9 +7,8 @@ namespace RimBank.Party.PartyReferenceDataDirectory.Api; /// /// The body of PUT …/{partyreferencedatadirectoryid}/Reference/{referenceid}/Update: BIAN's /// UpdateReference with its property names (ADR 0024, ADR 0029), as a partial update of the Reference. A value -/// left out keeps its value, and an empty one (or an object whose parts are all empty) clears it. The four BIAN -/// references to other parties are refused until the roadmap phase that records them (1.21, ADR 0032); properties that -/// are not BIAN's are ignored. +/// left out keeps its value, and an empty one (or an object whose parts are all empty) clears it. Parts of BIAN objects +/// RimBank does not record are refused; properties that are not BIAN's are ignored. /// public sealed record UpdatePartyReferenceRequest { @@ -99,6 +98,35 @@ public sealed record UpdatePartyReferenceRequest [JsonPropertyName("DocumentDirectoryEntryInstanceReference")] public DocumentDirectoryEntryModel? DocumentDirectoryEntryInstanceReference { get; init; } + /// + /// BIAN CorporateCustomerReference (1.21, ADR 0034): the company, as the id of a registered organisation in its + /// PartyReference. + /// + [JsonPropertyName("CorporateCustomerReference")] + public InvolvedPartyModel? CorporateCustomerReference { get; init; } + + /// + /// BIAN CorporateCustomerLegalEntityReference (1.21): the legal entity, as the id of a registered organisation in + /// its PartyReference. + /// + [JsonPropertyName("CorporateCustomerLegalEntityReference")] + public InvolvedPartyModel? CorporateCustomerLegalEntityReference { get; init; } + + /// + /// BIAN CompanyOfficerReference (1.21): the company officer, as the id of a registered person in its + /// PartyReference. + /// + [JsonPropertyName("CompanyOfficerReference")] + public InvolvedPartyModel? CompanyOfficerReference { get; init; } + + /// + /// BIAN CompanyOfficerRole (1.21, Max35Text): the officer's role as a plain string, for example Director. + /// BIAN types it as a Party, which has no role property (ADR 0034): an object is read for its parts, which are + /// all refused, and an empty one clears the role. + /// + [JsonPropertyName("CompanyOfficerRole")] + public JsonElement? CompanyOfficerRole { get; init; } + /// Every other property sent: the BIAN Reference fields RimBank does not record yet are found here. [JsonExtensionData] public Dictionary? Other { get; init; } @@ -127,6 +155,10 @@ .. PartsOf(PartyReferenceFields.CellPhoneNumber, CellPhoneNumber?.Other), .. PartsOf(PartyReferenceFields.SocialNetworkContacts, SocialNetworkContacts?.Other), .. GovernmentIssuedDocumentDetails?.UnsupportedParts(PartyReferenceFields.GovernmentIssuedDocumentDetails) ?? [], .. PartsOf(PartyReferenceFields.DocumentDirectoryEntryInstanceReference, DocumentDirectoryEntryInstanceReference?.Other), + .. PartsOf(PartyReferenceFields.CorporateCustomerReference, CorporateCustomerReference?.Other), + .. PartsOf(PartyReferenceFields.CorporateCustomerLegalEntityReference, CorporateCustomerLegalEntityReference?.Other), + .. PartsOf(PartyReferenceFields.CompanyOfficerReference, CompanyOfficerReference?.Other), + .. RolePartsOf(CompanyOfficerRole), ]; /// @@ -168,10 +200,41 @@ public Result ToCommand( GovernmentIssuedDocumentDetails?.ToInput(), DocumentDirectoryEntryInstanceReference is { } directory ? directory.DocumentDirectoryEntryIdentification ?? string.Empty - : null), + : null, + PartyReferenceOf(CorporateCustomerReference), + PartyReferenceOf(CorporateCustomerLegalEntityReference), + PartyReferenceOf(CompanyOfficerReference), + RoleOf(CompanyOfficerRole)), UnsupportedFields()) .Map(changes => new UpdatePartyReference(entryId, referenceId, expectedVersion, changes, idempotencyKey)); + private static string? PartyReferenceOf(InvolvedPartyModel? reference) => + reference switch + { + null => null, + _ => reference.PartyReference ?? string.Empty, + }; + + // A string is the role; null is not sent; an object (the BIAN Party shape) has no role, so it clears the role and its + // parts are reported as unsupported; any other JSON value is read as its text, which the role then checks. + private static string? RoleOf(JsonElement? role) => + role switch + { + null or { ValueKind: JsonValueKind.Null or JsonValueKind.Undefined } => null, + { ValueKind: JsonValueKind.String } text => text.GetString(), + { ValueKind: JsonValueKind.Object } => string.Empty, + { } other => other.GetRawText(), + }; + + private static IEnumerable RolePartsOf(JsonElement? role) => + role switch + { + { ValueKind: JsonValueKind.Object } parts => parts.EnumerateObject() + .Where(part => part.Value.ValueKind != JsonValueKind.Null) + .Select(part => $"{PartyReferenceFields.CompanyOfficerRole}.{part.Name}"), + _ => [], + }; + private static IEnumerable AddressPartsOf(string field, PostalAddressModel? address) => PartsOf(field, address?.Other).Concat(PartsOf($"{field}.{PostalAddress.CountryPart}", address?.Country?.Other)); diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/PartyReferenceDataDirectoryEntry/Decisions.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/PartyReferenceDataDirectoryEntry/Decisions.cs index e89ecfb..9ceaf35 100644 --- a/src/RimBank.Core/Party/PartyReferenceDataDirectory/PartyReferenceDataDirectoryEntry/Decisions.cs +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/PartyReferenceDataDirectoryEntry/Decisions.cs @@ -67,10 +67,15 @@ public sealed record ExchangeDemographicsDetails( /// The Reference the caller named. /// The changes to apply. /// The UTC date of the update: a date of birth after it is refused. +/// +/// The party type of each registered entry the changes reference (1.21, ADR 0034), loaded by the handler from the write +/// side. A referenced entry missing from it is not registered. null when the changes reference no entry. +/// public sealed record UpdatePartyReferenceDetails( PartyReferenceId PartyReferenceId, PartyReferenceChanges Changes, - DateOnly Today) : PartyReferenceDataDirectoryEntryCommand; + DateOnly Today, + IReadOnlyDictionary? ReferencedParties = null) : PartyReferenceDataDirectoryEntryCommand; public sealed partial record PartyReferenceDataDirectoryEntry { @@ -79,14 +84,18 @@ public sealed partial record PartyReferenceDataDirectoryEntry /// Register is accepted once per entry: a registered entry refuses it with /// party.party-already-registered, and a party type other than or /// is party.party-type-invalid. Update needs a registered entry - /// (party.party-not-found otherwise) and always records the refresh, even when the party type is unchanged. + /// (party.party-not-found otherwise) and always records the refresh, even when the party type is unchanged; it + /// refuses to make an organisation with corporate references a person (party.corporate-references-need-organisation). /// Demographics Update and Exchange need a registered entry and its own Demographics id /// (party.behavior-qualifier-not-found otherwise). Update always records the resulting details, and only a /// change makes them unverified again. Exchange needs recorded details (party.demographics-not-recorded). /// Reference Update needs a registered entry and its own Reference id, refuses a date of birth or customer-since date /// after today, a resulting customer-since date before the date of birth, and a resulting political exposure - /// description without a foreign or domestic exposure (party.reference-invalid), and always records the - /// resulting Reference. + /// description without a foreign or domestic exposure, or a resulting company officer role without an officer + /// (party.reference-invalid). Corporate references need an organisation's entry, and each reference it sets must + /// be another registered entry of the right party type (party.corporate-references-need-organisation, + /// party.self-reference, party.referenced-party-not-registered, + /// party.referenced-party-type-mismatch). It always records the resulting Reference. /// public static Result> Decide( PartyReferenceDataDirectoryEntryCommand command, @@ -109,6 +118,9 @@ public static Result> Decid PartyReferenceDataDirectoryEntryErrors.PartyNotFound, (UpdatePartyReferenceDataDirectoryEntryDetails { PartyType: { } partyType }, _) when !Enum.IsDefined(partyType) => PartyReferenceDataDirectoryEntryErrors.PartyTypeInvalid, + (UpdatePartyReferenceDataDirectoryEntryDetails { PartyType: PartyReferenceDataDirectory.PartyType.Person }, _) + when state.CurrentReference.CurrentCorporateReferences.HasAny => + PartyReferenceErrors.CorporateReferencesNeedOrganisation, (UpdatePartyReferenceDataDirectoryEntryDetails update, { Id: { } entryId, PartyType: { } current }) => Decision.Accept(new PartyReferenceDataDirectoryEntryUpdated( entryId, @@ -144,10 +156,44 @@ public static Result> Decid (UpdatePartyReferenceDetails { Changes.CustomerSinceDate.Value: { } since } update, _) when since > update.Today => PartyReferenceErrors.CustomerSinceDateAfterToday, (UpdatePartyReferenceDetails update, { Id: { } entryId }) => - DecideReferenceUpdate(entryId, update, state.CurrentReference.Apply(update.Changes)), + DecideReferences(entryId, state.PartyType, update, state.CurrentReference.Apply(update.Changes)), _ => throw new UnreachableException($"The entry does not decide {command}."), }; + // The references to other parties (roadmap 1.21, ADR 0034): only an organisation's entry holds them, and each one the + // Update sets names another registered entry of the right party type. The handler loaded those entries from the write + // side; references the Update keeps were checked when they were recorded. + private static Result> DecideReferences( + PartyReferenceDataDirectoryEntryId entryId, + PartyType? partyType, + UpdatePartyReferenceDetails update, + PartyReferenceDetails updated) + { + if (updated.CurrentCorporateReferences.HasAny && partyType != PartyReferenceDataDirectory.PartyType.Organisation) + { + return PartyReferenceErrors.CorporateReferencesNeedOrganisation; + } + + foreach (var (field, referenced) in update.Changes.ReferencedEntries()) + { + var expected = field == PartyReferenceFields.CompanyOfficerPartyReference ? PartyReferenceDataDirectory.PartyType.Person : PartyReferenceDataDirectory.PartyType.Organisation; + PartyType? actualType = update.ReferencedParties?.TryGetValue(referenced, out var loaded) == true ? loaded : null; + var refused = (referenced == entryId, actualType) switch + { + (true, _) => PartyReferenceErrors.SelfReference(field), + (false, null) => PartyReferenceErrors.ReferencedPartyNotRegistered(field), + (false, { } actual) when actual != expected => PartyReferenceErrors.ReferencedPartyTypeMismatch(field, expected), + _ => null, + }; + if (refused is not null) + { + return refused; + } + } + + return DecideReferenceUpdate(entryId, update, updated); + } + // The rules that hold across Reference fields are checked on the resulting Reference (roadmap 1.20, ADR 0032), so a // partial update cannot leave it inconsistent with values it keeps. private static Result> DecideReferenceUpdate( @@ -160,6 +206,8 @@ private static Result> Deci PartyReferenceErrors.PoliticalExposureDescriptionWithoutExposure, ({ CustomerSince: { } since }, { } born) when since < born => PartyReferenceErrors.CustomerSinceDateBeforeDateOfBirth, + _ when updated.CurrentCorporateReferences is { CompanyOfficerRole: not null, CompanyOfficer: null } => + PartyReferenceErrors.CompanyOfficerRoleWithoutOfficer, _ => Decision.Accept( new PartyReferenceUpdated(entryId, update.PartyReferenceId, updated)), }; diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Reference/CompanyOfficerRole.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Reference/CompanyOfficerRole.cs new file mode 100644 index 0000000..f3c3ed8 --- /dev/null +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Reference/CompanyOfficerRole.cs @@ -0,0 +1,29 @@ +using System.Text.Json.Serialization; +using RimBank.SharedKernel; + +namespace RimBank.Party.PartyReferenceDataDirectory; + +/// +/// The role the company officer plays for the corporate customer: BIAN Reference CompanyOfficerRole (roadmap 1.21, +/// ADR 0034), for example Director. BIAN types it as an ISO 20022 Party, which has no role property, so it is +/// read as the role text BIAN describes: trimmed, not blank and at most 35 characters (ISO 20022 Max35Text). It is only +/// recorded with a company officer. +/// +[JsonConverter(typeof(PartyReferenceTextJsonConverter))] +public sealed record CompanyOfficerRole : IPartyReferenceText +{ + /// ISO 20022 Max35Text. + public const int MaxLength = 35; + + private CompanyOfficerRole(string value) => Value = value; + + /// + public string Value { get; } + + /// + public static Result TryCreate(string? text) => + PartyReferenceText.Read(text, MaxLength, "company officer role").Map(value => new CompanyOfficerRole(value)); + + /// + public override string ToString() => Value; +} diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Reference/PartyCorporateReferences.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Reference/PartyCorporateReferences.cs new file mode 100644 index 0000000..6a5a43e --- /dev/null +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Reference/PartyCorporateReferences.cs @@ -0,0 +1,41 @@ +using System.Text.Json.Serialization; + +namespace RimBank.Party.PartyReferenceDataDirectory; + +/// +/// The corporate customer's references to other parties of this directory, held by the entry's Reference Behavior +/// Qualifier (roadmap 1.21, ADR 0034). Each reference is the id of a registered directory entry, checked on the write side +/// when it is recorded: the corporate customer and its legal entity are organisations, and the officer is a person. They +/// are recorded only on an organisation's entry. BIAN gives one object per field, so there is one officer. Each part is +/// optional: an unknown one is null. +/// +/// BIAN CorporateCustomerReference.PartyReference: the company. +/// BIAN CorporateCustomerLegalEntityReference.PartyReference: the legal entity. +/// BIAN CompanyOfficerReference.PartyReference: the identified company officer. +/// BIAN CompanyOfficerRole: the officer's role, only with an officer. +public sealed record PartyCorporateReferences( + PartyReferenceDataDirectoryEntryId? CorporateCustomer, + PartyReferenceDataDirectoryEntryId? LegalEntity, + PartyReferenceDataDirectoryEntryId? CompanyOfficer, + CompanyOfficerRole? CompanyOfficerRole) +{ + /// No reference recorded. + public static PartyCorporateReferences Empty { get; } = new(null, null, null, null); + + /// Whether any part is recorded. Computed, so it is not stored. + [JsonIgnore] + public bool HasAny => this != Empty; + + /// The references after a partial update: a part the changes leave out keeps its value. + /// The parsed changes. + /// The resulting references. + public PartyCorporateReferences Apply(PartyReferenceChanges changes) + { + ArgumentNullException.ThrowIfNull(changes); + return new PartyCorporateReferences( + changes.CorporateCustomer.ApplyTo(CorporateCustomer), + changes.LegalEntity.ApplyTo(LegalEntity), + changes.CompanyOfficer.ApplyTo(CompanyOfficer), + changes.CompanyOfficerRole.ApplyTo(CompanyOfficerRole)); + } +} diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Reference/PartyReferenceChanges.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Reference/PartyReferenceChanges.cs index a215cd1..2efd54b 100644 --- a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Reference/PartyReferenceChanges.cs +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Reference/PartyReferenceChanges.cs @@ -28,6 +28,10 @@ namespace RimBank.Party.PartyReferenceDataDirectory; /// The change of the customer-since date (1.20). /// The change of the government-issued document (1.20). /// The change of the document directory reference (1.20). +/// The change of the corporate customer reference (1.21). +/// The change of the legal entity reference (1.21). +/// The change of the company officer reference (1.21). +/// The change of the company officer's role (1.21). public sealed record PartyReferenceChanges( PartyIdentifierChange? TaxIdentificationNumber, PartyIdentifierChange? NationalRegistrationNumber, @@ -49,8 +53,25 @@ public sealed record PartyReferenceChanges( PartyReferenceChange? PoliticalExposureDescription = null, PartyReferenceChange? CustomerSinceDate = null, PartyReferenceChange? GovernmentIssuedDocument = null, - PartyReferenceChange? DocumentDirectoryEntry = null) + PartyReferenceChange? DocumentDirectoryEntry = null, + PartyReferenceChange? CorporateCustomer = null, + PartyReferenceChange? LegalEntity = null, + PartyReferenceChange? CompanyOfficer = null, + PartyReferenceChange? CompanyOfficerRole = null) { + /// + /// The directory entries this Update references (1.21, ADR 0034), each with the BIAN path that names it: the ones it + /// sets, never the ones it keeps or clears. The handler loads them through the write port so the decision can check + /// them. + /// + /// The BIAN path and the entry id of each reference set, in BIAN order. + public IReadOnlyList<(string Field, PartyReferenceDataDirectoryEntryId EntryId)> ReferencedEntries() => + [ + .. Referenced(PartyReferenceFields.CorporateCustomerPartyReference, CorporateCustomer), + .. Referenced(PartyReferenceFields.LegalEntityPartyReference, LegalEntity), + .. Referenced(PartyReferenceFields.CompanyOfficerPartyReference, CompanyOfficer), + ]; + /// /// The earliest date of birth accepted (inclusive, ADR 0029): an earlier one is almost always a typo. The latest is /// today, checked by the decision because it needs the handler's clock. @@ -121,7 +142,11 @@ public static Result Create(PartyReferenceInput input, IR fieldErrors), ReadDocument(input.GovernmentIssuedDocument, fieldErrors), ReadText( - input.DocumentDirectoryEntryIdentification, PartyReferenceFields.DocumentDirectoryEntryIdentification, fieldErrors)); + input.DocumentDirectoryEntryIdentification, PartyReferenceFields.DocumentDirectoryEntryIdentification, fieldErrors), + ReadEntry(input.CorporateCustomerReference, PartyReferenceFields.CorporateCustomerPartyReference, fieldErrors), + ReadEntry(input.CorporateCustomerLegalEntityReference, PartyReferenceFields.LegalEntityPartyReference, fieldErrors), + ReadEntry(input.CompanyOfficerReference, PartyReferenceFields.CompanyOfficerPartyReference, fieldErrors), + ReadText(input.CompanyOfficerRole, PartyReferenceFields.CompanyOfficerRole, fieldErrors)); return fieldErrors.Count switch { @@ -231,6 +256,40 @@ private static IReadOnlyList NotSupportedMessages(string field) => return new PartyReferenceChange(code.Value); } + private static IEnumerable<(string Field, PartyReferenceDataDirectoryEntryId EntryId)> Referenced( + string field, + PartyReferenceChange? change) => + change?.Value switch + { + { } entryId => [(field, entryId)], + null => [], + }; + + private static PartyReferenceChange? ReadEntry( + string? text, + string field, + Dictionary> fieldErrors) + { + if (text is null) + { + return null; + } + + if (string.IsNullOrWhiteSpace(text)) + { + return new PartyReferenceChange(null); + } + + var entryId = PartyReferenceDataDirectoryEntryId.TryCreate(text.Trim()); + if (entryId.IsFailure) + { + fieldErrors[field] = ["The party reference must be the PartyReferenceDataDirectoryEntryId returned by Register."]; + return null; + } + + return new PartyReferenceChange(entryId.Value); + } + private static PartyReferenceChange? ReadDocument( PartyDocumentInput? document, Dictionary> fieldErrors) diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Reference/PartyReferenceDetails.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Reference/PartyReferenceDetails.cs index 310035d..8e08afe 100644 --- a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Reference/PartyReferenceDetails.cs +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Reference/PartyReferenceDetails.cs @@ -5,8 +5,8 @@ namespace RimBank.Party.PartyReferenceDataDirectory; /// /// The record of the entry's Reference Behavior Qualifier, an entity of the entry (ADR 0024), shared by the entry's state /// and its view. Roadmap 1.10 records the party identifiers, 1.18 the names, date of birth, nationality and residency, -/// 1.19 the postal addresses and contact points, and 1.20 the declared legal standing and documents (ADR 0029, ADR 0032). -/// The references to other parties wait for 1.21. +/// 1.19 the postal addresses and contact points, 1.20 the declared legal standing and documents, and 1.21 the corporate +/// customer's references to other parties (ADR 0029, ADR 0032, ADR 0034). /// /// /// The parts added after 1.10 are null when nothing is recorded, so a Reference stored before them (an event or a @@ -29,6 +29,9 @@ namespace RimBank.Party.PartyReferenceDataDirectory; /// The party's declared government-issued document and document directory reference (1.20), or null when none is /// recorded. /// +/// +/// The corporate customer, legal entity, company officer and officer role (1.21), or null when none is recorded. +/// public sealed record PartyReferenceDetails( PartyIdentifiers Identifiers, PartyNames? Names = null, @@ -37,8 +40,13 @@ public sealed record PartyReferenceDetails( PartyAddresses? Addresses = null, PartyContactPoints? ContactPoints = null, PartyLegalStanding? LegalStanding = null, - PartyDocuments? Documents = null) + PartyDocuments? Documents = null, + PartyCorporateReferences? CorporateReferences = null) { + /// The corporate customer's references: empty when none is recorded. Computed, so it is not stored. + [JsonIgnore] + public PartyCorporateReferences CurrentCorporateReferences => CorporateReferences ?? PartyCorporateReferences.Empty; + /// The party's declared legal standing: empty when none is recorded. Computed, so it is not stored. [JsonIgnore] public PartyLegalStanding CurrentLegalStanding => LegalStanding ?? PartyLegalStanding.Empty; @@ -78,6 +86,7 @@ public PartyReferenceDetails Apply(PartyReferenceChanges changes) var contactPoints = CurrentContactPoints.Apply(changes); var legalStanding = CurrentLegalStanding.Apply(changes); var documents = CurrentDocuments.Apply(changes); + var corporateReferences = CurrentCorporateReferences.Apply(changes); return new PartyReferenceDetails( Identifiers.Apply(changes), names.HasAny ? names : null, @@ -86,6 +95,7 @@ public PartyReferenceDetails Apply(PartyReferenceChanges changes) addresses.HasAny ? addresses : null, contactPoints.HasAny ? contactPoints : null, legalStanding.HasAny ? legalStanding : null, - documents.HasAny ? documents : null); + documents.HasAny ? documents : null, + corporateReferences.HasAny ? corporateReferences : null); } } diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Reference/PartyReferenceErrors.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Reference/PartyReferenceErrors.cs index 9031e95..787eced 100644 --- a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Reference/PartyReferenceErrors.cs +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Reference/PartyReferenceErrors.cs @@ -2,7 +2,7 @@ namespace RimBank.Party.PartyReferenceDataDirectory; -/// The Reference Behavior Qualifier's business errors; their codes are documented in ADR 0024 and ADR 0029. +/// The Reference Behavior Qualifier's business errors; their codes are documented in ADR 0024, ADR 0029 and ADR 0034. public static class PartyReferenceErrors { /// The code of and . @@ -85,4 +85,50 @@ public static Error ReferenceFieldsNotSupported(IReadOnlyDictionary + /// The resulting Reference has a company officer role but no company officer (400, roadmap 1.21, ADR 0034): + /// party.reference-invalid naming . + /// + public static Error CompanyOfficerRoleWithoutOfficer { get; } = ReferenceInvalid(new Dictionary> + { + [PartyReferenceFields.CompanyOfficerRole] = + [ + "A company officer role needs a CompanyOfficerReference; clear the role in the same request when the officer is cleared.", + ], + }); + + /// + /// The resulting Reference has corporate or officer references on an entry that is not an organisation, or an entry + /// Update makes an organisation with such references a person (422, roadmap 1.21, ADR 0034). + /// + public static Error CorporateReferencesNeedOrganisation { get; } = Error.BusinessRule( + "party.corporate-references-need-organisation", + "Corporate customer, legal entity and company officer references are recorded only on an organisation's entry; " + + "clear them before the party type becomes Person."); + + /// A reference names the entry it is recorded on (422, roadmap 1.21, ADR 0034). + /// The BIAN path of the reference, for example CompanyOfficerReference.PartyReference. + /// The party.self-reference error, whose message names the path. + public static Error SelfReference(string field) => Error.BusinessRule( + "party.self-reference", + $"{field} names the party's own entry; a party cannot reference itself."); + + /// A reference names no registered entry of this directory (422, roadmap 1.21, ADR 0034). + /// The BIAN path of the reference. + /// The party.referenced-party-not-registered error, whose message names the path. + public static Error ReferencedPartyNotRegistered(string field) => Error.BusinessRule( + "party.referenced-party-not-registered", + $"{field} is not registered in the directory; register it first."); + + /// + /// A reference names an entry of the wrong party type: the corporate customer and the legal entity are organisations, + /// and the company officer is a person (422, roadmap 1.21, ADR 0034). + /// + /// The BIAN path of the reference. + /// The party type the reference needs. + /// The party.referenced-party-type-mismatch error, whose message names the path and the type. + public static Error ReferencedPartyTypeMismatch(string field, PartyType expected) => Error.BusinessRule( + "party.referenced-party-type-mismatch", + $"{field} must name a party of type {expected}."); } diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Reference/PartyReferenceFields.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Reference/PartyReferenceFields.cs index 5c0e4cb..37c4dc1 100644 --- a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Reference/PartyReferenceFields.cs +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Reference/PartyReferenceFields.cs @@ -117,6 +117,33 @@ public static class PartyReferenceFields public const string DocumentDirectoryEntryIdentification = DocumentDirectoryEntryInstanceReference + "." + DocumentDirectoryEntryIdentificationPart; + /// BIAN CorporateCustomerReference (1.21), an Involvedparty object. + public const string CorporateCustomerReference = "CorporateCustomerReference"; + + /// BIAN CorporateCustomerLegalEntityReference (1.21), an Involvedparty object. + public const string CorporateCustomerLegalEntityReference = "CorporateCustomerLegalEntityReference"; + + /// BIAN CompanyOfficerReference (1.21), an Involvedparty object. + public const string CompanyOfficerReference = "CompanyOfficerReference"; + + /// BIAN CompanyOfficerRole (1.21), read as the role text (ADR 0034). + public const string CompanyOfficerRole = "CompanyOfficerRole"; + + /// The part of a BIAN Involvedparty object RimBank records: the referenced directory entry. + public const string PartyReferencePart = "PartyReference"; + + /// The part of a BIAN Involvedparty object RimBank refuses: the role is in . + public const string InvolvementReferencePart = "InvolvementReference"; + + /// BIAN CorporateCustomerReference.PartyReference. + public const string CorporateCustomerPartyReference = CorporateCustomerReference + "." + PartyReferencePart; + + /// BIAN CorporateCustomerLegalEntityReference.PartyReference. + public const string LegalEntityPartyReference = CorporateCustomerLegalEntityReference + "." + PartyReferencePart; + + /// BIAN CompanyOfficerReference.PartyReference. + public const string CompanyOfficerPartyReference = CompanyOfficerReference + "." + PartyReferencePart; + /// The only part of a BIAN Country object RimBank records. public const string CountryCodePart = "Code"; @@ -128,13 +155,9 @@ public static class PartyReferenceFields /// /// Every top-level BIAN UpdateReference field RimBank does not record yet, with the roadmap phase that will - /// record it (ADR 0029). The four references to other parties wait for the Associations BQ (1.11, ADR 0032). + /// record it (ADR 0029). Empty since 1.21, which recorded the last four (ADR 0034); a later BIAN release that adds a + /// field stages it here. /// - public static FrozenDictionary Staged { get; } = new Dictionary(StringComparer.Ordinal) - { - ["CorporateCustomerReference"] = "1.21", - ["CorporateCustomerLegalEntityReference"] = "1.21", - ["CompanyOfficerReference"] = "1.21", - ["CompanyOfficerRole"] = "1.21", - }.ToFrozenDictionary(StringComparer.Ordinal); + public static FrozenDictionary Staged { get; } = + new Dictionary(StringComparer.Ordinal).ToFrozenDictionary(StringComparer.Ordinal); } diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Reference/PartyReferenceInput.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Reference/PartyReferenceInput.cs index d0e41bf..20c380f 100644 --- a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Reference/PartyReferenceInput.cs +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Reference/PartyReferenceInput.cs @@ -31,6 +31,13 @@ namespace RimBank.Party.PartyReferenceDataDirectory; /// BIAN DocumentDirectoryEntryInstanceReference.DocumentDirectoryEntryIdentification (1.20). An object with no /// value is sent as blank. /// +/// +/// BIAN CorporateCustomerReference.PartyReference (1.21, ADR 0034): a directory entry id. An object with no value +/// is sent as blank. +/// +/// BIAN CorporateCustomerLegalEntityReference.PartyReference (1.21). +/// BIAN CompanyOfficerReference.PartyReference (1.21). +/// BIAN CompanyOfficerRole (1.21): the role text, for example Director. public sealed record PartyReferenceInput( string? TaxIdentificationNumber = null, string? NationalRegistrationNumber = null, @@ -52,7 +59,11 @@ public sealed record PartyReferenceInput( string? PoliticalExposureDescription = null, string? CustomerSinceDate = null, PartyDocumentInput? GovernmentIssuedDocument = null, - string? DocumentDirectoryEntryIdentification = null) + string? DocumentDirectoryEntryIdentification = null, + string? CorporateCustomerReference = null, + string? CorporateCustomerLegalEntityReference = null, + string? CompanyOfficerReference = null, + string? CompanyOfficerRole = null) { /// Nothing sent: every value is kept. public static PartyReferenceInput None { get; } = new(); diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Reference/UpdatePartyReferenceHandler.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Reference/UpdatePartyReferenceHandler.cs index 750a3e7..b42e793 100644 --- a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Reference/UpdatePartyReferenceHandler.cs +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Reference/UpdatePartyReferenceHandler.cs @@ -8,7 +8,8 @@ public static class UpdatePartyReferenceHandler { /// /// Loads the entry; checks that it exists, that the Reference id is its own and that the caller's expected version - /// is current; decides the Update and appends it with that expected version. + /// is current; loads each other entry the changes reference through the write port, never a view (roadmap 1.21, + /// ADR 0034); decides the Update and appends it with that expected version. /// /// The command. /// The context's write port. @@ -16,7 +17,8 @@ public static class UpdatePartyReferenceHandler /// Cancels the load. /// /// The acknowledgement built from the decided state, party.party-not-found, - /// party.behavior-qualifier-not-found, party.version-conflict or the decision's error. + /// party.behavior-qualifier-not-found, party.version-conflict or the decision's error (including + /// party.referenced-party-not-registered and party.referenced-party-type-mismatch). /// public static async Task> HandleAsync( UpdatePartyReference command, @@ -30,6 +32,9 @@ public static async Task> HandleAsync( var history = await directory.LoadEntryAsync(command.EntryId, cancellationToken); var state = history.Aggregate(PartyReferenceDataDirectoryEntry.Initial, PartyReferenceDataDirectoryEntry.Evolve); + var referencedParties = state.IsRegistered && history.Count == command.ExpectedVersion + ? await LoadReferencedPartiesAsync(directory, command, cancellationToken) + : null; return (state.IsRegistered, state.PartyReferenceId == command.PartyReferenceId, history.Count == command.ExpectedVersion) switch { @@ -41,7 +46,8 @@ public static async Task> HandleAsync( new UpdatePartyReferenceDetails( command.PartyReferenceId, command.Changes, - DateOnly.FromDateTime(time.GetUtcNow().UtcDateTime)), + DateOnly.FromDateTime(time.GetUtcNow().UtcDateTime), + referencedParties), state) .Map(events => { @@ -56,4 +62,31 @@ public static async Task> HandleAsync( }), }; } + + // The party type of each registered entry the changes set a reference to. The entry itself is not loaded again: the + // decision refuses a reference to it. An entry that is not registered (an unknown id, or the id of another stream type, + // which loads no entry events) is left out, so the decision answers it as a value. + private static async Task> LoadReferencedPartiesAsync( + IPartyDirectory directory, + UpdatePartyReference command, + CancellationToken cancellationToken) + { + var parties = new Dictionary(); + foreach (var entryId in command.Changes.ReferencedEntries().Select(reference => reference.EntryId).Distinct()) + { + if (entryId == command.EntryId) + { + continue; + } + + var referenced = (await directory.LoadEntryAsync(entryId, cancellationToken)) + .Aggregate(PartyReferenceDataDirectoryEntry.Initial, PartyReferenceDataDirectoryEntry.Evolve); + if (referenced is { IsRegistered: true, PartyType: { } partyType }) + { + parties[entryId] = partyType; + } + } + + return parties; + } } diff --git a/src/RimBank.Host/RimBank.Host.http b/src/RimBank.Host/RimBank.Host.http index 39f27c6..cc0d540 100644 --- a/src/RimBank.Host/RimBank.Host.http +++ b/src/RimBank.Host/RimBank.Host.http @@ -100,7 +100,6 @@ Authorization: Bearer {{token.response.body.$.access_token}} ### A description without an exposure is refused on the resulting Reference: 400 application/problem+json with # "errorCode": "party.reference-invalid" and errors["PoliticalExposureDescriptionRecord"]. Nothing is stored. -# CompanyOfficerRole instead would be 400 party.reference-field-not-supported, naming roadmap phase 1.21. PUT {{host}}/PartyReferenceDataDirectory/{{register.response.body.$.PartyReferenceDataDirectoryEntryId}}/Reference/{{register.response.body.$.ReferenceId}}/Update Authorization: Bearer {{token.response.body.$.access_token}} Content-Type: application/json @@ -146,3 +145,49 @@ If-Match: "1" # owning entry finds it: the second party's id in the path is 404 party.association-not-found. GET {{host}}/PartyReferenceDataDirectory/{{register.response.body.$.PartyReferenceDataDirectoryEntryId}}/Associations/{{association.response.body.$.AssociationsId}}/Retrieve Authorization: Bearer {{token.response.body.$.access_token}} + +### Reference BQ (roadmap 1.21, ADR 0034): register the group the first party (an organisation since its Update) belongs to. +# @name group +POST {{host}}/PartyReferenceDataDirectory/Register +Authorization: Bearer {{token.response.body.$.access_token}} +Content-Type: application/json +Idempotency-Key: {{$guid}} + +{ "PartyType": "Organisation" } + +### Link the first party to its group (an organisation) and its officer (the second party, a person). Each reference is +# loaded on the write side: it must be registered (422 party.referenced-party-not-registered), not the party itself +# (422 party.self-reference), and of the right type (422 party.referenced-party-type-mismatch). Answers 200 with ETag +# "4", the role trimmed. +PUT {{host}}/PartyReferenceDataDirectory/{{register.response.body.$.PartyReferenceDataDirectoryEntryId}}/Reference/{{register.response.body.$.ReferenceId}}/Update +Authorization: Bearer {{token.response.body.$.access_token}} +Content-Type: application/json +Idempotency-Key: {{$guid}} +If-Match: "3" + +{ + "CorporateCustomerReference": { "PartyReference": "{{group.response.body.$.PartyReferenceDataDirectoryEntryId}}" }, + "CorporateCustomerLegalEntityReference": { "PartyReference": "{{group.response.body.$.PartyReferenceDataDirectoryEntryId}}" }, + "CompanyOfficerReference": { "PartyReference": "{{associate.response.body.$.PartyReferenceDataDirectoryEntryId}}" }, + "CompanyOfficerRole": " Director " +} + +### The group as the officer: 422 application/problem+json, "errorCode": "party.referenced-party-type-mismatch", and a +# detail naming CompanyOfficerReference.PartyReference. Nothing is stored. +PUT {{host}}/PartyReferenceDataDirectory/{{register.response.body.$.PartyReferenceDataDirectoryEntryId}}/Reference/{{register.response.body.$.ReferenceId}}/Update +Authorization: Bearer {{token.response.body.$.access_token}} +Content-Type: application/json +Idempotency-Key: {{$guid}} +If-Match: "4" + +{ "CompanyOfficerReference": { "PartyReference": "{{group.response.body.$.PartyReferenceDataDirectoryEntryId}}" } } + +### An organisation with corporate references cannot become a person: 422 party.corporate-references-need-organisation. +# Clear the four references first. +PUT {{host}}/PartyReferenceDataDirectory/{{register.response.body.$.PartyReferenceDataDirectoryEntryId}}/Update +Authorization: Bearer {{token.response.body.$.access_token}} +Content-Type: application/json +Idempotency-Key: {{$guid}} +If-Match: "4" + +{ "PartyType": "Person" } diff --git a/tests/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql.Tests/PartyReferenceRoundTripTests.cs b/tests/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql.Tests/PartyReferenceRoundTripTests.cs index 1597fae..3c4492f 100644 --- a/tests/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql.Tests/PartyReferenceRoundTripTests.cs +++ b/tests/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql.Tests/PartyReferenceRoundTripTests.cs @@ -116,6 +116,39 @@ await host.Store.RebuildViewAsync( folded.Reference.ShouldBe(_completeDetails); } + [Fact] + public async Task Corporate_references_are_checked_on_the_write_side_stored_as_ids_and_rebuilt_into_the_view() + { + await using var host = await server.StartHostAsync(); + var company = await RegisterAsync(host.Bus); + var group = await RegisterAsync(host.Bus); + var officer = (await host.Bus.InvokeAsync>(new RegisterParty(PartyType.Person, NewKey()), Cancellation)).Value; + var references = new PartyCorporateReferences(group.EntryId, group.EntryId, officer.EntryId, CompanyOfficerRole.TryCreate("Director").Value); + + var updated = (await UpdateAsync(host.Bus, company, 1, NewKey(), PartyReferenceChanges.None with + { + CorporateCustomer = new(references.CorporateCustomer), + LegalEntity = new(references.LegalEntity), + CompanyOfficer = new(references.CompanyOfficer), + CompanyOfficerRole = new(references.CompanyOfficerRole), + })).Value; + var mismatch = await UpdateAsync(host.Bus, company, 2, NewKey(), PartyReferenceChanges.None with { CompanyOfficer = new(group.EntryId) }); + await host.Store.RebuildViewAsync( + ViewRegistration.ProjectionName(), + TimeSpan.FromSeconds(60), + Cancellation); + var rebuilt = await host.Enquiry.FindEntryAsync(company.EntryId, Cancellation); + + updated.Reference.CorporateReferences.ShouldBe(references); + mismatch.Error.Code.ShouldBe("party.referenced-party-type-mismatch"); + rebuilt.ShouldNotBeNull().Version.ShouldBe(2); + rebuilt.CurrentReference.CurrentCorporateReferences.ShouldBe(references); + (await host.ScalarAsync( + $"SELECT data #>> '{{Details,CorporateReferences,CompanyOfficer}}' FROM {Schema}.mt_events " + + $"WHERE stream_id = '{company.EntryId.Value}' AND version = 2")) + .ShouldBe(officer.EntryId.ToString()); + } + [Fact] public async Task A_political_exposure_description_without_exposure_appends_nothing() { diff --git a/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/Demographics/DemographicsScenarios.cs b/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/Demographics/DemographicsScenarios.cs index 1fa9769..a6a7ed3 100644 --- a/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/Demographics/DemographicsScenarios.cs +++ b/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/Demographics/DemographicsScenarios.cs @@ -28,11 +28,11 @@ public static string Url(Guid entryId, Guid demographicsId, string operation) => public static string Url(string entryId, string demographicsId, string operation) => $"/PartyReferenceDataDirectory/{entryId}/Demographics/{demographicsId}/{operation}"; - public static async Task RegisterAsync(PartyApiHost host) + public static async Task RegisterAsync(PartyApiHost host, string partyType = "Person") { var result = await host.Alba.Scenario(_ => { - _.Post.Text("""{ "PartyType": "Person" }""").ToUrl(RegisterPartyEndpoint.Route); + _.Post.Text($$"""{ "PartyType": "{{partyType}}" }""").ToUrl(RegisterPartyEndpoint.Route); _.WithRequestHeader(HeaderNames.ContentType, "application/json"); _.WithRequestHeader(HeaderNames.Authorization, "Bearer " + TestTokens.Issue()); _.WithRequestHeader("Idempotency-Key", Guid.CreateVersion7().ToString()); diff --git a/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/Reference/CorporateReferencesEndpointTests.cs b/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/Reference/CorporateReferencesEndpointTests.cs new file mode 100644 index 0000000..d623f6e --- /dev/null +++ b/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/Reference/CorporateReferencesEndpointTests.cs @@ -0,0 +1,128 @@ +using Alba; +using Microsoft.Net.Http.Headers; +using static RimBank.Party.PartyReferenceDataDirectory.Api.Tests.AssociationScenarios; +using static RimBank.Party.PartyReferenceDataDirectory.Api.Tests.DemographicsScenarios; +using static RimBank.Party.PartyReferenceDataDirectory.Api.Tests.ReferenceScenarios; + +namespace RimBank.Party.PartyReferenceDataDirectory.Api.Tests; + +// Roadmap 1.21: the corporate and officer references over HTTP. An organisation's Reference names other registered +// entries (two organisations and a person), checked on the write side; a broken rule is a 422 Problem Details and nothing +// is stored; Retrieve shows what Update recorded (specs/tech-stack.md §5, ADR 0034). +public sealed class CorporateReferencesEndpointTests(PostgresqlServer server) +{ + [Fact] + public async Task An_organisation_records_its_references_and_retrieve_shows_them() + { + await using var host = await server.StartHostAsync(); + var company = await RegisterAsync(host, "Organisation"); + var group = await RegisterAsync(host, "Organisation"); + var officer = await RegisterAsync(host); + + var updated = await PutReferenceOkAsync( + host, + UpdateUrl(company), + References(group.PartyReferenceDataDirectoryEntryId, officer.PartyReferenceDataDirectoryEntryId), + "\"1\"", + "\"2\""); + + var expected = new PartyReferenceResponse(company.PartyReferenceDataDirectoryEntryId, company.ReferenceId, null, null) with + { + CorporateCustomerReference = new InvolvedPartyModel { PartyReference = group.PartyReferenceDataDirectoryEntryId.ToString() }, + CorporateCustomerLegalEntityReference = new InvolvedPartyModel { PartyReference = group.PartyReferenceDataDirectoryEntryId.ToString() }, + CompanyOfficerReference = new InvolvedPartyModel { PartyReference = officer.PartyReferenceDataDirectoryEntryId.ToString() }, + CompanyOfficerRole = "Director", + }; + updated.ShouldBe(expected); + var result = await host.Alba.Scenario(_ => + { + Get(_, RetrieveUrl(company)); + _.StatusCodeShouldBeOk(); + _.Header(HeaderNames.ETag).SingleValueShouldEqual("\"2\""); + }); + (await result.ReadAsJsonAsync()).ShouldBe(expected); + } + + [Fact] + public async Task A_reference_to_an_entry_that_is_not_registered_is_a_422_problem_and_nothing_is_stored() + { + await using var host = await server.StartHostAsync(); + var company = await RegisterAsync(host, "Organisation"); + + var problem = await PutProblemAsync( + host, + UpdateUrl(company), + $$"""{ "CorporateCustomerReference": { "PartyReference": "{{Guid.CreateVersion7()}}" } }""", + "\"1\"", + 422); + + problem.GetProperty("errorCode").GetString().ShouldBe("party.referenced-party-not-registered"); + problem.GetProperty("detail").GetString().ShouldNotBeNull().ShouldStartWith("CorporateCustomerReference.PartyReference"); + (await host.ScalarAsync( + $"SELECT count(*) FROM party_reference_data_directory.mt_events WHERE stream_id = '{company.PartyReferenceDataDirectoryEntryId}'")) + .ShouldBe(1); + } + + [Fact] + public async Task A_person_as_the_corporate_customer_is_a_422_type_mismatch() + { + await using var host = await server.StartHostAsync(); + var company = await RegisterAsync(host, "Organisation"); + var person = await RegisterAsync(host); + + var problem = await PutProblemAsync( + host, + UpdateUrl(company), + $$"""{ "CorporateCustomerReference": { "PartyReference": "{{person.PartyReferenceDataDirectoryEntryId}}" } }""", + "\"1\"", + 422); + + problem.GetProperty("errorCode").GetString().ShouldBe("party.referenced-party-type-mismatch"); + } + + [Fact] + public async Task A_malformed_party_reference_is_a_400_naming_its_path() + { + await using var host = await server.StartHostAsync(); + var company = await RegisterAsync(host, "Organisation"); + + var problem = await PutProblemAsync(host, UpdateUrl(company), """{ "CompanyOfficerReference": { "PartyReference": "ACME-1" } }""", "\"1\"", 400); + + problem.GetProperty("errorCode").GetString().ShouldBe("party.reference-invalid"); + problem.GetProperty("errors").EnumerateObject().Select(field => field.Name).ShouldBe(["CompanyOfficerReference.PartyReference"]); + } + + [Fact] + public async Task An_organisation_with_references_cannot_become_a_person() + { + await using var host = await server.StartHostAsync(); + var company = await RegisterAsync(host, "Organisation"); + var group = await RegisterAsync(host, "Organisation"); + var officer = await RegisterAsync(host); + await PutReferenceOkAsync( + host, + UpdateUrl(company), + References(group.PartyReferenceDataDirectoryEntryId, officer.PartyReferenceDataDirectoryEntryId), + "\"1\"", + "\"2\""); + + var problem = await PutProblemAsync( + host, + $"/PartyReferenceDataDirectory/{company.PartyReferenceDataDirectoryEntryId}/Update", + """{ "PartyType": "Person" }""", + "\"2\"", + 422); + + problem.GetProperty("errorCode").GetString().ShouldBe("party.corporate-references-need-organisation"); + } + + private static string References(Guid organisation, Guid person) => + $$""" + { + "CorporateCustomerReference": { "PartyReference": "{{organisation}}" }, + "CorporateCustomerLegalEntityReference": { "PartyReference": "{{organisation}}" }, + "CompanyOfficerReference": { "PartyReference": "{{person}}" }, + "CompanyOfficerRole": " Director " + } + """; +} diff --git a/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/Reference/PartyReferenceRequestTests.cs b/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/Reference/PartyReferenceRequestTests.cs index a8e56f3..cc2d1c3 100644 --- a/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/Reference/PartyReferenceRequestTests.cs +++ b/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/Reference/PartyReferenceRequestTests.cs @@ -119,12 +119,43 @@ public void An_empty_body_changes_nothing() => Read("{}").ToCommand(_entryId, _referenceId, 1, _key).Value.Changes.ShouldBe(PartyReferenceChanges.None); [Fact] - public void Staged_fields_and_unrecorded_parts_are_unsupported_whatever_their_case() + public void The_corporate_and_officer_references_are_read_from_their_party_reference() => + Read( + $$""" + { + "CorporateCustomerReference": { "PartyReference": "{{_companyId}}" }, + "CorporateCustomerLegalEntityReference": { "PartyReference": "{{_companyId}}" }, + "CompanyOfficerReference": { "PartyReference": "{{_officerId}}" }, + "CompanyOfficerRole": " Director " + } + """) + .ToCommand(_entryId, _referenceId, 1, _key) + .Value.Changes.ShouldBe(PartyReferenceChanges.None with + { + CorporateCustomer = new(_companyId), + LegalEntity = new(_companyId), + CompanyOfficer = new(_officerId), + CompanyOfficerRole = new(CompanyOfficerRole.TryCreate("Director").Value), + }); + + [Fact] + public void Empty_references_and_an_empty_role_object_clear_them() => + Read("""{ "CorporateCustomerReference": {}, "CompanyOfficerReference": { "PartyReference": "" }, "CompanyOfficerRole": {} }""") + .ToCommand(_entryId, _referenceId, 1, _key) + .Value.Changes.ShouldBe(PartyReferenceChanges.None with + { + CorporateCustomer = new(null), + CompanyOfficer = new(null), + CompanyOfficerRole = new(null), + }); + + [Fact] + public void Unrecorded_parts_are_unsupported_whatever_the_case_of_their_object() { var request = Read( """ { - "companyofficerreference": { "PartyReference": "x" }, + "companyofficerreference": { "PartyReference": "x", "InvolvementReference": "Director" }, "CompanyOfficerRole": { "PartyRole": "Director" }, "GovernmentIssuedIdentityReference": { "OtherIdentification": "X1", "Declaration": null }, "PartyLegalEntityReference": { "ContactPoint": "x" }, @@ -136,8 +167,8 @@ public void Staged_fields_and_unrecorded_parts_are_unsupported_whatever_their_ca request.UnsupportedFields().ShouldBe( [ - "CompanyOfficerReference", - "CompanyOfficerRole", + "CompanyOfficerReference.InvolvementReference", + "CompanyOfficerRole.PartyRole", "GovernmentIssuedIdentityReference.OtherIdentification", "PartyLegalEntityReference.ContactPoint", "Nationality.Citizen", @@ -216,6 +247,12 @@ public void An_unsupported_field_makes_the_command_a_validation_error() => Read("""{ "Nationality": { "Code": "FR", "Citizen": "Jane" } }""").ToCommand(_entryId, _referenceId, 1, _key) .Error.Code.ShouldBe("party.reference-field-not-supported"); + private static readonly PartyReferenceDataDirectoryEntryId _companyId = + PartyReferenceDataDirectoryEntryId.From(Guid.CreateVersion7(new DateTimeOffset(2026, 11, 8, 9, 1, 0, TimeSpan.Zero))); + + private static readonly PartyReferenceDataDirectoryEntryId _officerId = + PartyReferenceDataDirectoryEntryId.From(Guid.CreateVersion7(new DateTimeOffset(2026, 11, 8, 9, 2, 0, TimeSpan.Zero))); + private static UpdatePartyReferenceRequest Read(string json) => JsonSerializer.Deserialize(json, JsonSerializerOptions.Web).ShouldNotBeNull(); } diff --git a/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/Reference/ReferenceLogPrivacyTests.cs b/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/Reference/ReferenceLogPrivacyTests.cs index 4ebedc9..333a4a3 100644 --- a/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/Reference/ReferenceLogPrivacyTests.cs +++ b/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/Reference/ReferenceLogPrivacyTests.cs @@ -67,4 +67,43 @@ await host.Alba.Scenario(_ => logs.Containing(value).Select(entry => $"{entry.Level} {entry.Category}").ShouldBeEmpty($"'{value}' was logged"); } } + + // Roadmap 1.21 (ADR 0034): who the company's officer is, and in which role, is personal data too. Neither the referenced + // entries nor the role reach the logs, on success, on a refused reference or on Retrieve. + [Fact] + public async Task No_submitted_corporate_reference_or_role_is_logged() + { + var logs = new CapturedLogs(); + await using var host = await server.StartHostAsync(logs: logs); + var company = await RegisterAsync(host, "Organisation"); + var group = await RegisterAsync(host, "Organisation"); + var officer = await RegisterAsync(host); + var references = $$""" + { + "CorporateCustomerReference": { "PartyReference": "{{group.PartyReferenceDataDirectoryEntryId}}" }, + "CompanyOfficerReference": { "PartyReference": "{{officer.PartyReferenceDataDirectoryEntryId}}" }, + "CompanyOfficerRole": "Chief Risk Officer" + } + """; + + await PutReferenceOkAsync(host, UpdateUrl(company), references, "\"1\"", "\"2\""); + await PutProblemAsync( + host, + UpdateUrl(company), + $$"""{ "CompanyOfficerReference": { "PartyReference": "{{group.PartyReferenceDataDirectoryEntryId}}" } }""", + "\"2\"", + 422); + await host.Alba.Scenario(_ => + { + _.Get.Url(RetrieveUrl(company)); + _.WithRequestHeader(HeaderNames.Authorization, "Bearer " + TestTokens.Issue()); + _.StatusCodeShouldBeOk(); + }); + + logs.Containing($"/Reference/{company.ReferenceId}/Update").ShouldNotBeEmpty(); + foreach (var value in new[] { group.PartyReferenceDataDirectoryEntryId.ToString(), officer.PartyReferenceDataDirectoryEntryId.ToString(), "Chief Risk Officer" }) + { + logs.Containing(value).Select(entry => $"{entry.Level} {entry.Category}").ShouldBeEmpty($"'{value}' was logged"); + } + } } diff --git a/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/Reference/UpdatePartyReferenceEndpointTests.cs b/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/Reference/UpdatePartyReferenceEndpointTests.cs index 2e1a4d3..5bff996 100644 --- a/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/Reference/UpdatePartyReferenceEndpointTests.cs +++ b/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/Reference/UpdatePartyReferenceEndpointTests.cs @@ -354,7 +354,7 @@ public async Task Invalid_identifiers_are_a_validation_problem_naming_each_bian_ } [Fact] - public async Task A_reference_field_RimBank_does_not_record_yet_is_refused_with_its_phase_and_nothing_is_stored() + public async Task A_reference_part_RimBank_does_not_record_is_refused_and_nothing_is_stored() { await using var host = await server.StartHostAsync(); var registered = await RegisterAsync(host); @@ -363,6 +363,7 @@ public async Task A_reference_field_RimBank_does_not_record_yet_is_refused_with_ "GovernmentIssuedIdentityReference": { "TaxIdentificationNumber": "FR12345678901", "OtherIdentification": "X1" }, "Nationality": { "Code": "FR", "Citizen": "Jane" }, "CompanyOfficerRole": { "Identification": "Director" }, + "CompanyOfficerReference": { "PartyReference": "x", "InvolvementReference": "Director" }, "PartyAddress": null, "NotABianField": "ignored" } @@ -373,10 +374,15 @@ public async Task A_reference_field_RimBank_does_not_record_yet_is_refused_with_ problem.GetProperty("errorCode").GetString().ShouldBe("party.reference-field-not-supported"); var errors = problem.GetProperty("errors"); errors.EnumerateObject().Select(field => field.Name).ShouldBe( - ["Nationality.Citizen", "CompanyOfficerRole", "GovernmentIssuedIdentityReference.OtherIdentification"], + [ + "Nationality.Citizen", + "CompanyOfficerRole.Identification", + "CompanyOfficerReference.InvolvementReference", + "GovernmentIssuedIdentityReference.OtherIdentification", + ], ignoreOrder: true); errors.GetProperty("Nationality.Citizen")[0].GetString().ShouldBe("RimBank does not record this field."); - errors.GetProperty("CompanyOfficerRole")[0].GetString().ShouldNotBeNull().ShouldContain("1.21"); + errors.GetProperty("CompanyOfficerReference.InvolvementReference")[0].GetString().ShouldBe("RimBank does not record this field."); (await host.ScalarAsync( $"SELECT count(*) FROM party_reference_data_directory.mt_events WHERE stream_id = '{registered.PartyReferenceDataDirectoryEntryId}'")) .ShouldBe(1); diff --git a/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/PartyReferenceDataDirectoryEntry/EntryExamples.cs b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/PartyReferenceDataDirectoryEntry/EntryExamples.cs index 3b0a5d9..31fe2da 100644 --- a/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/PartyReferenceDataDirectoryEntry/EntryExamples.cs +++ b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/PartyReferenceDataDirectoryEntry/EntryExamples.cs @@ -125,6 +125,41 @@ public static PartyReferenceChanges ReferenceChangesTo(PartyIdentifiers identifi public static readonly PartyReferenceDetails FullestReferenceDetails = CompleteReferenceDetails with { LegalStanding = LegalStanding, Documents = Documents }; + // Two other entries a Reference can name (1.21): an organisation (the company and its legal entity) and a person (the + // company officer), registered at the same time as the entry. + public static readonly PartyReferenceDataDirectoryEntryId CompanyId = + PartyReferenceDataDirectoryEntryId.From(Guid.CreateVersion7(OpenDate.AddMinutes(1))); + + public static readonly PartyReferenceDataDirectoryEntryId OfficerId = + PartyReferenceDataDirectoryEntryId.From(Guid.CreateVersion7(OpenDate.AddMinutes(2))); + + public static PartyRegistered RegisteredEntry(PartyReferenceDataDirectoryEntryId entryId, PartyType partyType) => + new(entryId, partyType, OpenDate, Demographics, Reference, BankRelations); + + public static readonly PartyCorporateReferences CorporateReferences = new( + CompanyId, + CompanyId, + OfficerId, + CompanyOfficerRole.TryCreate("Director").Value); + + // The changes that set every 1.21 reference to the given ones. + public static PartyReferenceChanges CorporateReferenceChangesTo(PartyCorporateReferences references) => + PartyReferenceChanges.None with + { + CorporateCustomer = new(references.CorporateCustomer), + LegalEntity = new(references.LegalEntity), + CompanyOfficer = new(references.CompanyOfficer), + CompanyOfficerRole = new(references.CompanyOfficerRole), + }; + + // The party types of the company and the officer, as the Reference handler loads them. + public static readonly IReadOnlyDictionary ReferencedParties = + new Dictionary + { + [CompanyId] = PartyType.Organisation, + [OfficerId] = PartyType.Person, + }; + // The changes that set every value of the details. The 1.19 and 1.20 parts are only sent when the details have them, // so the changes of an earlier-shaped Reference stay the ones its own phase's request makes. public static PartyReferenceChanges ReferenceChangesTo(PartyReferenceDetails details) => @@ -148,10 +183,16 @@ public static PartyReferenceChanges ReferenceChangesTo(PartyReferenceDetails det CustomerSinceDate = details.LegalStanding is { } since ? new(since.CustomerSince) : null, GovernmentIssuedDocument = details.Documents is { } document ? new(document.GovernmentIssuedDocument) : null, DocumentDirectoryEntry = details.Documents is { } directory ? new(directory.DocumentDirectoryEntry) : null, + CorporateCustomer = details.CorporateReferences is { } customer ? new(customer.CorporateCustomer) : null, + LegalEntity = details.CorporateReferences is { } legal ? new(legal.LegalEntity) : null, + CompanyOfficer = details.CorporateReferences is { } officer ? new(officer.CompanyOfficer) : null, + CompanyOfficerRole = details.CorporateReferences is { } role ? new(role.CompanyOfficerRole) : null, }; - public static UpdatePartyReferenceDetails UpdateReference(PartyReferenceChanges? changes = null) => - new(Reference, changes ?? ReferenceChangesTo(Identifiers), Today); + public static UpdatePartyReferenceDetails UpdateReference( + PartyReferenceChanges? changes = null, + IReadOnlyDictionary? referencedParties = null) => + new(Reference, changes ?? ReferenceChangesTo(Identifiers), Today, referencedParties); public static PartyReferenceUpdated ReferenceUpdated(PartyReferenceDetails? details = null) => new(EntryId, Reference, details ?? ReferenceDetails); diff --git a/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Reference/CorporateReferencesDecisionTests.cs b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Reference/CorporateReferencesDecisionTests.cs new file mode 100644 index 0000000..35b82e1 --- /dev/null +++ b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Reference/CorporateReferencesDecisionTests.cs @@ -0,0 +1,132 @@ +using RimBank.SharedKernel; +using static RimBank.Party.PartyReferenceDataDirectory.Tests.EntryExamples; +using EntrySpecification = RimBank.SharedKernel.Testing.DeciderSpecification< + RimBank.Party.PartyReferenceDataDirectory.PartyReferenceDataDirectoryEntry, + RimBank.Party.PartyReferenceDataDirectory.PartyReferenceDataDirectoryEntryCommand, + RimBank.Party.PartyReferenceDataDirectory.PartyReferenceDataDirectoryEntryEvent>; + +namespace RimBank.Party.PartyReferenceDataDirectory.Tests; + +// The corporate and officer references of the Reference Update decision (roadmap 1.21, ADR 0034): only an organisation's +// entry holds them, each reference the Update sets names another registered entry of the right party type (the facts the +// handler loaded from the write side), and a role needs an officer. The entry Update cannot make such an entry a person. +public sealed class CorporateReferencesDecisionTests +{ + private static readonly PartyReferenceDetails _withReferences = new(PartyIdentifiers.Empty, CorporateReferences: CorporateReferences); + + [Fact] + public void An_organisation_records_its_corporate_customer_legal_entity_officer_and_role() => + EntrySpecification.Given(Registered(PartyType.Organisation)) + .When(UpdateReference(CorporateReferenceChangesTo(CorporateReferences), ReferencedParties)) + .Then(ReferenceUpdated(_withReferences)); + + [Fact] + public void A_partial_update_keeps_the_references_it_does_not_send_without_checking_them_again() => + EntrySpecification.Given(Registered(PartyType.Organisation), ReferenceUpdated(_withReferences)) + .When(UpdateReference(PartyReferenceChanges.None with { CompanyOfficerRole = new(CompanyOfficerRole.TryCreate("Secretary").Value) })) + .Then(ReferenceUpdated(_withReferences with + { + CorporateReferences = CorporateReferences with { CompanyOfficerRole = CompanyOfficerRole.TryCreate("Secretary").Value }, + })); + + [Fact] + public void Clearing_every_reference_leaves_no_corporate_references() => + EntrySpecification.Given(Registered(PartyType.Organisation), ReferenceUpdated(_withReferences)) + .When(UpdateReference(CorporateReferenceChangesTo(PartyCorporateReferences.Empty))) + .Then(ReferenceUpdated(PartyReferenceDetails.Empty)); + + [Fact] + public void A_person_s_entry_cannot_hold_corporate_references() => + EntrySpecification.Given(Registered(PartyType.Person)) + .When(UpdateReference(CorporateReferenceChangesTo(CorporateReferences), ReferencedParties)) + .ThenFails(ErrorKind.BusinessRule, "party.corporate-references-need-organisation"); + + [Fact] + public void A_person_may_clear_references_it_does_not_hold() => + EntrySpecification.Given(Registered(PartyType.Person)) + .When(UpdateReference(CorporateReferenceChangesTo(PartyCorporateReferences.Empty))) + .Then(ReferenceUpdated(PartyReferenceDetails.Empty)); + + [Fact] + public void A_reference_to_the_entry_itself_is_refused_naming_its_path() + { + var error = EntrySpecification.Given(Registered(PartyType.Organisation)) + .When(UpdateReference(PartyReferenceChanges.None with { LegalEntity = new(EntryId) }, ReferencedParties)) + .ThenFails(ErrorKind.BusinessRule, "party.self-reference"); + + error.Message.ShouldStartWith("CorporateCustomerLegalEntityReference.PartyReference"); + } + + [Fact] + public void A_reference_to_an_entry_that_is_not_registered_is_refused_naming_its_path() + { + var error = EntrySpecification.Given(Registered(PartyType.Organisation)) + .When(UpdateReference(PartyReferenceChanges.None with { CompanyOfficer = new(OfficerId) }, referencedParties: null)) + .ThenFails(ErrorKind.BusinessRule, "party.referenced-party-not-registered"); + + error.Message.ShouldStartWith("CompanyOfficerReference.PartyReference"); + } + + [Fact] + public void A_person_as_the_corporate_customer_is_a_type_mismatch() => + EntrySpecification.Given(Registered(PartyType.Organisation)) + .When(UpdateReference(PartyReferenceChanges.None with { CorporateCustomer = new(OfficerId) }, ReferencedParties)) + .ThenFails(ErrorKind.BusinessRule, "party.referenced-party-type-mismatch") + .Message.ShouldBe("CorporateCustomerReference.PartyReference must name a party of type Organisation."); + + [Fact] + public void A_person_as_the_legal_entity_is_a_type_mismatch() => + EntrySpecification.Given(Registered(PartyType.Organisation)) + .When(UpdateReference(PartyReferenceChanges.None with { LegalEntity = new(OfficerId) }, ReferencedParties)) + .ThenFails(ErrorKind.BusinessRule, "party.referenced-party-type-mismatch"); + + [Fact] + public void An_organisation_as_the_officer_is_a_type_mismatch() => + EntrySpecification.Given(Registered(PartyType.Organisation)) + .When(UpdateReference(PartyReferenceChanges.None with { CompanyOfficer = new(CompanyId) }, ReferencedParties)) + .ThenFails(ErrorKind.BusinessRule, "party.referenced-party-type-mismatch") + .Message.ShouldBe("CompanyOfficerReference.PartyReference must name a party of type Person."); + + [Fact] + public void A_role_without_an_officer_is_invalid() => + EntrySpecification.Given(Registered(PartyType.Organisation)) + .When(UpdateReference(PartyReferenceChanges.None with { CompanyOfficerRole = new(CorporateReferences.CompanyOfficerRole) })) + .ThenFails(ErrorKind.Validation, "party.reference-invalid") + .FieldErrors.Keys.ShouldBe(["CompanyOfficerRole"]); + + [Fact] + public void Clearing_the_officer_while_the_role_is_kept_is_invalid() => + EntrySpecification.Given(Registered(PartyType.Organisation), ReferenceUpdated(_withReferences)) + .When(UpdateReference(PartyReferenceChanges.None with { CompanyOfficer = new(null) })) + .ThenFails(ErrorKind.Validation, "party.reference-invalid"); + + [Fact] + public void Clearing_the_officer_and_the_role_together_is_accepted() => + EntrySpecification.Given(Registered(PartyType.Organisation), ReferenceUpdated(_withReferences)) + .When(UpdateReference(PartyReferenceChanges.None with { CompanyOfficer = new(null), CompanyOfficerRole = new(null) })) + .Then(ReferenceUpdated(_withReferences with + { + CorporateReferences = CorporateReferences with { CompanyOfficer = null, CompanyOfficerRole = null }, + })); + + [Fact] + public void An_organisation_with_corporate_references_cannot_become_a_person() => + EntrySpecification.Given(Registered(PartyType.Organisation), ReferenceUpdated(_withReferences)) + .When(Update(PartyType.Person)) + .ThenFails(ErrorKind.BusinessRule, "party.corporate-references-need-organisation"); + + [Fact] + public void An_organisation_with_corporate_references_can_be_refreshed_as_an_organisation() => + EntrySpecification.Given(Registered(PartyType.Organisation), ReferenceUpdated(_withReferences)) + .When(Update(partyType: null)) + .Then(Updated(PartyType.Organisation)); + + [Fact] + public void An_organisation_whose_references_are_cleared_can_become_a_person() => + EntrySpecification.Given( + Registered(PartyType.Organisation), + ReferenceUpdated(_withReferences), + ReferenceUpdated(PartyReferenceDetails.Empty)) + .When(Update(PartyType.Person)) + .Then(Updated(PartyType.Person)); +} diff --git a/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Reference/PartyCorporateReferencesTests.cs b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Reference/PartyCorporateReferencesTests.cs new file mode 100644 index 0000000..2b7796b --- /dev/null +++ b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Reference/PartyCorporateReferencesTests.cs @@ -0,0 +1,91 @@ +using System.Text.Json; +using System.Text.Json.Nodes; +using RimBank.SharedKernel; +using static RimBank.Party.PartyReferenceDataDirectory.Tests.EntryExamples; + +namespace RimBank.Party.PartyReferenceDataDirectory.Tests; + +// The corporate and officer references of the Reference BQ (roadmap 1.21, ADR 0034): the officer's role, the partial +// update of the references, and a Reference stored before 1.21 reading back unchanged. +public sealed class PartyCorporateReferencesTests +{ + private static readonly JsonSerializerOptions _json = new() { Converters = { new TypedIdJsonConverterFactory() } }; + + [Fact] + public void The_role_is_trimmed() => + CompanyOfficerRole.TryCreate(" Director ").Value.Value.ShouldBe("Director"); + + [Fact] + public void Thirty_five_characters_of_role_are_accepted() => + CompanyOfficerRole.TryCreate(new string('r', 35)).IsSuccess.ShouldBeTrue(); + + [Theory] + [InlineData(36)] + [InlineData(0)] + public void A_role_too_long_or_blank_is_invalid(int length) => + CompanyOfficerRole.TryCreate(new string('r', length)).Error.Code.ShouldBe("party.reference-invalid"); + + [Fact] + public void The_role_is_a_plain_json_string() => + JsonSerializer.Serialize(CompanyOfficerRole.TryCreate("Director").Value).ShouldBe("\"Director\""); + + [Fact] + public void Empty_references_have_nothing() + { + PartyCorporateReferences.Empty.HasAny.ShouldBeFalse(); + (PartyCorporateReferences.Empty with { LegalEntity = CompanyId }).HasAny.ShouldBeTrue(); + } + + [Fact] + public void The_changes_set_keep_and_clear_each_reference() => + CorporateReferences.Apply(PartyReferenceChanges.None with + { + CorporateCustomer = new(null), + CompanyOfficerRole = new(CompanyOfficerRole.TryCreate("Secretary").Value), + }) + .ShouldBe(CorporateReferences with + { + CorporateCustomer = null, + CompanyOfficerRole = CompanyOfficerRole.TryCreate("Secretary").Value, + }); + + [Fact] + public void The_reference_records_them_only_when_one_is_set() + { + var recorded = PartyReferenceDetails.Empty.Apply(CorporateReferenceChangesTo(CorporateReferences)); + recorded.CorporateReferences.ShouldBe(CorporateReferences); + + var cleared = recorded.Apply(CorporateReferenceChangesTo(PartyCorporateReferences.Empty)); + cleared.CorporateReferences.ShouldBeNull(); + cleared.CurrentCorporateReferences.ShouldBe(PartyCorporateReferences.Empty); + } + + [Fact] + public void Another_update_leaves_the_references_unchanged() + { + var details = FullestReferenceDetails with { CorporateReferences = CorporateReferences }; + + details.Apply(PartyReferenceChanges.None with { PartyAddress = new(null) }) + .ShouldBe(details with { Addresses = Addresses with { PartyAddress = null } }); + } + + [Fact] + public void A_reference_with_references_survives_a_json_round_trip() + { + var details = FullestReferenceDetails with { CorporateReferences = CorporateReferences }; + + JsonSerializer.Deserialize(JsonSerializer.Serialize(details, _json), _json).ShouldBe(details); + } + + [Fact] + public void A_reference_stored_before_1_21_reads_back_unchanged() + { + var stored = JsonNode.Parse(JsonSerializer.Serialize(FullestReferenceDetails, _json))!.AsObject(); + stored.Remove(nameof(PartyReferenceDetails.CorporateReferences)).ShouldBeTrue(); + + var read = JsonSerializer.Deserialize(stored.ToJsonString(), _json).ShouldNotBeNull(); + + read.ShouldBe(FullestReferenceDetails); + read.CurrentCorporateReferences.ShouldBe(PartyCorporateReferences.Empty); + } +} diff --git a/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Reference/PartyReferenceChangesTests.cs b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Reference/PartyReferenceChangesTests.cs index 429143c..875eb76 100644 --- a/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Reference/PartyReferenceChangesTests.cs +++ b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Reference/PartyReferenceChangesTests.cs @@ -3,8 +3,8 @@ namespace RimBank.Party.PartyReferenceDataDirectory.Tests; -// Reading the changes a Reference Update asks for (roadmap 1.10, 1.18 and 1.19, ADR 0029, ADR 0031): null keeps, blank clears, every -// invalid value is named with its BIAN field, and the fields RimBank does not record yet are refused with their phase. +// Reading the changes a Reference Update asks for (roadmap 1.10 to 1.21, ADR 0029, ADR 0031, ADR 0032, ADR 0034): null +// keeps, blank clears, every invalid value is named with its BIAN field, and the fields RimBank does not record are refused. public sealed class PartyReferenceChangesTests { [Fact] @@ -175,15 +175,73 @@ public void A_status_date_time_without_a_code_is_invalid() => .Error.FieldErrors.ShouldNotBeNull().Keys.ShouldBe(["ResidencyStatus.StatusDescription"]); [Fact] - public void A_staged_field_is_refused_with_the_phase_that_adds_it() + public void Given_corporate_and_officer_references_are_read_into_entry_ids_and_the_role() => + PartyReferenceChanges.Create( + new PartyReferenceInput( + CorporateCustomerReference: $" {CompanyId} ", + CorporateCustomerLegalEntityReference: CompanyId.ToString(), + CompanyOfficerReference: OfficerId.ToString(), + CompanyOfficerRole: " Director "), + []) + .Value.ShouldBe(CorporateReferenceChangesTo(CorporateReferences)); + + [Theory] + [InlineData("")] + [InlineData(" ")] + public void A_blank_reference_or_role_clears_it(string blank) => + PartyReferenceChanges.Create( + new PartyReferenceInput( + CorporateCustomerReference: blank, + CorporateCustomerLegalEntityReference: blank, + CompanyOfficerReference: blank, + CompanyOfficerRole: blank), + []) + .Value.ShouldBe(PartyReferenceChanges.None with + { + CorporateCustomer = new(null), + LegalEntity = new(null), + CompanyOfficer = new(null), + CompanyOfficerRole = new(null), + }); + + [Fact] + public void Every_invalid_reference_and_role_is_named_with_its_bian_path() { - var error = PartyReferenceChanges.Create(PartyReferenceInput.None, ["CompanyOfficerRole", "CorporateCustomerReference"]).Error; + var error = PartyReferenceChanges.Create( + new PartyReferenceInput( + CorporateCustomerReference: "ACME-1", + CorporateCustomerLegalEntityReference: Guid.Empty.ToString(), + CompanyOfficerReference: Guid.NewGuid().ToString(), // version 4: not an id the directory issues + CompanyOfficerRole: new string('r', 36)), + []) + .Error; - error.Kind.ShouldBe(ErrorKind.Validation); - error.Code.ShouldBe("party.reference-field-not-supported"); - var fieldErrors = error.FieldErrors.ShouldNotBeNull(); - fieldErrors["CompanyOfficerRole"].ShouldHaveSingleItem().ShouldContain("1.21"); - fieldErrors["CorporateCustomerReference"].ShouldHaveSingleItem().ShouldContain("1.21"); + error.Code.ShouldBe("party.reference-invalid"); + error.FieldErrors.Keys.Order(StringComparer.Ordinal).ShouldBe( + [ + "CompanyOfficerReference.PartyReference", + "CompanyOfficerRole", + "CorporateCustomerLegalEntityReference.PartyReference", + "CorporateCustomerReference.PartyReference", + ]); + } + + [Fact] + public void The_referenced_entries_are_the_ones_the_changes_set_with_their_bian_paths() + { + var changes = PartyReferenceChanges.None with + { + CorporateCustomer = new(CompanyId), + LegalEntity = new(null), + CompanyOfficer = new(OfficerId), + }; + + changes.ReferencedEntries().ShouldBe( + [ + ("CorporateCustomerReference.PartyReference", CompanyId), + ("CompanyOfficerReference.PartyReference", OfficerId), + ]); + PartyReferenceChanges.None.ReferencedEntries().ShouldBeEmpty(); } [Theory] @@ -202,6 +260,10 @@ public void A_staged_field_is_refused_with_the_phase_that_adds_it() [InlineData("GovernmentIssuedDocumentDetails.DocumentReference.DocumentIdentification.IdentifierIssuerReference")] [InlineData("GovernmentIssuedDocumentDetails.DocumentReference.DocumentValidityPeriod.ToDateTime.TimeZoneCode")] [InlineData("DocumentDirectoryEntryInstanceReference.DirectoryEntryStatus")] + [InlineData("CorporateCustomerReference.InvolvementReference")] + [InlineData("CorporateCustomerLegalEntityReference.InvolvementReference")] + [InlineData("CompanyOfficerReference.InvolvementReference")] + [InlineData("CompanyOfficerRole.Identification")] public void A_field_no_phase_adds_is_refused_without_a_phase(string field) => PartyReferenceChanges.Create(PartyReferenceInput.None, [field]).Error .FieldErrors.ShouldNotBeNull()[field] @@ -209,55 +271,47 @@ public void A_field_no_phase_adds_is_refused_without_a_phase(string field) => [Fact] public void Unsupported_fields_are_refused_before_the_values_are_checked() => - PartyReferenceChanges.Create(new PartyReferenceInput(new string('1', 36), DateofBirth: "garbage"), ["CompanyOfficerRole"]).Error.Code + PartyReferenceChanges.Create( + new PartyReferenceInput(new string('1', 36), DateofBirth: "garbage"), + ["CompanyOfficerReference.InvolvementReference"]) + .Error.Code .ShouldBe("party.reference-field-not-supported"); [Fact] - public void Every_bian_reference_field_is_either_recorded_or_staged() + public void Every_bian_reference_field_is_recorded() { // The 24 top-level fields of BIAN UpdateReference (PartyReferenceDataDirectory.yaml): two are recorded from 1.10, - // six from 1.18, six from 1.19 and six from 1.20; the four references to other parties wait for 1.21 (ADR 0032). - PartyReferenceFields.Staged.Count.ShouldBe(4); - PartyReferenceFields.Staged.Keys.ShouldNotContain(PartyReferenceFields.GovernmentIssuedIdentityReference); - PartyReferenceFields.Staged.Keys.ShouldNotContain(PartyReferenceFields.PartyLegalEntityReference); - string[] recordedIn118 = + // six from 1.18, six from 1.19, six from 1.20 and the four references to other parties from 1.21 (ADR 0034). + string[] recorded = [ + PartyReferenceFields.GovernmentIssuedIdentityReference, + PartyReferenceFields.PartyLegalEntityReference, PartyReferenceFields.PartyFullLegalName, PartyReferenceFields.PartyNameSalutation, PartyReferenceFields.DateofBirth, PartyReferenceFields.Nationality, PartyReferenceFields.PartyCountryOfResidence, PartyReferenceFields.ResidencyStatus, - ]; - PartyReferenceFields.Staged.Keys.ShouldNotContain(field => recordedIn118.Contains(field)); - string[] recordedIn119 = - [ PartyReferenceFields.ResidentialAddress, PartyReferenceFields.PartyAddress, PartyReferenceFields.CorporateAddress, PartyReferenceFields.EMailAddress, PartyReferenceFields.CellPhoneNumber, PartyReferenceFields.SocialNetworkContacts, - ]; - PartyReferenceFields.Staged.Keys.ShouldNotContain(field => recordedIn119.Contains(field)); - string[] recordedIn120 = - [ PartyReferenceFields.PartyLegalStructure, PartyReferenceFields.PoliticalExposureType, PartyReferenceFields.PoliticalExposureDescriptionRecord, PartyReferenceFields.CustomerSinceDate, PartyReferenceFields.GovernmentIssuedDocumentDetails, PartyReferenceFields.DocumentDirectoryEntryInstanceReference, + PartyReferenceFields.CorporateCustomerReference, + PartyReferenceFields.CorporateCustomerLegalEntityReference, + PartyReferenceFields.CompanyOfficerReference, + PartyReferenceFields.CompanyOfficerRole, ]; - PartyReferenceFields.Staged.Keys.ShouldNotContain(field => recordedIn120.Contains(field)); - PartyReferenceFields.Staged.Keys.Order(StringComparer.Ordinal).ShouldBe( - [ - "CompanyOfficerReference", - "CompanyOfficerRole", - "CorporateCustomerLegalEntityReference", - "CorporateCustomerReference", - ]); - PartyReferenceFields.Staged.Values.Distinct().ShouldBe(["1.21"]); + + recorded.Distinct(StringComparer.Ordinal).Count().ShouldBe(24); + PartyReferenceFields.Staged.ShouldBeEmpty(); } [Fact] diff --git a/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Reference/PartyReferencePartialUpdateProperties.cs b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Reference/PartyReferencePartialUpdateProperties.cs index 1b87670..b05ea94 100644 --- a/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Reference/PartyReferencePartialUpdateProperties.cs +++ b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Reference/PartyReferencePartialUpdateProperties.cs @@ -4,7 +4,7 @@ namespace RimBank.Party.PartyReferenceDataDirectory.Tests; -// The partial-update law of the Reference (roadmap 1.20): over every recorded field (1.10 to 1.20), an omitted change keeps +// The partial-update law of the Reference (roadmap 1.20): over every recorded field (1.10 to 1.21), an omitted change keeps // the current value, a given one sets or clears it, and applying the same changes twice is the same as once. public sealed class PartyReferencePartialUpdateProperties { @@ -32,6 +32,10 @@ private static readonly (string Name, Func Value ("CustomerSinceDate", d => d.CurrentLegalStanding.CustomerSince, c => Of(c.CustomerSinceDate)), ("GovernmentIssuedDocumentDetails", d => d.CurrentDocuments.GovernmentIssuedDocument, c => Of(c.GovernmentIssuedDocument)), ("DocumentDirectoryEntryInstanceReference", d => d.CurrentDocuments.DocumentDirectoryEntry, c => Of(c.DocumentDirectoryEntry)), + ("CorporateCustomerReference", d => d.CurrentCorporateReferences.CorporateCustomer, c => Of(c.CorporateCustomer)), + ("CorporateCustomerLegalEntityReference", d => d.CurrentCorporateReferences.LegalEntity, c => Of(c.LegalEntity)), + ("CompanyOfficerReference", d => d.CurrentCorporateReferences.CompanyOfficer, c => Of(c.CompanyOfficer)), + ("CompanyOfficerRole", d => d.CurrentCorporateReferences.CompanyOfficerRole, c => Of(c.CompanyOfficerRole)), ]; [Property] @@ -69,7 +73,7 @@ public Property Applying_the_same_changes_twice_is_applying_them_once() => [Fact] public void Every_recorded_bian_reference_field_is_covered() => - // 24 BIAN UpdateReference fields, less the four staged for 1.21; GovernmentIssuedIdentityReference holds two values. + // 24 BIAN UpdateReference fields, less the staged ones (none since 1.21); GovernmentIssuedIdentityReference holds two values. _fields.Length.ShouldBe(24 - PartyReferenceFields.Staged.Count + 1); private static (bool Sent, object? Value) Of(PartyReferenceChange? change) => diff --git a/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Reference/ReferenceArbitraries.cs b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Reference/ReferenceArbitraries.cs index 7ce5a3d..2aa4c45 100644 --- a/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Reference/ReferenceArbitraries.cs +++ b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Reference/ReferenceArbitraries.cs @@ -39,6 +39,12 @@ from lei in OrNull(LegalEntityIdentifier.TryCreate("5493001KJTIIGC8Y1R12").Value null, null)); + private static readonly PartyReferenceDataDirectoryEntryId[] _entries = + [ + PartyReferenceDataDirectoryEntryId.From(Guid.CreateVersion7(new DateTimeOffset(2026, 1, 2, 0, 0, 0, TimeSpan.Zero))), + PartyReferenceDataDirectoryEntryId.From(Guid.CreateVersion7(new DateTimeOffset(2026, 3, 4, 0, 0, 0, TimeSpan.Zero))), + ]; + // Built by applying changes that set every field to the empty Reference, so each generated Reference has the shape // Apply gives (an empty group is null). public static readonly Gen Details = @@ -61,6 +67,10 @@ from description in OrNull(PoliticalExposureDescription.TryCreate("Mayor").Value from since in OrNullValue(new DateOnly(2015, 3, 2)) from document in _documents from directory in OrNull(DocumentDirectoryEntryReference.TryCreate("DOC-000123").Value) + from corporateCustomer in OrNullValue(_entries) + from legalEntity in OrNullValue(_entries) + from officer in OrNullValue(_entries) + from role in OrNull(CompanyOfficerRole.TryCreate("Director").Value) select PartyReferenceDetails.Empty.Apply(new PartyReferenceChanges( new(identifiers.TaxIdentificationNumber), new(identifiers.NationalRegistrationNumber), @@ -82,12 +92,16 @@ select PartyReferenceDetails.Empty.Apply(new PartyReferenceChanges( new(description), new(since), new(document), - new(directory))); + new(directory), + new(corporateCustomer), + new(legalEntity), + new(officer), + new(role))); // For each field: omitted (keep), cleared, or set to a generated value. public static readonly Gen PartialChanges = from target in Details - from sent in Gen.ArrayOf(Gen.Elements(0, 1, 2), 21) + from sent in Gen.ArrayOf(Gen.Elements(0, 1, 2), 25) select Pick(ChangesTo(target), sent); // The changes that set every field of the details, clearing the unknown ones. @@ -113,7 +127,11 @@ public static PartyReferenceChanges ChangesTo(PartyReferenceDetails details) => new(details.CurrentLegalStanding.PoliticalExposureDescription), new(details.CurrentLegalStanding.CustomerSince), new(details.CurrentDocuments.GovernmentIssuedDocument), - new(details.CurrentDocuments.DocumentDirectoryEntry)); + new(details.CurrentDocuments.DocumentDirectoryEntry), + new(details.CurrentCorporateReferences.CorporateCustomer), + new(details.CurrentCorporateReferences.LegalEntity), + new(details.CurrentCorporateReferences.CompanyOfficer), + new(details.CurrentCorporateReferences.CompanyOfficerRole)); // 0 omits the field, 1 clears it, 2 sends the full change's value. private static PartyReferenceChanges Pick(PartyReferenceChanges full, int[] sent) => @@ -138,7 +156,11 @@ private static PartyReferenceChanges Pick(PartyReferenceChanges full, int[] sent Choose(full.PoliticalExposureDescription, sent[17]), ChooseValue(full.CustomerSinceDate, sent[18]), Choose(full.GovernmentIssuedDocument, sent[19]), - Choose(full.DocumentDirectoryEntry, sent[20])); + Choose(full.DocumentDirectoryEntry, sent[20]), + ChooseValue(full.CorporateCustomer, sent[21]), + ChooseValue(full.LegalEntity, sent[22]), + ChooseValue(full.CompanyOfficer, sent[23]), + Choose(full.CompanyOfficerRole, sent[24])); private static PartyReferenceChange? Choose(PartyReferenceChange? full, int sent) where T : class => diff --git a/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Reference/UpdatePartyReferenceHandlerTests.cs b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Reference/UpdatePartyReferenceHandlerTests.cs index f4f5990..d18e64c 100644 --- a/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Reference/UpdatePartyReferenceHandlerTests.cs +++ b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Reference/UpdatePartyReferenceHandlerTests.cs @@ -114,6 +114,100 @@ public async Task The_command_and_the_acknowledgement_survive_a_json_round_trip( .ShouldBe(acknowledged); } + [Fact] + public async Task The_referenced_entries_are_loaded_from_the_write_side_and_recorded() + { + _directory.Seed(EntryId, Registered(PartyType.Organisation)); + _directory.Seed(CompanyId, RegisteredEntry(CompanyId, PartyType.Organisation)); + _directory.Seed(OfficerId, RegisteredEntry(OfficerId, PartyType.Person)); + + var acknowledged = (await Update(Reference, expectedVersion: 1, CorporateReferenceChangesTo(CorporateReferences))).Value; + + acknowledged.Reference.CorporateReferences.ShouldBe(CorporateReferences); + _directory.StreamOf(EntryId).Count.ShouldBe(2); + _directory.StreamOf(CompanyId).ShouldBe([RegisteredEntry(CompanyId, PartyType.Organisation)]); + } + + [Fact] + public async Task A_referenced_entry_that_is_not_registered_is_refused_and_nothing_is_appended() + { + _directory.Seed(EntryId, Registered(PartyType.Organisation)); + + var result = await Update(Reference, expectedVersion: 1, PartyReferenceChanges.None with { CorporateCustomer = new(CompanyId) }); + + result.Error.Code.ShouldBe("party.referenced-party-not-registered"); + result.Error.Kind.ShouldBe(ErrorKind.BusinessRule); + _directory.StreamOf(EntryId).ShouldBe([Registered(PartyType.Organisation)]); + } + + [Fact] + public async Task An_association_id_given_as_a_reference_is_not_registered_never_a_failure() + { + _directory.Seed(EntryId, Registered(PartyType.Organisation)); + var associationId = PartyAssociationId.From(Guid.CreateVersion7(OpenDate.AddMinutes(9))); + _directory.Seed(associationId, new PartyAssociationRegistered( + associationId, + EntryId, + CompanyId, + PartyRelationshipType.PartyIsParentOfParty, + null)); + + var result = await Update( + Reference, + expectedVersion: 1, + PartyReferenceChanges.None with { LegalEntity = new(PartyReferenceDataDirectoryEntryId.From(associationId.Value)) }); + + result.Error.Code.ShouldBe("party.referenced-party-not-registered"); + } + + [Fact] + public async Task A_reference_to_the_entry_itself_is_refused() + { + _directory.Seed(EntryId, Registered(PartyType.Organisation)); + + var result = await Update(Reference, expectedVersion: 1, PartyReferenceChanges.None with { CorporateCustomer = new(EntryId) }); + + result.Error.Code.ShouldBe("party.self-reference"); + } + + [Fact] + public async Task The_party_types_loaded_are_the_ones_the_decision_checks() + { + _directory.Seed(EntryId, Registered(PartyType.Organisation)); + _directory.Seed(OfficerId, RegisteredEntry(OfficerId, PartyType.Organisation), new PartyReferenceDataDirectoryEntryUpdated(OfficerId, PartyType.Person, RefreshDate)); + _directory.Seed(CompanyId, RegisteredEntry(CompanyId, PartyType.Organisation)); + + (await Update(Reference, expectedVersion: 1, PartyReferenceChanges.None with { CompanyOfficer = new(OfficerId) })).IsSuccess.ShouldBeTrue(); + (await Update(Reference, expectedVersion: 2, PartyReferenceChanges.None with { CompanyOfficer = new(CompanyId) })) + .Error.Code.ShouldBe("party.referenced-party-type-mismatch"); + } + + [Fact] + public async Task A_person_s_entry_cannot_record_corporate_references() + { + _directory.Seed(EntryId, Registered(PartyType.Person)); + _directory.Seed(CompanyId, RegisteredEntry(CompanyId, PartyType.Organisation)); + + var result = await Update(Reference, expectedVersion: 1, PartyReferenceChanges.None with { CorporateCustomer = new(CompanyId) }); + + result.Error.Code.ShouldBe("party.corporate-references-need-organisation"); + } + + [Fact] + public async Task A_kept_reference_is_not_checked_again() + { + // The officer was recorded when it was registered; the stream here holds a reference to an entry the directory does + // not know, so the Update could only pass if the kept reference is not loaded again. + _directory.Seed( + EntryId, + Registered(PartyType.Organisation), + ReferenceUpdated(new PartyReferenceDetails(PartyIdentifiers.Empty, CorporateReferences: CorporateReferences))); + + var result = await Update(Reference, expectedVersion: 2, PartyReferenceChanges.None with { PartyFullLegalName = new(Names.FullLegalName) }); + + result.Value.Reference.CorporateReferences.ShouldBe(CorporateReferences); + } + private static UpdatePartyReference Command(PartyReferenceId referenceId, long expectedVersion, PartyReferenceChanges? changes = null) => new(EntryId, referenceId, expectedVersion, changes ?? ReferenceChangesTo(Identifiers), IdempotencyKey.From("reference-1")); diff --git a/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Retrieval/PartyReferenceDataDirectoryEntryViewProjectionTests.cs b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Retrieval/PartyReferenceDataDirectoryEntryViewProjectionTests.cs index 7e3f438..e44dcc8 100644 --- a/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Retrieval/PartyReferenceDataDirectoryEntryViewProjectionTests.cs +++ b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Retrieval/PartyReferenceDataDirectoryEntryViewProjectionTests.cs @@ -133,6 +133,38 @@ public void Legal_standing_and_documents_show_in_the_reference_section() => BankRelations, Reference: FullestReferenceDetails)); + [Fact] + public void Corporate_and_officer_references_show_in_the_reference_section() => + EntryViewSpecification.Given( + Registered(PartyType.Organisation), + ReferenceUpdated(FullestReferenceDetails), + ReferenceUpdated(FullestReferenceDetails with { CorporateReferences = CorporateReferences })) + .Then(new PartyReferenceDataDirectoryEntryView( + EntryId.Value, + Version: 3, + PartyType.Organisation, + OpenDate, + Demographics, + Reference, + BankRelations, + Reference: FullestReferenceDetails with { CorporateReferences = CorporateReferences })); + + [Fact] + public void A_reference_event_stored_before_1_21_still_projects_with_no_corporate_references() + { + // A PartyReferenceUpdated as roadmap 1.20 stored it: no CorporateReferences member. + var stored = JsonSerializer.SerializeToNode(ReferenceUpdated(FullestReferenceDetails), _json).ShouldNotBeNull(); + stored["Details"].ShouldNotBeNull().AsObject().Remove("CorporateReferences").ShouldBeTrue(); + var updated = stored.Deserialize(_json).ShouldNotBeNull(); + + var view = new PartyReferenceDataDirectoryEntryEvent[] { Registered(), updated } + .Aggregate((PartyReferenceDataDirectoryEntryView?)null, PartyReferenceDataDirectoryEntryViewProjection.Project) + .ShouldNotBeNull(); + + view.CurrentReference.ShouldBe(FullestReferenceDetails); + view.CurrentReference.CurrentCorporateReferences.ShouldBe(PartyCorporateReferences.Empty); + } + [Fact] public void A_reference_event_stored_before_1_20_still_projects_with_no_legal_standing_or_documents() { From ace0f323bac30307fc629d3421ace56d9ac2ad8a Mon Sep 17 00:00:00 2001 From: LaBani Said Date: Sun, 8 Nov 2026 20:25:40 +0100 Subject: [PATCH 3/3] Write ADR 0034, amend ADRs 0024, 0029 and 0032, and tick roadmap 1.21 Co-Authored-By: Claude Opus 5.5 --- ...-party-reference-data-directory-mapping.md | 13 ++- docs/adr/0029-reference-fields-in-stages.md | 23 +++-- ...-reference-legal-standing-and-documents.md | 2 +- ...erence-corporate-and-officer-references.md | 93 +++++++++++++++++++ .../plan.md | 44 ++++----- .../requirements.md | 8 +- .../validation.md | 2 +- specs/roadmap.md | 2 +- specs/tech-stack.md | 8 +- 9 files changed, 154 insertions(+), 41 deletions(-) create mode 100644 docs/adr/0034-reference-corporate-and-officer-references.md diff --git a/docs/adr/0024-party-reference-data-directory-mapping.md b/docs/adr/0024-party-reference-data-directory-mapping.md index 4b85f27..78ae4d8 100644 --- a/docs/adr/0024-party-reference-data-directory-mapping.md +++ b/docs/adr/0024-party-reference-data-directory-mapping.md @@ -68,7 +68,7 @@ Every `Retrieve` is a query, and every other operation is a command (mission pri **Retrieve request (1.7).** `GET /PartyReferenceDataDirectory/{partyreferencedatadirectoryid}/Retrieve` answers `200` from the entry's view only, with the BIAN Retrieve fields (`PartyType`, `DirectoryEntryDateType` = `OpenDate`, `DirectoryEntryDate`) and the ids of the entry and its three singleton BQs, in the same shape as the Register response. BIAN's `PartyReference` is not returned: the party's details are served by the Demographics and Reference Retrieves (1.9, 1.10). The entry's version is the strong `ETag` (`"1"`), and an `If-None-Match` that names it (weak comparison, a list or `*`) answers `304 Not Modified` with the `ETag` and no body. A route value that is not an identifier RimBank issues (not a GUID, empty, or not a version 7 GUID) is `400` with the shared `shared.invalid-identifier` code and `errors["partyreferencedatadirectoryid"]`; an unknown entry is `404` `party.party-not-found`. **Update request (1.8).** `PUT /PartyReferenceDataDirectory/{partyreferencedatadirectoryid}/Update` takes BIAN's `UpdatePartyReferenceDataDirectoryEntry` body. -- **What changes.** Only `PartyType` is used, and it is optional. When it is omitted, the entry keeps its type. When it is given, it is read like Register's, except that a blank value is `party.party-type-invalid`. +- **What changes.** Only `PartyType` is used, and it is optional. When it is omitted, the entry keeps its type. When it is given, it is read like Register's, except that a blank value is `party.party-type-invalid`. From 1.21, an organisation whose Reference records corporate or officer references cannot become a `Person` (`party.corporate-references-need-organisation`, [ADR 0034](0034-reference-corporate-and-officer-references.md)): the client clears them first. - **RefreshDate.** Every accepted Update records the time of the update (`TimeProvider`) as the entry's `RefreshDate`, BIAN's second `DirectoryEntryDateType`. An Update with an unchanged type is therefore still a business fact and appends `PartyReferenceDataDirectoryEntryUpdated`. - **Ignored fields.** `PartyReference`, `DirectoryEntryDateType` and `DirectoryEntryDate` are accepted and ignored, as in Register. - **Headers.** The request requires `Idempotency-Key` and `If-Match` ([ADR 0027](0027-optimistic-concurrency-for-commands.md)): missing → `428` `shared.if-match-required`, malformed → `400` `shared.if-match-invalid`, stale → `409` `party.version-conflict`. @@ -100,13 +100,18 @@ Every `Retrieve` is a query, and every other operation is a command (mission pri - `GovernmentIssuedDocumentDetails` (type, number, name and validity period) and `DocumentDirectoryEntryInstanceReference` (an opaque identification). - A value left out keeps its value, and an empty one (or an object whose parts are all empty) clears it. An invalid one is `party.reference-invalid` with the BIAN field names in `errors`. - Every accepted Update appends `PartyReferenceUpdated`, even when nothing changes. - - The four references to other parties (`CorporateCustomerReference`, `CorporateCustomerLegalEntityReference`, `CompanyOfficerReference`, `CompanyOfficerRole`) are refused with `party.reference-field-not-supported` until 1.21, after Associations (ADR 0029, ADR 0032). So are the parts of the objects above that RimBank does not record. + - From 1.21, it also updates the corporate customer's references to other parties ([ADR 0034](0034-reference-corporate-and-officer-references.md)): + - `CorporateCustomerReference.PartyReference` and `CorporateCustomerLegalEntityReference.PartyReference` (registered organisations) and `CompanyOfficerReference.PartyReference` (a registered person), each another entry of this directory, loaded through the write port; + - `CompanyOfficerRole` (Max35Text, only with an officer); + - only on an organisation's entry. + - The parts of the objects above that RimBank does not record are refused with `party.reference-field-not-supported`, including `InvolvementReference`. - **Retrieve** (`GET …/Reference/{referenceid}/Retrieve`) answers from the entry's view, with the entry's version as `ETag` and `304` on a matching `If-None-Match`. Before the first Update, it answers `200` with the ids only. - **Headers and responses.** Update requires `Idempotency-Key` and `If-Match`, as in 1.8. Both answer `200` with the same body: - `GovernmentIssuedIdentityReference` and `PartyLegalEntityReference`, each left out when it holds no identifier; - from 1.18: the names, `DateofBirth` as `YYYY-MM-DD`, `Nationality` and `PartyCountryOfResidence` as `{ "Code": … }`, and `ResidencyStatus`, each left out when unknown; - from 1.19: the three addresses, each part left out when unknown, and the contact points as `{ "EmailAddress": … }`, `{ "MobileNumber": … }` and `{ "URLAddress": … }`, each left out when unknown; - from 1.20: the legal structure and political exposure type in BIAN spelling, the description, `CustomerSinceDate` as `YYYY-MM-DD`, the document in BIAN's nested shape (validity dates as `YYYY-MM-DD`) and the directory reference, each left out when unknown; + - from 1.21: the three references as `{ "PartyReference": … }` and `CompanyOfficerRole` as a string, each left out when unknown; - the entry and Reference ids. Update builds it from its acknowledgement. @@ -188,6 +193,10 @@ The `ETag` returned by a Retrieve, and the `If-Match` a command sends back, is t | `party.association-not-found` | NotFound (404) | The association does not exist, or the path's entry is not its owner (1.11) | | `party.associate-not-registered` | BusinessRule (422) | `AssociateReference` is not an entry of this directory (1.11) | | `party.self-association` | BusinessRule (422) | The associate is the owning entry (1.11) | +| `party.corporate-references-need-organisation` | BusinessRule (422) | Corporate or officer references on an entry that is not an organisation, or an entry Update to `Person` while they are recorded (1.21, [ADR 0034](0034-reference-corporate-and-officer-references.md)) | +| `party.self-reference` | BusinessRule (422) | A Reference reference names the entry itself (1.21, ADR 0034) | +| `party.referenced-party-not-registered` | BusinessRule (422) | A Reference reference is not an entry of this directory (1.21, ADR 0034) | +| `party.referenced-party-type-mismatch` | BusinessRule (422) | The corporate customer or legal entity is not an organisation, or the officer is not a person (1.21, ADR 0034) | | `party.association-invalid` | Validation (400) | An Associations value is missing or not valid; `errors` names each BIAN path (1.11, [ADR 0033](0033-party-associations.md)) | | `party.association-field-not-supported` | Validation (400) | An Associations request sends a BIAN field or part RimBank does not record (1.11, ADR 0033) | | `party.associate-cannot-change` | BusinessRule (422) | An Associations Update names another associate than the registered one (1.11, ADR 0033) | diff --git a/docs/adr/0029-reference-fields-in-stages.md b/docs/adr/0029-reference-fields-in-stages.md index 0468aa6..70f31dd 100644 --- a/docs/adr/0029-reference-fields-in-stages.md +++ b/docs/adr/0029-reference-fields-in-stages.md @@ -109,13 +109,22 @@ Option 4, chosen when 1.10 was planned. | `GovernmentIssuedDocumentDetails` | `GovernmentIssuedDocument` | `PartyDocumentType` and the number (required), the name and the validity period | | `DocumentDirectoryEntryInstanceReference` | `DocumentDirectoryEntryReference` | `DocumentDirectoryEntryIdentification`, Max35Text, opaque | -### The other fields, in stages +### Corporate and officer references (recorded from 1.21) -| Phase | BIAN fields | -|---|---| -| 1.21 Corporate and officer references | `CorporateCustomerReference`, `CorporateCustomerLegalEntityReference`, `CompanyOfficerReference`, `CompanyOfficerRole` | +The four fields were planned for 1.20. They reference other parties, so they moved to 1.21, after the Associations BQ (1.11, ADR 0032). [ADR 0034](0034-reference-corporate-and-officer-references.md) gives the full rules. -The four fields were planned for 1.20. They reference other parties, so they moved to 1.21, after the Associations BQ (1.11, ADR 0032). +| BIAN field | Recorded as | Rule | +|---|---|---| +| `CorporateCustomerReference` | `PartyReferenceDataDirectoryEntryId` | Its `PartyReference`: another registered entry, an organisation | +| `CorporateCustomerLegalEntityReference` | `PartyReferenceDataDirectoryEntryId` | Its `PartyReference`: another registered entry, an organisation | +| `CompanyOfficerReference` | `PartyReferenceDataDirectoryEntryId` | Its `PartyReference`: another registered entry, a person | +| `CompanyOfficerRole` | `CompanyOfficerRole` | Max35Text, only with an officer | + +They are recorded only on an organisation's entry. `InvolvementReference` is refused, with no phase named. + +### The fields in stages + +Since 1.21, every BIAN Reference field is recorded and `PartyReferenceFields.Staged` is empty. A field a later BIAN release adds would be staged there with its phase. - **Refused until their phase lands.** A request that sends any of these fields with a value (not `null`) is `party.reference-field-not-supported` (400). `errors` names each field and the phase that will add it, and nothing is stored. The same applies to any other part of `GovernmentIssuedIdentityReference` or `PartyLegalEntityReference`, such as `OtherIdentification`. No phase is planned for those parts, so their message names none. - **The check comes first.** It runs before the identifiers are checked, so a request is never applied partly. @@ -126,7 +135,7 @@ The four fields were planned for 1.20. They reference other parties, so they mov ## Consequences - **Roadmap.** Rows 1.18, 1.19 and 1.20 are listed right after 1.10, and 1.21 right after 1.11. Each one removes its fields from `PartyReferenceFields.Staged`, adds them to `PartyReferenceDetails`, and updates this ADR's table. -- **Tests.** `PartyReferenceChangesTests` pins the staged fields and their phases, so a phase cannot add a field without updating the table: 22 across three phases at 1.10, 16 across 1.19 and 1.20 after 1.18, 10, all for 1.20, after 1.19, and 4, all for 1.21, since 1.20. +- **Tests.** `PartyReferenceChangesTests` pins the staged fields and their phases, so a phase cannot add a field without updating the table: 22 across three phases at 1.10, 16 across 1.19 and 1.20 after 1.18, 10, all for 1.20, after 1.19, 4, all for 1.21, after 1.20, and none since 1.21. - **Clients.** A client that sends a staged field gets a 400 that says when the field will be supported, never a silent drop. - **Uniqueness.** Identifiers are not unique across entries. A uniqueness rule (for example one LEI per entry) needs a cross-stream check and its own ADR. -- **PII.** The identifiers, from 1.18 the names, birth date, nationality and residency, from 1.19 the addresses and contact points, and from 1.20 the declared legal standing and documents, are personal data; political exposure and identity documents are sensitive. They live only in this context's stream and view, and are listed for 7.2. No new code logs them. +- **PII.** The identifiers, from 1.18 the names, birth date, nationality and residency, from 1.19 the addresses and contact points, from 1.20 the declared legal standing and documents, and from 1.21 the corporate customer's references and its officer's role, are personal data; political exposure and identity documents are sensitive. They live only in this context's stream and view, and are listed for 7.2. No new code logs them. diff --git a/docs/adr/0032-reference-legal-standing-and-documents.md b/docs/adr/0032-reference-legal-standing-and-documents.md index 8ff3fb1..a32e763 100644 --- a/docs/adr/0032-reference-legal-standing-and-documents.md +++ b/docs/adr/0032-reference-legal-standing-and-documents.md @@ -83,7 +83,7 @@ Option 3. **The directory records what the party declares, never the bank's asse ## Consequences -- **Roadmap.** Row 1.20 is reworded to the six fields. A new row, **1.21 Reference BQ: corporate and officer references**, is added after 1.11, and the four references are tagged `1.21` in `PartyReferenceFields.Staged`. +- **Roadmap.** Row 1.20 is reworded to the six fields. A new row, **1.21 Reference BQ: corporate and officer references**, is added after 1.11, and the four references are tagged `1.21` in `PartyReferenceFields.Staged`. 1.21 records them as checked directory entries on organisations only ([ADR 0034](0034-reference-corporate-and-officer-references.md)). - **Events.** `PartyReferenceUpdated` keeps its name. `PartyReferenceDetails` gains the nullable `LegalStanding` and `Documents` members, so events and views stored before 1.20 still load, fold and rebuild (proved by the PostgreSQL tests). - **Tests.** - The cross-field rules are Given / When / Then decision tests, and they are part of the entry's decider laws. diff --git a/docs/adr/0034-reference-corporate-and-officer-references.md b/docs/adr/0034-reference-corporate-and-officer-references.md new file mode 100644 index 0000000..e3c3dd9 --- /dev/null +++ b/docs/adr/0034-reference-corporate-and-officer-references.md @@ -0,0 +1,93 @@ +# 0034. Reference BQ: corporate and officer references as checked directory entries, on organisations only + +- Status: Accepted +- Date: 2026-11-08 +- Roadmap phase: 1.21 + +## Context + +[ADR 0032](0032-reference-legal-standing-and-documents.md) moved the last four BIAN Reference fields to roadmap 1.21, after the Associations BQ (1.11). They are references to other parties: + +- `CorporateCustomerReference` ("the corporate entity, Company for company customers"); +- `CorporateCustomerLegalEntityReference` ("the legal entity reference, for company customers"); +- `CompanyOfficerReference` ("one or more identified company officers for a corporate customer"). + + Each of these three is an `Involvedparty` (`PartyReference` and `InvolvementReference`, both strings). +- `CompanyOfficerRole` ("the specific role played by the identified officer", ISO 20022 `Party/Role/PartyRole`). + +What the [BIAN OpenAPI](../../doc-0/release14.0.0/apis-iso20022_ext-ddd/oas3/yamls/PartyReferenceDataDirectory.yaml) leaves open: + +- **What a `PartyReference` points at.** It is a free string. +- **The role's shape.** `CompanyOfficerRole` is typed as BIAN's `Party` schema, which has no role property (`ContactPoint`, `Identification`, `MoneyLaunderingCheck`, …). +- **How many officers.** The description says "one or more", but the schema is one object. +- **Whether the fields fit any party.** All four describe a company customer. + +[ADR 0033](0033-party-associations.md) set the rule for a link between parties in this directory: the other party is a directory entry id, checked on the write side. It rejected unchecked party links next to checked ones, because two guarantees for the same kind of link would confuse consumers. + +## Options considered + +1. **Checked entry ids, any party type.** Each `PartyReference` is a registered entry other than the party itself, and every value is allowed for a person and for an organisation, as in 1.18 and 1.20. Small, but it lets a person hold a "corporate customer", which BIAN's descriptions rule out. +2. **Checked entry ids with party-type rules.** As option 1, plus: + - only an organisation's entry holds the references; + - the corporate customer and the legal entity are organisations; + - the officer is a person. + + This is closest to BIAN's intent. It is the first party-type rule in the Reference BQ, and it needs a guard on the entry's own Update. +3. **Retire the fields to Associations.** Refuse them for good and tell clients to register associations instead. The smallest change, but BIAN Reference fields would never be recorded. +4. **Opaque text references.** Cheap, but ADR 0033 rejected unchecked party links. + +## Decision + +Option 2, chosen in the planning interview. + +### Recorded fields + +| BIAN path | Recorded as | Rule | +|---|---|---| +| `CorporateCustomerReference.PartyReference` | `PartyReferenceDataDirectoryEntryId` | A registered entry, not the party itself, of type `Organisation` | +| `CorporateCustomerLegalEntityReference.PartyReference` | `PartyReferenceDataDirectoryEntryId` | Same as above. It may be the same entry as the corporate customer | +| `CompanyOfficerReference.PartyReference` | `PartyReferenceDataDirectoryEntryId` | A registered entry, not the party itself, of type `Person`. One officer, because BIAN gives one object | +| `CompanyOfficerRole` | `CompanyOfficerRole` | A plain string, trimmed, not blank, at most 35 characters (Max35Text), for example `Director`. Only with an officer | + +- **The four live in `PartyCorporateReferences`.** It is a nullable member of `PartyReferenceDetails`, so events and views stored before 1.21 still load, fold and rebuild. +- **Partial update, as for the other Reference fields.** An omitted value keeps its value. A blank `PartyReference`, an empty object, a blank role or an empty role object clears the value. +- **Refused parts.** `InvolvementReference` is refused with `party.reference-field-not-supported` and no phase, because the role is in `CompanyOfficerRole`. So is every part of a `CompanyOfficerRole` sent as an object (BIAN's `Party` shape). + +### Rules + +- **Who checks what.** The handler loads each entry the Update **sets** through the write port (`IPartyDirectory`), never a view. The pure `Decide` then checks those loaded facts. + - References the Update keeps are not loaded again, because they were checked when they were recorded. + - An id of another stream type, such as an association, loads no entry events. So it is "not registered", never a cast failure (as in ADR 0033). +- **The order of the checks**, on the resulting Reference: + 1. Corporate references on an entry that is not an organisation are `party.corporate-references-need-organisation`. + 2. A reference to the party itself is `party.self-reference`. + 3. A reference that is not registered is `party.referenced-party-not-registered`. + 4. A reference of the wrong party type is `party.referenced-party-type-mismatch`. + 5. A role without an officer is `party.reference-invalid` naming `CompanyOfficerRole`. Clearing the officer while keeping the role is refused unless the same request clears the role, as for the political exposure description (ADR 0032). +- **The entry's Update keeps rule 1 true.** `PartyReferenceDataDirectoryEntry/Update` refuses `PartyType: Person` while corporate references are recorded, with `party.corporate-references-need-organisation`. The client clears the references first. An invariant must not depend on the order in which commands arrive. +- **Accepted drift.** A referenced entry can later change its own party type, for example the officer's entry becoming an organisation. The references that point at it are not checked again: that would need a cross-stream index on the write side, the same reason ADR 0033 gave for not enforcing uniqueness. The rule holds when a reference is recorded, and a consumer that needs the current type reads the referenced entry. +- **No link with Associations.** A Reference reference and an association are independent records. Neither is derived from the other, and a client that wants both registers both. + +### Error codes + +| Code | Kind | When | +|---|---|---| +| `party.corporate-references-need-organisation` | BusinessRule (422) | Corporate references on an entry that is not an organisation, or the entry Update to `Person` while they are recorded | +| `party.self-reference` | BusinessRule (422) | A reference names the party itself | +| `party.referenced-party-not-registered` | BusinessRule (422) | A reference names no registered entry | +| `party.referenced-party-type-mismatch` | BusinessRule (422) | The corporate customer or legal entity is not an organisation, or the officer is not a person | + +The Associations codes (`party.self-association`, `party.associate-not-registered`) are not reused, so each code names what failed. A business-rule `Error` carries no field errors ([ADR 0015](0015-problem-details-mapping.md)), so these 422 answers name the BIAN path at the start of their `detail` (for example `CompanyOfficerReference.PartyReference must name a party of type Person.`), not in `errors`. A malformed id or role is still `party.reference-invalid` (400), with the path in `errors`. + +## Consequences + +- **Staging is finished.** `PartyReferenceFields.Staged` is empty: all 24 BIAN `UpdateReference` fields are recorded. `PartyReferenceChangesTests` pins that, and `PartyReferencePartialUpdateProperties` covers the four new fields in the partial-update law. +- **The command handler reads other streams.** `UpdatePartyReferenceHandler` loads up to three more entry streams through `IPartyDirectory`, as `RegisterPartyAssociationHandler` does. It never uses a read port, so the CQRS architecture rules are unchanged. +- **HTTP.** The Reference adapter reuses the Associations `InvolvedPartyModel`. `CompanyOfficerRole` is read as raw JSON, so an object can be refused part by part instead of failing to bind. +- **PII.** Who a company's officer is, and in which role, is personal data. The values live only in this context's stream and view, are listed for 7.2, and a log-capture test proves that no new code logs them. +- **1.13 published language.** Integration events will carry these references as entry ids, so consumers keep their own copies (tech-stack §8.4). +- **Enforcement.** These tests pin the rules: + - `CorporateReferencesDecisionTests` and `PartyCorporateReferencesTests` (core); + - the `UpdatePartyReferenceHandlerTests` reference cases; + - `CorporateReferencesEndpointTests` (Alba); + - `PartyReferenceRoundTripTests` (PostgreSQL, with a view rebuild). diff --git a/specs/2026-11-08-reference-corporate-officer-refs/plan.md b/specs/2026-11-08-reference-corporate-officer-refs/plan.md index 3404803..8b363ac 100644 --- a/specs/2026-11-08-reference-corporate-officer-refs/plan.md +++ b/specs/2026-11-08-reference-corporate-officer-refs/plan.md @@ -3,26 +3,26 @@ Inside-out and test first (chosen in the interview), in the same order as 1.19 and 1.20. The solution builds and every test passes after each group. ## 1. Value objects (core `Reference/`) -- [ ] `CompanyOfficerRole`, an `IPartyReferenceText` with Max35Text that is trimmed and not blank, serialized through `PartyReferenceTextJsonConverter`. Tests first in `tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Reference/CompanyOfficerRoleTests.cs`. -- [ ] `PartyCorporateReferences` (`CorporateCustomer`, `LegalEntity`, `CompanyOfficer`, all `PartyReferenceDataDirectoryEntryId?`, plus `CompanyOfficerRole?`), with `IsEmpty` and `ReferencedEntries` (the ids that are set). Tests: `PartyCorporateReferencesTests`. -- [ ] Add the new member to `PartyReferenceDetails`: `CorporateReferences`, nullable and `[JsonIgnore]`-computed, with a `CurrentCorporateReferences` accessor. Extend `PartyReferenceDetailsTests` with a check that pre-1.21 JSON still deserialises. +- [x] `CompanyOfficerRole`, an `IPartyReferenceText` with Max35Text that is trimmed and not blank, serialized through `PartyReferenceTextJsonConverter`. Tests first in `tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Reference/CompanyOfficerRoleTests.cs`. +- [x] `PartyCorporateReferences` (`CorporateCustomer`, `LegalEntity`, `CompanyOfficer`, all `PartyReferenceDataDirectoryEntryId?`, plus `CompanyOfficerRole?`), with `IsEmpty` and `ReferencedEntries` (the ids that are set). Tests: `PartyCorporateReferencesTests`. +- [x] Add the new member to `PartyReferenceDetails`: `CorporateReferences`, nullable and `[JsonIgnore]`-computed, with a `CurrentCorporateReferences` accessor. Extend `PartyReferenceDetailsTests` with a check that pre-1.21 JSON still deserialises. ## 2. Changes, decisions, handler, entry guard, projection and HTTP (one commit) -- [ ] `PartyReferenceFields`: +- [x] `PartyReferenceFields`: - add constants for the four paths and their `.PartyReference` parts; - empty `Staged`; - list `….InvolvementReference` (all three) and object-shaped `CompanyOfficerRole` parts as not recorded. -- [ ] `PartyReferenceInput` and `PartyReferenceChanges`: +- [x] `PartyReferenceInput` and `PartyReferenceChanges`: - read the three ids as Guid v7 entry ids (`party.reference-invalid` naming `….PartyReference`); - read the role; - blank clears, omitted keeps. -- [ ] Update `PartyReferenceChangesTests`: the staged pin goes 4 → 0, and add the new unsupported parts. -- [ ] **Decide (`PartyReferenceDataDirectoryEntry` Reference decision):** +- [x] Update `PartyReferenceChangesTests`: the staged pin goes 4 → 0, and add the new unsupported parts. +- [x] **Decide (`PartyReferenceDataDirectoryEntry` Reference decision):** - `UpdatePartyReferenceDetails` gains `ReferencedParties` (an id → `PartyType?` lookup, where `null` means not registered); - - the checks run in this order: self-reference → not registered → type mismatch → the entry is not an Organisation (on the resulting Reference) → role without an officer (on the result); + - the checks run in this order: the entry is not an Organisation (on the resulting Reference) → self-reference → not registered → type mismatch → the existing date and PEP rules → role without an officer (on the result). The entry's own type comes first, because no reference can be recorded on a person at all; - add the errors to `PartyReferenceErrors`: `SelfReference`, `ReferencedPartyNotRegistered`, `ReferencedPartyTypeMismatch`, `CorporateReferencesNeedOrganisation`. - Given/When/Then tests go in `UpdatePartyReferenceTests`. -- [ ] **Handler (`UpdatePartyReferenceHandler`):** +- [x] **Handler (`UpdatePartyReferenceHandler`):** - after the entry, version and BQ checks, load each id in the given changes through `directory.LoadEntryAsync`; - fold each one with `Evolve` into `(IsRegistered, PartyType)`; - build `ReferencedParties`, then call `Decide`. @@ -31,10 +31,10 @@ Inside-out and test first (chosen in the interview), in the same order as 1.19 a - a Person given as the corporate customer, and an Organisation given as the officer; - a Person owner; - a kept reference is not reloaded. -- [ ] **Entry Update guard:** in the entry `Decide` for `UpdatePartyReferenceDataDirectoryEntryDetails`, refuse `PartyType = Person` when `CurrentReference.CurrentCorporateReferences` is not empty (`CorporateReferencesNeedOrganisation`). Add tests to the entry Update decision tests and the entry decider laws. -- [ ] **Projection:** `PartyReferenceDataDirectoryEntryViewProjection` carries `CorporateReferences` in the view's Reference section. Extend the projection test (Given events → Then view), including a pre-1.21 event. -- [ ] **HTTP (`src/RimBank.Api/Party/PartyReferenceDataDirectory/Reference/`):** - - add `InvolvedPartyModel`; +- [x] **Entry Update guard:** in the entry `Decide` for `UpdatePartyReferenceDataDirectoryEntryDetails`, refuse `PartyType = Person` when `CurrentReference.CurrentCorporateReferences` is not empty (`CorporateReferencesNeedOrganisation`). Add tests to the entry Update decision tests and the entry decider laws. +- [x] **Projection:** `PartyReferenceDataDirectoryEntryViewProjection` carries `CorporateReferences` in the view's Reference section. Extend the projection test (Given events → Then view), including a pre-1.21 event. +- [x] **HTTP (`src/RimBank.Api/Party/PartyReferenceDataDirectory/Reference/`):** + - reuse the Associations `InvolvedPartyModel`, and read `CompanyOfficerRole` as raw JSON; - add the four fields to the Update request and the Update/Retrieve response; - leave empty values out of the response; - report `InvolvementReference` and object-shaped role parts as unsupported; @@ -42,17 +42,17 @@ Inside-out and test first (chosen in the interview), in the same order as 1.19 a - Extend `PartyReferenceRequestTests` and `PartyReferenceResponseTests`. ## 3. Integration (Definition of done: adapters touched, read model rebuildable) -- [ ] In `UpdatePartyReferenceEndpointTests` and `RetrievePartyReferenceEndpointTests` (Alba): +- [x] In `UpdatePartyReferenceEndpointTests` and `RetrievePartyReferenceEndpointTests` (Alba): - a happy path that links an Organisation to an Organisation and a Person, and reads them back; - one 422 Problem Details (`party.referenced-party-not-registered`); - one 400 (`party.reference-field-not-supported` for `InvolvementReference`). -- [ ] Add a short `ReferenceScenarios` helper to register the referenced entries. -- [ ] In `PartyReferenceRoundTripTests` (Testcontainers): one case that appends the new event, rebuilds the inline view with `RebuildViewAsync`, and reads the references back. Also check that a stored pre-1.21 event still folds. +- [x] Add a short `ReferenceScenarios` helper to register the referenced entries. +- [x] In `PartyReferenceRoundTripTests` (Testcontainers): one case that appends the new event, rebuilds the inline view with `RebuildViewAsync`, and reads the references back. Also check that a stored pre-1.21 event still folds. ## 4. Demo, privacy and docs -- [ ] `src/RimBank.Host/RimBank.Host.http`: register an Organisation and a Person, run the Reference Update that links them, run the Retrieve, and show a 422 request (a Person as the corporate customer). -- [ ] `ReferenceLogPrivacyTests`: add the new fields to the submitted payload, and assert that no referenced id or role is logged. -- [ ] Write ADR 0034, and amend ADR 0029, ADR 0024 and ADR 0032. -- [ ] Update the `Reference/` tree in tech-stack §3.4. -- [ ] Roadmap: tick 1.21 and reword it to name the party-type rules. -- [ ] Run `dotnet build`, `dotnet test` and `dotnet format --verify-no-changes` locally before opening the PR (with the open-phase-pr skill). +- [x] `src/RimBank.Host/RimBank.Host.http`: register an Organisation and a Person, run the Reference Update that links them, run the Retrieve, and show a 422 request (a Person as the corporate customer). +- [x] `ReferenceLogPrivacyTests`: add the new fields to the submitted payload, and assert that no referenced id or role is logged. +- [x] Write ADR 0034, and amend ADR 0029, ADR 0024 and ADR 0032. +- [x] Update the `Reference/` tree in tech-stack §3.4. +- [x] Roadmap: tick 1.21 and reword it to name the party-type rules. +- [x] Run `dotnet build`, `dotnet test` and `dotnet format --verify-no-changes` locally before opening the PR (with the open-phase-pr skill). diff --git a/specs/2026-11-08-reference-corporate-officer-refs/requirements.md b/specs/2026-11-08-reference-corporate-officer-refs/requirements.md index 25deb84..1f903a8 100644 --- a/specs/2026-11-08-reference-corporate-officer-refs/requirements.md +++ b/specs/2026-11-08-reference-corporate-officer-refs/requirements.md @@ -56,11 +56,11 @@ Drivers: - **Refused parts:** `InvolvementReference`, at any of the three references, is refused with `party.reference-field-not-supported` and no phase. The role is carried by `CompanyOfficerRole`, as ADR 0033 did for `AssociateType`. A `CompanyOfficerRole` sent as an object (BIAN's `Party` shape) is refused the same way. - **Party-type rules (chosen in the interview):** 1. The four fields are recorded only on an **Organisation** entry. Recording one on a Person entry is `party.corporate-references-need-organisation` (422). This rule is checked in `Decide` on the resulting Reference. - 2. The corporate customer and legal entity references point at Organisation entries, and the officer at a Person entry. Otherwise the result is `party.referenced-party-type-mismatch` (422), and `errors` names the path. + 2. The corporate customer and legal entity references point at Organisation entries, and the officer at a Person entry. Otherwise the result is `party.referenced-party-type-mismatch` (422). A business-rule error carries no `errors` map (ADR 0015), so each 422 names the BIAN path at the start of its `detail`. 3. **The entry's `Update` (1.8) refuses a change of party type to `Person` while any corporate reference is recorded**, with the same `party.corporate-references-need-organisation`. The client clears the references first. Without this, rule 1 could be broken from the other side. - **Cross-aggregate checks (handler loads, `Decide` decides):** - a reference to the entry itself is `party.self-reference` (422); - - a reference that is not a registered entry is `party.referenced-party-not-registered` (422), naming the path. An association id sent as an entry id loads no events, so it fails the same way and is never a cast error (ADR 0033); + - a reference that is not a registered entry is `party.referenced-party-not-registered` (422), naming the path in its `detail`. An association id sent as an entry id loads no events, so it fails the same way and is never a cast error (ADR 0033); - only the references **given in this request** are loaded and checked. Kept ones were checked when they were recorded. - **Partial update (as in 1.18 to 1.20):** - an omitted field keeps its value, a given one replaces it, and a blank `PartyReference` or role clears it; @@ -69,7 +69,7 @@ Drivers: - **Malformed input:** an id that is not a Guid v7, or a role that is blank or too long, goes into `party.reference-invalid` (400), and `errors` names each path. The unsupported-field check still runs first, then the input reading, then the handler loads, then `Decide`. - **Staged table:** the four fields leave `PartyReferenceFields.Staged`, which becomes empty. The `PartyReferenceChangesTests` pin goes from 4 to 0. - **HTTP (`RimBank.Api/Party/PartyReferenceDataDirectory/Reference/`):** - - an `InvolvedPartyModel` (`PartyReference`, plus `InvolvementReference` read only to report it as unsupported); + - the Associations `InvolvedPartyModel` is reused (`PartyReference`, with its other parts, such as `InvolvementReference`, reported as unsupported). `CompanyOfficerRole` is read as raw JSON, so an object is refused part by part; - the Update request and the shared Update/Retrieve response gain the four fields, and empty values are left out of the response; - the new error codes are mapped through `RimBank.Problems` (`Error.BusinessRule` → 422). - **Demo:** requests in `src/RimBank.Host/RimBank.Host.http` that register an Organisation and a Person, link them through the Reference Update, and show one 422. @@ -87,7 +87,7 @@ Drivers: - **Deriving Associations from these references, or the reverse.** The two stay independent records. A client that wants both registers both. - **A role code list.** BIAN gives none, so the role is free text. No phase is planned. - **MCP tools (1.17), per-operation scopes (1.15), the Reference channels (after 7.2), and masking and encryption at rest (7.2).** -- **Checks not chosen in the interview:** extending the FsCheck partial-update law to the new fields, and a dedicated Testcontainers round-trip beyond the minimum that the Definition of done requires (see validation.md). +- **Checks not chosen in the interview:** a dedicated Testcontainers round-trip beyond the minimum that the Definition of done requires (see validation.md). The FsCheck partial-update law *was* extended in the end: its coverage test fails when a recorded field is missing from the law. ## Decisions | Decision | Choice | Rationale | diff --git a/specs/2026-11-08-reference-corporate-officer-refs/validation.md b/specs/2026-11-08-reference-corporate-officer-refs/validation.md index 0745af7..c201d06 100644 --- a/specs/2026-11-08-reference-corporate-officer-refs/validation.md +++ b/specs/2026-11-08-reference-corporate-officer-refs/validation.md @@ -40,7 +40,7 @@ Run in `src/RimBank.Host/RimBank.Host.http` against `dotnet run --project src/Ri - [ ] `POST /PartyReferenceDataDirectory/Register` for an Organisation (A), another Organisation (B) and a Person (P) gives three 201 responses, each with an `ETag`. - [ ] `PUT /PartyReferenceDataDirectory/{A}/Reference/{refId}/Update` with `If-Match` and an `Idempotency-Key`, and the body `{"CorporateCustomerReference":{"PartyReference":""},"CorporateCustomerLegalEntityReference":{"PartyReference":""},"CompanyOfficerReference":{"PartyReference":"

"},"CompanyOfficerRole":"Director"}`, gives a 200 that echoes the four fields and a new `ETag`. - [ ] `GET /PartyReferenceDataDirectory/{A}/Reference/{refId}/Retrieve` returns the same four fields. -- [ ] The same Update with `"CorporateCustomerReference":{"PartyReference":"

"}` gives a **422** `application/problem+json` with `errorCode: party.referenced-party-type-mismatch` and `errors` naming `CorporateCustomerReference.PartyReference`. +- [ ] The same Update with `"CorporateCustomerReference":{"PartyReference":"

"}` gives a **422** `application/problem+json` with `errorCode: party.referenced-party-type-mismatch` and a `detail` that starts with `CorporateCustomerReference.PartyReference`. - [ ] An Update with `"CompanyOfficerReference":{"PartyReference":"

","InvolvementReference":"x"}` gives a **400** `party.reference-field-not-supported`. - [ ] `PUT /PartyReferenceDataDirectory/{A}/Update` with `PartyType: Person` gives a **422** `party.corporate-references-need-organisation`. diff --git a/specs/roadmap.md b/specs/roadmap.md index 684a8a3..bb96692 100644 --- a/specs/roadmap.md +++ b/specs/roadmap.md @@ -57,7 +57,7 @@ - [x] **1.19 Reference BQ: addresses and contact points:** `ResidentialAddress`, `PartyAddress` and `CorporateAddress` (ISO 20022 postal address), and `eMailAddress`, `CellPhoneNumber` and `SocialNetworkContacts`, added to the Reference Update and Retrieve. - [x] **1.20 Reference BQ: legal standing, political exposure and documents:** `PartyLegalStructure`, `PoliticalExposureType`, `PoliticalExposureDescriptionRecord`, `CustomerSinceDate`, `GovernmentIssuedDocumentDetails` and `DocumentDirectoryEntryInstanceReference`, as the party declares them (never the bank's assessment, [ADR 0032](../docs/adr/0032-reference-legal-standing-and-documents.md)), added to the Reference Update and Retrieve. - [x] **1.11 Associations BQ:** party-to-party relationships as their own aggregate `PartyAssociation` (ADR 0024), with its own stream and inline view; Register/Update commands (owner and associate checked on the write side) and Retrieve query. It records the associate, the relationship type and the validity period ([ADR 0033](../docs/adr/0033-party-associations.md)). -- [ ] **1.21 Reference BQ: corporate and officer references:** `CorporateCustomerReference`, `CorporateCustomerLegalEntityReference`, `CompanyOfficerReference` and `CompanyOfficerRole`, references to other parties, added to the Reference Update and Retrieve after the Associations BQ (ADR 0032). +- [x] **1.21 Reference BQ: corporate and officer references:** `CorporateCustomerReference`, `CorporateCustomerLegalEntityReference`, `CompanyOfficerReference` and `CompanyOfficerRole`, references to other parties, added to the Reference Update and Retrieve after the Associations BQ (ADR 0032). Each reference is another registered entry, checked on the write side; they are recorded only on an organisation, the corporate customer and legal entity are organisations and the officer a person ([ADR 0034](../docs/adr/0034-reference-corporate-and-officer-references.md)). - [ ] **1.12 BankRelations BQ:** the party's relationships with the bank; Update command and Retrieve query. - [ ] **1.13 Published language:** `PartyReferenceDataDirectoryEntryCreated/Updated` integration events, mapped from domain events (not from read models), carrying the state consumers need, versioned, published through the outbox, and pinned by a schema contract test. - [ ] **1.14 Conformance:** OpenAPI and AsyncAPI conformance tests green for the implemented subset. diff --git a/specs/tech-stack.md b/specs/tech-stack.md index f54a046..d712c19 100644 --- a/specs/tech-stack.md +++ b/specs/tech-stack.md @@ -173,11 +173,13 @@ RimBank.Core/Party/PartyReferenceDataDirectory/ # namespace RimBank.Party.P │ ├─ GovernmentIssuedDocument.cs # declared documents (1.20): type, number, name and validity period, the opaque │ ├─ DocumentDirectoryEntryReference.cs # directory reference, and PartyDocuments │ ├─ PartyDocuments.cs -│ ├─ PartyReferenceDetails.cs # identifiers, names, date of birth, residency, addresses, contact points, legal standing, documents +│ ├─ CompanyOfficerRole.cs # corporate and officer references (1.21, ADR 0034): the officer's Max35Text role, and +│ ├─ PartyCorporateReferences.cs # the corporate customer, legal entity and officer as checked directory entry ids +│ ├─ PartyReferenceDetails.cs # identifiers, names, date of birth, residency, addresses, contact points, legal standing, documents, corporate references │ ├─ PartyReferenceInput.cs # the raw values an adapter sends -│ ├─ PartyReferenceChanges.cs # the partial-update changes; refuses the BIAN fields staged for 1.21 +│ ├─ PartyReferenceChanges.cs # the partial-update changes, and the entries they reference; refuses unrecorded BIAN parts │ ├─ Events.cs # PartyReferenceUpdated -│ ├─ UpdatePartyReference.cs # command, with its acknowledgement and handler +│ ├─ UpdatePartyReference.cs # command, with its acknowledgement and handler (which loads the referenced entries, 1.21) │ └─ RetrievePartyReference.cs # query over the entry's view, with its handler ├─ Associations/ # Behavior Qualifier as its own aggregate (ADR 0024, 1.11, ADR 0033) │ ├─ PartyAssociation.cs # state + evolve