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,55 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { ApplicationsAdapter } from '@registratie/infrastructure/applications.adapter';
|
||||
import { AdminCasesStore } from './admin-cases.store';
|
||||
|
||||
const summary = (id: string) => ({
|
||||
id,
|
||||
type: 'registratie',
|
||||
status: { tag: 'Concept', stepIndex: 0, stepCount: 3 },
|
||||
documentIds: [],
|
||||
createdAt: '2026-07-23T10:00:00Z',
|
||||
updatedAt: '2026-07-23T10:00:00Z',
|
||||
owner: '19012345601',
|
||||
});
|
||||
|
||||
function setup(adapter: Partial<ApplicationsAdapter>): AdminCasesStore {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [{ provide: ApplicationsAdapter, useValue: adapter }],
|
||||
});
|
||||
return TestBed.inject(AdminCasesStore);
|
||||
}
|
||||
|
||||
describe('AdminCasesStore', () => {
|
||||
it('loads and parses the cross-owner list', async () => {
|
||||
const store = setup({ listAll: () => Promise.resolve([summary('a'), summary('b')]) });
|
||||
await store.load();
|
||||
const s = store.cases();
|
||||
expect(s.tag).toBe('Success');
|
||||
expect(s.tag === 'Success' && s.value.map((c) => c.id)).toEqual(['a', 'b']);
|
||||
});
|
||||
|
||||
it('deletes optimistically and confirms via the admin endpoint', async () => {
|
||||
const deleteAny = vi.fn().mockResolvedValue(undefined);
|
||||
const store = setup({
|
||||
listAll: () => Promise.resolve([summary('a'), summary('b')]),
|
||||
deleteAny,
|
||||
});
|
||||
await store.load();
|
||||
|
||||
await store.delete('a');
|
||||
expect(deleteAny).toHaveBeenCalledWith('a');
|
||||
const s = store.cases();
|
||||
expect(s.tag === 'Success' && s.value.map((c) => c.id)).toEqual(['b']);
|
||||
});
|
||||
|
||||
it('rolls back the removal when the delete fails', async () => {
|
||||
const deleteAny = vi.fn().mockRejectedValue(new Error('boom'));
|
||||
const store = setup({ listAll: () => Promise.resolve([summary('a')]), deleteAny });
|
||||
await store.load();
|
||||
|
||||
await store.delete('a');
|
||||
const s = store.cases();
|
||||
expect(s.tag === 'Success' && s.value.map((c) => c.id)).toEqual(['a']); // reappears
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,57 @@
|
||||
import { Injectable, inject, signal } from '@angular/core';
|
||||
import { RemoteData } from '@shared/application/remote-data';
|
||||
import { Aanvraag } from '@registratie/domain/aanvraag';
|
||||
import {
|
||||
ApplicationsAdapter,
|
||||
parseApplications,
|
||||
} from '@registratie/infrastructure/applications.adapter';
|
||||
|
||||
type Err = Error | undefined;
|
||||
|
||||
/**
|
||||
* Admin view of ALL cases across owners (WP-36; `cases:manage`) — the back-office
|
||||
* counterpart of the user-facing `ApplicationsStore`. Same shape: one root singleton
|
||||
* owns the list as a writable RemoteData signal, delete removes the row synchronously
|
||||
* (optimistic) and rolls back on error. Admin delete removes any case (any owner,
|
||||
* submitted or not — the server enforces the capability).
|
||||
*/
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class AdminCasesStore {
|
||||
private adapter = inject(ApplicationsAdapter);
|
||||
|
||||
private state = signal<RemoteData<Err, Aanvraag[]>>({ tag: 'Loading' });
|
||||
readonly cases = this.state.asReadonly();
|
||||
|
||||
/** Fetch + parse at the trust boundary, then publish as RemoteData. Keeps the
|
||||
last-good value on a resync (only shows Loading on the first load). */
|
||||
async load() {
|
||||
if (this.state().tag !== 'Success') this.state.set({ tag: 'Loading' });
|
||||
try {
|
||||
const parsed = parseApplications(await this.adapter.listAll());
|
||||
this.state.set(
|
||||
parsed.ok
|
||||
? { tag: 'Success', value: parsed.value }
|
||||
: { tag: 'Failure', error: new Error(parsed.error) },
|
||||
);
|
||||
} catch (e) {
|
||||
this.state.set({ tag: 'Failure', error: e as Error });
|
||||
}
|
||||
}
|
||||
|
||||
reload() {
|
||||
void this.load();
|
||||
}
|
||||
|
||||
/** Delete a case: drop it now (synchronous), then confirm the DELETE; roll back on error. */
|
||||
async delete(id: string) {
|
||||
const before = this.state();
|
||||
if (before.tag === 'Success') {
|
||||
this.state.set({ tag: 'Success', value: before.value.filter((a) => a.id !== id) });
|
||||
}
|
||||
try {
|
||||
await this.adapter.deleteAny(id);
|
||||
} catch {
|
||||
this.state.set(before); // roll back: the row reappears
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,65 @@
|
||||
import { Injectable, inject, signal } from '@angular/core';
|
||||
import { RemoteData } from '@shared/application/remote-data';
|
||||
import { Aanvraag } from '@registratie/domain/aanvraag';
|
||||
import {
|
||||
ApplicationsAdapter,
|
||||
parseApplications,
|
||||
} from '@registratie/infrastructure/applications.adapter';
|
||||
|
||||
type Err = Error | undefined;
|
||||
|
||||
/**
|
||||
* The dashboard's view of the user's applications (aanvragen) — the backend is the
|
||||
* system of record (PRD 0001). One root singleton OWNS the list as a writable
|
||||
* RemoteData signal (CLAUDE.md §3: change state only through methods). Cancel removes
|
||||
* the row SYNCHRONOUSLY, so the block disappears deterministically — no dependence on
|
||||
* change-detection timing, HTTP caching, or a resource `reload()`. `reload()` re-fetches
|
||||
* so a page revisit reflects auto-approval (Concept → In behandeling → Goedgekeurd is
|
||||
* computed server-side on read).
|
||||
*/
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class ApplicationsStore {
|
||||
private adapter = inject(ApplicationsAdapter);
|
||||
|
||||
private state = signal<RemoteData<Err, Aanvraag[]>>({ tag: 'Loading' });
|
||||
readonly applications = this.state.asReadonly();
|
||||
|
||||
constructor() {
|
||||
void this.load();
|
||||
}
|
||||
|
||||
/** Fetch + parse at the trust boundary, then publish as RemoteData. Keeps the
|
||||
last-good value on a resync (only shows Loading on the first load). */
|
||||
async load() {
|
||||
if (this.state().tag !== 'Success') this.state.set({ tag: 'Loading' });
|
||||
try {
|
||||
const parsed = parseApplications(await this.adapter.list());
|
||||
this.state.set(
|
||||
parsed.ok
|
||||
? { tag: 'Success', value: parsed.value }
|
||||
: { tag: 'Failure', error: new Error(parsed.error) },
|
||||
);
|
||||
} catch (e) {
|
||||
this.state.set({ tag: 'Failure', error: e as Error });
|
||||
}
|
||||
}
|
||||
|
||||
/** Re-fetch (e.g. on dashboard revisit) so auto-approval transitions show up. */
|
||||
reload() {
|
||||
void this.load();
|
||||
}
|
||||
|
||||
/** Cancel a Concept: drop it now (synchronous, guaranteed), then confirm the DELETE.
|
||||
No resync — the delete succeeded, so the optimistic removal is authoritative. */
|
||||
async cancel(id: string) {
|
||||
const before = this.state();
|
||||
if (before.tag === 'Success') {
|
||||
this.state.set({ tag: 'Success', value: before.value.filter((a) => a.id !== id) });
|
||||
}
|
||||
try {
|
||||
await this.adapter.cancel(id);
|
||||
} catch {
|
||||
this.state.set(before); // roll back: the block reappears
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import { Injectable, computed, inject, signal } from '@angular/core';
|
||||
import { RemoteData, fromResource, map } from '@shared/application/remote-data';
|
||||
import { Aantekening } from '../domain/registration';
|
||||
import { BigProfile } from '../domain/big-profile';
|
||||
import { HerregistratieDecisions } from '../contracts/dashboard-view.dto';
|
||||
import { BigRegisterAdapter } from '../infrastructure/big-register.adapter';
|
||||
import {
|
||||
DashboardView,
|
||||
DashboardViewAdapter,
|
||||
parseDashboardView,
|
||||
} from '../infrastructure/dashboard-view.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 dashboard data now comes from ONE screen-shaped ("BFF-lite") call that
|
||||
* returns registration + person + server-computed `decisions`. One request → one
|
||||
* consistent snapshot, instead of stitching three independently loading/erroring
|
||||
* resources together client-side. See docs/reference/architecture/0001-bff-lite-decision-dtos.md.
|
||||
*/
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class BigProfileStore {
|
||||
private big = inject(BigRegisterAdapter);
|
||||
private viewAdapter = inject(DashboardViewAdapter);
|
||||
|
||||
private viewRes = this.viewAdapter.dashboardViewResource();
|
||||
private aantekeningenRes = this.big.aantekeningenResource();
|
||||
|
||||
/** The aggregated view, validated at the trust boundary (DTO → domain). */
|
||||
private view = computed<RemoteData<Err, DashboardView>>(() => {
|
||||
const rd = fromResource(this.viewRes);
|
||||
if (rd.tag !== 'Success') return rd;
|
||||
const parsed = parseDashboardView(rd.value);
|
||||
return parsed.ok
|
||||
? { tag: 'Success', value: parsed.value }
|
||||
: { tag: 'Failure', error: new Error(parsed.error) };
|
||||
});
|
||||
|
||||
/** Registration + person, from the single aggregated call. */
|
||||
readonly profile = computed<RemoteData<Err, BigProfile>>(() =>
|
||||
map(this.view(), (v) => v.profile),
|
||||
);
|
||||
|
||||
/** Server-computed decisions (e.g. herregistratie eligibility) — rendered, not recomputed. */
|
||||
readonly decisions = computed<RemoteData<Err, HerregistratieDecisions>>(() =>
|
||||
map(this.view(), (v) => v.decisions),
|
||||
);
|
||||
|
||||
/** Specialisms/notes stay a separate stream (they have their own empty state). */
|
||||
readonly aantekeningen = computed<RemoteData<Err, Aantekening[]>>(() => {
|
||||
const rd = fromResource(this.aantekeningenRes, (v) => !v || v.length === 0);
|
||||
return rd.tag === 'Success' ? { tag: 'Success', value: rd.value ?? [] } : rd;
|
||||
});
|
||||
|
||||
// --- 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.viewRes.reload(); // invalidate: re-fetch the now-updated view (registration + decisions)
|
||||
}
|
||||
rollbackHerregistratie() {
|
||||
this.pending.set(false); // submission failed — undo the optimistic flag
|
||||
}
|
||||
|
||||
// Retry hooks for [data]-fed <app-async> instances (they don't own the resource).
|
||||
reloadProfile() {
|
||||
this.viewRes.reload();
|
||||
}
|
||||
reloadAantekeningen() {
|
||||
this.aantekeningenRes.reload();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,155 @@
|
||||
import { ApplicationRef, signal } from '@angular/core';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import { ApplicationsAdapter } from '@registratie/infrastructure/applications.adapter';
|
||||
import { createDraftSync, DraftSnapshot } from './draft-sync';
|
||||
|
||||
function setup(adapter: Partial<ApplicationsAdapter>) {
|
||||
const navigate = vi.fn().mockResolvedValue(true);
|
||||
TestBed.configureTestingModule({
|
||||
providers: [
|
||||
{ provide: ApplicationsAdapter, useValue: adapter },
|
||||
{ provide: Router, useValue: { navigate } },
|
||||
{ provide: ActivatedRoute, useValue: { snapshot: { queryParamMap: { get: () => null } } } },
|
||||
],
|
||||
});
|
||||
const snap = signal<DraftSnapshot | null>(null);
|
||||
const onResume = vi.fn();
|
||||
const draftSync = TestBed.runInInjectionContext(() =>
|
||||
createDraftSync({
|
||||
type: 'registratie',
|
||||
snapshot: () => snap(),
|
||||
onResume,
|
||||
enabled: () => true,
|
||||
}),
|
||||
);
|
||||
TestBed.inject(ApplicationRef).tick(); // flush the effect's initial run
|
||||
return { draftSync, snap, navigate, onResume };
|
||||
}
|
||||
|
||||
const tick = () => TestBed.inject(ApplicationRef).tick();
|
||||
|
||||
describe('createDraftSync', () => {
|
||||
beforeEach(() => vi.useFakeTimers());
|
||||
afterEach(() => vi.useRealTimers());
|
||||
|
||||
it('coalesces rapid snapshot changes into ONE debounced sync of the latest value', async () => {
|
||||
const create = vi.fn().mockResolvedValue('a1');
|
||||
const syncDraft = vi.fn().mockResolvedValue(undefined);
|
||||
const { snap } = setup({ create, syncDraft });
|
||||
|
||||
snap.set({ draft: { step: 1 }, stepIndex: 0, stepCount: 3, documentIds: [] });
|
||||
tick();
|
||||
snap.set({ draft: { step: 1, x: 'a' }, stepIndex: 0, stepCount: 3, documentIds: [] });
|
||||
tick();
|
||||
snap.set({ draft: { step: 1, x: 'ab' }, stepIndex: 0, stepCount: 3, documentIds: [] });
|
||||
tick();
|
||||
|
||||
// still inside the 600ms debounce window — nothing has synced yet
|
||||
await vi.advanceTimersByTimeAsync(500);
|
||||
expect(syncDraft).not.toHaveBeenCalled();
|
||||
|
||||
await vi.advanceTimersByTimeAsync(200);
|
||||
expect(create).toHaveBeenCalledTimes(1); // one Concept created, not three
|
||||
expect(syncDraft).toHaveBeenCalledTimes(1); // one sync, not three
|
||||
expect(syncDraft).toHaveBeenCalledWith(
|
||||
'a1',
|
||||
expect.objectContaining({ draft: { step: 1, x: 'ab' } }), // the LAST snapshot wins
|
||||
);
|
||||
});
|
||||
|
||||
it('a trailing change after the debounce fires schedules its own sync', async () => {
|
||||
const create = vi.fn().mockResolvedValue('a1');
|
||||
const syncDraft = vi.fn().mockResolvedValue(undefined);
|
||||
const { snap } = setup({ create, syncDraft });
|
||||
|
||||
snap.set({ draft: { step: 1 }, stepIndex: 0, stepCount: 3, documentIds: [] });
|
||||
tick();
|
||||
await vi.advanceTimersByTimeAsync(600);
|
||||
expect(syncDraft).toHaveBeenCalledTimes(1);
|
||||
|
||||
snap.set({ draft: { step: 2 }, stepIndex: 1, stepCount: 3, documentIds: [] });
|
||||
tick();
|
||||
await vi.advanceTimersByTimeAsync(600);
|
||||
expect(syncDraft).toHaveBeenCalledTimes(2);
|
||||
expect(syncDraft).toHaveBeenLastCalledWith('a1', expect.objectContaining({ stepIndex: 1 }));
|
||||
});
|
||||
|
||||
describe('submit', () => {
|
||||
it('resolves ok with the server response on success', async () => {
|
||||
const create = vi.fn().mockResolvedValue('a1');
|
||||
const submit = vi.fn().mockResolvedValue({ id: 'a1', autoApprovable: true });
|
||||
const { draftSync } = setup({ create, submit });
|
||||
|
||||
const r = await draftSync.submit({});
|
||||
expect(r).toEqual({ ok: true, value: { id: 'a1', autoApprovable: true } });
|
||||
expect(submit).toHaveBeenCalledWith('a1', {});
|
||||
});
|
||||
|
||||
it('folds a rejected submit into a Result error, never throwing', async () => {
|
||||
const create = vi.fn().mockResolvedValue('a1');
|
||||
const submit = vi.fn().mockRejectedValue(new Error('boom'));
|
||||
const { draftSync } = setup({ create, submit });
|
||||
|
||||
const r = await draftSync.submit({});
|
||||
expect(r.ok).toBe(false);
|
||||
});
|
||||
|
||||
it('recovers from a create conflict by adopting the existing Concept (WP-35)', async () => {
|
||||
// Server enforces one Concept per type: a stale/cross-tab create is rejected (409),
|
||||
// and ensureId adopts the existing Concept from the list instead of erroring.
|
||||
const create = vi.fn().mockRejectedValue({ status: 409 });
|
||||
const list = vi.fn().mockResolvedValue([
|
||||
{
|
||||
id: 'existing-1',
|
||||
type: 'registratie',
|
||||
status: { tag: 'Concept', stepIndex: 1, stepCount: 3 },
|
||||
createdAt: '2026-07-23T10:00:00Z',
|
||||
updatedAt: '2026-07-23T10:00:00Z',
|
||||
},
|
||||
]);
|
||||
const submit = vi.fn().mockResolvedValue({ id: 'existing-1', autoApprovable: true });
|
||||
const { draftSync } = setup({ create, list, submit });
|
||||
|
||||
const r = await draftSync.submit({});
|
||||
expect(r.ok).toBe(true);
|
||||
expect(submit).toHaveBeenCalledWith('existing-1', {}); // adopted, not a new id
|
||||
});
|
||||
});
|
||||
|
||||
describe('flushPending (CanDeactivate guard / beforeunload)', () => {
|
||||
it('hasPendingSave reflects an armed debounce timer', () => {
|
||||
const { draftSync, snap } = setup({
|
||||
create: vi.fn().mockResolvedValue('a1'),
|
||||
syncDraft: vi.fn().mockResolvedValue(undefined),
|
||||
});
|
||||
expect(draftSync.hasPendingSave()).toBe(false);
|
||||
|
||||
snap.set({ draft: { step: 1 }, stepIndex: 0, stepCount: 3, documentIds: [] });
|
||||
tick(); // the effect arms the 600ms timer
|
||||
expect(draftSync.hasPendingSave()).toBe(true);
|
||||
});
|
||||
|
||||
it('flushPending writes the pending draft immediately, before the debounce fires', async () => {
|
||||
const create = vi.fn().mockResolvedValue('a1');
|
||||
const syncDraft = vi.fn().mockResolvedValue(undefined);
|
||||
const { draftSync, snap } = setup({ create, syncDraft });
|
||||
|
||||
snap.set({ draft: { step: 1 }, stepIndex: 0, stepCount: 3, documentIds: [] });
|
||||
tick();
|
||||
await draftSync.flushPending();
|
||||
|
||||
expect(syncDraft).toHaveBeenCalledTimes(1); // no timer advance needed
|
||||
expect(draftSync.hasPendingSave()).toBe(false); // timer consumed
|
||||
});
|
||||
|
||||
it('flushPending is a no-op when nothing is pending', async () => {
|
||||
const syncDraft = vi.fn().mockResolvedValue(undefined);
|
||||
const { draftSync } = setup({ create: vi.fn().mockResolvedValue('a1'), syncDraft });
|
||||
|
||||
await draftSync.flushPending();
|
||||
expect(syncDraft).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,236 @@
|
||||
import { DestroyRef, effect, inject } from '@angular/core';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { Result } from '@shared/kernel/fp';
|
||||
import { runSubmit, SUBMIT_FAILED } from '@shared/application/submit';
|
||||
import { registerPendingSave } from '@shared/application/pending-saves';
|
||||
import type {
|
||||
SubmitApplicationRequest,
|
||||
SubmitApplicationResponse,
|
||||
} from '@shared/infrastructure/api-client';
|
||||
import { AanvraagType } from '@registratie/domain/aanvraag';
|
||||
import {
|
||||
ApplicationsAdapter,
|
||||
parseApplications,
|
||||
} from '@registratie/infrastructure/applications.adapter';
|
||||
|
||||
/** What a wizard persists per step: the opaque machine snapshot + progress + docs. */
|
||||
export interface DraftSnapshot {
|
||||
draft: unknown;
|
||||
stepIndex: number;
|
||||
stepCount: number;
|
||||
documentIds: string[];
|
||||
}
|
||||
|
||||
export interface DraftSyncDeps {
|
||||
type: AanvraagType;
|
||||
/** The machine snapshot while it's worth persisting; null when not (pristine/done). */
|
||||
snapshot: () => DraftSnapshot | null;
|
||||
/** Seed the machine from a resumed draft. Called at most once, on init, and ONLY
|
||||
with a real draft on a still-pristine machine — see `applyResume`. */
|
||||
onResume: (draft: unknown) => void;
|
||||
/** Draft-sync only runs in the real app — false in Storybook/tests (explicit seed). */
|
||||
enabled: () => boolean;
|
||||
}
|
||||
|
||||
const DEBOUNCE_MS = 600; // ponytail: fixed debounce; tune if the sync feels laggy/chatty.
|
||||
|
||||
/**
|
||||
* The effectful glue that replaces per-wizard sessionStorage with a backend-owned
|
||||
* Concept (PRD 0001, phase D). Instantiated in a field initializer (like
|
||||
* `createStore`/`createUploadController`). Responsibilities:
|
||||
*
|
||||
* - resume: a `?aanvraag=<id>` link wins; otherwise resume the ONE existing Concept of
|
||||
* this type (at most one per type), seeding the machine from its saved draft;
|
||||
* - create-on-first-progress: when no Concept exists, one is created lazily the first
|
||||
* time the wizard reports a non-null snapshot, and its id is stamped into the URL;
|
||||
* - debounced draft sync on every subsequent change.
|
||||
*
|
||||
* Inert without a Router (stories) or when `enabled()` is false — no network, no resume.
|
||||
*/
|
||||
export function createDraftSync(deps: DraftSyncDeps) {
|
||||
const adapter = inject(ApplicationsAdapter);
|
||||
const router = inject(Router, { optional: true });
|
||||
const route = inject(ActivatedRoute, { optional: true });
|
||||
const active = () => deps.enabled() && !!router && !!route;
|
||||
|
||||
let id: string | undefined;
|
||||
let ensuring: Promise<string> | undefined; // in-flight create, so we never create twice
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
// Resolves once resume() has decided whether a Concept of this type already exists;
|
||||
// gates ensureId so a fast typist can't create a duplicate before that lookup lands.
|
||||
let resumeGate: Promise<unknown> = Promise.resolve();
|
||||
|
||||
const ensureId = async (): Promise<string> => {
|
||||
await resumeGate;
|
||||
if (id) return id;
|
||||
ensuring ??= adapter
|
||||
.create(deps.type)
|
||||
// WP-35: one Concept per type is server-enforced. Within a tab the resumeGate
|
||||
// already prevents a second create, but a cross-tab/stale race can still hit the
|
||||
// server's guard (409) — recover by adopting the existing Concept instead of
|
||||
// erroring. Only recover when one actually exists; otherwise surface the failure.
|
||||
.catch(async (e) => {
|
||||
const existing = await findConcept();
|
||||
if (existing) return existing;
|
||||
throw e;
|
||||
})
|
||||
.then((newId) => {
|
||||
id = newId;
|
||||
// Stamp the id into the URL (no navigation) so a reload resumes this Concept.
|
||||
void router!.navigate([], {
|
||||
relativeTo: route!,
|
||||
queryParams: { aanvraag: newId },
|
||||
queryParamsHandling: 'merge',
|
||||
replaceUrl: true,
|
||||
});
|
||||
return newId;
|
||||
});
|
||||
return ensuring;
|
||||
};
|
||||
|
||||
// Apply a resumed draft only when it's safe to: a late lookup must never clobber
|
||||
// progress the user already made while it was in flight, and "start fresh" needs no
|
||||
// dispatch (the machine already starts fresh). snapshot() is non-null once the user
|
||||
// has real progress.
|
||||
const applyResume = (draft: unknown | null) => {
|
||||
if (draft == null || deps.snapshot() != null) return;
|
||||
deps.onResume(draft);
|
||||
};
|
||||
|
||||
const flush = async () => {
|
||||
const snap = deps.snapshot();
|
||||
if (!snap) return;
|
||||
const theId = await ensureId();
|
||||
await adapter.syncDraft(theId, {
|
||||
draft: snap.draft,
|
||||
stepIndex: snap.stepIndex,
|
||||
stepCount: snap.stepCount,
|
||||
documentIds: snap.documentIds,
|
||||
});
|
||||
};
|
||||
|
||||
// One effect watches the snapshot; each change resets a debounce timer. The timer's
|
||||
// callback only does network I/O (never dispatch), so it can't livelock the store.
|
||||
effect(() => {
|
||||
if (!active()) return;
|
||||
const snap = deps.snapshot(); // tracked: fires on every machine change
|
||||
if (!snap) return;
|
||||
if (timer) clearTimeout(timer);
|
||||
// Null the handle when it fires so `hasPendingSave()` reflects "a write is still owed".
|
||||
timer = setTimeout(() => {
|
||||
timer = undefined;
|
||||
void flush();
|
||||
}, DEBOUNCE_MS);
|
||||
});
|
||||
|
||||
inject(DestroyRef).onDestroy(() => timer && clearTimeout(timer));
|
||||
|
||||
// Flush a pending debounced draft write before an in-app route change / unload (see
|
||||
// pending-saves.ts). onDestroy above only cancels the timer — this actually persists it.
|
||||
const hasPendingSave = () => timer !== undefined;
|
||||
const flushPending = async () => {
|
||||
if (timer === undefined) return;
|
||||
clearTimeout(timer);
|
||||
timer = undefined;
|
||||
await flush();
|
||||
};
|
||||
registerPendingSave({ hasPendingSave, flushPending });
|
||||
|
||||
// Attach to a specific Concept id and seed the machine from its draft. A non-Concept
|
||||
// (submitted/gone) id is treated as fresh so it can't reopen as an editable draft.
|
||||
const load = (linked: string): Promise<void> => {
|
||||
id = linked;
|
||||
return adapter
|
||||
.detail(linked)
|
||||
.then((dto) => {
|
||||
if (dto.status && dto.status.tag !== 'Concept') {
|
||||
id = undefined;
|
||||
applyResume(null);
|
||||
return;
|
||||
}
|
||||
applyResume(dto.draft ?? null);
|
||||
})
|
||||
.catch(() => {
|
||||
id = undefined;
|
||||
applyResume(null); // unknown/deleted id → start fresh
|
||||
});
|
||||
};
|
||||
|
||||
// Find the user's existing Concept of this type (at most one), if any.
|
||||
const findConcept = async (): Promise<string | undefined> => {
|
||||
try {
|
||||
const parsed = parseApplications(await adapter.list());
|
||||
return parsed.ok
|
||||
? parsed.value.find((a) => a.type === deps.type && a.status.tag === 'Concept')?.id
|
||||
: undefined;
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
/** True while a debounced draft write is still pending (PendingSave). */
|
||||
hasPendingSave,
|
||||
/** Flush the pending draft write now and await it; no-op when nothing is pending. */
|
||||
flushPending,
|
||||
|
||||
/** Resolve the initial state: a `?aanvraag` link wins; else resume this type's
|
||||
existing Concept; else start fresh (a Concept is created on first progress). */
|
||||
async resume() {
|
||||
let release!: () => void;
|
||||
resumeGate = new Promise<void>((r) => (release = r));
|
||||
try {
|
||||
if (!active()) {
|
||||
applyResume(null);
|
||||
return;
|
||||
}
|
||||
const linked = route!.snapshot.queryParamMap.get('aanvraag');
|
||||
if (linked) {
|
||||
await load(linked);
|
||||
return;
|
||||
}
|
||||
const existing = await findConcept();
|
||||
if (existing) {
|
||||
await load(existing);
|
||||
// Stamp the id into the URL so a reload resumes the same Concept.
|
||||
void router!.navigate([], {
|
||||
relativeTo: route!,
|
||||
queryParams: { aanvraag: existing },
|
||||
queryParamsHandling: 'merge',
|
||||
replaceUrl: true,
|
||||
});
|
||||
return;
|
||||
}
|
||||
applyResume(null);
|
||||
} finally {
|
||||
release();
|
||||
}
|
||||
},
|
||||
|
||||
/** Submit through the aanvraag lifecycle: ensure the Concept exists, then
|
||||
`POST /applications/{id}/submit` (server sets autoApprovable + transitions).
|
||||
Folded into a Result like the old submit-* commands. */
|
||||
submit(body: SubmitApplicationRequest): Promise<Result<string, SubmitApplicationResponse>> {
|
||||
return runSubmit(async () => adapter.submit(await ensureId(), body), SUBMIT_FAILED);
|
||||
},
|
||||
|
||||
/** Restart: discard the current in-progress Concept (delete it) and detach, so a
|
||||
fresh one is created on next progress. Keeps the one-per-type invariant. A
|
||||
submitted id can't be deleted (409, caught) — that submission correctly remains,
|
||||
and detaching still lets the user start a new Concept. */
|
||||
reset() {
|
||||
if (id) {
|
||||
void adapter.cancel(id).catch(() => {}); // Concept → deleted; submitted → 409, kept
|
||||
id = undefined;
|
||||
ensuring = undefined;
|
||||
}
|
||||
if (active())
|
||||
void router!.navigate([], {
|
||||
relativeTo: route!,
|
||||
queryParams: { aanvraag: null },
|
||||
queryParamsHandling: 'merge',
|
||||
replaceUrl: true,
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { Injectable, computed, inject } from '@angular/core';
|
||||
import { RemoteData, fromResource } from '@shared/application/remote-data';
|
||||
import { DuoLookupDto } from '../contracts/duo-diplomas.dto';
|
||||
import { BrpAdapter, parseBrpAddress } from '../infrastructure/brp.adapter';
|
||||
import { DuoAdapter, parseDuoLookup } from '../infrastructure/duo.adapter';
|
||||
|
||||
type Err = Error | undefined;
|
||||
|
||||
/**
|
||||
* Application-layer facade for the registratie wizard's two lookups (BRP address,
|
||||
* DUO diplomas). It owns the httpResources (created here, in the required injection
|
||||
* context), runs the trust-boundary parse, and exposes RemoteData / derived signals
|
||||
* — so the UI reaches the network through application/, never infrastructure/
|
||||
* directly (CLAUDE.md §1: ui → application → domain). Same facade shape as
|
||||
* BigProfileStore.
|
||||
*/
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class RegistratieLookupStore {
|
||||
private brp = inject(BrpAdapter);
|
||||
private duo = inject(DuoAdapter);
|
||||
|
||||
private adresRes = this.brp.adresResource();
|
||||
private diplomasRes = this.duo.diplomasResource();
|
||||
|
||||
/** BRP lookup outcome. A failure or "geen adres" never blocks the wizard — both
|
||||
fall back to manual entry (PRD §7). 'geen' covers both no-address-found and a
|
||||
malformed response; 'fout' is an unreachable BRP. */
|
||||
readonly adresStatus = computed<'laden' | 'gevonden' | 'geen' | 'fout'>(() => {
|
||||
const st = this.adresRes.status();
|
||||
if (st === 'loading' || st === 'reloading') return 'laden';
|
||||
if (st === 'error') return 'fout';
|
||||
const json = this.adresRes.value();
|
||||
const parsed = json !== undefined ? parseBrpAddress(json) : null;
|
||||
return parsed && parsed.ok && parsed.value.gevonden ? 'gevonden' : 'geen';
|
||||
});
|
||||
|
||||
/** The address to prefill the draft with, once BRP resolves with a found address;
|
||||
null otherwise (loading, error, no address, malformed). */
|
||||
readonly prefillAdres = computed<{ straat: string; postcode: string; woonplaats: string } | null>(
|
||||
() => {
|
||||
const json = this.adresRes.value();
|
||||
if (json === undefined) return null;
|
||||
const parsed = parseBrpAddress(json);
|
||||
return parsed.ok && parsed.value.gevonden && parsed.value.adres ? parsed.value.adres : null;
|
||||
},
|
||||
);
|
||||
|
||||
/** The DUO lookup (diplomas + manual fallback), validated at the trust boundary. */
|
||||
readonly duoLookup = computed<RemoteData<Err, DuoLookupDto>>(() => {
|
||||
const rd = fromResource(this.diplomasRes);
|
||||
if (rd.tag !== 'Success') return rd;
|
||||
const parsed = parseDuoLookup(rd.value);
|
||||
return parsed.ok
|
||||
? { tag: 'Success', value: parsed.value }
|
||||
: { tag: 'Failure', error: new Error(parsed.error) };
|
||||
});
|
||||
|
||||
/** Reload the BRP lookup (e.g. when the wizard restarts) so the address re-prefills. */
|
||||
reloadAdres() {
|
||||
this.adresRes.reload();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { Valid } from '@registratie/domain/change-request.machine';
|
||||
import { ChangeRequestAdapter } from '@registratie/infrastructure/change-request.adapter';
|
||||
import { createSubmitChangeRequest } from './submit-change-request';
|
||||
import { parseTelefoonnummer } from '@registratie/domain/value-objects/telefoonnummer';
|
||||
|
||||
const telefoon = parseTelefoonnummer('0612345678');
|
||||
if (!telefoon.ok) throw new Error('fixture phone should parse');
|
||||
|
||||
const data: Valid = { telefoon: telefoon.value };
|
||||
|
||||
function setup(adapter: Partial<ChangeRequestAdapter>) {
|
||||
TestBed.configureTestingModule({
|
||||
providers: [{ provide: ChangeRequestAdapter, useValue: adapter }],
|
||||
});
|
||||
return TestBed.runInInjectionContext(() => createSubmitChangeRequest());
|
||||
}
|
||||
|
||||
describe('createSubmitChangeRequest', () => {
|
||||
it('resolves ok with the referentie on success', async () => {
|
||||
const submit = setup({ changeRequest: () => Promise.resolve('BIG-2026-000123') });
|
||||
const r = await submit(data);
|
||||
expect(r).toEqual({ ok: true, value: 'BIG-2026-000123' });
|
||||
});
|
||||
|
||||
it('folds a rejected call into a Result error, never throwing', async () => {
|
||||
const submit = setup({
|
||||
changeRequest: () => Promise.reject(new Error('network kaput')),
|
||||
});
|
||||
const r = await submit(data);
|
||||
expect(r.ok).toBe(false);
|
||||
});
|
||||
|
||||
it('surfaces a ProblemDetails detail message when the server rejects with one', async () => {
|
||||
const submit = setup({
|
||||
changeRequest: () => Promise.reject({ detail: 'Telefoonnummer is ongeldig.' }),
|
||||
});
|
||||
const r = await submit(data);
|
||||
expect(r).toEqual({ ok: false, error: 'Telefoonnummer is ongeldig.' });
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import { inject } from '@angular/core';
|
||||
import { Result } from '@shared/kernel/fp';
|
||||
import { Valid } from '@registratie/domain/change-request.machine';
|
||||
import { runSubmit, SUBMIT_FAILED } from '@shared/application/submit';
|
||||
import { ChangeRequestAdapter } from '@registratie/infrastructure/change-request.adapter';
|
||||
|
||||
/**
|
||||
* Command factory: binds the change-request adapter (which owns the `ApiClient`)
|
||||
* in an injection context and returns the submit function the form calls. Same
|
||||
* field-initializer shape as `createStore`/`createDraftSync`, so the UI holds an
|
||||
* application command — not the network client. Returns a `Result`, never a thrown
|
||||
* error, so the form's reduce can branch on the outcome.
|
||||
*/
|
||||
export function createSubmitChangeRequest() {
|
||||
const adapter = inject(ChangeRequestAdapter);
|
||||
return (data: Valid): Promise<Result<string, string>> =>
|
||||
runSubmit(() => adapter.changeRequest(data), SUBMIT_FAILED);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
/**
|
||||
* WIRE CONTRACT for the BRP address lookup ("BFF-lite" — one screen-shaped call).
|
||||
*
|
||||
* In production this is GENERATED from the OpenAPI/TypeSpec spec and served by our
|
||||
* own backend, which talks to the BRP behind an adapter. The frontend never sees
|
||||
* the BRP's own wire format. See docs/reference/architecture/0001-bff-lite-decision-dtos.md.
|
||||
*
|
||||
* "Geen adres bekend" is a first-class outcome (`gevonden: false`), not an error —
|
||||
* the wizard falls back to manual entry (PRD §7). Slice 1 ships only the happy
|
||||
* path (gevonden: true).
|
||||
*/
|
||||
export interface BrpAddressDto {
|
||||
gevonden: boolean;
|
||||
adres?: { straat: string; postcode: string; woonplaats: string };
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
/**
|
||||
* WIRE CONTRACT for the dashboard screen — the "BFF-lite" response.
|
||||
*
|
||||
* PURE wire shapes: this file imports NOTHING (CLAUDE.md §1, ADR-0001). Enums are
|
||||
* inlined string-literal unions that describe the wire, not the domain. The
|
||||
* adapter's `parseDashboardView` validates this untrusted shape and MAPS it onto
|
||||
* the FE domain model (Registration/Person/BigProfile) — that map is the
|
||||
* decoupling seam: the wire can change without the domain following.
|
||||
*
|
||||
* In production these types are GENERATED from the OpenAPI/TypeSpec spec (one
|
||||
* source of truth for both sides), and the `decisions` block is computed BY THE
|
||||
* BACKEND — never recomputed on the client. The frontend renders decisions; it
|
||||
* does not own the rules. See docs/reference/architecture/0001-bff-lite-decision-dtos.md.
|
||||
*
|
||||
* One screen-shaped call replaces the previous three (BIG-register + BRP + …),
|
||||
* so the page always sees one consistent snapshot instead of three independently
|
||||
* loading/erroring resources.
|
||||
*/
|
||||
|
||||
/** Registration status on the wire: the discriminant tags as they arrive. */
|
||||
export type RegistrationStatusDto =
|
||||
| { tag: 'Geregistreerd'; herregistratieDatum: string } // ISO date
|
||||
| { tag: 'Geschorst'; geschorstTot: string; reden: string }
|
||||
| { tag: 'Doorgehaald'; doorgehaaldOp: string; reden: string };
|
||||
|
||||
export interface RegistrationDto {
|
||||
bigNummer: string;
|
||||
naam: string;
|
||||
beroep: string;
|
||||
registratiedatum: string; // ISO date
|
||||
geboortedatum: string;
|
||||
status: RegistrationStatusDto;
|
||||
}
|
||||
|
||||
export interface AdresDto {
|
||||
straat: string;
|
||||
postcode: string;
|
||||
woonplaats: string;
|
||||
}
|
||||
|
||||
export interface PersonDto {
|
||||
naam: string;
|
||||
geboortedatum: string; // ISO date
|
||||
adres: AdresDto;
|
||||
}
|
||||
|
||||
/** Server-computed decisions. Rendered by the FE as-is (decision DTO, ADR-0001):
|
||||
the eligibility rule lives on the backend; the optional reason lets the UI
|
||||
explain itself without knowing the rule. */
|
||||
export interface HerregistratieDecisions {
|
||||
eligibleForHerregistratie: boolean;
|
||||
herregistratieReason?: string;
|
||||
}
|
||||
|
||||
export interface DashboardViewDto {
|
||||
registration: RegistrationDto;
|
||||
person: PersonDto;
|
||||
decisions: HerregistratieDecisions;
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
/**
|
||||
* WIRE CONTRACT for the DUO diploma lookup ("BFF-lite" — one screen-shaped call
|
||||
* returning everything the beroep step needs).
|
||||
*
|
||||
* Each diploma carries its server-computed `beroep` (the profession it maps to)
|
||||
* and the `policyQuestions` (geldigheidsvragen) that apply to it. These are
|
||||
* DECISIONS computed by the backend from the diploma's attributes — the frontend
|
||||
* renders them, it does not derive them (decision-DTO pattern, ADR-0001). E.g. an
|
||||
* English-language diploma carries the Dutch-proficiency question.
|
||||
*
|
||||
* `handmatig` is the fallback when the diploma is not in the DUO list: the
|
||||
* professions the user may declare and the MAXIMAL policy-question set that then
|
||||
* applies (a manual diploma is unverified, so the strictest set is used).
|
||||
*/
|
||||
export interface DuoLookupDto {
|
||||
diplomas: DuoDiplomaDto[];
|
||||
handmatig: ManualDiplomaPolicyDto;
|
||||
}
|
||||
|
||||
export interface DuoDiplomaDto {
|
||||
id: string;
|
||||
naam: string;
|
||||
instelling: string;
|
||||
jaar: number;
|
||||
beroep: string; // server-derived profession
|
||||
policyQuestions: PolicyQuestionDto[]; // server-decided geldigheidsvragen
|
||||
}
|
||||
|
||||
export interface ManualDiplomaPolicyDto {
|
||||
beroepen: string[]; // professions the user may declare for a manual diploma
|
||||
policyQuestions: PolicyQuestionDto[]; // maximal set applied to a manual diploma
|
||||
}
|
||||
|
||||
export interface PolicyQuestionDto {
|
||||
id: string;
|
||||
vraag: string;
|
||||
type: 'ja-nee' | 'tekst';
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import {
|
||||
parseAanvraagStatus,
|
||||
parseApplicationSummary,
|
||||
parseApplications,
|
||||
parseApplicationDetail,
|
||||
} from './applications.adapter';
|
||||
|
||||
const concept = {
|
||||
id: 'a1',
|
||||
type: 'registratie',
|
||||
status: { tag: 'Concept', stepIndex: 1, stepCount: 4 },
|
||||
documentIds: [],
|
||||
createdAt: '2026-07-01T10:00:00Z',
|
||||
updatedAt: '2026-07-01T10:05:00Z',
|
||||
};
|
||||
|
||||
describe('parseAanvraagStatus', () => {
|
||||
it('parses each tag with its required fields', () => {
|
||||
expect(parseAanvraagStatus({ tag: 'Concept', stepIndex: 2, stepCount: 4 })).toEqual({
|
||||
ok: true,
|
||||
value: { tag: 'Concept', stepIndex: 2, stepCount: 4 },
|
||||
});
|
||||
expect(parseAanvraagStatus({ tag: 'Ingediend', referentie: 'BIG-1' }).ok).toBe(true);
|
||||
expect(
|
||||
parseAanvraagStatus({ tag: 'InBehandeling', referentie: 'BIG-1', manual: true }).ok,
|
||||
).toBe(true);
|
||||
expect(
|
||||
parseAanvraagStatus({ tag: 'MeerInfoGevraagd', referentie: 'BIG-1', reden: 'diploma?' }).ok,
|
||||
).toBe(true);
|
||||
expect(parseAanvraagStatus({ tag: 'Goedgekeurd', referentie: 'BIG-1' }).ok).toBe(true);
|
||||
expect(
|
||||
parseAanvraagStatus({ tag: 'Afgewezen', referentie: 'BIG-1', reden: 'geen uren' }).ok,
|
||||
).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects a missing status, unknown tag, and wrong-typed fields', () => {
|
||||
expect(parseAanvraagStatus(undefined).ok).toBe(false);
|
||||
expect(parseAanvraagStatus({ tag: 'Onzin' }).ok).toBe(false);
|
||||
expect(parseAanvraagStatus({ tag: 'InBehandeling', referentie: 'BIG-1' }).ok).toBe(false); // manual missing
|
||||
expect(parseAanvraagStatus({ tag: 'Concept', stepIndex: 1 }).ok).toBe(false); // stepCount missing
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseApplicationSummary', () => {
|
||||
it('maps a valid DTO to domain', () => {
|
||||
const r = parseApplicationSummary(concept);
|
||||
expect(r.ok && r.value.type).toBe('registratie');
|
||||
expect(r.ok && r.value.status.tag).toBe('Concept');
|
||||
});
|
||||
|
||||
it('rejects a bad type and non-objects', () => {
|
||||
expect(parseApplicationSummary({ ...concept, type: 'onbekend' }).ok).toBe(false);
|
||||
expect(parseApplicationSummary(null).ok).toBe(false);
|
||||
expect(parseApplicationSummary({ ...concept, id: 42 }).ok).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseApplications / parseApplicationDetail', () => {
|
||||
it('parses a list and fails fast on a bad element', () => {
|
||||
expect(parseApplications([concept, concept]).ok).toBe(true);
|
||||
expect(parseApplications([concept, { ...concept, status: { tag: 'x' } }]).ok).toBe(false);
|
||||
expect(parseApplications({}).ok).toBe(false);
|
||||
});
|
||||
|
||||
it('carries the opaque draft through detail', () => {
|
||||
const r = parseApplicationDetail({ ...concept, draft: { beroep: 'arts' } });
|
||||
expect(r.ok && (r.value.draft as { beroep: string }).beroep).toBe('arts');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,145 @@
|
||||
import { Injectable, inject } from '@angular/core';
|
||||
import { Result, ok, err } from '@shared/kernel/fp';
|
||||
import {
|
||||
ApiClient,
|
||||
AanvraagStatusDto,
|
||||
ApplicationSummaryDto,
|
||||
ApplicationDetailDto,
|
||||
DraftSyncRequest,
|
||||
SubmitApplicationRequest,
|
||||
SubmitApplicationResponse,
|
||||
} from '@shared/infrastructure/api-client';
|
||||
import {
|
||||
Aanvraag,
|
||||
AanvraagDetail,
|
||||
AanvraagStatus,
|
||||
AanvraagType,
|
||||
} from '@registratie/domain/aanvraag';
|
||||
|
||||
/**
|
||||
* Infrastructure adapter for the backend-owned Aanvraag aggregate — the only place
|
||||
* its HTTP lives (ADR-0001 anti-corruption boundary). The list is a resource; the
|
||||
* mutations (create/sync/cancel/submit) are thin commands the ApplicationsStore
|
||||
* orchestrates optimistically. The untrusted response is validated + mapped to
|
||||
* domain by the hand-written parse* boundary below.
|
||||
*/
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class ApplicationsAdapter {
|
||||
private client = inject(ApiClient);
|
||||
|
||||
/** The dashboard's application list (raw DTOs; the store parses at the boundary). */
|
||||
list(): Promise<ApplicationSummaryDto[]> {
|
||||
return this.client.applicationsAll();
|
||||
}
|
||||
|
||||
/** Admin: every case across all owners (WP-36; `cases:manage`). Parsed at the boundary. */
|
||||
listAll(): Promise<ApplicationSummaryDto[]> {
|
||||
return this.client.casesAll();
|
||||
}
|
||||
|
||||
/** Admin: delete ANY case (any owner, submitted or not — WP-36). */
|
||||
deleteAny(id: string): Promise<void> {
|
||||
return this.client.cases(id);
|
||||
}
|
||||
|
||||
detail(id: string): Promise<ApplicationDetailDto> {
|
||||
return this.client.applicationsGET(id);
|
||||
}
|
||||
|
||||
/** Create a Concept for a wizard type; resolves to the new aanvraag id. */
|
||||
create(type: AanvraagType): Promise<string> {
|
||||
return this.client.applicationsPOST({ type }).then((d) => d.id ?? '');
|
||||
}
|
||||
|
||||
/** Draft sync per step (idempotent). Keep it debounced at the call site — it is chatty. */
|
||||
syncDraft(id: string, body: DraftSyncRequest): Promise<void> {
|
||||
return this.client.applicationsPUT(id, body);
|
||||
}
|
||||
|
||||
/** Cancel a Concept (cascades to its unlinked documents server-side). */
|
||||
cancel(id: string): Promise<void> {
|
||||
return this.client.applicationsDELETE(id);
|
||||
}
|
||||
|
||||
submit(id: string, body: SubmitApplicationRequest): Promise<SubmitApplicationResponse> {
|
||||
return this.client.submit(id, body);
|
||||
}
|
||||
}
|
||||
|
||||
const AANVRAAG_TYPES: readonly string[] = ['registratie', 'herregistratie', 'intake'];
|
||||
|
||||
/** Trust-boundary parse of the status union — the tag drives which fields must exist. */
|
||||
export function parseAanvraagStatus(
|
||||
s: AanvraagStatusDto | undefined,
|
||||
): Result<string, AanvraagStatus> {
|
||||
if (!s || typeof s.tag !== 'string') return err('aanvraag: missing status');
|
||||
switch (s.tag) {
|
||||
case 'Concept':
|
||||
if (typeof s.stepIndex !== 'number' || typeof s.stepCount !== 'number')
|
||||
return err('aanvraag: bad Concept status');
|
||||
return ok({ tag: 'Concept', stepIndex: s.stepIndex, stepCount: s.stepCount });
|
||||
case 'Ingediend':
|
||||
if (typeof s.referentie !== 'string') return err('aanvraag: bad Ingediend status');
|
||||
return ok({ tag: 'Ingediend', referentie: s.referentie });
|
||||
case 'InBehandeling':
|
||||
if (typeof s.referentie !== 'string' || typeof s.manual !== 'boolean')
|
||||
return err('aanvraag: bad InBehandeling status');
|
||||
return ok({ tag: 'InBehandeling', referentie: s.referentie, manual: s.manual });
|
||||
case 'MeerInfoGevraagd':
|
||||
if (typeof s.referentie !== 'string' || typeof s.reden !== 'string')
|
||||
return err('aanvraag: bad MeerInfoGevraagd status');
|
||||
return ok({ tag: 'MeerInfoGevraagd', referentie: s.referentie, reden: s.reden });
|
||||
case 'Goedgekeurd':
|
||||
if (typeof s.referentie !== 'string') return err('aanvraag: bad Goedgekeurd status');
|
||||
return ok({ tag: 'Goedgekeurd', referentie: s.referentie });
|
||||
case 'Afgewezen':
|
||||
if (typeof s.referentie !== 'string' || typeof s.reden !== 'string')
|
||||
return err('aanvraag: bad Afgewezen status');
|
||||
return ok({ tag: 'Afgewezen', referentie: s.referentie, reden: s.reden });
|
||||
default:
|
||||
return err(`aanvraag: unknown status tag ${s.tag}`);
|
||||
}
|
||||
}
|
||||
|
||||
function parseCommon(dto: ApplicationSummaryDto): Result<string, Aanvraag> {
|
||||
if (typeof dto.id !== 'string') return err('aanvraag: missing id');
|
||||
if (typeof dto.type !== 'string' || !AANVRAAG_TYPES.includes(dto.type))
|
||||
return err(`aanvraag: bad type ${dto.type}`);
|
||||
if (typeof dto.createdAt !== 'string' || typeof dto.updatedAt !== 'string')
|
||||
return err('aanvraag: missing timestamps');
|
||||
const status = parseAanvraagStatus(dto.status);
|
||||
if (!status.ok) return status;
|
||||
return ok({
|
||||
id: dto.id,
|
||||
type: dto.type as AanvraagType,
|
||||
status: status.value,
|
||||
documentIds: dto.documentIds ?? [],
|
||||
createdAt: dto.createdAt,
|
||||
updatedAt: dto.updatedAt,
|
||||
submittedAt: dto.submittedAt,
|
||||
owner: dto.owner, // only present on the admin cross-owner list (WP-36)
|
||||
});
|
||||
}
|
||||
|
||||
export function parseApplicationSummary(json: unknown): Result<string, Aanvraag> {
|
||||
if (typeof json !== 'object' || json === null) return err('aanvraag: not an object');
|
||||
return parseCommon(json as ApplicationSummaryDto);
|
||||
}
|
||||
|
||||
export function parseApplications(json: unknown): Result<string, Aanvraag[]> {
|
||||
if (!Array.isArray(json)) return err('aanvragen: not an array');
|
||||
const out: Aanvraag[] = [];
|
||||
for (const item of json) {
|
||||
const parsed = parseApplicationSummary(item);
|
||||
if (!parsed.ok) return parsed;
|
||||
out.push(parsed.value);
|
||||
}
|
||||
return ok(out);
|
||||
}
|
||||
|
||||
export function parseApplicationDetail(json: unknown): Result<string, AanvraagDetail> {
|
||||
if (typeof json !== 'object' || json === null) return err('aanvraag: not an object');
|
||||
const base = parseCommon(json as ApplicationDetailDto);
|
||||
if (!base.ok) return base;
|
||||
return ok({ ...base.value, draft: (json as ApplicationDetailDto).draft ?? null });
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { parseAantekening } from './big-register.adapter';
|
||||
|
||||
describe('big-register.adapter parse boundary', () => {
|
||||
it('parses known aantekening types', () => {
|
||||
expect(
|
||||
parseAantekening({ type: 'Specialisme', omschrijving: 'x', datum: '2026-01-01' }),
|
||||
).toEqual({
|
||||
ok: true,
|
||||
value: { type: 'Specialisme', omschrijving: 'x', datum: '2026-01-01' },
|
||||
});
|
||||
expect(parseAantekening({ type: 'Aantekening' })).toEqual({
|
||||
ok: true,
|
||||
value: { type: 'Aantekening', omschrijving: '', datum: '' },
|
||||
});
|
||||
});
|
||||
|
||||
it('rejects an unknown type', () => {
|
||||
expect(parseAantekening({ type: 'Bogus' }).ok).toBe(false);
|
||||
expect(parseAantekening({}).ok).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,46 @@
|
||||
import { Injectable, inject, resource } from '@angular/core';
|
||||
import { Result, ok, err } from '@shared/kernel/fp';
|
||||
import { Aantekening, AantekeningType } from '../domain/registration';
|
||||
import { ApiClient, AantekeningDto } from '@shared/infrastructure/api-client';
|
||||
|
||||
/**
|
||||
* Infrastructure adapter for the BIG-register source. Exposes signal-based
|
||||
* resources (Angular's `resource` over the generated typed client); each returns
|
||||
* a Resource with status()/value()/error()/reload(). Call from an injection
|
||||
* context (a field initializer in the store).
|
||||
*
|
||||
* Note: registration + person are now served via the aggregated dashboard-view
|
||||
* endpoint (see DashboardViewAdapter). Only the notes stream remains separate.
|
||||
*/
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class BigRegisterAdapter {
|
||||
private client = inject(ApiClient);
|
||||
|
||||
aantekeningenResource() {
|
||||
return resource({
|
||||
loader: () =>
|
||||
this.client.notes().then((ns) => {
|
||||
const out: Aantekening[] = [];
|
||||
for (const n of ns) {
|
||||
const parsed = parseAantekening(n);
|
||||
if (!parsed.ok) throw new Error(parsed.error);
|
||||
out.push(parsed.value);
|
||||
}
|
||||
return out;
|
||||
}),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const AANTEKENING_TYPES: readonly AantekeningType[] = ['Specialisme', 'Aantekening'];
|
||||
|
||||
/** Trust-boundary parse: an unrecognized type is an explicit Failure, never a silent cast. */
|
||||
export function parseAantekening(n: AantekeningDto): Result<string, Aantekening> {
|
||||
if (!n.type || !AANTEKENING_TYPES.includes(n.type as AantekeningType))
|
||||
return err(`aantekening: unknown type ${n.type}`);
|
||||
return ok({
|
||||
type: n.type as AantekeningType,
|
||||
omschrijving: n.omschrijving ?? '',
|
||||
datum: n.datum ?? '',
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { parseBrpAddress } from './brp.adapter';
|
||||
|
||||
describe('parseBrpAddress (trust boundary)', () => {
|
||||
it('accepts a found address', () => {
|
||||
const r = parseBrpAddress({
|
||||
gevonden: true,
|
||||
adres: { straat: 'Lange Voorhout 9', postcode: '2514 EA', woonplaats: 'Den Haag' },
|
||||
});
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) expect(r.value.adres?.postcode).toBe('2514 EA');
|
||||
});
|
||||
|
||||
it('accepts "geen adres" (gevonden: false) as a valid outcome', () => {
|
||||
const r = parseBrpAddress({ gevonden: false });
|
||||
expect(r.ok).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects malformed responses', () => {
|
||||
expect(parseBrpAddress(null).ok).toBe(false);
|
||||
expect(parseBrpAddress({}).ok).toBe(false); // missing gevonden
|
||||
expect(parseBrpAddress({ gevonden: true }).ok).toBe(false); // found but no adres
|
||||
expect(parseBrpAddress({ gevonden: true, adres: { straat: 'x' } }).ok).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,40 @@
|
||||
import { Injectable, inject, resource } from '@angular/core';
|
||||
import { Result, ok, err } from '@shared/kernel/fp';
|
||||
import { BrpAddressDto } from '@registratie/contracts/brp-address.dto';
|
||||
import { ApiClient } from '@shared/infrastructure/api-client';
|
||||
|
||||
/**
|
||||
* Infrastructure adapter for the BRP address lookup, reached only through our own
|
||||
* ("BFF-lite") endpoint — the anti-corruption boundary. Data comes from the .NET
|
||||
* backend (`GET /api/brp/address`) via the generated typed client.
|
||||
*/
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class BrpAdapter {
|
||||
private client = inject(ApiClient);
|
||||
|
||||
// The value is untrusted JSON until parseBrpAddress validates it.
|
||||
adresResource() {
|
||||
return resource({ loader: () => this.client.address() });
|
||||
}
|
||||
}
|
||||
|
||||
/** Trust-boundary parse: validate the untrusted response shape. "Geen adres" is a
|
||||
valid outcome (gevonden: false), not a malformed response. ponytail: hand-written;
|
||||
reach for a schema lib once the contract count grows. */
|
||||
export function parseBrpAddress(json: unknown): Result<string, BrpAddressDto> {
|
||||
if (typeof json !== 'object' || json === null) return err('brp-address: not an object');
|
||||
const dto = json as Partial<BrpAddressDto>;
|
||||
if (typeof dto.gevonden !== 'boolean') return err('brp-address: missing/invalid gevonden');
|
||||
if (dto.gevonden) {
|
||||
const a = dto.adres;
|
||||
if (
|
||||
!a ||
|
||||
typeof a.straat !== 'string' ||
|
||||
typeof a.postcode !== 'string' ||
|
||||
typeof a.woonplaats !== 'string'
|
||||
) {
|
||||
return err('brp-address: missing/invalid adres');
|
||||
}
|
||||
}
|
||||
return ok({ gevonden: dto.gevonden, adres: dto.adres });
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { Injectable, inject } from '@angular/core';
|
||||
import { ApiClient } from '@shared/infrastructure/api-client';
|
||||
import { Valid } from '@registratie/domain/change-request.machine';
|
||||
|
||||
/**
|
||||
* Infrastructure adapter for the telefoonwijziging POST (`/api/v1/change-requests`) —
|
||||
* the single place the network client lives for contact changes, so the command
|
||||
* and the UI never touch `ApiClient`. The BRP address is authoritative and not
|
||||
* submitted (WP-34); only the phone number is. Returns the server reference; the
|
||||
* server re-validates and is the authority.
|
||||
*/
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class ChangeRequestAdapter {
|
||||
private client = inject(ApiClient);
|
||||
|
||||
async changeRequest(data: Valid): Promise<string> {
|
||||
const res = await this.client.changeRequests({ telefoon: data.telefoon });
|
||||
return res.referentie ?? '';
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { parseDashboardView } from './dashboard-view.adapter';
|
||||
|
||||
const valid = {
|
||||
registration: {
|
||||
bigNummer: '19012345601',
|
||||
naam: 'Dr. A. de Vries',
|
||||
beroep: 'Arts',
|
||||
registratiedatum: '2012-09-01',
|
||||
geboortedatum: '1985-03-14',
|
||||
status: { tag: 'Geregistreerd', herregistratieDatum: '2027-03-01' },
|
||||
},
|
||||
person: {
|
||||
naam: 'Dr. A. de Vries',
|
||||
geboortedatum: '1985-03-14',
|
||||
adres: { straat: 'X 1', postcode: '2514 EA', woonplaats: 'Den Haag' },
|
||||
},
|
||||
decisions: { eligibleForHerregistratie: true, herregistratieReason: 'within window' },
|
||||
};
|
||||
|
||||
describe('parseDashboardView (trust boundary)', () => {
|
||||
it('maps a valid response into a DashboardView', () => {
|
||||
const r = parseDashboardView(valid);
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) {
|
||||
expect(r.value.profile.registration.bigNummer).toBe('19012345601');
|
||||
expect(r.value.decisions.eligibleForHerregistratie).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('rejects malformed responses instead of trusting them', () => {
|
||||
expect(parseDashboardView(null).ok).toBe(false);
|
||||
expect(parseDashboardView({ ...valid, registration: undefined }).ok).toBe(false);
|
||||
expect(
|
||||
parseDashboardView({ ...valid, decisions: { eligibleForHerregistratie: 'yes' } }).ok,
|
||||
).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,96 @@
|
||||
import { Injectable, inject, resource } from '@angular/core';
|
||||
import { Result, ok, err } from '@shared/kernel/fp';
|
||||
import {
|
||||
DashboardViewDto,
|
||||
HerregistratieDecisions,
|
||||
} from '@registratie/contracts/dashboard-view.dto';
|
||||
import { Registration } from '@registratie/domain/registration';
|
||||
import { Person } from '@registratie/domain/person';
|
||||
import { BigProfile } from '@registratie/domain/big-profile';
|
||||
import { ApiClient } from '@shared/infrastructure/api-client';
|
||||
|
||||
/**
|
||||
* The parsed, frontend-side view: the wire DTO mapped onto our own domain model.
|
||||
* Lives HERE, not in contracts/, because it references domain types — contracts
|
||||
* stays import-free. This split is the decoupling seam (CLAUDE.md §1, ADR-0001).
|
||||
*/
|
||||
export interface DashboardView {
|
||||
profile: BigProfile;
|
||||
decisions: HerregistratieDecisions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Infrastructure adapter for the screen-shaped ("BFF-lite") dashboard endpoint.
|
||||
* ONE call returns registration + person + server-computed decisions. The data
|
||||
* comes from the .NET backend (`GET /api/dashboard-view`) via the generated typed
|
||||
* client; the decisions (e.g. herregistratie eligibility) are computed there.
|
||||
*/
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class DashboardViewAdapter {
|
||||
private client = inject(ApiClient);
|
||||
|
||||
// The value is still untrusted JSON — parseDashboardView validates it at the
|
||||
// boundary and maps DTO → domain before the app uses it.
|
||||
//
|
||||
// SEAM (G5): retry-with-backoff for non-mutating reads wraps the loader here —
|
||||
// e.g. `loader: () => withBackoff(() => this.client.dashboardView())` — since the
|
||||
// adapter is the single place HTTP lives. Reads are safe to retry; MUTATING calls
|
||||
// (the submit-* commands) must NEVER auto-retry — and don't. Manual retry
|
||||
// (resource.reload via <app-async>) covers the UX today, so backoff stays unbuilt.
|
||||
dashboardViewResource() {
|
||||
return resource({ loader: () => this.client.dashboardView() });
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Trust-boundary parse: validate the untrusted response shape and map the DTO
|
||||
* onto our own domain model. Hand-written on purpose — no Zod for a single
|
||||
* contract. ponytail: reach for a schema lib once the contract count grows.
|
||||
*/
|
||||
export function parseDashboardView(json: unknown): Result<string, DashboardView> {
|
||||
if (typeof json !== 'object' || json === null) return err('dashboard-view: not an object');
|
||||
const dto = json as Partial<DashboardViewDto>;
|
||||
|
||||
const reg = dto.registration;
|
||||
if (
|
||||
!reg ||
|
||||
typeof reg.bigNummer !== 'string' ||
|
||||
!reg.status ||
|
||||
typeof reg.status.tag !== 'string'
|
||||
) {
|
||||
return err('dashboard-view: missing/invalid registration');
|
||||
}
|
||||
const person = dto.person;
|
||||
if (!person || !person.adres || typeof person.adres.postcode !== 'string') {
|
||||
return err('dashboard-view: missing/invalid person');
|
||||
}
|
||||
const d = dto.decisions;
|
||||
if (!d || typeof d.eligibleForHerregistratie !== 'boolean') {
|
||||
return err('dashboard-view: missing/invalid decisions');
|
||||
}
|
||||
|
||||
// Map wire → domain. The shapes are identical today, so this reads as an
|
||||
// identity copy — but the TYPES differ (wire DTO vs domain), so the moment the
|
||||
// wire diverges the compiler forces a real mapping here. That's the seam.
|
||||
const registration: Registration = {
|
||||
bigNummer: reg.bigNummer,
|
||||
naam: reg.naam,
|
||||
beroep: reg.beroep,
|
||||
registratiedatum: reg.registratiedatum,
|
||||
geboortedatum: reg.geboortedatum,
|
||||
status: reg.status,
|
||||
};
|
||||
const persoon: Person = {
|
||||
naam: person.naam,
|
||||
geboortedatum: person.geboortedatum,
|
||||
adres: person.adres,
|
||||
};
|
||||
|
||||
return ok({
|
||||
profile: { registration, person: persoon },
|
||||
decisions: {
|
||||
eligibleForHerregistratie: d.eligibleForHerregistratie,
|
||||
herregistratieReason: d.herregistratieReason,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { parseDuoLookup } from './duo.adapter';
|
||||
|
||||
const valid = {
|
||||
diplomas: [
|
||||
{
|
||||
id: 'd1',
|
||||
naam: 'Geneeskunde',
|
||||
instelling: 'Universiteit Leiden',
|
||||
jaar: 2011,
|
||||
beroep: 'Arts',
|
||||
policyQuestions: [],
|
||||
},
|
||||
{
|
||||
id: 'd2',
|
||||
naam: 'Medicine',
|
||||
instelling: 'University of Edinburgh',
|
||||
jaar: 2013,
|
||||
beroep: 'Arts',
|
||||
policyQuestions: [{ id: 'nl-taal', vraag: 'Toon taalvaardigheid', type: 'ja-nee' }],
|
||||
},
|
||||
],
|
||||
handmatig: {
|
||||
beroepen: ['Arts', 'Verpleegkundige'],
|
||||
policyQuestions: [{ id: 'toelichting', vraag: 'Toelichting', type: 'tekst' }],
|
||||
},
|
||||
};
|
||||
|
||||
describe('parseDuoLookup (trust boundary)', () => {
|
||||
it('maps a valid lookup (diplomas + manual fallback)', () => {
|
||||
const r = parseDuoLookup(valid);
|
||||
expect(r.ok).toBe(true);
|
||||
if (r.ok) {
|
||||
expect(r.value.diplomas).toHaveLength(2);
|
||||
expect(r.value.diplomas[1].policyQuestions[0].id).toBe('nl-taal');
|
||||
expect(r.value.handmatig.beroepen).toContain('Verpleegkundige');
|
||||
expect(r.value.handmatig.policyQuestions[0].type).toBe('tekst');
|
||||
}
|
||||
});
|
||||
|
||||
it('accepts an empty diploma list (forces manual entry)', () => {
|
||||
const r = parseDuoLookup({ diplomas: [], handmatig: valid.handmatig });
|
||||
expect(r.ok).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects malformed responses', () => {
|
||||
expect(parseDuoLookup(null).ok).toBe(false);
|
||||
expect(parseDuoLookup({}).ok).toBe(false); // no diplomas
|
||||
expect(parseDuoLookup({ diplomas: [] }).ok).toBe(false); // no handmatig
|
||||
expect(parseDuoLookup({ diplomas: [{ id: 'd1' }], handmatig: valid.handmatig }).ok).toBe(false); // bad diploma
|
||||
expect(
|
||||
parseDuoLookup({
|
||||
diplomas: [],
|
||||
handmatig: {
|
||||
beroepen: ['Arts'],
|
||||
policyQuestions: [{ id: 'x', vraag: 'y', type: 'bogus' }],
|
||||
},
|
||||
}).ok,
|
||||
).toBe(false); // bad question type
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,82 @@
|
||||
import { Injectable, inject, resource } from '@angular/core';
|
||||
import { Result, ok, err } from '@shared/kernel/fp';
|
||||
import {
|
||||
DuoLookupDto,
|
||||
DuoDiplomaDto,
|
||||
PolicyQuestionDto,
|
||||
ManualDiplomaPolicyDto,
|
||||
} from '@registratie/contracts/duo-diplomas.dto';
|
||||
import { ApiClient } from '@shared/infrastructure/api-client';
|
||||
|
||||
/**
|
||||
* Infrastructure adapter for the DUO diploma lookup, reached only through our own
|
||||
* ("BFF-lite") endpoint — the anti-corruption boundary. The response carries the
|
||||
* user's diplomas (each with its server-computed beroep + policy questions) and
|
||||
* the manual-entry fallback policy. The frontend renders; it does not derive.
|
||||
* Data comes from the .NET backend (`GET /api/duo/diplomas`) via the typed client.
|
||||
*/
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class DuoAdapter {
|
||||
private client = inject(ApiClient);
|
||||
|
||||
diplomasResource() {
|
||||
return resource({ loader: () => this.client.diplomas() });
|
||||
}
|
||||
}
|
||||
|
||||
function parseQuestions(json: unknown): PolicyQuestionDto[] | null {
|
||||
if (!Array.isArray(json)) return null;
|
||||
const out: PolicyQuestionDto[] = [];
|
||||
for (const q of json) {
|
||||
if (typeof q !== 'object' || q === null) return null;
|
||||
const p = q as Partial<PolicyQuestionDto>;
|
||||
if (
|
||||
typeof p.id !== 'string' ||
|
||||
typeof p.vraag !== 'string' ||
|
||||
(p.type !== 'ja-nee' && p.type !== 'tekst')
|
||||
)
|
||||
return null;
|
||||
out.push({ id: p.id, vraag: p.vraag, type: p.type });
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Trust-boundary parse: validate the untrusted response shape (diplomas, each
|
||||
with derived beroep + policy questions, plus the manual-entry fallback). */
|
||||
export function parseDuoLookup(json: unknown): Result<string, DuoLookupDto> {
|
||||
if (typeof json !== 'object' || json === null) return err('duo-lookup: not an object');
|
||||
const dto = json as Partial<DuoLookupDto>;
|
||||
if (!Array.isArray(dto.diplomas)) return err('duo-lookup: missing diplomas');
|
||||
|
||||
const diplomas: DuoDiplomaDto[] = [];
|
||||
for (const item of dto.diplomas) {
|
||||
if (typeof item !== 'object' || item === null) return err('duo-lookup: invalid diploma');
|
||||
const d = item as Partial<DuoDiplomaDto>;
|
||||
const vragen = parseQuestions(d.policyQuestions);
|
||||
if (
|
||||
typeof d.id !== 'string' ||
|
||||
typeof d.naam !== 'string' ||
|
||||
typeof d.beroep !== 'string' ||
|
||||
vragen === null
|
||||
) {
|
||||
return err('duo-lookup: missing/invalid diploma fields');
|
||||
}
|
||||
diplomas.push({
|
||||
id: d.id,
|
||||
naam: d.naam,
|
||||
instelling: d.instelling ?? '',
|
||||
jaar: typeof d.jaar === 'number' ? d.jaar : 0,
|
||||
beroep: d.beroep,
|
||||
policyQuestions: vragen,
|
||||
});
|
||||
}
|
||||
|
||||
const hm = dto.handmatig;
|
||||
const hmVragen = hm ? parseQuestions(hm.policyQuestions) : null;
|
||||
if (!hm || !Array.isArray(hm.beroepen) || hmVragen === null) {
|
||||
return err('duo-lookup: missing/invalid handmatig fallback');
|
||||
}
|
||||
const handmatig: ManualDiplomaPolicyDto = { beroepen: hm.beroepen, policyQuestions: hmVragen };
|
||||
|
||||
return ok({ diplomas, handmatig });
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import { Component, computed, input, output } from '@angular/core';
|
||||
import { formatDatumNl } from '@shared/kernel/datum';
|
||||
import { ButtonComponent } from '@shared/ui/button/button.component';
|
||||
import { AlertComponent } from '@shared/ui/alert/alert.component';
|
||||
import { Aanvraag } from '@registratie/domain/aanvraag';
|
||||
import { TYPE_LABELS } from '@registratie/domain/aanvraag-view';
|
||||
import { blockActions } from '@registratie/domain/block-actions';
|
||||
|
||||
/** Organism: a resumable Concept ("lopende aanvraag") on the dashboard, rendered as
|
||||
a CIBG "melding" (warning) with its actions — verwijderen as a link, aanvraag
|
||||
openen as a button. Which actions show is driven by the pure `blockActions(status)`;
|
||||
the block only renders. Submitted/resolved aanvragen are NOT rendered here — they
|
||||
render as CIBG "aanvragen" rows (see application-link + aanvraag-view). */
|
||||
@Component({
|
||||
selector: 'app-aanvraag-block',
|
||||
imports: [ButtonComponent, AlertComponent],
|
||||
styles: [
|
||||
`
|
||||
.actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--rhc-space-max-md);
|
||||
margin-block-start: var(--rhc-space-max-sm);
|
||||
}
|
||||
`,
|
||||
],
|
||||
template: `
|
||||
@if (aanvraag().status.tag === 'Concept') {
|
||||
<app-alert type="warning">
|
||||
<h3 class="h5">{{ typeLabel() }}</h3>
|
||||
<p>{{ conceptText() }}</p>
|
||||
<div class="actions">
|
||||
@if (actions().includes('cancel')) {
|
||||
<app-button variant="subtle" (click)="cancel.emit()" i18n="@@aanvraagBlock.verwijderen"
|
||||
>Verwijderen</app-button
|
||||
>
|
||||
}
|
||||
@if (actions().includes('resume')) {
|
||||
<app-button (click)="resume.emit()" i18n="@@aanvraagBlock.openen"
|
||||
>Aanvraag openen</app-button
|
||||
>
|
||||
}
|
||||
</div>
|
||||
</app-alert>
|
||||
}
|
||||
`,
|
||||
})
|
||||
export class AanvraagBlockComponent {
|
||||
aanvraag = input.required<Aanvraag>();
|
||||
|
||||
resume = output<void>();
|
||||
cancel = output<void>();
|
||||
|
||||
protected typeLabel = computed(() => TYPE_LABELS[this.aanvraag().type]);
|
||||
protected actions = computed(() => blockActions(this.aanvraag().status));
|
||||
|
||||
// ponytail: display-only deadline derived as createdAt + 30 dagen; move to a
|
||||
// server-sent `completeBefore` on the DTO when the expiry rule becomes real.
|
||||
private deadline = computed(() => {
|
||||
const d = new Date(this.aanvraag().createdAt);
|
||||
d.setDate(d.getDate() + 30);
|
||||
return d.toISOString();
|
||||
});
|
||||
|
||||
/** The melding body for a Concept: wizard not finished + complete-before date. */
|
||||
protected conceptText = computed(() => {
|
||||
const s = this.aanvraag().status;
|
||||
if (s.tag !== 'Concept') return '';
|
||||
return $localize`:@@aanvraagBlock.conceptMelding:Deze aanvraag is nog niet volledig afgerond — u bent gebleven bij stap ${s.stepIndex + 1}:stap: van ${s.stepCount}:totaal:. Rond de aanvraag af vóór ${formatDatumNl(this.deadline())}:datum:.`;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import type { Meta, StoryObj } from '@storybook/angular';
|
||||
import { applicationConfig } from '@storybook/angular';
|
||||
import { provideRouter } from '@angular/router';
|
||||
import { AanvraagBlockComponent } from './aanvraag-block.component';
|
||||
import { Aanvraag } from '@registratie/domain/aanvraag';
|
||||
|
||||
const base = {
|
||||
id: 'a1',
|
||||
type: 'registratie',
|
||||
documentIds: [],
|
||||
createdAt: '2026-06-28T10:00:00Z',
|
||||
updatedAt: '2026-06-28T10:05:00Z',
|
||||
submittedAt: '2026-06-28T10:05:00Z',
|
||||
} satisfies Omit<Aanvraag, 'status'>;
|
||||
|
||||
const meta: Meta<AanvraagBlockComponent> = {
|
||||
title: 'Domein/Registratie/Aanvraag Block',
|
||||
component: AanvraagBlockComponent,
|
||||
decorators: [applicationConfig({ providers: [provideRouter([])] })],
|
||||
render: (args) => ({
|
||||
props: args,
|
||||
// A row is an <li> — the keuzelijst styling needs the real list context.
|
||||
template: `<ul class="keuzelijst__list"><app-aanvraag-block [aanvraag]="aanvraag" /></ul>`,
|
||||
}),
|
||||
parameters: {
|
||||
// Structural: app-aanvraag-block's host sits between the keuzelijst <ul> and its <li>
|
||||
// — axe's list/listitem rule needs them adjacent regardless of `display:contents`.
|
||||
// WP-11 (CIBG markup fidelity) reworks this markup; see docs/project/backlog/WP-11-markup-fidelity.md.
|
||||
a11y: { disable: true },
|
||||
},
|
||||
};
|
||||
export default meta;
|
||||
type Story = StoryObj<AanvraagBlockComponent>;
|
||||
|
||||
// One story per status variant; the block renders its own body + actions.
|
||||
// A Concept renders as a CIBG melding (block element), not a keuzelijst <li> — no <ul> wrapper.
|
||||
export const Concept: Story = {
|
||||
args: { aanvraag: { ...base, status: { tag: 'Concept', stepIndex: 1, stepCount: 3 } } },
|
||||
render: (args) => ({ props: args, template: `<app-aanvraag-block [aanvraag]="aanvraag" />` }),
|
||||
};
|
||||
export const InBehandelingAuto: Story = {
|
||||
args: {
|
||||
aanvraag: {
|
||||
...base,
|
||||
status: { tag: 'InBehandeling', referentie: 'BIG-2026-456789', manual: false },
|
||||
},
|
||||
},
|
||||
};
|
||||
export const InBehandelingManual: Story = {
|
||||
args: {
|
||||
aanvraag: {
|
||||
...base,
|
||||
type: 'registratie',
|
||||
status: { tag: 'InBehandeling', referentie: 'BIG-2026-456789', manual: true },
|
||||
},
|
||||
},
|
||||
};
|
||||
export const Goedgekeurd: Story = {
|
||||
args: { aanvraag: { ...base, status: { tag: 'Goedgekeurd', referentie: 'BIG-2026-456789' } } },
|
||||
};
|
||||
export const Afgewezen: Story = {
|
||||
args: {
|
||||
aanvraag: {
|
||||
...base,
|
||||
type: 'herregistratie',
|
||||
status: {
|
||||
tag: 'Afgewezen',
|
||||
referentie: 'BIG-2026-456789',
|
||||
reden: 'Aanvraag afgewezen: geen gewerkte uren geregistreerd.',
|
||||
},
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,74 @@
|
||||
import { Component, computed, inject } from '@angular/core';
|
||||
import { ActivatedRoute } from '@angular/router';
|
||||
import { PageShellComponent } from '@shared/layout/page-shell/page-shell.component';
|
||||
import { SkeletonComponent } from '@shared/ui/skeleton/skeleton.component';
|
||||
import { AlertComponent } from '@shared/ui/alert/alert.component';
|
||||
import { DataBlockComponent } from '@shared/ui/data-block/data-block.component';
|
||||
import { DataRowComponent } from '@shared/ui/data-row/data-row.component';
|
||||
import { ASYNC } from '@shared/ui/async/async.component';
|
||||
import { ApplicationsStore } from '@registratie/application/applications.store';
|
||||
import { Aanvraag } from '@registratie/domain/aanvraag';
|
||||
import { detailRows } from '@registratie/domain/aanvraag-view';
|
||||
|
||||
/** Page: a single aanvraag ("case"). Stub — it renders the aanvraag's known fields
|
||||
(soort, waarvoor, status, referentie, ingediend) in a CIBG Datablock; full case
|
||||
handling is future work. The dashboard "Mijn aanvragen" rows link here. */
|
||||
@Component({
|
||||
selector: 'app-aanvraag-detail-page',
|
||||
imports: [
|
||||
PageShellComponent,
|
||||
SkeletonComponent,
|
||||
AlertComponent,
|
||||
DataBlockComponent,
|
||||
DataRowComponent,
|
||||
...ASYNC,
|
||||
],
|
||||
template: `
|
||||
<app-page-shell
|
||||
i18n-heading="@@aanvraagDetail.heading"
|
||||
heading="Aanvraag"
|
||||
backLink="/dashboard"
|
||||
>
|
||||
<app-async [data]="store.applications()">
|
||||
<ng-template appAsyncLoaded>
|
||||
@if (applications(); as list) {
|
||||
@let a = find(list);
|
||||
@if (a) {
|
||||
<app-data-block
|
||||
i18n-ariaLabel="@@aanvraagDetail.ariaLabel"
|
||||
ariaLabel="Aanvraaggegevens"
|
||||
>
|
||||
@for (row of rows(a); track row.key) {
|
||||
<div app-data-row [key]="row.key" [value]="row.value"></div>
|
||||
}
|
||||
</app-data-block>
|
||||
<app-alert class="app-section" type="info" i18n="@@aanvraagDetail.stub">
|
||||
De volledige afhandeling van deze aanvraag is nog niet beschikbaar in deze POC.
|
||||
</app-alert>
|
||||
} @else {
|
||||
<app-alert type="warning" i18n="@@aanvraagDetail.nietGevonden"
|
||||
>Deze aanvraag is niet gevonden.</app-alert
|
||||
>
|
||||
}
|
||||
}
|
||||
</ng-template>
|
||||
<ng-template appAsyncLoading>
|
||||
<app-skeleton height="2.5rem" [count]="5" />
|
||||
</ng-template>
|
||||
</app-async>
|
||||
</app-page-shell>
|
||||
`,
|
||||
})
|
||||
export class AanvraagDetailPage {
|
||||
protected store = inject(ApplicationsStore);
|
||||
private id = inject(ActivatedRoute).snapshot.paramMap.get('id') ?? '';
|
||||
|
||||
protected find = (list: Aanvraag[]): Aanvraag | undefined => list.find((a) => a.id === this.id);
|
||||
protected rows = detailRows;
|
||||
|
||||
/** See DashboardPage's `profile` for why this narrows via a computed instead of `let-`. */
|
||||
protected readonly applications = computed(() => {
|
||||
const rd = this.store.applications();
|
||||
return rd.tag === 'Success' ? rd.value : undefined;
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,97 @@
|
||||
import { Component, input, output } 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';
|
||||
|
||||
export interface AdresValue {
|
||||
straat: string;
|
||||
postcode: string;
|
||||
woonplaats: string;
|
||||
}
|
||||
export type AdresErrors = Partial<Record<keyof AdresValue, string>>;
|
||||
|
||||
/** Organism: the editable address block (straat / postcode / woonplaats), grouped
|
||||
in a fieldset/legend. Pure & presentational — values in via `value`, errors in
|
||||
via `errors`, every keystroke out via `fieldChange`. No store, no services, no
|
||||
internal state; the container owns the Model and decides what a change means
|
||||
(registratie-wizard dispatches SetField; change-request-form sets its props).
|
||||
Composes the form-field molecule (×3) so labels/error wiring stay consistent. */
|
||||
@Component({
|
||||
selector: 'app-address-fields',
|
||||
imports: [FormsModule, FormFieldComponent, TextInputComponent],
|
||||
// No scoped `fieldset` reset here: the fieldset must keep CIBG's
|
||||
// `.form-horizontal fieldset` grey-box padding/margin. A local `fieldset{padding:0}`
|
||||
// would tie on specificity and (injected later) win, flattening the padding.
|
||||
styles: [
|
||||
`
|
||||
legend {
|
||||
padding: 0;
|
||||
font-weight: var(--rhc-text-font-weight-semi-bold);
|
||||
margin-block-end: var(--rhc-space-max-md);
|
||||
}
|
||||
`,
|
||||
],
|
||||
template: `
|
||||
<fieldset>
|
||||
<legend>{{ legend() }}</legend>
|
||||
<app-form-field
|
||||
i18n-label="@@address.straat"
|
||||
label="Straat en huisnummer"
|
||||
[fieldId]="idPrefix() + '-straat'"
|
||||
required
|
||||
[error]="errors().straat"
|
||||
>
|
||||
<app-text-input
|
||||
[inputId]="idPrefix() + '-straat'"
|
||||
[invalid]="!!errors().straat"
|
||||
[ngModel]="value().straat"
|
||||
(ngModelChange)="fieldChange.emit({ key: 'straat', value: $event })"
|
||||
name="straat"
|
||||
[ngModelOptions]="{ standalone: true }"
|
||||
/>
|
||||
</app-form-field>
|
||||
<app-form-field
|
||||
i18n-label="@@address.postcode"
|
||||
label="Postcode"
|
||||
[fieldId]="idPrefix() + '-postcode'"
|
||||
required
|
||||
[error]="errors().postcode"
|
||||
>
|
||||
<app-text-input
|
||||
[inputId]="idPrefix() + '-postcode'"
|
||||
[invalid]="!!errors().postcode"
|
||||
[ngModel]="value().postcode"
|
||||
(ngModelChange)="fieldChange.emit({ key: 'postcode', value: $event })"
|
||||
name="postcode"
|
||||
i18n-placeholder="@@address.postcodePlaceholder"
|
||||
placeholder="1234 AB"
|
||||
[ngModelOptions]="{ standalone: true }"
|
||||
/>
|
||||
</app-form-field>
|
||||
<app-form-field
|
||||
i18n-label="@@address.woonplaats"
|
||||
label="Woonplaats"
|
||||
[fieldId]="idPrefix() + '-woonplaats'"
|
||||
required
|
||||
[error]="errors().woonplaats"
|
||||
>
|
||||
<app-text-input
|
||||
[inputId]="idPrefix() + '-woonplaats'"
|
||||
[invalid]="!!errors().woonplaats"
|
||||
[ngModel]="value().woonplaats"
|
||||
(ngModelChange)="fieldChange.emit({ key: 'woonplaats', value: $event })"
|
||||
name="woonplaats"
|
||||
[ngModelOptions]="{ standalone: true }"
|
||||
/>
|
||||
</app-form-field>
|
||||
</fieldset>
|
||||
`,
|
||||
})
|
||||
export class AddressFieldsComponent {
|
||||
value = input.required<AdresValue>();
|
||||
errors = input<AdresErrors>({});
|
||||
/** Prefix for field ids/labels — keeps them unique if two blocks ever co-exist. */
|
||||
idPrefix = input('adres');
|
||||
legend = input($localize`:@@address.legend:Adres`);
|
||||
fieldChange = output<{ key: keyof AdresValue; value: string }>();
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import type { Meta, StoryObj } from '@storybook/angular';
|
||||
import { moduleMetadata } from '@storybook/angular';
|
||||
import { AddressFieldsComponent } from './address-fields.component';
|
||||
|
||||
const meta: Meta<AddressFieldsComponent> = {
|
||||
title: 'Domein/Registratie/Address Fields',
|
||||
component: AddressFieldsComponent,
|
||||
decorators: [moduleMetadata({ imports: [AddressFieldsComponent] })],
|
||||
render: (args) => ({
|
||||
props: { ...args, onChange: (e: unknown) => console.log('fieldChange', e) },
|
||||
template: `
|
||||
<app-address-fields [value]="value" [errors]="errors" (fieldChange)="onChange($event)" />`,
|
||||
}),
|
||||
};
|
||||
export default meta;
|
||||
type Story = StoryObj<AddressFieldsComponent>;
|
||||
|
||||
const empty = { straat: '', postcode: '', woonplaats: '' };
|
||||
|
||||
export const Default: Story = { args: { value: empty, errors: {} } };
|
||||
|
||||
export const Prefilled: Story = {
|
||||
args: {
|
||||
value: { straat: 'Stationsplein 1', postcode: '3511 ED', woonplaats: 'Utrecht' },
|
||||
errors: {},
|
||||
},
|
||||
};
|
||||
|
||||
export const WithErrors: Story = {
|
||||
args: {
|
||||
value: { straat: '', postcode: '12', woonplaats: '' },
|
||||
errors: {
|
||||
straat: 'Vul een straat en huisnummer in.',
|
||||
postcode: 'Voer een geldige postcode in, bijv. 1234 AB.',
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -0,0 +1,129 @@
|
||||
import { Component, computed, effect, inject } from '@angular/core';
|
||||
import { PageShellComponent } from '@shared/layout/page-shell/page-shell.component';
|
||||
import { AlertComponent } from '@shared/ui/alert/alert.component';
|
||||
import { ButtonComponent } from '@shared/ui/button/button.component';
|
||||
import { DataBlockComponent } from '@shared/ui/data-block/data-block.component';
|
||||
import { DataRowComponent } from '@shared/ui/data-row/data-row.component';
|
||||
import { ASYNC } from '@shared/ui/async/async.component';
|
||||
import { AccessStore } from '@shared/application/access.store';
|
||||
import { formatDatumNl } from '@shared/kernel/datum';
|
||||
import { Aanvraag } from '@registratie/domain/aanvraag';
|
||||
import { TYPE_LABELS, statusLabel, referentie } from '@registratie/domain/aanvraag-view';
|
||||
import { AdminCasesStore } from '@registratie/application/admin-cases.store';
|
||||
|
||||
/**
|
||||
* Admin page: every case across all owners, with an admin delete (WP-36). Lives in
|
||||
* `registratie` (which owns the Aanvraag aggregate) — the back-office counterpart of the
|
||||
* user's dashboard, reusing the same view labels + trust-boundary parse. Deny-by-default
|
||||
* capability gate (`cases:manage`): a denial alert for non-admins, the list for admins.
|
||||
* Delete is guarded by a native confirm — it is irreversible and may remove submitted cases.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-admin-cases-page',
|
||||
imports: [
|
||||
PageShellComponent,
|
||||
AlertComponent,
|
||||
ButtonComponent,
|
||||
DataBlockComponent,
|
||||
DataRowComponent,
|
||||
...ASYNC,
|
||||
],
|
||||
styles: [
|
||||
`
|
||||
.case {
|
||||
margin-block-end: var(--rhc-space-max-lg);
|
||||
}
|
||||
`,
|
||||
],
|
||||
template: `
|
||||
<app-page-shell [heading]="heading" [intro]="intro" backLink="/dashboard">
|
||||
@if (!access.ready()) {
|
||||
<!-- wait for /me before deciding — avoids flashing the denial to an admin -->
|
||||
} @else if (!canManage()) {
|
||||
<app-alert type="error">{{ deniedText }}</app-alert>
|
||||
} @else {
|
||||
<app-async [data]="store.cases()">
|
||||
<ng-template appAsyncError>
|
||||
<app-alert type="error">{{ failedText }}</app-alert>
|
||||
<app-button variant="secondary" (click)="reload()">{{ retryText }}</app-button>
|
||||
</ng-template>
|
||||
<ng-template appAsyncLoaded>
|
||||
@if (cases().length === 0) {
|
||||
<app-alert type="info">{{ emptyText }}</app-alert>
|
||||
} @else {
|
||||
@for (c of cases(); track c.id) {
|
||||
<div class="case">
|
||||
<app-data-block [heading]="typeLabel(c)" [level]="2">
|
||||
@for (row of rows(c); track row.key) {
|
||||
<div app-data-row [key]="row.key" [value]="row.value"></div>
|
||||
}
|
||||
</app-data-block>
|
||||
<app-button variant="secondary" (click)="confirmDelete(c)">{{
|
||||
deleteText
|
||||
}}</app-button>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
</ng-template>
|
||||
</app-async>
|
||||
}
|
||||
</app-page-shell>
|
||||
`,
|
||||
})
|
||||
export class AdminCasesPage {
|
||||
protected store = inject(AdminCasesStore);
|
||||
protected access = inject(AccessStore);
|
||||
|
||||
protected canManage = computed(() => this.access.can('cases:manage'));
|
||||
protected cases = computed(() => {
|
||||
const rd = this.store.cases();
|
||||
return rd.tag === 'Success' ? rd.value : [];
|
||||
});
|
||||
|
||||
protected heading = $localize`:@@adminCases.heading:Aanvragen beheren`;
|
||||
protected intro = $localize`:@@adminCases.intro:Alle aanvragen in het register. Een aanvraag verwijderen kan niet ongedaan worden gemaakt.`;
|
||||
protected deniedText = $localize`:@@adminCases.denied:U hebt geen rechten om aanvragen te beheren.`;
|
||||
protected failedText = $localize`:@@adminCases.failed:De aanvragen konden niet worden geladen.`;
|
||||
protected emptyText = $localize`:@@adminCases.empty:Er zijn geen aanvragen.`;
|
||||
protected retryText = $localize`:@@adminCases.retry:Opnieuw proberen`;
|
||||
protected deleteText = $localize`:@@adminCases.delete:Verwijderen`;
|
||||
|
||||
private ownerKey = $localize`:@@adminCases.owner:Eigenaar (BSN)`;
|
||||
private statusKey = $localize`:@@adminCases.status:Status`;
|
||||
private refKey = $localize`:@@adminCases.referentie:Referentie`;
|
||||
private ingediendKey = $localize`:@@adminCases.ingediend:Ingediend op`;
|
||||
|
||||
protected typeLabel = (c: Aanvraag) => TYPE_LABELS[c.type];
|
||||
|
||||
/** Key/value rows for one case (owner + lifecycle facts; the type is the block heading). */
|
||||
protected rows(c: Aanvraag): { key: string; value: string }[] {
|
||||
return [
|
||||
{ key: this.ownerKey, value: c.owner ?? '—' },
|
||||
{ key: this.statusKey, value: statusLabel(c.status) },
|
||||
{ key: this.refKey, value: referentie(c.status) || '—' },
|
||||
{ key: this.ingediendKey, value: c.submittedAt ? formatDatumNl(c.submittedAt) : '—' },
|
||||
];
|
||||
}
|
||||
|
||||
private loadRequested = false;
|
||||
constructor() {
|
||||
// Load once the capability resolves to allowed (a 403 GET would be wasted otherwise).
|
||||
// Depends only on canManage() + a plain flag — never the store model (WP-26 loop lesson).
|
||||
effect(() => {
|
||||
if (this.canManage() && !this.loadRequested) {
|
||||
this.loadRequested = true;
|
||||
void this.store.load();
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
protected reload() {
|
||||
void this.store.load();
|
||||
}
|
||||
|
||||
/** Native confirm — no dialog component exists, and admin delete is irreversible. */
|
||||
protected confirmDelete(c: Aanvraag) {
|
||||
const msg = $localize`:@@adminCases.confirm:Deze aanvraag definitief verwijderen?`;
|
||||
if (confirm(msg)) void this.store.delete(c.id);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
import { Component, computed, input } from '@angular/core';
|
||||
import { FormsModule } from '@angular/forms';
|
||||
import { ButtonComponent } from '@shared/ui/button/button.component';
|
||||
import { HeadingComponent } from '@shared/ui/heading/heading.component';
|
||||
import { AlertComponent } from '@shared/ui/alert/alert.component';
|
||||
import { FormFieldComponent } from '@shared/ui/form-field/form-field.component';
|
||||
import { TextInputComponent } from '@shared/ui/text-input/text-input.component';
|
||||
import { DataBlockComponent } from '@shared/ui/data-block/data-block.component';
|
||||
import { DataRowComponent } from '@shared/ui/data-row/data-row.component';
|
||||
import { Adres } from '@registratie/domain/person';
|
||||
import { createStore } from '@shared/application/store';
|
||||
import { whenTag } from '@shared/kernel/fp';
|
||||
import {
|
||||
ChangeRequestState,
|
||||
ChangeRequestMsg,
|
||||
initial,
|
||||
reduce,
|
||||
} from '@registratie/domain/change-request.machine';
|
||||
import { createSubmitChangeRequest } from '@registratie/application/submit-change-request';
|
||||
|
||||
/**
|
||||
* Organism: contact-change (telefoonwijziging) form. The BRP address is authoritative
|
||||
* and shown READ-ONLY (WP-34) — you change your address at the gemeente, not here — so
|
||||
* only the phone number is editable. Uses the SAME idiom as the wizards: all state in
|
||||
* one signal driven by the pure `reduce` (change-request.machine.ts), submitted via a
|
||||
* `submit-*` command returning `Result`. The server re-validates.
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-change-request-form',
|
||||
imports: [
|
||||
FormsModule,
|
||||
ButtonComponent,
|
||||
HeadingComponent,
|
||||
AlertComponent,
|
||||
FormFieldComponent,
|
||||
TextInputComponent,
|
||||
DataBlockComponent,
|
||||
DataRowComponent,
|
||||
],
|
||||
styles: [
|
||||
`
|
||||
.source {
|
||||
color: var(--rhc-color-grijs-700);
|
||||
font-size: var(--rhc-text-font-size-sm);
|
||||
margin-block-end: var(--rhc-space-max-lg);
|
||||
}
|
||||
legend {
|
||||
padding: 0;
|
||||
font-weight: var(--rhc-text-font-weight-semi-bold);
|
||||
margin-block-end: var(--rhc-space-max-md);
|
||||
}
|
||||
`,
|
||||
],
|
||||
template: `
|
||||
@if (state().tag === 'Submitted') {
|
||||
<app-alert type="ok" i18n="@@changeRequest.success">
|
||||
Uw wijziging is ontvangen (referentie {{ referentie() }}). U ontvangt binnen 5 werkdagen
|
||||
bericht.
|
||||
</app-alert>
|
||||
<div class="app-section">
|
||||
<app-button
|
||||
variant="secondary"
|
||||
(click)="dispatch({ tag: 'Reset' })"
|
||||
i18n="@@changeRequest.nieuwe"
|
||||
>Nieuwe wijziging doorgeven</app-button
|
||||
>
|
||||
</div>
|
||||
} @else {
|
||||
<app-heading [level]="2" i18n="@@changeRequest.heading">Contactgegevens wijzigen</app-heading>
|
||||
|
||||
@if (brpAdres(); as a) {
|
||||
<app-data-block class="app-section" [heading]="brpHeading" [level]="2">
|
||||
<div app-data-row [key]="straatLabel" [value]="a.straat"></div>
|
||||
<div app-data-row [key]="postcodeLabel" [value]="a.postcode"></div>
|
||||
<div app-data-row [key]="woonplaatsLabel" [value]="a.woonplaats"></div>
|
||||
</app-data-block>
|
||||
<p class="source" i18n="@@changeRequest.brpAdresBron">
|
||||
Uw adres komt uit de Basisregistratie Personen en kan hier niet worden gewijzigd. Wijzig
|
||||
het bij uw gemeente.
|
||||
</p>
|
||||
}
|
||||
|
||||
<form (ngSubmit)="onSubmit()" class="form-horizontal app-section">
|
||||
<div class="form-header">
|
||||
<div class="form-action">
|
||||
<span class="meta" i18n="@@form.verplichteVelden">* verplichte velden</span>
|
||||
</div>
|
||||
</div>
|
||||
<fieldset>
|
||||
<legend i18n="@@changeRequest.contactLegend">Contactgegevens</legend>
|
||||
<app-form-field
|
||||
i18n-label="@@changeRequest.telefoonLabel"
|
||||
label="Telefoonnummer"
|
||||
fieldId="cr-telefoon"
|
||||
required
|
||||
[error]="errors().telefoon"
|
||||
>
|
||||
<app-text-input
|
||||
inputId="cr-telefoon"
|
||||
[invalid]="!!errors().telefoon"
|
||||
[ngModel]="telefoon()"
|
||||
(ngModelChange)="dispatch({ tag: 'SetField', key: 'telefoon', value: $event })"
|
||||
name="telefoon"
|
||||
i18n-placeholder="@@changeRequest.telefoonPlaceholder"
|
||||
placeholder="0612345678"
|
||||
[ngModelOptions]="{ standalone: true }"
|
||||
/>
|
||||
</app-form-field>
|
||||
</fieldset>
|
||||
|
||||
@if (failedError()) {
|
||||
<app-alert type="error"
|
||||
><ng-container i18n="@@changeRequest.failed">Het indienen is niet gelukt:</ng-container>
|
||||
{{ failedError() }}</app-alert
|
||||
>
|
||||
}
|
||||
|
||||
<app-button type="submit" variant="primary" [disabled]="state().tag === 'Submitting'">
|
||||
{{ state().tag === 'Submitting' ? submitBezigLabel : submitLabel }}
|
||||
</app-button>
|
||||
</form>
|
||||
}
|
||||
`,
|
||||
})
|
||||
export class ChangeRequestFormComponent {
|
||||
// The submit command owns the ApiClient dependency (via the change-request
|
||||
// adapter); the UI holds only this bound command. Field initializer = injection
|
||||
// context, like createStore below.
|
||||
private submit = createSubmitChangeRequest();
|
||||
private store = createStore<ChangeRequestState, ChangeRequestMsg>(initial, reduce);
|
||||
|
||||
/** BRP address, shown read-only. Undefined until the profile loads. */
|
||||
brpAdres = input<Adres | undefined>(undefined);
|
||||
|
||||
/** Optional seed so Storybook / tests can mount any state directly. */
|
||||
seed = input<ChangeRequestState>(initial);
|
||||
|
||||
readonly state = this.store.model;
|
||||
protected dispatch = this.store.dispatch;
|
||||
|
||||
protected readonly submitLabel = $localize`:@@changeRequest.submit:Wijziging indienen`;
|
||||
protected readonly submitBezigLabel = $localize`:@@changeRequest.submitBezig:Bezig met indienen…`;
|
||||
|
||||
// Datablock heading + row keys (data-block/data-row take plain string inputs, so these
|
||||
// are $localize fields, not template i18n). Row keys reuse the existing address.* ids.
|
||||
protected readonly brpHeading = $localize`:@@changeRequest.brpAdresLabel:Adres (BRP)`;
|
||||
protected readonly straatLabel = $localize`:@@address.straat:Straat en huisnummer`;
|
||||
protected readonly postcodeLabel = $localize`:@@address.postcode:Postcode`;
|
||||
protected readonly woonplaatsLabel = $localize`:@@address.woonplaats:Woonplaats`;
|
||||
|
||||
private editing = computed(() => whenTag(this.state(), 'Editing'));
|
||||
protected errors = computed(() => this.editing()?.errors ?? {});
|
||||
protected failedError = computed(() => whenTag(this.state(), 'Failed')?.error ?? '');
|
||||
protected referentie = computed(() => whenTag(this.state(), 'Submitted')?.referentie ?? '');
|
||||
|
||||
/** The phone shown in the field — the live draft while editing, the parsed value
|
||||
while submitting/failed (so the user sees what they sent). */
|
||||
protected telefoon = computed(() => {
|
||||
const s = this.state();
|
||||
if (s.tag === 'Editing') return s.draft.telefoon;
|
||||
if (s.tag === 'Submitting' || s.tag === 'Failed') return s.data.telefoon;
|
||||
return '';
|
||||
});
|
||||
|
||||
constructor() {
|
||||
queueMicrotask(() => this.dispatch({ tag: 'Seed', state: this.seed() }));
|
||||
}
|
||||
|
||||
onSubmit() {
|
||||
this.dispatch({ tag: 'Submit' });
|
||||
this.runIfSubmitting();
|
||||
}
|
||||
|
||||
/** Effect: when we entered Submitting, call the command, then dispatch the outcome. */
|
||||
private async runIfSubmitting() {
|
||||
const s = this.state();
|
||||
if (s.tag !== 'Submitting') return;
|
||||
const r = await this.submit(s.data);
|
||||
if (r.ok) this.dispatch({ tag: 'SubmitConfirmed', referentie: r.value });
|
||||
else this.dispatch({ tag: 'SubmitFailed', error: r.error });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import type { Meta, StoryObj } from '@storybook/angular';
|
||||
import { applicationConfig } from '@storybook/angular';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { ChangeRequestFormComponent } from './change-request-form.component';
|
||||
import { provideApiClient } from '@shared/infrastructure/api-client.provider';
|
||||
import { Telefoonnummer } from '@registratie/domain/value-objects/telefoonnummer';
|
||||
|
||||
const brpAdres = { straat: 'Lange Voorhout 9', postcode: '2514 EA', woonplaats: 'Den Haag' };
|
||||
const validData = { telefoon: '0612345678' as Telefoonnummer };
|
||||
|
||||
const meta: Meta<ChangeRequestFormComponent> = {
|
||||
title: 'Domein/Registratie/Change Request Form',
|
||||
component: ChangeRequestFormComponent,
|
||||
// The form injects ApiClient (over HttpClient) for the submit command.
|
||||
decorators: [applicationConfig({ providers: [provideHttpClient(), provideApiClient()] })],
|
||||
args: { brpAdres },
|
||||
};
|
||||
export default meta;
|
||||
type Story = StoryObj<ChangeRequestFormComponent>;
|
||||
|
||||
// One render per state of the machine.
|
||||
export const Empty: Story = {
|
||||
args: { seed: { tag: 'Editing', draft: { telefoon: '' }, errors: {} } },
|
||||
};
|
||||
export const WithErrors: Story = {
|
||||
args: {
|
||||
seed: {
|
||||
tag: 'Editing',
|
||||
draft: { telefoon: 'nope' },
|
||||
errors: { telefoon: 'Voer een geldig telefoonnummer in, bijv. 0612345678.' },
|
||||
},
|
||||
},
|
||||
};
|
||||
export const Submitting: Story = { args: { seed: { tag: 'Submitting', data: validData } } };
|
||||
export const Submitted: Story = {
|
||||
args: { seed: { tag: 'Submitted', data: validData, referentie: 'BIG-2026-123456' } },
|
||||
};
|
||||
export const Failed: Story = {
|
||||
args: { seed: { tag: 'Failed', data: validData, error: 'Netwerkfout' } },
|
||||
};
|
||||
@@ -0,0 +1,335 @@
|
||||
import { Component, computed, inject } from '@angular/core';
|
||||
import { Router } from '@angular/router';
|
||||
import { PageShellComponent } from '@shared/layout/page-shell/page-shell.component';
|
||||
import { HeadingComponent } from '@shared/ui/heading/heading.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 { DataBlockComponent } from '@shared/ui/data-block/data-block.component';
|
||||
import { TaskListComponent } from '@shared/ui/task-list/task-list.component';
|
||||
import { ApplicationListComponent } from '@shared/ui/application-list/application-list.component';
|
||||
import { ApplicationLinkComponent } from '@shared/ui/application-link/application-link.component';
|
||||
import { ASYNC } from '@shared/ui/async/async.component';
|
||||
import { AccessStore } from '@shared/application/access.store';
|
||||
import { FeatureFlagStore } from '@shared/application/feature-flags.store';
|
||||
import { FLAG_INSCHRIJVING_OPEN } from '@shared/domain/feature-flag';
|
||||
import { ADMIN_LINKS } from '../../shell/nav.config';
|
||||
import { RegistrationSummaryComponent } from '@registratie/ui/registration-summary/registration-summary.component';
|
||||
import { RegistrationTableComponent } from '@registratie/ui/registration-table/registration-table.component';
|
||||
import { AanvraagBlockComponent } from '@registratie/ui/aanvraag-block/aanvraag-block.component';
|
||||
import { BigProfileStore } from '@registratie/application/big-profile.store';
|
||||
import { ApplicationsStore } from '@registratie/application/applications.store';
|
||||
import { Registration } from '@registratie/domain/registration';
|
||||
import { Aanvraag, AanvraagType } from '@registratie/domain/aanvraag';
|
||||
import { submittedRow } from '@registratie/domain/aanvraag-view';
|
||||
import { tasksFromProfile } from '@registratie/domain/tasks';
|
||||
|
||||
/** Page:"Mijn overzicht" — the portal home, following the NL Design System
|
||||
"Mijn omgeving" pattern (side nav +"Wat moet ik regelen" +"Mijn zaken"). */
|
||||
@Component({
|
||||
selector: 'app-dashboard-page',
|
||||
imports: [
|
||||
PageShellComponent,
|
||||
HeadingComponent,
|
||||
AlertComponent,
|
||||
SkeletonComponent,
|
||||
DataRowComponent,
|
||||
DataBlockComponent,
|
||||
TaskListComponent,
|
||||
ApplicationListComponent,
|
||||
ApplicationLinkComponent,
|
||||
...ASYNC,
|
||||
RegistrationSummaryComponent,
|
||||
RegistrationTableComponent,
|
||||
AanvraagBlockComponent,
|
||||
],
|
||||
template: `
|
||||
<app-page-shell
|
||||
i18n-heading="@@dashboard.heading"
|
||||
heading="Mijn overzicht"
|
||||
i18n-intro="@@dashboard.intro"
|
||||
intro="Welkom in uw persoonlijke omgeving van het BIG-register. Hier ziet u uw registratie en regelt u uw zaken."
|
||||
>
|
||||
<div class="app-stack">
|
||||
@if (aanvragen().length) {
|
||||
<section>
|
||||
@for (a of concepten(); track a.id) {
|
||||
<app-aanvraag-block
|
||||
animate.enter="app-item-enter"
|
||||
animate.leave="app-item-leave"
|
||||
[aanvraag]="a"
|
||||
(resume)="resume(a)"
|
||||
(cancel)="cancelAanvraag(a)"
|
||||
/>
|
||||
}
|
||||
@if (ingediend().length) {
|
||||
<app-heading [level]="2" class="app-section" i18n="@@dashboard.mijnAanvragen"
|
||||
>Mijn aanvragen</app-heading
|
||||
>
|
||||
<app-application-list>
|
||||
@for (a of ingediend(); track a.id) {
|
||||
@let row = submittedRow(a);
|
||||
<li
|
||||
app-application-link
|
||||
animate.enter="app-item-enter"
|
||||
animate.leave="app-item-leave"
|
||||
[heading]="row.heading"
|
||||
[subtitle]="row.subtitle"
|
||||
[status]="row.status"
|
||||
[to]="'/aanvraag/' + a.id"
|
||||
></li>
|
||||
}
|
||||
</app-application-list>
|
||||
}
|
||||
</section>
|
||||
}
|
||||
|
||||
@if (store.pendingHerregistratie()) {
|
||||
<app-alert type="info" i18n="@@dashboard.pendingHerregistratie"
|
||||
>Uw herregistratie-aanvraag is in behandeling.</app-alert
|
||||
>
|
||||
}
|
||||
|
||||
<app-async [data]="store.profile()" (retryClicked)="store.reloadProfile()">
|
||||
<ng-template appAsyncLoaded>
|
||||
@if (profile(); as p) {
|
||||
@let tasks = tasksFor(p.registration);
|
||||
|
||||
<section>
|
||||
@if (tasks.length) {
|
||||
<app-task-list
|
||||
class="app-section"
|
||||
i18n-listHeading="@@dashboard.watMoetIkRegelen"
|
||||
listHeading="Wat moet ik regelen"
|
||||
[tasks]="tasks"
|
||||
/>
|
||||
} @else {
|
||||
<app-heading [level]="2" i18n="@@dashboard.watMoetIkRegelen"
|
||||
>Wat moet ik regelen</app-heading
|
||||
>
|
||||
<p class="app-text-subtle" i18n="@@dashboard.nietsOpenstaan">
|
||||
U heeft op dit moment niets openstaan.
|
||||
</p>
|
||||
}
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<app-heading [level]="2" i18n="@@dashboard.mijnRegistratie"
|
||||
>Mijn registratie</app-heading
|
||||
>
|
||||
<div class="app-section">
|
||||
<app-registration-summary [reg]="p.registration" />
|
||||
</div>
|
||||
<app-data-block
|
||||
class="app-section"
|
||||
i18n-heading="@@dashboard.persoonsgegevens"
|
||||
heading="Persoonsgegevens (BRP)"
|
||||
>
|
||||
<div
|
||||
app-data-row
|
||||
i18n-key="@@dashboard.straat"
|
||||
key="Straat"
|
||||
[value]="p.person.adres.straat"
|
||||
></div>
|
||||
<div
|
||||
app-data-row
|
||||
i18n-key="@@dashboard.postcode"
|
||||
key="Postcode"
|
||||
[value]="p.person.adres.postcode"
|
||||
></div>
|
||||
<div
|
||||
app-data-row
|
||||
i18n-key="@@dashboard.woonplaats"
|
||||
key="Woonplaats"
|
||||
[value]="p.person.adres.woonplaats"
|
||||
></div>
|
||||
</app-data-block>
|
||||
</section>
|
||||
}
|
||||
</ng-template>
|
||||
<ng-template appAsyncLoading>
|
||||
<app-skeleton height="2.5rem" [count]="6" />
|
||||
</ng-template>
|
||||
</app-async>
|
||||
|
||||
<section>
|
||||
<app-heading [level]="2" i18n="@@dashboard.specialismen"
|
||||
>Specialismen en aantekeningen</app-heading
|
||||
>
|
||||
<div class="app-section">
|
||||
<app-async [data]="store.aantekeningen()" (retryClicked)="store.reloadAantekeningen()">
|
||||
<ng-template appAsyncLoaded>
|
||||
@if (aantekeningen(); as r) {
|
||||
<app-registration-table [rows]="r" />
|
||||
}
|
||||
</ng-template>
|
||||
<ng-template appAsyncLoading>
|
||||
<app-skeleton height="2.5rem" [count]="3" />
|
||||
</ng-template>
|
||||
<ng-template appAsyncEmpty>
|
||||
<p class="app-text-subtle" i18n="@@dashboard.geenSpecialismen">
|
||||
U heeft nog geen specialismen of aantekeningen.
|
||||
</p>
|
||||
</ng-template>
|
||||
</app-async>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section>
|
||||
<app-heading [level]="2" i18n="@@dashboard.watWiltUDoen">Wat wilt u doen?</app-heading>
|
||||
<app-application-list class="app-section">
|
||||
@for (a of acties(); track a.to) {
|
||||
<li
|
||||
app-application-link
|
||||
[heading]="a.titel"
|
||||
[subtitle]="a.tekst"
|
||||
[cta]="a.actie"
|
||||
[to]="a.to"
|
||||
></li>
|
||||
}
|
||||
</app-application-list>
|
||||
</section>
|
||||
|
||||
@if (adminLinks().length) {
|
||||
<section>
|
||||
<app-heading [level]="2" i18n="@@dashboard.beheer">Beheer</app-heading>
|
||||
<app-application-list class="app-section">
|
||||
@for (link of adminLinks(); track link.to) {
|
||||
<li
|
||||
app-application-link
|
||||
[heading]="link.label"
|
||||
[subtitle]="link.description"
|
||||
[to]="link.to"
|
||||
></li>
|
||||
}
|
||||
</app-application-list>
|
||||
</section>
|
||||
}
|
||||
</div>
|
||||
</app-page-shell>
|
||||
`,
|
||||
})
|
||||
export class DashboardPage {
|
||||
protected store = inject(BigProfileStore);
|
||||
private apps = inject(ApplicationsStore);
|
||||
private access = inject(AccessStore);
|
||||
private flags = inject(FeatureFlagStore);
|
||||
private router = inject(Router);
|
||||
|
||||
/** Admin pages the current principal may reach — capability-gated (never role-derived),
|
||||
the same source + filter the site header uses. Empty for a non-admin → section hidden. */
|
||||
protected adminLinks = computed(() => ADMIN_LINKS.filter((l) => this.access.can(l.cap)));
|
||||
|
||||
/** Pure view mapping for a submitted aanvraag → CIBG aanvragen-row fields. */
|
||||
protected submittedRow = submittedRow;
|
||||
|
||||
constructor() {
|
||||
// Re-fetch on each visit so server-computed auto-approval transitions show up
|
||||
// (Concept → In behandeling → Goedgekeurd after the processing window).
|
||||
this.apps.reload();
|
||||
}
|
||||
|
||||
/** The user's applications, sorted Concept → In behandeling → resolved. Empty →
|
||||
the"Mijn aanvragen" section is hidden (see template). */
|
||||
protected aanvragen = computed<Aanvraag[]>(() => {
|
||||
const rd = this.apps.applications();
|
||||
if (rd.tag !== 'Success') return [];
|
||||
const order: Record<Aanvraag['status']['tag'], number> = {
|
||||
Concept: 0,
|
||||
Ingediend: 1,
|
||||
InBehandeling: 1,
|
||||
MeerInfoGevraagd: 1,
|
||||
Goedgekeurd: 2,
|
||||
Afgewezen: 2,
|
||||
};
|
||||
return rd.value.slice().sort((a, b) => order[a.status.tag] - order[b.status.tag]);
|
||||
});
|
||||
/** A Concept ("lopende aanvraag") renders as a melding above the list; the rest
|
||||
as keuzelijst items — the two shapes need different HTML contexts. */
|
||||
protected concepten = computed(() => this.aanvragen().filter((a) => a.status.tag === 'Concept'));
|
||||
protected ingediend = computed(() => this.aanvragen().filter((a) => a.status.tag !== 'Concept'));
|
||||
|
||||
private readonly resumeRoutes: Record<AanvraagType, string> = {
|
||||
registratie: '/registreren',
|
||||
herregistratie: '/herregistratie',
|
||||
intake: '/intake',
|
||||
};
|
||||
protected resume(a: Aanvraag) {
|
||||
void this.router.navigate([this.resumeRoutes[a.type]], { queryParams: { aanvraag: a.id } });
|
||||
}
|
||||
protected cancelAanvraag(a: Aanvraag) {
|
||||
void this.apps.cancel(a.id);
|
||||
}
|
||||
|
||||
/** Server-computed eligibility (rendered, not recomputed). */
|
||||
private readonly eligible = computed(() => {
|
||||
const d = this.store.decisions();
|
||||
return d.tag === 'Success' && d.value.eligibleForHerregistratie;
|
||||
});
|
||||
|
||||
protected tasksFor(reg: Registration) {
|
||||
return tasksFromProfile(reg, this.eligible());
|
||||
}
|
||||
|
||||
/** Typed narrowing for the `<app-async>` loaded slot — `<ng-template>`'s own
|
||||
context can't inherit a generic from a sibling host input (Angular only infers
|
||||
a structural directive's type parameter from an input on that same node), so
|
||||
the Success value is unwrapped here instead of through `let-`. */
|
||||
protected readonly profile = computed(() => {
|
||||
const rd = this.store.profile();
|
||||
return rd.tag === 'Success' ? rd.value : undefined;
|
||||
});
|
||||
protected readonly aantekeningen = computed(() => {
|
||||
const rd = this.store.aantekeningen();
|
||||
return rd.tag === 'Success' ? rd.value : undefined;
|
||||
});
|
||||
|
||||
/** Primary transactional actions, as an "aanvragen" list (see CIBG's
|
||||
componenten/aanvragen). The core portal sections live in the header nav now;
|
||||
the teaching pages (concepts/brief) are only reachable from here. */
|
||||
private readonly allActies = [
|
||||
{
|
||||
to: '/registreren',
|
||||
titel: $localize`:@@dashboard.actie.inschrijven.titel:Inschrijven`,
|
||||
tekst: $localize`:@@dashboard.actie.inschrijven.tekst:Schrijf u in in het BIG-register via de registratiewizard.`,
|
||||
actie: $localize`:@@dashboard.actie.inschrijven.actie:Start inschrijving`,
|
||||
},
|
||||
{
|
||||
to: '/herregistratie',
|
||||
titel: $localize`:@@dashboard.actie.herregistratie.titel:Herregistratie aanvragen`,
|
||||
tekst: $localize`:@@dashboard.actie.herregistratie.tekst:Verleng uw registratie voor de komende periode.`,
|
||||
actie: $localize`:@@dashboard.actie.herregistratie.actie:Vraag aan`,
|
||||
},
|
||||
{
|
||||
to: '/intake',
|
||||
titel: $localize`:@@dashboard.actie.intake.titel:Herregistratie-intake`,
|
||||
tekst: $localize`:@@dashboard.actie.intake.tekst:Vragenlijst met vertakkingen.`,
|
||||
actie: $localize`:@@dashboard.actie.intake.actie:Start intake`,
|
||||
},
|
||||
{
|
||||
to: '/registratie',
|
||||
titel: $localize`:@@dashboard.actie.wijzigen.titel:Gegevens wijzigen`,
|
||||
tekst: $localize`:@@dashboard.actie.wijzigen.tekst:Bekijk uw gegevens of geef een wijziging door.`,
|
||||
actie: $localize`:@@dashboard.actie.wijzigen.actie:Bekijk gegevens`,
|
||||
},
|
||||
{
|
||||
to: '/concepts',
|
||||
titel: $localize`:@@dashboard.actie.concepten.titel:Functionele patronen`,
|
||||
tekst: $localize`:@@dashboard.actie.concepten.tekst:Bekijk de FP/TEA-bouwstenen van deze POC.`,
|
||||
actie: $localize`:@@dashboard.actie.concepten.actie:Bekijk patronen`,
|
||||
},
|
||||
{
|
||||
to: '/brief',
|
||||
titel: $localize`:@@dashboard.actie.brief.titel:Brief opstellen`,
|
||||
tekst: $localize`:@@dashboard.actie.brief.tekst:Stel een brief samen uit vaste en vrije onderdelen.`,
|
||||
actie: $localize`:@@dashboard.actie.brief.actie:Start brief`,
|
||||
},
|
||||
];
|
||||
|
||||
/** Hide the "Inschrijven" action when self-service registration is flagged off (WP-47). */
|
||||
protected readonly acties = computed(() =>
|
||||
this.allActies.filter(
|
||||
(a) => a.to !== '/registreren' || this.flags.enabled(FLAG_INSCHRIJVING_OPEN),
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,645 @@
|
||||
import { Component, computed, effect, inject, input, untracked } 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 { RadioGroupComponent, JA_NEE } from '@shared/ui/radio-group/radio-group.component';
|
||||
import { ButtonComponent } from '@shared/ui/button/button.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 { DataBlockComponent } from '@shared/ui/data-block/data-block.component';
|
||||
import { ReviewSectionComponent } from '@shared/ui/review-section/review-section.component';
|
||||
import { ConfirmationComponent } from '@shared/ui/confirmation/confirmation.component';
|
||||
import {
|
||||
WizardShellComponent,
|
||||
WizardError,
|
||||
WizardStatus,
|
||||
naarStapLabel,
|
||||
} from '@shared/layout/wizard-shell/wizard-shell.component';
|
||||
import { ASYNC } from '@shared/ui/async/async.component';
|
||||
import { AddressFieldsComponent } from '@registratie/ui/address-fields/address-fields.component';
|
||||
import { createStore } from '@shared/application/store';
|
||||
import { whenTag } from '@shared/kernel/fp';
|
||||
import { RemoteData } from '@shared/application/remote-data';
|
||||
import { RegistratieLookupStore } from '@registratie/application/registratie-lookup.store';
|
||||
import { DuoLookupDto, PolicyQuestionDto } from '@registratie/contracts/duo-diplomas.dto';
|
||||
import {
|
||||
RegistratieState,
|
||||
RegistratieMsg,
|
||||
Draft,
|
||||
DraftField,
|
||||
Correspondentie,
|
||||
StepId,
|
||||
initial,
|
||||
reduce,
|
||||
hasProgress,
|
||||
STEPS,
|
||||
} from '@registratie/domain/registratie-wizard.machine';
|
||||
import { createDraftSync } from '@registratie/application/draft-sync';
|
||||
import { DocumentUploadComponent } from '@shared/ui/upload/document-upload/document-upload.component';
|
||||
import { createUploadController } from '@shared/upload/upload-controller';
|
||||
import { UploadAdapter } from '@shared/upload/upload.adapter';
|
||||
import { UploadState, initialUpload, deliveryRefs } from '@shared/upload/upload.machine';
|
||||
|
||||
const KANALEN = [
|
||||
{ value: 'email', label: $localize`:@@registratie.kanaalEmail:E-mail` },
|
||||
{ value: 'post', label: $localize`:@@registratie.kanaalPost:Post` },
|
||||
];
|
||||
const HANDMATIG = '__handmatig__'; // sentinel option:"my diploma isn't listed"
|
||||
/** The server-owned geldigheidsvraag whose"ja" answer requires a Dutch-taalvaardigheid
|
||||
upload (proof of the confirmed B2 level). Stable id shared with the backend. */
|
||||
const NL_TAALVAARDIGHEID_VRAAG = 'nl-taalvaardigheid';
|
||||
|
||||
/** Organism: the BIG-registration wizard. All state lives in one signal driven by
|
||||
the pure `reduce` (registratie-wizard.machine.ts). The BRP address prefills the
|
||||
draft via an effect; the DUO diploma list renders through <app-async>; choosing
|
||||
a diploma reveals its server-derived beroep. The draft is persisted to the
|
||||
backend as a Concept aanvraag (createDraftSync) so a reload — or a"Verder gaan"
|
||||
from the dashboard via `?aanvraag=<id>` — resumes progress. Built from existing
|
||||
atoms/molecules. */
|
||||
@Component({
|
||||
selector: 'app-registratie-wizard',
|
||||
imports: [
|
||||
FormsModule,
|
||||
FormFieldComponent,
|
||||
TextInputComponent,
|
||||
RadioGroupComponent,
|
||||
ButtonComponent,
|
||||
AlertComponent,
|
||||
SkeletonComponent,
|
||||
DataRowComponent,
|
||||
DataBlockComponent,
|
||||
ReviewSectionComponent,
|
||||
ConfirmationComponent,
|
||||
WizardShellComponent,
|
||||
AddressFieldsComponent,
|
||||
DocumentUploadComponent,
|
||||
...ASYNC,
|
||||
],
|
||||
template: `
|
||||
<app-wizard-shell
|
||||
[steps]="stepLabels"
|
||||
[current]="cursor()"
|
||||
[stepTitle]="stepTitle()"
|
||||
i18n-processName="@@regWizard.processName"
|
||||
processName="Inschrijven in het BIG-register"
|
||||
[status]="shellStatus()"
|
||||
[primaryLabel]="primaryLabel()"
|
||||
[canGoBack]="cursor() > 0"
|
||||
[errors]="errorList()"
|
||||
[errorMessage]="errorMessage()"
|
||||
i18n-submittingLabel="@@regWizard.submitting"
|
||||
submittingLabel="Uw registratie wordt verwerkt…"
|
||||
(primary)="onPrimary()"
|
||||
(back)="dispatch({ tag: 'Back' })"
|
||||
(cancel)="restart()"
|
||||
(retry)="onRetry()"
|
||||
(goToStep)="dispatch({ tag: 'GaNaarStap', cursor: $event })"
|
||||
>
|
||||
@switch (step()) {
|
||||
@case ('adres') {
|
||||
@if (adresStatus() === 'laden') {
|
||||
<app-skeleton height="2.5rem" [count]="4" />
|
||||
} @else {
|
||||
@switch (adresStatus()) {
|
||||
@case ('gevonden') {
|
||||
<app-alert type="info" i18n="@@regWizard.brpGevonden"
|
||||
>Vooraf ingevuld op basis van de BRP. Controleer en pas zo nodig aan.</app-alert
|
||||
>
|
||||
}
|
||||
@case ('geen') {
|
||||
<app-alert type="warning" i18n="@@regWizard.brpGeen"
|
||||
>We vonden geen adres in de BRP. Vul uw adres hieronder handmatig in.</app-alert
|
||||
>
|
||||
}
|
||||
@case ('fout') {
|
||||
<app-alert type="warning" i18n="@@regWizard.brpFout"
|
||||
>We konden de BRP nu niet bereiken. Vul uw adres hieronder handmatig
|
||||
in.</app-alert
|
||||
>
|
||||
}
|
||||
}
|
||||
<app-address-fields
|
||||
[value]="{
|
||||
straat: draft().straat ?? '',
|
||||
postcode: draft().postcode ?? '',
|
||||
woonplaats: draft().woonplaats ?? '',
|
||||
}"
|
||||
[errors]="{
|
||||
straat: err('straat'),
|
||||
postcode: err('postcode'),
|
||||
woonplaats: err('woonplaats'),
|
||||
}"
|
||||
(fieldChange)="set($event.key, $event.value)"
|
||||
/>
|
||||
<fieldset>
|
||||
<app-form-field
|
||||
i18n-label="@@regWizard.correspondentieLabel"
|
||||
label="Hoe wilt u correspondentie ontvangen?"
|
||||
fieldId="correspondentie"
|
||||
required
|
||||
[error]="err('correspondentie')"
|
||||
>
|
||||
<app-radio-group
|
||||
name="correspondentie"
|
||||
[options]="kanalen"
|
||||
[invalid]="!!err('correspondentie')"
|
||||
[ngModel]="draft().correspondentie ?? ''"
|
||||
(ngModelChange)="setKanaal($event)"
|
||||
/>
|
||||
</app-form-field>
|
||||
</fieldset>
|
||||
@if (draft().correspondentie === 'email') {
|
||||
<fieldset>
|
||||
<app-form-field
|
||||
i18n-label="@@regWizard.emailLabel"
|
||||
label="E-mailadres"
|
||||
fieldId="email"
|
||||
required
|
||||
[error]="err('email')"
|
||||
>
|
||||
<app-text-input
|
||||
inputId="email"
|
||||
type="email"
|
||||
[invalid]="!!err('email')"
|
||||
[ngModel]="draft().email ?? ''"
|
||||
(ngModelChange)="set('email', $event)"
|
||||
name="email"
|
||||
i18n-placeholder="@@regWizard.emailPlaceholder"
|
||||
placeholder="naam@voorbeeld.nl"
|
||||
/>
|
||||
</app-form-field>
|
||||
</fieldset>
|
||||
}
|
||||
}
|
||||
}
|
||||
@case ('beroep') {
|
||||
<app-async [data]="lookupRd()">
|
||||
<ng-template appAsyncLoaded>
|
||||
@if (duoData(); as data) {
|
||||
<fieldset>
|
||||
<app-form-field
|
||||
i18n-label="@@regWizard.diplomaLabel"
|
||||
label="Kies het diploma waarmee u zich wilt registreren"
|
||||
fieldId="diploma"
|
||||
required
|
||||
[error]="err('diploma')"
|
||||
>
|
||||
<app-radio-group
|
||||
name="diploma"
|
||||
[options]="diplomaOptions(data)"
|
||||
[invalid]="!!err('diploma')"
|
||||
[ngModel]="diplomaKeuze()"
|
||||
(ngModelChange)="onDiplomaKeuze(data, $event)"
|
||||
/>
|
||||
</app-form-field>
|
||||
</fieldset>
|
||||
|
||||
@if (handmatigActief()) {
|
||||
<app-alert type="warning" i18n="@@regWizard.handmatigWaarschuwing"
|
||||
>Een handmatig ingevoerd diploma kan niet automatisch worden geverifieerd. Kies
|
||||
uw beroep en beantwoord de aanvullende vragen; uw aanvraag wordt daarna
|
||||
handmatig beoordeeld.</app-alert
|
||||
>
|
||||
<fieldset>
|
||||
<app-form-field
|
||||
i18n-label="@@regWizard.beroepLabel"
|
||||
label="Voor welk beroep wilt u zich registreren?"
|
||||
fieldId="hm-beroep"
|
||||
[error]="err('diploma')"
|
||||
>
|
||||
<app-radio-group
|
||||
name="hm-beroep"
|
||||
[options]="beroepOptions(data)"
|
||||
[invalid]="!!err('diploma')"
|
||||
[ngModel]="draft().beroep ?? ''"
|
||||
(ngModelChange)="dispatch({ tag: 'DeclareerBeroep', beroep: $event })"
|
||||
/>
|
||||
</app-form-field>
|
||||
</fieldset>
|
||||
} @else if (draft().beroep) {
|
||||
<app-data-block class="app-section">
|
||||
<div
|
||||
app-data-row
|
||||
i18n-key="@@regWizard.beroepAfgeleid"
|
||||
key="Beroep (afgeleid uit diploma)"
|
||||
[value]="draft().beroep ?? ''"
|
||||
></div>
|
||||
</app-data-block>
|
||||
}
|
||||
|
||||
@if (actieveVragen(data).length) {
|
||||
<fieldset>
|
||||
@for (q of actieveVragen(data); track q.id) {
|
||||
<app-form-field
|
||||
[label]="q.vraag"
|
||||
[fieldId]="'vraag-' + q.id"
|
||||
[error]="vraagErr(q.id)"
|
||||
>
|
||||
@if (q.type === 'ja-nee') {
|
||||
<app-radio-group
|
||||
[name]="'vraag-' + q.id"
|
||||
[options]="jaNee"
|
||||
[invalid]="!!vraagErr(q.id)"
|
||||
[ngModel]="antwoord(q.id)"
|
||||
(ngModelChange)="
|
||||
dispatch({ tag: 'SetAntwoord', vraagId: q.id, value: $event })
|
||||
"
|
||||
[ngModelOptions]="{ standalone: true }"
|
||||
/>
|
||||
} @else {
|
||||
<app-text-input
|
||||
[inputId]="'vraag-' + q.id"
|
||||
[invalid]="!!vraagErr(q.id)"
|
||||
[ngModel]="antwoord(q.id)"
|
||||
(ngModelChange)="
|
||||
dispatch({ tag: 'SetAntwoord', vraagId: q.id, value: $event })
|
||||
"
|
||||
[ngModelOptions]="{ standalone: true }"
|
||||
/>
|
||||
}
|
||||
</app-form-field>
|
||||
}
|
||||
</fieldset>
|
||||
}
|
||||
}
|
||||
</ng-template>
|
||||
<ng-template appAsyncLoading>
|
||||
<app-skeleton height="2.5rem" [count]="3" />
|
||||
</ng-template>
|
||||
</app-async>
|
||||
|
||||
<app-document-upload
|
||||
class="app-section"
|
||||
[state]="upload()"
|
||||
[previewUrlFor]="previewUrlFor"
|
||||
(fileSelected)="uploadCtl.onFileSelected($event.categoryId, $event.files)"
|
||||
(removeUpload)="uploadCtl.onRemove($event)"
|
||||
(retryUpload)="uploadCtl.onRetry($event)"
|
||||
(deleteUpload)="uploadCtl.onDelete($event)"
|
||||
(channelChange)="uploadCtl.onChannelChange($event.categoryId, $event.channel)"
|
||||
/>
|
||||
@if (err('documenten')) {
|
||||
<app-alert type="warning">{{ err('documenten') }}</app-alert>
|
||||
}
|
||||
}
|
||||
@case ('controle') {
|
||||
<app-alert type="info" i18n="@@regWizard.controleer"
|
||||
>Controleer uw gegevens en dien de registratie in.</app-alert
|
||||
>
|
||||
<app-review-section
|
||||
i18n-heading="@@regWizard.sectie.adres"
|
||||
heading="Adres en correspondentie"
|
||||
i18n-editAriaLabel="@@regWizard.adresWijzigenAria"
|
||||
editAriaLabel="Wijzigen adresgegevens"
|
||||
(edit)="dispatch({ tag: 'GaNaarStap', cursor: 0 })"
|
||||
>
|
||||
<div
|
||||
app-data-row
|
||||
i18n-key="@@regWizard.summary.adres"
|
||||
key="Adres"
|
||||
[value]="adresSamenvatting()"
|
||||
></div>
|
||||
<div
|
||||
app-data-row
|
||||
i18n-key="@@regWizard.summary.herkomstAdres"
|
||||
key="Herkomst adres"
|
||||
[value]="adresHerkomstLabel()"
|
||||
></div>
|
||||
<div
|
||||
app-data-row
|
||||
i18n-key="@@regWizard.summary.correspondentie"
|
||||
key="Correspondentie"
|
||||
[value]="correspondentieLabel()"
|
||||
></div>
|
||||
@if (draft().correspondentie === 'email') {
|
||||
<div
|
||||
app-data-row
|
||||
i18n-key="@@regWizard.summary.email"
|
||||
key="E-mailadres"
|
||||
[value]="draft().email ?? ''"
|
||||
></div>
|
||||
}
|
||||
</app-review-section>
|
||||
<app-review-section
|
||||
class="app-section"
|
||||
i18n-heading="@@regWizard.sectie.beroep"
|
||||
heading="Beroep en diploma"
|
||||
i18n-editAriaLabel="@@regWizard.diplomaWijzigenAria"
|
||||
editAriaLabel="Wijzigen beroep en diploma"
|
||||
(edit)="dispatch({ tag: 'GaNaarStap', cursor: 1 })"
|
||||
>
|
||||
<div
|
||||
app-data-row
|
||||
i18n-key="@@regWizard.summary.beroep"
|
||||
key="Beroep"
|
||||
[value]="draft().beroep ?? ''"
|
||||
></div>
|
||||
<div
|
||||
app-data-row
|
||||
i18n-key="@@regWizard.summary.herkomstDiploma"
|
||||
key="Herkomst diploma"
|
||||
[value]="diplomaHerkomstLabel()"
|
||||
></div>
|
||||
@for (item of samenvattingVragen(); track item.vraag) {
|
||||
<div app-data-row [key]="item.vraag" [value]="item.antwoord"></div>
|
||||
}
|
||||
</app-review-section>
|
||||
}
|
||||
}
|
||||
|
||||
<div wizardSuccess>
|
||||
<app-confirmation
|
||||
i18n-title="@@regWizard.success.title"
|
||||
title="Uw registratie is ontvangen"
|
||||
>
|
||||
<p class="app-section" i18n="@@regWizard.success.referentie">
|
||||
Uw referentienummer is {{ referentie() }}. Bewaar dit nummer voor uw administratie.
|
||||
</p>
|
||||
<div class="app-section">
|
||||
<app-button variant="secondary" (click)="restart()" i18n="@@regWizard.nieuweRegistratie"
|
||||
>Nieuwe registratie starten</app-button
|
||||
>
|
||||
</div>
|
||||
</app-confirmation>
|
||||
</div>
|
||||
</app-wizard-shell>
|
||||
`,
|
||||
})
|
||||
export class RegistratieWizardComponent {
|
||||
private lookup = inject(RegistratieLookupStore);
|
||||
private uploadAdapter = inject(UploadAdapter);
|
||||
private store = createStore<RegistratieState, RegistratieMsg>(initial, reduce);
|
||||
|
||||
/** Preview/download link for a completed upload; the dev-simulation `demo-*` ids
|
||||
have no stored bytes, so they get no link. */
|
||||
protected previewUrlFor = (documentId: string): string | undefined =>
|
||||
documentId.startsWith('demo-') ? undefined : this.uploadAdapter.contentUrl(documentId);
|
||||
|
||||
/** Optional seed so Storybook / tests can mount any state directly. */
|
||||
seed = input<RegistratieState>(initial);
|
||||
|
||||
readonly kanalen = KANALEN;
|
||||
readonly stepLabels = [
|
||||
$localize`:@@regWizard.step.adres:Adres`,
|
||||
$localize`:@@regWizard.step.beroep:Beroep`,
|
||||
$localize`:@@regWizard.step.controle:Controle`,
|
||||
]; // short labels for the stepper
|
||||
private stepTitles = [
|
||||
$localize`:@@regWizard.title.adres:Adres en correspondentievoorkeur`,
|
||||
$localize`:@@regWizard.title.beroep:Beroep op basis van uw diploma`,
|
||||
$localize`:@@regWizard.title.controle:Controleren en indienen`,
|
||||
];
|
||||
readonly state = this.store.model;
|
||||
readonly dispatch = this.store.dispatch;
|
||||
|
||||
private invullen = computed(() => whenTag(this.state(), 'Invullen'));
|
||||
protected cursor = computed(() => this.invullen()?.cursor ?? 0);
|
||||
protected draft = computed<Draft>(() => this.invullen()?.draft ?? { antwoorden: {} });
|
||||
protected upload = computed<UploadState>(() => this.invullen()?.upload ?? initialUpload);
|
||||
protected uploadCtl = createUploadController({
|
||||
wizardId: 'registratie',
|
||||
getUpload: () => this.upload(),
|
||||
dispatch: (msg) => this.dispatch({ tag: 'Upload', msg }),
|
||||
// Required documents depend on answers (server decides): a diploma upload only for a
|
||||
// manual diploma; a Dutch-taalvaardigheid upload only once the applicant confirms
|
||||
// ("ja") the B2 language requirement.
|
||||
getCategoryParams: () => ({
|
||||
diplomaHerkomst: this.draft().diplomaHerkomst,
|
||||
taalvaardigheid: this.draft().antwoorden[NL_TAALVAARDIGHEID_VRAAG],
|
||||
}),
|
||||
});
|
||||
// Backend draft-sync (replaces sessionStorage): create a Concept once the user has
|
||||
// made progress, then debounced-sync the whole machine snapshot; resume by `?aanvraag`.
|
||||
private draftSync = createDraftSync({
|
||||
type: 'registratie',
|
||||
snapshot: () => {
|
||||
const s = this.state();
|
||||
if (s.tag !== 'Invullen' || !hasProgress(s)) return null;
|
||||
const documentIds = deliveryRefs(s.upload)
|
||||
.filter((r) => r.channel === 'digital' && r.documentId)
|
||||
.map((r) => r.documentId!);
|
||||
return { draft: s, stepIndex: s.cursor, stepCount: STEPS.length, documentIds };
|
||||
},
|
||||
onResume: (draft) => this.dispatch({ tag: 'Seed', state: draft as RegistratieState }),
|
||||
enabled: () => this.seed() === initial,
|
||||
});
|
||||
protected step = computed<StepId>(() => STEPS[Math.min(this.cursor(), STEPS.length - 1)]);
|
||||
protected stepTitle = computed(
|
||||
() => this.stepTitles[Math.min(this.cursor(), this.stepTitles.length - 1)],
|
||||
);
|
||||
protected referentie = computed(() => whenTag(this.state(), 'Ingediend')?.referentie ?? '');
|
||||
protected failedError = computed(() => whenTag(this.state(), 'Mislukt')?.error ?? '');
|
||||
|
||||
// --- Presentational wiring for the shared wizard shell ---------------------
|
||||
protected primaryLabel = computed(() => {
|
||||
if (this.step() === 'controle') return $localize`:@@regWizard.indienen:Registratie indienen`;
|
||||
const next = this.cursor() + 1;
|
||||
return naarStapLabel(next + 1, this.stepLabels[next]);
|
||||
});
|
||||
protected errorMessage = computed(
|
||||
() =>
|
||||
$localize`:@@regWizard.indienenMislukt:Het indienen is niet gelukt:` +
|
||||
` ${this.failedError()}`,
|
||||
);
|
||||
protected shellStatus = computed<WizardStatus>(() => {
|
||||
switch (this.state().tag) {
|
||||
case 'Invullen':
|
||||
return 'editing';
|
||||
case 'Indienen':
|
||||
return 'submitting';
|
||||
case 'Ingediend':
|
||||
return 'submitted';
|
||||
case 'Mislukt':
|
||||
return 'failed';
|
||||
}
|
||||
});
|
||||
/** Current step's errors (incl. per-question), flattened for the error summary. */
|
||||
protected errorList = computed<WizardError[]>(() => {
|
||||
const e = this.invullen()?.errors ?? {};
|
||||
const out: WizardError[] = [];
|
||||
for (const [k, v] of Object.entries(e)) {
|
||||
if (k !== 'antwoorden' && typeof v === 'string' && v) out.push({ id: k, message: v });
|
||||
}
|
||||
for (const [qid, msg] of Object.entries(e.antwoorden ?? {})) {
|
||||
if (msg) out.push({ id: 'vraag-' + qid, message: msg });
|
||||
}
|
||||
return out;
|
||||
});
|
||||
protected adresSamenvatting = computed(() => {
|
||||
const d = this.draft();
|
||||
return [d.straat, [d.postcode, d.woonplaats].filter(Boolean).join(' ')]
|
||||
.filter(Boolean)
|
||||
.join(', ');
|
||||
});
|
||||
// Readable labels for the controle summary (instead of raw enum values).
|
||||
protected adresHerkomstLabel = computed(
|
||||
() =>
|
||||
({
|
||||
brp: $localize`:@@regWizard.herkomst.adresBrp:Automatisch uit de BRP`,
|
||||
handmatig: $localize`:@@regWizard.herkomst.adresHandmatig:Handmatig ingevoerd`,
|
||||
})[this.draft().adresHerkomst ?? 'handmatig'],
|
||||
);
|
||||
protected correspondentieLabel = computed(
|
||||
() =>
|
||||
({
|
||||
email: $localize`:@@regWizard.corr.email:Per e-mail`,
|
||||
post: $localize`:@@regWizard.corr.post:Per post`,
|
||||
})[this.draft().correspondentie ?? 'post'],
|
||||
);
|
||||
protected diplomaHerkomstLabel = computed(
|
||||
() =>
|
||||
({
|
||||
duo: $localize`:@@regWizard.herkomst.diplomaDuo:Geverifieerd via DUO`,
|
||||
handmatig: $localize`:@@regWizard.herkomst.diplomaHandmatig:Handmatig ingevoerd (wordt beoordeeld)`,
|
||||
})[this.draft().diplomaHerkomst ?? 'handmatig'],
|
||||
);
|
||||
|
||||
/** BRP lookup outcome (laden/gevonden/geen/fout) and the parsed DUO lookup, both
|
||||
served by the application facade — the wizard renders, it does not fetch/parse. */
|
||||
protected adresStatus = this.lookup.adresStatus;
|
||||
protected lookupRd: () => RemoteData<Error | undefined, DuoLookupDto> = this.lookup.duoLookup;
|
||||
|
||||
/** Parsed lookup as a plain value (or null) — used outside the beroep step (the
|
||||
controle summary) where the <app-async> template variable isn't in scope, and
|
||||
inside it too: `<ng-template appAsyncLoaded>`'s own context can't inherit a
|
||||
generic from the sibling [data] input (Angular only infers a structural
|
||||
directive's type parameter from an input on that same node). */
|
||||
protected duoData = computed<DuoLookupDto | null>(() => {
|
||||
const rd = this.lookupRd();
|
||||
return rd.tag === 'Success' ? rd.value : null;
|
||||
});
|
||||
|
||||
readonly jaNee = JA_NEE;
|
||||
|
||||
protected err = (k: DraftField | 'correspondentie' | 'diploma' | 'documenten') =>
|
||||
this.invullen()?.errors[k] ?? '';
|
||||
protected vraagErr = (id: string) => this.invullen()?.errors.antwoorden?.[id] ?? '';
|
||||
protected antwoord = (id: string) => this.draft().antwoorden[id] ?? ''; // runtime guard: missing key → undefined
|
||||
protected set = (key: DraftField, value: string) =>
|
||||
this.dispatch({ tag: 'SetField', key, value });
|
||||
protected setKanaal = (value: string) =>
|
||||
this.dispatch({ tag: 'SetCorrespondentie', value: value as Correspondentie });
|
||||
|
||||
/** True while the user is entering a diploma manually (not in the DUO list). */
|
||||
protected handmatigActief = computed(() => this.draft().diplomaHerkomst === 'handmatig');
|
||||
/** The radio selection: a diploma id, or the"not listed" sentinel in manual mode. */
|
||||
protected diplomaKeuze = computed(() =>
|
||||
this.handmatigActief() ? HANDMATIG : (this.draft().diplomaId ?? ''),
|
||||
);
|
||||
|
||||
protected diplomaOptions = (data: DuoLookupDto) => [
|
||||
...data.diplomas.map((d) => ({
|
||||
value: d.id,
|
||||
label: `${d.naam} — ${d.instelling} (${d.jaar})`,
|
||||
})),
|
||||
{
|
||||
value: HANDMATIG,
|
||||
label: $localize`:@@regWizard.diplomaNietBij:Mijn diploma staat er niet bij`,
|
||||
},
|
||||
];
|
||||
|
||||
protected beroepOptions = (data: DuoLookupDto) =>
|
||||
data.handmatig.beroepen.map((b) => ({ value: b, label: b }));
|
||||
|
||||
/** The policy questions that apply to the current choice (server-decided). */
|
||||
protected actieveVragen = (data: DuoLookupDto): PolicyQuestionDto[] => {
|
||||
if (this.handmatigActief()) return data.handmatig.policyQuestions;
|
||||
return data.diplomas.find((d) => d.id === this.draft().diplomaId)?.policyQuestions ?? [];
|
||||
};
|
||||
|
||||
/** Answered policy questions for the controle summary (question text + answer). */
|
||||
protected samenvattingVragen = computed(() => {
|
||||
const data = this.duoData();
|
||||
const d = this.draft();
|
||||
if (!data) return [] as { vraag: string; antwoord: string }[];
|
||||
const alle = [
|
||||
...data.diplomas.flatMap((x) => x.policyQuestions),
|
||||
...data.handmatig.policyQuestions,
|
||||
];
|
||||
return (d.vraagIds ?? []).map((id) => ({
|
||||
vraag: alle.find((q) => q.id === id)?.vraag ?? id,
|
||||
antwoord: d.antwoorden[id] ?? '',
|
||||
}));
|
||||
});
|
||||
|
||||
protected onDiplomaKeuze(data: DuoLookupDto, id: string) {
|
||||
if (id === HANDMATIG) {
|
||||
this.dispatch({
|
||||
tag: 'KiesHandmatig',
|
||||
vraagIds: data.handmatig.policyQuestions.map((q) => q.id),
|
||||
});
|
||||
return;
|
||||
}
|
||||
const d = data.diplomas.find((x) => x.id === id);
|
||||
if (d)
|
||||
this.dispatch({
|
||||
tag: 'KiesDiploma',
|
||||
diplomaId: d.id,
|
||||
beroep: d.beroep,
|
||||
vraagIds: d.policyQuestions.map((q) => q.id),
|
||||
});
|
||||
}
|
||||
|
||||
constructor() {
|
||||
// An explicit seed (stories/tests) wins; otherwise resume from the backend draft
|
||||
// (`?aanvraag=<id>`), or start fresh. Persistence is the draftSync controller's job.
|
||||
const seeded = this.seed();
|
||||
queueMicrotask(() =>
|
||||
seeded !== initial ? this.dispatch({ tag: 'Seed', state: seeded }) : this.draftSync.resume(),
|
||||
);
|
||||
// Prefill the address from the BRP lookup as it arrives. Track only the facade's
|
||||
// parsed prefill signal; untrack the dispatch (it reads the state signal, which
|
||||
// would otherwise make this effect loop on its own write). Don't clobber
|
||||
// edits/restored data. A null prefill (loading/error/geen adres) leaves manual entry.
|
||||
effect(() => {
|
||||
const a = this.lookup.prefillAdres();
|
||||
if (!a) return;
|
||||
untracked(() => {
|
||||
const s = this.state();
|
||||
if (s.tag !== 'Invullen' || s.draft.straat) return;
|
||||
this.dispatch({
|
||||
tag: 'PrefillAdres',
|
||||
straat: a.straat,
|
||||
postcode: a.postcode,
|
||||
woonplaats: a.woonplaats,
|
||||
});
|
||||
});
|
||||
});
|
||||
// A11y: focus management (step heading on step change, error summary on a
|
||||
// failed submit) now lives in the shared WizardShellComponent.
|
||||
}
|
||||
|
||||
onPrimary() {
|
||||
const s = this.state();
|
||||
if (s.tag !== 'Invullen') return;
|
||||
this.dispatch(this.step() === 'controle' ? { tag: 'Submit' } : { tag: 'Next' });
|
||||
this.runIfIndienen();
|
||||
}
|
||||
|
||||
onRetry() {
|
||||
this.dispatch({ tag: 'Retry' });
|
||||
this.runIfIndienen();
|
||||
}
|
||||
|
||||
/** Reset the wizard to a fresh start. Reload the BRP lookup so the address
|
||||
re-prefills, keeping the form and the"vooraf ingevuld" note consistent. */
|
||||
restart() {
|
||||
this.draftSync.reset(); // discard the current Concept; a fresh one starts on next progress
|
||||
this.dispatch({ tag: 'Seed', state: initial });
|
||||
this.lookup.reloadAdres();
|
||||
}
|
||||
|
||||
/** The effect: when we enter Indienen, submit through the aanvraag lifecycle
|
||||
(duo → auto-approve, handmatig → manual), then dispatch the outcome. */
|
||||
private async runIfIndienen() {
|
||||
const s = this.state();
|
||||
if (s.tag !== 'Indienen') return;
|
||||
const r = await this.draftSync.submit({
|
||||
diplomaHerkomst: s.data.diplomaHerkomst,
|
||||
documents: s.data.documents,
|
||||
});
|
||||
if (r.ok) this.dispatch({ tag: 'SubmitConfirmed', referentie: r.value.referentie ?? '' });
|
||||
else this.dispatch({ tag: 'SubmitFailed', error: r.error });
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,94 @@
|
||||
import type { Meta, StoryObj } from '@storybook/angular';
|
||||
import { applicationConfig } from '@storybook/angular';
|
||||
import { provideHttpClient } from '@angular/common/http';
|
||||
import { provideApiClient } from '@shared/infrastructure/api-client.provider';
|
||||
import { RegistratieWizardComponent } from './registratie-wizard.component';
|
||||
import {
|
||||
Draft,
|
||||
RegistratieState,
|
||||
ValidRegistratie,
|
||||
} from '@registratie/domain/registratie-wizard.machine';
|
||||
import { initialUpload } from '@shared/upload/upload.machine';
|
||||
import { Postcode } from '@registratie/domain/value-objects/postcode';
|
||||
|
||||
const adres: Partial<Draft> = {
|
||||
straat: 'Lange Voorhout 9',
|
||||
postcode: '2514 EA',
|
||||
woonplaats: 'Den Haag',
|
||||
adresHerkomst: 'brp',
|
||||
correspondentie: 'post',
|
||||
};
|
||||
const filled: Partial<Draft> = {
|
||||
...adres,
|
||||
diplomaId: 'd1',
|
||||
beroep: 'Arts',
|
||||
diplomaHerkomst: 'duo',
|
||||
vraagIds: [],
|
||||
};
|
||||
|
||||
const invullen = (draft: Partial<Draft>, cursor = 0): RegistratieState => ({
|
||||
tag: 'Invullen',
|
||||
draft: { antwoorden: {}, ...draft },
|
||||
cursor,
|
||||
errors: {},
|
||||
upload: initialUpload,
|
||||
});
|
||||
|
||||
const validData: ValidRegistratie = {
|
||||
adres: { straat: 'Lange Voorhout 9', postcode: '2514 EA' as Postcode, woonplaats: 'Den Haag' },
|
||||
adresHerkomst: 'brp',
|
||||
correspondentie: 'post',
|
||||
diplomaId: 'd1',
|
||||
diplomaHerkomst: 'duo',
|
||||
beroep: 'Arts',
|
||||
antwoorden: {},
|
||||
documents: [],
|
||||
};
|
||||
|
||||
const meta: Meta<RegistratieWizardComponent> = {
|
||||
title: 'Domein/Registratie/RegistratieWizard',
|
||||
component: RegistratieWizardComponent,
|
||||
decorators: [applicationConfig({ providers: [provideHttpClient(), provideApiClient()] })],
|
||||
};
|
||||
export default meta;
|
||||
type Story = StoryObj<RegistratieWizardComponent>;
|
||||
|
||||
export const Adres: Story = { args: { seed: invullen(adres, 0) } };
|
||||
export const Beroep: Story = { args: { seed: invullen(filled, 1) } };
|
||||
/** English-language diploma → the Dutch-proficiency policy question appears. */
|
||||
export const BeroepEngelstalig: Story = {
|
||||
args: {
|
||||
seed: invullen(
|
||||
{
|
||||
...adres,
|
||||
diplomaId: 'd2',
|
||||
beroep: 'Arts',
|
||||
diplomaHerkomst: 'duo',
|
||||
vraagIds: ['nl-taalvaardigheid'],
|
||||
},
|
||||
1,
|
||||
),
|
||||
},
|
||||
};
|
||||
/** Diploma not in DUO → declare beroep + the maximal policy-question set. */
|
||||
export const BeroepHandmatig: Story = {
|
||||
args: {
|
||||
seed: invullen(
|
||||
{
|
||||
...adres,
|
||||
diplomaId: 'handmatig',
|
||||
diplomaHerkomst: 'handmatig',
|
||||
vraagIds: ['nl-taalvaardigheid', 'diploma-erkend', 'toelichting'],
|
||||
},
|
||||
1,
|
||||
),
|
||||
},
|
||||
};
|
||||
export const Controle: Story = { args: { seed: invullen(filled, 2) } };
|
||||
export const Indienen: Story = { args: { seed: { tag: 'Indienen', data: validData } } };
|
||||
export const Ingediend: Story = {
|
||||
args: { seed: { tag: 'Ingediend', data: validData, referentie: 'BIG-2026-123456' } },
|
||||
};
|
||||
export const Mislukt: Story = {
|
||||
args: { seed: { tag: 'Mislukt', data: validData, error: 'Netwerkfout' } },
|
||||
};
|
||||
@@ -0,0 +1,27 @@
|
||||
import { Component } from '@angular/core';
|
||||
import { PageShellComponent } from '@shared/layout/page-shell/page-shell.component';
|
||||
import { AlertComponent } from '@shared/ui/alert/alert.component';
|
||||
import { RegistratieWizardComponent } from '@registratie/ui/registratie-wizard/registratie-wizard.component';
|
||||
|
||||
/** Page: register in the BIG-register. Built entirely from existing building
|
||||
blocks (page shell + alert + the registratie-wizard organism). */
|
||||
@Component({
|
||||
selector: 'app-registratie-page',
|
||||
imports: [PageShellComponent, AlertComponent, RegistratieWizardComponent],
|
||||
template: `
|
||||
<app-page-shell
|
||||
i18n-heading="@@registratie.heading"
|
||||
heading="Inschrijven in het BIG-register"
|
||||
backLink="/dashboard"
|
||||
>
|
||||
<app-alert type="info" i18n="@@registratie.intro">
|
||||
In drie stappen schrijft u zich in: uw adres en correspondentievoorkeur, het diploma waarmee
|
||||
u zich registreert, en een controle. Uw gegevens blijven bewaard als u de pagina herlaadt.
|
||||
</app-alert>
|
||||
<div class="app-section">
|
||||
<app-registratie-wizard />
|
||||
</div>
|
||||
</app-page-shell>
|
||||
`,
|
||||
})
|
||||
export class RegistratiePage {}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { Component, computed, inject } from '@angular/core';
|
||||
import { PageShellComponent } from '@shared/layout/page-shell/page-shell.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,
|
||||
SkeletonComponent,
|
||||
...ASYNC,
|
||||
RegistrationSummaryComponent,
|
||||
ChangeRequestFormComponent,
|
||||
],
|
||||
template: `
|
||||
<app-page-shell
|
||||
i18n-heading="@@registratieDetail.heading"
|
||||
heading="Mijn gegevens"
|
||||
backLink="/dashboard"
|
||||
>
|
||||
<app-async [data]="store.profile()">
|
||||
<ng-template appAsyncLoaded>
|
||||
@if (profile(); as p) {
|
||||
<app-registration-summary [reg]="p.registration" />
|
||||
}
|
||||
</ng-template>
|
||||
<ng-template appAsyncLoading>
|
||||
<app-skeleton height="2.5rem" [count]="6" />
|
||||
</ng-template>
|
||||
</app-async>
|
||||
|
||||
<div class="app-section">
|
||||
<app-change-request-form [brpAdres]="profile()?.person?.adres" />
|
||||
</div>
|
||||
</app-page-shell>
|
||||
`,
|
||||
})
|
||||
export class RegistrationDetailPage {
|
||||
protected store = inject(BigProfileStore);
|
||||
|
||||
/** See DashboardPage's `profile` for why this narrows via a computed instead of `let-`. */
|
||||
protected readonly profile = computed(() => {
|
||||
const rd = this.store.profile();
|
||||
return rd.tag === 'Success' ? rd.value : undefined;
|
||||
});
|
||||
}
|
||||
+72
@@ -0,0 +1,72 @@
|
||||
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';
|
||||
import { DataBlockComponent } from '@shared/ui/data-block/data-block.component';
|
||||
|
||||
/** Organism: registration summary in a CIBG Datablock. Composes data-row rows +
|
||||
status-badge atom (no card wrapper — the datablock carries its own surface). */
|
||||
@Component({
|
||||
selector: 'app-registration-summary',
|
||||
imports: [DatePipe, DataRowComponent, StatusBadgeComponent, DataBlockComponent],
|
||||
template: `
|
||||
<app-data-block i18n-ariaLabel="@@summary.ariaLabel" ariaLabel="Registratiegegevens">
|
||||
<div
|
||||
app-data-row
|
||||
i18n-key="@@summary.bigNummer"
|
||||
key="BIG-nummer"
|
||||
[value]="reg().bigNummer"
|
||||
></div>
|
||||
<div app-data-row i18n-key="@@summary.naam" key="Naam" [value]="reg().naam"></div>
|
||||
<div app-data-row i18n-key="@@summary.beroep" key="Beroep" [value]="reg().beroep"></div>
|
||||
<div app-data-row i18n-key="@@summary.status" key="Status">
|
||||
<app-status-badge [label]="label()" [color]="color()" />
|
||||
</div>
|
||||
<div
|
||||
app-data-row
|
||||
i18n-key="@@summary.registratiedatum"
|
||||
key="Registratiedatum"
|
||||
[value]="reg().registratiedatum | date: 'longDate'"
|
||||
></div>
|
||||
<!-- Each status variant renders only the row its own data supports. A single
|
||||
@let binds status once so the @switch narrows its union by tag -- calling
|
||||
reg().status again per case would give the checker a fresh, unnarrowed call. -->
|
||||
@let status = reg().status;
|
||||
@switch (status.tag) {
|
||||
@case ('Geregistreerd') {
|
||||
<div
|
||||
app-data-row
|
||||
i18n-key="@@summary.uiterste"
|
||||
key="Uiterste herregistratie"
|
||||
[value]="status.herregistratieDatum | date: 'longDate'"
|
||||
></div>
|
||||
}
|
||||
@case ('Geschorst') {
|
||||
<div
|
||||
app-data-row
|
||||
i18n-key="@@summary.geschorstTot"
|
||||
key="Geschorst tot"
|
||||
[value]="status.geschorstTot | date: 'longDate'"
|
||||
></div>
|
||||
<div app-data-row i18n-key="@@summary.reden" key="Reden" [value]="status.reden"></div>
|
||||
}
|
||||
@case ('Doorgehaald') {
|
||||
<div
|
||||
app-data-row
|
||||
i18n-key="@@summary.doorgehaaldOp"
|
||||
key="Doorgehaald op"
|
||||
[value]="status.doorgehaaldOp | date: 'longDate'"
|
||||
></div>
|
||||
<div app-data-row i18n-key="@@summary.reden" key="Reden" [value]="status.reden"></div>
|
||||
}
|
||||
}
|
||||
</app-data-block>
|
||||
`,
|
||||
})
|
||||
export class RegistrationSummaryComponent {
|
||||
reg = input.required<Registration>();
|
||||
protected label = () => statusLabel(this.reg().status.tag);
|
||||
protected color = () => statusColor(this.reg().status.tag);
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
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: 'Domein/Registratie/Registration Summary',
|
||||
component: RegistrationSummaryComponent,
|
||||
};
|
||||
export default meta;
|
||||
type Story = StoryObj<RegistrationSummaryComponent>;
|
||||
|
||||
// Each story feeds a different union variant; the datablock 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' },
|
||||
},
|
||||
},
|
||||
};
|
||||
@@ -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="table-responsive">
|
||||
<table class="table table-striped">
|
||||
<thead>
|
||||
<tr>
|
||||
<th scope="col" i18n="@@table.type">Type</th>
|
||||
<th scope="col" i18n="@@table.omschrijving">Omschrijving</th>
|
||||
<th scope="col" i18n="@@table.datum">Datum</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody>
|
||||
@for (row of rows(); track row.omschrijving) {
|
||||
<tr>
|
||||
<td>{{ row.type }}</td>
|
||||
<td>{{ row.omschrijving }}</td>
|
||||
<td>{{ row.datum | date: 'mediumDate' }}</td>
|
||||
</tr>
|
||||
}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
`,
|
||||
})
|
||||
export class RegistrationTableComponent {
|
||||
rows = input.required<Aantekening[]>();
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import type { Meta, StoryObj } from '@storybook/angular';
|
||||
import { RegistrationTableComponent } from './registration-table.component';
|
||||
|
||||
const meta: Meta<RegistrationTableComponent> = {
|
||||
title: 'Domein/Registratie/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',
|
||||
},
|
||||
],
|
||||
},
|
||||
};
|
||||
Reference in New Issue
Block a user