Restructure into DDD bounded contexts + functional state management

Reorganise from atomic-design-only folders into bounded contexts
(auth / registratie / herregistratie) over a shared kernel, each split into
domain / application / infrastructure / ui layers. Dependencies point inward;
the domain layer is framework-free. Path aliases (@shared/@auth/@registratie/
@herregistratie) make import direction explicit.

State management (Elm-style, native TS, no new deps):
- shared/application/store.ts — createStore(init, update): pure reducer + signal
- shared/application/remote-data.ts — add map/map2/map3/andThen combinators so
  several services fold into one RemoteData; <app-async> gains an [rd] input
- registratie/application/big-profile.store.ts — root singleton combining the
  BIG-register and BRP services via map2 into one state; holds the optimistic
  herregistratie flag shared with the dashboard
- herregistratie: machine gains a WizardMsg union + pure reduce; submit is a
  command that calls infra and dispatches the result, with optimistic update +
  rollback against the shared store
- auth: SessionStore + DigiD adapter + functional route guard; login establishes
  the session, protected routes use canActivate

Rich domain: registration.policy.ts (statusColor/label, herregistratie
eligibility, invariants); BigNummer/Postcode/Uren value objects with smart
constructors. status-badge is now domain-free (colour/label inputs).

Specs for the reducer, RemoteData combinators, and eligibility policy.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-06-26 07:20:13 +02:00
parent 6bd6e854c7
commit 2114514ad7
74 changed files with 841 additions and 347 deletions

View File

@@ -0,0 +1,60 @@
import { Injectable, computed, inject, signal } from '@angular/core';
import { RemoteData, fromResource, map2 } from '@shared/application/remote-data';
import { Aantekening } from '../domain/registration';
import { BigProfile } from '../domain/big-profile';
import { BigRegisterAdapter } from '../infrastructure/big-register.adapter';
import { BrpAdapter } from '../infrastructure/brp.adapter';
type Err = Error | undefined;
/**
* The single source of truth for the logged-in professional's profile, shared
* across pages (providedIn:'root' = one instance). It owns the httpResources
* (created here, in the required injection context) and exposes them as
* RemoteData signals.
*
* The headline trick: `profile` combines TWO independent services — the
* BIG-register and the BRP — into ONE RemoteData via map2. A page renders a
* single state (loading / error / loaded), never juggling three.
*/
@Injectable({ providedIn: 'root' })
export class BigProfileStore {
private big = inject(BigRegisterAdapter);
private brp = inject(BrpAdapter);
private registrationRes = this.big.registrationResource();
private aantekeningenRes = this.big.aantekeningenResource();
private personRes = this.brp.personResource();
/** BIG-register + BRP folded into one state. */
readonly profile = computed<RemoteData<Err, BigProfile>>(() =>
map2(
fromResource(this.registrationRes),
fromResource(this.personRes),
// httpResource types value as T | undefined; in the Success branch it is
// always present, so narrowing here is safe.
(registration, person) => ({ registration: registration!, person: person! }),
),
);
/** Specialisms/notes stay a separate stream (they have their own empty state). */
readonly aantekeningen = computed<RemoteData<Err, Aantekening[]>>(() =>
fromResource(this.aantekeningenRes, (v) => v.length === 0),
);
// --- Optimistic herregistratie state, shared with the dashboard -----------
private pending = signal(false);
/** True while a herregistratie submission is in flight or just submitted. */
readonly pendingHerregistratie = this.pending.asReadonly();
beginHerregistratie() {
this.pending.set(true); // optimistic: show it immediately on the dashboard
}
confirmHerregistratie() {
this.pending.set(false);
this.registrationRes.reload(); // invalidate: re-fetch the now-updated registration
}
rollbackHerregistratie() {
this.pending.set(false); // submission failed — undo the optimistic flag
}
}

View File

@@ -0,0 +1,12 @@
import { Registration } from './registration';
import { Person } from './person';
/**
* The view the dashboard/detail render: a registration (from the BIG-register)
* enriched with person data (from the BRP). It only exists when BOTH sources
* have loaded — see BigProfileStore, which builds it with map2.
*/
export interface BigProfile {
registration: Registration;
person: Person;
}

