diff --git a/docs/adr/0024-party-reference-data-directory-mapping.md b/docs/adr/0024-party-reference-data-directory-mapping.md index 78ae4d8..b99b3b0 100644 --- a/docs/adr/0024-party-reference-data-directory-mapping.md +++ b/docs/adr/0024-party-reference-data-directory-mapping.md @@ -123,6 +123,12 @@ Every `Retrieve` is a query, and every other operation is a command (mission pri - **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. +**BankRelations requests (1.12).** The BankRelations record lives in the entry (an entity, as decided above), so both operations use the entry's stream, version and inline view. [ADR 0035](0035-party-bank-relations.md) decides which BIAN fields are recorded and the rules on them. +- **Ids.** Both routes carry `{partyreferencedatadirectoryid}` and `{bankrelationsid}`. A malformed one is `400` `shared.invalid-identifier`, naming that parameter in `errors`. +- **Update** (`PUT …/BankRelations/{bankrelationsid}/Update`) is a partial update of `BankRelationType`, `BusinessUnitEmployeeReference.PartyReference` and, in `BankRelationReference`, the start and end dates and the lifecycle status. The checks run in order: the ids, the request values (`400`), the entry (`404` `party.party-not-found`), the BankRelations id (`404` `party.behavior-qualifier-not-found`), the `If-Match` version (`409` `party.version-conflict`), and then the reference (`422` `party.self-reference`, `party.referenced-party-not-registered`, `party.referenced-party-type-mismatch`), loaded through `PartyDirectory` when the Update sets it or changes the type. +- **Retrieve** (`GET …/BankRelations/{bankrelationsid}/Retrieve`) answers from the entry's view, with the entry's version as `ETag` and `304` on a matching `If-None-Match`. +- **Headers and responses.** Update requires `Idempotency-Key` and `If-Match`, as in 1.8. Both answer `200` with `BankRelationsId`, `PartyReferenceDataDirectoryEntryId`, `BankRelationType`, `BusinessUnitEmployeeReference` `{ "PartyReference": … }` and `BankRelationReference` (dates as UTC date-times, the status in `StatusDescription`), each left out when unknown. Update builds it from its 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 @@ -134,7 +140,7 @@ Every `Retrieve` is a query, and every other operation is a command (mission pri | Entry | `DemographicsUpdated` | `UpdateDemographics` (carries the full resulting details and their verification status and date, 1.9) | | 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` | +| Entry | `BankRelationsUpdated` | `UpdateBankRelations` (carries the full resulting BankRelations: the type, the employee or unit, the dates and the lifecycle status, 1.12, [ADR 0035](0035-party-bank-relations.md)) | | 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) | @@ -194,9 +200,11 @@ The `ETag` returned by a Retrieve, and the `If-Match` a command sends back, is t | `party.associate-not-registered` | BusinessRule (422) | `AssociateReference` is not an entry of this directory (1.11) | | `party.self-association` | BusinessRule (422) | The associate is the owning entry (1.11) | | `party.corporate-references-need-organisation` | BusinessRule (422) | Corporate or officer references on an entry that is not an organisation, or an entry Update to `Person` while they are recorded (1.21, [ADR 0034](0034-reference-corporate-and-officer-references.md)) | -| `party.self-reference` | BusinessRule (422) | A Reference reference names the entry itself (1.21, ADR 0034) | -| `party.referenced-party-not-registered` | BusinessRule (422) | A Reference reference is not an entry of this directory (1.21, ADR 0034) | -| `party.referenced-party-type-mismatch` | BusinessRule (422) | The corporate customer or legal entity is not an organisation, or the officer is not a person (1.21, ADR 0034) | +| `party.self-reference` | BusinessRule (422) | A Reference reference, or the BankRelations employee or unit, names the entry itself (1.21, ADR 0034; 1.12, [ADR 0035](0035-party-bank-relations.md)) | +| `party.referenced-party-not-registered` | BusinessRule (422) | A Reference reference, or the BankRelations employee or unit, is not an entry of this directory (1.21, ADR 0034; 1.12, ADR 0035) | +| `party.referenced-party-type-mismatch` | BusinessRule (422) | The corporate customer or legal entity is not an organisation, or the officer is not a person (1.21, ADR 0034); the BankRelations employee is not a person, or the unit not an organisation (1.12, ADR 0035) | +| `party.bank-relations-invalid` | Validation (400) | A BankRelations value is not valid, an employee or unit has no type, or the relationship ends before it starts; `errors` names each BIAN path (1.12, ADR 0035) | +| `party.bank-relations-field-not-supported` | Validation (400) | A BankRelations Update sends a BIAN field or part RimBank does not record; `errors` names each path (1.12, ADR 0035) | | `party.association-invalid` | Validation (400) | An Associations value is missing or not valid; `errors` names each BIAN path (1.11, [ADR 0033](0033-party-associations.md)) | | `party.association-field-not-supported` | Validation (400) | An Associations request sends a BIAN field or part RimBank does not record (1.11, ADR 0033) | | `party.associate-cannot-change` | BusinessRule (422) | An Associations Update names another associate than the registered one (1.11, ADR 0033) | diff --git a/docs/adr/0035-party-bank-relations.md b/docs/adr/0035-party-bank-relations.md new file mode 100644 index 0000000..d753a93 --- /dev/null +++ b/docs/adr/0035-party-bank-relations.md @@ -0,0 +1,82 @@ +# 0035. BankRelations: what is recorded + +- Status: Accepted +- Date: 2026-11-08 +- Roadmap phase: 1.12 + +## Context + +BankRelations is the last Behavior Qualifier of Party Reference Data Directory. [ADR 0024](0024-party-reference-data-directory-mapping.md) made it a singleton entity of the entry aggregate, like Demographics and Reference: its id is created at Register, its section of the entry is empty until its first Update, its event is `BankRelationsUpdated`, and its Retrieve reads the entry's inline view. + +The [BIAN OpenAPI](../../doc-0/release14.0.0/apis-iso20022_ext-ddd/oas3/yamls/PartyReferenceDataDirectory.yaml) gives `BankRelations/Update` and `BankRelations/Retrieve` the same body: + +- `BankRelationType`: a free string, "the type of relationship (e.g. relationship manager)", with no code list; +- `BusinessUnitEmployeeReference` (`Involvedparty`: `PartyReference`, `InvolvementReference`): "the associated employee or unit"; +- `BankRelationReference` (`PartyRelationship`): `RelationshipType`, `RelationshipValidityPeriod`, `RelationshipStartDate` and `RelationshipEndDate` (ISO `Datetime` objects), `RelationshipLifecycleStatus` (ISO 20022 `Status`) and `RelationshipIdentification`. + +Three things are open in the spec: + +- **What a type is.** Free text cannot drive a rule, and the mission asks for business values, not primitives (principle 3). +- **What the employee or unit is.** RimBank has no employee or organisation-unit context. [ADR 0033](0033-party-associations.md) and [ADR 0034](0034-reference-corporate-and-officer-references.md) decided that a link to another party in this directory is a registered entry id, checked on the write side. +- **How much of `PartyRelationship` to keep.** It has six parts, some of them overlapping (a validity period next to start and end dates). + +## Options considered + +1. **Free-text type, unchecked reference.** The smallest change, but a type nobody can rely on, and a party link with a weaker guarantee than every other one in the directory, which ADR 0033 rejected. +2. **Closed type, unchecked reference.** The type becomes a business value, but the reference still names nothing RimBank knows. +3. **Closed type, checked reference with a party-type rule.** The type says whether the bank's side is an employee (a person) or a unit (an organisation), and the reference is a registered entry of that type, loaded on the write side as in ADR 0034. + +## Decision + +Option 3, chosen in the planning interview. It keeps one guarantee for every party link in the directory, and it gives the type a meaning a rule can check. + +### Recorded fields + +| BIAN path | Recorded as | Rule | +|---|---|---| +| `BankRelationType` | `BankRelationType` | `RelationshipManager` or `AccountOfficer` (an employee's role), `ServicingBranch` or `ServicingBusinessUnit` (a unit's role). Read in any case, answered as written here | +| `BusinessUnitEmployeeReference.PartyReference` | `PartyReferenceDataDirectoryEntryId` | A registered entry, not the party itself, of type `Person` for an employee's role and `Organisation` for a unit's. Only with a type | +| `BankRelationReference.RelationshipStartDate.DateTimeContent` | UTC `DateTimeOffset` | An ISO 8601 date-time (UTC when it has no offset) or a date (00:00 UTC) | +| `BankRelationReference.RelationshipEndDate.DateTimeContent` | UTC `DateTimeOffset` | Same reading, and not before the start | +| `BankRelationReference.RelationshipLifecycleStatus.StatusDescription` | `BankRelationLifecycleStatus` | `Active`, `Suspended` or `Ended`, read in any case | + +- **One relationship per entry.** BIAN gives one object, and ADR 0024 makes the BQ a singleton. A party with several bank contacts (a relationship manager and a servicing branch) would need its own aggregate, as Associations did; that is left to a later phase and its own ADR. +- **The type list is closed and small.** A new value is an amendment of this ADR, with the party type it references. +- **Partial update, as for the other BQs.** An omitted value keeps its value. A blank value or an empty object clears it, and an empty `BankRelationReference` clears the dates and the status. +- **Refused parts** (`party.bank-relations-field-not-supported`, no phase planned): `BusinessUnitEmployeeReference.InvolvementReference` (the role is the type), `RelationshipType`, `RelationshipValidityPeriod` (it duplicates the start and end dates), `RelationshipIdentification`, the other `Datetime` parts (`TimeZoneCode`, `DaylightSavingIndicator`, `DateTimeType`) and the other `Status` parts (`StatusReason`, `StatusDateTime`, `ValidityTime`). They are checked before the values, so nothing is updated partly. Properties that are not BIAN's are ignored. + +### Rules + +The rules are checked on the **resulting** BankRelations, so a partial update cannot leave it inconsistent with values it keeps: + +1. A reference without a type is `party.bank-relations-invalid` naming `BankRelationType`. Clearing the type while the reference is kept is refused unless the same request clears the reference. +2. An end before the start is `party.bank-relations-invalid` naming `BankRelationReference.RelationshipEndDate.DateTimeContent`. The same day is accepted. +3. The reference names the party itself: `party.self-reference`. +4. The reference names no registered entry: `party.referenced-party-not-registered`. An id of another stream type, such as an association, loads no entry events, so it is not registered (as in ADR 0033). +5. The reference's party type does not fit the type: `party.referenced-party-type-mismatch`. + +- **Who checks what.** The handler loads the referenced entry through `IPartyDirectory`, never a view, when the Update sets the reference or changes the type. A reference kept with its type is not loaded again: it was checked when it was recorded. The pure `Decide` checks the loaded party type. +- **The owner's party type does not matter.** Both persons and organisations have bank relations, so, unlike ADR 0034, the entry's own Update needs no guard. +- **Accepted drift.** The referenced entry may later change its own party type. It is not re-checked, for the reason ADR 0034 gives: that would need a cross-stream index on the write side. +- **No clock.** The dates are never compared with today, and no "active" flag is derived from them: a view must not depend on the clock (tech-stack §8.2). The lifecycle status is what the party declares, and `Ended` does not require an end date. + +### Error codes + +| Code | Kind | When | +|---|---|---| +| `party.bank-relations-invalid` | Validation (400) | A value is not valid, a reference has no type, or the relationship ends before it starts; `errors` names each BIAN path | +| `party.bank-relations-field-not-supported` | Validation (400) | The request sends a BIAN part RimBank does not record; `errors` names each path | + +Rules 3 to 5 reuse the ADR 0034 codes (`party.self-reference`, `party.referenced-party-not-registered`, `party.referenced-party-type-mismatch`), because they already mean "a reference to another party of this directory". As there, a business-rule error carries no field errors, so the `detail` starts with the BIAN path (`BusinessUnitEmployeeReference.PartyReference must name a party of type Person.`). + +## Consequences + +- **The Stage 1 BQs are complete over HTTP.** 1.13 (published language) and 1.17 (MCP tools for Update and the BQs) can follow. The `BankRelations/Created` and `Updated` channels stay deferred (ADR 0024). +- **The entry carries a nullable `BankRelations` section** in its state, its event and its view, so streams and views written before 1.12 still load, fold and rebuild. +- **The command handler reads another stream.** `UpdateBankRelationsHandler` loads at most one more entry through `IPartyDirectory`, as the Reference and Associations handlers do. It never uses a read port, so the CQRS architecture rules are unchanged. +- **PII.** Who manages a party at the bank, and since when, is personal data. The values live only in this context's stream and view, are listed for 7.2, and a log-capture test proves that no new code logs them. +- **Enforcement.** These tests pin the rules: + - `BankRelationsDecisionTests`, `BankRelationsChangesTests`, `BankRelationTypesTests`, `BankRelationsPartialUpdateProperties` and `UpdateBankRelationsHandlerTests` (core); + - `UpdateBankRelationsEndpointTests`, `RetrieveBankRelationsEndpointTests` and `BankRelationsLogPrivacyTests` (Alba); + - `BankRelationsRoundTripTests` (PostgreSQL, with a view rebuild); + - `PartyReferenceDataDirectoryConformanceTests` (the two BIAN operations). diff --git a/specs/2026-11-08-party-bank-relations-bq/plan.md b/specs/2026-11-08-party-bank-relations-bq/plan.md new file mode 100644 index 0000000..ed7d2eb --- /dev/null +++ b/specs/2026-11-08-party-bank-relations-bq/plan.md @@ -0,0 +1,66 @@ +# Plan: Party Reference Data Directory: BankRelations BQ + +Every group is written test first. After each group the solution builds and its tests pass (one commit per group, one PR, branched from `main`). +- Test namespaces end with `.Tests`; context namespaces stay flat: every core type is in `RimBank.Party.PartyReferenceDataDirectory`, every HTTP type in `….Api` (tech-stack §3.3, ADR 0026). +- Switch expressions only (IDE0066). +- Business rules, validation errors and value parsing live in `RimBank.Core`; the adapters only translate the transport. +- 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: domain (values, entity, decision); flows and view; PostgreSQL; HTTP and demo; docs. +- **No `BankRelationPeriod` value object.** The dates are two fields of `BankRelationsDetails`, because a partial update can change one bound only; "start ≤ end" is checked on the resulting details by the decision (`BankRelationsErrors.EndDateBeforeStartDate`). +- **Fewer files.** The raw input (`BankRelationsInput`, `BankRelationReferenceInput`) lives next to `BankRelationsChanges.Create`, and `BankRelationsFields` only names paths: no top-level BIAN field is refused, only parts of the three objects. The changes reuse `PartyReferenceChange`. +- **Shared reading of dates.** `PartyReferenceDates.TryReadUtcInstant` reads a date or date-time as UTC, and `AssociationValidityPeriod` now uses it too. +- **The 422 errors stay in `PartyReferenceErrors`**, documented as shared with BankRelations, rather than moving to a new class. +- **The handler decides what to load** with `BankRelationsDetails.ReferenceToCheck(changes)`, which the decision also uses, and passes the loaded party type (`UpdateBankRelationsDetails.ReferencedPartyType`). No port member was added. +- **Tests.** `BankRelationTypesTests` also covers the lifecycle statuses; the projection cases are in `BankRelationsViewProjectionTests`; the HTTP helpers are in `BankRelationsScenarios`. +- **ADR 0035** is the new ADR (0034 was taken by 1.21). + +## 1. Domain: BankRelations values, entity and decision +- [ ] `BankRelations/BankRelationType.cs` (enum, 4 values) and `BankRelationTypes.cs` (spelling, read in any case, and the required `PartyType` per value), after `PartyTypes` / `PartyRelationshipTypes`. +- [ ] `BankRelations/BankRelationLifecycleStatus.cs` (enum) and `BankRelationLifecycleStatuses.cs`. +- [ ] `BankRelations/BankRelationPeriod.cs`: optional `StartDate` / `EndDate`, ISO 8601 read as UTC, start ≤ end. +- [ ] `BankRelations/BankRelationsDetails.cs`: type, employee/unit `PartyReferenceDataDirectoryEntryId?`, period, status. +- [ ] `BankRelations/BankRelationsFields.cs`: recorded and refused BIAN paths (no phase). +- [ ] `BankRelations/BankRelationsChanges.cs` + `BankRelationsInput.cs`: raw adapter values → typed partial changes; refused fields first, then every value, gathered into one `party.bank-relations-invalid` naming each BIAN path; a reference without a resulting type is invalid. +- [ ] `BankRelations/BankRelationsErrors.cs`: `BankRelationsInvalid`, `BankRelationsFieldNotSupported` (both Validation). The 422 errors come from the ADR 0034 reference errors (move them to a shared place in the context if they live in `Reference/`). +- [ ] `BankRelations/Events.cs`: `BankRelationsUpdated(entryId, bankRelationsId, BankRelationsDetails)` deriving from the entry's event base. +- [ ] Entry aggregate: nullable `BankRelations` in `PartyReferenceDataDirectoryEntry`, `Evolve` for `BankRelationsUpdated`, and an `UpdateBankRelations` decision in `Decisions.cs`: BQ id, expected version, then self → not registered → type mismatch, using the referenced entry's facts passed in by the handler. +- [ ] Tests in `tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/BankRelations/`: + - `BankRelationTypesTests`, `BankRelationLifecycleStatusesTests`, `BankRelationPeriodTests`, `BankRelationsChangesTests`; + - `BankRelationsDecisionTests` (Given / When / Then) for every error code and the accepted paths (set, keep, clear, type change re-checks the kept reference); + - FsCheck `BankRelationsPartialUpdateProperties` (omitted fields keep their value; an Update with no changes keeps the state) and arbitraries in `EntryExamples` / a `BankRelationsArbitraries`. + +## 2. Command and query flows (core, in-memory ports) +- [ ] `BankRelations/UpdateBankRelations.cs` (`ICommand`, with `ExpectedVersion`), `UpdateBankRelationsAcknowledged.cs`, `UpdateBankRelationsHandler.cs`: load the entry; load the referenced entry only when set or when the type changes; decide; append with the expected version; acknowledge from the decided state. +- [ ] `PartyReferenceDataDirectoryEntryView` gains a nullable `BankRelations` section; `PartyReferenceDataDirectoryEntryViewProjection` folds `BankRelationsUpdated` (pure, no clock). +- [ ] `BankRelations/RetrieveBankRelations.cs` (`IQuery<…>`) and `RetrieveBankRelationsHandler.cs`: entry not found / BQ id foreign → the existing 404 codes. +- [ ] In-memory adapters in `RimBank.Core.Tests` handle the new event (no new port members expected; `IPartyDirectory.LoadEntryAsync` already covers the referenced entry). +- [ ] Tests: `UpdateBankRelationsHandlerTests` (not found, foreign BQ id, stale version, self, unregistered, association id as reference, type mismatch, accepted, kept reference not reloaded), `RetrieveBankRelationsHandlerTests`, and the projection test cases (Given events → Then view, including a pre-1.12 event history). + +## 3. PostgreSQL adapter +- [ ] `PartyReferenceDataDirectoryPostgresql.Configure`: map `party_bank_relations_updated`. +- [ ] `tests/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql.Tests/BankRelationsRoundTripTests.cs`: + - register two entries, Update BankRelations with a reference, Retrieve in the same store (inline read-your-write); + - stale expected version → `party.version-conflict`; + - same `Idempotency-Key` and payload returns the first acknowledgement and appends once; + - `RebuildViewAsync` gives the same view. + +## 4. HTTP adapter and demo +- [ ] `src/RimBank.Api/Party/PartyReferenceDataDirectory/BankRelations/`: + - `BankRelationsRouteValues.cs` (`bankrelationsid` as a typed id, else `shared.invalid-identifier`); + - `UpdateBankRelationsRequest.cs` (captures unknown members so the core refuses them by path), `BankRelationReferenceModel.cs`, `BankRelationsResponse.cs`; reuse `InvolvedPartyModel` and the 1.20 `DateTimeContent` model; + - `UpdateBankRelationsEndpoint.cs` (`PUT`, `RequireIdempotencyKey()`, `If-Match`, `ETag`) and `RetrieveBankRelationsEndpoint.cs` (`GET`, `ETag`, `304`), each with its BIAN `OperationId`. +- [ ] `PartyReferenceDataDirectoryApi`: map both endpoints. +- [ ] `tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/BankRelations/`: `UpdateBankRelationsEndpointTests`, `RetrieveBankRelationsEndpointTests`, `BankRelationsLogPrivacyTests` (after `ReferenceLogPrivacyTests`). +- [ ] `PartyReferenceDataDirectoryConformanceTests._implemented` gains `BankRelations/Update` and `BankRelations/Retrieve`. +- [ ] `src/RimBank.Host/RimBank.Host.http`: a "BankRelations BQ (roadmap 1.12, ADR 0035)" block: register a customer, a relationship manager (Person) and a branch (Organisation); set the manager; retrieve; change to `ServicingBranch` pointing at the person (422 type mismatch); point at the customer itself (422 self-reference). + +## 5. Docs and roadmap +- [ ] `docs/adr/0035-party-bank-relations.md` (from `template.md`), as in requirements.md. +- [ ] ADR 0024: "BankRelations requests (1.12)", the events table and the error codes table. +- [ ] `specs/tech-stack.md` §3.4: the `BankRelations/` tree and the `RimBank.Api` folder list. +- [ ] `specs/roadmap.md`: tick 1.12. +- [ ] `dotnet format --verify-no-changes` and the full `dotnet test`. +- [ ] Run the `.http` demo against the Aspire host and paste the output in the PR. +- [ ] Add an "As built" section to this plan if the implementation differs. diff --git a/specs/2026-11-08-party-bank-relations-bq/requirements.md b/specs/2026-11-08-party-bank-relations-bq/requirements.md new file mode 100644 index 0000000..e6f6ba3 --- /dev/null +++ b/specs/2026-11-08-party-bank-relations-bq/requirements.md @@ -0,0 +1,86 @@ +# Party Reference Data Directory: BankRelations BQ + +Roadmap phase: 1.12 +Branch: plan/1.12-party-bank-relations-bq + +## Context +BankRelations is the last Behavior Qualifier of Party Reference Data Directory still missing. [ADR 0024](../../docs/adr/0024-party-reference-data-directory-mapping.md) made it a **singleton entity of the entry aggregate**, like Demographics and Reference: its `BankRelationsId` is created at Register (1.2–1.5), its section of the entry is empty until the first Update, its event is `BankRelationsUpdated`, and its Retrieve reads the entry's inline view. The catalogue already names the command `UpdateBankRelations` and the query `RetrieveBankRelations` for 1.12. + +The [BIAN OpenAPI](../../doc-0/release14.0.0/apis-iso20022_ext-ddd/oas3/yamls/PartyReferenceDataDirectory.yaml) gives `BankRelations/Update` (`PUT …/{partyreferencedatadirectoryid}/BankRelations/{bankrelationsid}/Update`) and `BankRelations/Retrieve` (`GET …/Retrieve`), with the same body (`UpdateBankRelations`, `RetrieveBankRelations`): +- `BankRelationType`: a string, "the type of relationship (e.g. relationship manager)", no enum; +- `BusinessUnitEmployeeReference` (`Involvedparty`: `PartyReference`, `InvolvementReference`): "the associated employee or unit"; +- `BankRelationReference` (`PartyRelationship`): `RelationshipType`, `RelationshipValidityPeriod`, `RelationshipStartDate`, `RelationshipEndDate` (ISO `Datetime` objects with `DateTimeContent`), `RelationshipLifecycleStatus` (ISO `Status`), `RelationshipIdentification`. + +**Chosen in the interview:** the core slice with a checked reference. 1.12 records the relation type as a closed enum, the employee or unit as a **checked directory entry** (bank staff and business units are parties too, as ADR 0033 and ADR 0034 decided for party links), and the relationship's start date, end date and lifecycle status. Every other field is refused. + +It depends on 1.2–1.8 and on the checked-reference pattern of 1.11 and 1.21 (ADR 0033, ADR 0034), all merged. It unblocks the BankRelations MCP tools (**1.17**) and completes the BQs of Stage 1, so 1.13 (published language) can follow. + +Drivers: +- Mission principles 3 (enums and value objects, no primitive obsession), 4 (event-sourced truth), 5 (the command acknowledges from the decided state; the reference check reads the **write side**), 8 (Problem Details), 10 (small step: one BQ, a core slice of its fields). +- Tech-stack §3.4 (`BankRelations/` folder, flat namespace, ADR 0026), §5 (routes, `Idempotency-Key`, `If-Match`, `ETag`), §7 (BQ as an entity, the default), §8.1–8.3 (inline view, rebuildable). + +**CQRS split:** +- **Command side:** `UpdateBankRelations`. The handler loads the entry stream through `IPartyDirectory`; when the request **sets** an employee or unit reference, it also loads that entry stream (never a view). A pure `Decide` checks the facts and appends `BankRelationsUpdated` with the expected version. It acknowledges from the decided state. +- **Query side:** `RetrieveBankRelations` reads the BankRelations section of the **inline** `PartyReferenceDataDirectoryEntryView` through `IPartyDirectoryEnquiry`, after checking the BQ id. No new view, no async projection. + +## Scope +### In scope +- **`BankRelationType` (enum) + `BankRelationTypes` (BIAN-style spelling, read in any case, after `PartyTypes`):** + - `RelationshipManager`, `AccountOfficer` (staff roles: the reference must be a **Person**); + - `ServicingBranch`, `ServicingBusinessUnit` (unit roles: the reference must be an **Organisation**). + - BIAN gives no list; ADR 0035 records this one and how to extend it. +- **`BankRelations` entity (core `BankRelations/`):** a nullable section of the entry state and view, so events and views stored before 1.12 still load and rebuild: + - `Type` (`BankRelationType`); + - `BusinessUnitEmployee` (`PartyReferenceDataDirectoryEntryId`); + - `Relationship`: `StartDate` and `EndDate` (UTC `DateTimeOffset`, read from `DateTimeContent` as ISO 8601; a date alone or a value without an offset is UTC), `LifecycleStatus` (`BankRelationLifecycleStatus`: `Active`, `Suspended`, `Ended`, read from `RelationshipLifecycleStatus.StatusDescription`). +- **Rules (checked on the resulting BankRelations, in this order):** + 1. request values: unknown or refused field → 400 `party.bank-relations-field-not-supported`; bad type, status, date or id → 400 `party.bank-relations-invalid` (`errors` names each BIAN path); `StartDate` ≤ `EndDate`; a reference without a type is `party.bank-relations-invalid` naming `BankRelationType`; + 2. the reference is the entry itself → 422 `party.self-reference`; + 3. the reference is not a registered entry → 422 `party.referenced-party-not-registered`; + 4. the reference's party type does not fit the relation type → 422 `party.referenced-party-type-mismatch`. + - Codes 2–4 are reused from ADR 0034: they already mean "a reference in this directory". As there, the 422 `detail` starts with the BIAN path. + - A kept reference is not loaded again; a type change re-checks the kept reference against the new type (one entry load). + - **Accepted drift:** the referenced entry may later change its own `PartyType`; it is not re-checked (no cross-stream index, as ADR 0034). + - No check against today, and no "active" flag derived from the dates (a view must not depend on the clock, tech-stack §8.2). `Ended` does not require an `EndDate`. +- **Update (`PUT …/BankRelations/{bankrelationsid}/Update`):** + - partial update as in 1.9–1.21: an omitted field keeps its value, a given one replaces it, a blank value or empty object clears it; + - checks in order: route ids (400 `shared.invalid-identifier`) → body (400) → entry exists (404 `party.party-not-found`) → BQ id belongs to the entry (404 `party.behavior-qualifier-not-found`) → `If-Match` (409 `party.version-conflict`) → rules 2–4 (422); + - requires `Idempotency-Key` and `If-Match` (428 / 400 / 409, ADR 0027); + - every accepted Update appends `BankRelationsUpdated` with the full resulting BankRelations, even when nothing changes; answers `200` with the new entry version as `ETag`. +- **Retrieve (`GET …/BankRelations/{bankrelationsid}/Retrieve`):** from the entry view, with the entry version as `ETag` and `304` on a matching `If-None-Match`; unknown entry 404 `party.party-not-found`, foreign BQ id 404 `party.behavior-qualifier-not-found`. +- **Response (Update and Retrieve, `200`):** `BankRelationsId`, `PartyReferenceDataDirectoryEntryId`, `BankRelationType`, `BusinessUnitEmployeeReference { "PartyReference" }`, `BankRelationReference { RelationshipStartDate { DateTimeContent }, RelationshipEndDate { DateTimeContent }, RelationshipLifecycleStatus { StatusDescription } }`; unknown values are left out. Update builds it from its acknowledgement. +- **Refused (400 `party.bank-relations-field-not-supported`, no phase):** `BusinessUnitEmployeeReference.InvolvementReference` (the role is `BankRelationType`), `BankRelationReference.RelationshipType`, `RelationshipValidityPeriod` (duplicates start/end), `RelationshipIdentification`, the other `Datetime` parts (`TimeZoneCode`, `DaylightSavingIndicator`, `DateTimeType`) and the other `Status` parts (`StatusReason`, `StatusDateTime`, `ValidityTime`). Checked before the value checks, as for Reference. +- **PostgreSQL:** stable stored event name `party_bank_relations_updated`; the existing inline entry view folds it. +- **HTTP (`RimBank.Api/Party/PartyReferenceDataDirectory/BankRelations/`):** two endpoints, models and route values, mapped in `PartyReferenceDataDirectoryApi`; reuses the Associations `InvolvedPartyModel`. +- **Demo** block in `src/RimBank.Host/RimBank.Host.http`. +- **Docs:** ADR 0035 (new), ADR 0024 amended, tech-stack §3.4, roadmap 1.12 ticked. + +### Out of scope +- Several bank relations per party (for example two relationship managers): BIAN's body is one object and ADR 0024 makes the BQ a singleton. A later phase would need an ADR (likely its own aggregate, as Associations). +- The refused fields above: no phase planned. +- A bank-side employee or organisation-unit context (HR, branch network): not in the roadmap; staff and units are recorded as directory entries. +- The `BankRelations/Created` and `BankRelations/Updated` channels (deferred, ADR 0024), the MCP tools (**1.17**), per-operation scopes (**1.15**), and masking and encryption at rest (**7.2**). +- Listing a party's bank relations from the employee's side ("whose relationship manager is X"): not a BIAN operation; would need an async cross-stream view and an ADR. + +## Decisions +| Decision | Choice | Rationale | +|---|---|---| +| Recorded fields | Type, employee/unit reference, start/end dates, lifecycle status; the rest refused | Chosen in the interview. The minimum that makes a bank relation meaningful (principle 10) | +| `BankRelationType` | Closed enum of 4 values, plain string, read in any case | BIAN gives free text with one example. An enum lets the party-type rule exist and avoids primitive obsession (principle 3). Extending it is an ADR amendment | +| Employee or unit reference | A registered entry id, checked on the write side, never the entry itself | Chosen in the interview. Same guarantee as every party link (ADR 0033, ADR 0034); one kind of link, one guarantee | +| Party-type rule | Staff roles → Person, unit roles → Organisation; the owning entry may be either type | Follows BIAN's "employee or unit". The owner's type does not matter, so no guard on the entry's own Update (unlike ADR 0034) | +| Error codes | Reuse `party.self-reference`, `party.referenced-party-not-registered`, `party.referenced-party-type-mismatch`; add `party.bank-relations-invalid` and `party.bank-relations-field-not-supported` | The 422 codes already mean "a reference in this directory" (ADR 0034). One 400 code per BQ contract, as for Reference and Associations | +| Lifecycle status | `Active` / `Suspended` / `Ended` from `StatusDescription`; no cross-rule with dates | ISO `Status` has no code list. Keeps the rules small; dates and status are what the party declares | +| Dates | `DateTimeContent` as ISO 8601, stored UTC, start ≤ end, no check against today | Same reading as the 1.20 document dates and 1.11 periods; projections must not read the clock (§8.2) | +| Update semantics | Partial: omitted keeps, given replaces, blank/empty clears | Same as 1.9–1.21 | +| Read model | BankRelations section in the existing inline entry view, nullable | ADR 0024; old events and views still fold and rebuild | +| Version and `ETag` | The entry's stream version | ADR 0024 "Concurrency" | +| Work order | Domain-out, test first, one PR, one commit per group, from `main` | Chosen in the interview. 1.21 is merged (#127), so there is nothing to rebase on | + +## ADRs to write +- **ADR 0035 (new): BankRelations: what is recorded.** The recorded and refused fields, the 4 relation types and their party-type rule, the lifecycle status values, the reused 422 codes and the two new 400 codes, the accepted drift, and why one relation per party. Options considered: free-text type with an unchecked reference; enum type with an unchecked reference; enum type with a checked reference (chosen). +- **Amend ADR 0024:** a "BankRelations requests (1.12)" paragraph (routes, check order, headers, response), the events table (`BankRelationsUpdated` final shape) and the error codes table (the new codes, and 1.12 added to the reused ones). +- **Tech-stack §3.4:** the `BankRelations/` tree with the real files, and `BankRelations/` in the `RimBank.Api` folder list. + +## Open questions +- None. (The 4 relation types are a proposal; adjust in review of ADR 0035 if you want other values.) diff --git a/specs/2026-11-08-party-bank-relations-bq/validation.md b/specs/2026-11-08-party-bank-relations-bq/validation.md new file mode 100644 index 0000000..044c6af --- /dev/null +++ b/specs/2026-11-08-party-bank-relations-bq/validation.md @@ -0,0 +1,44 @@ +# Validation: Party Reference Data Directory: BankRelations BQ + +## Done when (from roadmap) +> **1.12 BankRelations BQ:** the party's relationships with the bank; Update command and Retrieve query. +> + Definition of done (roadmap.md) + +Concretely: `BankRelations/Update` and `BankRelations/Retrieve` work over HTTP for the fields in requirements.md, every refused field and broken rule answers Problem Details, and the BankRelations section folds into the inline entry view and rebuilds from the event store. + +## Automated checks +- [ ] **Core (Shouldly, FsCheck)** in `RimBank.Core.Tests`: + - value tests: `BankRelationTypesTests` (4 values, any case, required party type), `BankRelationLifecycleStatusesTests`, `BankRelationPeriodTests` (ISO 8601, date alone as UTC, start ≤ end), `BankRelationsChangesTests` (refused paths first, every invalid path named, reference without type); + - `BankRelationsDecisionTests`: accepted set/keep/clear; `party.behavior-qualifier-not-found`, `party.version-conflict`, `party.self-reference`, `party.referenced-party-not-registered`, `party.referenced-party-type-mismatch` (staff role → Organisation, unit role → Person, type change against a kept reference); + - `BankRelationsPartialUpdateProperties`: omitted fields keep their value; an empty Update keeps the state but still appends; + - projection test (Given events → Then view), including a history without any `BankRelationsUpdated` (section stays empty); + - handler tests for Update and Retrieve; the referenced entry is loaded through `IPartyDirectory` only, and only when set or re-checked. +- [ ] **PostgreSQL (Testcontainers)** `BankRelationsRoundTripTests`: inline read-your-write, stale version 409, idempotent replay appends once, `RebuildViewAsync` gives the same view. +- [ ] **HTTP (Alba)** `UpdateBankRelationsEndpointTests` / `RetrieveBankRelationsEndpointTests`: + - `200` with the response shape and `ETag`; `304` on matching `If-None-Match`; + - `400` `shared.invalid-identifier`, `party.bank-relations-invalid`, `party.bank-relations-field-not-supported` (each refused path in `errors`); + - `404` `party.party-not-found`, `party.behavior-qualifier-not-found`; + - `409` stale `If-Match`; `428` missing `If-Match`; missing `Idempotency-Key`; + - `422` self, unregistered (including an association id), type mismatch, with the BIAN path at the start of `detail`; + - every error is `application/problem+json`. +- [ ] **Log privacy** `BankRelationsLogPrivacyTests`: no submitted BankRelations value (reference id, dates, status) appears in logs on success, refusal, conflict or retrieve. +- [ ] **Conformance**: `PartyReferenceDataDirectoryConformanceTests` lists `BankRelations/Update` (PUT, command) and `BankRelations/Retrieve` (GET, query) and is green. +- [ ] **Architecture tests** green (no read port in the command handler, pure projection, flat namespaces, no `double`/`float`). +- [ ] `dotnet format --verify-no-changes`, full `dotnet test`, CodeQL: green in GitHub Actions. + +## Manual / demo checks +- [ ] `dotnet run --project src/RimBank.AppHost`, then run the "BankRelations BQ (roadmap 1.12, ADR 0035)" block of `src/RimBank.Host/RimBank.Host.http`: + - Update with `BankRelationType: RelationshipManager` pointing at a Person → `200`, `ETag` incremented; + - Retrieve → `200` with the same values; repeat with `If-None-Match` → `304`; + - `ServicingBranch` pointing at the Person → `422` `party.referenced-party-type-mismatch`, Problem Details; + - reference to the customer itself → `422` `party.self-reference`; + - `RelationshipIdentification` in the body → `400` `party.bank-relations-field-not-supported` naming the path. +- [ ] Paste the demo output in the PR description. + +## Merge criteria +- [ ] All checks above pass in CI +- [ ] Roadmap checkbox 1.12 ticked in the same PR +- [ ] ADR 0035 written; ADR 0024 and tech-stack §3.4 amended +- [ ] No BankRelations value (PII) in logs; the new fields listed for 7.2 +- [ ] MCP tools not added (1.17), and the PR says so, so the HTTP/MCP parity gap is explicit +- [ ] PR opened with the `open-phase-pr` skill (labels, milestone, board, `Closes #`) diff --git a/specs/roadmap.md b/specs/roadmap.md index bb96692..0e23408 100644 --- a/specs/roadmap.md +++ b/specs/roadmap.md @@ -58,7 +58,7 @@ - [x] **1.20 Reference BQ: legal standing, political exposure and documents:** `PartyLegalStructure`, `PoliticalExposureType`, `PoliticalExposureDescriptionRecord`, `CustomerSinceDate`, `GovernmentIssuedDocumentDetails` and `DocumentDirectoryEntryInstanceReference`, as the party declares them (never the bank's assessment, [ADR 0032](../docs/adr/0032-reference-legal-standing-and-documents.md)), added to the Reference Update and Retrieve. - [x] **1.11 Associations BQ:** party-to-party relationships as their own aggregate `PartyAssociation` (ADR 0024), with its own stream and inline view; Register/Update commands (owner and associate checked on the write side) and Retrieve query. It records the associate, the relationship type and the validity period ([ADR 0033](../docs/adr/0033-party-associations.md)). - [x] **1.21 Reference BQ: corporate and officer references:** `CorporateCustomerReference`, `CorporateCustomerLegalEntityReference`, `CompanyOfficerReference` and `CompanyOfficerRole`, references to other parties, added to the Reference Update and Retrieve after the Associations BQ (ADR 0032). Each reference is another registered entry, checked on the write side; they are recorded only on an organisation, the corporate customer and legal entity are organisations and the officer a person ([ADR 0034](../docs/adr/0034-reference-corporate-and-officer-references.md)). -- [ ] **1.12 BankRelations BQ:** the party's relationships with the bank; Update command and Retrieve query. +- [x] **1.12 BankRelations BQ:** the party's relationships with the bank; Update command and Retrieve query. It records a closed relation type, the bank employee (a person) or unit (an organisation) as a registered entry checked on the write side, and the relationship's dates and lifecycle status ([ADR 0035](../docs/adr/0035-party-bank-relations.md)). - [ ] **1.13 Published language:** `PartyReferenceDataDirectoryEntryCreated/Updated` integration events, mapped from domain events (not from read models), carrying the state consumers need, versioned, published through the outbox, and pinned by a schema contract test. - [ ] **1.14 Conformance:** OpenAPI and AsyncAPI conformance tests green for the implemented subset. - [ ] **1.15 Authorisation policies:** per-operation policies (separate scopes for command and query operations), with tests. diff --git a/specs/tech-stack.md b/specs/tech-stack.md index d712c19..c1b6e49 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/, Associations/ +│ │ └─ Party/PartyReferenceDataDirectory/ # namespace RimBank.Party.PartyReferenceDataDirectory.Api for every folder: Registration/, Retrieval/, Update/, Demographics/, Reference/, Associations/, BankRelations/ │ ├─ 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) @@ -196,7 +196,15 @@ RimBank.Core/Party/PartyReferenceDataDirectory/ # namespace RimBank.Party.P │ ├─ RetrievePartyAssociation.cs # query over the association's view, with its handler │ ├─ PartyAssociationView.cs │ └─ PartyAssociationViewProjection.cs -├─ BankRelations/ +├─ BankRelations/ # Behavior Qualifier: entity of the entry (1.12, ADR 0035) +│ ├─ BankRelationsId.cs +│ ├─ BankRelationType.cs # employee roles (a person) and unit roles (an organisation), names read in any +│ ├─ BankRelationLifecycleStatus.cs # case by …s.cs; Active / Suspended / Ended +│ ├─ BankRelationsDetails.cs # type, checked employee or unit entry id, UTC start and end dates, status +│ ├─ BankRelationsChanges.cs # the raw input and the partial-update changes; refuses unrecorded BIAN parts +│ ├─ Events.cs # BankRelationsUpdated (decided by the entry's Decide) +│ ├─ UpdateBankRelations.cs # command, with its acknowledgement and handler (which loads the referenced entry) +│ └─ RetrieveBankRelations.cs # query over the entry's view, with its handler ├─ IPartyDirectory.cs # write port: load and append the entry and association event streams └─ IPartyDirectoryEnquiry.cs # read port: query the entry and association views ``` diff --git a/src/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql/PartyReferenceDataDirectoryPostgresql.cs b/src/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql/PartyReferenceDataDirectoryPostgresql.cs index dbeec98..235c665 100644 --- a/src/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql/PartyReferenceDataDirectoryPostgresql.cs +++ b/src/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql/PartyReferenceDataDirectoryPostgresql.cs @@ -26,6 +26,7 @@ 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_bank_relations_updated"); options.Events.MapEventType("party_association_registered"); options.Events.MapEventType("party_association_updated"); options.AddInlineView(); diff --git a/src/RimBank.Api/Party/PartyReferenceDataDirectory/BankRelations/BankRelationReferenceModel.cs b/src/RimBank.Api/Party/PartyReferenceDataDirectory/BankRelations/BankRelationReferenceModel.cs new file mode 100644 index 0000000..3202acc --- /dev/null +++ b/src/RimBank.Api/Party/PartyReferenceDataDirectory/BankRelations/BankRelationReferenceModel.cs @@ -0,0 +1,90 @@ +using System.Globalization; +using System.Text.Json; +using System.Text.Json.Serialization; + +namespace RimBank.Party.PartyReferenceDataDirectory.Api; + +/// +/// BIAN's BankRelations BankRelationReference (a PartyRelationship), in requests and responses (roadmap 1.12, +/// ADR 0035). RimBank records the DateTimeContent of RelationshipStartDate and RelationshipEndDate, and +/// the StatusDescription of RelationshipLifecycleStatus; a request that sends any other part (such as +/// RelationshipIdentification) is refused. +/// +public sealed record BankRelationReferenceModel +{ + /// BIAN RelationshipStartDate: when the relationship started. + [JsonPropertyName("RelationshipStartDate")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public DateTimeModel? RelationshipStartDate { get; init; } + + /// BIAN RelationshipEndDate: when the relationship ended or ends. + [JsonPropertyName("RelationshipEndDate")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public DateTimeModel? RelationshipEndDate { get; init; } + + /// BIAN RelationshipLifecycleStatus: where the relationship stands. + [JsonPropertyName("RelationshipLifecycleStatus")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public RelationshipLifecycleStatusModel? RelationshipLifecycleStatus { get; init; } + + /// The other parts a request sent, which RimBank does not record. + [JsonExtensionData] + public Dictionary? Other { get; init; } + + /// The recorded parts as raw text: an object sent without its recorded part is sent blank, which clears it. + /// The input the core reads. + public BankRelationReferenceInput ToInput() => + new( + RelationshipStartDate is { } start ? start.DateTimeContent ?? string.Empty : null, + RelationshipEndDate is { } end ? end.DateTimeContent ?? string.Empty : null, + RelationshipLifecycleStatus is { } status ? status.StatusDescription ?? string.Empty : null); + + /// The BIAN paths of the parts sent with a value that RimBank does not record. + /// The paths, in the order sent. + public IEnumerable UnsupportedParts() => + [ + .. ReferenceModelParts.Present(BankRelationsFields.BankRelationReference, Other), + .. ReferenceModelParts.Present(BankRelationsFields.RelationshipStartDate, RelationshipStartDate?.Other), + .. ReferenceModelParts.Present(BankRelationsFields.RelationshipEndDate, RelationshipEndDate?.Other), + .. ReferenceModelParts.Present(BankRelationsFields.RelationshipLifecycleStatus, RelationshipLifecycleStatus?.Other), + ]; + + /// The recorded relationship parts of some BankRelations, or null when none is known. + /// The BankRelations. + /// The model, with each unknown part left out. + public static BankRelationReferenceModel? From(BankRelationsDetails details) + { + ArgumentNullException.ThrowIfNull(details); + return details is { StartDate: null, EndDate: null, LifecycleStatus: null } + ? null + : new BankRelationReferenceModel + { + RelationshipStartDate = DateOf(details.StartDate), + RelationshipEndDate = DateOf(details.EndDate), + RelationshipLifecycleStatus = details.LifecycleStatus is { } status + ? new RelationshipLifecycleStatusModel { StatusDescription = status.ToBianName() } + : null, + }; + } + + private static DateTimeModel? DateOf(DateTimeOffset? value) => + value is { } instant + ? new DateTimeModel { DateTimeContent = instant.UtcDateTime.ToString("yyyy-MM-dd'T'HH:mm:ss.FFFFFFF'Z'", CultureInfo.InvariantCulture) } + : null; +} + +/// +/// BIAN's RelationshipLifecycleStatus (ISO 20022 Status) inside +/// (roadmap 1.12). RimBank records StatusDescription; a request that sends any other part of it is refused. +/// +public sealed record RelationshipLifecycleStatusModel +{ + /// BIAN StatusDescription: Active, Suspended or Ended. + [JsonPropertyName("StatusDescription")] + [JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + public string? StatusDescription { get; init; } + + /// The other parts a request sent (for example StatusReason), which RimBank does not record. + [JsonExtensionData] + public Dictionary? Other { get; init; } +} diff --git a/src/RimBank.Api/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsResponse.cs b/src/RimBank.Api/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsResponse.cs new file mode 100644 index 0000000..4c73ed7 --- /dev/null +++ b/src/RimBank.Api/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsResponse.cs @@ -0,0 +1,52 @@ +using System.Text.Json.Serialization; + +namespace RimBank.Party.PartyReferenceDataDirectory.Api; + +/// +/// The answer of BIAN BankRelations/Update and BankRelations/Retrieve (roadmap 1.12, ADR 0035): the entry's +/// BankRelations, with every unknown value left out. +/// +/// The entry's BankRelations: the {bankrelationsid} of its operations. +/// The entry. +/// BIAN BankRelationType. +/// BIAN BusinessUnitEmployeeReference: the employee's or unit's entry. +/// BIAN BankRelationReference: the relationship's dates and lifecycle status. +public sealed record BankRelationsResponse( + [property: JsonPropertyName("BankRelationsId")] Guid BankRelationsId, + [property: JsonPropertyName("PartyReferenceDataDirectoryEntryId")] Guid PartyReferenceDataDirectoryEntryId, + [property: JsonPropertyName("BankRelationType"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + string? BankRelationType = null, + [property: JsonPropertyName("BusinessUnitEmployeeReference"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + InvolvedPartyModel? BusinessUnitEmployeeReference = null, + [property: JsonPropertyName("BankRelationReference"), JsonIgnore(Condition = JsonIgnoreCondition.WhenWritingNull)] + BankRelationReferenceModel? BankRelationReference = null) +{ + /// The answer of an Update, built from its acknowledgement, never from a read model (tech-stack §5). + /// The command's acknowledgement. + /// The response. + public static BankRelationsResponse From(UpdateBankRelationsAcknowledged acknowledged) + { + ArgumentNullException.ThrowIfNull(acknowledged); + return From(acknowledged.BankRelationsId, acknowledged.EntryId, acknowledged.BankRelations); + } + + /// The answer of a Retrieve, built from the entry's view. + /// The entry's view. + /// The response. + public static BankRelationsResponse From(PartyReferenceDataDirectoryEntryView view) + { + ArgumentNullException.ThrowIfNull(view); + return From(view.BankRelationsId, view.EntryId, view.CurrentBankRelations); + } + + private static BankRelationsResponse From( + BankRelationsId bankRelationsId, + PartyReferenceDataDirectory.PartyReferenceDataDirectoryEntryId entryId, + BankRelationsDetails details) => + new( + bankRelationsId.Value, + entryId.Value, + details.Type?.ToBianName(), + details.BusinessUnitEmployee is { } employee ? new InvolvedPartyModel { PartyReference = employee.ToString() } : null, + BankRelationReferenceModel.From(details)); +} diff --git a/src/RimBank.Api/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsRouteValues.cs b/src/RimBank.Api/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsRouteValues.cs new file mode 100644 index 0000000..e59798d --- /dev/null +++ b/src/RimBank.Api/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsRouteValues.cs @@ -0,0 +1,21 @@ +using RimBank.SharedKernel; + +namespace RimBank.Party.PartyReferenceDataDirectory.Api; + +/// Reads the two ids every BankRelations route carries, entry first. +internal static class BankRelationsRouteValues +{ + /// + /// The entry and BankRelations ids, or shared.invalid-identifier naming partyreferencedatadirectoryid or + /// bankrelationsid. + /// + public static Result<(PartyReferenceDataDirectoryEntryId EntryId, BankRelationsId BankRelationsId)> Read( + string partyreferencedatadirectoryid, + string bankrelationsid) => + (PartyReferenceDataDirectoryEntryId.TryCreate(partyreferencedatadirectoryid), BankRelationsId.TryCreate(bankrelationsid)) switch + { + ({ IsFailure: true }, _) => PartyReferenceDataDirectoryEntryErrors.EntryIdInvalid, + (_, { IsFailure: true }) => BankRelationsErrors.BankRelationsIdInvalid, + var (entryId, bankRelationsId) => (entryId.Value, bankRelationsId.Value), + }; +} diff --git a/src/RimBank.Api/Party/PartyReferenceDataDirectory/BankRelations/RetrieveBankRelationsEndpoint.cs b/src/RimBank.Api/Party/PartyReferenceDataDirectory/BankRelations/RetrieveBankRelationsEndpoint.cs new file mode 100644 index 0000000..e7a7336 --- /dev/null +++ b/src/RimBank.Api/Party/PartyReferenceDataDirectory/BankRelations/RetrieveBankRelationsEndpoint.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}/BankRelations/{bankrelationsid}/Retrieve: BIAN +/// BankRelations/Retrieve, a query (ADR 0024, ADR 0035). It dispatches and +/// answers only from the entry's view (tech-stack §5). +/// +public static class RetrieveBankRelationsEndpoint +{ + /// The BIAN route. + public const string Route = "/PartyReferenceDataDirectory/{partyreferencedatadirectoryid}/BankRelations/{bankrelationsid}/Retrieve"; + + /// The BIAN operation id, also the endpoint name. + public const string OperationId = "BankRelations/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 MapRetrieveBankRelations(this IEndpointRouteBuilder endpoints) => + endpoints.MapGet(Route, HandleAsync) + .WithName(OperationId) + .WithTags("BankRelations") + .WithSummary("Retrieve details about customer bank relations entries in the directory") + .WithDescription( + "Returns the party's relationship with the bank: BankRelationType, the employee or unit in " + + "BusinessUnitEmployeeReference.PartyReference, and in BankRelationReference the RelationshipStartDate and " + + "RelationshipEndDate (UTC date-times) and the RelationshipLifecycleStatus. Unknown values are left out. The " + + "ETag header is the entry'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 BankRelations and the + /// entry's 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 {bankrelationsid} 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 bankrelationsid, + IMessageBus bus, + HttpContext http, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(bus); + ArgumentNullException.ThrowIfNull(http); + + var ids = BankRelationsRouteValues.Read(partyreferencedatadirectoryid, bankrelationsid); + if (ids.IsFailure) + { + return ids.Error.ToHttpResult(); + } + + var view = await bus.InvokeAsync>( + new RetrieveBankRelations(ids.Value.EntryId, ids.Value.BankRelationsId), + 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(BankRelationsResponse.From(found)); + }, + error => error.ToHttpResult()); + } +} diff --git a/src/RimBank.Api/Party/PartyReferenceDataDirectory/BankRelations/UpdateBankRelationsEndpoint.cs b/src/RimBank.Api/Party/PartyReferenceDataDirectory/BankRelations/UpdateBankRelationsEndpoint.cs new file mode 100644 index 0000000..3806b30 --- /dev/null +++ b/src/RimBank.Api/Party/PartyReferenceDataDirectory/BankRelations/UpdateBankRelationsEndpoint.cs @@ -0,0 +1,98 @@ +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}/BankRelations/{bankrelationsid}/Update: BIAN +/// BankRelations/Update, a command (ADR 0024, ADR 0035). It dispatches with the +/// entry's version from If-Match (ADR 0027) and answers from its acknowledgement, never from a read model +/// (tech-stack §5). +/// +public static class UpdateBankRelationsEndpoint +{ + /// The BIAN route. + public const string Route = "/PartyReferenceDataDirectory/{partyreferencedatadirectoryid}/BankRelations/{bankrelationsid}/Update"; + + /// The BIAN operation id, also the endpoint name. + public const string OperationId = "BankRelations/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 MapUpdateBankRelations(this IEndpointRouteBuilder endpoints) => + endpoints.MapPut(Route, HandleAsync) + .RequireIdempotencyKey() + .WithName(OperationId) + .WithTags("BankRelations") + .WithSummary("Update details about a customer's bank relations entry for the customer") + .WithDescription( + "Updates the party's relationship with the bank as a partial update. BankRelationType is RelationshipManager " + + "or AccountOfficer (BusinessUnitEmployeeReference.PartyReference then names a registered person) or " + + "ServicingBranch or ServicingBusinessUnit (it then names a registered organisation); the reference must be " + + "another entry of the directory and needs a type. BankRelationReference records RelationshipStartDate and " + + "RelationshipEndDate (DateTimeContent, an ISO 8601 date or date-time, the end not before the start) and " + + "RelationshipLifecycleStatus.StatusDescription (Active, Suspended or Ended). A value left out keeps its value, " + + "an empty one clears it, and an empty BankRelationReference clears the dates and the status. Every other " + + "part (InvolvementReference, RelationshipType, RelationshipValidityPeriod, RelationshipIdentification, the " + + "other Datetime and Status parts) is refused with party.bank-relations-field-not-supported. Send the entry'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 BankRelations and the entry's new version as ETag, or the first error as Problem Details. + /// + /// The {partyreferencedatadirectoryid} route value, as sent. + /// The {bankrelationsid} 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 bankrelationsid, + UpdateBankRelationsRequest request, + IdempotencyKeyHeader idempotency, + IMessageBus bus, + HttpContext http, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(request); + ArgumentNullException.ThrowIfNull(idempotency); + ArgumentNullException.ThrowIfNull(bus); + ArgumentNullException.ThrowIfNull(http); + + var command = BankRelationsRouteValues.Read(partyreferencedatadirectoryid, bankrelationsid) + .Bind(ids => StreamVersionTag.ReadIfMatch(http.Request) + .Bind(expectedVersion => request.ToCommand(ids.EntryId, ids.BankRelationsId, 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(BankRelationsResponse.From(acknowledged)); + }, + error => error.ToHttpResult()); + } +} diff --git a/src/RimBank.Api/Party/PartyReferenceDataDirectory/BankRelations/UpdateBankRelationsRequest.cs b/src/RimBank.Api/Party/PartyReferenceDataDirectory/BankRelations/UpdateBankRelationsRequest.cs new file mode 100644 index 0000000..83306fd --- /dev/null +++ b/src/RimBank.Api/Party/PartyReferenceDataDirectory/BankRelations/UpdateBankRelationsRequest.cs @@ -0,0 +1,61 @@ +using System.Text.Json; +using System.Text.Json.Serialization; +using RimBank.SharedKernel; + +namespace RimBank.Party.PartyReferenceDataDirectory.Api; + +/// +/// The body of PUT …/{partyreferencedatadirectoryid}/BankRelations/{bankrelationsid}/Update: BIAN's +/// UpdateBankRelations (roadmap 1.12, ADR 0035), a partial update in which a value left out keeps its value and an +/// empty one clears it. The parts of the BIAN objects RimBank does not record are refused; properties that are not BIAN's +/// are ignored. +/// +public sealed record UpdateBankRelationsRequest +{ + /// BIAN BankRelationType, for example RelationshipManager. + [JsonPropertyName("BankRelationType")] + public string? BankRelationType { get; init; } + + /// BIAN BusinessUnitEmployeeReference: the employee's or unit's directory entry id in its PartyReference. + [JsonPropertyName("BusinessUnitEmployeeReference")] + public InvolvedPartyModel? BusinessUnitEmployeeReference { get; init; } + + /// BIAN BankRelationReference: the relationship's dates and lifecycle status. + [JsonPropertyName("BankRelationReference")] + public BankRelationReferenceModel? BankRelationReference { get; init; } + + /// Every other property sent, which is not a BIAN BankRelations field and is ignored. + [JsonExtensionData] + public Dictionary? Other { get; init; } + + /// The BIAN paths of the parts this request sends with a value that RimBank does not record. + /// The paths, in the order sent. + public IReadOnlyList UnsupportedFields() => + [ + .. ReferenceModelParts.Present(BankRelationsFields.BusinessUnitEmployeeReference, BusinessUnitEmployeeReference?.Other), + .. BankRelationReference?.UnsupportedParts() ?? [], + ]; + + /// + /// The Update command this request asks for, party.bank-relations-field-not-supported or + /// party.bank-relations-invalid. + /// + /// The entry the route names. + /// The BankRelations 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 ToCommand( + PartyReferenceDataDirectoryEntryId entryId, + BankRelationsId bankRelationsId, + long expectedVersion, + IdempotencyKey idempotencyKey) => + BankRelationsChanges.Create(ToInput(), UnsupportedFields()) + .Map(changes => new UpdateBankRelations(entryId, bankRelationsId, expectedVersion, changes, idempotencyKey)); + + private BankRelationsInput ToInput() => + new( + BankRelationType, + BusinessUnitEmployeeReference is { } employee ? employee.PartyReference ?? string.Empty : null, + BankRelationReference?.ToInput()); +} diff --git a/src/RimBank.Api/Party/PartyReferenceDataDirectory/PartyReferenceDataDirectoryApi.cs b/src/RimBank.Api/Party/PartyReferenceDataDirectory/PartyReferenceDataDirectoryApi.cs index d9a8346..dc9d34a 100644 --- a/src/RimBank.Api/Party/PartyReferenceDataDirectory/PartyReferenceDataDirectoryApi.cs +++ b/src/RimBank.Api/Party/PartyReferenceDataDirectory/PartyReferenceDataDirectoryApi.cs @@ -21,6 +21,8 @@ public static IEndpointRouteBuilder MapPartyReferenceDataDirectoryEndpoints(this endpoints.MapRegisterPartyAssociation(); endpoints.MapUpdatePartyAssociation(); endpoints.MapRetrievePartyAssociation(); + endpoints.MapUpdateBankRelations(); + endpoints.MapRetrieveBankRelations(); return endpoints; } } diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/AssociationValidityPeriod.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/AssociationValidityPeriod.cs index 85c98c3..e7b9342 100644 --- a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/AssociationValidityPeriod.cs +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Associations/AssociationValidityPeriod.cs @@ -1,4 +1,3 @@ -using System.Globalization; using RimBank.SharedKernel; namespace RimBank.Party.PartyReferenceDataDirectory; @@ -53,14 +52,9 @@ public static Result TryCreate(AssociationValidityPer return null; } - if (DateOnly.TryParseExact(text.Trim(), "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var date)) + if (PartyReferenceDates.TryReadUtcInstant(text, out var instant)) { - return new DateTimeOffset(date.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero); - } - - if (PartyReferenceDates.TryReadDateTime(text, out var dateTime)) - { - return dateTime.ToUniversalTime(); + return instant; } fieldErrors[field] = ["The value must be an ISO 8601 date-time, for example 2024-01-01T00:00:00Z, or date."]; diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/BankRelations/BankRelationLifecycleStatus.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/BankRelations/BankRelationLifecycleStatus.cs new file mode 100644 index 0000000..17df5ae --- /dev/null +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/BankRelations/BankRelationLifecycleStatus.cs @@ -0,0 +1,18 @@ +namespace RimBank.Party.PartyReferenceDataDirectory; + +/// +/// Where the party's relationship with the bank stands: BIAN BankRelationReference.RelationshipLifecycleStatus, an +/// ISO 20022 Status whose StatusDescription RimBank reads as one of these values (roadmap 1.12, ADR 0035). It +/// is recorded as declared and never derived from the relationship's dates. +/// +public enum BankRelationLifecycleStatus +{ + /// The relationship is in force. + Active = 1, + + /// The relationship is on hold. + Suspended = 2, + + /// The relationship has ended. + Ended = 3, +} diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/BankRelations/BankRelationLifecycleStatuses.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/BankRelations/BankRelationLifecycleStatuses.cs new file mode 100644 index 0000000..b11f5ea --- /dev/null +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/BankRelations/BankRelationLifecycleStatuses.cs @@ -0,0 +1,35 @@ +using RimBank.SharedKernel; + +namespace RimBank.Party.PartyReferenceDataDirectory; + +/// Reads and writes the names of (roadmap 1.12, ADR 0035). +public static class BankRelationLifecycleStatuses +{ + /// The spelling of a lifecycle status in requests and responses, for example Active. + /// The status. + /// Its name. + public static string ToBianName(this BankRelationLifecycleStatus status) => + Enum.IsDefined(status) + ? status.ToString() + : throw new ArgumentOutOfRangeException(nameof(status), status, "Not a bank relation lifecycle status."); + + /// Reads a lifecycle status a caller sent: trimmed, names matched without regard to case. + /// The text sent, not blank. + /// + /// The status, or party.bank-relations-invalid naming + /// . + /// + public static Result Read(string text) + { + ArgumentNullException.ThrowIfNull(text); + var trimmed = text.Trim(); + return Enum.GetValues() + .Where(status => string.Equals(status.ToString(), trimmed, StringComparison.OrdinalIgnoreCase)) + .Select(status => (BankRelationLifecycleStatus?)status) + .FirstOrDefault() switch + { + { } status => status, + null => BankRelationsErrors.LifecycleStatusInvalid, + }; + } +} diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/BankRelations/BankRelationType.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/BankRelations/BankRelationType.cs new file mode 100644 index 0000000..57dc5cd --- /dev/null +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/BankRelations/BankRelationType.cs @@ -0,0 +1,21 @@ +namespace RimBank.Party.PartyReferenceDataDirectory; + +/// +/// What the bank is to the party: BIAN BankRelationType, "the type of relationship (e.g. relationship manager)" +/// (roadmap 1.12, ADR 0035). BIAN gives no list, so RimBank closes it to these values. Each one says which kind of party +/// BusinessUnitEmployeeReference names (see ). +/// +public enum BankRelationType +{ + /// A bank employee manages the relationship with the party. The reference is a person. + RelationshipManager = 1, + + /// A bank employee is the officer of the party's accounts. The reference is a person. + AccountOfficer = 2, + + /// A branch of the bank services the party. The reference is an organisation. + ServicingBranch = 3, + + /// Another business unit of the bank services the party. The reference is an organisation. + ServicingBusinessUnit = 4, +} diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/BankRelations/BankRelationTypes.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/BankRelations/BankRelationTypes.cs new file mode 100644 index 0000000..dc33250 --- /dev/null +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/BankRelations/BankRelationTypes.cs @@ -0,0 +1,50 @@ +using System.Diagnostics; +using RimBank.SharedKernel; + +namespace RimBank.Party.PartyReferenceDataDirectory; + +/// Reads and writes the names of , and the party each one references (roadmap 1.12, ADR 0035). +public static class BankRelationTypes +{ + /// The spelling of a bank relation type in requests and responses, for example RelationshipManager. + /// The type. + /// Its name. + public static string ToBianName(this BankRelationType type) => + Enum.IsDefined(type) + ? type.ToString() + : throw new ArgumentOutOfRangeException(nameof(type), type, "Not a bank relation type."); + + /// + /// The party type BusinessUnitEmployeeReference must name for this relation: a person for an employee's role, an + /// organisation for a unit's. + /// + /// The type. + /// or . + public static PartyType ReferencedPartyType(this BankRelationType type) => + type switch + { + BankRelationType.RelationshipManager or BankRelationType.AccountOfficer => PartyType.Person, + BankRelationType.ServicingBranch or BankRelationType.ServicingBusinessUnit => PartyType.Organisation, + _ => throw new UnreachableException($"Not a bank relation type: {type}."), + }; + + /// + /// Reads a bank relation type a caller sent: trimmed, names matched without regard to case. An enum number is not a + /// name. + /// + /// The text sent, not blank. + /// The type, or party.bank-relations-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 => (BankRelationType?)type) + .FirstOrDefault() switch + { + { } type => type, + null => BankRelationsErrors.BankRelationTypeInvalid, + }; + } +} diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsChanges.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsChanges.cs new file mode 100644 index 0000000..7d3c26f --- /dev/null +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsChanges.cs @@ -0,0 +1,151 @@ +using RimBank.SharedKernel; + +namespace RimBank.Party.PartyReferenceDataDirectory; + +/// +/// The changes a BIAN BankRelations/Update asks for: a partial update (roadmap 1.12, ADR 0035). A null change +/// keeps the current value; a change with a null value clears it. Adapters build it with . +/// +/// The change of BankRelationType. +/// The change of BusinessUnitEmployeeReference.PartyReference. +/// The change of BankRelationReference.RelationshipStartDate. +/// The change of BankRelationReference.RelationshipEndDate. +/// The change of BankRelationReference.RelationshipLifecycleStatus. +public sealed record BankRelationsChanges( + PartyReferenceChange? Type = null, + PartyReferenceChange? BusinessUnitEmployee = null, + PartyReferenceChange? StartDate = null, + PartyReferenceChange? EndDate = null, + PartyReferenceChange? LifecycleStatus = null) +{ + /// No change at all: an Update that only records that the BankRelations was reviewed. + public static BankRelationsChanges None { get; } = new(); + + /// The changes that set every part to , clearing the unknown ones. + /// The details to record. + /// The changes. + public static BankRelationsChanges To(BankRelationsDetails details) + { + ArgumentNullException.ThrowIfNull(details); + return new BankRelationsChanges( + new(details.Type), + new(details.BusinessUnitEmployee), + new(details.StartDate), + new(details.EndDate), + new(details.LifecycleStatus)); + } + + /// + /// Reads the changes a caller sent. Fields and parts RimBank does not record are refused first, so nothing is updated + /// partly. A blank value clears its part, and an empty BankRelationReference clears the dates and the status. + /// + /// The values sent: null keeps. + /// The BIAN paths of the fields and parts sent with a value that RimBank does not record. + /// + /// The changes, party.bank-relations-field-not-supported naming every unsupported path, or + /// party.bank-relations-invalid naming every invalid value. + /// + public static Result Create(BankRelationsInput input, IReadOnlyCollection unsupportedFields) + { + ArgumentNullException.ThrowIfNull(input); + ArgumentNullException.ThrowIfNull(unsupportedFields); + if (unsupportedFields.Count > 0) + { + return BankRelationsErrors.BankRelationsFieldsNotSupported(unsupportedFields + .Distinct(StringComparer.Ordinal) + .ToDictionary( + field => field, + IReadOnlyList (_) => ["RimBank does not record this field."], + StringComparer.Ordinal)); + } + + var fieldErrors = new Dictionary>(StringComparer.Ordinal); + var relationship = input.BankRelationReference switch + { + { IsEmpty: true } => new BankRelationReferenceInput(string.Empty, string.Empty, string.Empty), + var given => given, + }; + var changes = new BankRelationsChanges( + Read(input.BankRelationType, BankRelationsFields.BankRelationType, BankRelationTypes.Read, fieldErrors), + Read(input.BusinessUnitEmployeePartyReference, BankRelationsFields.BusinessUnitEmployeePartyReference, ReadEntry, fieldErrors), + Read(relationship?.RelationshipStartDate, BankRelationsFields.RelationshipStartDateContent, ReadInstant, fieldErrors), + Read(relationship?.RelationshipEndDate, BankRelationsFields.RelationshipEndDateContent, ReadInstant, fieldErrors), + Read(relationship?.RelationshipLifecycleStatus, BankRelationsFields.RelationshipLifecycleStatusDescription, BankRelationLifecycleStatuses.Read, fieldErrors)); + + return fieldErrors.Count switch + { + 0 => changes, + _ => BankRelationsErrors.BankRelationsInvalid(fieldErrors), + }; + } + + // null keeps, blank clears, anything else is read; a value that cannot be read is named by its BIAN path. + private static PartyReferenceChange? Read( + string? text, + string field, + Func> read, + Dictionary> fieldErrors) + where TValue : struct + { + if (text is null) + { + return null; + } + + if (string.IsNullOrWhiteSpace(text)) + { + return new PartyReferenceChange(null); + } + + var value = read(text); + if (value.IsFailure) + { + fieldErrors[field] = value.Error.FieldErrors.Values.FirstOrDefault() ?? [value.Error.Message]; + return null; + } + + return new PartyReferenceChange(value.Value); + } + + private static Result ReadEntry(string text) => + PartyReferenceDataDirectoryEntryId.TryCreate(text.Trim()) switch + { + { IsFailure: true } => Error.Validation( + BankRelationsErrors.BankRelationsInvalidCode, + "The employee or unit must be the PartyReferenceDataDirectoryEntryId returned by Register."), + var entry => entry, + }; + + private static Result ReadInstant(string text) => + PartyReferenceDates.TryReadUtcInstant(text, out var instant) + ? instant + : Error.Validation( + BankRelationsErrors.BankRelationsInvalidCode, + "The value must be an ISO 8601 date-time, for example 2024-01-01T00:00:00Z, or date."); +} + +/// +/// The raw values an adapter received for a BIAN BankRelations/Update (roadmap 1.12). +/// reads them, so HTTP and MCP accept and refuse exactly the same values. null means not sent; an empty string means +/// sent blank, which clears the value. +/// +/// BIAN BankRelationType. +/// BIAN BusinessUnitEmployeeReference.PartyReference. +/// BIAN BankRelationReference, if sent. +public sealed record BankRelationsInput( + string? BankRelationType, + string? BusinessUnitEmployeePartyReference, + BankRelationReferenceInput? BankRelationReference); + +/// The recorded parts of a BIAN BankRelationReference a caller sent, as raw text (roadmap 1.12). +/// RelationshipStartDate.DateTimeContent. +/// RelationshipEndDate.DateTimeContent. +/// RelationshipLifecycleStatus.StatusDescription. +public sealed record BankRelationReferenceInput( + string? RelationshipStartDate, + string? RelationshipEndDate, + string? RelationshipLifecycleStatus) +{ + /// Whether no part was sent: such an object clears the dates and the status. + public bool IsEmpty => RelationshipStartDate is null && RelationshipEndDate is null && RelationshipLifecycleStatus is null; +} diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsDetails.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsDetails.cs new file mode 100644 index 0000000..6126573 --- /dev/null +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsDetails.cs @@ -0,0 +1,59 @@ +using System.Text.Json.Serialization; + +namespace RimBank.Party.PartyReferenceDataDirectory; + +/// +/// The party's relationship with the bank, held by the entry's BankRelations Behavior Qualifier (roadmap 1.12, ADR 0035): +/// what the bank is to the party, which employee or unit of the bank it is, and when and how the relationship stands. +/// BIAN gives one object, so there is one relationship per entry. Each part is optional: an unknown one is null. +/// +/// BIAN BankRelationType. +/// +/// BIAN BusinessUnitEmployeeReference.PartyReference: the directory entry of the employee (a person) or the unit (an +/// organisation), checked on the write side when it is recorded. Only with a . +/// +/// BIAN BankRelationReference.RelationshipStartDate, in UTC. +/// BIAN BankRelationReference.RelationshipEndDate, in UTC, not before . +/// BIAN BankRelationReference.RelationshipLifecycleStatus.StatusDescription. +public sealed record BankRelationsDetails( + BankRelationType? Type, + PartyReferenceDataDirectoryEntryId? BusinessUnitEmployee, + DateTimeOffset? StartDate, + DateTimeOffset? EndDate, + BankRelationLifecycleStatus? LifecycleStatus) +{ + /// Nothing recorded: the BankRelations of an entry before its first Update. + public static BankRelationsDetails Empty { get; } = new(null, null, null, null, null); + + /// Whether any part is recorded. Computed, so it is not stored. + [JsonIgnore] + public bool HasAny => this != Empty; + + /// The details after a partial update: a part the changes leave out keeps its value. + /// The parsed changes. + /// The resulting details. + public BankRelationsDetails Apply(BankRelationsChanges changes) + { + ArgumentNullException.ThrowIfNull(changes); + return new BankRelationsDetails( + changes.Type.ApplyTo(Type), + changes.BusinessUnitEmployee.ApplyTo(BusinessUnitEmployee), + changes.StartDate.ApplyTo(StartDate), + changes.EndDate.ApplyTo(EndDate), + changes.LifecycleStatus.ApplyTo(LifecycleStatus)); + } + + /// + /// The employee or unit an Update must check against the write side: the resulting reference when the changes set it + /// or change the type it must fit. A reference the Update keeps, with its type, was checked when it was recorded. + /// + /// The parsed changes. + /// The entry to check, or null. + public PartyReferenceDataDirectoryEntryId? ReferenceToCheck(BankRelationsChanges changes) + { + ArgumentNullException.ThrowIfNull(changes); + return changes.BusinessUnitEmployee is not null || changes.Type is not null + ? Apply(changes).BusinessUnitEmployee + : null; + } +} diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsErrors.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsErrors.cs new file mode 100644 index 0000000..6b2b11d --- /dev/null +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsErrors.cs @@ -0,0 +1,85 @@ +using RimBank.SharedKernel; + +namespace RimBank.Party.PartyReferenceDataDirectory; + +/// +/// The BankRelations Behavior Qualifier's own errors; their codes are documented in ADR 0024 and ADR 0035. A reference to +/// another party that breaks a rule answers the shared reference errors of . +/// +public static class BankRelationsErrors +{ + /// The code of . + public const string BankRelationsInvalidCode = "party.bank-relations-invalid"; + + /// The code of . + public const string BankRelationsFieldNotSupportedCode = "party.bank-relations-field-not-supported"; + + /// + /// The BankRelations 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 BankRelationsIdInvalid { get; } = Error.Validation( + TypedId.InvalidIdentifierCode, + "The value is not a valid identifier.", + new Dictionary> + { + [BankRelationsFields.BankRelationsId] = ["The bank relations id must be the BankRelationsId returned by Register."], + }); + + /// One or more BankRelations values are not valid (400), with a message per BIAN field. + /// The BIAN field names and their messages. + /// The party.bank-relations-invalid error. + public static Error BankRelationsInvalid(IReadOnlyDictionary> fieldErrors) => + Error.Validation(BankRelationsInvalidCode, "The BankRelations values are not valid.", fieldErrors); + + /// A BankRelationType that is not one RimBank records (400). + public static Error BankRelationTypeInvalid { get; } = BankRelationsInvalid(new Dictionary> + { + [BankRelationsFields.BankRelationType] = + [ + "The bank relation type must be one of " + string.Join(", ", Enum.GetNames()) + ".", + ], + }); + + /// A lifecycle status that is not one RimBank records (400). + public static Error LifecycleStatusInvalid { get; } = BankRelationsInvalid(new Dictionary> + { + [BankRelationsFields.RelationshipLifecycleStatusDescription] = + [ + "The lifecycle status must be one of " + string.Join(", ", Enum.GetNames()) + ".", + ], + }); + + /// + /// The resulting BankRelations has an employee or unit but no relation type, which says what kind of party it must be + /// (400): party.bank-relations-invalid naming . + /// + public static Error ReferenceWithoutType { get; } = BankRelationsInvalid(new Dictionary> + { + [BankRelationsFields.BankRelationType] = + [ + "A BusinessUnitEmployeeReference needs a BankRelationType; clear the reference in the same request when the type is cleared.", + ], + }); + + /// + /// The resulting BankRelations ends before it starts (400): party.bank-relations-invalid naming + /// . + /// + public static Error EndDateBeforeStartDate { get; } = BankRelationsInvalid(new Dictionary> + { + [BankRelationsFields.RelationshipEndDateContent] = ["The relationship must not end before it starts."], + }); + + /// + /// The request sent BIAN BankRelations fields or parts RimBank does not record (400, ADR 0035), with a message per + /// BIAN path. + /// + /// The BIAN paths and their messages. + /// The party.bank-relations-field-not-supported error. + public static Error BankRelationsFieldsNotSupported(IReadOnlyDictionary> fieldErrors) => + Error.Validation( + BankRelationsFieldNotSupportedCode, + "The request sends BankRelations fields that RimBank does not record; nothing was updated.", + fieldErrors); +} diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsFields.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsFields.cs new file mode 100644 index 0000000..153ae31 --- /dev/null +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsFields.cs @@ -0,0 +1,45 @@ +namespace RimBank.Party.PartyReferenceDataDirectory; + +/// +/// The BIAN names of the BankRelations fields and parameters, used as the keys of field errors so HTTP and MCP name them +/// the same way (roadmap 1.12, ADR 0035). +/// +public static class BankRelationsFields +{ + /// The BIAN parameter that names the entry's BankRelations. + public const string BankRelationsId = "bankrelationsid"; + + /// BIAN BankRelationType. + public const string BankRelationType = "BankRelationType"; + + /// BIAN BusinessUnitEmployeeReference, an Involvedparty object. + public const string BusinessUnitEmployeeReference = "BusinessUnitEmployeeReference"; + + /// BIAN BusinessUnitEmployeeReference.PartyReference: the employee's or unit's directory entry id. + public const string BusinessUnitEmployeePartyReference = BusinessUnitEmployeeReference + "." + PartyReferenceFields.PartyReferencePart; + + /// BIAN BankRelationReference, a PartyRelationship object. + public const string BankRelationReference = "BankRelationReference"; + + /// BIAN BankRelationReference.RelationshipStartDate, a Datetime object. + public const string RelationshipStartDate = BankRelationReference + ".RelationshipStartDate"; + + /// BIAN BankRelationReference.RelationshipEndDate, a Datetime object. + public const string RelationshipEndDate = BankRelationReference + ".RelationshipEndDate"; + + /// BIAN BankRelationReference.RelationshipLifecycleStatus, an ISO 20022 Status object. + public const string RelationshipLifecycleStatus = BankRelationReference + ".RelationshipLifecycleStatus"; + + /// The part of a BIAN Datetime object RimBank records. + public const string DateTimeContentPart = "DateTimeContent"; + + /// BIAN BankRelationReference.RelationshipStartDate.DateTimeContent. + public const string RelationshipStartDateContent = RelationshipStartDate + "." + DateTimeContentPart; + + /// BIAN BankRelationReference.RelationshipEndDate.DateTimeContent. + public const string RelationshipEndDateContent = RelationshipEndDate + "." + DateTimeContentPart; + + /// BIAN BankRelationReference.RelationshipLifecycleStatus.StatusDescription. + public const string RelationshipLifecycleStatusDescription = + RelationshipLifecycleStatus + "." + PartyReferenceFields.StatusDescriptionPart; +} diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/BankRelations/Events.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/BankRelations/Events.cs new file mode 100644 index 0000000..138a9ef --- /dev/null +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/BankRelations/Events.cs @@ -0,0 +1,13 @@ +namespace RimBank.Party.PartyReferenceDataDirectory; + +/// +/// The entry's BankRelations was updated (BIAN BankRelations/Update, roadmap 1.12). It carries the full +/// BankRelations after the update, so a consumer never needs the earlier events to know it (tech-stack §8.4). +/// +/// The entry. +/// The entry's BankRelations. +/// The BankRelations after the update. +public sealed record BankRelationsUpdated( + PartyReferenceDataDirectoryEntryId EntryId, + BankRelationsId BankRelationsId, + BankRelationsDetails Details) : PartyReferenceDataDirectoryEntryEvent; diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/BankRelations/RetrieveBankRelations.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/BankRelations/RetrieveBankRelations.cs new file mode 100644 index 0000000..e801a24 --- /dev/null +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/BankRelations/RetrieveBankRelations.cs @@ -0,0 +1,12 @@ +using RimBank.SharedKernel; + +namespace RimBank.Party.PartyReferenceDataDirectory; + +/// +/// Retrieve the party's BankRelations: BIAN BankRelations/Retrieve (ADR 0024, ADR 0035). Handled by +/// , which reads the entry's view; adapters show its BankRelations section. +/// +/// The entry: the {partyreferencedatadirectoryid} route value. +/// The entry's BankRelations: the {bankrelationsid} route value. +public sealed record RetrieveBankRelations(PartyReferenceDataDirectoryEntryId EntryId, BankRelationsId BankRelationsId) + : IQuery; diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/BankRelations/RetrieveBankRelationsHandler.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/BankRelations/RetrieveBankRelationsHandler.cs new file mode 100644 index 0000000..f7dd86e --- /dev/null +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/BankRelations/RetrieveBankRelationsHandler.cs @@ -0,0 +1,31 @@ +using RimBank.SharedKernel; + +namespace RimBank.Party.PartyReferenceDataDirectory; + +/// Handles on the read side (tech-stack §8.2, ADR 0024). +public static class RetrieveBankRelationsHandler +{ + /// Reads the entry's view through the read port and checks that the BankRelations id is the entry's. + /// The query. + /// The context's read port. + /// Cancels the read. + /// + /// The entry's view, party.party-not-found when the entry does not exist, or + /// party.behavior-qualifier-not-found when the BankRelations id is not the entry's. + /// + public static async Task> HandleAsync( + RetrieveBankRelations query, + IPartyDirectoryEnquiry enquiry, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(query); + ArgumentNullException.ThrowIfNull(enquiry); + + return await enquiry.FindEntryAsync(query.EntryId, cancellationToken) switch + { + null => PartyReferenceDataDirectoryEntryErrors.PartyNotFound, + { } view when view.BankRelationsId != query.BankRelationsId => PartyReferenceDataDirectoryEntryErrors.BehaviorQualifierNotFound, + { } view => view, + }; + } +} diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/BankRelations/UpdateBankRelations.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/BankRelations/UpdateBankRelations.cs new file mode 100644 index 0000000..d617b4c --- /dev/null +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/BankRelations/UpdateBankRelations.cs @@ -0,0 +1,22 @@ +using RimBank.SharedKernel; + +namespace RimBank.Party.PartyReferenceDataDirectory; + +/// +/// Update the party's BankRelations: BIAN BankRelations/Update (ADR 0024, ADR 0035), a partial update. Handled by +/// , which acknowledges with . +/// +/// The entry: the {partyreferencedatadirectoryid} route value. +/// The entry's BankRelations: the {bankrelationsid} route value. +/// +/// The entry'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 UpdateBankRelations( + PartyReferenceDataDirectoryEntryId EntryId, + BankRelationsId BankRelationsId, + long ExpectedVersion, + BankRelationsChanges Changes, + IdempotencyKey IdempotencyKey) : ICommand; diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/BankRelations/UpdateBankRelationsAcknowledged.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/BankRelations/UpdateBankRelationsAcknowledged.cs new file mode 100644 index 0000000..4b415b5 --- /dev/null +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/BankRelations/UpdateBankRelationsAcknowledged.cs @@ -0,0 +1,16 @@ +namespace RimBank.Party.PartyReferenceDataDirectory; + +/// +/// The acknowledgement of : the entry's BankRelations as the Update 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 entry. +/// The entry's BankRelations. +/// The entry's stream version after the Update, which the next command sends back as If-Match. +/// The BankRelations after the Update. +public sealed record UpdateBankRelationsAcknowledged( + PartyReferenceDataDirectoryEntryId EntryId, + BankRelationsId BankRelationsId, + long Version, + BankRelationsDetails BankRelations); diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/BankRelations/UpdateBankRelationsHandler.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/BankRelations/UpdateBankRelationsHandler.cs new file mode 100644 index 0000000..1e89ebd --- /dev/null +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/BankRelations/UpdateBankRelationsHandler.cs @@ -0,0 +1,81 @@ +using System.Diagnostics; +using RimBank.SharedKernel; + +namespace RimBank.Party.PartyReferenceDataDirectory; + +/// Handles on the write side (tech-stack §8.1, ADR 0024, ADR 0027, ADR 0035). +public static class UpdateBankRelationsHandler +{ + /// + /// Loads the entry; checks that it exists, that the BankRelations id is its own and that the caller's expected version + /// is current; loads the employee or unit to check through the write port, never a view; decides the Update and + /// appends it with that expected version. + /// + /// The command. + /// The context's write port. + /// Cancels the loads. + /// + /// The acknowledgement built from the decided state, party.party-not-found, + /// party.behavior-qualifier-not-found, party.version-conflict or the decision's error (including + /// party.self-reference, party.referenced-party-not-registered and + /// party.referenced-party-type-mismatch). + /// + public static async Task> HandleAsync( + UpdateBankRelations command, + IPartyDirectory directory, + CancellationToken cancellationToken) + { + ArgumentNullException.ThrowIfNull(command); + ArgumentNullException.ThrowIfNull(directory); + + var history = await directory.LoadEntryAsync(command.EntryId, cancellationToken); + var state = history.Aggregate(PartyReferenceDataDirectoryEntry.Initial, PartyReferenceDataDirectoryEntry.Evolve); + + var refused = (state.IsRegistered, state.BankRelationsId == command.BankRelationsId, history.Count == command.ExpectedVersion) switch + { + (false, _, _) => PartyReferenceDataDirectoryEntryErrors.PartyNotFound, + (true, false, _) => PartyReferenceDataDirectoryEntryErrors.BehaviorQualifierNotFound, + (true, true, false) => PartyReferenceDataDirectoryEntryErrors.VersionConflict, + _ => null, + }; + if (refused is not null) + { + return refused; + } + + var referencedPartyType = await LoadReferencedPartyTypeAsync( + directory, command.EntryId, state.CurrentBankRelations.ReferenceToCheck(command.Changes), cancellationToken); + + return PartyReferenceDataDirectoryEntry + .Decide(new UpdateBankRelationsDetails(command.BankRelationsId, command.Changes, referencedPartyType), state) + .Map(events => + { + directory.AppendToEntry(command.EntryId, command.ExpectedVersion, events); + var decided = events.Aggregate(state, PartyReferenceDataDirectoryEntry.Evolve); + return decided.BankRelations switch + { + { } bankRelations => new UpdateBankRelationsAcknowledged( + command.EntryId, command.BankRelationsId, history.Count + events.Count, bankRelations), + null => throw new UnreachableException("An accepted BankRelations Update leaves a BankRelations record."), + }; + }); + } + + // The party type of the employee or unit, if it is a registered entry. The entry itself is not loaded again (the + // decision refuses it), and an id of another stream type loads no entry events, so it is "not registered". + private static async Task LoadReferencedPartyTypeAsync( + IPartyDirectory directory, + PartyReferenceDataDirectoryEntryId entryId, + PartyReferenceDataDirectoryEntryId? referenced, + CancellationToken cancellationToken) + { + if (referenced is not { } other || other == entryId) + { + return null; + } + + var state = (await directory.LoadEntryAsync(other, cancellationToken)) + .Aggregate(PartyReferenceDataDirectoryEntry.Initial, PartyReferenceDataDirectoryEntry.Evolve); + return state.IsRegistered ? state.PartyType : null; + } +} diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/PartyReferenceDataDirectoryEntry/Decisions.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/PartyReferenceDataDirectoryEntry/Decisions.cs index 9ceaf35..36c2c36 100644 --- a/src/RimBank.Core/Party/PartyReferenceDataDirectory/PartyReferenceDataDirectoryEntry/Decisions.cs +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/PartyReferenceDataDirectoryEntry/Decisions.cs @@ -77,6 +77,21 @@ public sealed record UpdatePartyReferenceDetails( DateOnly Today, IReadOnlyDictionary? ReferencedParties = null) : PartyReferenceDataDirectoryEntryCommand; +/// +/// Update the entry's BankRelations (BIAN BankRelations/Update, roadmap 1.12, ADR 0035): a partial update. The +/// handler has already checked the entry, the BankRelations id and the expected version. +/// +/// The BankRelations the caller named. +/// The changes to apply. +/// +/// The party type of the employee or unit to check (), loaded by the +/// handler from the write side, or null when that entry is not registered or there is nothing to check. +/// +public sealed record UpdateBankRelationsDetails( + BankRelationsId BankRelationsId, + BankRelationsChanges Changes, + PartyType? ReferencedPartyType = null) : PartyReferenceDataDirectoryEntryCommand; + public sealed partial record PartyReferenceDataDirectoryEntry { /// @@ -95,7 +110,10 @@ public sealed partial record PartyReferenceDataDirectoryEntry /// (party.reference-invalid). Corporate references need an organisation's entry, and each reference it sets must /// be another registered entry of the right party type (party.corporate-references-need-organisation, /// party.self-reference, party.referenced-party-not-registered, - /// party.referenced-party-type-mismatch). It always records the resulting Reference. + /// party.referenced-party-type-mismatch). It always records the resulting Reference. BankRelations Update needs a + /// registered entry and its own BankRelations id, refuses a resulting employee or unit without a type or a relationship + /// that ends before it starts (party.bank-relations-invalid), and an employee or unit it sets, or keeps under a new + /// type, that is the entry itself, not registered or of the wrong party type (ADR 0035). It always records the result. /// public static Result> Decide( PartyReferenceDataDirectoryEntryCommand command, @@ -126,7 +144,7 @@ public static Result> Decid entryId, update.PartyType ?? current, update.RefreshDate)), - (UpdateDemographicsDetails or ExchangeDemographicsDetails or UpdatePartyReferenceDetails, { Id: null }) => + (UpdateDemographicsDetails or ExchangeDemographicsDetails or UpdatePartyReferenceDetails or UpdateBankRelationsDetails, { Id: null }) => PartyReferenceDataDirectoryEntryErrors.PartyNotFound, (UpdateDemographicsDetails update, _) when update.DemographicsId != state.DemographicsId => PartyReferenceDataDirectoryEntryErrors.BehaviorQualifierNotFound, @@ -157,6 +175,10 @@ public static Result> Decid PartyReferenceErrors.CustomerSinceDateAfterToday, (UpdatePartyReferenceDetails update, { Id: { } entryId }) => DecideReferences(entryId, state.PartyType, update, state.CurrentReference.Apply(update.Changes)), + (UpdateBankRelationsDetails update, _) when update.BankRelationsId != state.BankRelationsId => + PartyReferenceDataDirectoryEntryErrors.BehaviorQualifierNotFound, + (UpdateBankRelationsDetails update, { Id: { } entryId }) => + DecideBankRelations(entryId, update, state.CurrentBankRelations), _ => throw new UnreachableException($"The entry does not decide {command}."), }; @@ -212,6 +234,29 @@ private static Result> Deci new PartyReferenceUpdated(entryId, update.PartyReferenceId, updated)), }; + // The BankRelations rules (roadmap 1.12, ADR 0035), checked on the resulting BankRelations so a partial update cannot + // leave it inconsistent with values it keeps: an employee or unit needs a type, the relationship does not end before it + // starts, and the employee or unit to check is another registered entry of the party type the relation type needs. + private static Result> DecideBankRelations( + PartyReferenceDataDirectoryEntryId entryId, + UpdateBankRelationsDetails update, + BankRelationsDetails current) + { + var updated = current.Apply(update.Changes); + const string field = BankRelationsFields.BusinessUnitEmployeePartyReference; + return (updated, current.ReferenceToCheck(update.Changes), update.ReferencedPartyType) switch + { + ({ BusinessUnitEmployee: not null, Type: null }, _, _) => BankRelationsErrors.ReferenceWithoutType, + ({ StartDate: { } start, EndDate: { } end }, _, _) when end < start => BankRelationsErrors.EndDateBeforeStartDate, + (_, { } referenced, _) when referenced == entryId => PartyReferenceErrors.SelfReference(field), + (_, not null, null) => PartyReferenceErrors.ReferencedPartyNotRegistered(field), + ({ Type: { } type }, not null, { } actual) when actual != type.ReferencedPartyType() => + PartyReferenceErrors.ReferencedPartyTypeMismatch(field, type.ReferencedPartyType()), + _ => Decision.Accept( + new BankRelationsUpdated(entryId, update.BankRelationsId, updated)), + }; + } + private static Result> DecideDemographicsUpdate( PartyReferenceDataDirectoryEntryId entryId, UpdateDemographicsDetails update, diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/PartyReferenceDataDirectoryEntry/PartyReferenceDataDirectoryEntry.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/PartyReferenceDataDirectoryEntry/PartyReferenceDataDirectoryEntry.cs index 0a40775..23d70de 100644 --- a/src/RimBank.Core/Party/PartyReferenceDataDirectory/PartyReferenceDataDirectoryEntry/PartyReferenceDataDirectoryEntry.cs +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/PartyReferenceDataDirectoryEntry/PartyReferenceDataDirectoryEntry.cs @@ -16,6 +16,7 @@ namespace RimBank.Party.PartyReferenceDataDirectory; /// The entry's DirectoryEntryDate of type RefreshDate: its last Update, if any. /// The entry's Demographics record, or null until its first Update (see ). /// The entry's Reference record, or null until its first Update (see ). +/// The entry's BankRelations, or null until its first Update (see ). public sealed partial record PartyReferenceDataDirectoryEntry( PartyReferenceDataDirectoryEntryId? Id, PartyType? PartyType, @@ -25,7 +26,8 @@ public sealed partial record PartyReferenceDataDirectoryEntry( BankRelationsId? BankRelationsId, DateTimeOffset? RefreshDate = null, DemographicsRecord? Demographics = null, - PartyReferenceDetails? Reference = null) + PartyReferenceDetails? Reference = null, + BankRelationsDetails? BankRelations = null) : IDecider { /// An entry that is not registered yet. @@ -40,6 +42,9 @@ public sealed partial record PartyReferenceDataDirectoryEntry( /// The entry's Reference record: empty until its first Update. public PartyReferenceDetails CurrentReference => Reference ?? PartyReferenceDetails.Empty; + /// The entry's BankRelations: empty until its first Update. + public BankRelationsDetails CurrentBankRelations => BankRelations ?? BankRelationsDetails.Empty; + /// public static PartyReferenceDataDirectoryEntry Evolve( PartyReferenceDataDirectoryEntry state, @@ -71,6 +76,7 @@ public static PartyReferenceDataDirectoryEntry Evolve( }, }, PartyReferenceUpdated updated => state with { Reference = updated.Details }, + BankRelationsUpdated updated => state with { BankRelations = updated.Details }, _ => throw new UnreachableException($"The entry does not know {domainEvent}."), }; } diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Reference/PartyReferenceDates.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Reference/PartyReferenceDates.cs index a0bff3a..b5622a6 100644 --- a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Reference/PartyReferenceDates.cs +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Reference/PartyReferenceDates.cs @@ -24,6 +24,28 @@ public static bool TryReadDateTime(string text, out DateTimeOffset value) => DateTimeStyles.AssumeUniversal, out value); + /// + /// A point in time kept in UTC: an ISO 8601 date-time (one without an offset is UTC) or a date alone (00:00 UTC that + /// day). Used by the association periods (roadmap 1.11) and the bank relationship dates (roadmap 1.12). + /// + public static bool TryReadUtcInstant(string text, out DateTimeOffset value) + { + if (DateOnly.TryParseExact(text.Trim(), "yyyy-MM-dd", CultureInfo.InvariantCulture, DateTimeStyles.None, out var date)) + { + value = new DateTimeOffset(date.ToDateTime(TimeOnly.MinValue), TimeSpan.Zero); + return true; + } + + if (TryReadDateTime(text, out var dateTime)) + { + value = dateTime.ToUniversalTime(); + return true; + } + + value = default; + return false; + } + /// /// A calendar date: an ISO 8601 date such as 1990-05-17, or the date as written in an ISO 8601 date-time, with /// no time-zone conversion, because a date of birth has no time of day. diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Reference/PartyReferenceErrors.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Reference/PartyReferenceErrors.cs index 787eced..0b4c8e2 100644 --- a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Reference/PartyReferenceErrors.cs +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Reference/PartyReferenceErrors.cs @@ -2,7 +2,10 @@ namespace RimBank.Party.PartyReferenceDataDirectory; -/// The Reference Behavior Qualifier's business errors; their codes are documented in ADR 0024, ADR 0029 and ADR 0034. +/// +/// The Reference Behavior Qualifier's business errors; their codes are documented in ADR 0024, ADR 0029 and ADR 0034. The +/// reference errors are shared with BankRelations (ADR 0035). +/// public static class PartyReferenceErrors { /// The code of and . @@ -107,14 +110,14 @@ public static Error ReferenceFieldsNotSupported(IReadOnlyDictionaryA reference names the entry it is recorded on (422, roadmap 1.21, ADR 0034). + /// A reference names the entry it is recorded on (422, roadmap 1.21, ADR 0034; BankRelations, 1.12, ADR 0035). /// The BIAN path of the reference, for example CompanyOfficerReference.PartyReference. /// The party.self-reference error, whose message names the path. public static Error SelfReference(string field) => Error.BusinessRule( "party.self-reference", $"{field} names the party's own entry; a party cannot reference itself."); - /// A reference names no registered entry of this directory (422, roadmap 1.21, ADR 0034). + /// A reference names no registered entry of this directory (422, roadmap 1.21, ADR 0034; BankRelations, 1.12, ADR 0035). /// The BIAN path of the reference. /// The party.referenced-party-not-registered error, whose message names the path. public static Error ReferencedPartyNotRegistered(string field) => Error.BusinessRule( @@ -123,7 +126,8 @@ public static Error ReferencedPartyNotRegistered(string field) => Error.Business /// /// A reference names an entry of the wrong party type: the corporate customer and the legal entity are organisations, - /// and the company officer is a person (422, roadmap 1.21, ADR 0034). + /// and the company officer is a person (422, roadmap 1.21, ADR 0034); the BankRelations employee is a person and the unit an + /// organisation (1.12, ADR 0035). /// /// The BIAN path of the reference. /// The party type the reference needs. diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Retrieval/PartyReferenceDataDirectoryEntryView.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Retrieval/PartyReferenceDataDirectoryEntryView.cs index 7f7f206..fecf3d6 100644 --- a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Retrieval/PartyReferenceDataDirectoryEntryView.cs +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Retrieval/PartyReferenceDataDirectoryEntryView.cs @@ -23,6 +23,10 @@ namespace RimBank.Party.PartyReferenceDataDirectory; /// The entry's Reference section, served by BIAN Reference/Retrieve, or null until its first Update /// (also in documents projected before roadmap 1.10); see . /// +/// +/// The entry's BankRelations section, served by BIAN BankRelations/Retrieve, or null until its first Update +/// (also in documents projected before roadmap 1.12); see . +/// public sealed record PartyReferenceDataDirectoryEntryView( Guid Id, long Version, @@ -33,8 +37,13 @@ public sealed record PartyReferenceDataDirectoryEntryView( BankRelationsId BankRelationsId, DateTimeOffset? RefreshDate = null, DemographicsRecord? Demographics = null, - PartyReferenceDetails? Reference = null) + PartyReferenceDetails? Reference = null, + BankRelationsDetails? BankRelations = null) { + /// The entry's BankRelations section: empty until its first Update. Computed, so it is not stored. + [JsonIgnore] + public BankRelationsDetails CurrentBankRelations => BankRelations ?? BankRelationsDetails.Empty; + /// The entry's Demographics section: empty and unverified until its first Update. Computed, so it is not stored. [JsonIgnore] public DemographicsRecord CurrentDemographics => Demographics ?? DemographicsRecord.Empty; diff --git a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Retrieval/PartyReferenceDataDirectoryEntryViewProjection.cs b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Retrieval/PartyReferenceDataDirectoryEntryViewProjection.cs index a3a6aa3..4129ed0 100644 --- a/src/RimBank.Core/Party/PartyReferenceDataDirectory/Retrieval/PartyReferenceDataDirectoryEntryViewProjection.cs +++ b/src/RimBank.Core/Party/PartyReferenceDataDirectory/Retrieval/PartyReferenceDataDirectoryEntryViewProjection.cs @@ -54,6 +54,11 @@ public sealed class PartyReferenceDataDirectoryEntryViewProjection Version = view.Version + 1, Reference = updated.Details, }, + (_, BankRelationsUpdated updated) => view with + { + Version = view.Version + 1, + BankRelations = updated.Details, + }, (_, _) => view with { Version = view.Version + 1 }, }; } diff --git a/src/RimBank.Host/RimBank.Host.http b/src/RimBank.Host/RimBank.Host.http index cc0d540..54b5cc8 100644 --- a/src/RimBank.Host/RimBank.Host.http +++ b/src/RimBank.Host/RimBank.Host.http @@ -191,3 +191,55 @@ Idempotency-Key: {{$guid}} If-Match: "4" { "PartyType": "Person" } + +### BankRelations BQ (roadmap 1.12, ADR 0035): the second party (a person) is the first party's relationship manager. +# The employee or unit is loaded on the write side, like a Reference reference. Answers 200 with ETag "5", +# BankRelationType "RelationshipManager" and RelationshipStartDate "2024-01-01T00:00:00Z". +PUT {{host}}/PartyReferenceDataDirectory/{{register.response.body.$.PartyReferenceDataDirectoryEntryId}}/BankRelations/{{register.response.body.$.BankRelationsId}}/Update +Authorization: Bearer {{token.response.body.$.access_token}} +Content-Type: application/json +Idempotency-Key: {{$guid}} +If-Match: "4" + +{ + "BankRelationType": "relationshipmanager", + "BusinessUnitEmployeeReference": { "PartyReference": "{{associate.response.body.$.PartyReferenceDataDirectoryEntryId}}" }, + "BankRelationReference": { + "RelationshipStartDate": { "DateTimeContent": "2024-01-01" }, + "RelationshipLifecycleStatus": { "StatusDescription": "Active" } + } +} + +### Retrieve the BankRelations: the same values, ETag "5". Send If-None-Match: "5" to get 304 Not Modified. +GET {{host}}/PartyReferenceDataDirectory/{{register.response.body.$.PartyReferenceDataDirectoryEntryId}}/BankRelations/{{register.response.body.$.BankRelationsId}}/Retrieve +Authorization: Bearer {{token.response.body.$.access_token}} + +### A servicing branch must be an organisation, and the kept manager is a person: 422 application/problem+json, +# "errorCode": "party.referenced-party-type-mismatch", detail "BusinessUnitEmployeeReference.PartyReference must name a +# party of type Organisation.". Send the group's id as the reference too, and it is accepted. +PUT {{host}}/PartyReferenceDataDirectory/{{register.response.body.$.PartyReferenceDataDirectoryEntryId}}/BankRelations/{{register.response.body.$.BankRelationsId}}/Update +Authorization: Bearer {{token.response.body.$.access_token}} +Content-Type: application/json +Idempotency-Key: {{$guid}} +If-Match: "5" + +{ "BankRelationType": "ServicingBranch" } + +### The party itself as its relationship manager: 422 party.self-reference. Nothing is stored. +PUT {{host}}/PartyReferenceDataDirectory/{{register.response.body.$.PartyReferenceDataDirectoryEntryId}}/BankRelations/{{register.response.body.$.BankRelationsId}}/Update +Authorization: Bearer {{token.response.body.$.access_token}} +Content-Type: application/json +Idempotency-Key: {{$guid}} +If-Match: "5" + +{ "BusinessUnitEmployeeReference": { "PartyReference": "{{register.response.body.$.PartyReferenceDataDirectoryEntryId}}" } } + +### A BIAN part RimBank does not record: 400 party.bank-relations-field-not-supported with +# errors["BankRelationReference.RelationshipIdentification"]. Nothing is stored. +PUT {{host}}/PartyReferenceDataDirectory/{{register.response.body.$.PartyReferenceDataDirectoryEntryId}}/BankRelations/{{register.response.body.$.BankRelationsId}}/Update +Authorization: Bearer {{token.response.body.$.access_token}} +Content-Type: application/json +Idempotency-Key: {{$guid}} +If-Match: "5" + +{ "BankRelationReference": { "RelationshipIdentification": { "IdentifierValue": "REL-1" } } } diff --git a/tests/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql.Tests/BankRelationsRoundTripTests.cs b/tests/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql.Tests/BankRelationsRoundTripTests.cs new file mode 100644 index 0000000..4ddb61f --- /dev/null +++ b/tests/Party/RimBank.Party.PartyReferenceDataDirectory.Postgresql.Tests/BankRelationsRoundTripTests.cs @@ -0,0 +1,169 @@ +using RimBank.Postgresql; +using RimBank.SharedKernel; +using Wolverine; + +namespace RimBank.Party.PartyReferenceDataDirectory.Postgresql.Tests; + +// Roadmap 1.12: the BankRelations Update and Retrieve dispatched through the message bus. The Update checks the employee +// or unit on the write side, appends to the entry's stream at the caller's expected version, and the inline view's +// BankRelations section follows in the same transaction (ADR 0024, ADR 0027, ADR 0035). +public sealed class BankRelationsRoundTripTests(PostgresqlServer server) +{ + private const string Schema = "party_reference_data_directory"; + + private static readonly DateTimeOffset _start = new(2024, 1, 1, 0, 0, 0, TimeSpan.Zero); + + private static CancellationToken Cancellation => TestContext.Current.CancellationToken; + + [Fact] + public async Task Updating_the_bank_relations_commits_the_next_version_and_retrieve_sees_it_at_once() + { + await using var host = await server.StartHostAsync(); + var customer = await RegisterAsync(host.Bus, PartyType.Person); + var manager = await RegisterAsync(host.Bus, PartyType.Person); + var relation = Relation(manager.EntryId); + + var updated = (await UpdateAsync(host.Bus, customer, 1, NewKey(), BankRelationsChanges.To(relation))).Value; + var retrieved = (await RetrieveAsync(host.Bus, customer)).Value; + + updated.ShouldBe(new UpdateBankRelationsAcknowledged(customer.EntryId, customer.BankRelationsId, 2, relation)); + retrieved.Version.ShouldBe(2); + retrieved.BankRelations.ShouldBe(relation); + await using var query = host.Store.QuerySession(); + (await query.Events.FetchStreamStateAsync(customer.EntryId.Value, Cancellation)).ShouldNotBeNull().Version.ShouldBe(2); + } + + [Fact] + public async Task The_event_is_stored_under_a_stable_name_with_names_and_a_plain_entry_id() + { + await using var host = await server.StartHostAsync(); + var customer = await RegisterAsync(host.Bus, PartyType.Organisation); + var manager = await RegisterAsync(host.Bus, PartyType.Person); + await UpdateAsync(host.Bus, customer, 1, NewKey(), BankRelationsChanges.To(Relation(manager.EntryId))); + + async Task EventPart(string path) => await host.ScalarAsync( + $"SELECT data #>> '{{Details,{path}}}' FROM {Schema}.mt_events WHERE stream_id = '{customer.EntryId.Value}' AND version = 2"); + + (await host.ScalarAsync($"SELECT type FROM {Schema}.mt_events WHERE stream_id = '{customer.EntryId.Value}' AND version = 2")) + .ShouldBe("party_bank_relations_updated"); + (await EventPart("Type")).ShouldBe("RelationshipManager"); + (await EventPart("LifecycleStatus")).ShouldBe("Active"); + (await EventPart("BusinessUnitEmployee")).ShouldBe(manager.EntryId.ToString()); + } + + [Fact] + public async Task An_organisation_as_relationship_manager_is_refused_on_the_write_side_and_appends_nothing() + { + await using var host = await server.StartHostAsync(); + var customer = await RegisterAsync(host.Bus, PartyType.Person); + var branch = await RegisterAsync(host.Bus, PartyType.Organisation); + + var refused = await UpdateAsync(host.Bus, customer, 1, NewKey(), BankRelationsChanges.To(Relation(branch.EntryId))); + + refused.Error.Code.ShouldBe("party.referenced-party-type-mismatch"); + (await host.Enquiry.FindEntryAsync(customer.EntryId, Cancellation)).ShouldNotBeNull().Version.ShouldBe(1); + } + + [Fact] + public async Task An_employee_that_is_not_registered_is_refused() + { + await using var host = await server.StartHostAsync(); + var customer = await RegisterAsync(host.Bus, PartyType.Person); + + var refused = await UpdateAsync( + host.Bus, customer, 1, NewKey(), BankRelationsChanges.To(Relation(PartyReferenceDataDirectoryEntryId.New(TimeProvider.System)))); + + refused.Error.Code.ShouldBe("party.referenced-party-not-registered"); + } + + [Fact] + public async Task A_stale_version_is_a_conflict_and_appends_nothing() + { + await using var host = await server.StartHostAsync(); + var customer = await RegisterAsync(host.Bus, PartyType.Person); + await UpdateAsync(host.Bus, customer, 1, NewKey(), Started()); + + var stale = await UpdateAsync(host.Bus, customer, 1, NewKey(), Started()); + + stale.Error.ShouldBe(PartyReferenceDataDirectoryEntryErrors.VersionConflict); + (await host.Enquiry.FindEntryAsync(customer.EntryId, Cancellation)).ShouldNotBeNull().Version.ShouldBe(2); + } + + [Fact] + public async Task The_same_key_and_payload_replays_the_first_acknowledgement_and_appends_once() + { + await using var host = await server.StartHostAsync(); + var customer = await RegisterAsync(host.Bus, PartyType.Person); + var key = NewKey(); + + var first = await UpdateAsync(host.Bus, customer, 1, key, Started()); + var again = await UpdateAsync(host.Bus, customer, 1, key, Started()); + + again.Value.ShouldBe(first.Value); + (await host.ScalarAsync( + $"SELECT count(*) FROM {Schema}.mt_events WHERE stream_id = '{customer.EntryId.Value}' AND type = 'party_bank_relations_updated'")) + .ShouldBe(1); + } + + [Fact] + public async Task Rebuilding_the_view_from_the_event_store_restores_the_bank_relations() + { + await using var host = await server.StartHostAsync(); + var customer = await RegisterAsync(host.Bus, PartyType.Person); + var manager = await RegisterAsync(host.Bus, PartyType.Person); + await UpdateAsync(host.Bus, customer, 1, NewKey(), BankRelationsChanges.To(Relation(manager.EntryId))); + var before = await host.Enquiry.FindEntryAsync(customer.EntryId, Cancellation); + await using (var session = host.Store.LightweightSession()) + { + session.Delete(customer.EntryId.Value); + await session.SaveChangesAsync(Cancellation); + } + + await host.Store.RebuildViewAsync( + ViewRegistration.ProjectionName(), + TimeSpan.FromSeconds(60), + Cancellation); + + (await host.Enquiry.FindEntryAsync(customer.EntryId, Cancellation)).ShouldBe(before); + before.ShouldNotBeNull().CurrentBankRelations.ShouldBe(Relation(manager.EntryId)); + } + + [Fact] + public async Task A_foreign_bank_relations_id_is_not_found_for_commands_and_queries() + { + await using var host = await server.StartHostAsync(); + var customer = await RegisterAsync(host.Bus, PartyType.Person); + var foreign = customer with { BankRelationsId = BankRelationsId.New(TimeProvider.System) }; + + var update = await UpdateAsync(host.Bus, foreign, 1, NewKey(), Started()); + var retrieve = await RetrieveAsync(host.Bus, foreign); + + update.Error.ShouldBe(PartyReferenceDataDirectoryEntryErrors.BehaviorQualifierNotFound); + retrieve.Error.ShouldBe(PartyReferenceDataDirectoryEntryErrors.BehaviorQualifierNotFound); + } + + private static BankRelationsDetails Relation(PartyReferenceDataDirectoryEntryId employee) => + new(BankRelationType.RelationshipManager, employee, _start, null, BankRelationLifecycleStatus.Active); + + private static BankRelationsChanges Started() => new(StartDate: new(_start)); + + private static async Task RegisterAsync(IMessageBus bus, PartyType partyType) => + (await bus.InvokeAsync>(new RegisterParty(partyType, NewKey()), Cancellation)).Value; + + private static Task> UpdateAsync( + IMessageBus bus, + RegisterPartyAcknowledged registered, + long expectedVersion, + IdempotencyKey key, + BankRelationsChanges changes) => + bus.InvokeAsync>( + new UpdateBankRelations(registered.EntryId, registered.BankRelationsId, expectedVersion, changes, key), + Cancellation); + + private static Task> RetrieveAsync(IMessageBus bus, RegisterPartyAcknowledged registered) => + bus.InvokeAsync>( + new RetrieveBankRelations(registered.EntryId, registered.BankRelationsId), + Cancellation); + + private static IdempotencyKey NewKey() => IdempotencyKey.From(Guid.CreateVersion7().ToString()); +} diff --git a/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsLogPrivacyTests.cs b/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsLogPrivacyTests.cs new file mode 100644 index 0000000..f4dc89b --- /dev/null +++ b/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsLogPrivacyTests.cs @@ -0,0 +1,64 @@ +using Alba; +using RimBank.Host.Testing; +using static RimBank.Party.PartyReferenceDataDirectory.Api.Tests.BankRelationsScenarios; +using static RimBank.Party.PartyReferenceDataDirectory.Api.Tests.DemographicsScenarios; + +namespace RimBank.Party.PartyReferenceDataDirectory.Api.Tests; + +// Roadmap 1.12 (mission quality bar "Security", ADR 0035, 7.2): who manages a party at the bank, since when and how the +// relationship stands is personal data. Whatever the outcome (accepted, refused as invalid, refused by a rule, refused as +// stale) and on Retrieve, none of the submitted values reaches the host's logs, even at Debug level. +public sealed class BankRelationsLogPrivacyTests(PostgresqlServer server) +{ + [Fact] + public async Task No_submitted_bank_relations_value_is_logged_on_success_refusal_conflict_or_retrieve() + { + var logs = new CapturedLogs(); + await using var host = await server.StartHostAsync(logs: logs); + var customer = await RegisterAsync(host); + var manager = await RegisterAsync(host); + var branch = await RegisterAsync(host, "Organisation"); + var managed = $$""" + { + "BankRelationType": "RelationshipManager", + "BusinessUnitEmployeeReference": { "PartyReference": "{{manager.PartyReferenceDataDirectoryEntryId}}" }, + "BankRelationReference": { + "RelationshipStartDate": { "DateTimeContent": "2019-04-23" }, + "RelationshipEndDate": { "DateTimeContent": "2031-08-14T00:00:00Z" }, + "RelationshipLifecycleStatus": { "StatusDescription": "Suspended" } + } + } + """; + + await PutBankRelationsOkAsync(host, BankRelationsUpdateUrl(customer), managed, "\"1\"", "\"2\""); + await PutProblemAsync( + host, + BankRelationsUpdateUrl(customer), + """{ "BankRelationReference": { "RelationshipStartDate": { "DateTimeContent": "23/04/2019-x" } } }""", + "\"2\"", + 400); + await PutProblemAsync(host, BankRelationsUpdateUrl(customer), ManagedBody(branch.PartyReferenceDataDirectoryEntryId), "\"2\"", 422); + await PutProblemAsync(host, BankRelationsUpdateUrl(customer), managed, "\"1\"", 409); + await host.Alba.Scenario(_ => + { + AssociationScenarios.Get(_, BankRelationsRetrieveUrl(customer)); + _.StatusCodeShouldBeOk(); + }); + + // The capture sees the requests themselves (their path holds no BankRelations value), so an empty match means not logged. + logs.Containing($"/BankRelations/{customer.BankRelationsId}/Update").ShouldNotBeEmpty(); + string[] values = + [ + manager.PartyReferenceDataDirectoryEntryId.ToString(), + branch.PartyReferenceDataDirectoryEntryId.ToString(), + "2019-04-23", + "2031-08-14", + "Suspended", + "23/04/2019-x", + ]; + foreach (var value in values) + { + logs.Containing(value).Select(entry => $"{entry.Level} {entry.Category}").ShouldBeEmpty($"'{value}' was logged"); + } + } +} diff --git a/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsScenarios.cs b/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsScenarios.cs new file mode 100644 index 0000000..9c11e79 --- /dev/null +++ b/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsScenarios.cs @@ -0,0 +1,75 @@ +using System.Text.Json; +using Alba; +using Microsoft.Net.Http.Headers; + +namespace RimBank.Party.PartyReferenceDataDirectory.Api.Tests; + +// The requests the BankRelations endpoint tests share (roadmap 1.12). Register, Put and the Problem Details checks are +// the Demographics ones, Get is the Associations one. +internal static class BankRelationsScenarios +{ + public static string BankRelationsUrl(Guid entryId, Guid bankRelationsId, string operation) => + BankRelationsUrl(entryId.ToString(), bankRelationsId.ToString(), operation); + + public static string BankRelationsUrl(string entryId, string bankRelationsId, string operation) => + $"/PartyReferenceDataDirectory/{entryId}/BankRelations/{bankRelationsId}/{operation}"; + + public static string BankRelationsUpdateUrl(RegisterPartyResponse registered) => + BankRelationsUrl(registered.PartyReferenceDataDirectoryEntryId, registered.BankRelationsId, "Update"); + + public static string BankRelationsRetrieveUrl(RegisterPartyResponse registered) => + BankRelationsUrl(registered.PartyReferenceDataDirectoryEntryId, registered.BankRelationsId, "Retrieve"); + + public static string ManagedBody(Guid employeeId, string type = "relationshipmanager") => + $$""" + { + "BankRelationType": "{{type}}", + "BusinessUnitEmployeeReference": { "PartyReference": "{{employeeId}}" }, + "BankRelationReference": { + "RelationshipStartDate": { "DateTimeContent": "2024-01-01" }, + "RelationshipLifecycleStatus": { "StatusDescription": "active" } + }, + "NotABianField": "ignored" + } + """; + + public static BankRelationsResponse ManagedResponse(RegisterPartyResponse registered, Guid employeeId) => + new( + registered.BankRelationsId, + registered.PartyReferenceDataDirectoryEntryId, + "RelationshipManager", + new InvolvedPartyModel { PartyReference = employeeId.ToString() }, + new BankRelationReferenceModel + { + RelationshipStartDate = new DateTimeModel { DateTimeContent = "2024-01-01T00:00:00Z" }, + RelationshipLifecycleStatus = new RelationshipLifecycleStatusModel { StatusDescription = "Active" }, + }); + + public static async Task PutBankRelationsOkAsync(PartyApiHost host, string url, string body, string ifMatch, string etag) + { + var result = await host.Alba.Scenario(_ => + { + DemographicsScenarios.Put(_, url, body, ifMatch); + _.StatusCodeShouldBeOk(); + _.ContentTypeShouldBe("application/json; charset=utf-8"); + _.Header(HeaderNames.ETag).SingleValueShouldEqual(etag); + }); + + return (await result.ReadAsJsonAsync()).ShouldNotBeNull(); + } + + public static async Task GetBankRelationsProblemAsync(PartyApiHost host, string url, int status) + { + var result = await host.Alba.Scenario(_ => + { + AssociationScenarios.Get(_, url); + _.StatusCodeShouldBe(status); + _.ContentTypeShouldBe(DemographicsScenarios.ProblemJson); + }); + + return await DemographicsScenarios.ProblemOf(result, status); + } + + public static string[] ErrorFields(JsonElement problem) => + [.. problem.GetProperty("errors").EnumerateObject().Select(field => field.Name)]; +} diff --git a/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/BankRelations/RetrieveBankRelationsEndpointTests.cs b/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/BankRelations/RetrieveBankRelationsEndpointTests.cs new file mode 100644 index 0000000..4e89bb5 --- /dev/null +++ b/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/BankRelations/RetrieveBankRelationsEndpointTests.cs @@ -0,0 +1,96 @@ +using Alba; +using Microsoft.Net.Http.Headers; +using static RimBank.Party.PartyReferenceDataDirectory.Api.Tests.BankRelationsScenarios; +using static RimBank.Party.PartyReferenceDataDirectory.Api.Tests.DemographicsScenarios; + +namespace RimBank.Party.PartyReferenceDataDirectory.Api.Tests; + +// Roadmap 1.12: GET …/BankRelations/{bankrelationsid}/Retrieve over HTTP, answered from the entry's inline view with its +// version as ETag (specs/tech-stack.md §5, ADR 0024, ADR 0035). +public sealed class RetrieveBankRelationsEndpointTests(PostgresqlServer server) +{ + [Fact] + public async Task Retrieve_shows_what_update_recorded_with_the_entry_version() + { + await using var host = await server.StartHostAsync(); + var customer = await RegisterAsync(host); + var manager = await RegisterAsync(host); + await PutBankRelationsOkAsync(host, BankRelationsUpdateUrl(customer), ManagedBody(manager.PartyReferenceDataDirectoryEntryId), "\"1\"", "\"2\""); + + var result = await host.Alba.Scenario(_ => + { + AssociationScenarios.Get(_, BankRelationsRetrieveUrl(customer)); + _.StatusCodeShouldBeOk(); + _.Header(HeaderNames.ETag).SingleValueShouldEqual("\"2\""); + }); + + (await result.ReadAsJsonAsync()).ShouldBe(ManagedResponse(customer, manager.PartyReferenceDataDirectoryEntryId)); + } + + [Fact] + public async Task Bank_relations_never_updated_answer_the_ids_only() + { + await using var host = await server.StartHostAsync(); + var customer = await RegisterAsync(host); + + var result = await host.Alba.Scenario(_ => + { + AssociationScenarios.Get(_, BankRelationsRetrieveUrl(customer)); + _.StatusCodeShouldBeOk(); + _.Header(HeaderNames.ETag).SingleValueShouldEqual("\"1\""); + }); + + (await result.ReadAsTextAsync()).ShouldBe( + $$"""{"BankRelationsId":"{{customer.BankRelationsId}}","PartyReferenceDataDirectoryEntryId":"{{customer.PartyReferenceDataDirectoryEntryId}}"}"""); + } + + [Fact] + public async Task A_current_If_None_Match_is_not_modified() + { + await using var host = await server.StartHostAsync(); + var customer = await RegisterAsync(host); + + await host.Alba.Scenario(_ => + { + AssociationScenarios.Get(_, BankRelationsRetrieveUrl(customer), ifNoneMatch: "\"1\""); + _.StatusCodeShouldBe(304); + _.Header(HeaderNames.ETag).SingleValueShouldEqual("\"1\""); + }); + } + + [Fact] + public async Task An_unknown_entry_is_a_party_not_found_problem() + { + await using var host = await server.StartHostAsync(); + + var problem = await GetBankRelationsProblemAsync(host, BankRelationsUrl(Guid.CreateVersion7(), Guid.CreateVersion7(), "Retrieve"), 404); + + problem.GetProperty("errorCode").GetString().ShouldBe("party.party-not-found"); + } + + [Fact] + public async Task A_foreign_bank_relations_id_is_a_behavior_qualifier_not_found_problem() + { + await using var host = await server.StartHostAsync(); + var customer = await RegisterAsync(host); + var other = await RegisterAsync(host); + + var problem = await GetBankRelationsProblemAsync( + host, BankRelationsUrl(customer.PartyReferenceDataDirectoryEntryId, other.BankRelationsId, "Retrieve"), 404); + + problem.GetProperty("errorCode").GetString().ShouldBe("party.behavior-qualifier-not-found"); + } + + [Fact] + public async Task A_malformed_bank_relations_id_is_a_400_naming_the_parameter() + { + await using var host = await server.StartHostAsync(); + var customer = await RegisterAsync(host); + + var problem = await GetBankRelationsProblemAsync( + host, BankRelationsUrl(customer.PartyReferenceDataDirectoryEntryId.ToString(), Guid.NewGuid().ToString(), "Retrieve"), 400); + + problem.GetProperty("errorCode").GetString().ShouldBe("shared.invalid-identifier"); + ErrorFields(problem).ShouldBe(["bankrelationsid"]); + } +} diff --git a/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/BankRelations/UpdateBankRelationsEndpointTests.cs b/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/BankRelations/UpdateBankRelationsEndpointTests.cs new file mode 100644 index 0000000..4b69c2b --- /dev/null +++ b/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/BankRelations/UpdateBankRelationsEndpointTests.cs @@ -0,0 +1,257 @@ +using System.Text.Json; +using Alba; +using Microsoft.Net.Http.Headers; +using RimBank.Host.Testing; +using static RimBank.Party.PartyReferenceDataDirectory.Api.Tests.BankRelationsScenarios; +using static RimBank.Party.PartyReferenceDataDirectory.Api.Tests.DemographicsScenarios; + +namespace RimBank.Party.PartyReferenceDataDirectory.Api.Tests; + +// Roadmap 1.12: PUT …/BankRelations/{bankrelationsid}/Update over HTTP (specs/tech-stack.md §5, ADR 0027, ADR 0035). The +// employee or unit is checked on the write side; every refusal is Problem Details and stores nothing. +public sealed class UpdateBankRelationsEndpointTests(PostgresqlServer server) +{ + [Fact] + public async Task A_relationship_manager_is_recorded_and_answered_with_the_next_version() + { + await using var host = await server.StartHostAsync(); + var customer = await RegisterAsync(host); + var manager = await RegisterAsync(host); + + var updated = await PutBankRelationsOkAsync( + host, BankRelationsUpdateUrl(customer), ManagedBody(manager.PartyReferenceDataDirectoryEntryId), "\"1\"", "\"2\""); + + updated.ShouldBe(ManagedResponse(customer, manager.PartyReferenceDataDirectoryEntryId)); + } + + [Fact] + public async Task A_partial_update_keeps_what_it_does_not_send_and_an_empty_relationship_clears_the_dates_and_status() + { + await using var host = await server.StartHostAsync(); + var customer = await RegisterAsync(host); + var manager = await RegisterAsync(host); + await PutBankRelationsOkAsync(host, BankRelationsUpdateUrl(customer), ManagedBody(manager.PartyReferenceDataDirectoryEntryId), "\"1\"", "\"2\""); + + var ended = await PutBankRelationsOkAsync( + host, + BankRelationsUpdateUrl(customer), + """{ "BankRelationReference": { "RelationshipEndDate": { "DateTimeContent": "2026-06-30T02:00:00+02:00" }, "RelationshipLifecycleStatus": { "StatusDescription": "Ended" } } }""", + "\"2\"", + "\"3\""); + var cleared = await PutBankRelationsOkAsync(host, BankRelationsUpdateUrl(customer), """{ "BankRelationReference": {} }""", "\"3\"", "\"4\""); + + ended.ShouldBe(ManagedResponse(customer, manager.PartyReferenceDataDirectoryEntryId) with + { + BankRelationReference = new BankRelationReferenceModel + { + RelationshipStartDate = new DateTimeModel { DateTimeContent = "2024-01-01T00:00:00Z" }, + RelationshipEndDate = new DateTimeModel { DateTimeContent = "2026-06-30T00:00:00Z" }, + RelationshipLifecycleStatus = new RelationshipLifecycleStatusModel { StatusDescription = "Ended" }, + }, + }); + cleared.ShouldBe(ManagedResponse(customer, manager.PartyReferenceDataDirectoryEntryId) with { BankRelationReference = null }); + } + + [Fact] + public async Task A_branch_services_an_organisation() + { + await using var host = await server.StartHostAsync(); + var company = await RegisterAsync(host, "Organisation"); + var branch = await RegisterAsync(host, "Organisation"); + + var updated = await PutBankRelationsOkAsync( + host, + BankRelationsUpdateUrl(company), + $$"""{ "BankRelationType": "ServicingBranch", "BusinessUnitEmployeeReference": { "PartyReference": "{{branch.PartyReferenceDataDirectoryEntryId}}" } }""", + "\"1\"", + "\"2\""); + + updated.ShouldBe(new BankRelationsResponse( + company.BankRelationsId, + company.PartyReferenceDataDirectoryEntryId, + "ServicingBranch", + new InvolvedPartyModel { PartyReference = branch.PartyReferenceDataDirectoryEntryId.ToString() })); + } + + [Fact] + public async Task A_person_as_servicing_branch_is_a_422_type_mismatch_and_nothing_is_stored() + { + await using var host = await server.StartHostAsync(); + var customer = await RegisterAsync(host); + var person = await RegisterAsync(host); + + var problem = await PutProblemAsync( + host, BankRelationsUpdateUrl(customer), ManagedBody(person.PartyReferenceDataDirectoryEntryId, "ServicingBranch"), "\"1\"", 422); + + problem.GetProperty("errorCode").GetString().ShouldBe("party.referenced-party-type-mismatch"); + problem.GetProperty("detail").GetString().ShouldBe("BusinessUnitEmployeeReference.PartyReference must name a party of type Organisation."); + (await host.ScalarAsync( + $"SELECT count(*) FROM party_reference_data_directory.mt_events WHERE stream_id = '{customer.PartyReferenceDataDirectoryEntryId}'")) + .ShouldBe(1); + } + + [Fact] + public async Task The_party_itself_as_its_relationship_manager_is_a_422_self_reference() + { + await using var host = await server.StartHostAsync(); + var customer = await RegisterAsync(host); + + var problem = await PutProblemAsync(host, BankRelationsUpdateUrl(customer), ManagedBody(customer.PartyReferenceDataDirectoryEntryId), "\"1\"", 422); + + problem.GetProperty("errorCode").GetString().ShouldBe("party.self-reference"); + problem.GetProperty("detail").GetString().ShouldNotBeNull().ShouldStartWith("BusinessUnitEmployeeReference.PartyReference"); + } + + [Fact] + public async Task An_employee_that_is_not_registered_is_a_422_and_an_association_id_is_not_an_entry() + { + await using var host = await server.StartHostAsync(); + var (owner, _, association) = await AssociationScenarios.AssociateAsync(host); + + var unknown = await PutProblemAsync(host, BankRelationsUpdateUrl(owner), ManagedBody(Guid.CreateVersion7()), "\"1\"", 422); + var associationId = await PutProblemAsync(host, BankRelationsUpdateUrl(owner), ManagedBody(association.AssociationsId), "\"1\"", 422); + + unknown.GetProperty("errorCode").GetString().ShouldBe("party.referenced-party-not-registered"); + associationId.GetProperty("errorCode").GetString().ShouldBe("party.referenced-party-not-registered"); + } + + [Fact] + public async Task Every_invalid_value_is_a_400_naming_its_path() + { + await using var host = await server.StartHostAsync(); + var customer = await RegisterAsync(host); + + var problem = await PutProblemAsync( + host, + BankRelationsUpdateUrl(customer), + """ + { + "BankRelationType": "Customer", + "BusinessUnitEmployeeReference": { "PartyReference": "EMP-1" }, + "BankRelationReference": { + "RelationshipStartDate": { "DateTimeContent": "01/01/2024" }, + "RelationshipEndDate": { "DateTimeContent": "soon" }, + "RelationshipLifecycleStatus": { "StatusDescription": "Closed" } + } + } + """, + "\"1\"", + 400); + + problem.GetProperty("errorCode").GetString().ShouldBe("party.bank-relations-invalid"); + ErrorFields(problem).ShouldBe( + [ + "BankRelationType", + "BusinessUnitEmployeeReference.PartyReference", + "BankRelationReference.RelationshipStartDate.DateTimeContent", + "BankRelationReference.RelationshipEndDate.DateTimeContent", + "BankRelationReference.RelationshipLifecycleStatus.StatusDescription", + ], + ignoreOrder: true); + } + + [Theory] + [InlineData("""{ "BusinessUnitEmployeeReference": { "PartyReference": "018f0000-0000-7000-8000-000000000000" } }""", "BankRelationType")] + [InlineData("""{ "BankRelationReference": { "RelationshipStartDate": { "DateTimeContent": "2025-01-02" }, "RelationshipEndDate": { "DateTimeContent": "2025-01-01" } } }""", "BankRelationReference.RelationshipEndDate.DateTimeContent")] + public async Task A_resulting_bank_relations_that_breaks_a_value_rule_is_a_400(string body, string field) + { + await using var host = await server.StartHostAsync(); + var customer = await RegisterAsync(host); + + var problem = await PutProblemAsync(host, BankRelationsUpdateUrl(customer), body, "\"1\"", 400); + + problem.GetProperty("errorCode").GetString().ShouldBe("party.bank-relations-invalid"); + ErrorFields(problem).ShouldBe([field]); + } + + [Fact] + public async Task Every_part_rimbank_does_not_record_is_refused_by_path_before_the_values_are_read() + { + await using var host = await server.StartHostAsync(); + var customer = await RegisterAsync(host); + + var problem = await PutProblemAsync( + host, + BankRelationsUpdateUrl(customer), + """ + { + "BankRelationType": "Customer", + "BusinessUnitEmployeeReference": { "InvolvementReference": "RM" }, + "BankRelationReference": { + "RelationshipType": "Primary", + "RelationshipValidityPeriod": { "FromDateTime": { "DateTimeContent": "2024-01-01" } }, + "RelationshipIdentification": { "IdentifierValue": "REL-1" }, + "RelationshipStartDate": { "DateTimeContent": "2024-01-01", "TimeZoneCode": "CET" }, + "RelationshipLifecycleStatus": { "StatusDescription": "Active", "StatusReason": "Onboarded" }, + "RelationshipEndDate": null + } + } + """, + "\"1\"", + 400); + + problem.GetProperty("errorCode").GetString().ShouldBe("party.bank-relations-field-not-supported"); + ErrorFields(problem).ShouldBe( + [ + "BusinessUnitEmployeeReference.InvolvementReference", + "BankRelationReference.RelationshipType", + "BankRelationReference.RelationshipValidityPeriod", + "BankRelationReference.RelationshipIdentification", + "BankRelationReference.RelationshipStartDate.TimeZoneCode", + "BankRelationReference.RelationshipLifecycleStatus.StatusReason", + ], + ignoreOrder: true); + } + + [Fact] + public async Task A_stale_If_Match_is_a_409_and_a_missing_one_a_428() + { + await using var host = await server.StartHostAsync(); + var customer = await RegisterAsync(host); + await PutBankRelationsOkAsync(host, BankRelationsUpdateUrl(customer), "{}", "\"1\"", "\"2\""); + + var stale = await PutProblemAsync(host, BankRelationsUpdateUrl(customer), "{}", "\"1\"", 409); + var missing = await PutProblemAsync(host, BankRelationsUpdateUrl(customer), "{}", ifMatch: null, 428); + + stale.GetProperty("errorCode").GetString().ShouldBe("party.version-conflict"); + missing.GetProperty("errorCode").GetString().ShouldBe("shared.if-match-required"); + } + + [Fact] + public async Task A_missing_Idempotency_Key_is_a_validation_problem() + { + await using var host = await server.StartHostAsync(); + var customer = await RegisterAsync(host); + + var result = await host.Alba.Scenario(_ => + { + _.Put.Text("{}").ToUrl(BankRelationsUpdateUrl(customer)); + _.WithRequestHeader(HeaderNames.ContentType, "application/json"); + _.WithRequestHeader(HeaderNames.Authorization, "Bearer " + TestTokens.Issue()); + _.WithRequestHeader(HeaderNames.IfMatch, "\"1\""); + _.StatusCodeShouldBe(400); + _.ContentTypeShouldBe(ProblemJson); + }); + + (await result.ReadAsJsonAsync()).GetProperty("errorCode").GetString().ShouldBe("shared.idempotency-key-missing"); + } + + [Fact] + public async Task Unknown_entries_and_foreign_or_malformed_ids_are_problems() + { + await using var host = await server.StartHostAsync(); + var customer = await RegisterAsync(host); + var other = await RegisterAsync(host); + + var unknown = await PutProblemAsync(host, BankRelationsUrl(Guid.CreateVersion7(), Guid.CreateVersion7(), "Update"), "{}", "\"1\"", 404); + var foreign = await PutProblemAsync( + host, BankRelationsUrl(customer.PartyReferenceDataDirectoryEntryId, other.BankRelationsId, "Update"), "{}", "\"1\"", 404); + var malformed = await PutProblemAsync( + host, BankRelationsUrl(customer.PartyReferenceDataDirectoryEntryId.ToString(), "not-an-id", "Update"), "{}", "\"1\"", 400); + + unknown.GetProperty("errorCode").GetString().ShouldBe("party.party-not-found"); + foreign.GetProperty("errorCode").GetString().ShouldBe("party.behavior-qualifier-not-found"); + malformed.GetProperty("errorCode").GetString().ShouldBe("shared.invalid-identifier"); + ErrorFields(malformed).ShouldBe(["bankrelationsid"]); + } +} diff --git a/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/PartyReferenceDataDirectoryConformanceTests.cs b/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/PartyReferenceDataDirectoryConformanceTests.cs index 3c5b437..97ef4c5 100644 --- a/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/PartyReferenceDataDirectoryConformanceTests.cs +++ b/tests/RimBank.Api.Tests/Party/PartyReferenceDataDirectory/PartyReferenceDataDirectoryConformanceTests.cs @@ -22,6 +22,8 @@ public sealed class PartyReferenceDataDirectoryConformanceTests(PostgresqlServer RegisterPartyAssociationEndpoint.OperationId, UpdatePartyAssociationEndpoint.OperationId, RetrievePartyAssociationEndpoint.OperationId, + UpdateBankRelationsEndpoint.OperationId, + RetrieveBankRelationsEndpoint.OperationId, ]; [Fact] diff --git a/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/BankRelations/BankRelationTypesTests.cs b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/BankRelations/BankRelationTypesTests.cs new file mode 100644 index 0000000..f728b37 --- /dev/null +++ b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/BankRelations/BankRelationTypesTests.cs @@ -0,0 +1,62 @@ +using RimBank.SharedKernel; + +namespace RimBank.Party.PartyReferenceDataDirectory.Tests; + +// The bank relation types and lifecycle statuses (roadmap 1.12, ADR 0035): read in any case, written as their names, and +// each type names the party type of the employee or unit it references. +public sealed class BankRelationTypesTests +{ + [Theory] + [InlineData("RelationshipManager", BankRelationType.RelationshipManager)] + [InlineData(" accountofficer ", BankRelationType.AccountOfficer)] + [InlineData("SERVICINGBRANCH", BankRelationType.ServicingBranch)] + [InlineData("ServicingBusinessUnit", BankRelationType.ServicingBusinessUnit)] + public void A_type_is_read_in_any_case(string text, BankRelationType expected) => + BankRelationTypes.Read(text).Value.ShouldBe(expected); + + [Theory] + [InlineData("Relationship Manager")] + [InlineData("1")] + [InlineData("Customer")] + public void Anything_else_is_invalid_naming_the_field(string text) + { + var error = BankRelationTypes.Read(text).Error; + + error.Code.ShouldBe("party.bank-relations-invalid"); + error.Kind.ShouldBe(ErrorKind.Validation); + error.FieldErrors.Keys.ShouldBe(["BankRelationType"]); + } + + [Theory] + [InlineData(BankRelationType.RelationshipManager, PartyType.Person)] + [InlineData(BankRelationType.AccountOfficer, PartyType.Person)] + [InlineData(BankRelationType.ServicingBranch, PartyType.Organisation)] + [InlineData(BankRelationType.ServicingBusinessUnit, PartyType.Organisation)] + public void An_employee_s_role_references_a_person_and_a_unit_s_an_organisation(BankRelationType type, PartyType expected) => + type.ReferencedPartyType().ShouldBe(expected); + + [Fact] + public void Every_type_is_written_as_its_name() => + Enum.GetValues().Select(type => type.ToBianName()) + .ShouldBe(["RelationshipManager", "AccountOfficer", "ServicingBranch", "ServicingBusinessUnit"]); + + [Fact] + public void An_undefined_type_has_no_name() => + Should.Throw(() => ((BankRelationType)99).ToBianName()); + + [Theory] + [InlineData("active", BankRelationLifecycleStatus.Active)] + [InlineData(" Suspended ", BankRelationLifecycleStatus.Suspended)] + [InlineData("ENDED", BankRelationLifecycleStatus.Ended)] + public void A_lifecycle_status_is_read_in_any_case(string text, BankRelationLifecycleStatus expected) => + BankRelationLifecycleStatuses.Read(text).Value.ShouldBe(expected); + + [Fact] + public void An_unknown_lifecycle_status_is_invalid_naming_its_path() => + BankRelationLifecycleStatuses.Read("Closed").Error.FieldErrors.Keys + .ShouldBe(["BankRelationReference.RelationshipLifecycleStatus.StatusDescription"]); + + [Fact] + public void Every_lifecycle_status_is_written_as_its_name() => + Enum.GetValues().Select(status => status.ToBianName()).ShouldBe(["Active", "Suspended", "Ended"]); +} diff --git a/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsChangesTests.cs b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsChangesTests.cs new file mode 100644 index 0000000..9ba3c55 --- /dev/null +++ b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsChangesTests.cs @@ -0,0 +1,100 @@ +using RimBank.SharedKernel; +using static RimBank.Party.PartyReferenceDataDirectory.Tests.BankRelationsExamples; + +namespace RimBank.Party.PartyReferenceDataDirectory.Tests; + +// Reading a BankRelations Update (roadmap 1.12, ADR 0035): unsupported paths are refused first, every invalid value is +// named by its BIAN path, null keeps, blank clears, and an empty BankRelationReference clears the dates and the status. +public sealed class BankRelationsChangesTests +{ + private static readonly string[] _none = []; + + [Fact] + public void Every_recorded_value_is_read() + { + var changes = BankRelationsChanges.Create( + new BankRelationsInput( + " relationshipmanager ", + ManagerId.ToString(), + new BankRelationReferenceInput("2024-01-01", "2026-06-30T02:00:00+02:00", "active")), + _none).Value; + + changes.ShouldBe(new BankRelationsChanges( + new(BankRelationType.RelationshipManager), + new(ManagerId), + new(StartDate), + new(EndDate), + new(BankRelationLifecycleStatus.Active))); + } + + [Fact] + public void Nothing_sent_changes_nothing() => + BankRelationsChanges.Create(new BankRelationsInput(null, null, null), _none).Value.ShouldBe(BankRelationsChanges.None); + + [Fact] + public void Blank_values_clear_their_parts() => + BankRelationsChanges.Create(new BankRelationsInput(" ", "", new BankRelationReferenceInput("", null, " ")), _none).Value + .ShouldBe(new BankRelationsChanges(new(null), new(null), new(null), null, new(null))); + + [Fact] + public void An_empty_bank_relation_reference_clears_the_dates_and_the_status() => + BankRelationsChanges.Create(new BankRelationsInput(null, null, new BankRelationReferenceInput(null, null, null)), _none).Value + .ShouldBe(new BankRelationsChanges(StartDate: new(null), EndDate: new(null), LifecycleStatus: new(null))); + + [Fact] + public void Every_invalid_value_is_named_by_its_path() + { + var error = BankRelationsChanges.Create( + new BankRelationsInput( + "Customer", + "BRANCH-1", + new BankRelationReferenceInput("01/01/2024", "tomorrow", "Closed")), + _none).Error; + + error.Code.ShouldBe("party.bank-relations-invalid"); + error.FieldErrors.Keys.ShouldBe( + [ + "BankRelationType", + "BusinessUnitEmployeeReference.PartyReference", + "BankRelationReference.RelationshipStartDate.DateTimeContent", + "BankRelationReference.RelationshipEndDate.DateTimeContent", + "BankRelationReference.RelationshipLifecycleStatus.StatusDescription", + ], + ignoreOrder: true); + } + + [Fact] + public void A_party_reference_that_is_not_a_version_7_id_is_invalid() => + BankRelationsChanges.Create(new BankRelationsInput(null, Guid.NewGuid().ToString(), null), _none).Error.FieldErrors.Keys + .ShouldBe(["BusinessUnitEmployeeReference.PartyReference"]); + + [Fact] + public void Unsupported_paths_are_refused_before_the_values_are_read() + { + var error = BankRelationsChanges.Create( + new BankRelationsInput("Customer", null, null), + ["BankRelationReference.RelationshipIdentification", "BusinessUnitEmployeeReference.InvolvementReference"]).Error; + + error.Code.ShouldBe("party.bank-relations-field-not-supported"); + error.Kind.ShouldBe(ErrorKind.Validation); + error.FieldErrors.Keys.ShouldBe( + ["BankRelationReference.RelationshipIdentification", "BusinessUnitEmployeeReference.InvolvementReference"], + ignoreOrder: true); + } + + [Fact] + public void The_changes_to_some_details_give_those_details_whatever_the_current_ones() => + new BankRelationsDetails(BankRelationType.ServicingBranch, BranchId, null, EndDate, BankRelationLifecycleStatus.Ended) + .Apply(BankRelationsChanges.To(ManagedRelation)) + .ShouldBe(ManagedRelation); + + [Fact] + public void Only_a_change_of_the_reference_or_the_type_asks_for_a_check() + { + ManagedRelation.ReferenceToCheck(BankRelationsChanges.None).ShouldBeNull(); + ManagedRelation.ReferenceToCheck(new BankRelationsChanges(LifecycleStatus: new(BankRelationLifecycleStatus.Ended))).ShouldBeNull(); + ManagedRelation.ReferenceToCheck(new BankRelationsChanges(Type: new(BankRelationType.ServicingBranch))).ShouldBe(ManagerId); + ManagedRelation.ReferenceToCheck(new BankRelationsChanges(BusinessUnitEmployee: new(BranchId))).ShouldBe(BranchId); + ManagedRelation.ReferenceToCheck(new BankRelationsChanges(BusinessUnitEmployee: new(null))).ShouldBeNull(); + } +} diff --git a/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsDecisionTests.cs b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsDecisionTests.cs new file mode 100644 index 0000000..f4bed46 --- /dev/null +++ b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsDecisionTests.cs @@ -0,0 +1,151 @@ +using RimBank.SharedKernel; +using static RimBank.Party.PartyReferenceDataDirectory.Tests.BankRelationsExamples; +using static RimBank.Party.PartyReferenceDataDirectory.Tests.EntryExamples; +using EntrySpecification = RimBank.SharedKernel.Testing.DeciderSpecification< + RimBank.Party.PartyReferenceDataDirectory.PartyReferenceDataDirectoryEntry, + RimBank.Party.PartyReferenceDataDirectory.PartyReferenceDataDirectoryEntryCommand, + RimBank.Party.PartyReferenceDataDirectory.PartyReferenceDataDirectoryEntryEvent>; + +namespace RimBank.Party.PartyReferenceDataDirectory.Tests; + +// The BankRelations Update decision (roadmap 1.12, ADR 0035): checked on the resulting BankRelations. An employee or unit +// needs a type, the relationship does not end before it starts, and the employee or unit to check (set, or kept under a +// new type) is another registered entry of the party type the relation type needs, as the handler loaded it. +public sealed class BankRelationsDecisionTests +{ + [Theory] + [InlineData(PartyType.Person)] + [InlineData(PartyType.Organisation)] + public void Any_party_records_its_relationship_manager(PartyType partyType) => + EntrySpecification.Given(Registered(partyType)) + .When(UpdateRelations(BankRelationsChanges.To(ManagedRelation), PartyType.Person)) + .Then(RelationsUpdated(ManagedRelation)); + + [Fact] + public void A_branch_services_the_party() => + EntrySpecification.Given(Registered()) + .When(UpdateRelations( + new BankRelationsChanges(new(BankRelationType.ServicingBranch), new(BranchId)), + PartyType.Organisation)) + .Then(RelationsUpdated(BankRelationsDetails.Empty with { Type = BankRelationType.ServicingBranch, BusinessUnitEmployee = BranchId })); + + [Fact] + public void A_partial_update_keeps_what_it_does_not_send_without_checking_the_reference_again() => + EntrySpecification.Given(Registered(), RelationsUpdated(ManagedRelation)) + .When(UpdateRelations(new BankRelationsChanges(EndDate: new(EndDate), LifecycleStatus: new(BankRelationLifecycleStatus.Ended)))) + .Then(RelationsUpdated(ManagedRelation with { EndDate = EndDate, LifecycleStatus = BankRelationLifecycleStatus.Ended })); + + [Fact] + public void An_update_with_no_change_is_still_recorded() => + EntrySpecification.Given(Registered(), RelationsUpdated(ManagedRelation)) + .When(UpdateRelations(BankRelationsChanges.None)) + .Then(RelationsUpdated(ManagedRelation)); + + [Fact] + public void Clearing_every_part_leaves_empty_bank_relations() => + EntrySpecification.Given(Registered(), RelationsUpdated(ManagedRelation)) + .When(UpdateRelations(BankRelationsChanges.To(BankRelationsDetails.Empty))) + .Then(RelationsUpdated(BankRelationsDetails.Empty)); + + [Fact] + public void Dates_and_status_need_no_type() => + EntrySpecification.Given(Registered()) + .When(UpdateRelations(new BankRelationsChanges(StartDate: new(StartDate), LifecycleStatus: new(BankRelationLifecycleStatus.Suspended)))) + .Then(RelationsUpdated(BankRelationsDetails.Empty with { StartDate = StartDate, LifecycleStatus = BankRelationLifecycleStatus.Suspended })); + + [Fact] + public void An_unknown_entry_is_not_found() => + EntrySpecification.Given() + .When(UpdateRelations(BankRelationsChanges.None)) + .ThenFails(ErrorKind.NotFound, "party.party-not-found"); + + [Fact] + public void A_foreign_bank_relations_id_is_not_found() => + EntrySpecification.Given(Registered()) + .When(new UpdateBankRelationsDetails(BankRelationsId.From(Guid.CreateVersion7(OpenDate.AddDays(1))), BankRelationsChanges.None)) + .ThenFails(ErrorKind.NotFound, "party.behavior-qualifier-not-found"); + + [Fact] + public void A_reference_without_a_type_is_invalid() => + EntrySpecification.Given(Registered()) + .When(UpdateRelations(new BankRelationsChanges(BusinessUnitEmployee: new(ManagerId)), PartyType.Person)) + .ThenFails(ErrorKind.Validation, "party.bank-relations-invalid") + .FieldErrors.Keys.ShouldBe(["BankRelationType"]); + + [Fact] + public void Clearing_the_type_while_the_reference_is_kept_is_invalid() => + EntrySpecification.Given(Registered(), RelationsUpdated(ManagedRelation)) + .When(UpdateRelations(new BankRelationsChanges(Type: new(null)))) + .ThenFails(ErrorKind.Validation, "party.bank-relations-invalid"); + + [Fact] + public void A_relationship_that_ends_before_it_starts_is_invalid_even_when_the_start_is_kept() => + EntrySpecification.Given(Registered(), RelationsUpdated(ManagedRelation)) + .When(UpdateRelations(new BankRelationsChanges(EndDate: new(StartDate.AddDays(-1))))) + .ThenFails(ErrorKind.Validation, "party.bank-relations-invalid") + .FieldErrors.Keys.ShouldBe(["BankRelationReference.RelationshipEndDate.DateTimeContent"]); + + [Fact] + public void A_relationship_may_start_and_end_on_the_same_day() => + EntrySpecification.Given(Registered()) + .When(UpdateRelations(new BankRelationsChanges(StartDate: new(StartDate), EndDate: new(StartDate)))) + .Then(RelationsUpdated(BankRelationsDetails.Empty with { StartDate = StartDate, EndDate = StartDate })); + + [Fact] + public void The_entry_itself_as_its_employee_is_refused_naming_the_path() => + EntrySpecification.Given(Registered()) + .When(UpdateRelations(new BankRelationsChanges(new(BankRelationType.RelationshipManager), new(EntryId)))) + .ThenFails(ErrorKind.BusinessRule, "party.self-reference") + .Message.ShouldStartWith("BusinessUnitEmployeeReference.PartyReference"); + + [Fact] + public void An_employee_that_is_not_registered_is_refused_naming_the_path() => + EntrySpecification.Given(Registered()) + .When(UpdateRelations(BankRelationsChanges.To(ManagedRelation), referencedPartyType: null)) + .ThenFails(ErrorKind.BusinessRule, "party.referenced-party-not-registered") + .Message.ShouldStartWith("BusinessUnitEmployeeReference.PartyReference"); + + [Fact] + public void An_organisation_as_relationship_manager_is_a_type_mismatch() => + EntrySpecification.Given(Registered()) + .When(UpdateRelations(BankRelationsChanges.To(ManagedRelation), PartyType.Organisation)) + .ThenFails(ErrorKind.BusinessRule, "party.referenced-party-type-mismatch") + .Message.ShouldBe("BusinessUnitEmployeeReference.PartyReference must name a party of type Person."); + + [Fact] + public void A_person_as_servicing_branch_is_a_type_mismatch() => + EntrySpecification.Given(Registered()) + .When(UpdateRelations(new BankRelationsChanges(new(BankRelationType.ServicingBranch), new(ManagerId)), PartyType.Person)) + .ThenFails(ErrorKind.BusinessRule, "party.referenced-party-type-mismatch") + .Message.ShouldBe("BusinessUnitEmployeeReference.PartyReference must name a party of type Organisation."); + + [Fact] + public void A_new_type_is_checked_against_the_kept_reference() => + EntrySpecification.Given(Registered(), RelationsUpdated(ManagedRelation)) + .When(UpdateRelations(new BankRelationsChanges(Type: new(BankRelationType.ServicingBusinessUnit)), PartyType.Person)) + .ThenFails(ErrorKind.BusinessRule, "party.referenced-party-type-mismatch"); + + [Fact] + public void A_new_type_that_fits_the_kept_reference_is_accepted() => + EntrySpecification.Given(Registered(), RelationsUpdated(ManagedRelation)) + .When(UpdateRelations(new BankRelationsChanges(Type: new(BankRelationType.AccountOfficer)), PartyType.Person)) + .Then(RelationsUpdated(ManagedRelation with { Type = BankRelationType.AccountOfficer })); + + [Fact] + public void The_value_rules_are_checked_before_the_reference() => + EntrySpecification.Given(Registered()) + .When(UpdateRelations( + new BankRelationsChanges(BusinessUnitEmployee: new(EntryId), StartDate: new(EndDate), EndDate: new(StartDate)))) + .ThenFails(ErrorKind.Validation, "party.bank-relations-invalid"); + + [Fact] + public void An_update_of_the_bank_relations_changes_no_other_section() + { + var state = new PartyReferenceDataDirectoryEntryEvent[] { Registered(), ReferenceUpdated(), RelationsUpdated(ManagedRelation) } + .Aggregate(PartyReferenceDataDirectoryEntry.Initial, PartyReferenceDataDirectoryEntry.Evolve); + + state.CurrentReference.ShouldBe(ReferenceDetails); + state.CurrentBankRelations.ShouldBe(ManagedRelation); + PartyReferenceDataDirectoryEntry.Initial.CurrentBankRelations.ShouldBe(BankRelationsDetails.Empty); + } +} diff --git a/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsExamples.cs b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsExamples.cs new file mode 100644 index 0000000..420184d --- /dev/null +++ b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsExamples.cs @@ -0,0 +1,31 @@ +using static RimBank.Party.PartyReferenceDataDirectory.Tests.EntryExamples; + +namespace RimBank.Party.PartyReferenceDataDirectory.Tests; + +// Fixed values for the BankRelations tests (roadmap 1.12): a bank employee (a person) and a branch (an organisation), +// registered at the same time as the entry, and the relationship the entry records with them. +internal static class BankRelationsExamples +{ + public static readonly PartyReferenceDataDirectoryEntryId ManagerId = + PartyReferenceDataDirectoryEntryId.From(Guid.CreateVersion7(OpenDate.AddMinutes(3))); + + public static readonly PartyReferenceDataDirectoryEntryId BranchId = + PartyReferenceDataDirectoryEntryId.From(Guid.CreateVersion7(OpenDate.AddMinutes(4))); + + public static readonly DateTimeOffset StartDate = new(2024, 1, 1, 0, 0, 0, TimeSpan.Zero); + + public static readonly DateTimeOffset EndDate = new(2026, 6, 30, 0, 0, 0, TimeSpan.Zero); + + public static readonly BankRelationsDetails ManagedRelation = new( + BankRelationType.RelationshipManager, + ManagerId, + StartDate, + null, + BankRelationLifecycleStatus.Active); + + public static UpdateBankRelationsDetails UpdateRelations(BankRelationsChanges changes, PartyType? referencedPartyType = null) => + new(BankRelations, changes, referencedPartyType); + + public static BankRelationsUpdated RelationsUpdated(BankRelationsDetails details) => + new(EntryId, BankRelations, details); +} diff --git a/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsPartialUpdateProperties.cs b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsPartialUpdateProperties.cs new file mode 100644 index 0000000..5530ad2 --- /dev/null +++ b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsPartialUpdateProperties.cs @@ -0,0 +1,70 @@ +using FsCheck; +using FsCheck.Fluent; +using FsCheck.Xunit; +using static RimBank.Party.PartyReferenceDataDirectory.Tests.BankRelationsExamples; + +namespace RimBank.Party.PartyReferenceDataDirectory.Tests; + +// The partial-update law of the BankRelations (roadmap 1.12): an omitted change keeps the current value, a given one sets +// or clears it, and applying the same changes twice is the same as once. +public sealed class BankRelationsPartialUpdateProperties +{ + private static readonly Gen _details = + from type in Gen.Elements([null, .. Enum.GetValues().Select(type => (BankRelationType?)type)]) + from reference in Gen.Elements(null, ManagerId, BranchId) + from start in Gen.Elements(null, StartDate, EndDate) + from end in Gen.Elements(null, StartDate, EndDate) + from status in Gen.Elements([null, .. Enum.GetValues().Select(status => (BankRelationLifecycleStatus?)status)]) + select new BankRelationsDetails(type, reference, start, end, status); + + // Each part is omitted (false) or sent with the target's value (which may clear it). + private static readonly Gen _changes = + from target in _details + from sent in Gen.ArrayOf(Gen.Elements(false, true), 5) + let full = BankRelationsChanges.To(target) + select new BankRelationsChanges( + sent[0] ? full.Type : null, + sent[1] ? full.BusinessUnitEmployee : null, + sent[2] ? full.StartDate : null, + sent[3] ? full.EndDate : null, + sent[4] ? full.LifecycleStatus : null); + + private static readonly (Func Value, Func Change)[] _parts = + [ + (d => d.Type, c => (c.Type is not null, c.Type?.Value)), + (d => d.BusinessUnitEmployee, c => (c.BusinessUnitEmployee is not null, c.BusinessUnitEmployee?.Value)), + (d => d.StartDate, c => (c.StartDate is not null, c.StartDate?.Value)), + (d => d.EndDate, c => (c.EndDate is not null, c.EndDate?.Value)), + (d => d.LifecycleStatus, c => (c.LifecycleStatus is not null, c.LifecycleStatus?.Value)), + ]; + + [Property] + public Property No_change_keeps_any_bank_relations() => + Prop.ForAll(_details.ToArbitrary(), details => details.Apply(BankRelationsChanges.None) == details); + + [Property] + public Property The_changes_to_some_details_give_those_details_whatever_the_current_ones() => + Prop.ForAll(_details.ToArbitrary(), _details.ToArbitrary(), (current, target) => current.Apply(BankRelationsChanges.To(target)) == target); + + [Property] + public Property An_omitted_part_keeps_its_value_and_a_sent_one_takes_the_change() => + Prop.ForAll( + _details.ToArbitrary(), + _changes.ToArbitrary(), + (current, changes) => + { + var updated = current.Apply(changes); + return _parts.All(part => part.Change(changes) switch + { + (false, _) => Equals(part.Value(updated), part.Value(current)), + (true, var value) => Equals(part.Value(updated), value), + }); + }); + + [Property] + public Property Applying_the_same_changes_twice_is_applying_them_once() => + Prop.ForAll( + _details.ToArbitrary(), + _changes.ToArbitrary(), + (current, changes) => current.Apply(changes).Apply(changes) == current.Apply(changes)); +} diff --git a/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsViewProjectionTests.cs b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsViewProjectionTests.cs new file mode 100644 index 0000000..eef0cff --- /dev/null +++ b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/BankRelations/BankRelationsViewProjectionTests.cs @@ -0,0 +1,51 @@ +using System.Text.Json; +using RimBank.SharedKernel; +using static RimBank.Party.PartyReferenceDataDirectory.Tests.BankRelationsExamples; +using static RimBank.Party.PartyReferenceDataDirectory.Tests.EntryExamples; +using EntryViewSpecification = RimBank.SharedKernel.Testing.ProjectionSpecification< + RimBank.Party.PartyReferenceDataDirectory.PartyReferenceDataDirectoryEntryViewProjection, + RimBank.Party.PartyReferenceDataDirectory.PartyReferenceDataDirectoryEntryView, + RimBank.Party.PartyReferenceDataDirectory.PartyReferenceDataDirectoryEntryEvent>; + +namespace RimBank.Party.PartyReferenceDataDirectory.Tests; + +// The BankRelations section of the entry's view (roadmap 1.12): Given events → Then view, so it can always be rebuilt +// from the entry's stream, including one written before 1.12. +public sealed class BankRelationsViewProjectionTests +{ + private static readonly JsonSerializerOptions _json = new() { Converters = { new TypedIdJsonConverterFactory() } }; + + private static PartyReferenceDataDirectoryEntryView RegisteredView(long version) => + new(EntryId.Value, version, PartyType.Person, OpenDate, Demographics, Reference, BankRelations); + + [Fact] + public void Updated_bank_relations_show_in_the_view_at_the_next_version() => + EntryViewSpecification.Given(Registered(), RelationsUpdated(ManagedRelation)) + .Then(RegisteredView(2) with { BankRelations = ManagedRelation }); + + [Fact] + public void The_last_update_wins_and_other_sections_are_kept() => + EntryViewSpecification.Given( + Registered(), + RelationsUpdated(ManagedRelation), + ReferenceUpdated(), + RelationsUpdated(BankRelationsDetails.Empty)) + .Then(RegisteredView(4) with { Reference = ReferenceDetails, BankRelations = BankRelationsDetails.Empty }); + + [Fact] + public void A_stream_written_before_1_12_has_no_bank_relations_section() => + EntryViewSpecification.Given(Registered(), DetailsUpdated(), ReferenceUpdated()) + .Then(RegisteredView(3) with { Demographics = new DemographicsRecord(Details, DemographicsVerificationStatus.Unverified, null), Reference = ReferenceDetails }); + + [Fact] + public void The_view_s_bank_relations_survive_a_json_round_trip_and_a_view_stored_before_1_12_still_loads() + { + var view = RegisteredView(2) with { BankRelations = ManagedRelation }; + var json = JsonSerializer.Serialize(view, _json); + + JsonSerializer.Deserialize(json, _json).ShouldBe(view); + json.ShouldNotContain("CurrentBankRelations"); + JsonSerializer.Deserialize(JsonSerializer.Serialize(RegisteredView(1), _json), _json) + .ShouldNotBeNull().CurrentBankRelations.ShouldBe(BankRelationsDetails.Empty); + } +} diff --git a/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/BankRelations/RetrieveBankRelationsHandlerTests.cs b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/BankRelations/RetrieveBankRelationsHandlerTests.cs new file mode 100644 index 0000000..91ad501 --- /dev/null +++ b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/BankRelations/RetrieveBankRelationsHandlerTests.cs @@ -0,0 +1,49 @@ +using RimBank.SharedKernel; +using static RimBank.Party.PartyReferenceDataDirectory.Tests.BankRelationsExamples; +using static RimBank.Party.PartyReferenceDataDirectory.Tests.EntryExamples; + +namespace RimBank.Party.PartyReferenceDataDirectory.Tests; + +// The BankRelations Retrieve flow on the query side (BIAN BankRelations/Retrieve, roadmap 1.12): the handler only reads +// the entry's view and checks that the BankRelations id is the entry's. +public sealed class RetrieveBankRelationsHandlerTests +{ + private readonly InMemoryPartyDirectoryEnquiry _enquiry = new(); + + [Fact] + public async Task The_entry_s_bank_relations_are_retrieved_from_its_view() + { + _enquiry.Seed(EntryId, Registered(), ReferenceUpdated(), RelationsUpdated(ManagedRelation)); + + var view = (await Retrieve(BankRelations)).Value; + + view.Version.ShouldBe(3); + view.CurrentBankRelations.ShouldBe(ManagedRelation); + } + + [Fact] + public async Task Bank_relations_never_updated_are_empty() + { + _enquiry.Seed(EntryId, Registered()); + + var view = (await Retrieve(BankRelations)).Value; + + view.CurrentBankRelations.ShouldBe(BankRelationsDetails.Empty); + } + + [Fact] + public async Task An_unknown_entry_is_party_not_found() => + (await Retrieve(BankRelations)).Error.ShouldBe(PartyReferenceDataDirectoryEntryErrors.PartyNotFound); + + [Fact] + public async Task A_foreign_bank_relations_id_is_behavior_qualifier_not_found() + { + _enquiry.Seed(EntryId, Registered()); + + (await Retrieve(BankRelationsId.From(Guid.CreateVersion7(OpenDate.AddDays(1))))).Error + .ShouldBe(PartyReferenceDataDirectoryEntryErrors.BehaviorQualifierNotFound); + } + + private Task> Retrieve(BankRelationsId bankRelationsId) => + RetrieveBankRelationsHandler.HandleAsync(new RetrieveBankRelations(EntryId, bankRelationsId), _enquiry, CancellationToken.None); +} diff --git a/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/BankRelations/UpdateBankRelationsHandlerTests.cs b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/BankRelations/UpdateBankRelationsHandlerTests.cs new file mode 100644 index 0000000..7024466 --- /dev/null +++ b/tests/RimBank.Core.Tests/Party/PartyReferenceDataDirectory/BankRelations/UpdateBankRelationsHandlerTests.cs @@ -0,0 +1,162 @@ +using System.Text.Json; +using RimBank.SharedKernel; +using static RimBank.Party.PartyReferenceDataDirectory.Tests.BankRelationsExamples; +using static RimBank.Party.PartyReferenceDataDirectory.Tests.EntryExamples; + +namespace RimBank.Party.PartyReferenceDataDirectory.Tests; + +// The BankRelations Update flow on the command side (roadmap 1.12, ADR 0035): the handler checks the entry, the +// BankRelations id and the expected version, in that order, loads the employee or unit to check from the write side, +// decides, appends with that version and acknowledges from the decision. +public sealed class UpdateBankRelationsHandlerTests +{ + private static readonly JsonSerializerOptions _json = new() { Converters = { new TypedIdJsonConverterFactory() } }; + + private static readonly BankRelationsId _otherBankRelations = BankRelationsId.From(Guid.CreateVersion7(OpenDate.AddMinutes(5))); + + private readonly InMemoryPartyDirectory _directory = new(); + + [Fact] + public async Task Updating_the_bank_relations_loads_the_employee_appends_and_acknowledges_the_next_version() + { + _directory.Seed(EntryId, Registered()); + _directory.Seed(ManagerId, RegisteredEntry(ManagerId, PartyType.Person)); + + var acknowledged = (await Update(BankRelations, expectedVersion: 1, BankRelationsChanges.To(ManagedRelation))).Value; + + _directory.StreamOf(EntryId).ShouldBe([Registered(), RelationsUpdated(ManagedRelation)]); + _directory.StreamOf(ManagerId).ShouldBe([RegisteredEntry(ManagerId, PartyType.Person)]); + acknowledged.ShouldBe(new UpdateBankRelationsAcknowledged(EntryId, BankRelations, 2, ManagedRelation)); + } + + [Fact] + public async Task The_acknowledgement_is_the_state_the_decision_produced() + { + _directory.Seed(EntryId, Registered(), ReferenceUpdated(), RelationsUpdated(ManagedRelation)); + + var acknowledged = (await Update(BankRelations, expectedVersion: 3, BankRelationsChanges.None)).Value; + + var state = _directory.StreamOf(EntryId).Aggregate(PartyReferenceDataDirectoryEntry.Initial, PartyReferenceDataDirectoryEntry.Evolve); + acknowledged.Version.ShouldBe(4); + acknowledged.BankRelations.ShouldBe(state.CurrentBankRelations); + acknowledged.BankRelations.ShouldBe(ManagedRelation); + } + + [Fact] + public async Task A_kept_reference_is_not_checked_again() + { + // The manager's entry is not in this directory any more: only a load would find it missing. + _directory.Seed(EntryId, Registered(), RelationsUpdated(ManagedRelation)); + + var result = await Update(BankRelations, expectedVersion: 2, new BankRelationsChanges(LifecycleStatus: new(BankRelationLifecycleStatus.Suspended))); + + result.IsSuccess.ShouldBeTrue(); + } + + [Fact] + public async Task A_new_type_is_checked_against_the_kept_reference_as_loaded() + { + _directory.Seed(EntryId, Registered(), RelationsUpdated(ManagedRelation)); + _directory.Seed(ManagerId, RegisteredEntry(ManagerId, PartyType.Person)); + + var result = await Update(BankRelations, expectedVersion: 2, new BankRelationsChanges(Type: new(BankRelationType.ServicingBranch))); + + result.Error.Code.ShouldBe("party.referenced-party-type-mismatch"); + _directory.StreamOf(EntryId).Count.ShouldBe(2); + } + + [Fact] + public async Task The_party_type_loaded_is_the_current_one() + { + _directory.Seed(EntryId, Registered()); + _directory.Seed(BranchId, RegisteredEntry(BranchId, PartyType.Person), new PartyReferenceDataDirectoryEntryUpdated(BranchId, PartyType.Organisation, RefreshDate)); + + var result = await Update(BankRelations, expectedVersion: 1, new BankRelationsChanges(new(BankRelationType.ServicingBranch), new(BranchId))); + + result.IsSuccess.ShouldBeTrue(); + } + + [Fact] + public async Task An_employee_that_is_not_registered_is_refused_and_nothing_is_appended() + { + _directory.Seed(EntryId, Registered()); + + var result = await Update(BankRelations, expectedVersion: 1, BankRelationsChanges.To(ManagedRelation)); + + result.Error.Code.ShouldBe("party.referenced-party-not-registered"); + _directory.StreamOf(EntryId).ShouldBe([Registered()]); + } + + [Fact] + public async Task An_association_id_given_as_the_employee_is_not_registered_never_a_failure() + { + _directory.Seed(EntryId, Registered()); + var associationId = PartyAssociationId.From(ManagerId.Value); + _directory.Seed(associationId, new PartyAssociationRegistered( + associationId, EntryId, CompanyId, PartyRelationshipType.PartyIsSubsidiaryOfParty, null)); + + var result = await Update(BankRelations, expectedVersion: 1, BankRelationsChanges.To(ManagedRelation)); + + result.Error.Code.ShouldBe("party.referenced-party-not-registered"); + } + + [Fact] + public async Task The_entry_itself_as_its_employee_is_refused() + { + _directory.Seed(EntryId, Registered()); + + var result = await Update(BankRelations, expectedVersion: 1, new BankRelationsChanges(new(BankRelationType.RelationshipManager), new(EntryId))); + + result.Error.Code.ShouldBe("party.self-reference"); + } + + [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(EntryId, Registered()); + + var result = await Update(BankRelations, expectedVersion, BankRelationsChanges.None); + + result.Error.ShouldBe(PartyReferenceDataDirectoryEntryErrors.VersionConflict); + _directory.StreamOf(EntryId).ShouldBe([Registered()]); + } + + [Fact] + public async Task An_unknown_entry_is_not_found_before_the_id_and_the_version_are_checked() + { + var result = await Update(_otherBankRelations, expectedVersion: 7, BankRelationsChanges.None); + + result.Error.ShouldBe(PartyReferenceDataDirectoryEntryErrors.PartyNotFound); + _directory.Entries.ShouldBeEmpty(); + } + + [Fact] + public async Task A_foreign_bank_relations_id_is_not_found_before_the_version_is_checked() + { + _directory.Seed(EntryId, Registered()); + + var result = await Update(_otherBankRelations, expectedVersion: 7, BankRelationsChanges.None); + + result.Error.ShouldBe(PartyReferenceDataDirectoryEntryErrors.BehaviorQualifierNotFound); + } + + [Fact] + public async Task The_command_and_the_acknowledgement_survive_a_json_round_trip() + { + _directory.Seed(EntryId, Registered()); + _directory.Seed(ManagerId, RegisteredEntry(ManagerId, PartyType.Person)); + var command = Command(BankRelations, expectedVersion: 1, BankRelationsChanges.To(ManagedRelation)); + var acknowledged = (await UpdateBankRelationsHandler.HandleAsync(command, _directory, CancellationToken.None)).Value; + + JsonSerializer.Deserialize(JsonSerializer.Serialize(command, _json), _json).ShouldBe(command); + JsonSerializer.Deserialize(JsonSerializer.Serialize(acknowledged, _json), _json).ShouldBe(acknowledged); + } + + private static UpdateBankRelations Command(BankRelationsId bankRelationsId, long expectedVersion, BankRelationsChanges changes) => + new(EntryId, bankRelationsId, expectedVersion, changes, IdempotencyKey.TryCreate("bank-relations-1").Value); + + private Task> Update(BankRelationsId bankRelationsId, long expectedVersion, BankRelationsChanges changes) => + UpdateBankRelationsHandler.HandleAsync(Command(bankRelationsId, expectedVersion, changes), _directory, CancellationToken.None); +}