feat(WP-67): merge behandelportal into this repo as a monorepo
Restructures into apps/ssp + apps/behandelportal (two Angular projects) plus libs/shared + libs/beheer (cross-app libraries), replacing WP-61's separate sibling repo. That split had already produced real drift: a hand-vendored copy of the backend's OpenAPI doc, a shared/ui+layout tree forked and silently diverging (7 files), and beheer + the styles.scss token bridge duplicated byte-for-byte across both repos. - git mv the SSP's src/app/* into apps/ssp/; fold shared/, beheer/, environments/, the Storybook docs/*.mdx, and styles.scss into libs/shared + libs/beheer (all confirmed identical between the two repos before merging). auth stays deliberately duplicated per ADR-0002 (actor-specific, expected to diverge) - amended there. - One generated API client (libs/shared), no more vendored swagger.json. - .dependency-cruiser split into a base factory + one config per app, and Storybook into .storybook-ssp/.storybook-behandelportal - both forced by the @auth/* alias resolving to different directories per app. - SiteHeaderComponent/ShellComponent gained HEADER_NAV_ITEMS/ HEADER_ADMIN_LINKS/DEBUG_PANEL injection tokens so each app supplies its own nav/admin-links/dev-panel instead of one being hardcoded. - CLAUDE.md, ARCHITECTURE.md, dependencies.md, and ADR-0002 updated; WP-67 backlog entry documents the full decision trail. npm run ci green (lint, dep:check x2, 360 tests across ssp/ behandelportal/shared/beheer, both localized builds, backend tests, snippet + api-client drift); both dev servers, both Storybook instances, and docker compose verified working. The old sibling repo (/home/eho/repos/behandelportal) is left untouched, not deleted. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,81 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { submittedRow, detailRows, purposeLabel, statusLabel, TYPE_LABELS } from './aanvraag-view';
|
||||
import { Aanvraag } from './aanvraag';
|
||||
|
||||
const base = {
|
||||
id: '1',
|
||||
type: 'herregistratie' as const,
|
||||
documentIds: [],
|
||||
createdAt: '',
|
||||
updatedAt: '',
|
||||
submittedAt: '2024-05-12',
|
||||
};
|
||||
|
||||
describe('submittedRow', () => {
|
||||
it('heading is the type, subtitle is the purpose', () => {
|
||||
const row = submittedRow({
|
||||
...base,
|
||||
status: { tag: 'InBehandeling', referentie: 'R1', manual: false },
|
||||
} as Aanvraag);
|
||||
expect(row.heading).toBe(TYPE_LABELS.herregistratie);
|
||||
expect(row.subtitle).toBe(purposeLabel('herregistratie'));
|
||||
});
|
||||
|
||||
it('status line carries the status label, reference and submit date', () => {
|
||||
const row = submittedRow({
|
||||
...base,
|
||||
status: { tag: 'InBehandeling', referentie: 'R1', manual: false },
|
||||
} as Aanvraag);
|
||||
expect(row.status).toContain(
|
||||
statusLabel({ tag: 'InBehandeling', referentie: 'R1', manual: false }),
|
||||
);
|
||||
expect(row.status).toContain('R1');
|
||||
expect(row.status).toContain('12 mei 2024');
|
||||
});
|
||||
|
||||
it('manual review adds a note; rejection adds its reason', () => {
|
||||
const manual = submittedRow({
|
||||
...base,
|
||||
status: { tag: 'InBehandeling', referentie: 'R1', manual: true },
|
||||
} as Aanvraag);
|
||||
expect(manual.status).toContain('handmatig');
|
||||
const rejected = submittedRow({
|
||||
...base,
|
||||
status: { tag: 'Afgewezen', referentie: 'R2', reden: 'Onvoldoende uren' },
|
||||
} as Aanvraag);
|
||||
expect(rejected.status).toContain('Onvoldoende uren');
|
||||
});
|
||||
|
||||
it('meer-info-gevraagd adds its reason, like a rejection', () => {
|
||||
const row = submittedRow({
|
||||
...base,
|
||||
status: { tag: 'MeerInfoGevraagd', referentie: 'R3', reden: 'Diploma ontbreekt' },
|
||||
} as Aanvraag);
|
||||
expect(row.status).toContain('Diploma ontbreekt');
|
||||
});
|
||||
});
|
||||
|
||||
describe('detailRows', () => {
|
||||
it('lists soort/waarvoor/status/referentie/ingediend, plus reason when rejected', () => {
|
||||
const rows = detailRows({
|
||||
...base,
|
||||
status: { tag: 'Afgewezen', referentie: 'R2', reden: 'Onvoldoende uren' },
|
||||
} as Aanvraag);
|
||||
const values = rows.map((r) => r.value);
|
||||
expect(values).toContain(TYPE_LABELS.herregistratie);
|
||||
expect(values).toContain('R2');
|
||||
expect(values).toContain('Onvoldoende uren');
|
||||
expect(rows.length).toBe(6);
|
||||
});
|
||||
|
||||
it('reference falls back to em dash for a Concept', () => {
|
||||
const rows = detailRows({
|
||||
...base,
|
||||
submittedAt: undefined,
|
||||
status: { tag: 'Concept', stepIndex: 0, stepCount: 3 },
|
||||
} as Aanvraag);
|
||||
const ref = rows.find((r) => r.value === '—');
|
||||
expect(ref).toBeTruthy();
|
||||
expect(rows.length).toBe(5);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,108 @@
|
||||
import { formatDatumNl } from '@shared/kernel/datum';
|
||||
import { Aanvraag, AanvraagStatus, AanvraagType } from './aanvraag';
|
||||
|
||||
/** View-model mapping for an aanvraag: type → labels, status → label, and the fields
|
||||
for a CIBG "aanvragen" row / the case-detail page. Pure, no Angular — the UI
|
||||
renders these, it does not derive them. */
|
||||
|
||||
export const TYPE_LABELS: Record<AanvraagType, string> = {
|
||||
registratie: $localize`:@@aanvraagBlock.type.registratie:Inschrijving`,
|
||||
herregistratie: $localize`:@@aanvraagBlock.type.herregistratie:Herregistratie`,
|
||||
intake: $localize`:@@aanvraagBlock.type.intake:Herregistratie-intake`,
|
||||
};
|
||||
|
||||
/** What the aanvraag is for (shown under the title). */
|
||||
export function purposeLabel(type: AanvraagType): string {
|
||||
switch (type) {
|
||||
case 'registratie':
|
||||
return $localize`:@@aanvraag.purpose.registratie:Inschrijving in het BIG-register`;
|
||||
case 'herregistratie':
|
||||
return $localize`:@@aanvraag.purpose.herregistratie:Verlenging van uw BIG-registratie`;
|
||||
case 'intake':
|
||||
return $localize`:@@aanvraag.purpose.intake:Intake-vragenlijst voor uw herregistratie`;
|
||||
}
|
||||
}
|
||||
|
||||
/** The status as a plain label (what state the aanvraag is in). */
|
||||
export function statusLabel(status: AanvraagStatus): string {
|
||||
switch (status.tag) {
|
||||
case 'Concept':
|
||||
return $localize`:@@aanvraag.status.concept:Concept (nog niet ingediend)`;
|
||||
case 'Ingediend':
|
||||
return $localize`:@@aanvraag.status.ingediend:Ingediend`;
|
||||
case 'InBehandeling':
|
||||
return $localize`:@@aanvraag.status.inBehandeling:In behandeling`;
|
||||
case 'MeerInfoGevraagd':
|
||||
return $localize`:@@aanvraag.status.meerInfoGevraagd:Meer informatie gevraagd`;
|
||||
case 'Goedgekeurd':
|
||||
return $localize`:@@aanvraag.status.goedgekeurd:Goedgekeurd`;
|
||||
case 'Afgewezen':
|
||||
return $localize`:@@aanvraag.status.afgewezen:Afgewezen`;
|
||||
}
|
||||
}
|
||||
|
||||
/** The reference number, or '' for a Concept (which has none yet). */
|
||||
export function referentie(status: AanvraagStatus): string {
|
||||
return status.tag === 'Concept' ? '' : status.referentie;
|
||||
}
|
||||
|
||||
export interface AanvraagRow {
|
||||
heading: string;
|
||||
/** What the aanvraag is for (the `.subtitle` line). */
|
||||
subtitle: string;
|
||||
/** The status: label + reference + submit date (+ any note) — the `.status` line. */
|
||||
status: string;
|
||||
}
|
||||
|
||||
/** Fields for a submitted aanvraag's row in the dashboard "aanvragen" list (Concept
|
||||
has no row — it renders as a resumable melding, see aanvraag-block). */
|
||||
export function submittedRow(a: Aanvraag): AanvraagRow {
|
||||
const s = a.status;
|
||||
const parts = [statusLabel(s)];
|
||||
const ref = referentie(s);
|
||||
if (ref) parts.push($localize`:@@aanvraag.row.ref:Referentie ${ref}:ref:`);
|
||||
if (a.submittedAt)
|
||||
parts.push(
|
||||
$localize`:@@aanvraag.row.ingediend:ingediend op ${formatDatumNl(a.submittedAt)}:datum:`,
|
||||
);
|
||||
if (s.tag === 'InBehandeling' && s.manual)
|
||||
parts.push(
|
||||
$localize`:@@aanvraagBlock.manual:Uw aanvraag wordt handmatig beoordeeld in de backoffice.`,
|
||||
);
|
||||
if (s.tag === 'Afgewezen' || s.tag === 'MeerInfoGevraagd') parts.push(s.reden);
|
||||
return {
|
||||
heading: TYPE_LABELS[a.type],
|
||||
subtitle: purposeLabel(a.type),
|
||||
status: parts.join(' · '),
|
||||
};
|
||||
}
|
||||
|
||||
/** Key/value rows for the case-detail page (CIBG Datablock). */
|
||||
export function detailRows(a: Aanvraag): { key: string; value: string }[] {
|
||||
const rows = [
|
||||
{ key: $localize`:@@aanvraag.detail.soort:Soort aanvraag`, value: TYPE_LABELS[a.type] },
|
||||
{ key: $localize`:@@aanvraag.detail.waarvoor:Waarvoor`, value: purposeLabel(a.type) },
|
||||
{ key: $localize`:@@aanvraag.detail.status:Status`, value: statusLabel(a.status) },
|
||||
{
|
||||
key: $localize`:@@aanvraag.detail.referentie:Referentie`,
|
||||
value: referentie(a.status) || '—',
|
||||
},
|
||||
{
|
||||
key: $localize`:@@aanvraag.detail.ingediend:Ingediend op`,
|
||||
value: a.submittedAt ? formatDatumNl(a.submittedAt) : '—',
|
||||
},
|
||||
];
|
||||
if (a.status.tag === 'Afgewezen') {
|
||||
rows.push({
|
||||
key: $localize`:@@aanvraag.detail.reden:Reden van afwijzing`,
|
||||
value: a.status.reden,
|
||||
});
|
||||
}
|
||||
if (a.status.tag === 'MeerInfoGevraagd') {
|
||||
rows.push({
|
||||
key: $localize`:@@aanvraag.detail.meerInfoReden:Gevraagde informatie`,
|
||||
value: a.status.reden,
|
||||
});
|
||||
}
|
||||
return rows;
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
/**
|
||||
* An application (aanvraag) as the frontend sees it — the parsed, domain-side view
|
||||
* of the backend-owned aggregate (see backend ApplicationStore + PRD 0001). Pure
|
||||
* types, no Angular. Lives in `registratie` because the dashboard (here) is the
|
||||
* consumer and the downstream wizards (`herregistratie → registratie`) produce them.
|
||||
*
|
||||
* The status is a discriminated union so illegal states are unrepresentable — same
|
||||
* reflex as RemoteData. The server computes which tag applies (auto-approval on
|
||||
* read); the FE renders it, it does not recompute the lifecycle.
|
||||
*/
|
||||
export type AanvraagType = 'registratie' | 'herregistratie' | 'intake';
|
||||
|
||||
// Ingediend/MeerInfoGevraagd (ADR-0002/WP-63) are widened into the union so the parse
|
||||
// boundary + renderers are ready, but no backend path emits them yet — that's WP-65's
|
||||
// behandelaar-facing transition endpoint.
|
||||
export type AanvraagStatus =
|
||||
| { tag: 'Concept'; stepIndex: number; stepCount: number }
|
||||
| { tag: 'Ingediend'; referentie: string }
|
||||
| { tag: 'InBehandeling'; referentie: string; manual: boolean } // manual=true → "wordt handmatig beoordeeld"
|
||||
| { tag: 'MeerInfoGevraagd'; referentie: string; reden: string }
|
||||
| { tag: 'Goedgekeurd'; referentie: string }
|
||||
| { tag: 'Afgewezen'; referentie: string; reden: string };
|
||||
|
||||
export interface Aanvraag {
|
||||
id: string;
|
||||
type: AanvraagType;
|
||||
status: AanvraagStatus;
|
||||
documentIds: string[];
|
||||
createdAt: string;
|
||||
updatedAt: string;
|
||||
submittedAt?: string;
|
||||
/** The case owner (a BSN). Only populated by the admin cross-owner list (WP-36);
|
||||
the user's own list leaves it undefined. */
|
||||
owner?: string;
|
||||
}
|
||||
|
||||
/** Detail adds the opaque wizard snapshot used to resume a Concept. */
|
||||
export interface AanvraagDetail extends Aanvraag {
|
||||
draft: unknown;
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { blockActions } from './block-actions';
|
||||
|
||||
describe('blockActions', () => {
|
||||
it('a Concept can be resumed or cancelled', () => {
|
||||
expect(blockActions({ tag: 'Concept', stepIndex: 1, stepCount: 3 })).toEqual([
|
||||
'resume',
|
||||
'cancel',
|
||||
]);
|
||||
});
|
||||
|
||||
it('an in-behandeling aanvraag only exposes its documents', () => {
|
||||
expect(blockActions({ tag: 'InBehandeling', referentie: 'BIG-1', manual: true })).toEqual([
|
||||
'viewDocuments',
|
||||
]);
|
||||
});
|
||||
|
||||
it('ingediend and meer-info-gevraagd behave like in-behandeling', () => {
|
||||
expect(blockActions({ tag: 'Ingediend', referentie: 'BIG-1' })).toEqual(['viewDocuments']);
|
||||
expect(blockActions({ tag: 'MeerInfoGevraagd', referentie: 'BIG-1', reden: 'x' })).toEqual([
|
||||
'viewDocuments',
|
||||
]);
|
||||
});
|
||||
|
||||
it('resolved aanvragen have no actions', () => {
|
||||
expect(blockActions({ tag: 'Goedgekeurd', referentie: 'BIG-1' })).toEqual([]);
|
||||
expect(blockActions({ tag: 'Afgewezen', referentie: 'BIG-1', reden: 'x' })).toEqual([]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,20 @@
|
||||
import { AanvraagStatus } from './aanvraag';
|
||||
|
||||
/** What a dashboard "Mijn aanvragen" block offers per status. The badge itself
|
||||
follows directly from `status.tag` (the UI maps tag → colour + label), so this
|
||||
pure function owns only the *actions* decision. */
|
||||
export type BlockAction = 'resume' | 'cancel' | 'viewDocuments';
|
||||
|
||||
export function blockActions(status: AanvraagStatus): BlockAction[] {
|
||||
switch (status.tag) {
|
||||
case 'Concept':
|
||||
return ['resume', 'cancel'];
|
||||
case 'Ingediend':
|
||||
case 'InBehandeling':
|
||||
case 'MeerInfoGevraagd':
|
||||
return ['viewDocuments'];
|
||||
case 'Goedgekeurd':
|
||||
case 'Afgewezen':
|
||||
return [];
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { ChangeRequestState, reduce, initial } from './change-request.machine';
|
||||
|
||||
const editingWith = (telefoon: string): ChangeRequestState => ({
|
||||
tag: 'Editing',
|
||||
draft: { telefoon },
|
||||
errors: {},
|
||||
});
|
||||
|
||||
describe('change-request reduce', () => {
|
||||
it('SetField updates the draft while editing', () => {
|
||||
const s = reduce(initial, { tag: 'SetField', key: 'telefoon', value: '0612345678' });
|
||||
expect(s.tag).toBe('Editing');
|
||||
expect((s as Extract<ChangeRequestState, { tag: 'Editing' }>).draft.telefoon).toBe(
|
||||
'0612345678',
|
||||
);
|
||||
});
|
||||
|
||||
it('Submit with an invalid draft stays Editing and reports field errors', () => {
|
||||
const s = reduce(editingWith('nope'), { tag: 'Submit' });
|
||||
expect(s.tag).toBe('Editing');
|
||||
const errors = (s as Extract<ChangeRequestState, { tag: 'Editing' }>).errors;
|
||||
expect(errors.telefoon).toBeTruthy();
|
||||
});
|
||||
|
||||
it('Submit with a valid draft moves to Submitting with parsed (normalised) data', () => {
|
||||
const s = reduce(editingWith('06 12 34 56 78'), { tag: 'Submit' });
|
||||
expect(s.tag).toBe('Submitting');
|
||||
expect((s as Extract<ChangeRequestState, { tag: 'Submitting' }>).data.telefoon).toBe(
|
||||
'0612345678',
|
||||
);
|
||||
});
|
||||
|
||||
it('SubmitConfirmed maps Submitting to Submitted with the referentie', () => {
|
||||
const submitting = reduce(editingWith('0612345678'), { tag: 'Submit' });
|
||||
const ok = reduce(submitting, { tag: 'SubmitConfirmed', referentie: 'BIG-2026-1' });
|
||||
expect(ok).toMatchObject({ tag: 'Submitted', referentie: 'BIG-2026-1' });
|
||||
});
|
||||
|
||||
it('SubmitFailed maps Submitting to Failed with the error', () => {
|
||||
const submitting = reduce(editingWith('0612345678'), { tag: 'Submit' });
|
||||
const failed = reduce(submitting, { tag: 'SubmitFailed', error: 'boom' });
|
||||
expect(failed).toMatchObject({ tag: 'Failed', error: 'boom' });
|
||||
});
|
||||
|
||||
it('Retry re-submits a failure', () => {
|
||||
const submitting = reduce(editingWith('0612345678'), { tag: 'Submit' });
|
||||
const failed = reduce(submitting, { tag: 'SubmitFailed', error: 'boom' });
|
||||
expect(reduce(failed, { tag: 'Retry' }).tag).toBe('Submitting');
|
||||
});
|
||||
|
||||
it('Reset returns to the initial editing state', () => {
|
||||
const submitting = reduce(editingWith('0612345678'), { tag: 'Submit' });
|
||||
expect(reduce(submitting, { tag: 'Reset' })).toEqual(initial);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,81 @@
|
||||
import { Result, assertNever } from '@shared/kernel/fp';
|
||||
import {
|
||||
Telefoonnummer,
|
||||
parseTelefoonnummer,
|
||||
} from '@registratie/domain/value-objects/telefoonnummer';
|
||||
|
||||
/** What the user is typing (raw, possibly invalid). The BRP address is NOT part of
|
||||
the form — it is authoritative and shown read-only (WP-34); only the phone number
|
||||
is editable here. */
|
||||
export interface Draft {
|
||||
telefoon: string;
|
||||
}
|
||||
|
||||
/** After parsing — telefoon is the branded type, so downstream can't get a raw one. */
|
||||
export interface Valid {
|
||||
telefoon: Telefoonnummer;
|
||||
}
|
||||
|
||||
export type Errors = Partial<Record<keyof Draft, string>>;
|
||||
|
||||
/**
|
||||
* The contact-change (telefoonwijziging) form as one tagged union — the SAME idiom
|
||||
* as the wizards, just single-step. `draft`/`errors` exist only while Editing;
|
||||
* Submitting/Submitted/Failed carry the parsed `Valid`. Illegal states (submitting
|
||||
* an invalid draft, a success screen with errors) are unrepresentable.
|
||||
*/
|
||||
// #region showcase:machine
|
||||
export type ChangeRequestState =
|
||||
| { tag: 'Editing'; draft: Draft; errors: Errors } // draft/errors exist ONLY while editing
|
||||
| { tag: 'Submitting'; data: Valid } // carries the parsed value, no errors
|
||||
| { tag: 'Submitted'; data: Valid; referentie: string }
|
||||
| { tag: 'Failed'; data: Valid; error: string };
|
||||
// #endregion showcase:machine
|
||||
|
||||
export const initial: ChangeRequestState = {
|
||||
tag: 'Editing',
|
||||
draft: { telefoon: '' },
|
||||
errors: {},
|
||||
};
|
||||
|
||||
/** Parse via the value object; on success hand back a Valid, else per-field errors. */
|
||||
function validate(draft: Draft): Result<Errors, Valid> {
|
||||
const telefoon = parseTelefoonnummer(draft.telefoon);
|
||||
if (telefoon.ok) return { ok: true, value: { telefoon: telefoon.value } };
|
||||
return { ok: false, error: { telefoon: telefoon.error } };
|
||||
}
|
||||
|
||||
export type ChangeRequestMsg =
|
||||
| { tag: 'SetField'; key: keyof Draft; value: string }
|
||||
| { tag: 'Submit' }
|
||||
| { tag: 'Retry' }
|
||||
| { tag: 'SubmitConfirmed'; referentie: string }
|
||||
| { tag: 'SubmitFailed'; error: string }
|
||||
| { tag: 'Reset' }
|
||||
| { tag: 'Seed'; state: ChangeRequestState }; // mount a specific state (stories/tests)
|
||||
|
||||
export function reduce(s: ChangeRequestState, m: ChangeRequestMsg): ChangeRequestState {
|
||||
switch (m.tag) {
|
||||
case 'SetField':
|
||||
return s.tag === 'Editing' ? { ...s, draft: { ...s.draft, [m.key]: m.value } } : s;
|
||||
case 'Submit': {
|
||||
if (s.tag !== 'Editing') return s;
|
||||
const r = validate(s.draft);
|
||||
return r.ok ? { tag: 'Submitting', data: r.value } : { ...s, errors: r.error };
|
||||
}
|
||||
case 'Retry':
|
||||
return s.tag === 'Failed' ? { tag: 'Submitting', data: s.data } : s;
|
||||
case 'SubmitConfirmed':
|
||||
return s.tag === 'Submitting'
|
||||
? { tag: 'Submitted', data: s.data, referentie: m.referentie }
|
||||
: s;
|
||||
case 'SubmitFailed':
|
||||
return s.tag === 'Submitting' ? { tag: 'Failed', data: s.data, error: m.error } : s;
|
||||
case 'Reset':
|
||||
return initial;
|
||||
case 'Seed':
|
||||
return m.state;
|
||||
default:
|
||||
return assertNever(m);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { hasProgress, initial, RegistratieState } from './registratie-wizard.machine';
|
||||
|
||||
const invullen = (over: Partial<Extract<RegistratieState, { tag: 'Invullen' }>>) => ({
|
||||
...(initial as Extract<RegistratieState, { tag: 'Invullen' }>),
|
||||
...over,
|
||||
});
|
||||
|
||||
describe('hasProgress', () => {
|
||||
it('is false for a fresh wizard', () => {
|
||||
expect(hasProgress(initial as Extract<RegistratieState, { tag: 'Invullen' }>)).toBe(false);
|
||||
});
|
||||
|
||||
it('ignores an auto-prefilled BRP address at step 0', () => {
|
||||
const s = invullen({
|
||||
draft: {
|
||||
straat: 'Lange Voorhout 9',
|
||||
postcode: '2514 EA',
|
||||
woonplaats: 'Den Haag',
|
||||
adresHerkomst: 'brp',
|
||||
antwoorden: {},
|
||||
},
|
||||
});
|
||||
expect(hasProgress(s)).toBe(false);
|
||||
});
|
||||
|
||||
it('is true once the user advances, picks correspondence/diploma, or is past step 0', () => {
|
||||
expect(hasProgress(invullen({ cursor: 1 }))).toBe(true);
|
||||
expect(hasProgress(invullen({ draft: { correspondentie: 'post', antwoorden: {} } }))).toBe(
|
||||
true,
|
||||
);
|
||||
expect(hasProgress(invullen({ draft: { diplomaId: 'd1', antwoorden: {} } }))).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
@@ -0,0 +1,303 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { ok, err } from '@shared/kernel/fp';
|
||||
import { initialUpload } from '@shared/upload/upload.machine';
|
||||
import {
|
||||
Draft,
|
||||
RegistratieState,
|
||||
STEPS,
|
||||
initial,
|
||||
currentStep,
|
||||
next,
|
||||
back,
|
||||
gaNaarStap,
|
||||
kiesDiploma,
|
||||
kiesHandmatig,
|
||||
declareerBeroep,
|
||||
setAntwoord,
|
||||
setField,
|
||||
prefillAdres,
|
||||
submit,
|
||||
resolve,
|
||||
reduce,
|
||||
} from './registratie-wizard.machine';
|
||||
|
||||
const invullen = (draft: Partial<Draft>, cursor = 0): RegistratieState => ({
|
||||
tag: 'Invullen',
|
||||
draft: { antwoorden: {}, ...draft },
|
||||
cursor,
|
||||
errors: {},
|
||||
upload: initialUpload,
|
||||
});
|
||||
|
||||
const validAdres = {
|
||||
straat: 'Lange Voorhout 9',
|
||||
postcode: '2514 EA',
|
||||
woonplaats: 'Den Haag',
|
||||
correspondentie: 'post' as const,
|
||||
adresHerkomst: 'brp' as const,
|
||||
};
|
||||
const validDraft: Partial<Draft> = {
|
||||
...validAdres,
|
||||
diplomaId: 'd1',
|
||||
beroep: 'Arts',
|
||||
diplomaHerkomst: 'duo',
|
||||
};
|
||||
|
||||
describe('STEPS (fixed)', () => {
|
||||
it('always has the same three steps', () => {
|
||||
expect(STEPS).toEqual(['adres', 'beroep', 'controle']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('navigation', () => {
|
||||
it('Next is a no-op (sets errors) when the adres step is invalid', () => {
|
||||
const s = next(initial);
|
||||
expect(s.tag).toBe('Invullen');
|
||||
expect((s as any).cursor).toBe(0);
|
||||
expect((s as any).errors.straat).toBeTruthy();
|
||||
expect((s as any).errors.correspondentie).toBeTruthy();
|
||||
});
|
||||
|
||||
it('Next advances once the adres step is valid', () => {
|
||||
const s = next(invullen(validAdres));
|
||||
expect((s as any).cursor).toBe(1);
|
||||
expect(currentStep(s as any)).toBe('beroep');
|
||||
});
|
||||
|
||||
it('requires a valid e-mail only when the channel is email', () => {
|
||||
const bad = next(invullen({ ...validAdres, correspondentie: 'email' }));
|
||||
expect((bad as any).errors.email).toBeTruthy();
|
||||
const good = next(invullen({ ...validAdres, correspondentie: 'email', email: 'a@b.nl' }));
|
||||
expect((good as any).cursor).toBe(1);
|
||||
});
|
||||
|
||||
it('beroep step requires a chosen diploma', () => {
|
||||
const noDiploma = next(invullen(validAdres, 1));
|
||||
expect((noDiploma as any).cursor).toBe(1);
|
||||
expect((noDiploma as any).errors.diploma).toBeTruthy();
|
||||
const withDiploma = next(invullen(validDraft, 1));
|
||||
expect((withDiploma as any).cursor).toBe(2);
|
||||
});
|
||||
|
||||
it('Back never goes below the first step and preserves the draft', () => {
|
||||
expect(back(initial)).toBe(initial);
|
||||
const s = back(invullen(validDraft, 2));
|
||||
expect((s as any).cursor).toBe(1);
|
||||
expect((s as any).draft.beroep).toBe('Arts');
|
||||
});
|
||||
|
||||
it('GaNaarStap only jumps backwards', () => {
|
||||
expect((gaNaarStap(invullen(validDraft, 2), 0) as any).cursor).toBe(0);
|
||||
expect((gaNaarStap(invullen(validDraft, 1), 2) as any).cursor).toBe(1); // forward jump rejected
|
||||
});
|
||||
});
|
||||
|
||||
describe('adres origin (BRP vs handmatig)', () => {
|
||||
it('prefillAdres flags origin brp', () => {
|
||||
const s = prefillAdres(invullen({}), 'Lange Voorhout 9', '2514 EA', 'Den Haag');
|
||||
expect((s as any).draft.adresHerkomst).toBe('brp');
|
||||
expect((s as any).draft.straat).toBe('Lange Voorhout 9');
|
||||
});
|
||||
|
||||
it('editing a prefilled address field flips origin to handmatig', () => {
|
||||
const prefilled = prefillAdres(invullen({}), 'Lange Voorhout 9', '2514 EA', 'Den Haag');
|
||||
const edited = setField(prefilled, 'woonplaats', 'Rotterdam');
|
||||
expect((edited as any).draft.adresHerkomst).toBe('handmatig');
|
||||
});
|
||||
|
||||
it('typing an address with no BRP prefill yields handmatig', () => {
|
||||
const s = setField(invullen({}), 'straat', 'Kerkstraat 1');
|
||||
expect((s as any).draft.adresHerkomst).toBe('handmatig');
|
||||
});
|
||||
|
||||
it('editing the e-mail field does not change the address origin', () => {
|
||||
const prefilled = prefillAdres(invullen({}), 'Lange Voorhout 9', '2514 EA', 'Den Haag');
|
||||
const edited = setField(prefilled, 'email', 'a@b.nl');
|
||||
expect((edited as any).draft.adresHerkomst).toBe('brp');
|
||||
});
|
||||
|
||||
it('a manually entered address still submits (only manual diploma is gated)', () => {
|
||||
const s = submit(
|
||||
invullen({
|
||||
straat: 'Kerkstraat 1',
|
||||
postcode: '1234 AB',
|
||||
woonplaats: 'Utrecht',
|
||||
correspondentie: 'post',
|
||||
adresHerkomst: 'handmatig',
|
||||
diplomaId: 'd1',
|
||||
beroep: 'Arts',
|
||||
diplomaHerkomst: 'duo',
|
||||
}),
|
||||
);
|
||||
expect(s.tag).toBe('Indienen');
|
||||
expect((s as any).data.adresHerkomst).toBe('handmatig');
|
||||
});
|
||||
});
|
||||
|
||||
describe('kiesDiploma', () => {
|
||||
it('derives the beroep from the chosen diploma and flags origin duo', () => {
|
||||
const s = kiesDiploma(invullen({}), 'd9', 'Verpleegkundige', []);
|
||||
expect((s as any).draft.diplomaId).toBe('d9');
|
||||
expect((s as any).draft.beroep).toBe('Verpleegkundige');
|
||||
expect((s as any).draft.diplomaHerkomst).toBe('duo');
|
||||
});
|
||||
});
|
||||
|
||||
describe('policy questions (geldigheidsvragen)', () => {
|
||||
it('a diploma with questions blocks Next until they are answered', () => {
|
||||
let s = kiesDiploma(invullen(validAdres, 1), 'd2', 'Arts', ['nl-taalvaardigheid']);
|
||||
const blocked = next(s);
|
||||
expect((blocked as any).cursor).toBe(1);
|
||||
expect((blocked as any).errors.antwoorden['nl-taalvaardigheid']).toBeTruthy();
|
||||
s = setAntwoord(s, 'nl-taalvaardigheid', 'ja');
|
||||
expect((next(s) as any).cursor).toBe(2);
|
||||
});
|
||||
|
||||
it('validateAll keeps only the answers to the questions that applied', () => {
|
||||
let s = kiesDiploma(invullen(validAdres, 2), 'd2', 'Arts', ['nl-taalvaardigheid']);
|
||||
s = setAntwoord(s, 'nl-taalvaardigheid', 'ja');
|
||||
s = setAntwoord(s, 'stale', 'x'); // not in vraagIds
|
||||
const done = submit(s);
|
||||
expect(done.tag).toBe('Indienen');
|
||||
expect((done as any).data.antwoorden).toEqual({ 'nl-taalvaardigheid': 'ja' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('manual diploma fallback', () => {
|
||||
const maxIds = ['nl-taalvaardigheid', 'diploma-erkend', 'toelichting'];
|
||||
|
||||
it('KiesHandmatig flags handmatig with the maximal question set and no beroep yet', () => {
|
||||
const s = kiesHandmatig(invullen(validAdres, 1), maxIds);
|
||||
expect((s as any).draft.diplomaHerkomst).toBe('handmatig');
|
||||
expect((s as any).draft.beroep).toBeUndefined();
|
||||
expect((s as any).draft.vraagIds).toEqual(maxIds);
|
||||
});
|
||||
|
||||
it('requires a declared beroep + all maximal questions before submit', () => {
|
||||
let s = kiesHandmatig(invullen(validAdres, 2), maxIds);
|
||||
expect(submit(s).tag).toBe('Invullen'); // no beroep declared
|
||||
s = declareerBeroep(s, 'Fysiotherapeut');
|
||||
expect(submit(s).tag).toBe('Invullen'); // questions unanswered
|
||||
for (const id of maxIds) s = setAntwoord(s, id, 'ja');
|
||||
const done = submit(s);
|
||||
expect(done.tag).toBe('Indienen');
|
||||
expect((done as any).data.diplomaHerkomst).toBe('handmatig');
|
||||
expect((done as any).data.beroep).toBe('Fysiotherapeut');
|
||||
});
|
||||
});
|
||||
|
||||
describe('submit', () => {
|
||||
it('stays in Invullen when the draft is incomplete (no diploma)', () => {
|
||||
expect(submit(invullen(validAdres)).tag).toBe('Invullen');
|
||||
});
|
||||
|
||||
it('reaches Indienen with a complete, valid draft, carrying its data', () => {
|
||||
const good = submit(invullen(validDraft));
|
||||
expect(good.tag).toBe('Indienen');
|
||||
expect((good as any).data.beroep).toBe('Arts');
|
||||
expect((good as any).data.adres.postcode).toBe('2514 EA');
|
||||
expect((good as any).data.adresHerkomst).toBe('brp');
|
||||
});
|
||||
|
||||
it('resolve maps Indienen to Ingediend with the referentie', () => {
|
||||
const ingediend = resolve(submit(invullen(validDraft)), ok('BIG-2026-001'));
|
||||
expect(ingediend.tag).toBe('Ingediend');
|
||||
expect((ingediend as any).referentie).toBe('BIG-2026-001');
|
||||
});
|
||||
|
||||
it('resolve maps Indienen to Mislukt on a failed submit', () => {
|
||||
expect(resolve(submit(invullen(validDraft)), err('boom')).tag).toBe('Mislukt');
|
||||
});
|
||||
});
|
||||
|
||||
describe('reduce (message-driven happy path)', () => {
|
||||
it('drives the full flow via messages', () => {
|
||||
let s: RegistratieState = initial;
|
||||
s = reduce(s, {
|
||||
tag: 'PrefillAdres',
|
||||
straat: 'Lange Voorhout 9',
|
||||
postcode: '2514 EA',
|
||||
woonplaats: 'Den Haag',
|
||||
});
|
||||
s = reduce(s, { tag: 'SetCorrespondentie', value: 'post' });
|
||||
s = reduce(s, { tag: 'Next' });
|
||||
expect(currentStep(s as any)).toBe('beroep');
|
||||
s = reduce(s, { tag: 'KiesDiploma', diplomaId: 'd1', beroep: 'Arts', vraagIds: [] });
|
||||
s = reduce(s, { tag: 'Next' });
|
||||
expect(currentStep(s as any)).toBe('controle');
|
||||
s = reduce(s, { tag: 'Submit' });
|
||||
expect(s.tag).toBe('Indienen');
|
||||
s = reduce(s, { tag: 'SubmitConfirmed', referentie: 'BIG-2026-001' });
|
||||
expect(s.tag).toBe('Ingediend');
|
||||
});
|
||||
|
||||
it('SubmitFailed moves Indienen to Mislukt', () => {
|
||||
const s = reduce(reduce(invullen(validDraft), { tag: 'Submit' }), {
|
||||
tag: 'SubmitFailed',
|
||||
error: 'boom',
|
||||
});
|
||||
expect(s.tag).toBe('Mislukt');
|
||||
});
|
||||
|
||||
it('Retry returns Mislukt to Indienen with the same data', () => {
|
||||
const mislukt = reduce(reduce(invullen(validDraft), { tag: 'Submit' }), {
|
||||
tag: 'SubmitFailed',
|
||||
error: 'boom',
|
||||
});
|
||||
const s = reduce(mislukt, { tag: 'Retry' });
|
||||
expect(s.tag).toBe('Indienen');
|
||||
expect((s as any).data.beroep).toBe('Arts');
|
||||
});
|
||||
});
|
||||
|
||||
describe('inline document upload (beroep step)', () => {
|
||||
const cat = {
|
||||
categoryId: 'diploma',
|
||||
label: 'Diploma',
|
||||
description: '',
|
||||
required: true,
|
||||
acceptedTypes: [],
|
||||
maxSizeMb: 10,
|
||||
multiple: false,
|
||||
allowPostDelivery: true,
|
||||
};
|
||||
|
||||
it('routes Upload messages through the upload reducer', () => {
|
||||
const s = reduce(invullen(validDraft), {
|
||||
tag: 'Upload',
|
||||
msg: { type: 'CategoriesLoaded', categories: [cat] },
|
||||
});
|
||||
expect((s as any).upload.categories).toHaveLength(1);
|
||||
});
|
||||
|
||||
it('blocks the beroep step until a required category is satisfied', () => {
|
||||
let s = reduce(invullen(validDraft, 1), {
|
||||
tag: 'Upload',
|
||||
msg: { type: 'CategoriesLoaded', categories: [cat] },
|
||||
});
|
||||
s = reduce(s, { tag: 'Next' }); // beroep → controle blocked
|
||||
expect(currentStep(s as any)).toBe('beroep');
|
||||
expect((s as any).errors.documenten).toBeTruthy();
|
||||
// choosing post delivery satisfies the requirement
|
||||
s = reduce(s, {
|
||||
tag: 'Upload',
|
||||
msg: { type: 'DeliveryChannelChanged', categoryId: 'diploma', channel: 'post' },
|
||||
});
|
||||
s = reduce(s, { tag: 'Next' });
|
||||
expect(currentStep(s as any)).toBe('controle');
|
||||
});
|
||||
|
||||
it('includes delivery refs in the submitted data', () => {
|
||||
let s = reduce(invullen(validDraft), {
|
||||
tag: 'Upload',
|
||||
msg: { type: 'CategoriesLoaded', categories: [cat] },
|
||||
});
|
||||
s = reduce(s, {
|
||||
tag: 'Upload',
|
||||
msg: { type: 'DeliveryChannelChanged', categoryId: 'diploma', channel: 'post' },
|
||||
});
|
||||
const done = submit(s as any);
|
||||
expect(done.tag).toBe('Indienen');
|
||||
expect((done as any).data.documents).toEqual([{ categoryId: 'diploma', channel: 'post' }]);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,360 @@
|
||||
import { Result, ok, err, assertNever } from '@shared/kernel/fp';
|
||||
import { Postcode, parsePostcode } from '@registratie/domain/value-objects/postcode';
|
||||
import { Email, parseEmail } from '@registratie/domain/value-objects/email';
|
||||
import {
|
||||
UploadState,
|
||||
UploadMsg,
|
||||
DeliveryChannel,
|
||||
initialUpload,
|
||||
reduceUpload,
|
||||
requiredCategoriesSatisfied,
|
||||
deliveryRefs,
|
||||
} from '@shared/upload/upload.machine';
|
||||
|
||||
/**
|
||||
* A FIXED 3-step registration wizard. The steps never change in number (always
|
||||
* `STEPS`): (1) adres + correspondentievoorkeur, (2) beroep o.b.v. diploma,
|
||||
* (3) controle & indienen. Follow-up questions appear *inline within a step*
|
||||
* (e.g. choosing 'email' reveals the e-mail field). "Is this field required
|
||||
* right now" is a pure function (`validateStep`), so it is trivial to test and
|
||||
* impossible to get out of sync with the data. Invariants live here, not in the
|
||||
* UI: the wizard reaches `Indienen` only when a complete `ValidRegistratie` parses.
|
||||
*/
|
||||
|
||||
export type StepId = 'adres' | 'beroep' | 'controle';
|
||||
|
||||
/** The fixed step list. Number of steps never changes; questions reveal inline. */
|
||||
export const STEPS: StepId[] = ['adres', 'beroep', 'controle'];
|
||||
|
||||
/** Where a piece of data came from — recorded on the aggregate (PRD §5). */
|
||||
export type AdresHerkomst = 'brp' | 'handmatig';
|
||||
export type DiplomaHerkomst = 'duo' | 'handmatig';
|
||||
export type Correspondentie = 'email' | 'post';
|
||||
|
||||
/** One record carried across every step (and persisted). All optional: the user
|
||||
fills it in gradually. Adres fields are kept flat so one `SetField` message
|
||||
serves them all (mirrors the intake machine). */
|
||||
export interface Draft {
|
||||
straat?: string;
|
||||
postcode?: string;
|
||||
woonplaats?: string;
|
||||
adresHerkomst?: AdresHerkomst;
|
||||
correspondentie?: Correspondentie;
|
||||
email?: string;
|
||||
diplomaId?: string;
|
||||
diplomaHerkomst?: DiplomaHerkomst;
|
||||
beroep?: string; // DERIVED from the chosen DUO diploma (or declared for a manual one)
|
||||
vraagIds?: string[]; // ids of the policy questions that apply to the chosen diploma
|
||||
antwoorden: Record<string, string>; // geldigheidsantwoorden, keyed by question id
|
||||
}
|
||||
|
||||
/** What we have after the controle step parses — guaranteed valid/typed. */
|
||||
export interface ValidRegistratie {
|
||||
adres: { straat: string; postcode: Postcode; woonplaats: string };
|
||||
adresHerkomst: AdresHerkomst;
|
||||
correspondentie: Correspondentie;
|
||||
email?: Email; // only when correspondentie === 'email'
|
||||
diplomaId: string;
|
||||
diplomaHerkomst: DiplomaHerkomst;
|
||||
beroep: string;
|
||||
antwoorden: Record<string, string>;
|
||||
documents: Array<{ categoryId: string; channel: DeliveryChannel; documentId?: string }>;
|
||||
}
|
||||
|
||||
/** Text fields settable via SetField. */
|
||||
export type DraftField = 'straat' | 'postcode' | 'woonplaats' | 'email';
|
||||
|
||||
/** Per-field error map. `antwoorden` holds per-policy-question errors, keyed by
|
||||
question id (a step can show several questions). */
|
||||
export interface Errors {
|
||||
straat?: string;
|
||||
postcode?: string;
|
||||
woonplaats?: string;
|
||||
email?: string;
|
||||
correspondentie?: string;
|
||||
diploma?: string;
|
||||
documenten?: string;
|
||||
antwoorden?: Record<string, string>;
|
||||
}
|
||||
|
||||
export type RegistratieState =
|
||||
| { tag: 'Invullen'; draft: Draft; cursor: number; errors: Errors; upload: UploadState }
|
||||
| { tag: 'Indienen'; data: ValidRegistratie }
|
||||
| { tag: 'Ingediend'; data: ValidRegistratie; referentie: string }
|
||||
| { tag: 'Mislukt'; data: ValidRegistratie; error: string };
|
||||
|
||||
const emptyDraft: Draft = { antwoorden: {} };
|
||||
export const initial: RegistratieState = {
|
||||
tag: 'Invullen',
|
||||
draft: emptyDraft,
|
||||
cursor: 0,
|
||||
errors: {},
|
||||
upload: initialUpload,
|
||||
};
|
||||
|
||||
/** Which step the cursor currently points at (clamped to the fixed list). */
|
||||
export function currentStep(s: Extract<RegistratieState, { tag: 'Invullen' }>): StepId {
|
||||
return STEPS[Math.min(s.cursor, STEPS.length - 1)];
|
||||
}
|
||||
|
||||
/** Has the user meaningfully started, so it's worth persisting as a Concept? Excludes
|
||||
the automatic BRP address prefill on step 0 — a bare page visit creates nothing.
|
||||
ponytail: an address typed at step 0 without any of these signals is not yet
|
||||
persisted (created once they advance/choose); accepted regression vs. sessionStorage. */
|
||||
export function hasProgress(s: Extract<RegistratieState, { tag: 'Invullen' }>): boolean {
|
||||
const d = s.draft;
|
||||
return (
|
||||
s.cursor > 0 ||
|
||||
!!d.correspondentie ||
|
||||
!!d.email ||
|
||||
!!d.diplomaId ||
|
||||
!!d.beroep ||
|
||||
deliveryRefs(s.upload).some((r) => r.channel === 'digital' && !!r.documentId)
|
||||
);
|
||||
}
|
||||
|
||||
/** Validate every question currently visible in ONE step. Errors keyed per field. */
|
||||
function validateStep(step: StepId, d: Draft, upload: UploadState): Result<Errors, void> {
|
||||
const errors: Errors = {};
|
||||
switch (step) {
|
||||
case 'adres': {
|
||||
if (!d.straat || d.straat.trim() === '')
|
||||
errors.straat = $localize`:@@validation.straat2:Vul een straat en huisnummer in.`;
|
||||
const pc = parsePostcode(d.postcode ?? '');
|
||||
if (!pc.ok) errors.postcode = pc.error;
|
||||
if (!d.woonplaats || d.woonplaats.trim() === '')
|
||||
errors.woonplaats = $localize`:@@validation.woonplaats:Vul een woonplaats in.`;
|
||||
if (!d.correspondentie)
|
||||
errors.correspondentie = $localize`:@@validation.maakKeuze:Maak een keuze.`;
|
||||
// E-mail is only required when 'email' is the chosen channel.
|
||||
if (d.correspondentie === 'email') {
|
||||
const e = parseEmail(d.email ?? '');
|
||||
if (!e.ok) errors.email = e.error;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'beroep': {
|
||||
// A diploma must be chosen (or declared manually); its beroep is then known.
|
||||
if (!d.diplomaId || !d.beroep) {
|
||||
errors.diploma = $localize`:@@validation.diploma:Kies het diploma waarmee u zich wilt registreren, of voer het handmatig in.`;
|
||||
break;
|
||||
}
|
||||
// Every policy question the chosen diploma raised must be answered. Which
|
||||
// questions apply is server-decided (carried in `vraagIds`); we only check
|
||||
// they're answered.
|
||||
const open: Record<string, string> = {};
|
||||
for (const id of d.vraagIds ?? []) {
|
||||
if (!(d.antwoorden[id] ?? '').trim())
|
||||
open[id] = $localize`:@@validation.beantwoordVraag:Beantwoord deze vraag.`;
|
||||
}
|
||||
if (Object.keys(open).length > 0) errors.antwoorden = open;
|
||||
// Required documents for this wizard attach to the beroep step (inline upload).
|
||||
if (!requiredCategoriesSatisfied(upload)) {
|
||||
errors.documenten = $localize`:@@validation.documenten:Lever de verplichte documenten aan (upload of kies "per post nasturen").`;
|
||||
}
|
||||
break;
|
||||
}
|
||||
case 'controle':
|
||||
break; // controle shows a summary; no own fields
|
||||
default:
|
||||
return assertNever(step);
|
||||
}
|
||||
return Object.keys(errors).length > 0 ? err(errors) : ok(undefined);
|
||||
}
|
||||
|
||||
/** Parse the whole wizard into a ValidRegistratie (called on submit). */
|
||||
function validateAll(d: Draft, upload: UploadState): Result<Errors, ValidRegistratie> {
|
||||
const errors: Errors = {};
|
||||
for (const step of STEPS) {
|
||||
const r = validateStep(step, d, upload);
|
||||
if (!r.ok) Object.assign(errors, r.error);
|
||||
}
|
||||
if (Object.keys(errors).length > 0) return err(errors);
|
||||
|
||||
const pc = parsePostcode(d.postcode ?? '');
|
||||
// validateStep guaranteed these parse, but keep the compiler happy.
|
||||
if (!pc.ok || !d.diplomaId || !d.beroep || !d.correspondentie) return err(errors);
|
||||
const email = d.correspondentie === 'email' ? parseEmail(d.email ?? '') : undefined;
|
||||
// Keep only the answers to the questions that actually applied.
|
||||
const vraagIds = d.vraagIds ?? [];
|
||||
const antwoorden = Object.fromEntries(vraagIds.map((id) => [id, d.antwoorden[id] ?? '']));
|
||||
|
||||
return ok({
|
||||
adres: { straat: d.straat!, postcode: pc.value, woonplaats: d.woonplaats! },
|
||||
adresHerkomst: d.adresHerkomst ?? 'handmatig',
|
||||
correspondentie: d.correspondentie,
|
||||
email: email?.ok ? email.value : undefined,
|
||||
diplomaId: d.diplomaId,
|
||||
diplomaHerkomst: d.diplomaHerkomst ?? 'handmatig',
|
||||
beroep: d.beroep,
|
||||
antwoorden,
|
||||
documents: deliveryRefs(upload),
|
||||
});
|
||||
}
|
||||
|
||||
export function setField(s: RegistratieState, key: DraftField, value: string): RegistratieState {
|
||||
if (s.tag !== 'Invullen') return s;
|
||||
const draft: Draft = { ...s.draft, [key]: value };
|
||||
// Editing an address field means the user owns it now — not the BRP copy.
|
||||
if (key === 'straat' || key === 'postcode' || key === 'woonplaats')
|
||||
draft.adresHerkomst = 'handmatig';
|
||||
return { ...s, draft };
|
||||
}
|
||||
|
||||
export function setCorrespondentie(s: RegistratieState, value: Correspondentie): RegistratieState {
|
||||
if (s.tag !== 'Invullen') return s;
|
||||
return { ...s, draft: { ...s.draft, correspondentie: value } };
|
||||
}
|
||||
|
||||
/** Prefill the address from a BRP lookup and flag its origin (PRD §7). */
|
||||
export function prefillAdres(
|
||||
s: RegistratieState,
|
||||
straat: string,
|
||||
postcode: string,
|
||||
woonplaats: string,
|
||||
): RegistratieState {
|
||||
if (s.tag !== 'Invullen') return s;
|
||||
return { ...s, draft: { ...s.draft, straat, postcode, woonplaats, adresHerkomst: 'brp' } };
|
||||
}
|
||||
|
||||
/** Pick a DUO diploma; the beroep is derived from it and the applicable policy
|
||||
questions (`vraagIds`) come with it (both server-computed, passed in). */
|
||||
export function kiesDiploma(
|
||||
s: RegistratieState,
|
||||
diplomaId: string,
|
||||
beroep: string,
|
||||
vraagIds: string[],
|
||||
): RegistratieState {
|
||||
if (s.tag !== 'Invullen') return s;
|
||||
return {
|
||||
...s,
|
||||
draft: { ...s.draft, diplomaId, beroep, vraagIds, diplomaHerkomst: 'duo' },
|
||||
errors: {},
|
||||
};
|
||||
}
|
||||
|
||||
/** Switch to manual diploma entry: the diploma isn't in DUO, so the MAXIMAL
|
||||
policy-question set applies and the entry is flagged handmatig/unverified. The
|
||||
beroep is declared separately (declareerBeroep). */
|
||||
export function kiesHandmatig(s: RegistratieState, vraagIds: string[]): RegistratieState {
|
||||
if (s.tag !== 'Invullen') return s;
|
||||
return {
|
||||
...s,
|
||||
draft: {
|
||||
...s.draft,
|
||||
diplomaId: 'handmatig',
|
||||
beroep: undefined,
|
||||
vraagIds,
|
||||
diplomaHerkomst: 'handmatig',
|
||||
},
|
||||
errors: {},
|
||||
};
|
||||
}
|
||||
|
||||
/** Declare the beroep for a manually-entered diploma (chosen from a fixed list). */
|
||||
export function declareerBeroep(s: RegistratieState, beroep: string): RegistratieState {
|
||||
if (s.tag !== 'Invullen') return s;
|
||||
return { ...s, draft: { ...s.draft, beroep } };
|
||||
}
|
||||
|
||||
export function setAntwoord(s: RegistratieState, vraagId: string, value: string): RegistratieState {
|
||||
if (s.tag !== 'Invullen') return s;
|
||||
return { ...s, draft: { ...s.draft, antwoorden: { ...s.draft.antwoorden, [vraagId]: value } } };
|
||||
}
|
||||
|
||||
export function next(s: RegistratieState): RegistratieState {
|
||||
if (s.tag !== 'Invullen') return s;
|
||||
const r = validateStep(currentStep(s), s.draft, s.upload);
|
||||
if (!r.ok) return { ...s, errors: r.error };
|
||||
return { ...s, cursor: Math.min(s.cursor + 1, STEPS.length - 1), errors: {} };
|
||||
}
|
||||
|
||||
export function back(s: RegistratieState): RegistratieState {
|
||||
if (s.tag !== 'Invullen' || s.cursor === 0) return s;
|
||||
return { ...s, cursor: s.cursor - 1, errors: {} };
|
||||
}
|
||||
|
||||
/** Jump back to an earlier step to correct data (controle → step N). Forward
|
||||
jumps are not allowed (would skip validation). Preserves the draft. */
|
||||
export function gaNaarStap(s: RegistratieState, cursor: number): RegistratieState {
|
||||
if (s.tag !== 'Invullen' || cursor < 0 || cursor >= s.cursor) return s;
|
||||
return { ...s, cursor, errors: {} };
|
||||
}
|
||||
|
||||
export function submit(s: RegistratieState): RegistratieState {
|
||||
if (s.tag !== 'Invullen') return s;
|
||||
const r = validateAll(s.draft, s.upload);
|
||||
return r.ok ? { tag: 'Indienen', data: r.value } : { ...s, errors: r.error };
|
||||
}
|
||||
|
||||
/** Route an upload sub-message through the pure upload reducer (Invullen only). */
|
||||
export function upload(s: RegistratieState, msg: UploadMsg): RegistratieState {
|
||||
if (s.tag !== 'Invullen') return s;
|
||||
return { ...s, upload: reduceUpload(s.upload, msg) };
|
||||
}
|
||||
|
||||
export function resolve(s: RegistratieState, r: Result<string, string>): RegistratieState {
|
||||
if (s.tag !== 'Indienen') return s;
|
||||
return r.ok
|
||||
? { tag: 'Ingediend', data: s.data, referentie: r.value }
|
||||
: { tag: 'Mislukt', data: s.data, error: r.error };
|
||||
}
|
||||
|
||||
export type RegistratieMsg =
|
||||
| { tag: 'SetField'; key: DraftField; value: string }
|
||||
| { tag: 'SetCorrespondentie'; value: Correspondentie }
|
||||
| { tag: 'PrefillAdres'; straat: string; postcode: string; woonplaats: string }
|
||||
| { tag: 'KiesDiploma'; diplomaId: string; beroep: string; vraagIds: string[] }
|
||||
| { tag: 'KiesHandmatig'; vraagIds: string[] }
|
||||
| { tag: 'DeclareerBeroep'; beroep: string }
|
||||
| { tag: 'SetAntwoord'; vraagId: string; value: string }
|
||||
| { tag: 'Next' }
|
||||
| { tag: 'Back' }
|
||||
| { tag: 'GaNaarStap'; cursor: number }
|
||||
| { tag: 'Submit' }
|
||||
| { tag: 'Retry' }
|
||||
| { tag: 'SubmitConfirmed'; referentie: string }
|
||||
| { tag: 'SubmitFailed'; error: string }
|
||||
| { tag: 'Upload'; msg: UploadMsg }
|
||||
| { tag: 'Seed'; state: RegistratieState };
|
||||
|
||||
export function reduce(s: RegistratieState, m: RegistratieMsg): RegistratieState {
|
||||
switch (m.tag) {
|
||||
case 'SetField':
|
||||
return setField(s, m.key, m.value);
|
||||
case 'SetCorrespondentie':
|
||||
return setCorrespondentie(s, m.value);
|
||||
case 'PrefillAdres':
|
||||
return prefillAdres(s, m.straat, m.postcode, m.woonplaats);
|
||||
case 'KiesDiploma':
|
||||
return kiesDiploma(s, m.diplomaId, m.beroep, m.vraagIds);
|
||||
case 'KiesHandmatig':
|
||||
return kiesHandmatig(s, m.vraagIds);
|
||||
case 'DeclareerBeroep':
|
||||
return declareerBeroep(s, m.beroep);
|
||||
case 'SetAntwoord':
|
||||
return setAntwoord(s, m.vraagId, m.value);
|
||||
case 'Next':
|
||||
return next(s);
|
||||
case 'Back':
|
||||
return back(s);
|
||||
case 'GaNaarStap':
|
||||
return gaNaarStap(s, m.cursor);
|
||||
case 'Submit':
|
||||
return submit(s);
|
||||
case 'Retry':
|
||||
return s.tag === 'Mislukt' ? { tag: 'Indienen', data: s.data } : s;
|
||||
case 'SubmitConfirmed':
|
||||
return s.tag === 'Indienen'
|
||||
? { tag: 'Ingediend', data: s.data, referentie: m.referentie }
|
||||
: s;
|
||||
case 'SubmitFailed':
|
||||
return s.tag === 'Indienen' ? { tag: 'Mislukt', data: s.data, error: m.error } : s;
|
||||
case 'Upload':
|
||||
return upload(s, m.msg);
|
||||
case 'Seed':
|
||||
return m.state;
|
||||
default:
|
||||
return assertNever(m);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
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');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,58 @@
|
||||
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.
|
||||
SERVER-OWNED RULE: this now runs on the backend (BFF), which ships the result
|
||||
as `decisions.eligibleForHerregistratie` in the dashboard view. Kept here as
|
||||
the reference implementation + unit test; the frontend no longer calls it. */
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
// #region showcase:union
|
||||
export type RegistrationStatus =
|
||||
| { tag: 'Geregistreerd'; herregistratieDatum: string } // only this variant carries the date
|
||||
| { tag: 'Geschorst'; geschorstTot: string; reden: string }
|
||||
| { tag: 'Doorgehaald'; doorgehaaldOp: string; reden: string };
|
||||
// #endregion showcase:union
|
||||
|
||||
/** 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;
|
||||
}
|
||||
|
||||
/** A note is either a recognised specialism or a plain annotation — a closed set,
|
||||
not an open string, so a typo can't slip through. */
|
||||
export type AantekeningType = 'Specialisme' | 'Aantekening';
|
||||
|
||||
export interface Aantekening {
|
||||
type: AantekeningType;
|
||||
omschrijving: string;
|
||||
datum: string;
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { tasksFromProfile } from './tasks';
|
||||
import { Registration } from './registration';
|
||||
|
||||
const base: Registration = {
|
||||
bigNummer: '12345678901',
|
||||
naam: 'A. Tester',
|
||||
beroep: 'arts',
|
||||
registratiedatum: '2018-01-01',
|
||||
geboortedatum: '1980-01-01',
|
||||
status: { tag: 'Geregistreerd', herregistratieDatum: '2026-12-31' },
|
||||
};
|
||||
|
||||
describe('tasksFromProfile', () => {
|
||||
it('offers herregistratie when the server says eligible, with the formatted deadline', () => {
|
||||
const tasks = tasksFromProfile(base, true);
|
||||
expect(tasks).toHaveLength(1);
|
||||
expect(tasks[0].to).toBe('/herregistratie');
|
||||
expect(tasks[0].description).toContain('31 december 2026');
|
||||
});
|
||||
|
||||
it('offers nothing when the server says not eligible', () => {
|
||||
expect(tasksFromProfile(base, false)).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('surfaces a notice for a suspended registration (independent of eligibility)', () => {
|
||||
const reg: Registration = {
|
||||
...base,
|
||||
status: { tag: 'Geschorst', geschorstTot: '2027-01-01', reden: 'Onderzoek' },
|
||||
};
|
||||
const tasks = tasksFromProfile(reg, false);
|
||||
expect(tasks).toHaveLength(1);
|
||||
expect(tasks[0].title).toContain('geschorst');
|
||||
expect(tasks[0].description).toBe('Onderzoek');
|
||||
});
|
||||
|
||||
it('surfaces a notice for a struck-off registration', () => {
|
||||
const reg: Registration = {
|
||||
...base,
|
||||
status: { tag: 'Doorgehaald', doorgehaaldOp: '2025-01-01', reden: 'Op eigen verzoek' },
|
||||
};
|
||||
const tasks = tasksFromProfile(reg, false);
|
||||
expect(tasks).toHaveLength(1);
|
||||
expect(tasks[0].title).toContain('doorgehaald');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,59 @@
|
||||
import { formatDatumNl } from '@shared/kernel/datum';
|
||||
import { Registration } from './registration';
|
||||
import { herregistratieDeadline } from './registration.policy';
|
||||
|
||||
/**
|
||||
* What the dashboard's "Wat moet ik regelen" list needs. Pure presentation data
|
||||
* derived from the registration — no Angular. Mirrors the shared TaskItem shape.
|
||||
*/
|
||||
export interface PortalTask {
|
||||
title: string;
|
||||
description: string;
|
||||
to: string;
|
||||
actionLabel: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Derive the open tasks for a professional (pure). Eligibility is the server's
|
||||
* decision (`decisions.eligibleForHerregistratie`), passed in — the FE renders it,
|
||||
* it does not recompute the rule (ADR-0001). The deadline is still formatted
|
||||
* client-side for the task copy (presentation, not a rule).
|
||||
*/
|
||||
export function tasksFromProfile(
|
||||
reg: Registration,
|
||||
eligibleForHerregistratie: boolean,
|
||||
): PortalTask[] {
|
||||
const tasks: PortalTask[] = [];
|
||||
|
||||
if (eligibleForHerregistratie) {
|
||||
const deadline = herregistratieDeadline(reg);
|
||||
tasks.push({
|
||||
title: $localize`:@@task.herregistratie.title:Vraag uw herregistratie aan`,
|
||||
description: deadline
|
||||
? $localize`:@@task.herregistratie.deadline:Verleng uw registratie vóór ${formatDatumNl(deadline)}:deadline:.`
|
||||
: $localize`:@@task.herregistratie.nodeadline:U kunt nu uw herregistratie aanvragen.`,
|
||||
to: '/herregistratie',
|
||||
actionLabel: $localize`:@@task.herregistratie.action:Herregistratie aanvragen`,
|
||||
});
|
||||
}
|
||||
|
||||
if (reg.status.tag === 'Geschorst') {
|
||||
tasks.push({
|
||||
title: $localize`:@@task.geschorst.title:Uw registratie is geschorst`,
|
||||
description: reg.status.reden,
|
||||
to: '/registratie',
|
||||
actionLabel: $localize`:@@task.bekijkGegevens.action:Bekijk uw gegevens`,
|
||||
});
|
||||
}
|
||||
|
||||
if (reg.status.tag === 'Doorgehaald') {
|
||||
tasks.push({
|
||||
title: $localize`:@@task.doorgehaald.title:Uw registratie is doorgehaald`,
|
||||
description: reg.status.reden,
|
||||
to: '/registratie',
|
||||
actionLabel: $localize`:@@task.bekijkGegevens.action:Bekijk uw gegevens`,
|
||||
});
|
||||
}
|
||||
|
||||
return tasks;
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { parseBigNummer } from './big-nummer';
|
||||
|
||||
describe('parseBigNummer', () => {
|
||||
it('accepts exactly 11 digits, trimming whitespace', () => {
|
||||
const r = parseBigNummer(' 12345678901 ');
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) expect(r.value).toBe('12345678901');
|
||||
});
|
||||
|
||||
it('rejects wrong length or non-digits', () => {
|
||||
expect(parseBigNummer('').ok).toBe(false);
|
||||
expect(parseBigNummer('1234567890').ok).toBe(false); // 10 digits
|
||||
expect(parseBigNummer('123456789012').ok).toBe(false); // 12 digits
|
||||
expect(parseBigNummer('1234567890a').ok).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,11 @@
|
||||
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($localize`:@@validation.bigNummer:Een BIG-nummer bestaat uit 11 cijfers.`);
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { parseEmail } from './email';
|
||||
|
||||
describe('parseEmail', () => {
|
||||
it('accepts a well-formed address and trims it', () => {
|
||||
const r = parseEmail(' naam@voorbeeld.nl ');
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) expect(r.value).toBe('naam@voorbeeld.nl');
|
||||
});
|
||||
|
||||
it('rejects malformed addresses', () => {
|
||||
expect(parseEmail('').ok).toBe(false);
|
||||
expect(parseEmail('naam').ok).toBe(false);
|
||||
expect(parseEmail('naam@voorbeeld').ok).toBe(false);
|
||||
expect(parseEmail('naam @voorbeeld.nl').ok).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,21 @@
|
||||
import { Brand, Result, ok, err } from '@shared/kernel/fp';
|
||||
|
||||
/**
|
||||
* Value object: an e-mail address. "Parse, don't validate" — an Email is a
|
||||
* distinct type from a raw string, mintable only via parseEmail, so holding one
|
||||
* is proof it is well-formed. Format-only check (the FE keeps format validation
|
||||
* for instant feedback; the backend stays the authority — see ADR-0001).
|
||||
*/
|
||||
export type Email = Brand<string, 'Email'>;
|
||||
|
||||
export function parseEmail(raw: string): Result<string, Email> {
|
||||
const t = raw.trim();
|
||||
// Deliberately lax: a single @ with non-empty, dot-bearing parts. Good enough
|
||||
// for instant feedback; the server re-validates.
|
||||
if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(t)) {
|
||||
return err(
|
||||
$localize`:@@validation.email:Voer een geldig e-mailadres in, bijv. naam@voorbeeld.nl.`,
|
||||
);
|
||||
}
|
||||
return ok(t as Email);
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { parsePostcode } from './postcode';
|
||||
|
||||
describe('parsePostcode', () => {
|
||||
it('normalises to "1234 AB" (uppercase, single space, trimmed)', () => {
|
||||
for (const raw of ['1234ab', '1234 AB', ' 1234ab ', '1234AB']) {
|
||||
const r = parsePostcode(raw);
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) expect(r.value).toBe('1234 AB');
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects malformed postcodes', () => {
|
||||
expect(parsePostcode('').ok).toBe(false);
|
||||
expect(parsePostcode('0234AB').ok).toBe(false); // leading zero
|
||||
expect(parsePostcode('123AB').ok).toBe(false); // 3 digits
|
||||
expect(parsePostcode('1234A').ok).toBe(false); // 1 letter
|
||||
expect(parsePostcode('1234ABC').ok).toBe(false); // 3 letters
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,19 @@
|
||||
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'>;
|
||||
|
||||
// #region showcase:parse
|
||||
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($localize`:@@validation.postcode: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);
|
||||
}
|
||||
// #endregion showcase:parse
|
||||
@@ -0,0 +1,20 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { parseTelefoonnummer } from './telefoonnummer';
|
||||
|
||||
describe('parseTelefoonnummer', () => {
|
||||
it('accepts a 10-digit number starting 0 and strips formatting', () => {
|
||||
const r = parseTelefoonnummer('06 12 34 56 78');
|
||||
expect(r.ok && r.value).toBe('0612345678');
|
||||
});
|
||||
|
||||
it('normalises a +31 prefix to a leading 0', () => {
|
||||
const r = parseTelefoonnummer('+31 6 12345678');
|
||||
expect(r.ok && r.value).toBe('0612345678');
|
||||
});
|
||||
|
||||
it('rejects a too-short number, a non-0 start, and junk', () => {
|
||||
expect(parseTelefoonnummer('12345').ok).toBe(false);
|
||||
expect(parseTelefoonnummer('1612345678').ok).toBe(false);
|
||||
expect(parseTelefoonnummer('nope').ok).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,25 @@
|
||||
import { Brand, Result, ok, err } from '@shared/kernel/fp';
|
||||
|
||||
/**
|
||||
* Value object: a Dutch phone number. "Parse, don't validate" — a Telefoonnummer is
|
||||
* a distinct type from a raw string, mintable only via parseTelefoonnummer, so holding
|
||||
* one is proof it is well-formed. Format-only check (the FE keeps format validation for
|
||||
* instant feedback; the backend stays the authority — see ADR-0001). The parsed value
|
||||
* is normalised to digits (spaces/dashes/parens dropped, a leading +31 → 0).
|
||||
*/
|
||||
export type Telefoonnummer = Brand<string, 'Telefoonnummer'>;
|
||||
|
||||
export function parseTelefoonnummer(raw: string): Result<string, Telefoonnummer> {
|
||||
const digits = raw
|
||||
.trim()
|
||||
.replace(/[\s\-()]/g, '')
|
||||
.replace(/^\+31/, '0');
|
||||
// Deliberately lax: a Dutch number is 10 digits starting 0 (mobile 06 or landline).
|
||||
// Good enough for instant feedback; the server re-validates.
|
||||
if (!/^0\d{9}$/.test(digits)) {
|
||||
return err(
|
||||
$localize`:@@validation.telefoon:Voer een geldig telefoonnummer in, bijv. 0612345678.`,
|
||||
);
|
||||
}
|
||||
return ok(digits as Telefoonnummer);
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { parseUren } from './uren';
|
||||
|
||||
describe('parseUren', () => {
|
||||
it('accepts non-negative whole numbers, including 0', () => {
|
||||
for (const [raw, n] of [
|
||||
['0', 0],
|
||||
[' 40 ', 40],
|
||||
['1000', 1000],
|
||||
] as const) {
|
||||
const r = parseUren(raw);
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) expect(r.value).toBe(n);
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects empty, negative, and non-integer input', () => {
|
||||
expect(parseUren('').ok).toBe(false);
|
||||
expect(parseUren('-1').ok).toBe(false);
|
||||
expect(parseUren('1.5').ok).toBe(false);
|
||||
expect(parseUren('abc').ok).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -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($localize`:@@validation.uren:Vul een geheel aantal in (0 of meer).`);
|
||||
}
|
||||
return ok(n as Uren);
|
||||
}
|
||||
Reference in New Issue
Block a user