View File

@@ -0,0 +1,12 @@
/** Person identity as supplied by the BRP (Basisregistratie Personen). */
export interface Adres {
straat: string;
postcode: string;
woonplaats: string;
}
export interface Person {
naam: string;
geboortedatum: string; // ISO date
adres: Adres;
}

View File

@@ -0,0 +1,27 @@
import { describe, it, expect } from 'vitest';
import { Registration } from './registration';
import { isHerregistratieEligible, statusColor } from './registration.policy';
const reg = (status: Registration['status']): Registration => ({
bigNummer: '19012345601', naam: 'Test', beroep: 'Arts',
registratiedatum: '2012-09-01', geboortedatum: '1985-03-14', status,
});
describe('registration.policy', () => {
it('only an active registration within the window is eligible', () => {
const active = reg({ tag: 'Geregistreerd', herregistratieDatum: '2027-01-01' });
expect(isHerregistratieEligible(active, new Date('2026-06-01'))).toBe(true); // within 12 months
expect(isHerregistratieEligible(active, new Date('2020-01-01'))).toBe(false); // too early
});
it('struck-off / suspended registrations are never eligible', () => {
expect(isHerregistratieEligible(reg({ tag: 'Doorgehaald', doorgehaaldOp: '2024-05-01', reden: 'x' }), new Date('2027-01-01'))).toBe(false);
expect(isHerregistratieEligible(reg({ tag: 'Geschorst', geschorstTot: '2026-12-31', reden: 'x' }), new Date('2027-01-01'))).toBe(false);
});
it('statusColor is total over the union', () => {
expect(statusColor('Geregistreerd')).toContain('groen');
expect(statusColor('Doorgehaald')).toContain('rood');
expect(statusColor('Geschorst')).toContain('oranje');
});
});

View File

@@ -0,0 +1,51 @@
import { assertNever } from '@shared/kernel/fp';
import { Registration, RegistrationStatus, StatusTag } from './registration';
/**
* Domain logic for a registration — pure functions, NO Angular. This is where
* "what the business rules say" lives, separate from "how it looks" (UI) and
* "where the data comes from" (infrastructure). Keeping it framework-free means
* it is trivial to read and unit-test.
*/
/** Human-readable label for a status. */
export function statusLabel(tag: StatusTag): string {
return tag; // the tag already reads as Dutch; kept as a function so labels can diverge later
}
/** Brand colour token for a status. assertNever forces a colour for every new
status variant at compile time. */
export function statusColor(tag: StatusTag): string {
switch (tag) {
case 'Geregistreerd':
return 'var(--rhc-color-groen-500)';
case 'Doorgehaald':
return 'var(--rhc-color-rood-500)';
case 'Geschorst':
return 'var(--rhc-color-oranje-500)';
default:
return assertNever(tag);
}
}
/** The herregistratie deadline, if the status has one (only the active state does). */
export function herregistratieDeadline(reg: Registration): Date | null {
return reg.status.tag === 'Geregistreerd' ? new Date(reg.status.herregistratieDatum) : null;
}
/** A registration may apply for herregistratie only while active and within the
window before its deadline. A struck-off or suspended registration may not. */
export function isHerregistratieEligible(reg: Registration, today: Date, windowMonths = 12): boolean {
const deadline = herregistratieDeadline(reg);
if (!deadline) return false;
const windowStart = new Date(deadline);
windowStart.setMonth(windowStart.getMonth() - windowMonths);
return today >= windowStart;
}
/** Invariant check used in tests/demos: a non-active status must not carry a
herregistratie date. The union already enforces this structurally; this is
the runtime statement of the same rule. */
export function isStatusConsistent(status: RegistrationStatus): boolean {
return status.tag === 'Geregistreerd' ? typeof status.herregistratieDatum === 'string' : true;
}

View File

