From b74bd7a809da028c6e045a527ac9f5e7ea2dfead Mon Sep 17 00:00:00 2001 From: LaBani Said Date: Sun, 8 Nov 2026 18:55:46 +0100 Subject: [PATCH 1/6] Plan roadmap 1.11: Associations BQ as its own PartyAssociation aggregate Requirements, plan and validation for Register, Update and Retrieve of party associations: the associate, the relationship type and the validity period, with owner and associate checked on the write side (ADR 0024). Co-Authored-By: Claude Opus 5.5 --- .../2026-11-08-party-associations-bq/plan.md | 64 +++++++++ .../requirements.md | 136 ++++++++++++++++++ .../validation.md | 64 +++++++++ 3 files changed, 264 insertions(+) create mode 100644 specs/2026-11-08-party-associations-bq/plan.md create mode 100644 specs/2026-11-08-party-associations-bq/requirements.md create mode 100644 specs/2026-11-08-party-associations-bq/validation.md diff --git a/specs/2026-11-08-party-associations-bq/plan.md b/specs/2026-11-08-party-associations-bq/plan.md new file mode 100644 index 0000000..ded054d --- /dev/null +++ b/specs/2026-11-08-party-associations-bq/plan.md @@ -0,0 +1,64 @@ +# Plan: Party Reference Data Directory: Associations BQ + +Every group is written test first. After each group, the solution builds and its tests pass (one commit per group, one PR). +- Test namespaces end with `.Tests`, and context namespaces stay flat: every core type is in `RimBank.Party.PartyReferenceDataDirectory`, and every HTTP type in `….Api` (tech-stack §3.3, ADR 0026). +- Use switch expressions only (IDE0066). +- Business rules live in `RimBank.Core`. The adapters only translate the transport (memory: business logic in core). +- The Testcontainers and Alba tests need Docker. If it is not available locally, they run in CI. + +## 1. Domain: the `PartyAssociation` aggregate +- [ ] `Associations/PartyAssociationId.cs`: a Guid v7 `readonly record struct` implementing `ITypedId` (ADR 0008), with its typed-ID contract test. +- [ ] `Associations/PartyRelationshipType.cs` (enum, 9 values) and `PartyRelationshipTypes.cs` (BIAN spelling, reading in any case, after the `PartyTypes` pattern). +- [ ] `Associations/AssociationValidityPeriod.cs`: `Create(from?, to?)` → `Result`, reading ISO 8601 (a date alone or a value without an offset as UTC), `From` ≤ `To`, at least one bound. +- [ ] `Associations/PartyAssociationErrors.cs`: `AssociationInvalid` (Validation, with field errors), `AssociationFieldNotSupported` (Validation), `AssociateCannotChange` (BusinessRule), `AssociationNotFound` (NotFound), `SelfAssociation` and `AssociateNotRegistered` (BusinessRule). +- [ ] `Associations/AssociationFields.cs`: the BIAN paths, the recorded ones, and the refused ones with their phase (`1.21` or none), after `PartyReferenceFields`. +- [ ] `Associations/PartyAssociationChanges.cs` + `PartyAssociationInput.cs`: the raw values an adapter sends, turned into typed changes. Unsupported fields are checked first, then every value, gathered into one `party.association-invalid` naming each BIAN path. +- [ ] `Associations/Events.cs`: `PartyAssociationEvent` (base), `PartyAssociationRegistered`, `PartyAssociationUpdated`. +- [ ] `Associations/PartyAssociation.cs` (state + `Evolve`, `IDecider`) and `Decisions.cs`: + - Register decision: owner registered, associate ≠ owner, associate registered (the handler passes the two entry states); + - Update decision: the association exists, the owner matches, the expected version matches, the associate is unchanged. +- [ ] Tests in `tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Associations/`: + - `PartyRelationshipTypeTests`, `AssociationValidityPeriodTests`, `PartyAssociationChangesTests`; + - `PartyAssociationDecisionTests` (Given / When / Then) for every error code and for the accepted paths; + - FsCheck `PartyAssociationLawsProperties`: the evolve/decide laws, owner and associate never change, and an Update with no changes keeps the state. + +## 2. Command and query flows (core, in-memory ports) +- [ ] `IPartyDirectory`: `LoadAssociationAsync`, `StartAssociation`, `AppendToAssociation(id, expectedVersion, events)`; the remarks are updated. +- [ ] `IPartyDirectoryEnquiry`: `FindAssociationAsync`. +- [ ] `Associations/RegisterPartyAssociation.cs` (command, `ICommand`), `RegisterPartyAssociationAcknowledged.cs`, `RegisterPartyAssociationHandler.cs`: create the id (`TimeProvider`), load both entry streams, decide, start the stream, and acknowledge from the decided state with version 1. +- [ ] `Associations/UpdatePartyAssociation.cs` (with `ExpectedVersion`), its acknowledgement and handler: load, decide, and append with the expected version. +- [ ] `Associations/PartyAssociationView.cs` and `PartyAssociationViewProjection.cs` (pure `IProjection`, time only from event data). +- [ ] `Associations/RetrievePartyAssociation.cs` (`IQuery`) and its handler: not found, or the owner is not the path entry → `party.association-not-found`. +- [ ] `InMemoryPartyDirectory` and `InMemoryPartyDirectoryEnquiry` gain the association streams and views, with their own tests. +- [ ] Tests: + - handler tests for Register (unknown owner, self, unknown associate, accepted), Update (not found, wrong owner, stale version, another associate, accepted) and Retrieve (found, not found, wrong owner); + - `PartyAssociationViewProjectionTests` (Given events → Then view). + +## 3. PostgreSQL adapter +- [ ] `PartyReferenceDataDirectoryPostgresql.Configure`: map `party_association_registered` and `party_association_updated`, and add `AddInlineView()`. +- [ ] `MartenPartyDirectory`: the three association members (start with an exclusive stream, append with the expected version, as for the entry). +- [ ] `MartenPartyDirectoryEnquiry.FindAssociationAsync`. +- [ ] `tests/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql.Tests/PartyAssociationRoundTripTests.cs`: + - Register then Retrieve in the same store (inline read-your-write), next to an entry stream; + - Update with a stale version → `party.version-conflict`; + - the same `Idempotency-Key` and payload on Register returns the first acknowledgement and starts no second stream; + - `RebuildViewAsync` gives the same view. +- [ ] `MartenPartyDirectoryTests` / `MartenPartyDirectoryEnquiryTests` gain the association members. + +## 4. HTTP adapter +- [ ] `src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/`: + - `AssociationRouteValues.cs` (`associationsid` read as a typed id, else `shared.invalid-identifier`); + - `InvolvedPartyModel.cs`, `AssociationValidityPeriodModel.cs` (a new model: here `FromDateTime` and `ToDateTime` are plain strings, unlike the nested `DateTimeContent` of the 1.20 document period), `RegisterPartyAssociationRequest.cs`, `UpdatePartyAssociationRequest.cs`, `PartyAssociationResponse.cs`. The requests capture unknown members, so the core can refuse them by path; + - `RegisterPartyAssociationEndpoint.cs` (`POST`, `RequireIdempotencyKey()`, `ETag`), `UpdatePartyAssociationEndpoint.cs` (`PUT`, `Idempotency-Key`, `If-Match`), `RetrievePartyAssociationEndpoint.cs` (`GET`, `ETag`, `304`), each with its `OperationId`. +- [ ] `PartyReferenceDataDirectoryApi`: map the three endpoints. +- [ ] `tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/Associations/`: `RegisterPartyAssociationEndpointTests`, `UpdatePartyAssociationEndpointTests`, `RetrievePartyAssociationEndpointTests` (see validation.md). +- [ ] `PartyReferenceDataDirectoryConformanceTests._implemented` gains the three operation ids. +- [ ] `src/RimBank.Host/RimBank.Host.http`: an "Associations BQ (roadmap 1.11, ADR 0033)" block that registers a second party, associates the two, updates the period, retrieves, and shows a self-association 422. + +## 5. Docs and roadmap +- [ ] `docs/adr/0033-party-associations.md` (from `template.md`), as in requirements.md. +- [ ] ADR 0024: the "Associations requests (1.11)" paragraph, the events table, and the error codes table. +- [ ] `specs/tech-stack.md` §3.4: the `Associations/` tree and the `RimBank.Api` folder list. +- [ ] `specs/roadmap.md`: tick 1.11. +- [ ] `dotnet format --verify-no-changes` and the full `dotnet test` run. +- [ ] Add an "As built" section to this plan if the implementation differs. diff --git a/specs/2026-11-08-party-associations-bq/requirements.md b/specs/2026-11-08-party-associations-bq/requirements.md new file mode 100644 index 0000000..24a89a1 --- /dev/null +++ b/specs/2026-11-08-party-associations-bq/requirements.md @@ -0,0 +1,136 @@ +# Party Reference Data Directory: Associations BQ + +Roadmap phase: 1.11 +Branch: plan/1.11-party-associations-bq + +## Context +1.1 decided that Associations is the one Behavior Qualifier of this domain with its own lifecycle and many instances per party, so it is **its own aggregate, `PartyAssociation`**, with its own stream, typed id, version and inline view ([ADR 0024](../../docs/adr/0024-party-reference-data-directory-mapping.md), options and cross-aggregate rule). The catalogue already tags `Associations/Register`, `Associations/Update` and `Associations/Retrieve` with `1.11`, and `IPartyDirectory` / `IPartyDirectoryEnquiry` say they grow here. + +The [BIAN OpenAPI](../../doc-0/release14.0.0/apis-iso20022_ext-ddd/oas3/yamls/PartyReferenceDataDirectory.yaml) gives the three operations the same body (`RegisterAssociations`, `UpdateAssociations`, `RetrieveAssociations`): +- `AssociateReference` (`Involvedparty`: `PartyReference`, `InvolvementReference`); +- `AssociateType` (`Party_Partyrelationshiptypevalues`). The enum lists 7 values, and its description lists 2 more: `PartyIsThePowerOfAttorneyForParty` and `PartyReceivesBenefitsFromAParty`; +- `AssociationValidFromToDate` (ISO 20022 `DateTimePeriod`: `FromDateTime`, `ToDateTime` and unrelated payment parts); +- `EmployeeReference`, `AssociateObligationorDependencyDescription`, `ProductInstanceReference`, `PreferredBeneficiary`, `ProxyRepresentativePowerofAttorneyReference` and `ProductInstanseInvolvementReference`. + +**Chosen in the interview:** the core slice. 1.11 records the associate, the relationship type and the validity period. Every other field is refused, as ADR 0029 does for Reference. + +It depends on 1.2–1.8 (entry aggregate, write and read ports, Marten store, `If-Match`), all done. It unblocks **1.21** (corporate and officer references, ADR 0032) and the Associations MCP tools (**1.17**). + +Drivers: +- Mission principles: + - 3: value objects and enums, no primitive obsession; + - 4: event-sourced truth; + - 5: commands acknowledge from the decided state, and the cross-aggregate checks read the **write side**, never a view; + - 8: Problem Details; + - 10: small steps, so only three BIAN fields. +- Tech-stack: + - §3.4: the `Associations/` folder, with a flat namespace (ADR 0026); + - §5: routes, `Idempotency-Key`, `If-Match` and `ETag`; + - §7: a BQ as its own aggregate needs an ADR (ADR 0024 records it); + - §8.1–8.3: an inline single-stream view that can be rebuilt. + +**CQRS split:** +- **Command side:** + - `RegisterPartyAssociation`: the handler creates the `PartyAssociationId` (`TimeProvider`), loads the owner's and the associate's **entry streams** through `IPartyDirectory`, runs the pure `Decide`, and starts the association stream; + - `UpdatePartyAssociation`: load the association stream, check the owner and `ExpectedVersion`, decide, and append with the expected version. + - Both acknowledge from the decided state, never from the view. +- **Query side:** `RetrievePartyAssociation` reads the new **inline** `PartyAssociationView` through `IPartyDirectoryEnquiry`. There is no async projection, and no list of a party's associations (not a BIAN operation, ADR 0024). + +## Scope +### In scope +- **Aggregate `PartyAssociation` (core `Associations/`):** + - `PartyAssociationId` (Guid v7 typed id, ADR 0008); + - state: id, owner `PartyReferenceDataDirectoryEntryId`, associate `PartyReferenceDataDirectoryEntryId`, `PartyRelationshipType`, optional `AssociationValidityPeriod`; + - `Evolve` and a pure `Decide` for Register and Update, with `IDecider` (ADR 0010); + - events (`PartyAssociationEvent` base): `PartyAssociationRegistered` (the full state) and `PartyAssociationUpdated` (the full resulting type and period). +- **`PartyRelationshipType` (enum) + `PartyRelationshipTypes` (BIAN spelling):** + - the 7 enum values plus the 2 that only BIAN's description lists (ADR 0033); + - read in any case, answered in BIAN spelling; + - BIAN's enum wrapper is flattened to a plain string, as for `PartyType` (ADR 0024); + - **direction:** the record reads "the owner (path entry) *type* the associate". For example, `PartyIsParentOfParty` means the owner is the associate's parent. +- **`AssociationValidityPeriod` (value object):** + - `FromDateTime` and `ToDateTime`, both optional, at least one given; + - read as an ISO 8601 date-time (a date alone, or a value without an offset, is read as UTC) and stored as UTC `DateTimeOffset`; + - `From` ≤ `To` when both are given; + - no check against today: an association can be recorded after it ended or before it starts. A set `ToDateTime` is how an association is ended. No "active" flag is derived, because a view must not depend on the clock. +- **Register (`POST /PartyReferenceDataDirectory/{partyreferencedatadirectoryid}/Associations/Register`):** + - `AssociateReference.PartyReference` is required: an entry id RimBank issues (Guid v7); + - `AssociateType` is required; `AssociationValidFromToDate` is optional; + - checks in order: request values (400) → owner entry exists (404 `party.party-not-found`) → associate ≠ owner (422 `party.self-association`) → associate entry exists (422 `party.associate-not-registered`); + - both checks load entry streams through `IPartyDirectory` (ADR 0024 cross-aggregate rule); + - no uniqueness check: the same pair and type can be recorded twice (for example, for two periods), because uniqueness would need a cross-stream index (ADR 0033); + - requires `Idempotency-Key`; answers `200` with `ETag` `"1"`. +- **Update (`PUT …/Associations/{associationsid}/Update`):** + - a partial update, as in 1.9–1.20: an omitted field keeps its value, and a given one replaces it; + - `AssociateType` cannot be cleared (blank → `party.association-invalid`); + - an empty `AssociationValidFromToDate` object clears the period; + - `AssociateReference`: the same associate is accepted; another one is 422 `party.associate-cannot-change` (owner and associate never change, ADR 0024); + - checks in order: route ids (400 `shared.invalid-identifier`) → body values (400) → association exists and its owner is the path entry (404 `party.association-not-found`) → `If-Match` (409 `party.version-conflict`) → associate unchanged (422); + - requires `Idempotency-Key` and `If-Match` (428 / 400 / 409, ADR 0027); + - every accepted Update appends `PartyAssociationUpdated`, even when nothing changes. +- **Retrieve (`GET …/Associations/{associationsid}/Retrieve`):** + - answers from `PartyAssociationView`, with the association's version as `ETag` and `304` on a matching `If-None-Match`; + - an unknown association, or one whose owner is not the path entry, is 404 `party.association-not-found`. +- **Response (all three, `200`):** `AssociationsId`, `PartyReferenceDataDirectoryEntryId`, `AssociateReference` `{ "PartyReference": … }`, `AssociateType` in BIAN spelling, and `AssociationValidFromToDate` (each bound as ISO 8601 UTC, left out when unknown). Register and Update build it from their acknowledgement. +- **Refused fields:** every other BIAN field, `AssociateReference.InvolvementReference` and the non-date parts of `DateTimePeriod` are refused with 400 `party.association-field-not-supported`, with `errors` naming each path (and `1.21` where it applies, otherwise no phase). The check runs before the value checks, as for Reference. +- **Ports:** + - `IPartyDirectory` gains `LoadAssociationAsync`, `StartAssociation` and `AppendToAssociation`; + - `IPartyDirectoryEnquiry` gains `FindAssociationAsync`; + - in-memory test adapters in `RimBank.Core.Tests` and Marten implementations in `.Postgresql`. +- **PostgreSQL:** stable stored event names `party_association_registered` and `party_association_updated`, and `AddInlineView`. +- **HTTP (`RimBank.Api/Party/PartyReferenceDataDirectory/Associations/`):** three endpoints, the request/response models and route values, mapped in `PartyReferenceDataDirectoryApi`. +- **Demo requests** in `src/RimBank.Host/RimBank.Host.http` (approach group 4). +- **Docs:** + - new ADR 0033; + - ADR 0024 amended; + - tech-stack §3.4 updated; + - the roadmap row 1.11 ticked. + +### Out of scope +- `EmployeeReference`, `AssociateObligationorDependencyDescription`, `PreferredBeneficiary` and `ProxyRepresentativePowerofAttorneyReference`: refused, no phase planned. (The power-of-attorney link itself is recordable as `PartyIsThePowerOfAttorneyForParty`.) +- `ProductInstanceReference` and `ProductInstanseInvolvementReference`: product agreements belong to Stage 2+ contexts. Refused, no phase planned. +- The corporate and officer Reference fields: **1.21**. +- Listing a party's associations, or the inverse view (associations where a party is the associate): not a BIAN operation. A later phase would need an async cross-stream view and an ADR (ADR 0024). +- Rules tied to `PartyType` (for example, only organisations can be `PartyIsSubsidiaryOfParty`). Every type is accepted for both party types. +- Ending an association by a Control operation, or terminating an entry (deferred, ADR 0024). +- The `Associations/Created` and `Associations/Updated` channels (deferred, ADR 0024), the MCP tools (**1.17**, as for every BQ so far), per-operation scopes (**1.15**), and masking and encryption at rest (**7.2**). +- A log-capture PII test and a run of the manual demo (not chosen in the interview). + +## Decisions +| Decision | Choice | Rationale | +|---|---|---| +| Recorded fields | The associate, `AssociateType` and the validity period; everything else refused | Chosen in the interview. It is the minimum that makes an association meaningful, and principle 10 keeps the phase to about a day | +| Relationship types | The 7 enum values plus `PartyIsThePowerOfAttorneyForParty` and `PartyReceivesBenefitsFromAParty` | The BIAN description lists 9 values and the enum misses 2. RimBank follows the intent (mission "Source of truth" 3), as ADR 0032 did for `CharitableIncorporatedOrganisation` | +| Direction | "Owner *type* associate" | BIAN's value names read "Party … Party". Fixing the order once avoids two readings of the same record | +| Enum JSON shape | Plain string, with BIAN's wrapper flattened, in any case on input | Same as `PartyType` (ADR 0024) | +| Associate identity | `AssociateReference.PartyReference` must be an entry id of this directory; `InvolvementReference` refused | ADR 0024: the associate must be an entry RimBank knows. The role is carried by `AssociateType` | +| Validity period | Optional `From`/`To`, UTC `DateTimeOffset`, `From` ≤ `To`, no check against today, no derived "active" flag | BIAN types it `ISODateTime`. A projection must not depend on the clock (tech-stack §8.2) | +| Owner and associate | Fixed at Register; changing the associate is 422 `party.associate-cannot-change` | ADR 0024. A different associate is a different association, so the client registers a new one | +| Uniqueness | None | Checking it would need a cross-stream index on the write side. Duplicates are harmless, and two periods of the same link are legitimate | +| Cross-aggregate checks | Owner and associate loaded from their entry streams through `IPartyDirectory` | ADR 0024 and mission principle 5. Entries are never deleted, so a passed check stays true | +| Update semantics | Partial: omitted keeps, given replaces, an empty period clears; the type cannot be cleared | Same as 1.9–1.20 | +| New error codes | `party.association-invalid` (400), `party.association-field-not-supported` (400), `party.associate-cannot-change` (422) | One code per contract, as for Reference. The other codes are already in ADR 0024 | +| Version and `ETag` | The association's own stream version | ADR 0024 "Concurrency" | +| Work order | Domain-out, test first, one PR, one commit per group | Chosen in the interview | + +## ADRs to write +- **ADR 0033 (new): Party associations: what is recorded.** It records: + - the recorded fields and the refused ones (with phases); + - the 9 relationship types, their BIAN spelling and the direction rule; + - the validity period rules, and why there is no "active" flag; + - immutable owner and associate, and `party.associate-cannot-change`; + - no uniqueness; + - the three new error codes. + + Options considered: + - recording the free-text party references as opaque, unchecked references; + - the 7 enum values only; + - checking the period against today. +- **Amend ADR 0024:** + - an "Associations requests (1.11)" paragraph with the routes, check order, headers and response; + - the domain events table (final names); + - the error codes table (the three new codes, and the 1.11 tags). +- **Tech-stack §3.4:** the `Associations/` tree with the real files, and the `RimBank.Api` folder list gains `Associations/`. + +## Open questions +- None. diff --git a/specs/2026-11-08-party-associations-bq/validation.md b/specs/2026-11-08-party-associations-bq/validation.md new file mode 100644 index 0000000..5927d76 --- /dev/null +++ b/specs/2026-11-08-party-associations-bq/validation.md @@ -0,0 +1,64 @@ +# Validation: Party Reference Data Directory: Associations BQ + +## Done when (from roadmap) +> **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. +> + Definition of done (roadmap.md) + +The MCP tools for these operations are roadmap **1.17**, as for every BQ so far. So the Definition of done's parity item is met there, not here. + +## Automated checks +- [ ] `RimBank.Core.Tests` (`RimBank.Party.PartyReferenceDataDirectory.Tests`, folder `Associations/`): + - the typed-ID contract for `PartyAssociationId`; + - `PartyRelationshipTypeTests`: all 9 values, any case in, BIAN spelling out, an unknown value refused; + - `AssociationValidityPeriodTests`: date and date-time inputs, no offset read as UTC, `From` > `To` refused, an empty period refused; + - `PartyAssociationChangesTests`: each refused path (and its `1.21` tag where it applies), the unsupported check first, one `party.association-invalid` naming every bad path; + - `PartyAssociationDecisionTests` (Given / When / Then): `party.party-not-found`, `party.self-association`, `party.associate-not-registered`, `party.association-not-found` (missing, wrong owner), `party.version-conflict`, `party.associate-cannot-change`, the type cannot be cleared, and accepted Register and Update (an unchanged Update still appends); + - handler tests with `InMemoryPartyDirectory` / `InMemoryPartyDirectoryEnquiry` for Register, Update and Retrieve, including the check order. +- [ ] FsCheck `PartyAssociationLawsProperties`: the evolve/decide laws, owner and associate never change, and an Update with no changes keeps the state. +- [ ] Projection test (Given events → Then view) in `PartyAssociationViewProjectionTests`: Register, then Updates that replace and clear the period. +- [ ] `RimBank.Party.PartyReferenceDataDirectory.Postgresql.Tests` (Testcontainers), `PartyAssociationRoundTripTests`: + - both stream types live in the one context store; + - inline read-your-write after Register and Update; + - a stale version on the association stream → `party.version-conflict`; + - an idempotent Register (the same key returns the first acknowledgement, one stream); + - `RebuildViewAsync` gives the same `PartyAssociationView` (DoD: read models can be rebuilt). +- [ ] `RimBank.Api.Tests` (Alba), `Associations/`: + - Register `200`, with `ETag` `"1"` and the response shape; Update `200` with `ETag` `"2"`; Retrieve `200`, and `304` on a matching `If-None-Match`; + - `application/problem+json` with a stable `errorCode` for: + - 400: `shared.invalid-identifier` (each route id), `party.association-invalid` (missing associate or type, bad type, bad date, `From` > `To`, `errors` paths), `party.association-field-not-supported` (`ProductInstanceReference`, `AssociateReference.InvolvementReference`), a missing `Idempotency-Key`, `shared.if-match-invalid`; + - 404: `party.party-not-found` (Register on an unknown owner), `party.association-not-found` (unknown association, or a path entry that is not the owner, on Update and Retrieve); + - 409: `party.version-conflict`; + - 422: `party.self-association`, `party.associate-not-registered`, `party.associate-cannot-change`; + - 428: `shared.if-match-required`. +- [ ] `PartyReferenceDataDirectoryConformanceTests`: the three Associations routes are mapped with the spec's methods (`POST`, `PUT`, `GET`), and `Retrieve` is the only `GET`. +- [ ] `RimBank.Conformance.Tests` green: the catalogue rows stay `1.11`. +- [ ] `RimBank.Architecture.Tests` green: + - the new command handlers use only `IPartyDirectory` (no view, no read port); + - the query handler uses only `IPartyDirectoryEnquiry`; + - `PartyAssociationViewProjection` is pure and implements `IProjection`, and `PartyAssociation` implements `IDecider`; + - `PartyAssociationId` is a `readonly record struct`; + - flat namespaces, no `double` or `float`, no business rule in `.Api`. +- [ ] `dotnet format --verify-no-changes` clean, with no warnings. +- [ ] GitHub Actions CI green: build, test, format, CodeQL. + +## Manual / demo checks +Optional (no manual demo was chosen in the interview). The requests are in `src/RimBank.Host/RimBank.Host.http`, for reviewers: +- [ ] Run `dotnet run --project src/RimBank.AppHost`, register two parties, then send `POST /PartyReferenceDataDirectory/{ownerId}/Associations/Register` with `Idempotency-Key` and this body: + ```json + { + "AssociateReference": { "PartyReference": "" }, + "AssociateType": "partyisparentofparty", + "AssociationValidFromToDate": { "FromDateTime": "2024-01-01" } + } + ``` + Expected: 200, `ETag` `"1"`, `AssociateType` `PartyIsParentOfParty`, `FromDateTime` `2024-01-01T00:00:00Z`. +- [ ] `PUT …/Associations/{associationsid}/Update` with `If-Match: "1"` and `{"AssociationValidFromToDate":{"FromDateTime":"2024-01-01","ToDateTime":"2025-12-31"}}` → 200, `ETag` `"2"`, the type kept. +- [ ] `GET …/Associations/{associationsid}/Retrieve` → 200 with the same values; with `If-None-Match: "2"` → 304. +- [ ] Register with the owner's own id as the associate → 422 `party.self-association`. + +## Merge criteria +- [ ] All checks above pass in CI +- [ ] Roadmap checkbox 1.11 ticked in the same PR +- [ ] ADR 0033 written; ADR 0024 and tech-stack §3.4 amended +- [ ] No association value logged by new code; no secrets in source +- [ ] The PR opened with the `open-phase-pr` skill (labels, milestone, board, `Closes #`) From e65f5798b8f85f2b6389ac84671999725caef830 Mon Sep 17 00:00:00 2001 From: LaBani Said Date: Sun, 8 Nov 2026 19:02:23 +0100 Subject: [PATCH 2/6] Add the PartyAssociation aggregate: relationship types, validity period and decisions (roadmap 1.11) The Associations BQ as its own aggregate (ADR 0024): PartyAssociationId, the nine BIAN relationship types, the ISO 8601 validity period, the Register and Update input readers that refuse unrecorded fields first, and the pure Register/Update decisions with their decider laws. Co-Authored-By: Claude Opus 5.5 --- .../Associations/AssociationValidityPeriod.cs | 78 ++++++++++++ .../Associations/Decisions.cs | 86 +++++++++++++ .../Associations/Events.cs | 32 +++++ .../Associations/PartyAssociation.cs | 46 +++++++ .../Associations/PartyAssociationChanges.cs | 57 +++++++++ .../Associations/PartyAssociationErrors.cs | 84 ++++++++++++ .../Associations/PartyAssociationFields.cs | 46 +++++++ .../Associations/PartyAssociationId.cs | 42 ++++++ .../Associations/PartyAssociationInput.cs | 120 ++++++++++++++++++ .../Associations/PartyAssociationTerms.cs | 47 +++++++ .../Associations/PartyRelationshipType.cs | 36 ++++++ .../Associations/PartyRelationshipTypes.cs | 35 +++++ .../Associations/AssociationExamples.cs | 51 ++++++++ .../AssociationValidityPeriodTests.cs | 41 ++++++ .../PartyAssociationDecisionTests.cs | 113 +++++++++++++++++ .../PartyAssociationIdContractTests.cs | 5 + .../PartyAssociationInputTests.cs | 89 +++++++++++++ .../PartyAssociationLawsProperties.cs | 102 +++++++++++++++ .../PartyRelationshipTypesTests.cs | 45 +++++++ 19 files changed, 1155 insertions(+) create mode 100644 src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/AssociationValidityPeriod.cs create mode 100644 src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/Decisions.cs create mode 100644 src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/Events.cs create mode 100644 src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyAssociation.cs create mode 100644 src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyAssociationChanges.cs create mode 100644 src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyAssociationErrors.cs create mode 100644 src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyAssociationFields.cs create mode 100644 src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyAssociationId.cs create mode 100644 src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyAssociationInput.cs create mode 100644 src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyAssociationTerms.cs create mode 100644 src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyRelationshipType.cs create mode 100644 src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyRelationshipTypes.cs create mode 100644 tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Associations/AssociationExamples.cs create mode 100644 tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Associations/AssociationValidityPeriodTests.cs create mode 100644 tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Associations/PartyAssociationDecisionTests.cs create mode 100644 tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Associations/PartyAssociationIdContractTests.cs create mode 100644 tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Associations/PartyAssociationInputTests.cs create mode 100644 tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Associations/PartyAssociationLawsProperties.cs create mode 100644 tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Associations/PartyRelationshipTypesTests.cs diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/AssociationValidityPeriod.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/AssociationValidityPeriod.cs new file mode 100644 index 0000000..85c98c3 --- /dev/null +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/AssociationValidityPeriod.cs @@ -0,0 +1,78 @@ +using System.Globalization; +using RimBank.SharedKernel; + +namespace RimBank.Party.PartyReferenceDataDirectory; + +/// +/// When an association holds: BIAN AssociationValidFromToDate, the FromDateTime and ToDateTime of an +/// ISO 20022 DateTimePeriod (roadmap 1.11, ADR 0033). At least one bound is known, both are UTC, and +/// is not after . It is never compared with today: an association can be recorded +/// after it ended or before it starts, and a known is how an association is ended. +/// +/// When the association starts, if known. +/// When the association ends, if known. +public sealed record AssociationValidityPeriod(DateTimeOffset? From, DateTimeOffset? To) +{ + /// + /// Reads the period a caller sent. Each bound is an ISO 8601 date-time (one without an offset is UTC) or a date + /// (00:00 UTC that day), and is kept in UTC. + /// + /// The bounds sent; at least one is not blank. + /// + /// The period, or a validation error whose field errors name or + /// (relative to the period). + /// + public static Result TryCreate(AssociationValidityPeriodInput input) + { + ArgumentNullException.ThrowIfNull(input); + var fieldErrors = new Dictionary>(StringComparer.Ordinal); + var from = ReadBound(input.FromDateTime, PartyAssociationFields.FromDateTime, fieldErrors); + var to = ReadBound(input.ToDateTime, PartyAssociationFields.ToDateTime, fieldErrors); + + if (fieldErrors.Count == 0 && from is null && to is null) + { + fieldErrors[PartyAssociationFields.FromDateTime] = ["The validity period needs a FromDateTime, a ToDateTime or both."]; + } + + if (fieldErrors.Count == 0 && from > to) + { + fieldErrors[PartyAssociationFields.ToDateTime] = ["The end of the validity period must not be before its start."]; + } + + return fieldErrors.Count switch + { + 0 => new AssociationValidityPeriod(from, to), + _ => Error.Validation(PartyAssociationErrors.AssociationInvalidCode, "The validity period is not valid.", fieldErrors), + }; + } + + private static DateTimeOffset? ReadBound(string? text, string field, Dictionary> fieldErrors) + { + if (string.IsNullOrWhiteSpace(text)) + { + return null; + } + + if (DateOnly.TryParseExact(text.Trim(), "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var date)) + { + return new DateTimeOffset(date.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero); + } + + if (PartyReferenceDates.TryReadDateTime(text, out var dateTime)) + { + return dateTime.ToUniversalTime(); + } + + fieldErrors[field] = ["The value must be an ISO 8601 date-time, for example 2024-01-01T00:00:00Z, or date."]; + return null; + } +} + +/// The validity period a caller sent, as raw text (roadmap 1.11). +/// BIAN FromDateTime, if sent. +/// BIAN ToDateTime, if sent. +public sealed record AssociationValidityPeriodInput(string? FromDateTime, string? ToDateTime) +{ + /// Whether both bounds are missing or blank: such a period clears the recorded one. + public bool IsBlank => string.IsNullOrWhiteSpace(FromDateTime) && string.IsNullOrWhiteSpace(ToDateTime); +} diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/Decisions.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/Decisions.cs new file mode 100644 index 0000000..c5cc84f --- /dev/null +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/Decisions.cs @@ -0,0 +1,86 @@ +using System.Diagnostics; +using RimBank.SharedKernel; + +namespace RimBank.Party.PartyReferenceDataDirectory; + +/// +/// An input to the association's . It is not an : the +/// context's command handlers build it from their own commands, with the ids and the write-side checks already set. +/// +public abstract record PartyAssociationCommand; + +/// +/// Associate the owner with another party (BIAN Associations/Register). The handler creates the association id, +/// and loads the owner's and the associate's entry streams through the write port to tell whether each is registered +/// (ADR 0024, cross-aggregate rule). +/// +/// The new association. +/// The entry that owns the association. +/// The associate, type and validity period. +/// Whether the owner's entry stream holds a registered entry. +/// Whether the associate's entry stream holds a registered entry. +public sealed record RegisterPartyAssociationDetails( + PartyAssociationId AssociationId, + PartyReferenceDataDirectoryEntryId OwnerId, + PartyAssociationTerms Terms, + bool OwnerIsRegistered, + bool AssociateIsRegistered) : PartyAssociationCommand; + +/// +/// Update an association (BIAN Associations/Update): a partial update. The handler has already checked the +/// expected version. +/// +/// The entry the caller named: it must own the association. +/// The changes to apply. +public sealed record UpdatePartyAssociationDetails( + PartyReferenceDataDirectoryEntryId OwnerId, + PartyAssociationChanges Changes) : PartyAssociationCommand; + +public sealed partial record PartyAssociation +{ + /// + /// + /// Register is accepted once per association (party.association-already-registered), with a defined type + /// (party.association-invalid), then needs, in order, a registered owner (party.party-not-found), an + /// associate other than the owner (party.self-association) and a registered associate + /// (party.associate-not-registered). Update needs a registered association owned by the caller's entry + /// (party.association-not-found), a defined type (party.association-invalid) and the same associate + /// (party.associate-cannot-change), and always records the resulting type and period, even when nothing + /// changes. + /// + public static Result> Decide(PartyAssociationCommand command, PartyAssociation state) => + (command, state) switch + { + (RegisterPartyAssociationDetails, { IsRegistered: true }) => + PartyAssociationErrors.AssociationAlreadyRegistered, + (RegisterPartyAssociationDetails register, _) when !Enum.IsDefined(register.Terms.AssociateType) => + PartyAssociationErrors.AssociateTypeInvalid, + (RegisterPartyAssociationDetails { OwnerIsRegistered: false }, _) => + PartyReferenceDataDirectoryEntryErrors.PartyNotFound, + (RegisterPartyAssociationDetails register, _) when register.Terms.Associate == register.OwnerId => + PartyAssociationErrors.SelfAssociation, + (RegisterPartyAssociationDetails { AssociateIsRegistered: false }, _) => + PartyAssociationErrors.AssociateNotRegistered, + (RegisterPartyAssociationDetails register, _) => + Decision.Accept(new PartyAssociationRegistered( + register.AssociationId, + register.OwnerId, + register.Terms.Associate, + register.Terms.AssociateType, + register.Terms.ValidityPeriod)), + (UpdatePartyAssociationDetails, { IsRegistered: false }) => + PartyAssociationErrors.AssociationNotFound, + (UpdatePartyAssociationDetails update, _) when update.OwnerId != state.OwnerId => + PartyAssociationErrors.AssociationNotFound, + (UpdatePartyAssociationDetails { Changes.AssociateType: { } type }, _) when !Enum.IsDefined(type) => + PartyAssociationErrors.AssociateTypeInvalid, + (UpdatePartyAssociationDetails { Changes.Associate: { } associate }, _) when associate != state.AssociateId => + PartyAssociationErrors.AssociateCannotChange, + (UpdatePartyAssociationDetails update, { Id: { } id, AssociateType: { } current }) => + Decision.Accept(new PartyAssociationUpdated( + id, + update.Changes.AssociateType ?? current, + update.Changes.ValidityPeriod is { } period ? period.Value : state.ValidityPeriod)), + _ => throw new UnreachableException($"The association does not decide {command}."), + }; +} diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/Events.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/Events.cs new file mode 100644 index 0000000..4b43230 --- /dev/null +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/Events.cs @@ -0,0 +1,32 @@ +namespace RimBank.Party.PartyReferenceDataDirectory; + +/// A domain event of a party association (ADR 0024). Internal to this context. +public abstract record PartyAssociationEvent; + +/// +/// A party was associated with another party of the directory (BIAN Associations/Register, roadmap 1.11). Its +/// owner and associate never change afterwards. +/// +/// The new association. +/// The entry that owns the association: the path's {partyreferencedatadirectoryid}. +/// The associated entry. +/// How the owner relates to the associate. +/// When the association holds, if known. +public sealed record PartyAssociationRegistered( + PartyAssociationId AssociationId, + PartyReferenceDataDirectoryEntryId OwnerId, + PartyReferenceDataDirectoryEntryId AssociateId, + PartyRelationshipType AssociateType, + AssociationValidityPeriod? ValidityPeriod) : PartyAssociationEvent; + +/// +/// An association was updated (BIAN Associations/Update, roadmap 1.11). It carries the type and the validity +/// period the association has from now on, changed or not. +/// +/// The association. +/// How the owner relates to the associate after the update. +/// When the association holds after the update, if known. +public sealed record PartyAssociationUpdated( + PartyAssociationId AssociationId, + PartyRelationshipType AssociateType, + AssociationValidityPeriod? ValidityPeriod) : PartyAssociationEvent; diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyAssociation.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyAssociation.cs new file mode 100644 index 0000000..94e5e29 --- /dev/null +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyAssociation.cs @@ -0,0 +1,46 @@ +using System.Diagnostics; +using RimBank.SharedKernel; + +namespace RimBank.Party.PartyReferenceDataDirectory; + +/// +/// A party association, the Associations Behavior Qualifier as its own aggregate (ADR 0024): the fold of its event +/// stream. Every member is null until the association is registered. +/// +/// The association. +/// The entry that owns the association. +/// The associated entry. +/// How the owner relates to the associate. +/// When the association holds, if known. +public sealed partial record PartyAssociation( + PartyAssociationId? Id, + PartyReferenceDataDirectoryEntryId? OwnerId, + PartyReferenceDataDirectoryEntryId? AssociateId, + PartyRelationshipType? AssociateType, + AssociationValidityPeriod? ValidityPeriod) + : IDecider +{ + /// An association that is not registered yet. + public static PartyAssociation Initial { get; } = new(null, null, null, null, null); + + /// Whether the association has been registered. + public bool IsRegistered => Id is not null; + + /// + public static PartyAssociation Evolve(PartyAssociation state, PartyAssociationEvent domainEvent) => + domainEvent switch + { + PartyAssociationRegistered registered => new PartyAssociation( + registered.AssociationId, + registered.OwnerId, + registered.AssociateId, + registered.AssociateType, + registered.ValidityPeriod), + PartyAssociationUpdated updated => state with + { + AssociateType = updated.AssociateType, + ValidityPeriod = updated.ValidityPeriod, + }, + _ => throw new UnreachableException($"The association does not know {domainEvent}."), + }; +} diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyAssociationChanges.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyAssociationChanges.cs new file mode 100644 index 0000000..b64548f --- /dev/null +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyAssociationChanges.cs @@ -0,0 +1,57 @@ +using RimBank.SharedKernel; + +namespace RimBank.Party.PartyReferenceDataDirectory; + +/// +/// The changes a BIAN Associations/Update asks for: a partial update (roadmap 1.11, ADR 0033). null keeps +/// the current value. Adapters build it with . +/// +/// +/// The associate the caller named, if any. The associate never changes, so the decision only accepts the current one. +/// +/// The new relationship type, if any. It cannot be cleared. +/// The change of the validity period: a change with no value clears it. +public sealed record PartyAssociationChanges( + PartyReferenceDataDirectoryEntryId? Associate, + PartyRelationshipType? AssociateType, + AssociationValidityPeriodChange? ValidityPeriod) +{ + /// No change at all: an Update that only records that the association was reviewed. + public static PartyAssociationChanges None { get; } = new(null, null, null); + + /// + /// Reads the changes a caller sent. Fields RimBank does not record are refused first, so nothing is updated partly. + /// A blank associate or type is invalid (neither can be cleared); a blank validity period clears it. + /// + /// The values sent: null keeps. + /// The BIAN paths of the fields sent with a value that RimBank does not record. + /// + /// The changes, party.association-field-not-supported naming every unsupported field, or + /// party.association-invalid naming every invalid value. + /// + public static Result Create(PartyAssociationInput input, IReadOnlyCollection unsupportedFields) + { + ArgumentNullException.ThrowIfNull(input); + ArgumentNullException.ThrowIfNull(unsupportedFields); + if (PartyAssociationInputReader.Unsupported(unsupportedFields) is { } unsupported) + { + return unsupported; + } + + var fieldErrors = new Dictionary>(StringComparer.Ordinal); + var changes = new PartyAssociationChanges( + PartyAssociationInputReader.ReadAssociate(input.AssociatePartyReference, required: false, fieldErrors), + PartyAssociationInputReader.ReadType(input.AssociateType, required: false, fieldErrors), + PartyAssociationInputReader.ReadPeriod(input.ValidFromToDate, fieldErrors)); + + return fieldErrors.Count switch + { + 0 => changes, + _ => PartyAssociationErrors.AssociationInvalid(fieldErrors), + }; + } +} + +/// A change of an association's validity period: null clears it. +/// The new period, or null to clear it. +public sealed record AssociationValidityPeriodChange(AssociationValidityPeriod? Value); diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyAssociationErrors.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyAssociationErrors.cs new file mode 100644 index 0000000..1381cba --- /dev/null +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyAssociationErrors.cs @@ -0,0 +1,84 @@ +using RimBank.SharedKernel; + +namespace RimBank.Party.PartyReferenceDataDirectory; + +/// The Associations Behavior Qualifier's business errors; their codes are documented in ADR 0024 and ADR 0033. +public static class PartyAssociationErrors +{ + /// The code of . + public const string AssociationInvalidCode = "party.association-invalid"; + + /// The code of . + public const string AssociationFieldNotSupportedCode = "party.association-field-not-supported"; + + /// + /// The association id a caller sent is not an id the directory issues (400). It keeps the shared + /// shared.invalid-identifier code of and names . + /// + public static Error AssociationIdInvalid { get; } = Error.Validation( + TypedId.InvalidIdentifierCode, + "The value is not a valid identifier.", + new Dictionary> + { + [PartyAssociationFields.AssociationsId] = ["The associations id must be the AssociationsId returned by Associations/Register."], + }); + + /// One or more association values are not valid (400), with a message per BIAN field. + /// The BIAN field names and their messages. + /// The party.association-invalid error. + public static Error AssociationInvalid(IReadOnlyDictionary> fieldErrors) => + Error.Validation(AssociationInvalidCode, "The association values are not valid.", fieldErrors); + + /// An AssociateType that is not a BIAN relationship type (400). + public static Error AssociateTypeInvalid { get; } = AssociationInvalid(new Dictionary> + { + [PartyAssociationFields.AssociateType] = + [ + "The associate type must be one of " + string.Join(", ", Enum.GetNames()) + ".", + ], + }); + + /// + /// The request sent BIAN Associations fields RimBank does not record (400, ADR 0033), with a message per BIAN field. + /// + /// The BIAN field names and their messages. + /// The party.association-field-not-supported error. + public static Error AssociationFieldsNotSupported(IReadOnlyDictionary> fieldErrors) => + Error.Validation( + AssociationFieldNotSupportedCode, + "The request sends Associations fields that RimBank does not record; nothing was recorded.", + fieldErrors); + + /// Register on an association whose stream already exists (409). Ids are new, so only a replay meets it. + public static Error AssociationAlreadyRegistered { get; } = Error.Conflict( + "party.association-already-registered", + "This association is already registered."); + + /// The association does not exist, or the path's entry is not its owner (404, ADR 0024). + public static Error AssociationNotFound { get; } = Error.NotFound( + "party.association-not-found", + "This association does not exist for the party's directory entry."); + + /// The associate is the owning entry itself (422, ADR 0024). + public static Error SelfAssociation { get; } = Error.BusinessRule( + "party.self-association", + "A party cannot be associated with itself."); + + /// The associate is not an entry of this directory (422, ADR 0024). + public static Error AssociateNotRegistered { get; } = Error.BusinessRule( + "party.associate-not-registered", + "The associate is not registered in the directory; register it first."); + + /// An Update names another associate than the one registered (422, ADR 0033). + public static Error AssociateCannotChange { get; } = Error.BusinessRule( + "party.associate-cannot-change", + "The associate of an association never changes; register a new association instead."); + + /// + /// The version an Update expected (its If-Match) is not the association's current stream version (409, + /// ADR 0027). Same code as the entry's conflict. + /// + public static Error VersionConflict { get; } = Error.Conflict( + PartyReferenceDataDirectoryEntryErrors.VersionConflict.Code, + "The association has changed since it was read; retrieve it again and retry with its current version."); +} diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyAssociationFields.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyAssociationFields.cs new file mode 100644 index 0000000..08849d0 --- /dev/null +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyAssociationFields.cs @@ -0,0 +1,46 @@ +using System.Collections.Frozen; + +namespace RimBank.Party.PartyReferenceDataDirectory; + +/// +/// The BIAN names of the Associations fields and parameters, used as the keys of field errors so HTTP and MCP name them +/// the same way, and the BIAN Associations fields RimBank does not record (roadmap 1.11, ADR 0033). +/// +public static class PartyAssociationFields +{ + /// The BIAN parameter that names an association. + public const string AssociationsId = "associationsid"; + + /// BIAN AssociateReference, which names the associate. + public const string AssociateReference = "AssociateReference"; + + /// BIAN AssociateReference.PartyReference: the associate's directory entry id. + public const string AssociatePartyReference = AssociateReference + ".PartyReference"; + + /// BIAN AssociateType. + public const string AssociateType = "AssociateType"; + + /// BIAN AssociationValidFromToDate. + public const string AssociationValidFromToDate = "AssociationValidFromToDate"; + + /// The FromDateTime part of a validity period. + public const string FromDateTime = "FromDateTime"; + + /// The ToDateTime part of a validity period. + public const string ToDateTime = "ToDateTime"; + + /// + /// The BIAN Associations fields RimBank does not record (ADR 0033). No roadmap phase records them yet: the + /// employer contact, the obligations, the beneficiaries and the proxy are not modelled, and product agreements belong + /// to later contexts. + /// + public static FrozenSet NotRecorded { get; } = new[] + { + "EmployeeReference", + "AssociateObligationorDependencyDescription", + "ProductInstanceReference", + "PreferredBeneficiary", + "ProxyRepresentativePowerofAttorneyReference", + "ProductInstanseInvolvementReference", + }.ToFrozenSet(StringComparer.Ordinal); +} diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyAssociationId.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyAssociationId.cs new file mode 100644 index 0000000..e241758 --- /dev/null +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyAssociationId.cs @@ -0,0 +1,42 @@ +using RimBank.SharedKernel; + +namespace RimBank.Party.PartyReferenceDataDirectory; + +/// +/// Identifies a party association (the Associations Behavior Qualifier, its own aggregate): the stream id of the +/// PartyAssociation aggregate and the {associationsid} route value (ADR 0024). +/// +public readonly record struct PartyAssociationId : ITypedId +{ + private PartyAssociationId(Guid value) => Value = value; + + /// + public Guid Value { get; } + + /// + public static PartyAssociationId New(TimeProvider time) => new(TypedId.NewGuid(time)); + + /// + public static PartyAssociationId From(Guid value) => new(TypedId.EnsureValid(value)); + + /// + public static Result TryCreate(Guid value) => TypedId.TryCreate(value); + + /// + public static Result TryCreate(string? text) => TypedId.TryCreate(text); + + /// + public override string ToString() => TypedId.Format(Value); + + /// + public static bool operator <(PartyAssociationId left, PartyAssociationId right) => TypedId.Compare(left, right) < 0; + + /// + public static bool operator <=(PartyAssociationId left, PartyAssociationId right) => TypedId.Compare(left, right) <= 0; + + /// + public static bool operator >(PartyAssociationId left, PartyAssociationId right) => TypedId.Compare(left, right) > 0; + + /// + public static bool operator >=(PartyAssociationId left, PartyAssociationId right) => TypedId.Compare(left, right) >= 0; +} diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyAssociationInput.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyAssociationInput.cs new file mode 100644 index 0000000..6af4b15 --- /dev/null +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyAssociationInput.cs @@ -0,0 +1,120 @@ +using RimBank.SharedKernel; + +namespace RimBank.Party.PartyReferenceDataDirectory; + +/// +/// The raw values an adapter received for an association (BIAN RegisterAssociations or UpdateAssociations, +/// roadmap 1.11). and read them, so +/// HTTP and MCP accept and refuse exactly the same values. +/// +/// BIAN AssociateReference.PartyReference, if sent. +/// BIAN AssociateType, if sent. +/// BIAN AssociationValidFromToDate, if sent. +public sealed record PartyAssociationInput( + string? AssociatePartyReference, + string? AssociateType, + AssociationValidityPeriodInput? ValidFromToDate); + +/// Reads the values of a , gathering every invalid one. +internal static class PartyAssociationInputReader +{ + /// + /// party.association-field-not-supported naming every field in , if any. + /// + public static Error? Unsupported(IReadOnlyCollection unsupportedFields) => + unsupportedFields.Count switch + { + 0 => null, + _ => PartyAssociationErrors.AssociationFieldsNotSupported(unsupportedFields + .Distinct(StringComparer.Ordinal) + .ToDictionary( + field => field, + IReadOnlyList (_) => ["RimBank does not record this field."], + StringComparer.Ordinal)), + }; + + public static PartyReferenceDataDirectoryEntryId? ReadAssociate( + string? text, + bool required, + Dictionary> fieldErrors) + { + if (string.IsNullOrWhiteSpace(text)) + { + if (required || text is not null) + { + fieldErrors[PartyAssociationFields.AssociatePartyReference] = + ["The associate is required: the PartyReferenceDataDirectoryEntryId of a registered party."]; + } + + return null; + } + + var associate = PartyReferenceDataDirectoryEntryId.TryCreate(text.Trim()); + if (associate.IsFailure) + { + fieldErrors[PartyAssociationFields.AssociatePartyReference] = + ["The associate must be the PartyReferenceDataDirectoryEntryId returned by Register."]; + return null; + } + + return associate.Value; + } + + public static PartyRelationshipType? ReadType( + string? text, + bool required, + Dictionary> fieldErrors) + { + if (string.IsNullOrWhiteSpace(text)) + { + if (required || text is not null) + { + fieldErrors[PartyAssociationFields.AssociateType] = ["The associate type is required."]; + } + + return null; + } + + var type = PartyRelationshipTypes.Read(text); + if (type.IsFailure) + { + foreach (var (field, messages) in type.Error.FieldErrors) + { + fieldErrors[field] = messages; + } + + return null; + } + + return type.Value; + } + + /// The period sent: null when none was sent, a change with no value when a blank one was sent. + public static AssociationValidityPeriodChange? ReadPeriod( + AssociationValidityPeriodInput? input, + Dictionary> fieldErrors) + { + if (input is null) + { + return null; + } + + if (input.IsBlank) + { + return new AssociationValidityPeriodChange(null); + } + + var period = AssociationValidityPeriod.TryCreate(input); + if (period.IsFailure) + { + foreach (var (part, messages) in period.Error.FieldErrors) + { + fieldErrors[$"{PartyAssociationFields.AssociationValidFromToDate}.{part}"] = messages; + } + + return null; + } + + return new AssociationValidityPeriodChange(period.Value); + } +} diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyAssociationTerms.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyAssociationTerms.cs new file mode 100644 index 0000000..aaa75f6 --- /dev/null +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyAssociationTerms.cs @@ -0,0 +1,47 @@ +using RimBank.SharedKernel; + +namespace RimBank.Party.PartyReferenceDataDirectory; + +/// +/// What a BIAN Associations/Register records (roadmap 1.11, ADR 0033): the associate, how the owner relates to it, +/// and when the association holds. Adapters build it with . +/// +/// The associate's directory entry. Whether it is registered is the handler's check. +/// How the owner relates to the associate. +/// When the association holds, if known. +public sealed record PartyAssociationTerms( + PartyReferenceDataDirectoryEntryId Associate, + PartyRelationshipType AssociateType, + AssociationValidityPeriod? ValidityPeriod) +{ + /// + /// Reads the terms a caller sent. Fields RimBank does not record are refused first, so nothing is recorded partly. + /// The associate and the type are required; a blank validity period means none. + /// + /// The values sent. + /// The BIAN paths of the fields sent with a value that RimBank does not record. + /// + /// The terms, party.association-field-not-supported naming every unsupported field, or + /// party.association-invalid naming every missing or invalid value. + /// + public static Result Create(PartyAssociationInput input, IReadOnlyCollection unsupportedFields) + { + ArgumentNullException.ThrowIfNull(input); + ArgumentNullException.ThrowIfNull(unsupportedFields); + if (PartyAssociationInputReader.Unsupported(unsupportedFields) is { } unsupported) + { + return unsupported; + } + + var fieldErrors = new Dictionary>(StringComparer.Ordinal); + var associate = PartyAssociationInputReader.ReadAssociate(input.AssociatePartyReference, required: true, fieldErrors); + var type = PartyAssociationInputReader.ReadType(input.AssociateType, required: true, fieldErrors); + var period = PartyAssociationInputReader.ReadPeriod(input.ValidFromToDate, fieldErrors); + + return (fieldErrors.Count, associate, type) switch + { + (0, { } associateId, { } associateType) => new PartyAssociationTerms(associateId, associateType, period?.Value), + _ => PartyAssociationErrors.AssociationInvalid(fieldErrors), + }; + } +} diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyRelationshipType.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyRelationshipType.cs new file mode 100644 index 0000000..e0c3966 --- /dev/null +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyRelationshipType.cs @@ -0,0 +1,36 @@ +namespace RimBank.Party.PartyReferenceDataDirectory; + +/// +/// How the owner of an association relates to its associate: BIAN Party_Partyrelationshiptypevalues (roadmap +/// 1.11, ADR 0033). A record reads "the owner type the associate": means the +/// owner is the associate's parent. The member names are the BIAN names, and are what the store keeps. +/// +public enum PartyRelationshipType +{ + /// The owner is the parent of the associate. + PartyIsParentOfParty, + + /// The owner is a subsidiary of the associate. + PartyIsSubsidiaryOfParty, + + /// The owner is certified by the associate. + PartyIsCertifiedByParty, + + /// The owner is married to the associate. + PartyIsMarriedToParty, + + /// The owner acts on behalf of the associate. + PartyActsOnBehalfOfParty, + + /// The owner is a contact point for the associate. + PartyIsContactPointForParty, + + /// The owner is trusted by the associate. + PartyIsTrustedByParty, + + /// The owner holds a power of attorney for the associate. Listed only in BIAN's description (ADR 0033). + PartyIsThePowerOfAttorneyForParty, + + /// The owner receives benefits from the associate. Listed only in BIAN's description (ADR 0033). + PartyReceivesBenefitsFromAParty, +} diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyRelationshipTypes.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyRelationshipTypes.cs new file mode 100644 index 0000000..ab69c74 --- /dev/null +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyRelationshipTypes.cs @@ -0,0 +1,35 @@ +using RimBank.SharedKernel; + +namespace RimBank.Party.PartyReferenceDataDirectory; + +/// Reads and writes the BIAN names of (roadmap 1.11, ADR 0033). +public static class PartyRelationshipTypes +{ + /// The BIAN spelling of a relationship type, for example PartyIsParentOfParty. + /// The type. + /// Its BIAN name. + public static string ToBianName(this PartyRelationshipType type) => + Enum.IsDefined(type) + ? type.ToString() + : throw new ArgumentOutOfRangeException(nameof(type), type, "Not a party relationship type."); + + /// + /// Reads a relationship type a caller sent: trimmed, BIAN names matched without regard to case. An enum number is + /// not a name. + /// + /// The text sent, not blank. + /// The type, or party.association-invalid naming . + public static Result Read(string text) + { + ArgumentNullException.ThrowIfNull(text); + var trimmed = text.Trim(); + return Enum.GetValues() + .Where(type => string.Equals(type.ToString(), trimmed, StringComparison.OrdinalIgnoreCase)) + .Select(type => (PartyRelationshipType?)type) + .FirstOrDefault() switch + { + { } type => type, + null => PartyAssociationErrors.AssociateTypeInvalid, + }; + } +} diff --git a/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Associations/AssociationExamples.cs b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Associations/AssociationExamples.cs new file mode 100644 index 0000000..ba6b6f1 --- /dev/null +++ b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Associations/AssociationExamples.cs @@ -0,0 +1,51 @@ +namespace RimBank.Party.PartyReferenceDataDirectory.Tests; + +// Fixed values for the association's tests (roadmap 1.11), so every run decides the same commands. The owner is the +// entry of EntryExamples. +internal static class AssociationExamples +{ + public static readonly DateTimeOffset RegisteredAt = EntryExamples.OpenDate.AddDays(10); + + public static readonly PartyReferenceDataDirectoryEntryId Owner = EntryExamples.EntryId; + + public static readonly PartyReferenceDataDirectoryEntryId Associate = + PartyReferenceDataDirectoryEntryId.From(Guid.CreateVersion7(EntryExamples.OpenDate.AddMinutes(1))); + + public static readonly PartyReferenceDataDirectoryEntryId Stranger = + PartyReferenceDataDirectoryEntryId.From(Guid.CreateVersion7(EntryExamples.OpenDate.AddMinutes(2))); + + public static readonly PartyAssociationId AssociationId = PartyAssociationId.From(Guid.CreateVersion7(RegisteredAt)); + + public static readonly AssociationValidityPeriod Period = + new(new DateTimeOffset(2024, 1, 1, 0, 0, 0, TimeSpan.Zero), null); + + public static readonly AssociationValidityPeriod EndedPeriod = + new(new DateTimeOffset(2024, 1, 1, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2025, 12, 31, 0, 0, 0, TimeSpan.Zero)); + + public static PartyAssociationTerms Terms( + PartyReferenceDataDirectoryEntryId? associate = null, + PartyRelationshipType type = PartyRelationshipType.PartyIsParentOfParty, + AssociationValidityPeriod? period = null) => + new(associate ?? Associate, type, period ?? Period); + + public static RegisterPartyAssociationDetails Register( + PartyAssociationTerms? terms = null, + bool ownerIsRegistered = true, + bool associateIsRegistered = true) => + new(AssociationId, Owner, terms ?? Terms(), ownerIsRegistered, associateIsRegistered); + + public static PartyAssociationRegistered Registered( + PartyRelationshipType type = PartyRelationshipType.PartyIsParentOfParty, + AssociationValidityPeriod? period = null) => + new(AssociationId, Owner, Associate, type, period ?? Period); + + public static UpdatePartyAssociationDetails Update( + PartyAssociationChanges? changes = null, + PartyReferenceDataDirectoryEntryId? owner = null) => + new(owner ?? Owner, changes ?? PartyAssociationChanges.None); + + public static PartyAssociationUpdated Updated( + PartyRelationshipType type = PartyRelationshipType.PartyIsParentOfParty, + AssociationValidityPeriod? period = null) => + new(AssociationId, type, period); +} diff --git a/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Associations/AssociationValidityPeriodTests.cs b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Associations/AssociationValidityPeriodTests.cs new file mode 100644 index 0000000..e866fbf --- /dev/null +++ b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Associations/AssociationValidityPeriodTests.cs @@ -0,0 +1,41 @@ +namespace RimBank.Party.PartyReferenceDataDirectory.Tests; + +// BIAN AssociationValidFromToDate (roadmap 1.11, ADR 0033): ISO 8601 bounds kept in UTC, from not after to. +public sealed class AssociationValidityPeriodTests +{ + [Fact] + public void A_date_is_midnight_utc() => + AssociationValidityPeriod.TryCreate(new("2024-01-01", null)).Value + .ShouldBe(new AssociationValidityPeriod(new DateTimeOffset(2024, 1, 1, 0, 0, 0, TimeSpan.Zero), null)); + + [Fact] + public void A_date_time_with_an_offset_is_kept_in_utc() => + AssociationValidityPeriod.TryCreate(new(null, "2025-12-31T23:30:00+01:00")).Value + .ShouldBe(new AssociationValidityPeriod(null, new DateTimeOffset(2025, 12, 31, 22, 30, 0, TimeSpan.Zero))); + + [Fact] + public void A_date_time_without_an_offset_is_utc() => + AssociationValidityPeriod.TryCreate(new("2024-03-04T05:06:07", null)).Value.From + .ShouldBe(new DateTimeOffset(2024, 3, 4, 5, 6, 7, TimeSpan.Zero)); + + [Fact] + public void Both_bounds_can_be_the_same_instant() => + AssociationValidityPeriod.TryCreate(new("2024-01-01", "2024-01-01T00:00:00Z")).IsSuccess.ShouldBeTrue(); + + [Fact] + public void An_end_before_the_start_is_invalid_and_names_the_end() + { + var error = AssociationValidityPeriod.TryCreate(new("2025-01-01", "2024-12-31")).Error; + + error.Code.ShouldBe("party.association-invalid"); + error.FieldErrors.Keys.ShouldBe(["ToDateTime"]); + } + + [Theory] + [InlineData("01/01/2024", null, "FromDateTime")] + [InlineData(null, "2024-13-01", "ToDateTime")] + [InlineData(null, null, "FromDateTime")] + [InlineData(" ", "", "FromDateTime")] + public void A_bound_that_is_not_iso_8601_or_no_bound_at_all_is_invalid(string? from, string? to, string field) => + AssociationValidityPeriod.TryCreate(new(from, to)).Error.FieldErrors.Keys.ShouldBe([field]); +} diff --git a/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Associations/PartyAssociationDecisionTests.cs b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Associations/PartyAssociationDecisionTests.cs new file mode 100644 index 0000000..31fca45 --- /dev/null +++ b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Associations/PartyAssociationDecisionTests.cs @@ -0,0 +1,113 @@ +using RimBank.SharedKernel; +using static RimBank.Party.PartyReferenceDataDirectory.Tests.AssociationExamples; +using AssociationSpecification = RimBank.SharedKernel.Testing.DeciderSpecification< + RimBank.Party.PartyReferenceDataDirectory.PartyAssociation, + RimBank.Party.PartyReferenceDataDirectory.PartyAssociationCommand, + RimBank.Party.PartyReferenceDataDirectory.PartyAssociationEvent>; + +namespace RimBank.Party.PartyReferenceDataDirectory.Tests; + +// The PartyAssociation decisions (BIAN Associations/Register and Associations/Update, roadmap 1.11, ADR 0024, ADR 0033). +// Whether the owner and the associate are registered is the handler's write-side load; the expected version is the +// handler's check. +public sealed class PartyAssociationDecisionTests +{ + [Fact] + public void Registering_an_association_records_its_owner_associate_type_and_period() => + AssociationSpecification.Given() + .When(Register()) + .Then(Registered()); + + [Fact] + public void A_registration_without_a_period_records_none() => + AssociationSpecification.Given() + .When(Register(Terms() with { ValidityPeriod = null })) + .Then(new PartyAssociationRegistered(AssociationId, Owner, Associate, PartyRelationshipType.PartyIsParentOfParty, null)); + + [Fact] + public void An_unknown_owner_is_not_found_before_anything_else() => + AssociationSpecification.Given() + .When(Register(Terms(associate: Owner), ownerIsRegistered: false, associateIsRegistered: false)) + .ThenFails(ErrorKind.NotFound, "party.party-not-found"); + + [Fact] + public void A_party_cannot_be_associated_with_itself() => + AssociationSpecification.Given() + .When(Register(Terms(associate: Owner))) + .ThenFails(ErrorKind.BusinessRule, "party.self-association"); + + [Fact] + public void The_associate_must_be_registered_in_the_directory() => + AssociationSpecification.Given() + .When(Register(associateIsRegistered: false)) + .ThenFails(ErrorKind.BusinessRule, "party.associate-not-registered"); + + [Fact] + public void An_undefined_type_is_refused() => + AssociationSpecification.Given() + .When(Register(Terms(type: (PartyRelationshipType)99))) + .ThenFails(ErrorKind.Validation, "party.association-invalid"); + + [Fact] + public void An_association_is_registered_once() => + AssociationSpecification.Given(Registered()) + .When(Register()) + .ThenFails(ErrorKind.Conflict, "party.association-already-registered"); + + [Fact] + public void Updating_the_type_and_the_period_records_both() => + AssociationSpecification.Given(Registered()) + .When(Update(new PartyAssociationChanges( + null, + PartyRelationshipType.PartyIsTrustedByParty, + new AssociationValidityPeriodChange(EndedPeriod)))) + .Then(Updated(PartyRelationshipType.PartyIsTrustedByParty, EndedPeriod)); + + [Fact] + public void An_update_without_changes_keeps_everything_and_is_still_recorded() => + AssociationSpecification.Given(Registered()) + .When(Update()) + .Then(Updated(PartyRelationshipType.PartyIsParentOfParty, Period)); + + [Fact] + public void A_later_update_starts_from_what_the_previous_one_left() => + AssociationSpecification.Given(Registered(), Updated(PartyRelationshipType.PartyIsMarriedToParty, EndedPeriod)) + .When(Update()) + .Then(Updated(PartyRelationshipType.PartyIsMarriedToParty, EndedPeriod)); + + [Fact] + public void An_empty_period_change_clears_the_period() => + AssociationSpecification.Given(Registered()) + .When(Update(new PartyAssociationChanges(null, null, new AssociationValidityPeriodChange(null)))) + .Then(Updated(PartyRelationshipType.PartyIsParentOfParty, period: null)); + + [Fact] + public void Naming_the_same_associate_is_accepted() => + AssociationSpecification.Given(Registered()) + .When(Update(new PartyAssociationChanges(Associate, null, null))) + .Then(Updated(PartyRelationshipType.PartyIsParentOfParty, Period)); + + [Fact] + public void The_associate_cannot_change() => + AssociationSpecification.Given(Registered()) + .When(Update(new PartyAssociationChanges(Stranger, null, null))) + .ThenFails(ErrorKind.BusinessRule, "party.associate-cannot-change"); + + [Fact] + public void An_association_that_is_not_registered_is_not_found() => + AssociationSpecification.Given() + .When(Update()) + .ThenFails(ErrorKind.NotFound, "party.association-not-found"); + + [Fact] + public void An_association_of_another_owner_is_not_found() => + AssociationSpecification.Given(Registered()) + .When(Update(owner: Stranger)) + .ThenFails(ErrorKind.NotFound, "party.association-not-found"); + + [Fact] + public void An_undefined_type_cannot_be_set() => + AssociationSpecification.Given(Registered()) + .When(Update(new PartyAssociationChanges(null, (PartyRelationshipType)99, null))) + .ThenFails(ErrorKind.Validation, "party.association-invalid"); +} diff --git a/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Associations/PartyAssociationIdContractTests.cs b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Associations/PartyAssociationIdContractTests.cs new file mode 100644 index 0000000..ba96600 --- /dev/null +++ b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Associations/PartyAssociationIdContractTests.cs @@ -0,0 +1,5 @@ +using RimBank.SharedKernel.Testing; + +namespace RimBank.Party.PartyReferenceDataDirectory.Tests; + +public sealed class PartyAssociationIdContractTests : TypedIdContractTests; diff --git a/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Associations/PartyAssociationInputTests.cs b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Associations/PartyAssociationInputTests.cs new file mode 100644 index 0000000..6df4eb0 --- /dev/null +++ b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Associations/PartyAssociationInputTests.cs @@ -0,0 +1,89 @@ +namespace RimBank.Party.PartyReferenceDataDirectory.Tests; + +// Reading what a caller sent for Associations/Register and Associations/Update (roadmap 1.11, ADR 0033): the fields +// RimBank does not record are refused first, then every invalid value is named in one party.association-invalid. +public sealed class PartyAssociationInputTests +{ + private static readonly string _associate = AssociationExamples.Associate.ToString(); + + [Fact] + public void Register_terms_read_the_associate_the_type_and_the_period() => + PartyAssociationTerms.Create( + new PartyAssociationInput($" {_associate} ", "partyisparentofparty", new("2024-01-01", null)), + []) + .Value.ShouldBe(AssociationExamples.Terms()); + + [Fact] + public void Register_terms_without_a_period_or_with_a_blank_one_have_none() + { + PartyAssociationTerms.Create(new PartyAssociationInput(_associate, "PartyIsMarriedToParty", null), []) + .Value.ValidityPeriod.ShouldBeNull(); + PartyAssociationTerms.Create(new PartyAssociationInput(_associate, "PartyIsMarriedToParty", new("", " ")), []) + .Value.ValidityPeriod.ShouldBeNull(); + } + + [Fact] + public void Register_terms_need_the_associate_and_the_type() + { + var error = PartyAssociationTerms.Create(new PartyAssociationInput(null, " ", null), []).Error; + + error.Code.ShouldBe("party.association-invalid"); + error.FieldErrors.Keys.ShouldBe(["AssociateReference.PartyReference", "AssociateType"], ignoreOrder: true); + } + + [Fact] + public void Every_invalid_value_is_named_with_its_bian_path() + { + var error = PartyAssociationTerms.Create( + new PartyAssociationInput("not-an-id", "Cousin", new("2025-01-01", "2024-01-01")), + []) + .Error; + + error.Code.ShouldBe("party.association-invalid"); + error.FieldErrors.Keys.ShouldBe( + ["AssociateReference.PartyReference", "AssociateType", "AssociationValidFromToDate.ToDateTime"], + ignoreOrder: true); + } + + [Fact] + public void Fields_that_are_not_recorded_are_refused_before_the_values_are_read() + { + var error = PartyAssociationTerms.Create( + new PartyAssociationInput(null, null, null), + ["ProductInstanceReference", "AssociateReference.InvolvementReference", "ProductInstanceReference"]) + .Error; + + error.Code.ShouldBe("party.association-field-not-supported"); + error.FieldErrors.Keys.ShouldBe(["ProductInstanceReference", "AssociateReference.InvolvementReference"]); + } + + [Fact] + public void Update_changes_keep_what_is_left_out() => + PartyAssociationChanges.Create(new PartyAssociationInput(null, null, null), []).Value + .ShouldBe(PartyAssociationChanges.None); + + [Fact] + public void Update_changes_read_the_type_the_period_and_the_associate_named() => + PartyAssociationChanges.Create( + new PartyAssociationInput(_associate, "PartyIsTrustedByParty", new("2024-01-01", "2025-12-31")), + []) + .Value.ShouldBe(new PartyAssociationChanges( + AssociationExamples.Associate, + PartyRelationshipType.PartyIsTrustedByParty, + new AssociationValidityPeriodChange(AssociationExamples.EndedPeriod))); + + [Fact] + public void A_blank_period_clears_it() => + PartyAssociationChanges.Create(new PartyAssociationInput(null, null, new(null, "")), []).Value.ValidityPeriod + .ShouldBe(new AssociationValidityPeriodChange(null)); + + [Fact] + public void Neither_the_type_nor_the_associate_can_be_cleared() => + PartyAssociationChanges.Create(new PartyAssociationInput("", "", null), []).Error.FieldErrors.Keys + .ShouldBe(["AssociateReference.PartyReference", "AssociateType"], ignoreOrder: true); + + [Fact] + public void Update_changes_refuse_the_fields_that_are_not_recorded() => + PartyAssociationChanges.Create(new PartyAssociationInput(null, null, null), ["EmployeeReference"]).Error.Code + .ShouldBe("party.association-field-not-supported"); +} diff --git a/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Associations/PartyAssociationLawsProperties.cs b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Associations/PartyAssociationLawsProperties.cs new file mode 100644 index 0000000..afa9d7e --- /dev/null +++ b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Associations/PartyAssociationLawsProperties.cs @@ -0,0 +1,102 @@ +using FsCheck; +using FsCheck.Fluent; +using FsCheck.Xunit; +using AssociationLaws = RimBank.SharedKernel.Testing.DeciderLaws< + RimBank.Party.PartyReferenceDataDirectory.PartyAssociation, + RimBank.Party.PartyReferenceDataDirectory.PartyAssociationCommand, + RimBank.Party.PartyReferenceDataDirectory.PartyAssociationEvent>; + +namespace RimBank.Party.PartyReferenceDataDirectory.Tests; + +// The decider laws on the association (ADR 0010, roadmap 1.11), and its own: the owner and the associate never change, +// and an Update with no changes keeps the state. Each runs 100 command sequences. +public sealed class PartyAssociationLawsProperties +{ + private static readonly Gen _entries = + Gen.Elements(AssociationExamples.Owner, AssociationExamples.Associate, AssociationExamples.Stranger); + + private static readonly Gen _types = Gen.Frequency( + (6, Gen.Elements(Enum.GetValues())), + (1, Gen.Constant((PartyRelationshipType)99))); + + private static readonly Gen _periods = + Gen.Elements(null, AssociationExamples.Period, AssociationExamples.EndedPeriod); + + private static readonly Gen _mostlyRegistered = Gen.Frequency((4, Gen.Constant(true)), (1, Gen.Constant(false))); + + // Registers repeat (party.association-already-registered), the owner is sometimes the associate + // (party.self-association) and either side is sometimes not registered. + private static readonly Gen _registers = + from owner in _entries + from associate in _entries + from type in _types + from period in _periods + from ownerIsRegistered in _mostlyRegistered + from associateIsRegistered in _mostlyRegistered + select (PartyAssociationCommand)new RegisterPartyAssociationDetails( + AssociationExamples.AssociationId, + owner, + new PartyAssociationTerms(associate, type, period), + ownerIsRegistered, + associateIsRegistered); + + // Updates name any owner and associate, so party.association-not-found and party.associate-cannot-change are common. + private static readonly Gen _updates = + from owner in _entries + from associate in Gen.Frequency( + (2, Gen.Constant((PartyReferenceDataDirectoryEntryId?)null)), + (1, _entries.Select(entry => (PartyReferenceDataDirectoryEntryId?)entry))) + from type in Gen.Frequency( + (2, Gen.Constant((PartyRelationshipType?)null)), + (2, _types.Select(type => (PartyRelationshipType?)type))) + from period in Gen.Frequency( + (2, Gen.Constant((AssociationValidityPeriodChange?)null)), + (2, _periods.Select(value => (AssociationValidityPeriodChange?)new AssociationValidityPeriodChange(value)))) + select (PartyAssociationCommand)new UpdatePartyAssociationDetails(owner, new PartyAssociationChanges(associate, type, period)); + + private static readonly Gen _commands = Gen.OneOf(_registers, _updates); + + [Property] + public Property Decisions_are_deterministic() => AssociationLaws.DecisionsAreDeterministic(_commands); + + [Property] + public Property Decided_events_evolve() => AssociationLaws.DecidedEventsEvolve(_commands); + + [Property] + public Property The_owner_and_the_associate_never_change_once_registered() => + Prop.ForAll(_commands.ListOf().ToArbitrary(), commands => + { + var state = PartyAssociation.Initial; + (PartyReferenceDataDirectoryEntryId?, PartyReferenceDataDirectoryEntryId?)? parties = null; + foreach (var command in commands) + { + var decided = PartyAssociation.Decide(command, state); + if (decided.IsSuccess) + { + state = decided.Value.Aggregate(state, PartyAssociation.Evolve); + } + + parties ??= state.IsRegistered ? (state.OwnerId, state.AssociateId) : null; + if (parties is { } registered) + { + (state.OwnerId, state.AssociateId).ShouldBe(registered); + } + } + }); + + [Property] + public Property An_update_without_changes_keeps_the_state() => + Prop.ForAll(_registers.ToArbitrary(), register => + { + var registered = PartyAssociation.Decide(register, PartyAssociation.Initial); + if (registered.IsFailure) + { + return; + } + + var state = registered.Value.Aggregate(PartyAssociation.Initial, PartyAssociation.Evolve); + var update = new UpdatePartyAssociationDetails(state.OwnerId!.Value, PartyAssociationChanges.None); + + PartyAssociation.Decide(update, state).Value.Aggregate(state, PartyAssociation.Evolve).ShouldBe(state); + }); +} diff --git a/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Associations/PartyRelationshipTypesTests.cs b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Associations/PartyRelationshipTypesTests.cs new file mode 100644 index 0000000..a6f56a6 --- /dev/null +++ b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Associations/PartyRelationshipTypesTests.cs @@ -0,0 +1,45 @@ +namespace RimBank.Party.PartyReferenceDataDirectory.Tests; + +// BIAN Party_Partyrelationshiptypevalues (roadmap 1.11, ADR 0033): the 7 enum values and the 2 that only BIAN's +// description lists. +public sealed class PartyRelationshipTypesTests +{ + [Fact] + public void There_are_nine_types_named_as_bian_names_them() => + Enum.GetValues().Select(type => type.ToBianName()).ShouldBe( + [ + "PartyIsParentOfParty", + "PartyIsSubsidiaryOfParty", + "PartyIsCertifiedByParty", + "PartyIsMarriedToParty", + "PartyActsOnBehalfOfParty", + "PartyIsContactPointForParty", + "PartyIsTrustedByParty", + "PartyIsThePowerOfAttorneyForParty", + "PartyReceivesBenefitsFromAParty", + ]); + + [Theory] + [InlineData("PartyIsParentOfParty", PartyRelationshipType.PartyIsParentOfParty)] + [InlineData("partyismarriedtoparty", PartyRelationshipType.PartyIsMarriedToParty)] + [InlineData(" PARTYISTHEPOWEROFATTORNEYFORPARTY ", PartyRelationshipType.PartyIsThePowerOfAttorneyForParty)] + [InlineData("PartyReceivesBenefitsFromAParty", PartyRelationshipType.PartyReceivesBenefitsFromAParty)] + public void A_type_is_read_trimmed_and_without_regard_to_case(string text, PartyRelationshipType type) => + PartyRelationshipTypes.Read(text).Value.ShouldBe(type); + + [Theory] + [InlineData("Parent")] + [InlineData("0")] + [InlineData("Party Is Parent Of Party")] + public void Another_text_is_invalid_and_names_the_associate_type(string text) + { + var error = PartyRelationshipTypes.Read(text).Error; + + error.Code.ShouldBe("party.association-invalid"); + error.FieldErrors.Keys.ShouldBe(["AssociateType"]); + } + + [Fact] + public void An_undefined_type_has_no_bian_name() => + Should.Throw(() => ((PartyRelationshipType)99).ToBianName()); +} From c96731f7ea27f5f507b680b3f842e7690a0a166e Mon Sep 17 00:00:00 2001 From: LaBani Said Date: Sun, 8 Nov 2026 19:06:10 +0100 Subject: [PATCH 3/6] Add the Associations Register, Update and Retrieve flows with the association view (roadmap 1.11) RegisterPartyAssociation loads the owner's and the associate's entry streams through IPartyDirectory (never a view), UpdatePartyAssociation checks the owner and the expected version, and RetrievePartyAssociation reads the new PartyAssociationView. Both ports gain the association streams and views, with in-memory adapters and the Marten members. Co-Authored-By: Claude Opus 5.5 --- .../MartenPartyDirectory.cs | 25 ++++- .../MartenPartyDirectoryEnquiry.cs | 7 ++ .../PartyAssociationAcknowledged.cs | 35 ++++++ .../Associations/PartyAssociationView.cs | 27 +++++ .../PartyAssociationViewProjection.cs | 35 ++++++ .../Associations/RegisterPartyAssociation.cs | 15 +++ .../RegisterPartyAssociationHandler.cs | 58 ++++++++++ .../Associations/RetrievePartyAssociation.cs | 12 ++ .../RetrievePartyAssociationHandler.cs | 27 +++++ .../Associations/UpdatePartyAssociation.cs | 23 ++++ .../UpdatePartyAssociationHandler.cs | 45 ++++++++ .../IPartyDirectory.cs | 29 ++++- .../IPartyDirectoryEnquiry.cs | 8 +- .../PartyAssociationViewProjectionTests.cs | 34 ++++++ .../RegisterPartyAssociationHandlerTests.cs | 104 ++++++++++++++++++ .../RetrievePartyAssociationHandlerTests.cs | 38 +++++++ .../UpdatePartyAssociationHandlerTests.cs | 81 ++++++++++++++ .../InMemoryPartyDirectory.cs | 38 +++++++ .../InMemoryPartyDirectoryEnquiry.cs | 15 +++ .../Registration/RegisterPartyHandlerTests.cs | 11 ++ 20 files changed, 664 insertions(+), 3 deletions(-) create mode 100644 src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyAssociationAcknowledged.cs create mode 100644 src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyAssociationView.cs create mode 100644 src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyAssociationViewProjection.cs create mode 100644 src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/RegisterPartyAssociation.cs create mode 100644 src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/RegisterPartyAssociationHandler.cs create mode 100644 src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/RetrievePartyAssociation.cs create mode 100644 src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/RetrievePartyAssociationHandler.cs create mode 100644 src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/UpdatePartyAssociation.cs create mode 100644 src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/UpdatePartyAssociationHandler.cs create mode 100644 tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Associations/PartyAssociationViewProjectionTests.cs create mode 100644 tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Associations/RegisterPartyAssociationHandlerTests.cs create mode 100644 tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Associations/RetrievePartyAssociationHandlerTests.cs create mode 100644 tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Associations/UpdatePartyAssociationHandlerTests.cs diff --git a/src/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql/MartenPartyDirectory.cs b/src/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql/MartenPartyDirectory.cs index 4977046..5ee61f7 100644 --- a/src/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql/MartenPartyDirectory.cs +++ b/src/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql/MartenPartyDirectory.cs @@ -16,7 +16,7 @@ public async Task> LoadEntr CancellationToken cancellationToken) { var stream = await session.Events.FetchStreamAsync(entryId.Value, token: cancellationToken); - return [.. stream.Select(stored => (PartyReferenceDataDirectoryEntryEvent)stored.Data)]; + return [.. stream.Select(stored => stored.Data).OfType()]; } /// @@ -35,4 +35,27 @@ public void AppendToEntry( ArgumentNullException.ThrowIfNull(events); session.Events.Append(entryId.Value, expectedVersion + events.Count, [.. events]); } + + /// + public async Task> LoadAssociationAsync( + PartyAssociationId associationId, + CancellationToken cancellationToken) + { + var stream = await session.Events.FetchStreamAsync(associationId.Value, token: cancellationToken); + return [.. stream.Select(stored => stored.Data).OfType()]; + } + + /// + public void StartAssociation(PartyAssociationId associationId, IReadOnlyList events) + { + ArgumentNullException.ThrowIfNull(events); + session.Events.StartStream(associationId.Value, [.. events]); + } + + /// + public void AppendToAssociation(PartyAssociationId associationId, long expectedVersion, IReadOnlyList events) + { + ArgumentNullException.ThrowIfNull(events); + session.Events.Append(associationId.Value, expectedVersion + events.Count, [.. events]); + } } diff --git a/src/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql/MartenPartyDirectoryEnquiry.cs b/src/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql/MartenPartyDirectoryEnquiry.cs index 75e131d..24dde95 100644 --- a/src/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql/MartenPartyDirectoryEnquiry.cs +++ b/src/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql/MartenPartyDirectoryEnquiry.cs @@ -18,4 +18,11 @@ public sealed class MartenPartyDirectoryEnquiry(IPartyReferenceDataDirectoryStor await using var query = store.QuerySession(); return await query.LoadAsync(entryId.Value, cancellationToken); } + + /// + public async Task FindAssociationAsync(PartyAssociationId associationId, CancellationToken cancellationToken) + { + await using var query = store.QuerySession(); + return await query.LoadAsync(associationId.Value, cancellationToken); + } } diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyAssociationAcknowledged.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyAssociationAcknowledged.cs new file mode 100644 index 0000000..116409e --- /dev/null +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyAssociationAcknowledged.cs @@ -0,0 +1,35 @@ +using System.Diagnostics; + +namespace RimBank.Party.PartyReferenceDataDirectory; + +/// +/// The acknowledgement of and : the association +/// as the decision left it, never a read model (tech-stack §5 and §8.1). The idempotency policy stores it and returns it +/// again for a repeated key (ADR 0018). +/// +/// The association. +/// The association's stream version after the command, which the next Update sends back as If-Match. +/// The entry that owns the association. +/// The associated entry. +/// How the owner relates to the associate. +/// When the association holds, if known. +public sealed record PartyAssociationAcknowledged( + PartyAssociationId AssociationId, + long Version, + PartyReferenceDataDirectoryEntryId OwnerId, + PartyReferenceDataDirectoryEntryId AssociateId, + PartyRelationshipType AssociateType, + AssociationValidityPeriod? ValidityPeriod) +{ + /// The acknowledgement of a registered association at . + /// The state the decision produced. + /// Its stream version. + /// The acknowledgement. + internal static PartyAssociationAcknowledged From(PartyAssociation decided, long version) => + decided switch + { + { Id: { } id, OwnerId: { } owner, AssociateId: { } associate, AssociateType: { } type } => + new PartyAssociationAcknowledged(id, version, owner, associate, type, decided.ValidityPeriod), + _ => throw new UnreachableException("An accepted association command leaves the association registered."), + }; +} diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyAssociationView.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyAssociationView.cs new file mode 100644 index 0000000..bfa981b --- /dev/null +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyAssociationView.cs @@ -0,0 +1,27 @@ +using System.Text.Json.Serialization; + +namespace RimBank.Party.PartyReferenceDataDirectory; + +/// +/// The read model of a party association, served by BIAN Associations/Retrieve (ADR 0024, roadmap 1.11). +/// Projected inline from the association's stream by ; it holds no behaviour +/// and never feeds a decision. +/// +/// The association's stream id, the identity of the view's document. +/// The association's stream version: the ETag a Retrieve returns and an Update sends back in If-Match. +/// The entry that owns the association. +/// The associated entry. +/// How the owner relates to the associate. +/// When the association holds, if known. +public sealed record PartyAssociationView( + Guid Id, + long Version, + PartyReferenceDataDirectoryEntryId OwnerId, + PartyReferenceDataDirectoryEntryId AssociateId, + PartyRelationshipType AssociateType, + AssociationValidityPeriod? ValidityPeriod) +{ + /// The association, as its typed id. Computed from , so it is not stored. + [JsonIgnore] + public PartyAssociationId AssociationId => PartyAssociationId.From(Id); +} diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyAssociationViewProjection.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyAssociationViewProjection.cs new file mode 100644 index 0000000..c612b50 --- /dev/null +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/PartyAssociationViewProjection.cs @@ -0,0 +1,35 @@ +using RimBank.SharedKernel; + +namespace RimBank.Party.PartyReferenceDataDirectory; + +/// +/// Projects an association's events into its (tech-stack §8.2, ADR 0024). Pure: run +/// inline by Marten in the context's .Postgresql adapter, and by the core's tests without a database. +/// +/// +/// Every event of the association's stream bumps , so the view's version is +/// always the stream version. An event before leaves no view. +/// +public sealed class PartyAssociationViewProjection : IProjection +{ + /// + public static PartyAssociationView? Project(PartyAssociationView? view, PartyAssociationEvent domainEvent) => + (view, domainEvent) switch + { + (_, PartyAssociationRegistered registered) => new PartyAssociationView( + registered.AssociationId.Value, + Version: 1, + registered.OwnerId, + registered.AssociateId, + registered.AssociateType, + registered.ValidityPeriod), + (null, _) => null, + (_, PartyAssociationUpdated updated) => view with + { + Version = view.Version + 1, + AssociateType = updated.AssociateType, + ValidityPeriod = updated.ValidityPeriod, + }, + (_, _) => view with { Version = view.Version + 1 }, + }; +} diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/RegisterPartyAssociation.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/RegisterPartyAssociation.cs new file mode 100644 index 0000000..2989816 --- /dev/null +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/RegisterPartyAssociation.cs @@ -0,0 +1,15 @@ +using RimBank.SharedKernel; + +namespace RimBank.Party.PartyReferenceDataDirectory; + +/// +/// Associate a party with another party of the directory: BIAN Associations/Register (ADR 0024, ADR 0033). +/// Handled by , which acknowledges with . +/// +/// The entry that owns the association: the {partyreferencedatadirectoryid} route value. +/// The associate, type and validity period, built by . +/// The caller's key for this request (ADR 0018). The handler never reads it. +public sealed record RegisterPartyAssociation( + PartyReferenceDataDirectoryEntryId OwnerId, + PartyAssociationTerms Terms, + IdempotencyKey IdempotencyKey) : ICommand; diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/RegisterPartyAssociationHandler.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/RegisterPartyAssociationHandler.cs new file mode 100644 index 0000000..86d536d --- /dev/null +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/RegisterPartyAssociationHandler.cs @@ -0,0 +1,58 @@ +using RimBank.SharedKernel; + +namespace RimBank.Party.PartyReferenceDataDirectory; + +/// Handles on the write side (tech-stack §8.1, ADR 0024). +public static class RegisterPartyAssociationHandler +{ + /// + /// Creates the association id; loads the owner's and the associate's entry streams through the write port, never a + /// view (ADR 0024, cross-aggregate rule); decides Register and starts the association's stream only when the decision + /// accepts. + /// + /// The command. + /// The context's write port. + /// The clock for the new id. + /// Cancels the loads. + /// + /// The acknowledgement built from the decided state, or party.party-not-found, party.self-association, + /// party.associate-not-registered or another decision error. + /// + public static async Task> HandleAsync( + RegisterPartyAssociation command, + IPartyDirectory directory, + TimeProvider time, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(command); + ArgumentNullException.ThrowIfNull(directory); + ArgumentNullException.ThrowIfNull(time); + + var associationId = PartyAssociationId.New(time); + var owner = await IsRegisteredAsync(directory, command.OwnerId, cancellationToken); + var associate = command.Terms.Associate == command.OwnerId + ? owner + : await IsRegisteredAsync(directory, command.Terms.Associate, cancellationToken); + var history = await directory.LoadAssociationAsync(associationId, cancellationToken); + var state = history.Aggregate(PartyAssociation.Initial, PartyAssociation.Evolve); + + return PartyAssociation + .Decide(new RegisterPartyAssociationDetails(associationId, command.OwnerId, command.Terms, owner, associate), state) + .Map(events => + { + directory.StartAssociation(associationId, events); + return PartyAssociationAcknowledged.From( + events.Aggregate(state, PartyAssociation.Evolve), + history.Count + events.Count); + }); + } + + private static async Task IsRegisteredAsync( + IPartyDirectory directory, + PartyReferenceDataDirectoryEntryId entryId, + CancellationToken cancellationToken) + { + var history = await directory.LoadEntryAsync(entryId, cancellationToken); + return history.Aggregate(PartyReferenceDataDirectoryEntry.Initial, PartyReferenceDataDirectoryEntry.Evolve).IsRegistered; + } +} diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/RetrievePartyAssociation.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/RetrievePartyAssociation.cs new file mode 100644 index 0000000..90bad00 --- /dev/null +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/RetrievePartyAssociation.cs @@ -0,0 +1,12 @@ +using RimBank.SharedKernel; + +namespace RimBank.Party.PartyReferenceDataDirectory; + +/// +/// Retrieve an association: BIAN Associations/Retrieve (ADR 0024). Handled by +/// , which reads the association's view. +/// +/// The entry the caller named: the {partyreferencedatadirectoryid} route value. +/// The association: the {associationsid} route value. +public sealed record RetrievePartyAssociation(PartyReferenceDataDirectoryEntryId OwnerId, PartyAssociationId AssociationId) + : IQuery; diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/RetrievePartyAssociationHandler.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/RetrievePartyAssociationHandler.cs new file mode 100644 index 0000000..eef1945 --- /dev/null +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/RetrievePartyAssociationHandler.cs @@ -0,0 +1,27 @@ +using RimBank.SharedKernel; + +namespace RimBank.Party.PartyReferenceDataDirectory; + +/// Handles on the read side (tech-stack §8.2, ADR 0024). +public static class RetrievePartyAssociationHandler +{ + /// Reads the association's view through the read port and checks that the caller's entry owns it. + /// The query. + /// The context's read port. + /// Cancels the read. + /// The association's view, or party.association-not-found when it does not exist or has another owner. + public static async Task> HandleAsync( + RetrievePartyAssociation query, + IPartyDirectoryEnquiry enquiry, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(query); + ArgumentNullException.ThrowIfNull(enquiry); + + return await enquiry.FindAssociationAsync(query.AssociationId, cancellationToken) switch + { + { } view when view.OwnerId == query.OwnerId => view, + _ => PartyAssociationErrors.AssociationNotFound, + }; + } +} diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/UpdatePartyAssociation.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/UpdatePartyAssociation.cs new file mode 100644 index 0000000..9f2545b --- /dev/null +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/UpdatePartyAssociation.cs @@ -0,0 +1,23 @@ +using RimBank.SharedKernel; + +namespace RimBank.Party.PartyReferenceDataDirectory; + +/// +/// Update an association: BIAN Associations/Update (ADR 0024, ADR 0033), a partial update of its type and validity +/// period. Handled by , which acknowledges with +/// . +/// +/// The entry the caller named: the {partyreferencedatadirectoryid} route value. +/// The association: the {associationsid} route value. +/// +/// The association's stream version the caller last read (its If-Match, ADR 0027). Any other current version is +/// party.version-conflict. +/// +/// The changes, built by . +/// The caller's key for this request (ADR 0018). The handler never reads it. +public sealed record UpdatePartyAssociation( + PartyReferenceDataDirectoryEntryId OwnerId, + PartyAssociationId AssociationId, + long ExpectedVersion, + PartyAssociationChanges Changes, + IdempotencyKey IdempotencyKey) : ICommand; diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/UpdatePartyAssociationHandler.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/UpdatePartyAssociationHandler.cs new file mode 100644 index 0000000..0a32ad6 --- /dev/null +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/UpdatePartyAssociationHandler.cs @@ -0,0 +1,45 @@ +using RimBank.SharedKernel; + +namespace RimBank.Party.PartyReferenceDataDirectory; + +/// Handles on the write side (tech-stack §8.1, ADR 0024, ADR 0027). +public static class UpdatePartyAssociationHandler +{ + /// + /// Loads the association; checks that it exists and is owned by the caller's entry, then that the caller's expected + /// version is current; decides the Update and appends it with that expected version. + /// + /// The command. + /// The context's write port. + /// Cancels the load. + /// + /// The acknowledgement built from the decided state, party.association-not-found, + /// party.version-conflict or the decision's error. + /// + public static async Task> HandleAsync( + UpdatePartyAssociation command, + IPartyDirectory directory, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(command); + ArgumentNullException.ThrowIfNull(directory); + + var history = await directory.LoadAssociationAsync(command.AssociationId, cancellationToken); + var state = history.Aggregate(PartyAssociation.Initial, PartyAssociation.Evolve); + + return (state.IsRegistered && state.OwnerId == command.OwnerId, history.Count == command.ExpectedVersion) switch + { + (false, _) => PartyAssociationErrors.AssociationNotFound, + (true, false) => PartyAssociationErrors.VersionConflict, + (true, true) => PartyAssociation + .Decide(new UpdatePartyAssociationDetails(command.OwnerId, command.Changes), state) + .Map(events => + { + directory.AppendToAssociation(command.AssociationId, command.ExpectedVersion, events); + return PartyAssociationAcknowledged.From( + events.Aggregate(state, PartyAssociation.Evolve), + history.Count + events.Count); + }), + }; + } +} diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/IPartyDirectory.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/IPartyDirectory.cs index acbda4a..1f504c7 100644 --- a/src/RimBank.Core/Party/PartyReferenceDataDirectory/IPartyDirectory.cs +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/IPartyDirectory.cs @@ -8,7 +8,8 @@ namespace RimBank.Party.PartyReferenceDataDirectory; /// .Postgresql adapter. /// /// -/// It grows with the operations that need it: Associations (1.11) add the PartyAssociation streams. +/// It holds the two stream types of the context: the entries and, from roadmap 1.11, the PartyAssociation streams. +/// Loading a stream of the other type gives no events, so an association id is never mistaken for an entry. /// public interface IPartyDirectory : IWritePort { @@ -40,4 +41,30 @@ void AppendToEntry( PartyReferenceDataDirectoryEntryId entryId, long expectedVersion, IReadOnlyList events); + + /// Loads the events of an association, oldest first (roadmap 1.11). + /// The association. + /// Cancels the load. + /// The association's history, empty if the association does not exist. + Task> LoadAssociationAsync( + PartyAssociationId associationId, + CancellationToken cancellationToken); + + /// + /// Starts the stream of a new association with . The stream is only staged: the handler's + /// transaction commits it, and fails if a stream with the same id already exists. + /// + /// The new association. + /// The events its decision returned. + void StartAssociation(PartyAssociationId associationId, IReadOnlyList events); + + /// + /// Appends to an existing association whose stream is at + /// (ADR 0027). The events are only staged: the handler's transaction commits them, and fails if another writer + /// appended to the stream in the meantime. + /// + /// The association. + /// The stream version the handler decided against. + /// The events its decision returned. + void AppendToAssociation(PartyAssociationId associationId, long expectedVersion, IReadOnlyList events); } diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/IPartyDirectoryEnquiry.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/IPartyDirectoryEnquiry.cs index b18eeb1..c737457 100644 --- a/src/RimBank.Core/Party/PartyReferenceDataDirectory/IPartyDirectoryEnquiry.cs +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/IPartyDirectoryEnquiry.cs @@ -7,7 +7,7 @@ namespace RimBank.Party.PartyReferenceDataDirectory; /// and §8.2, ADR 0024). Its Marten implementation, over the inline-projected documents, lives in the context's /// .Postgresql adapter. Command handlers never use it. /// -/// It grows with the queries that need it: Associations (1.11) add the association view. +/// It reads the entry views and, from roadmap 1.11, the association views. public interface IPartyDirectoryEnquiry : IReadPort { /// Finds the view of an entry. @@ -17,4 +17,10 @@ public interface IPartyDirectoryEnquiry : IReadPort Task FindEntryAsync( PartyReferenceDataDirectoryEntryId entryId, CancellationToken cancellationToken); + + /// Finds the view of an association (roadmap 1.11). + /// The association. + /// Cancels the read. + /// The association's view, or null if the association does not exist. + Task FindAssociationAsync(PartyAssociationId associationId, CancellationToken cancellationToken); } diff --git a/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Associations/PartyAssociationViewProjectionTests.cs b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Associations/PartyAssociationViewProjectionTests.cs new file mode 100644 index 0000000..f5b792a --- /dev/null +++ b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Associations/PartyAssociationViewProjectionTests.cs @@ -0,0 +1,34 @@ +using static RimBank.Party.PartyReferenceDataDirectory.Tests.AssociationExamples; +using AssociationViewSpecification = RimBank.SharedKernel.Testing.ProjectionSpecification< + RimBank.Party.PartyReferenceDataDirectory.PartyAssociationViewProjection, + RimBank.Party.PartyReferenceDataDirectory.PartyAssociationView, + RimBank.Party.PartyReferenceDataDirectory.PartyAssociationEvent>; + +namespace RimBank.Party.PartyReferenceDataDirectory.Tests; + +// The association's view, projected from its events (roadmap 1.11, tech-stack §8.2): Given events → Then view. +public sealed class PartyAssociationViewProjectionTests +{ + [Fact] + public void A_registered_association_has_a_view_at_version_one() => + AssociationViewSpecification.Given(Registered()) + .Then(new PartyAssociationView(AssociationId.Value, 1, Owner, Associate, PartyRelationshipType.PartyIsParentOfParty, Period)); + + [Fact] + public void An_update_replaces_the_type_and_the_period() => + AssociationViewSpecification.Given(Registered(), Updated(PartyRelationshipType.PartyIsTrustedByParty, EndedPeriod)) + .Then(new PartyAssociationView(AssociationId.Value, 2, Owner, Associate, PartyRelationshipType.PartyIsTrustedByParty, EndedPeriod)); + + [Fact] + public void An_update_can_clear_the_period() => + AssociationViewSpecification.Given(Registered(), Updated(PartyRelationshipType.PartyIsTrustedByParty, EndedPeriod), Updated()) + .Then(new PartyAssociationView(AssociationId.Value, 3, Owner, Associate, PartyRelationshipType.PartyIsParentOfParty, null)); + + [Fact] + public void An_update_before_the_registration_leaves_no_view() => + AssociationViewSpecification.Given(Updated()).ThenNoView(); + + [Fact] + public void The_view_names_its_association() => + PartyAssociationViewProjection.Project(null, Registered())!.AssociationId.ShouldBe(AssociationId); +} diff --git a/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Associations/RegisterPartyAssociationHandlerTests.cs b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Associations/RegisterPartyAssociationHandlerTests.cs new file mode 100644 index 0000000..5a0816a --- /dev/null +++ b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Associations/RegisterPartyAssociationHandlerTests.cs @@ -0,0 +1,104 @@ +using RimBank.SharedKernel; +using RimBank.SharedKernel.Testing; +using static RimBank.Party.PartyReferenceDataDirectory.Tests.AssociationExamples; + +namespace RimBank.Party.PartyReferenceDataDirectory.Tests; + +// The Associations/Register flow on the command side (roadmap 1.11, ADR 0024): the owner and the associate are loaded +// from their entry streams through the write port, the decision runs, and the association's stream starts. +public sealed class RegisterPartyAssociationHandlerTests +{ + private static readonly IdempotencyKey _key = IdempotencyKey.From("register-association-1"); + + private readonly InMemoryPartyDirectory _directory = new(); + + private readonly FixedTimeProvider _time = new(RegisteredAt); + + [Fact] + public async Task Registering_starts_the_association_stream_and_acknowledges_version_one() + { + SeedEntries(Owner, Associate); + + var acknowledged = (await Register(Terms())).Value; + + acknowledged.Version.ShouldBe(1); + acknowledged.OwnerId.ShouldBe(Owner); + acknowledged.AssociateId.ShouldBe(Associate); + acknowledged.AssociateType.ShouldBe(PartyRelationshipType.PartyIsParentOfParty); + acknowledged.ValidityPeriod.ShouldBe(Period); + _directory.Associations.ShouldBe([acknowledged.AssociationId]); + _directory.StreamOf(acknowledged.AssociationId).ShouldBe( + [ + new PartyAssociationRegistered(acknowledged.AssociationId, Owner, Associate, PartyRelationshipType.PartyIsParentOfParty, Period), + ]); + } + + [Fact] + public async Task The_association_id_is_a_new_version_7_id_from_the_clock() + { + SeedEntries(Owner, Associate); + + var acknowledged = (await Register(Terms())).Value; + + acknowledged.AssociationId.Value.Version.ShouldBe(7); + } + + [Fact] + public async Task An_unknown_owner_is_not_found_and_nothing_is_started() + { + SeedEntries(Associate); + + var result = await Register(Terms()); + + result.Error.ShouldBe(PartyReferenceDataDirectoryEntryErrors.PartyNotFound); + _directory.Associations.ShouldBeEmpty(); + } + + [Fact] + public async Task The_owner_cannot_be_its_own_associate() + { + SeedEntries(Owner); + + var result = await Register(Terms(associate: Owner)); + + result.Error.ShouldBe(PartyAssociationErrors.SelfAssociation); + _directory.Associations.ShouldBeEmpty(); + } + + [Fact] + public async Task An_associate_that_is_not_in_the_directory_is_refused() + { + SeedEntries(Owner); + + var result = await Register(Terms(associate: Stranger)); + + result.Error.ShouldBe(PartyAssociationErrors.AssociateNotRegistered); + _directory.Associations.ShouldBeEmpty(); + } + + [Fact] + public async Task An_association_id_is_not_an_entry_and_cannot_be_an_associate() + { + SeedEntries(Owner); + _directory.Seed(AssociationId, Registered()); + + var result = await Register(Terms(associate: PartyReferenceDataDirectoryEntryId.From(AssociationId.Value))); + + result.Error.ShouldBe(PartyAssociationErrors.AssociateNotRegistered); + } + + private void SeedEntries(params PartyReferenceDataDirectoryEntryId[] entries) + { + foreach (var entry in entries) + { + _directory.Seed(entry, EntryExamples.Registered() with { EntryId = entry }); + } + } + + private Task> Register(PartyAssociationTerms terms) => + RegisterPartyAssociationHandler.HandleAsync( + new RegisterPartyAssociation(Owner, terms, _key), + _directory, + _time, + TestContext.Current.CancellationToken); +} diff --git a/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Associations/RetrievePartyAssociationHandlerTests.cs b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Associations/RetrievePartyAssociationHandlerTests.cs new file mode 100644 index 0000000..e90c882 --- /dev/null +++ b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Associations/RetrievePartyAssociationHandlerTests.cs @@ -0,0 +1,38 @@ +using static RimBank.Party.PartyReferenceDataDirectory.Tests.AssociationExamples; + +namespace RimBank.Party.PartyReferenceDataDirectory.Tests; + +// The Associations/Retrieve flow on the query side (roadmap 1.11, ADR 0024): the view, only for the entry that owns it. +public sealed class RetrievePartyAssociationHandlerTests +{ + private readonly InMemoryPartyDirectoryEnquiry _enquiry = new(); + + [Fact] + public async Task The_owner_retrieves_the_association_view() + { + _enquiry.Seed(AssociationId, Registered(), Updated(PartyRelationshipType.PartyIsMarriedToParty, EndedPeriod)); + + var view = (await Retrieve(Owner)).Value; + + view.ShouldBe(new PartyAssociationView( + AssociationId.Value, 2, Owner, Associate, PartyRelationshipType.PartyIsMarriedToParty, EndedPeriod)); + } + + [Fact] + public async Task An_unknown_association_is_not_found() => + (await Retrieve(Owner)).Error.ShouldBe(PartyAssociationErrors.AssociationNotFound); + + [Fact] + public async Task Another_entry_than_the_owner_does_not_find_it() + { + _enquiry.Seed(AssociationId, Registered()); + + (await Retrieve(Associate)).Error.ShouldBe(PartyAssociationErrors.AssociationNotFound); + } + + private Task> Retrieve(PartyReferenceDataDirectoryEntryId owner) => + RetrievePartyAssociationHandler.HandleAsync( + new RetrievePartyAssociation(owner, AssociationId), + _enquiry, + TestContext.Current.CancellationToken); +} diff --git a/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Associations/UpdatePartyAssociationHandlerTests.cs b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Associations/UpdatePartyAssociationHandlerTests.cs new file mode 100644 index 0000000..6748908 --- /dev/null +++ b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Associations/UpdatePartyAssociationHandlerTests.cs @@ -0,0 +1,81 @@ +using RimBank.SharedKernel; +using static RimBank.Party.PartyReferenceDataDirectory.Tests.AssociationExamples; + +namespace RimBank.Party.PartyReferenceDataDirectory.Tests; + +// The Associations/Update flow on the command side (roadmap 1.11, ADR 0027): the handler checks that the association +// exists and is the caller's entry's, then the expected version, decides, appends with that version and acknowledges +// from the decision. +public sealed class UpdatePartyAssociationHandlerTests +{ + private static readonly IdempotencyKey _key = IdempotencyKey.From("update-association-1"); + + private static readonly PartyAssociationChanges _end = + new(null, null, new AssociationValidityPeriodChange(EndedPeriod)); + + private readonly InMemoryPartyDirectory _directory = new(); + + [Fact] + public async Task Updating_appends_the_update_and_acknowledges_the_next_version() + { + _directory.Seed(AssociationId, Registered()); + + var acknowledged = (await Update(expectedVersion: 1, _end)).Value; + + _directory.StreamOf(AssociationId).ShouldBe([Registered(), Updated(PartyRelationshipType.PartyIsParentOfParty, EndedPeriod)]); + acknowledged.ShouldBe(new PartyAssociationAcknowledged( + AssociationId, 2, Owner, Associate, PartyRelationshipType.PartyIsParentOfParty, EndedPeriod)); + } + + [Theory] + [InlineData(0)] + [InlineData(2)] + public async Task An_expected_version_that_is_not_the_current_one_is_a_conflict_and_nothing_is_appended(long expectedVersion) + { + _directory.Seed(AssociationId, Registered()); + + var result = await Update(expectedVersion, _end); + + result.Error.ShouldBe(PartyAssociationErrors.VersionConflict); + result.Error.Code.ShouldBe("party.version-conflict"); + _directory.StreamOf(AssociationId).ShouldBe([Registered()]); + } + + [Fact] + public async Task An_unknown_association_is_not_found_before_the_version_is_checked() + { + var result = await Update(expectedVersion: 7, _end); + + result.Error.ShouldBe(PartyAssociationErrors.AssociationNotFound); + } + + [Fact] + public async Task An_association_of_another_owner_is_not_found_before_the_version_is_checked() + { + _directory.Seed(AssociationId, Registered()); + + var result = await Update(expectedVersion: 7, _end, owner: Stranger); + + result.Error.ShouldBe(PartyAssociationErrors.AssociationNotFound); + } + + [Fact] + public async Task Another_associate_is_refused_after_the_version_check() + { + _directory.Seed(AssociationId, Registered()); + + var result = await Update(expectedVersion: 1, new PartyAssociationChanges(Stranger, null, null)); + + result.Error.ShouldBe(PartyAssociationErrors.AssociateCannotChange); + _directory.StreamOf(AssociationId).ShouldBe([Registered()]); + } + + private Task> Update( + long expectedVersion, + PartyAssociationChanges changes, + PartyReferenceDataDirectoryEntryId? owner = null) => + UpdatePartyAssociationHandler.HandleAsync( + new UpdatePartyAssociation(owner ?? Owner, AssociationId, expectedVersion, changes, _key), + _directory, + TestContext.Current.CancellationToken); +} diff --git a/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/InMemoryPartyDirectory.cs b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/InMemoryPartyDirectory.cs index 07f2db8..5a93c87 100644 --- a/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/InMemoryPartyDirectory.cs +++ b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/InMemoryPartyDirectory.cs @@ -49,4 +49,42 @@ public void Seed(PartyReferenceDataDirectoryEntryId entryId, params PartyReferen /// The events of , or none. public IReadOnlyList StreamOf(PartyReferenceDataDirectoryEntryId entryId) => _entries.TryGetValue(entryId, out var events) ? [.. events] : []; + + private readonly Dictionary> _associations = []; + + /// Every association stream, for assertions. + public IReadOnlyCollection Associations => _associations.Keys; + + public Task> LoadAssociationAsync( + PartyAssociationId associationId, + CancellationToken cancellationToken) => + Task.FromResult(StreamOf(associationId)); + + public void StartAssociation(PartyAssociationId associationId, IReadOnlyList events) + { + ArgumentNullException.ThrowIfNull(events); + if (!_associations.TryAdd(associationId, [.. events])) + { + throw new InvalidOperationException($"The association stream {associationId} already exists."); + } + } + + public void AppendToAssociation(PartyAssociationId associationId, long expectedVersion, IReadOnlyList events) + { + ArgumentNullException.ThrowIfNull(events); + if (!_associations.TryGetValue(associationId, out var stream) || stream.Count != expectedVersion) + { + throw new InvalidOperationException($"The association stream {associationId} is not at version {expectedVersion}."); + } + + stream.AddRange(events); + } + + /// Preloads the history of , as if it had been committed earlier. + public void Seed(PartyAssociationId associationId, params PartyAssociationEvent[] events) => + StartAssociation(associationId, events); + + /// The events of , or none. + public IReadOnlyList StreamOf(PartyAssociationId associationId) => + _associations.TryGetValue(associationId, out var events) ? [.. events] : []; } diff --git a/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/InMemoryPartyDirectoryEnquiry.cs b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/InMemoryPartyDirectoryEnquiry.cs index 134efb8..6ce052d 100644 --- a/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/InMemoryPartyDirectoryEnquiry.cs +++ b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/InMemoryPartyDirectoryEnquiry.cs @@ -24,4 +24,19 @@ public void Seed(PartyReferenceDataDirectoryEntryId entryId, params PartyReferen _entries[entryId] = view; } } + + private readonly Dictionary _associations = []; + + public Task FindAssociationAsync(PartyAssociationId associationId, CancellationToken cancellationToken) => + Task.FromResult(_associations.GetValueOrDefault(associationId)); + + /// Projects the history of , as if its events had been committed earlier. + public void Seed(PartyAssociationId associationId, params PartyAssociationEvent[] events) + { + var view = events.Aggregate((PartyAssociationView?)null, PartyAssociationViewProjection.Project); + if (view is not null) + { + _associations[associationId] = view; + } + } } diff --git a/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Registration/RegisterPartyHandlerTests.cs b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Registration/RegisterPartyHandlerTests.cs index fc8beed..72f59e8 100644 --- a/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Registration/RegisterPartyHandlerTests.cs +++ b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/Registration/RegisterPartyHandlerTests.cs @@ -150,5 +150,16 @@ public void AppendToEntry( long expectedVersion, IReadOnlyList events) => Started = true; + + public Task> LoadAssociationAsync( + PartyAssociationId associationId, + CancellationToken cancellationToken) => + Task.FromResult>([]); + + public void StartAssociation(PartyAssociationId associationId, IReadOnlyList events) => + Started = true; + + public void AppendToAssociation(PartyAssociationId associationId, long expectedVersion, IReadOnlyList events) => + Started = true; } } From ce23532a95fb2ab58b1878e30946464bd3afb1ac Mon Sep 17 00:00:00 2001 From: LaBani Said Date: Sun, 8 Nov 2026 19:08:47 +0100 Subject: [PATCH 4/6] Store party associations in the context's Marten store with an inline view (roadmap 1.11) Stable stored names for PartyAssociationRegistered and PartyAssociationUpdated, the inline PartyAssociationView next to the entry view, and Testcontainers round trips: read-your-write, stale version, idempotent Register, an association id is never an entry, and a rebuild restores the view. Co-Authored-By: Claude Opus 5.5 --- .../PartyReferenceDataDirectoryPostgresql.cs | 5 +- .../PartyAssociationRoundTripTests.cs | 146 ++++++++++++++++++ 2 files changed, 150 insertions(+), 1 deletion(-) create mode 100644 tests/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql.Tests/PartyAssociationRoundTripTests.cs diff --git a/src/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql/PartyReferenceDataDirectoryPostgresql.cs b/src/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql/PartyReferenceDataDirectoryPostgresql.cs index 2a12409..dbeec98 100644 --- a/src/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql/PartyReferenceDataDirectoryPostgresql.cs +++ b/src/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql/PartyReferenceDataDirectoryPostgresql.cs @@ -5,7 +5,7 @@ namespace RimBank.Party.PartyReferenceDataDirectory.Postgresql; /// -/// Registers the Party Reference Data Directory's store, its inline entry view, and its write and read ports in the +/// Registers the Party Reference Data Directory's store, its inline entry and association views, and its write and read ports in the /// host (ADR 0014, ADR 0016, ADR 0017). /// public static class PartyReferenceDataDirectoryPostgresql @@ -26,7 +26,10 @@ public static void Configure(StoreOptions options) options.Events.MapEventType("demographics_updated"); options.Events.MapEventType("demographics_exchanged"); options.Events.MapEventType("party_reference_updated"); + options.Events.MapEventType("party_association_registered"); + options.Events.MapEventType("party_association_updated"); options.AddInlineView(); + options.AddInlineView(); } /// diff --git a/tests/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql.Tests/PartyAssociationRoundTripTests.cs b/tests/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql.Tests/PartyAssociationRoundTripTests.cs new file mode 100644 index 0000000..b581f6b --- /dev/null +++ b/tests/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql.Tests/PartyAssociationRoundTripTests.cs @@ -0,0 +1,146 @@ +using RimBank.Postgresql; +using RimBank.SharedKernel; +using Wolverine; + +namespace RimBank.Party.PartyReferenceDataDirectory.Postgresql.Tests; + +// Roadmap 1.11: the PartyAssociation aggregate in the context's one store, next to the entry streams (ADR 0024). Register +// and Update dispatched through the message bus commit the association's stream, and its inline view follows in the +// same transaction; a stale version is party.version-conflict, a repeated key replays, and the view can be rebuilt. +public sealed class PartyAssociationRoundTripTests(PostgresqlServer server) +{ + private static readonly AssociationValidityPeriod _period = new(new DateTimeOffset(2024, 1, 1, 0, 0, 0, TimeSpan.Zero), null); + + private static readonly AssociationValidityPeriod _ended = + new(new DateTimeOffset(2024, 1, 1, 0, 0, 0, TimeSpan.Zero), new DateTimeOffset(2025, 12, 31, 0, 0, 0, TimeSpan.Zero)); + + private static CancellationToken Cancellation => TestContext.Current.CancellationToken; + + [Fact] + public async Task Registering_an_association_commits_its_own_stream_and_the_view_follows_at_once() + { + await using var host = await server.StartHostAsync(); + var (owner, associate) = (await RegisterPartyAsync(host.Bus), await RegisterPartyAsync(host.Bus)); + + var registered = (await RegisterAsync(host.Bus, owner, associate, NewKey())).Value; + + registered.ShouldBe(new PartyAssociationAcknowledged( + registered.AssociationId, 1, owner, associate, PartyRelationshipType.PartyIsParentOfParty, _period)); + (await host.Enquiry.FindAssociationAsync(registered.AssociationId, Cancellation)).ShouldBe(new PartyAssociationView( + registered.AssociationId.Value, 1, owner, associate, PartyRelationshipType.PartyIsParentOfParty, _period)); + (await host.Enquiry.FindEntryAsync(owner, Cancellation)).ShouldNotBeNull().Version.ShouldBe(1); + await using var query = host.Store.QuerySession(); + (await query.Events.FetchStreamStateAsync(registered.AssociationId.Value, Cancellation)).ShouldNotBeNull().Version.ShouldBe(1); + } + + [Fact] + public async Task Updating_commits_the_next_version_and_the_view_follows_at_once() + { + await using var host = await server.StartHostAsync(); + var (owner, associate) = (await RegisterPartyAsync(host.Bus), await RegisterPartyAsync(host.Bus)); + var registered = (await RegisterAsync(host.Bus, owner, associate, NewKey())).Value; + + var updated = (await UpdateAsync(host.Bus, owner, registered.AssociationId, 1, NewKey())).Value; + + updated.Version.ShouldBe(2); + updated.ValidityPeriod.ShouldBe(_ended); + (await host.Enquiry.FindAssociationAsync(registered.AssociationId, Cancellation)).ShouldBe(new PartyAssociationView( + registered.AssociationId.Value, 2, owner, associate, PartyRelationshipType.PartyIsParentOfParty, _ended)); + } + + [Fact] + public async Task An_update_at_a_stale_version_is_a_conflict_and_appends_nothing() + { + await using var host = await server.StartHostAsync(); + var (owner, associate) = (await RegisterPartyAsync(host.Bus), await RegisterPartyAsync(host.Bus)); + var registered = (await RegisterAsync(host.Bus, owner, associate, NewKey())).Value; + await UpdateAsync(host.Bus, owner, registered.AssociationId, 1, NewKey()); + + var stale = await UpdateAsync(host.Bus, owner, registered.AssociationId, 1, NewKey()); + + stale.Error.ShouldBe(PartyAssociationErrors.VersionConflict); + (await host.Enquiry.FindAssociationAsync(registered.AssociationId, Cancellation)).ShouldNotBeNull().Version.ShouldBe(2); + } + + [Fact] + public async Task The_same_key_and_payload_replays_the_first_acknowledgement_and_starts_no_second_stream() + { + await using var host = await server.StartHostAsync(); + var (owner, associate) = (await RegisterPartyAsync(host.Bus), await RegisterPartyAsync(host.Bus)); + var key = NewKey(); + + var first = await RegisterAsync(host.Bus, owner, associate, key); + var again = await RegisterAsync(host.Bus, owner, associate, key); + + again.Value.ShouldBe(first.Value); + (await host.ScalarAsync( + "select count(*) from party_reference_data_directory.mt_events where type = 'party_association_registered'")) + .ShouldBe(1); + } + + [Fact] + public async Task An_associate_that_is_not_registered_is_refused_and_an_association_is_never_an_entry() + { + await using var host = await server.StartHostAsync(); + var (owner, associate) = (await RegisterPartyAsync(host.Bus), await RegisterPartyAsync(host.Bus)); + var registered = (await RegisterAsync(host.Bus, owner, associate, NewKey())).Value; + + var unknown = await RegisterAsync(host.Bus, owner, PartyReferenceDataDirectoryEntryId.New(TimeProvider.System), NewKey()); + var association = await RegisterAsync( + host.Bus, owner, PartyReferenceDataDirectoryEntryId.From(registered.AssociationId.Value), NewKey()); + + unknown.Error.ShouldBe(PartyAssociationErrors.AssociateNotRegistered); + association.Error.ShouldBe(PartyAssociationErrors.AssociateNotRegistered); + (await host.Enquiry.FindEntryAsync(PartyReferenceDataDirectoryEntryId.From(registered.AssociationId.Value), Cancellation)) + .ShouldBeNull(); + } + + [Fact] + public async Task Rebuilding_the_view_from_the_event_store_restores_the_association() + { + await using var host = await server.StartHostAsync(); + var (owner, associate) = (await RegisterPartyAsync(host.Bus), await RegisterPartyAsync(host.Bus)); + var registered = (await RegisterAsync(host.Bus, owner, associate, NewKey())).Value; + await UpdateAsync(host.Bus, owner, registered.AssociationId, 1, NewKey()); + var before = await host.Enquiry.FindAssociationAsync(registered.AssociationId, Cancellation); + await using (var session = host.Store.LightweightSession()) + { + session.Delete(registered.AssociationId.Value); + await session.SaveChangesAsync(Cancellation); + } + + await host.Store.RebuildViewAsync( + ViewRegistration.ProjectionName(), + TimeSpan.FromSeconds(60), + Cancellation); + + (await host.Enquiry.FindAssociationAsync(registered.AssociationId, Cancellation)).ShouldBe(before); + before.ShouldNotBeNull().Version.ShouldBe(2); + } + + private static async Task RegisterPartyAsync(IMessageBus bus) => + (await bus.InvokeAsync>(new RegisterParty(PartyType.Person, NewKey()), Cancellation)) + .Value.EntryId; + + private static Task> RegisterAsync( + IMessageBus bus, + PartyReferenceDataDirectoryEntryId owner, + PartyReferenceDataDirectoryEntryId associate, + IdempotencyKey key) => + bus.InvokeAsync>( + new RegisterPartyAssociation(owner, new PartyAssociationTerms(associate, PartyRelationshipType.PartyIsParentOfParty, _period), key), + Cancellation); + + private static Task> UpdateAsync( + IMessageBus bus, + PartyReferenceDataDirectoryEntryId owner, + PartyAssociationId associationId, + long expectedVersion, + IdempotencyKey key) => + bus.InvokeAsync>( + new UpdatePartyAssociation( + owner, associationId, expectedVersion, new PartyAssociationChanges(null, null, new AssociationValidityPeriodChange(_ended)), key), + Cancellation); + + private static IdempotencyKey NewKey() => IdempotencyKey.From(Guid.CreateVersion7().ToString()); +} From b993ff72dfc8ae7a923d7b8672e4c7acee79c58c Mon Sep 17 00:00:00 2001 From: LaBani Said Date: Sun, 8 Nov 2026 19:14:11 +0100 Subject: [PATCH 5/6] =?UTF-8?q?Add=20PUT/POST/GET=20=E2=80=A6/Associations?= =?UTF-8?q?=20endpoints=20with=20Problem=20Details=20and=20conformance=20(?= =?UTF-8?q?roadmap=201.11)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit POST /PartyReferenceDataDirectory/{id}/Associations/Register, PUT …/Associations/{associationsid}/Update (If-Match) and GET …/Retrieve (ETag, 304), one BIAN request model for both commands, the three operations in the conformance list, and the demo requests in RimBank.Host.http. Co-Authored-By: Claude Opus 5.5 --- .../Associations/AssociationRouteValues.cs | 29 ++++ .../AssociationValidityPeriodModel.cs | 44 +++++ .../Associations/InvolvedPartyModel.cs | 21 +++ .../Associations/PartyAssociationRequest.cs | 86 ++++++++++ .../Associations/PartyAssociationResponse.cs | 54 +++++++ .../RegisterPartyAssociationEndpoint.cs | 91 +++++++++++ .../RetrievePartyAssociationEndpoint.cs | 84 ++++++++++ .../UpdatePartyAssociationEndpoint.cs | 92 +++++++++++ .../PartyReferenceDataDirectoryApi.cs | 3 + src/RimBank.Host/RimBank.Host.http | 38 +++++ .../Associations/AssociationScenarios.cs | 105 ++++++++++++ .../RegisterPartyAssociationEndpointTests.cs | 141 ++++++++++++++++ .../RetrievePartyAssociationEndpointTests.cs | 78 +++++++++ .../UpdatePartyAssociationEndpointTests.cs | 152 ++++++++++++++++++ ...yReferenceDataDirectoryConformanceTests.cs | 3 + 15 files changed, 1021 insertions(+) create mode 100644 src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/AssociationRouteValues.cs create mode 100644 src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/AssociationValidityPeriodModel.cs create mode 100644 src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/InvolvedPartyModel.cs create mode 100644 src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/PartyAssociationRequest.cs create mode 100644 src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/PartyAssociationResponse.cs create mode 100644 src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/RegisterPartyAssociationEndpoint.cs create mode 100644 src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/RetrievePartyAssociationEndpoint.cs create mode 100644 src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/UpdatePartyAssociationEndpoint.cs create mode 100644 tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/Associations/AssociationScenarios.cs create mode 100644 tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/Associations/RegisterPartyAssociationEndpointTests.cs create mode 100644 tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/Associations/RetrievePartyAssociationEndpointTests.cs create mode 100644 tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/Associations/UpdatePartyAssociationEndpointTests.cs diff --git a/src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/AssociationRouteValues.cs b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/AssociationRouteValues.cs new file mode 100644 index 0000000..a6189f0 --- /dev/null +++ b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/AssociationRouteValues.cs @@ -0,0 +1,29 @@ +using RimBank.SharedKernel; + +namespace RimBank.Party.PartyReferenceDataDirectory.Api; + +/// Reads the ids the Associations routes carry, entry first (roadmap 1.11). +internal static class AssociationRouteValues +{ + /// The owner's entry id, or shared.invalid-identifier naming partyreferencedatadirectoryid. + public static Result ReadOwner(string partyreferencedatadirectoryid) => + PartyReferenceDataDirectoryEntryId.TryCreate(partyreferencedatadirectoryid) switch + { + { IsFailure: true } => PartyReferenceDataDirectoryEntryErrors.EntryIdInvalid, + var ownerId => ownerId.Value, + }; + + /// + /// The owner's entry id and the association id, or shared.invalid-identifier naming + /// partyreferencedatadirectoryid or associationsid. + /// + public static Result<(PartyReferenceDataDirectoryEntryId OwnerId, PartyAssociationId AssociationId)> Read( + string partyreferencedatadirectoryid, + string associationsid) => + (PartyReferenceDataDirectoryEntryId.TryCreate(partyreferencedatadirectoryid), PartyAssociationId.TryCreate(associationsid)) switch + { + ({ IsFailure: true }, _) => PartyReferenceDataDirectoryEntryErrors.EntryIdInvalid, + (_, { IsFailure: true }) => PartyAssociationErrors.AssociationIdInvalid, + var (ownerId, associationId) => (ownerId.Value, associationId.Value), + }; +} diff --git a/src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/AssociationValidityPeriodModel.cs b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/AssociationValidityPeriodModel.cs new file mode 100644 index 0000000..e90f478 --- /dev/null +++ b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/AssociationValidityPeriodModel.cs @@ -0,0 +1,44 @@ +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace RimBank.Party.PartyReferenceDataDirectory.Api; + +/// +/// BIAN's DateTimePeriod as the Associations AssociationValidFromToDate, in requests and responses (roadmap +/// 1.11, ADR 0033). Unlike the document period of a Reference, its bounds are plain ISO 8601 strings. RimBank records +/// FromDateTime and ToDateTime; a request that sends any other part of it is refused. +/// +public sealed record AssociationValidityPeriodModel +{ + /// BIAN FromDateTime: when the association starts, an ISO 8601 date-time or date. + [JsonPropertyName("FromDateTime")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? FromDateTime { get; init; } + + /// BIAN ToDateTime: when the association ends, an ISO 8601 date-time or date. + [JsonPropertyName("ToDateTime")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? ToDateTime { get; init; } + + /// The other parts a request sent (for example NumberOfDays), which RimBank does not record. + [JsonExtensionData] + public Dictionary? Other { get; init; } + + /// The period as a response shows it: each known bound in UTC, for example 2024-01-01T00:00:00Z. + /// The recorded period, if any. + /// The model, or null when no period is recorded. + public static AssociationValidityPeriodModel? From(AssociationValidityPeriod? period) => + period switch + { + null => null, + _ => new AssociationValidityPeriodModel { FromDateTime = Format(period.From), ToDateTime = Format(period.To) }, + }; + + /// The raw bounds, for the core to read. + /// The input. + public AssociationValidityPeriodInput ToInput() => new(FromDateTime, ToDateTime); + + private static string? Format(DateTimeOffset? bound) => + bound?.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss.FFFFFFF'Z'", CultureInfo.InvariantCulture); +} diff --git a/src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/InvolvedPartyModel.cs b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/InvolvedPartyModel.cs new file mode 100644 index 0000000..40fcf7c --- /dev/null +++ b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/InvolvedPartyModel.cs @@ -0,0 +1,21 @@ +using System.Text.Json; +using System.Text.Json.Serialization; + +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. +/// +public sealed record InvolvedPartyModel +{ + /// BIAN PartyReference: the associate's PartyReferenceDataDirectoryEntryId. + [JsonPropertyName("PartyReference")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? PartyReference { get; init; } + + /// The other parts a request sent, which RimBank does not record. + [JsonExtensionData] + public Dictionary? Other { get; init; } +} diff --git a/src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/PartyAssociationRequest.cs b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/PartyAssociationRequest.cs new file mode 100644 index 0000000..d44ec7c --- /dev/null +++ b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/PartyAssociationRequest.cs @@ -0,0 +1,86 @@ +using System.Text.Json; +using System.Text.Json.Serialization; +using RimBank.SharedKernel; + +namespace RimBank.Party.PartyReferenceDataDirectory.Api; + +/// +/// The body of POST …/{partyreferencedatadirectoryid}/Associations/Register and +/// PUT …/Associations/{associationsid}/Update: BIAN's RegisterAssociations and UpdateAssociations, which +/// have the same properties (roadmap 1.11, ADR 0033). Register needs the associate and the type; Update is a partial +/// update in which a value left out keeps its value and an empty validity period clears it. The other BIAN Associations +/// fields are refused; properties that are not BIAN's are ignored. +/// +public sealed record PartyAssociationRequest +{ + /// BIAN AssociateReference: the associate's directory entry id in its PartyReference. + [JsonPropertyName("AssociateReference")] + public InvolvedPartyModel? AssociateReference { get; init; } + + /// + /// BIAN AssociateType, as a plain string (BIAN's enum wrapper flattened, ADR 0024), for example + /// PartyIsParentOfParty. + /// + [JsonPropertyName("AssociateType")] + public string? AssociateType { get; init; } + + /// BIAN AssociationValidFromToDate: when the association holds. + [JsonPropertyName("AssociationValidFromToDate")] + public AssociationValidityPeriodModel? AssociationValidFromToDate { get; init; } + + /// Every other property sent: the BIAN Associations fields RimBank does not record are found here. + [JsonExtensionData] + public Dictionary? Other { get; init; } + + /// + /// The BIAN paths of the Associations fields this request sends with a value that RimBank does not record: the + /// top-level fields of (matched without regard to case) and every + /// other part of the objects it reads. A field sent as null is not sent. + /// + /// The paths, in the order sent. + public IReadOnlyList UnsupportedFields() => + [ + .. Present(Other) + .Select(name => PartyAssociationFields.NotRecorded.FirstOrDefault(field => string.Equals(field, name, StringComparison.OrdinalIgnoreCase))) + .OfType(), + .. Present(AssociateReference?.Other).Select(part => $"{PartyAssociationFields.AssociateReference}.{part}"), + .. Present(AssociationValidFromToDate?.Other).Select(part => $"{PartyAssociationFields.AssociationValidFromToDate}.{part}"), + ]; + + /// + /// The Register command this request asks for, party.association-field-not-supported or + /// party.association-invalid. + /// + /// The entry the route names. + /// The request's Idempotency-Key (ADR 0018). + /// The command, or the validation error. + public Result ToRegisterCommand(PartyReferenceDataDirectoryEntryId ownerId, IdempotencyKey idempotencyKey) => + PartyAssociationTerms.Create(ToInput(), UnsupportedFields()) + .Map(terms => new RegisterPartyAssociation(ownerId, terms, idempotencyKey)); + + /// + /// The Update command this request asks for, party.association-field-not-supported or + /// party.association-invalid. + /// + /// The entry the route names. + /// The association the route names. + /// The version from If-Match (ADR 0027). + /// The request's Idempotency-Key (ADR 0018). + /// The command, or the validation error. + public Result ToUpdateCommand( + PartyReferenceDataDirectoryEntryId ownerId, + PartyAssociationId associationId, + long expectedVersion, + IdempotencyKey idempotencyKey) => + PartyAssociationChanges.Create(ToInput(), UnsupportedFields()) + .Map(changes => new UpdatePartyAssociation(ownerId, associationId, expectedVersion, changes, idempotencyKey)); + + private PartyAssociationInput ToInput() => + new( + AssociateReference is { } associate ? associate.PartyReference ?? string.Empty : null, + AssociateType, + AssociationValidFromToDate?.ToInput()); + + private static IEnumerable Present(Dictionary? properties) => + (properties ?? []).Where(property => property.Value.ValueKind != JsonValueKind.Null).Select(property => property.Key); +} diff --git a/src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/PartyAssociationResponse.cs b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/PartyAssociationResponse.cs new file mode 100644 index 0000000..47b6620 --- /dev/null +++ b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/PartyAssociationResponse.cs @@ -0,0 +1,54 @@ +using System.Text.Json.Serialization; + +namespace RimBank.Party.PartyReferenceDataDirectory.Api; + +/// +/// The body every Associations operation answers with (roadmap 1.11, ADR 0033): BIAN's RetrieveAssociations fields +/// RimBank records, with the ids of the association and of the entry that owns it. Register and Update build it from +/// their acknowledgement, Retrieve from the association's view. +/// +/// The association: the {associationsid} of its Update and Retrieve. +/// The entry that owns the association. +/// BIAN AssociateReference: the associate's entry id in its PartyReference. +/// BIAN AssociateType, in BIAN spelling. +/// BIAN AssociationValidFromToDate, left out when no period is recorded. +public sealed record PartyAssociationResponse( + [property: JsonPropertyName("AssociationsId")] Guid AssociationsId, + [property: JsonPropertyName("PartyReferenceDataDirectoryEntryId")] Guid PartyReferenceDataDirectoryEntryId, + [property: JsonPropertyName("AssociateReference")] InvolvedPartyModel AssociateReference, + [property: JsonPropertyName("AssociateType")] string AssociateType, + [property: JsonPropertyName("AssociationValidFromToDate"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + AssociationValidityPeriodModel? AssociationValidFromToDate = null) +{ + /// The answer of a Register or an Update, from its acknowledgement. + /// The acknowledgement. + /// The response. + public static PartyAssociationResponse From(PartyAssociationAcknowledged acknowledged) + { + ArgumentNullException.ThrowIfNull(acknowledged); + return From( + acknowledged.AssociationId, acknowledged.OwnerId, acknowledged.AssociateId, acknowledged.AssociateType, acknowledged.ValidityPeriod); + } + + /// The answer of a Retrieve, from the association's view. + /// The view. + /// The response. + public static PartyAssociationResponse From(PartyAssociationView view) + { + ArgumentNullException.ThrowIfNull(view); + return From(view.AssociationId, view.OwnerId, view.AssociateId, view.AssociateType, view.ValidityPeriod); + } + + private static PartyAssociationResponse From( + PartyAssociationId associationId, + PartyReferenceDataDirectory.PartyReferenceDataDirectoryEntryId ownerId, + PartyReferenceDataDirectory.PartyReferenceDataDirectoryEntryId associateId, + PartyRelationshipType type, + AssociationValidityPeriod? period) => + new( + associationId.Value, + ownerId.Value, + new InvolvedPartyModel { PartyReference = associateId.ToString() }, + type.ToBianName(), + AssociationValidityPeriodModel.From(period)); +} diff --git a/src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/RegisterPartyAssociationEndpoint.cs b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/RegisterPartyAssociationEndpoint.cs new file mode 100644 index 0000000..f456fdf --- /dev/null +++ b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/RegisterPartyAssociationEndpoint.cs @@ -0,0 +1,91 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Routing; +using RimBank.Api; +using RimBank.Problems; +using RimBank.SharedKernel; +using Wolverine; + +namespace RimBank.Party.PartyReferenceDataDirectory.Api; + +/// +/// POST /PartyReferenceDataDirectory/{partyreferencedatadirectoryid}/Associations/Register: BIAN +/// Associations/Register, a command (ADR 0024, ADR 0033). It dispatches and +/// answers from its acknowledgement, never from a read model (tech-stack §5). +/// +public static class RegisterPartyAssociationEndpoint +{ + /// The BIAN route. + public const string Route = "/PartyReferenceDataDirectory/{partyreferencedatadirectoryid}/Associations/Register"; + + /// The BIAN operation id, also the endpoint name. + public const string OperationId = "Associations/Register"; + + /// Maps the endpoint, which requires an Idempotency-Key header (ADR 0018). + /// The host's endpoints. + /// The endpoint's builder. + public static RouteHandlerBuilder MapRegisterPartyAssociation(this IEndpointRouteBuilder endpoints) => + endpoints.MapPost(Route, HandleAsync) + .RequireIdempotencyKey() + .WithName(OperationId) + .WithTags("Associations") + .WithSummary("Capture Association Details") + .WithDescription( + "Associates the party with another party of the directory. AssociateReference.PartyReference (the associate's " + + "PartyReferenceDataDirectoryEntryId) and AssociateType are required. AssociateType is one of " + + "PartyIsParentOfParty, PartyIsSubsidiaryOfParty, PartyIsCertifiedByParty, PartyIsMarriedToParty, " + + "PartyActsOnBehalfOfParty, PartyIsContactPointForParty, PartyIsTrustedByParty, " + + "PartyIsThePowerOfAttorneyForParty or PartyReceivesBenefitsFromAParty, read as \"this party the " + + "associate\". AssociationValidFromToDate (FromDateTime and ToDateTime, ISO 8601, from not after to) is " + + "optional. The associate must be registered and must not be the party itself (422). The other BIAN " + + "Associations fields are refused with party.association-field-not-supported. The ETag header is the " + + "association's version.") + .Produces(StatusCodes.Status200OK) + .ProducesValidationProblem() + .ProducesProblem(StatusCodes.Status401Unauthorized) + .ProducesProblem(StatusCodes.Status404NotFound) + .ProducesProblem(StatusCodes.Status409Conflict) + .ProducesProblem(StatusCodes.Status422UnprocessableEntity) + .ProducesProblem(StatusCodes.Status500InternalServerError); + + /// + /// Validates the id and the request, dispatches , and answers 200 with the new + /// association and its version as ETag, or the first error as Problem Details. + /// + /// The {partyreferencedatadirectoryid} route value, as sent. + /// The BIAN Register body. + /// The Idempotency-Key header, already required by the endpoint filter. + /// The host's message bus. + /// The request, to set the ETag header. + /// The request's cancellation. + /// The HTTP result. + public static async Task HandleAsync( + string partyreferencedatadirectoryid, + PartyAssociationRequest request, + IdempotencyKeyHeader idempotency, + IMessageBus bus, + HttpContext http, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(idempotency); + ArgumentNullException.ThrowIfNull(bus); + ArgumentNullException.ThrowIfNull(http); + + var command = AssociationRouteValues.ReadOwner(partyreferencedatadirectoryid) + .Bind(ownerId => request.ToRegisterCommand(ownerId, idempotency.Value)); + if (command.IsFailure) + { + return command.Error.ToHttpResult(); + } + + var outcome = await bus.InvokeAsync>(command.Value, cancellationToken); + return outcome.Match( + acknowledged => + { + StreamVersionTag.SetOn(http.Response, acknowledged.Version); + return TypedResults.Ok(PartyAssociationResponse.From(acknowledged)); + }, + error => error.ToHttpResult()); + } +} diff --git a/src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/RetrievePartyAssociationEndpoint.cs b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/RetrievePartyAssociationEndpoint.cs new file mode 100644 index 0000000..b587d8b --- /dev/null +++ b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/RetrievePartyAssociationEndpoint.cs @@ -0,0 +1,84 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Routing; +using RimBank.Api; +using RimBank.Problems; +using RimBank.SharedKernel; +using Wolverine; + +namespace RimBank.Party.PartyReferenceDataDirectory.Api; + +/// +/// GET /PartyReferenceDataDirectory/{partyreferencedatadirectoryid}/Associations/{associationsid}/Retrieve: BIAN +/// Associations/Retrieve, a query (ADR 0024). It dispatches and answers +/// only from the association's view (tech-stack §5). +/// +public static class RetrievePartyAssociationEndpoint +{ + /// The BIAN route. + public const string Route = "/PartyReferenceDataDirectory/{partyreferencedatadirectoryid}/Associations/{associationsid}/Retrieve"; + + /// The BIAN operation id, also the endpoint name. + public const string OperationId = "Associations/Retrieve"; + + /// Maps the endpoint. A query changes nothing, so it needs no Idempotency-Key. + /// The host's endpoints. + /// The endpoint's builder. + public static RouteHandlerBuilder MapRetrievePartyAssociation(this IEndpointRouteBuilder endpoints) => + endpoints.MapGet(Route, HandleAsync) + .WithName(OperationId) + .WithTags("Associations") + .WithSummary("Retrieve details about association entries in the directory record") + .WithDescription( + "Returns the association: AssociateReference.PartyReference (the associate's entry id), AssociateType and, " + + "when recorded, AssociationValidFromToDate in UTC. Only the entry that owns the association finds it. The " + + "ETag header is the association's version; send it in If-None-Match to get 304 Not Modified while it is " + + "current.") + .Produces(StatusCodes.Status200OK) + .Produces(StatusCodes.Status304NotModified) + .ProducesValidationProblem() + .ProducesProblem(StatusCodes.Status401Unauthorized) + .ProducesProblem(StatusCodes.Status404NotFound) + .ProducesProblem(StatusCodes.Status500InternalServerError); + + /// + /// Validates the ids, dispatches , and answers 200 with the association and its + /// version as ETag, 304 when If-None-Match already names that version, or the query's error as Problem + /// Details. + /// + /// The {partyreferencedatadirectoryid} route value, as sent. + /// The {associationsid} route value, as sent. + /// The host's message bus. + /// The request, to read If-None-Match and set the ETag header. + /// The request's cancellation. + /// The HTTP result. + public static async Task HandleAsync( + string partyreferencedatadirectoryid, + string associationsid, + IMessageBus bus, + HttpContext http, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(bus); + ArgumentNullException.ThrowIfNull(http); + + var ids = AssociationRouteValues.Read(partyreferencedatadirectoryid, associationsid); + if (ids.IsFailure) + { + return ids.Error.ToHttpResult(); + } + + var view = await bus.InvokeAsync>( + new RetrievePartyAssociation(ids.Value.OwnerId, ids.Value.AssociationId), + cancellationToken); + return view.Match( + found => + { + StreamVersionTag.SetOn(http.Response, found.Version); + return StreamVersionTag.IsNotModified(http.Request, found.Version) + ? TypedResults.StatusCode(StatusCodes.Status304NotModified) + : (IResult)TypedResults.Ok(PartyAssociationResponse.From(found)); + }, + error => error.ToHttpResult()); + } +} diff --git a/src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/UpdatePartyAssociationEndpoint.cs b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/UpdatePartyAssociationEndpoint.cs new file mode 100644 index 0000000..335b644 --- /dev/null +++ b/src/RimBank.Api/Party/PartyReferenceDataDirectory/Associations/UpdatePartyAssociationEndpoint.cs @@ -0,0 +1,92 @@ +using Microsoft.AspNetCore.Builder; +using Microsoft.AspNetCore.Http; +using Microsoft.AspNetCore.Routing; +using RimBank.Api; +using RimBank.Problems; +using RimBank.SharedKernel; +using Wolverine; + +namespace RimBank.Party.PartyReferenceDataDirectory.Api; + +/// +/// PUT /PartyReferenceDataDirectory/{partyreferencedatadirectoryid}/Associations/{associationsid}/Update: BIAN +/// Associations/Update, a command (ADR 0024, ADR 0033). It dispatches with +/// the association's version from If-Match (ADR 0027) and answers from its acknowledgement (tech-stack §5). +/// +public static class UpdatePartyAssociationEndpoint +{ + /// The BIAN route. + public const string Route = "/PartyReferenceDataDirectory/{partyreferencedatadirectoryid}/Associations/{associationsid}/Update"; + + /// The BIAN operation id, also the endpoint name. + public const string OperationId = "Associations/Update"; + + /// Maps the endpoint, which requires an Idempotency-Key (ADR 0018) and an If-Match header (ADR 0027). + /// The host's endpoints. + /// The endpoint's builder. + public static RouteHandlerBuilder MapUpdatePartyAssociation(this IEndpointRouteBuilder endpoints) => + endpoints.MapPut(Route, HandleAsync) + .RequireIdempotencyKey() + .WithName(OperationId) + .WithTags("Associations") + .WithSummary("Update details about an association entry for the customer") + .WithDescription( + "Updates the association as a partial update: AssociateType and AssociationValidFromToDate (FromDateTime and " + + "ToDateTime, ISO 8601, from not after to). A value left out keeps its value, and an empty validity period " + + "clears it; the type cannot be cleared. The owner and the associate never change: an " + + "AssociateReference.PartyReference other than the registered associate is 422 " + + "party.associate-cannot-change. Send the association's ETag in If-Match: a missing one is 428, and one that " + + "is no longer current is 409. The ETag of the answer is the new version.") + .Produces(StatusCodes.Status200OK) + .ProducesValidationProblem() + .ProducesProblem(StatusCodes.Status401Unauthorized) + .ProducesProblem(StatusCodes.Status404NotFound) + .ProducesProblem(StatusCodes.Status409Conflict) + .ProducesProblem(StatusCodes.Status422UnprocessableEntity) + .ProducesProblem(StatusCodes.Status428PreconditionRequired) + .ProducesProblem(StatusCodes.Status500InternalServerError); + + /// + /// Validates the ids, If-Match and the request, dispatches , and answers 200 + /// with the association and its new version as ETag, or the first error as Problem Details. + /// + /// The {partyreferencedatadirectoryid} route value, as sent. + /// The {associationsid} route value, as sent. + /// The BIAN Update body. + /// The Idempotency-Key header, already required by the endpoint filter. + /// The host's message bus. + /// The request, to read If-Match and set the ETag header. + /// The request's cancellation. + /// The HTTP result. + public static async Task HandleAsync( + string partyreferencedatadirectoryid, + string associationsid, + PartyAssociationRequest request, + IdempotencyKeyHeader idempotency, + IMessageBus bus, + HttpContext http, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(idempotency); + ArgumentNullException.ThrowIfNull(bus); + ArgumentNullException.ThrowIfNull(http); + + var command = AssociationRouteValues.Read(partyreferencedatadirectoryid, associationsid) + .Bind(ids => StreamVersionTag.ReadIfMatch(http.Request) + .Bind(expectedVersion => request.ToUpdateCommand(ids.OwnerId, ids.AssociationId, expectedVersion, idempotency.Value))); + if (command.IsFailure) + { + return command.Error.ToHttpResult(); + } + + var outcome = await bus.InvokeAsync>(command.Value, cancellationToken); + return outcome.Match( + acknowledged => + { + StreamVersionTag.SetOn(http.Response, acknowledged.Version); + return TypedResults.Ok(PartyAssociationResponse.From(acknowledged)); + }, + error => error.ToHttpResult()); + } +} diff --git a/src/RimBank.Api/Party/PartyReferenceDataDirectory/PartyReferenceDataDirectoryApi.cs b/src/RimBank.Api/Party/PartyReferenceDataDirectory/PartyReferenceDataDirectoryApi.cs index d0d57af..d9a8346 100644 --- a/src/RimBank.Api/Party/PartyReferenceDataDirectory/PartyReferenceDataDirectoryApi.cs +++ b/src/RimBank.Api/Party/PartyReferenceDataDirectory/PartyReferenceDataDirectoryApi.cs @@ -18,6 +18,9 @@ public static IEndpointRouteBuilder MapPartyReferenceDataDirectoryEndpoints(this endpoints.MapRetrieveDemographics(); endpoints.MapUpdatePartyReference(); endpoints.MapRetrievePartyReference(); + endpoints.MapRegisterPartyAssociation(); + endpoints.MapUpdatePartyAssociation(); + endpoints.MapRetrievePartyAssociation(); return endpoints; } } diff --git a/src/RimBank.Host/RimBank.Host.http b/src/RimBank.Host/RimBank.Host.http index 8de6e13..39f27c6 100644 --- a/src/RimBank.Host/RimBank.Host.http +++ b/src/RimBank.Host/RimBank.Host.http @@ -108,3 +108,41 @@ Idempotency-Key: {{$guid}} If-Match: "3" { "PoliticalExposureType": "Nopoliticalexposure" } + +### Associations BQ (roadmap 1.11, ADR 0033): register a second party, to associate with the first one. +# @name associate +POST {{host}}/PartyReferenceDataDirectory/Register +Authorization: Bearer {{token.response.body.$.access_token}} +Content-Type: application/json +Idempotency-Key: {{$guid}} + +{ "PartyType": "Person" } + +### Associate them: "the first party is the parent of the second". Answers 200 with ETag "1" (the association's own +# version), AssociateType in BIAN spelling and FromDateTime "2024-01-01T00:00:00Z". The associate must be registered +# (422 party.associate-not-registered) and must not be the party itself (422 party.self-association). +# @name association +POST {{host}}/PartyReferenceDataDirectory/{{register.response.body.$.PartyReferenceDataDirectoryEntryId}}/Associations/Register +Authorization: Bearer {{token.response.body.$.access_token}} +Content-Type: application/json +Idempotency-Key: {{$guid}} + +{ + "AssociateReference": { "PartyReference": "{{associate.response.body.$.PartyReferenceDataDirectoryEntryId}}" }, + "AssociateType": "partyisparentofparty", + "AssociationValidFromToDate": { "FromDateTime": "2024-01-01" } +} + +### End the association: If-Match is the association's ETag. Answers 200 with ETag "2"; the type is kept. +PUT {{host}}/PartyReferenceDataDirectory/{{register.response.body.$.PartyReferenceDataDirectoryEntryId}}/Associations/{{association.response.body.$.AssociationsId}}/Update +Authorization: Bearer {{token.response.body.$.access_token}} +Content-Type: application/json +Idempotency-Key: {{$guid}} +If-Match: "1" + +{ "AssociationValidFromToDate": { "FromDateTime": "2024-01-01", "ToDateTime": "2025-12-31" } } + +### Retrieve the association: the same values, ETag "2". Send If-None-Match: "2" to get 304 Not Modified. Only the +# 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}} diff --git a/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/Associations/AssociationScenarios.cs b/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/Associations/AssociationScenarios.cs new file mode 100644 index 0000000..ba31d0d --- /dev/null +++ b/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/Associations/AssociationScenarios.cs @@ -0,0 +1,105 @@ +using System.Text.Json; +using Alba; +using Microsoft.Net.Http.Headers; +using RimBank.Host.Testing; +using static RimBank.Party.PartyReferenceDataDirectory.Api.Tests.DemographicsScenarios; + +namespace RimBank.Party.PartyReferenceDataDirectory.Api.Tests; + +// The requests the Associations endpoint tests share (roadmap 1.11). Register, Put and the Problem Details checks are the +// Demographics ones. +internal static class AssociationScenarios +{ + public static string RegisterUrl(Guid ownerId) => RegisterUrl(ownerId.ToString()); + + public static string RegisterUrl(string ownerId) => $"/PartyReferenceDataDirectory/{ownerId}/Associations/Register"; + + public static string AssociationUrl(Guid ownerId, Guid associationId, string operation) => + AssociationUrl(ownerId.ToString(), associationId.ToString(), operation); + + public static string AssociationUrl(string ownerId, string associationId, string operation) => + $"/PartyReferenceDataDirectory/{ownerId}/Associations/{associationId}/{operation}"; + + public static string RegisterBody(Guid associateId, string type = "partyisparentofparty") => + $$""" + { + "AssociateReference": { "PartyReference": "{{associateId}}" }, + "AssociateType": "{{type}}", + "AssociationValidFromToDate": { "FromDateTime": "2024-01-01" }, + "NotABianField": "ignored" + } + """; + + public static void Post(Scenario scenario, string url, string body, string? key = null) + { + scenario.Post.Text(body).ToUrl(url); + scenario.WithRequestHeader(HeaderNames.ContentType, "application/json"); + scenario.WithRequestHeader(HeaderNames.Authorization, "Bearer " + TestTokens.Issue()); + if (key is not "") + { + scenario.WithRequestHeader("Idempotency-Key", key ?? Guid.CreateVersion7().ToString()); + } + } + + public static void Get(Scenario scenario, string url, string? ifNoneMatch = null) + { + scenario.Get.Url(url); + scenario.WithRequestHeader(HeaderNames.Authorization, "Bearer " + TestTokens.Issue()); + if (ifNoneMatch is not null) + { + scenario.WithRequestHeader(HeaderNames.IfNoneMatch, ifNoneMatch); + } + } + + // Registers two parties and associates the second with the first. + public static async Task<(RegisterPartyResponse Owner, RegisterPartyResponse Associate, PartyAssociationResponse Association)> + AssociateAsync(PartyApiHost host) + { + var owner = await RegisterAsync(host); + var associate = await RegisterAsync(host); + var association = await PostOkAsync(host, RegisterUrl(owner.PartyReferenceDataDirectoryEntryId), RegisterBody(associate.PartyReferenceDataDirectoryEntryId)); + return (owner, associate, association); + } + + public static async Task PostOkAsync(PartyApiHost host, string url, string body) + { + var result = await host.Alba.Scenario(_ => + { + Post(_, url, body); + _.StatusCodeShouldBeOk(); + _.ContentTypeShouldBe("application/json; charset=utf-8"); + _.Header(HeaderNames.ETag).SingleValueShouldEqual("\"1\""); + }); + + return (await result.ReadAsJsonAsync()).ShouldNotBeNull(); + } + + public static async Task PostProblemAsync(PartyApiHost host, string url, string body, int status) + { + var result = await host.Alba.Scenario(_ => + { + Post(_, url, body); + _.StatusCodeShouldBe(status); + _.ContentTypeShouldBe(ProblemJson); + }); + + return await ProblemOf(result, status); + } + + public static async Task PutAssociationOkAsync( + PartyApiHost host, + string url, + string body, + string ifMatch, + string etag) + { + var result = await host.Alba.Scenario(_ => + { + Put(_, url, body, ifMatch); + _.StatusCodeShouldBeOk(); + _.Header(HeaderNames.ETag).SingleValueShouldEqual(etag); + }); + + return (await result.ReadAsJsonAsync()).ShouldNotBeNull(); + } +} diff --git a/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/Associations/RegisterPartyAssociationEndpointTests.cs b/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/Associations/RegisterPartyAssociationEndpointTests.cs new file mode 100644 index 0000000..de03cd0 --- /dev/null +++ b/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/Associations/RegisterPartyAssociationEndpointTests.cs @@ -0,0 +1,141 @@ +using System.Text.Json; +using Alba; +using static RimBank.Party.PartyReferenceDataDirectory.Api.Tests.AssociationScenarios; +using static RimBank.Party.PartyReferenceDataDirectory.Api.Tests.DemographicsScenarios; + +namespace RimBank.Party.PartyReferenceDataDirectory.Api.Tests; + +// Roadmap 1.11: BIAN Associations/Register over HTTP. A command with an Idempotency-Key, answered from its acknowledgement +// with the association's version as ETag; every error is Problem Details (specs/tech-stack.md §5, ADR 0024, ADR 0033). +public sealed class RegisterPartyAssociationEndpointTests(PostgresqlServer server) +{ + [Fact] + public async Task Register_associates_two_parties_and_answers_the_association() + { + await using var host = await server.StartHostAsync(); + var owner = await RegisterAsync(host); + var associate = await RegisterAsync(host); + + var result = await host.Alba.Scenario(_ => + { + Post(_, RegisterUrl(owner.PartyReferenceDataDirectoryEntryId), RegisterBody(associate.PartyReferenceDataDirectoryEntryId)); + _.StatusCodeShouldBeOk(); + }); + + var body = await result.ReadAsJsonAsync(); + Guid.Parse(body.GetProperty("AssociationsId").GetString()!).Version.ShouldBe(7); + body.GetProperty("PartyReferenceDataDirectoryEntryId").GetGuid().ShouldBe(owner.PartyReferenceDataDirectoryEntryId); + body.GetProperty("AssociateReference").GetProperty("PartyReference").GetString() + .ShouldBe(associate.PartyReferenceDataDirectoryEntryId.ToString()); + body.GetProperty("AssociateType").GetString().ShouldBe("PartyIsParentOfParty"); + body.GetProperty("AssociationValidFromToDate").GetProperty("FromDateTime").GetString().ShouldBe("2024-01-01T00:00:00Z"); + body.GetProperty("AssociationValidFromToDate").TryGetProperty("ToDateTime", out _).ShouldBeFalse(); + } + + [Fact] + public async Task A_missing_idempotency_key_is_a_problem() + { + await using var host = await server.StartHostAsync(); + var owner = await RegisterAsync(host); + var associate = await RegisterAsync(host); + + var result = await host.Alba.Scenario(_ => + { + Post(_, RegisterUrl(owner.PartyReferenceDataDirectoryEntryId), RegisterBody(associate.PartyReferenceDataDirectoryEntryId), key: ""); + _.StatusCodeShouldBe(400); + _.ContentTypeShouldBe(ProblemJson); + }); + + await ProblemOf(result, 400); + } + + [Fact] + public async Task An_owner_id_that_is_not_an_identifier_is_a_problem() + { + await using var host = await server.StartHostAsync(); + + var problem = await PostProblemAsync(host, RegisterUrl("not-an-id"), RegisterBody(Guid.CreateVersion7()), 400); + + problem.GetProperty("errorCode").GetString().ShouldBe("shared.invalid-identifier"); + problem.GetProperty("errors").TryGetProperty("partyreferencedatadirectoryid", out _).ShouldBeTrue(); + } + + [Fact] + public async Task Invalid_values_are_named_with_their_bian_paths() + { + await using var host = await server.StartHostAsync(); + var owner = await RegisterAsync(host); + + var problem = await PostProblemAsync( + host, + RegisterUrl(owner.PartyReferenceDataDirectoryEntryId), + """{ "AssociateType": "Cousin", "AssociationValidFromToDate": { "FromDateTime": "2025-01-01", "ToDateTime": "2024-01-01" } }""", + 400); + + problem.GetProperty("errorCode").GetString().ShouldBe("party.association-invalid"); + var errors = problem.GetProperty("errors"); + errors.TryGetProperty("AssociateReference.PartyReference", out _).ShouldBeTrue(); + errors.TryGetProperty("AssociateType", out _).ShouldBeTrue(); + errors.TryGetProperty("AssociationValidFromToDate.ToDateTime", out _).ShouldBeTrue(); + } + + [Fact] + public async Task Fields_rimbank_does_not_record_are_refused() + { + await using var host = await server.StartHostAsync(); + var owner = await RegisterAsync(host); + + var problem = await PostProblemAsync( + host, + RegisterUrl(owner.PartyReferenceDataDirectoryEntryId), + """ + { + "AssociateReference": { "PartyReference": "x", "InvolvementReference": "Guarantor" }, + "AssociateType": "PartyIsParentOfParty", + "productinstancereference": { "ProductInstanceReference": "P-1" }, + "PreferredBeneficiary": null + } + """, + 400); + + problem.GetProperty("errorCode").GetString().ShouldBe("party.association-field-not-supported"); + problem.GetProperty("errors").EnumerateObject().Select(field => field.Name) + .ShouldBe(["ProductInstanceReference", "AssociateReference.InvolvementReference"]); + } + + [Fact] + public async Task An_unknown_owner_is_not_found() + { + await using var host = await server.StartHostAsync(); + var associate = await RegisterAsync(host); + + var problem = await PostProblemAsync( + host, RegisterUrl(Guid.CreateVersion7()), RegisterBody(associate.PartyReferenceDataDirectoryEntryId), 404); + + problem.GetProperty("errorCode").GetString().ShouldBe("party.party-not-found"); + } + + [Fact] + public async Task A_party_cannot_be_associated_with_itself() + { + await using var host = await server.StartHostAsync(); + var owner = await RegisterAsync(host); + + var problem = await PostProblemAsync( + host, RegisterUrl(owner.PartyReferenceDataDirectoryEntryId), RegisterBody(owner.PartyReferenceDataDirectoryEntryId), 422); + + problem.GetProperty("errorCode").GetString().ShouldBe("party.self-association"); + } + + [Fact] + public async Task An_associate_that_is_not_registered_is_refused() + { + await using var host = await server.StartHostAsync(); + var owner = await RegisterAsync(host); + + var problem = await PostProblemAsync( + host, RegisterUrl(owner.PartyReferenceDataDirectoryEntryId), RegisterBody(Guid.CreateVersion7()), 422); + + problem.GetProperty("errorCode").GetString().ShouldBe("party.associate-not-registered"); + } +} diff --git a/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/Associations/RetrievePartyAssociationEndpointTests.cs b/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/Associations/RetrievePartyAssociationEndpointTests.cs new file mode 100644 index 0000000..e2cafe6 --- /dev/null +++ b/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/Associations/RetrievePartyAssociationEndpointTests.cs @@ -0,0 +1,78 @@ +using Alba; +using Microsoft.Net.Http.Headers; +using static RimBank.Party.PartyReferenceDataDirectory.Api.Tests.AssociationScenarios; +using static RimBank.Party.PartyReferenceDataDirectory.Api.Tests.DemographicsScenarios; + +namespace RimBank.Party.PartyReferenceDataDirectory.Api.Tests; + +// Roadmap 1.11: BIAN Associations/Retrieve over HTTP. A query answered from the association's view with its version as +// ETag; every error is Problem Details (specs/tech-stack.md §5, ADR 0024). +public sealed class RetrievePartyAssociationEndpointTests(PostgresqlServer server) +{ + [Fact] + public async Task Retrieve_shows_what_Register_and_Update_recorded_with_the_association_version() + { + await using var host = await server.StartHostAsync(); + var (owner, _, association) = await AssociateAsync(host); + var updated = await PutAssociationOkAsync( + host, + AssociationUrl(owner.PartyReferenceDataDirectoryEntryId, association.AssociationsId, "Update"), + """{ "AssociateType": "PartyIsMarriedToParty" }""", + "\"1\"", + "\"2\""); + + var result = await host.Alba.Scenario(_ => + { + Get(_, AssociationUrl(owner.PartyReferenceDataDirectoryEntryId, association.AssociationsId, "Retrieve")); + _.StatusCodeShouldBeOk(); + _.Header(HeaderNames.ETag).SingleValueShouldEqual("\"2\""); + }); + + (await result.ReadAsJsonAsync()).ShouldBe(updated); + } + + [Fact] + public async Task A_current_if_none_match_is_304() + { + await using var host = await server.StartHostAsync(); + var (owner, _, association) = await AssociateAsync(host); + + await host.Alba.Scenario(_ => + { + Get(_, AssociationUrl(owner.PartyReferenceDataDirectoryEntryId, association.AssociationsId, "Retrieve"), ifNoneMatch: "\"1\""); + _.StatusCodeShouldBe(304); + _.Header(HeaderNames.ETag).SingleValueShouldEqual("\"1\""); + }); + } + + [Fact] + public async Task Only_the_owner_finds_the_association() + { + await using var host = await server.StartHostAsync(); + var (_, associate, association) = await AssociateAsync(host); + + var result = await host.Alba.Scenario(_ => + { + Get(_, AssociationUrl(associate.PartyReferenceDataDirectoryEntryId, association.AssociationsId, "Retrieve")); + _.StatusCodeShouldBe(404); + _.ContentTypeShouldBe(ProblemJson); + }); + + (await ProblemOf(result, 404)).GetProperty("errorCode").GetString().ShouldBe("party.association-not-found"); + } + + [Fact] + public async Task An_association_id_that_is_not_an_identifier_is_a_problem() + { + await using var host = await server.StartHostAsync(); + + var result = await host.Alba.Scenario(_ => + { + Get(_, AssociationUrl(Guid.CreateVersion7().ToString(), "12", "Retrieve")); + _.StatusCodeShouldBe(400); + _.ContentTypeShouldBe(ProblemJson); + }); + + (await ProblemOf(result, 400)).GetProperty("errors").TryGetProperty("associationsid", out _).ShouldBeTrue(); + } +} diff --git a/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/Associations/UpdatePartyAssociationEndpointTests.cs b/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/Associations/UpdatePartyAssociationEndpointTests.cs new file mode 100644 index 0000000..1cfcb81 --- /dev/null +++ b/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/Associations/UpdatePartyAssociationEndpointTests.cs @@ -0,0 +1,152 @@ +using static RimBank.Party.PartyReferenceDataDirectory.Api.Tests.AssociationScenarios; +using static RimBank.Party.PartyReferenceDataDirectory.Api.Tests.DemographicsScenarios; + +namespace RimBank.Party.PartyReferenceDataDirectory.Api.Tests; + +// Roadmap 1.11: BIAN Associations/Update over HTTP. A partial update with an Idempotency-Key and If-Match (ADR 0027), +// answered from its acknowledgement; every error is Problem Details (ADR 0024, ADR 0033). +public sealed class UpdatePartyAssociationEndpointTests(PostgresqlServer server) +{ + private const string EndThePeriod = + """{ "AssociationValidFromToDate": { "FromDateTime": "2024-01-01", "ToDateTime": "2025-12-31T23:30:00+01:00" } }"""; + + [Fact] + public async Task Update_changes_the_period_keeps_the_type_and_answers_the_next_version() + { + await using var host = await server.StartHostAsync(); + var (owner, _, association) = await AssociateAsync(host); + + var updated = await PutAssociationOkAsync( + host, AssociationUrl(owner.PartyReferenceDataDirectoryEntryId, association.AssociationsId, "Update"), EndThePeriod, "\"1\"", "\"2\""); + + updated.AssociateType.ShouldBe("PartyIsParentOfParty"); + updated.AssociationValidFromToDate.ShouldNotBeNull().ToDateTime.ShouldBe("2025-12-31T22:30:00Z"); + updated.AssociateReference.PartyReference.ShouldBe(association.AssociateReference.PartyReference); + } + + [Fact] + public async Task Update_changes_the_type_and_an_empty_period_clears_it() + { + await using var host = await server.StartHostAsync(); + var (owner, associate, association) = await AssociateAsync(host); + + var updated = await PutAssociationOkAsync( + host, + AssociationUrl(owner.PartyReferenceDataDirectoryEntryId, association.AssociationsId, "Update"), + $$""" + { + "AssociateReference": { "PartyReference": "{{associate.PartyReferenceDataDirectoryEntryId}}" }, + "AssociateType": "PartyIsTrustedByParty", + "AssociationValidFromToDate": {} + } + """, + "\"1\"", + "\"2\""); + + updated.AssociateType.ShouldBe("PartyIsTrustedByParty"); + updated.AssociationValidFromToDate.ShouldBeNull(); + } + + [Fact] + public async Task A_missing_if_match_is_428() + { + await using var host = await server.StartHostAsync(); + var (owner, _, association) = await AssociateAsync(host); + + var problem = await PutProblemAsync( + host, AssociationUrl(owner.PartyReferenceDataDirectoryEntryId, association.AssociationsId, "Update"), EndThePeriod, null, 428); + + problem.GetProperty("errorCode").GetString().ShouldBe("shared.if-match-required"); + } + + [Fact] + public async Task A_malformed_if_match_is_400() + { + await using var host = await server.StartHostAsync(); + var (owner, _, association) = await AssociateAsync(host); + + var problem = await PutProblemAsync( + host, AssociationUrl(owner.PartyReferenceDataDirectoryEntryId, association.AssociationsId, "Update"), EndThePeriod, "*", 400); + + problem.GetProperty("errorCode").GetString().ShouldBe("shared.if-match-invalid"); + } + + [Fact] + public async Task A_stale_if_match_is_a_version_conflict() + { + await using var host = await server.StartHostAsync(); + var (owner, _, association) = await AssociateAsync(host); + var url = AssociationUrl(owner.PartyReferenceDataDirectoryEntryId, association.AssociationsId, "Update"); + await PutAssociationOkAsync(host, url, EndThePeriod, "\"1\"", "\"2\""); + + var problem = await PutProblemAsync(host, url, EndThePeriod, "\"1\"", 409); + + problem.GetProperty("errorCode").GetString().ShouldBe("party.version-conflict"); + } + + [Fact] + public async Task An_association_id_that_is_not_an_identifier_is_a_problem() + { + await using var host = await server.StartHostAsync(); + var owner = await RegisterAsync(host); + + var problem = await PutProblemAsync(host, AssociationUrl(owner.PartyReferenceDataDirectoryEntryId.ToString(), "nope", "Update"), EndThePeriod, "\"1\"", 400); + + problem.GetProperty("errorCode").GetString().ShouldBe("shared.invalid-identifier"); + problem.GetProperty("errors").TryGetProperty("associationsid", out _).ShouldBeTrue(); + } + + [Fact] + public async Task An_entry_that_does_not_own_the_association_does_not_find_it() + { + await using var host = await server.StartHostAsync(); + var (_, associate, association) = await AssociateAsync(host); + + var problem = await PutProblemAsync( + host, AssociationUrl(associate.PartyReferenceDataDirectoryEntryId, association.AssociationsId, "Update"), EndThePeriod, "\"1\"", 404); + + problem.GetProperty("errorCode").GetString().ShouldBe("party.association-not-found"); + } + + [Fact] + public async Task An_unknown_association_is_not_found() + { + await using var host = await server.StartHostAsync(); + var owner = await RegisterAsync(host); + + var problem = await PutProblemAsync( + host, AssociationUrl(owner.PartyReferenceDataDirectoryEntryId, Guid.CreateVersion7(), "Update"), EndThePeriod, "\"1\"", 404); + + problem.GetProperty("errorCode").GetString().ShouldBe("party.association-not-found"); + } + + [Fact] + public async Task Another_associate_is_refused() + { + await using var host = await server.StartHostAsync(); + var (owner, _, association) = await AssociateAsync(host); + var other = await RegisterAsync(host); + + var problem = await PutProblemAsync( + host, + AssociationUrl(owner.PartyReferenceDataDirectoryEntryId, association.AssociationsId, "Update"), + $$"""{ "AssociateReference": { "PartyReference": "{{other.PartyReferenceDataDirectoryEntryId}}" } }""", + "\"1\"", + 422); + + problem.GetProperty("errorCode").GetString().ShouldBe("party.associate-cannot-change"); + } + + [Fact] + public async Task The_type_cannot_be_cleared() + { + await using var host = await server.StartHostAsync(); + var (owner, _, association) = await AssociateAsync(host); + + var problem = await PutProblemAsync( + host, AssociationUrl(owner.PartyReferenceDataDirectoryEntryId, association.AssociationsId, "Update"), """{ "AssociateType": "" }""", "\"1\"", 400); + + problem.GetProperty("errorCode").GetString().ShouldBe("party.association-invalid"); + problem.GetProperty("errors").TryGetProperty("AssociateType", out _).ShouldBeTrue(); + } +} diff --git a/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/PartyReferenceDataDirectoryConformanceTests.cs b/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/PartyReferenceDataDirectoryConformanceTests.cs index 3d882a7..3c5b437 100644 --- a/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/PartyReferenceDataDirectoryConformanceTests.cs +++ b/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/PartyReferenceDataDirectoryConformanceTests.cs @@ -19,6 +19,9 @@ public sealed class PartyReferenceDataDirectoryConformanceTests(PostgresqlServer RetrieveDemographicsEndpoint.OperationId, UpdatePartyReferenceEndpoint.OperationId, RetrievePartyReferenceEndpoint.OperationId, + RegisterPartyAssociationEndpoint.OperationId, + UpdatePartyAssociationEndpoint.OperationId, + RetrievePartyAssociationEndpoint.OperationId, ]; [Fact] From 5ffd140e075e6b656f94fe6fd9997280a554da7d Mon Sep 17 00:00:00 2001 From: LaBani Said Date: Sun, 8 Nov 2026 19:18:54 +0100 Subject: [PATCH 6/6] Document roadmap 1.11: ADR 0033, ADR 0024 associations, tech-stack tree and roadmap tick ADR 0033 records what a party association records (associate, nine relationship types, validity period), the refused BIAN fields and the new error codes; ADR 0024 gains the Associations requests paragraph; the plan gains an As-built section. Co-Authored-By: Claude Opus 5.5 --- ...-party-reference-data-directory-mapping.md | 21 ++++-- docs/adr/0033-party-associations.md | 73 +++++++++++++++++++ .../2026-11-08-party-associations-bq/plan.md | 9 +++ specs/roadmap.md | 2 +- specs/tech-stack.md | 16 +++- 5 files changed, 111 insertions(+), 10 deletions(-) create mode 100644 docs/adr/0033-party-associations.md diff --git a/docs/adr/0024-party-reference-data-directory-mapping.md b/docs/adr/0024-party-reference-data-directory-mapping.md index 30a0e59..4b85f27 100644 --- a/docs/adr/0024-party-reference-data-directory-mapping.md +++ b/docs/adr/0024-party-reference-data-directory-mapping.md @@ -111,6 +111,13 @@ Every `Retrieve` is a query, and every other operation is a command (mission pri Update builds it from its acknowledgement. +**Associations requests (1.11).** An association is its own aggregate (decided above), so its operations use the association's own stream, version and inline view. [ADR 0033](0033-party-associations.md) decides which BIAN fields are recorded. +- **Ids.** Every route carries `{partyreferencedatadirectoryid}` (the owner), and Update and Retrieve also `{associationsid}`. A malformed one is `400` `shared.invalid-identifier`, naming that parameter in `errors`. +- **Register** (`POST …/{partyreferencedatadirectoryid}/Associations/Register`) records `AssociateReference.PartyReference` (the associate's entry id) and `AssociateType` (both required) and an optional `AssociationValidFromToDate`. The checks run in order: the request values (`400`), the owner (`404` `party.party-not-found`), the associate is not the owner (`422` `party.self-association`), and the associate is registered (`422` `party.associate-not-registered`). Both entries are loaded from their streams through `PartyDirectory`. It answers `200` with `ETag` `"1"`. +- **Update** (`PUT …/Associations/{associationsid}/Update`) is a partial update of the type and the validity period. The checks run in order: the ids, the request values, the association exists and its owner is the path's entry (`404` `party.association-not-found`), the `If-Match` version (`409` `party.version-conflict`), and the associate is unchanged (`422` `party.associate-cannot-change`). +- **Retrieve** (`GET …/Associations/{associationsid}/Retrieve`) answers from `PartyAssociationView`, with the association's version as `ETag` and `304` on a matching `If-None-Match`. Only the owning entry finds it. +- **Headers and responses.** Register requires `Idempotency-Key`, and Update also `If-Match`, as in 1.8. All three answer `200` with the same body: `AssociationsId`, `PartyReferenceDataDirectoryEntryId` (the owner), `AssociateReference` `{ "PartyReference": … }`, `AssociateType` in BIAN spelling and `AssociationValidFromToDate` (bounds in UTC, left out when unknown). Register and Update build it from their acknowledgement. + **Deferred** means not in Stage 1 and not scheduled (no speculative coverage, mission non-goals). Control (terminate an entry) is the likeliest to come next. It needs its own decisions on what a terminated entry means for its associations and for consumers, and those are recorded when it is scheduled. Demographics/Exchange (accept, verify, reject) is a command on the entry. Its semantics are decided in [ADR 0028](0028-demographics-exchange-as-verification.md) (1.9). ### Domain events @@ -123,8 +130,8 @@ Every `Retrieve` is a query, and every other operation is a command (mission pri | Entry | `DemographicsExchanged` | `ExchangeDemographics` (carries the verification status and date, 1.9, [ADR 0028](0028-demographics-exchange-as-verification.md)) | | Entry | `PartyReferenceUpdated` | `UpdatePartyReference` (carries the full resulting Reference: the party identifiers from 1.10, and the names, date of birth, nationality and residency from 1.18, [ADR 0029](0029-reference-fields-in-stages.md)) | | Entry | `BankRelationsUpdated` | `UpdateBankRelations` | -| PartyAssociation | `PartyAssociationRegistered` | `RegisterPartyAssociation` | -| PartyAssociation | `PartyAssociationUpdated` | `UpdatePartyAssociation` | +| PartyAssociation | `PartyAssociationRegistered` | `RegisterPartyAssociation` (carries the owner, the associate, the type and the validity period, 1.11, [ADR 0033](0033-party-associations.md)) | +| PartyAssociation | `PartyAssociationUpdated` | `UpdatePartyAssociation` (carries the resulting type and validity period, 1.11) | The exact names are fixed by the phase that adds each event, within this list. Each phase may add events (for example a no-op guard needs none), and any addition updates this table. @@ -178,9 +185,13 @@ The `ETag` returned by a Retrieve, and the `If-Match` a command sends back, is t | `party.party-type-required` | Validation (400) | The Register request has no `PartyType`, or an empty one (1.5) | | `party.party-not-found` | NotFound (404) | The path's entry does not exist (any command or query on an entry, including `Associations/Register`) | | `party.behavior-qualifier-not-found` | NotFound (404) | The path's Demographics, Reference or BankRelations id does not belong to the entry | -| `party.association-not-found` | NotFound (404) | The association does not exist, or the path's entry is not its owner | -| `party.associate-not-registered` | BusinessRule (422) | `AssociateReference` is not an entry of this directory | -| `party.self-association` | BusinessRule (422) | The associate is the owning entry | +| `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.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) | +| `party.association-already-registered` | Conflict (409) | Register on an association stream that already exists; only a replayed decision meets it (1.11, ADR 0033) | | `party.demographics-invalid` | Validation (400) | A Demographics Update text is longer than its ISO 20022 type allows; `errors` names each BIAN field (1.9) | | `party.exchange-action-type-required` | Validation (400) | A Demographics Exchange has no `ExchangeActionType`, or a blank one (1.9, ADR 0028) | | `party.exchange-action-type-invalid` | Validation (400) | An `ExchangeActionType` other than `Verify` or `Reject` (1.9, ADR 0028) | diff --git a/docs/adr/0033-party-associations.md b/docs/adr/0033-party-associations.md new file mode 100644 index 0000000..a2f5495 --- /dev/null +++ b/docs/adr/0033-party-associations.md @@ -0,0 +1,73 @@ +# 0033. Associations BQ: what a party association records + +- Status: Accepted +- Date: 2026-11-08 +- Roadmap phase: 1.11 + +## Context + +[ADR 0024](0024-party-reference-data-directory-mapping.md) made the Associations Behavior Qualifier its own aggregate, `PartyAssociation`, with its own stream, typed id, version and inline view. It also fixed the cross-aggregate rule: Register needs the owning entry and the associate entry to exist in this directory, checked on the write side, and the two must differ. It left open which BIAN fields an association records. + +The [BIAN OpenAPI](../../doc-0/release14.0.0/apis-iso20022_ext-ddd/oas3/yamls/PartyReferenceDataDirectory.yaml) gives `Associations/Register`, `Associations/Update` and `Associations/Retrieve` the same body, with nine fields: + +- `AssociateReference` (`Involvedparty`: `PartyReference`, `InvolvementReference`); +- `AssociateType` (`Party_Partyrelationshiptypevalues`). Its enum lists 7 values, but its description lists 9: it adds `PartyIsThePowerOfAttorneyForParty` and `PartyReceivesBenefitsFromAParty`; +- `AssociationValidFromToDate` (ISO 20022 `DateTimePeriod`: `FromDateTime`, `ToDateTime`, and payment parts such as `RelatedStandingOrder` and `NumberOfDays`); +- `EmployeeReference`, `AssociateObligationorDependencyDescription`, `PreferredBeneficiary`, `ProxyRepresentativePowerofAttorneyReference`, `ProductInstanceReference` and `ProductInstanseInvolvementReference`. + +Roadmap 1.11 is one small phase (mission principle 10), and the interview chose the core slice. + +## Options considered + +1. **The core slice: associate, type and validity period, the rest refused.** It is the minimum that makes an association meaningful: who, how, and when. +2. **The core slice plus the free-text party references** (`EmployeeReference`, `PreferredBeneficiary`, `ProxyRepresentativePowerofAttorneyReference`) **as opaque, unchecked references.** This adds three party links that the directory cannot verify, next to an associate it does verify. Two kinds of party reference with different guarantees would confuse consumers. +3. **The 7 enum values only.** This follows the enum strictly, and drops two relationships that BIAN's own description lists, including power of attorney, a common banking relationship. +4. **Checking the period against today** (for example, refusing a past end). Banks record associations late, and record future ones ahead of time. A rule tied to the clock would refuse both. + +## Decision + +Option 1. + +### Recorded fields + +| BIAN path | Recorded as | Rule | +|---|---|---| +| `AssociateReference.PartyReference` | `PartyReferenceDataDirectoryEntryId` | Required at Register. A directory entry id (Guid v7), registered and other than the owner (ADR 0024) | +| `AssociateType` | `PartyRelationshipType` | Required at Register. One of 9 values, read trimmed and in any case, answered in BIAN spelling. BIAN's enum wrapper is flattened to a plain string, as for `PartyType` | +| `AssociationValidFromToDate.FromDateTime`, `.ToDateTime` | `AssociationValidityPeriod` | Optional. ISO 8601 date-time (one without an offset is UTC) or date (00:00 UTC), stored in UTC; at least one bound; `From` ≤ `To`; never compared with today | + +- **Relationship types.** The 7 enum values plus `PartyIsThePowerOfAttorneyForParty` and `PartyReceivesBenefitsFromAParty`, because BIAN's description lists them (mission "Source of truth" 3, as ADR 0032 did for `CharitableIncorporatedOrganisation`). The member names are the BIAN names, so the store keeps BIAN spelling. +- **Direction.** A record reads "the owner (the path's entry) *type* the associate": `PartyIsParentOfParty` means the owner is the associate's parent. The inverse is not recorded: the associate's side would be another association, registered by its own owner. +- **Ending an association.** A known `ToDateTime` is how an association ends. No "active" flag is derived, because a view must not depend on the clock (tech-stack §8.2). A consumer compares the period with its own time. +- **Owner and associate never change.** An Update that names the registered associate is accepted. One that names another is `party.associate-cannot-change` (422): a different associate is a different association, so the client registers a new one. +- **No uniqueness.** The same owner, associate and type can be registered twice, for example for two periods. Checking it would need a cross-stream index on the write side, and a duplicate does no harm. +- **Partial update.** Like the singleton BQs: an omitted value keeps its value, a given one replaces it, and an empty `AssociationValidFromToDate` clears the period. The type cannot be cleared. Every accepted Update appends `PartyAssociationUpdated`, even when nothing changes. + +### Refused fields + +A request that sends one of these with a value is refused with `party.association-field-not-supported` (400), `errors` naming each BIAN path. The check runs before the values are read, so nothing is recorded partly. Properties that are not BIAN's are ignored. + +- `EmployeeReference`, `AssociateObligationorDependencyDescription`, `PreferredBeneficiary`, `ProxyRepresentativePowerofAttorneyReference`: no phase is planned. The power-of-attorney link itself is recordable as the type `PartyIsThePowerOfAttorneyForParty`. +- `ProductInstanceReference`, `ProductInstanseInvolvementReference`: product agreements belong to later contexts (Stage 2+). No phase is planned. +- `AssociateReference.InvolvementReference`: the role is carried by `AssociateType`. +- Every part of `AssociationValidFromToDate` other than `FromDateTime` and `ToDateTime`. + +### Error codes + +The codes ADR 0024 lists for associations stay (`party.party-not-found`, `party.self-association`, `party.associate-not-registered`, `party.association-not-found`, `party.version-conflict`). This decision adds: + +| Code | Kind | When | +|---|---|---| +| `party.association-invalid` | Validation (400) | A missing associate or type at Register, a blank one at Update, an associate that is not an entry id, an unknown type, or an invalid period; `errors` names each BIAN path | +| `party.association-field-not-supported` | Validation (400) | A BIAN field or part RimBank does not record | +| `party.associate-cannot-change` | BusinessRule (422) | An Update names another associate | +| `party.association-already-registered` | Conflict (409) | Register on an association stream that already exists. The handler creates a new id, so only a replayed decision meets it | + +## Consequences + +- `RimBank.Core/Party/PartyReferenceDataDirectory/Associations/` holds the aggregate (`PartyAssociation`, its events and decisions), the value objects (`PartyRelationshipType`, `AssociationValidityPeriod`), the input readers (`PartyAssociationTerms`, `PartyAssociationChanges`), the flows and the view. `PartyAssociationFields.NotRecorded` lists the refused fields. +- `IPartyDirectory` and `IPartyDirectoryEnquiry` cover both stream types. Loading one type of stream as the other gives no events, so an association id used as an associate is `party.associate-not-registered`, never a cast failure. +- The HTTP adapter has one request model for Register and Update (`PartyAssociationRequest`), because BIAN's two bodies are the same. +- The view and its events carry PII: who is related to whom. They are listed for 7.2 with the other Party data. +- 1.21 (the corporate and officer Reference fields) can now decide whether those references are associations, plain references, or both. +- **Enforcement:** `PartyAssociationInputTests`, `PartyAssociationDecisionTests` and `PartyAssociationLawsProperties` (core), `PartyAssociationRoundTripTests` (PostgreSQL), and the Alba Associations endpoint tests pin these rules. diff --git a/specs/2026-11-08-party-associations-bq/plan.md b/specs/2026-11-08-party-associations-bq/plan.md index ded054d..59ac735 100644 --- a/specs/2026-11-08-party-associations-bq/plan.md +++ b/specs/2026-11-08-party-associations-bq/plan.md @@ -6,6 +6,15 @@ Every group is written test first. After each group, the solution builds and its - Business rules live in `RimBank.Core`. The adapters only translate the transport (memory: business logic in core). - The Testcontainers and Alba tests need Docker. If it is not available locally, they run in CI. +## As built (differences from the plan below) +- **Commits.** One per group, in order: aggregate; flows and ports (with the Marten port members, so the solution builds); PostgreSQL wiring and round trips; HTTP; docs. +- **Input readers.** Register reads `PartyAssociationTerms` (associate and type required) and Update reads `PartyAssociationChanges`; both share `PartyAssociationInputReader`. The fields class is `PartyAssociationFields`, and its `NotRecorded` set names no phase: none of the refused fields is planned (1.21 is about Reference fields). +- **One acknowledgement and one request model.** `PartyAssociationAcknowledged` answers Register and Update, and `PartyAssociationRequest` is the body of both, because BIAN's two bodies are the same. +- **One more error code.** `party.association-already-registered` (409) completes the decider for a replayed Register (ADR 0033). +- **Write-side owner check.** The Register decision takes `OwnerIsRegistered` and `AssociateIsRegistered` from the handler's loads of the two entry streams, so `Decide` stays pure. +- **Stream types.** `MartenPartyDirectory.LoadEntryAsync` and `LoadAssociationAsync` keep only their own event type, so an association id sent as an associate is `party.associate-not-registered`, not a cast failure. `PartyAssociationRoundTripTests` and `RegisterPartyAssociationHandlerTests` pin it. +- **Tests.** The value and input tests are `PartyRelationshipTypesTests`, `AssociationValidityPeriodTests` and `PartyAssociationInputTests`; the PostgreSQL port behaviour is covered by `PartyAssociationRoundTripTests` rather than new cases in `MartenPartyDirectoryTests`. + ## 1. Domain: the `PartyAssociation` aggregate - [ ] `Associations/PartyAssociationId.cs`: a Guid v7 `readonly record struct` implementing `ITypedId` (ADR 0008), with its typed-ID contract test. - [ ] `Associations/PartyRelationshipType.cs` (enum, 9 values) and `PartyRelationshipTypes.cs` (BIAN spelling, reading in any case, after the `PartyTypes` pattern). diff --git a/specs/roadmap.md b/specs/roadmap.md index a2b8d2b..684a8a3 100644 --- a/specs/roadmap.md +++ b/specs/roadmap.md @@ -56,7 +56,7 @@ - [x] **1.18 Reference BQ: names and residency:** `PartyFullLegalName`, `PartyNameSalutation`, `DateofBirth`, `Nationality`, `PartyCountryOfResidence` (an ISO 3166 country value object) and `ResidencyStatus`, added to the Reference Update and Retrieve. - [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. -- [ ] **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. +- [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). - [ ] **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. diff --git a/specs/tech-stack.md b/specs/tech-stack.md index 9aacf13..f54a046 100644 --- a/specs/tech-stack.md +++ b/specs/tech-stack.md @@ -86,7 +86,7 @@ Before a service domain is created, its mapping must be checked against the BIAN │ ├─ RimBank.Problems/ # Error → RFC 9457 Problem Details mapping, shared by .Api, .Mcp and the host (ADR 0015) │ ├─ RimBank.Api/ # the HTTP API of every context, one folder per context (ADR 0025) │ │ ├─ (root) # namespace RimBank.Api: the Idempotency-Key header (ADR 0018), stream-version entity tags (ETag, If-None-Match, If-Match: ADR 0027) -│ │ └─ Party/PartyReferenceDataDirectory/ # namespace RimBank.Party.PartyReferenceDataDirectory.Api for every folder: Registration/, Retrieval/, Update/, Demographics/, Reference/ +│ │ └─ Party/PartyReferenceDataDirectory/ # namespace RimBank.Party.PartyReferenceDataDirectory.Api for every folder: Registration/, Retrieval/, Update/, Demographics/, Reference/, Associations/ │ ├─ RimBank.Mcp/ # MCP conventions at its root: Error → isError Problem Details, the tool error filter (ADR 0022); each context's tools as a folder from 1.16 (ADR 0025) │ ├─ RimBank.Postgresql/ # Marten conventions every .Postgresql uses: per-context store, role, views, rebuild (ADR 0016); Wolverine wiring with write and read ports (ADR 0017); command idempotency (ADR 0018); one retry on a lost concurrency race (ADR 0027) │ ├─ RimBank.Core/ # the core of every context: domain + application logic, one folder per context (ADR 0023) @@ -179,11 +179,19 @@ RimBank.Core/Party/PartyReferenceDataDirectory/ # namespace RimBank.Party.P │ ├─ Events.cs # PartyReferenceUpdated │ ├─ UpdatePartyReference.cs # command, with its acknowledgement and handler │ └─ RetrievePartyReference.cs # query over the entry's view, with its handler -├─ Associations/ # Behavior Qualifier as its own aggregate (ADR 0024) +├─ Associations/ # Behavior Qualifier as its own aggregate (ADR 0024, 1.11, ADR 0033) │ ├─ PartyAssociation.cs # state + evolve │ ├─ PartyAssociationId.cs -│ ├─ Events.cs -│ ├─ Decisions.cs +│ ├─ PartyRelationshipType.cs # the 9 BIAN relationship types, BIAN names (…s.cs reads them in any case) +│ ├─ AssociationValidityPeriod.cs # FromDateTime / ToDateTime in UTC, from not after to +│ ├─ PartyAssociationInput.cs # the raw values an adapter sends +│ ├─ PartyAssociationTerms.cs # what Register records; refuses the fields in PartyAssociationFields.NotRecorded +│ ├─ PartyAssociationChanges.cs # the partial-update changes of Update +│ ├─ Events.cs # PartyAssociationRegistered, PartyAssociationUpdated +│ ├─ Decisions.cs # pure decide: the owner and associate checks come from the handler's write-side loads +│ ├─ RegisterPartyAssociation.cs # command, with its handler; PartyAssociationAcknowledged answers Register and Update +│ ├─ UpdatePartyAssociation.cs # command, with its handler +│ ├─ RetrievePartyAssociation.cs # query over the association's view, with its handler │ ├─ PartyAssociationView.cs │ └─ PartyAssociationViewProjection.cs ├─ BankRelations/