@@ -0,0 +1,29 @@
/**
* Registration status as a discriminated union: each variant owns exactly the
* data that makes sense for it. Only an active (Geregistreerd) registration has
* a herregistratie date; a struck-off (Doorgehaald) one cannot carry one. The
* old flat interface allowed that impossible combination — this makes it
* unrepresentable.
*/
export type RegistrationStatus =
| { tag: 'Geregistreerd'; herregistratieDatum: string } // ISO date
| { tag: 'Geschorst'; geschorstTot: string; reden: string }
| { tag: 'Doorgehaald'; doorgehaaldOp: string; reden: string };
/** Just the discriminant — for atoms that only need the label/color. */
export type StatusTag = RegistrationStatus['tag'];
export interface Registration {
bigNummer: string;
naam: string;
beroep: string; // arts, verpleegkundige, apotheker, ...
registratiedatum: string; // ISO date
geboortedatum: string;
status: RegistrationStatus;
}
export interface Aantekening {
type: string; // specialisme of aantekening
omschrijving: string;
datum: string;
}

View File

@@ -0,0 +1,9 @@
import { Brand, Result, ok, err } from '@shared/kernel/fp';
/** Value object: a BIG registration number — 11 digits. */
export type BigNummer = Brand<string, 'BigNummer'>;
export function parseBigNummer(raw: string): Result<string, BigNummer> {
const t = raw.trim();
return /^\d{11}$/.test(t) ? ok(t as BigNummer) : err('Een BIG-nummer bestaat uit 11 cijfers.');
}

View File

@@ -0,0 +1,17 @@
import { Brand, Result, ok, err } from '@shared/kernel/fp';
/**
* Value object: a Dutch postcode. "Parse, don't validate" — a Postcode is a
* distinct type from a raw string, mintable only via parsePostcode, so holding
* one is proof it is well-formed.
*/
export type Postcode = Brand<string, 'Postcode'>;
export function parsePostcode(raw: string): Result<string, Postcode> {
const t = raw.trim().toUpperCase();
if (!/^[1-9]\d{3}\s?[A-Z]{2}$/.test(t)) {
return err('Voer een geldige postcode in, bijv. 1234 AB.');
}
// Normalise to "1234 AB" — the parser also cleans up.
return ok(t.replace(/^(\d{4})\s?([A-Z]{2})$/, '$1 $2') as Postcode);
}

View File

@@ -0,0 +1,14 @@
import { Brand, Result, ok, err } from '@shared/kernel/fp';
/** Value object: a non-negative whole number of hours. */
export type Uren = Brand<number, 'Uren'>;
export function parseUren(raw: string): Result<string, Uren> {
const t = raw.trim();
const n = Number(t);
// Number('') is 0 — guard the empty string explicitly.
if (t === '' || !Number.isInteger(n) || n < 0) {
return err('Vul een geheel aantal in (0 of meer).');
}
return ok(n as Uren);
}

View File

@@ -0,0 +1,20 @@
import { Injectable } from '@angular/core';
import { httpResource } from '@angular/common/http';
import { Registration, Aantekening } from '../domain/registration';
/**
* Infrastructure adapter for the BIG-register source. Exposes signal-based
* resources (Angular's httpResource); each returns a Resource with
* status()/value()/error()/reload(). Call from an injection context
* (a field initializer in the store).
*/
@Injectable({ providedIn: 'root' })
export class BigRegisterAdapter {
registrationResource() {
return httpResource<Registration>(() => 'mock/registration.json');
}
aantekeningenResource() {
return httpResource<Aantekening[]>(() => 'mock/notes.json', { defaultValue: [] });
}
}

View File

@@ -0,0 +1,11 @@
import { Injectable } from '@angular/core';
import { httpResource } from '@angular/common/http';
import { Person } from '../domain/person';
/** Infrastructure adapter for the BRP (Basisregistratie Personen) source. */
@Injectable({ providedIn: 'root' })
export class BrpAdapter {
personResource() {
return httpResource<Person>(() => 'mock/brp.json');
}
}

View File

@@ -0,0 +1,59 @@
import { Component, output, signal } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { FormFieldComponent } from '@shared/ui/form-field/form-field.component';
import { TextInputComponent } from '@shared/ui/text-input/text-input.component';
import { ButtonComponent } from '@shared/ui/button/button.component';
import { HeadingComponent } from '@shared/ui/heading/heading.component';
import { Postcode, parsePostcode } from '@registratie/domain/value-objects/postcode';
/** A submitted change request carries a *parsed* postcode (branded Postcode),
not a raw string — downstream code can't receive an unvalidated one. */
export interface ChangeRequest {
street: string;
zip: Postcode;
city: string;
}
/** Organism: change-request (adreswijziging) form. Reuses the same form-field
molecule + text-input/button atoms as the login form. Field errors come
straight from the parser's Result — no parallel "is it valid" flag to drift. */
@Component({
selector: 'app-change-request-form',
imports: [FormsModule, FormFieldComponent, TextInputComponent, ButtonComponent, HeadingComponent],
template: `
<app-heading [level]="2">Adreswijziging doorgeven</app-heading>
<form (ngSubmit)="onSubmit()" style="max-width:28rem">
<app-form-field label="Straat en huisnummer" fieldId="street" [error]="streetError()">
<app-text-input inputId="street" [(ngModel)]="street" name="street" [invalid]="!!streetError()" />
</app-form-field>
<app-form-field label="Postcode" fieldId="zip" [error]="zipError()">
<app-text-input inputId="zip" [(ngModel)]="zip" name="zip" placeholder="1234 AB" [invalid]="!!zipError()" />
</app-form-field>
<app-form-field label="Woonplaats" fieldId="city">
<app-text-input inputId="city" [(ngModel)]="city" name="city" />
</app-form-field>
<div style="margin-top:1rem">
<app-button type="submit" variant="primary">Wijziging indienen</app-button>
</div>
</form>
`,
})
export class ChangeRequestFormComponent {
street = '';
zip = '';
city = '';
streetError = signal('');
zipError = signal('');
submitted = output<ChangeRequest>();
onSubmit() {
const street = this.street.trim();
this.streetError.set(street ? '' : 'Vul straat en huisnummer in.');
const postcode = parsePostcode(this.zip);
this.zipError.set(postcode.ok ? '' : postcode.error);
if (!street || !postcode.ok) return;
this.submitted.emit({ street, zip: postcode.value, city: this.city.trim() });
}
}

View File

@@ -0,0 +1,72 @@
import { Component, inject } from '@angular/core';
import { PageShellComponent } from '@shared/layout/page-shell/page-shell.component';
import { HeadingComponent } from '@shared/ui/heading/heading.component';
import { LinkComponent } from '@shared/ui/link/link.component';
import { AlertComponent } from '@shared/ui/alert/alert.component';
import { SkeletonComponent } from '@shared/ui/skeleton/skeleton.component';
import { DataRowComponent } from '@shared/ui/data-row/data-row.component';
import { ASYNC } from '@shared/ui/async/async.component';
import { RegistrationSummaryComponent } from '@registratie/ui/registration-summary/registration-summary.component';
import { RegistrationTableComponent } from '@registratie/ui/registration-table/registration-table.component';
import { BigProfileStore } from '@registratie/application/big-profile.store';
@Component({
selector: 'app-dashboard-page',
imports: [
PageShellComponent, HeadingComponent, LinkComponent, AlertComponent, SkeletonComponent,
DataRowComponent, ...ASYNC, RegistrationSummaryComponent, RegistrationTableComponent,
],
template: `
<app-page-shell heading="Mijn BIG-registratie">
@if (store.pendingHerregistratie()) {
<app-alert type="info">Uw herregistratie-aanvraag is in behandeling.</app-alert>
}
<!-- ONE state for two combined services (BIG-register + BRP). -->
<app-async [data]="store.profile()">
<ng-template appAsyncLoaded let-p>
<app-registration-summary [reg]="$any(p).registration" />
<div class="rhc-card rhc-card--default" style="margin-top:1rem">
<app-heading [level]="2">Persoonsgegevens (BRP)</app-heading>
<dl class="rhc-data-summary rhc-data-summary--row">
<app-data-row key="Straat" [value]="$any(p).person.adres.straat" />
<app-data-row key="Postcode" [value]="$any(p).person.adres.postcode" />
<app-data-row key="Woonplaats" [value]="$any(p).person.adres.woonplaats" />
</dl>
</div>
</ng-template>
<ng-template appAsyncLoading>
<app-skeleton height="2.5rem" [count]="6" />
</ng-template>
</app-async>
<div style="margin-top:2rem">
<app-heading [level]="2">Specialismen en aantekeningen</app-heading>
<app-async [data]="store.aantekeningen()">
<ng-template appAsyncLoaded let-r>
<app-registration-table [rows]="$any(r)" />
</ng-template>
<ng-template appAsyncLoading>
<app-skeleton height="2.5rem" [count]="3" />
</ng-template>
<ng-template appAsyncEmpty>
<p class="rhc-paragraph">U heeft nog geen specialismen of aantekeningen.</p>
</ng-template>
</app-async>
</div>
<p style="margin-top:2rem">
<app-link to="/registratie">Gegevens bekijken of een wijziging doorgeven →</app-link>
</p>
<p>
<app-link to="/herregistratie">Herregistratie aanvragen →</app-link>
</p>
<p>
<app-link to="/concepts">Functionele patronen (impossible states) →</app-link>
</p>
</app-page-shell>
`,
})
export class DashboardPage {
protected store = inject(BigProfileStore);
}

View File

@@ -0,0 +1,40 @@
import { Component, inject, signal } from '@angular/core';
import { PageShellComponent } from '@shared/layout/page-shell/page-shell.component';
import { AlertComponent } from '@shared/ui/alert/alert.component';
import { SkeletonComponent } from '@shared/ui/skeleton/skeleton.component';
import { ASYNC } from '@shared/ui/async/async.component';
import { RegistrationSummaryComponent } from '@registratie/ui/registration-summary/registration-summary.component';
import { ChangeRequestFormComponent } from '@registratie/ui/change-request-form/change-request-form.component';
import { BigProfileStore } from '@registratie/application/big-profile.store';
@Component({
selector: 'app-registration-detail-page',
imports: [
PageShellComponent, AlertComponent, SkeletonComponent, ...ASYNC,
RegistrationSummaryComponent, ChangeRequestFormComponent,
],
template: `
<app-page-shell heading="Mijn gegevens" backLink="/dashboard">
<app-async [data]="store.profile()">
<ng-template appAsyncLoaded let-p>
<app-registration-summary [reg]="$any(p).registration" />
</ng-template>
<ng-template appAsyncLoading>
<app-skeleton height="2.5rem" [count]="6" />
</ng-template>
</app-async>
<div style="margin-top:2rem">
@if (submitted()) {
<app-alert type="ok">Uw adreswijziging is ontvangen. U ontvangt binnen 5 werkdagen bericht.</app-alert>
} @else {
<app-change-request-form (submitted)="submitted.set(true)" />
}
</div>
</app-page-shell>
`,
})
export class RegistrationDetailPage {
protected store = inject(BigProfileStore);
submitted = signal(false);
}

View File

@@ -0,0 +1,44 @@
import { Component, input } from '@angular/core';
import { DatePipe } from '@angular/common';
import { Registration } from '@registratie/domain/registration';
import { statusColor, statusLabel } from '@registratie/domain/registration.policy';
import { DataRowComponent } from '@shared/ui/data-row/data-row.component';
import { StatusBadgeComponent } from '@shared/ui/status-badge/status-badge.component';
/** Organism: registration summary card. Composes data-row molecules + status-badge atom. */
@Component({
selector: 'app-registration-summary',
imports: [DatePipe, DataRowComponent, StatusBadgeComponent],
template: `
<div class="rhc-card rhc-card--default">
<dl class="rhc-data-summary rhc-data-summary--row">
<app-data-row key="BIG-nummer" [value]="reg().bigNummer" />
<app-data-row key="Naam" [value]="reg().naam" />
<app-data-row key="Beroep" [value]="reg().beroep" />
<app-data-row key="Status">
<app-status-badge [label]="label()" [color]="color()" />
</app-data-row>
<app-data-row key="Registratiedatum" [value]="reg().registratiedatum | date:'longDate'" />
<!-- Each status variant renders only the row its own data supports. -->
@switch (reg().status.tag) {
@case ('Geregistreerd') {
<app-data-row key="Uiterste herregistratie" [value]="$any(reg().status).herregistratieDatum | date:'longDate'" />
}
@case ('Geschorst') {
<app-data-row key="Geschorst tot" [value]="$any(reg().status).geschorstTot | date:'longDate'" />
<app-data-row key="Reden" [value]="$any(reg().status).reden" />
}
@case ('Doorgehaald') {
<app-data-row key="Doorgehaald op" [value]="$any(reg().status).doorgehaaldOp | date:'longDate'" />
<app-data-row key="Reden" [value]="$any(reg().status).reden" />
}
}
</dl>
</div>
`,
})
export class RegistrationSummaryComponent {
reg = input.required<Registration>();
protected label = () => statusLabel(this.reg().status.tag);
protected color = () => statusColor(this.reg().status.tag);
}

View File

@@ -0,0 +1,30 @@
import type { Meta, StoryObj } from '@storybook/angular';
import { RegistrationSummaryComponent } from './registration-summary.component';
import { Registration } from '@registratie/domain/registration';
const base = {
bigNummer: '19012345601',
naam: 'Dr. A. (Anna) de Vries',
beroep: 'Arts',
registratiedatum: '2012-09-01',
geboortedatum: '1985-03-14',
} satisfies Omit<Registration, 'status'>;
const meta: Meta<RegistrationSummaryComponent> = {
title: 'Organisms/Registration Summary',
component: RegistrationSummaryComponent,
};
export default meta;
type Story = StoryObj<RegistrationSummaryComponent>;
// Each story feeds a different union variant; the card renders only the rows
// that variant's data supports (note Doorgehaald has no herregistratie date).
export const Geregistreerd: Story = {
args: { reg: { ...base, status: { tag: 'Geregistreerd', herregistratieDatum: '2027-09-01' } } },
};
export const Geschorst: Story = {
args: { reg: { ...base, status: { tag: 'Geschorst', geschorstTot: '2026-12-31', reden: 'Lopend tuchtonderzoek' } } },
};
export const Doorgehaald: Story = {
args: { reg: { ...base, status: { tag: 'Doorgehaald', doorgehaaldOp: '2024-05-01', reden: 'Op eigen verzoek' } } },
};

View File

@@ -0,0 +1,34 @@
import { Component, input } from '@angular/core';
import { DatePipe } from '@angular/common';
import { Aantekening } from '@registratie/domain/registration';
/** Organism: table of specialismen/aantekeningen. */
@Component({
selector: 'app-registration-table',
imports: [DatePipe],
template: `
<div class="utrecht-table-container utrecht-table-container--overflow-inline">
<table class="utrecht-table utrecht-table--html-table utrecht-table--alternate-row-color">
<thead>
<tr>
<th class="utrecht-table__header-cell">Type</th>
<th class="utrecht-table__header-cell">Omschrijving</th>
<th class="utrecht-table__header-cell">Datum</th>
</tr>
</thead>
<tbody>
@for (row of rows(); track row.omschrijving) {
<tr>
<td class="utrecht-table__cell">{{ row.type }}</td>
<td class="utrecht-table__cell">{{ row.omschrijving }}</td>
<td class="utrecht-table__cell">{{ row.datum | date:'mediumDate' }}</td>
</tr>
}
</tbody>
</table>
</div>
`,
})
export class RegistrationTableComponent {
rows = input.required<Aantekening[]>();
}

View File

@@ -0,0 +1,18 @@
import type { Meta, StoryObj } from '@storybook/angular';
import { RegistrationTableComponent } from './registration-table.component';
const meta: Meta<RegistrationTableComponent> = {
title: 'Organisms/Registration Table',
component: RegistrationTableComponent,
};
export default meta;
type Story = StoryObj<RegistrationTableComponent>;
export const Default: Story = {
args: {
rows: [
{ type: 'Specialisme', omschrijving: 'Huisartsgeneeskunde', datum: '2016-04-12' },
{ type: 'Aantekening', omschrijving: 'Erkend opleider huisartsgeneeskunde', datum: '2019-01-08' },
],
},
};