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:
eho
2026-08-02 21:01:57 +02:00
co-authored by Claude Sonnet 5
parent d3f3b13345
commit e7156c5132
403 changed files with 7103 additions and 60917 deletions
@@ -0,0 +1,32 @@
import { Injectable, inject, signal } from '@angular/core';
import { RemoteData } from '@shared/application/remote-data';
import { AuditEntry } from '@beheer/domain/audit-entry';
import { AuditAdapter, parseAuditEntries } from '@beheer/infrastructure/audit.adapter';
type Err = Error | undefined;
/**
* Admin view of the persisted authz/PII-reveal audit trail (WP-41/42). One root singleton
* owning the list as a RemoteData signal, parsed at the trust boundary. Read-only.
*/
@Injectable({ providedIn: 'root' })
export class AuditStore {
private adapter = inject(AuditAdapter);
private state = signal<RemoteData<Err, AuditEntry[]>>({ tag: 'Loading' });
readonly entries = this.state.asReadonly();
async load() {
if (this.state().tag !== 'Success') this.state.set({ tag: 'Loading' });
try {
const parsed = parseAuditEntries(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 });
}
}
}
@@ -0,0 +1,65 @@
import { TestBed } from '@angular/core/testing';
import { describe, it, expect } from 'vitest';
import { Result, ok } from '@shared/kernel/fp';
import { StamRow, StamTable } from '@beheer/domain/stamdata';
import { StamdataAdapter } from '@beheer/infrastructure/stamdata.adapter';
import { StamdataStore } from './stamdata.store';
const table: StamTable = {
id: 'professions',
label: 'Opleiding → beroep',
temporal: false,
columns: [
{ name: 'program', type: 'text', isKey: true, options: [] },
{ name: 'beroep', type: 'text', isKey: false, options: [] },
],
};
const rows: StamRow[] = [{ program: 'geneeskunde', beroep: 'Arts' }];
function setup(): StamdataStore {
const adapter: Partial<StamdataAdapter> = {
list: (): Promise<Result<string, StamTable[]>> => Promise.resolve(ok([table])),
load: (): Promise<Result<string, { table: StamTable; rows: StamRow[] }>> =>
Promise.resolve(ok({ table, rows: rows.map((r) => ({ ...r })) })),
};
TestBed.configureTestingModule({ providers: [{ provide: StamdataAdapter, useValue: adapter }] });
return TestBed.inject(StamdataStore);
}
describe('StamdataStore undo/redo (WP-32)', () => {
it('records a cell edit, undoes and redoes it', async () => {
const store = setup();
await store.load();
expect(store.canUndo()).toBe(false);
store.editCell(0, 'beroep', 'Chirurg');
expect(store.rows()[0]['beroep']).toBe('Chirurg');
expect(store.canUndo()).toBe(true);
store.undo();
expect(store.rows()[0]['beroep']).toBe('Arts');
expect(store.canRedo()).toBe(true);
store.redo();
expect(store.rows()[0]['beroep']).toBe('Chirurg');
expect(store.canRedo()).toBe(false);
});
it('records addRow and undoes it', async () => {
const store = setup();
await store.load();
store.addRow();
expect(store.rows().length).toBe(2);
store.undo();
expect(store.rows().length).toBe(1);
});
it('clears history when switching table', async () => {
const store = setup();
await store.load();
store.addRow();
expect(store.canUndo()).toBe(true);
await store.selectTable('professions');
expect(store.canUndo()).toBe(false);
});
});
@@ -0,0 +1,150 @@
import { Injectable, computed, inject, signal } from '@angular/core';
import { createStore } from '@shared/application/store';
import { machineRemoteData } from '@shared/application/machine-remote-data';
import { createHistory } from '@shared/application/history';
import {
ChangeCounts,
StamRow,
StamTable,
changeCounts,
isValid,
rowErrors,
toJson,
} from '@beheer/domain/stamdata';
import {
StamdataEditorMsg,
StamdataEditorState,
initial,
reduce,
} from '@beheer/domain/stamdata-editor.machine';
import { StamdataAdapter } from '@beheer/infrastructure/stamdata.adapter';
type LoadedState = Extract<StamdataEditorState, { tag: 'loaded' }>;
/**
* Root singleton for the stamdata maintenance editor (ADR-0004). The Elm machine owns the
* draft rows; commands here load the catalog + a selected table and produce the download.
* There is deliberately NO save command — the reducer stays pure and the edit leaves as a
* downloaded JSON file that the admin drops into the repo (the CI build is the authority).
*/
@Injectable({ providedIn: 'root' })
export class StamdataStore {
private adapter = inject(StamdataAdapter);
private store = createStore<StamdataEditorState, StamdataEditorMsg>(initial, reduce);
readonly model = this.store.model;
readonly tables = signal<readonly StamTable[]>([]);
readonly selectedTableId = signal<string | null>(null);
/** Preview: show only rows valid on this date ('' = show all, editable). A local filter,
so toggling it never round-trips or drops unsaved edits (see domain `activeOn`). */
readonly previewDate = signal<string>('');
readonly remoteData = computed(() => machineRemoteData(this.model()));
private loaded = computed<LoadedState | null>(() => {
const s = this.model();
return s.tag === 'loaded' ? s : null;
});
readonly table = computed<StamTable | null>(() => this.loaded()?.table ?? null);
readonly rows = computed<readonly StamRow[]>(() => this.loaded()?.rows ?? []);
readonly errors = computed<readonly string[]>(() => {
const s = this.loaded();
return s ? rowErrors(s.table, s.rows) : [];
});
readonly counts = computed<ChangeCounts>(() => {
const s = this.loaded();
return s ? changeCounts(s.table, s.original, s.rows) : { added: 0, removed: 0, edited: 0 };
});
readonly dirty = computed(() => {
const c = this.counts();
return c.added + c.removed + c.edited > 0;
});
/** Download is blocked while previewing (the filtered view is not the full file) or while
any row has a format error (the CI gate would reject it anyway — fail fast here). */
readonly canDownload = computed(() => {
const s = this.loaded();
return this.previewDate() === '' && this.dirty() && s !== null && isValid(s.table, s.rows);
});
async load() {
this.store.dispatch({ tag: 'Loading' });
const list = await this.adapter.list();
if (!list.ok) {
this.store.dispatch({ tag: 'LoadFailed', reason: list.error });
return;
}
this.tables.set(list.value);
const first = list.value[0];
if (!first) {
this.store.dispatch({ tag: 'LoadFailed', reason: NO_TABLES });
return;
}
await this.selectTable(first.id);
}
async selectTable(tableId: string) {
this.selectedTableId.set(tableId);
this.previewDate.set('');
this.history.clear(); // undo history is per-table, not across tables
this.store.dispatch({ tag: 'Loading' });
const r = await this.adapter.load(tableId);
if (r.ok) this.store.dispatch({ tag: 'Loaded', table: r.value.table, rows: r.value.rows });
else this.store.dispatch({ tag: 'LoadFailed', reason: r.error });
}
setPreviewDate(date: string) {
this.previewDate.set(date);
}
/** Undo/redo over the edited rows (WP-32): the document snapshot is `rows`; restore via
the existing `Seed` msg. Only real edits are recorded (a no-op reduce leaves no step). */
private history = createHistory<readonly StamRow[]>(50);
readonly canUndo = this.history.canUndo;
readonly canRedo = this.history.canRedo;
private recordThenDispatch(msg: StamdataEditorMsg) {
const before = this.rows();
this.store.dispatch(msg);
if (this.loaded() && this.rows() !== before) this.history.record(before);
}
editCell(row: number, column: string, value: string) {
this.recordThenDispatch({ tag: 'CellEdited', row, column, value });
}
addRow() {
this.recordThenDispatch({ tag: 'RowAdded' });
}
removeRow(row: number) {
this.recordThenDispatch({ tag: 'RowRemoved', row });
}
undo() {
this.restore((rows) => this.history.undo(rows));
}
redo() {
this.restore((rows) => this.history.redo(rows));
}
private restore(step: (current: readonly StamRow[]) => readonly StamRow[] | undefined) {
const s = this.loaded();
if (!s) return;
const target = step(s.rows);
if (target === undefined) return;
// copy readonly history snapshot into the machine's mutable rows shape
this.store.dispatch({ tag: 'Seed', state: { ...s, rows: [...target] } });
}
/** Emit the edited data-file for the admin to drop into the repo (see domain `toJson`). */
download() {
const s = this.loaded();
if (!s || !this.canDownload()) return;
const blob = new Blob([toJson(s.table, s.rows)], { type: 'application/json' });
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = `${s.table.id}.json`;
a.click();
URL.revokeObjectURL(url);
}
}
const NO_TABLES = $localize`:@@beheer.noTables:Er is geen stamdata om te beheren.`;
+30
View File
@@ -0,0 +1,30 @@
// Wire DTOs for the stamdata maintenance reads (ADR-0004). Generic by design: a table is
// a reflected column schema + opaque JSON rows, so ONE contract serves every table. Field
// names mirror the backend Contracts/Dtos.cs 1:1; this file imports NOTHING (the wire seam).
export interface StamdataColumnDto {
name: string;
type: string;
isKey: boolean;
options?: string[];
}
export interface StamdataTableSummaryDto {
id: string;
label: string;
columns: StamdataColumnDto[];
temporal: boolean;
}
// A cell is whatever JSON the data-file holds for that column (string/date, number, or
// null for an open-ended geldigTot). The adapter narrows each to editable text.
export type StamdataCellDto = string | number | boolean | null;
export type StamdataRowDto = Record<string, StamdataCellDto>;
export interface StamdataTableDto {
id: string;
label: string;
columns: StamdataColumnDto[];
temporal: boolean;
rows: StamdataRowDto[];
}
+10
View File
@@ -0,0 +1,10 @@
/** One authz/PII-reveal audit row as the FE sees it (WP-41 backend → WP-42 view). Pure
type; data-minimised (no PII) by construction on the server. */
export interface AuditEntry {
at: string; // ISO timestamp
action: string;
resource: string;
decision: 'allow' | 'deny';
role: string;
correlationId: string;
}
@@ -0,0 +1,63 @@
import { describe, it, expect } from 'vitest';
import { StamTable } from './stamdata';
import { StamdataEditorState, initial, reduce } from './stamdata-editor.machine';
const table: StamTable = {
id: 'professions',
label: 'Opleiding → beroep',
temporal: true,
columns: [
{ name: 'program', type: 'text', isKey: true, options: [] },
{ name: 'beroep', type: 'text', isKey: false, options: [] },
{ name: 'geldigVan', type: 'date', isKey: false, options: [] },
{ name: 'geldigTot', type: 'date', isKey: false, options: [] },
],
};
const seedLoaded = (): StamdataEditorState =>
reduce(initial, {
tag: 'Loaded',
table,
rows: [{ program: 'geneeskunde', beroep: 'Arts', geldigVan: '2000-01-01', geldigTot: '' }],
});
describe('stamdata-editor reduce', () => {
it('Loaded snapshots original independently of rows', () => {
const s = seedLoaded();
expect(s.tag).toBe('loaded');
if (s.tag !== 'loaded') return;
const edited = reduce(s, { tag: 'CellEdited', row: 0, column: 'beroep', value: 'Chirurg' });
if (edited.tag !== 'loaded') return;
expect(edited.rows[0]['beroep']).toBe('Chirurg');
expect(edited.original[0]['beroep']).toBe('Arts'); // snapshot untouched → diff works
});
it('RowAdded appends an empty row shaped by the schema', () => {
const s = reduce(seedLoaded(), { tag: 'RowAdded' });
if (s.tag !== 'loaded') return;
expect(s.rows).toHaveLength(2);
expect(s.rows[1]).toEqual({ program: '', beroep: '', geldigVan: '', geldigTot: '' });
});
it('RowRemoved drops the row at the index', () => {
const s = reduce(reduce(seedLoaded(), { tag: 'RowAdded' }), { tag: 'RowRemoved', row: 0 });
if (s.tag !== 'loaded') return;
expect(s.rows).toHaveLength(1);
});
it('edit messages are ignored unless loaded', () => {
expect(reduce(initial, { tag: 'RowAdded' })).toBe(initial);
expect(
reduce({ tag: 'failed', reason: 'x' }, { tag: 'CellEdited', row: 0, column: 'a', value: 'b' })
.tag,
).toBe('failed');
});
it('LoadFailed and Loading transition regardless of prior state', () => {
expect(reduce(seedLoaded(), { tag: 'LoadFailed', reason: 'boom' })).toEqual({
tag: 'failed',
reason: 'boom',
});
expect(reduce(seedLoaded(), { tag: 'Loading' })).toEqual({ tag: 'loading' });
});
});
@@ -0,0 +1,55 @@
import { assertNever } from '@shared/kernel/fp';
import { StamRow, StamTable, emptyRow } from '@beheer/domain/stamdata';
/**
* The stamdata table editor as one Elm-style tagged union (the house form idiom). While
* `loaded`, the draft `rows` are the edit state and `original` is the loaded snapshot the
* diff compares against — no separate `dirty` flag (derive it, don't store it). Loading and
* failure are states here too, so the page can render them via `<app-async>`.
*
* There is no submit/save Msg: an edit stays local until the admin downloads the file (the
* apply path is a reviewed PR, not a runtime write — ADR-0004).
*/
export type StamdataEditorState =
| { tag: 'loading' }
| { tag: 'failed'; reason: string }
| { tag: 'loaded'; table: StamTable; rows: StamRow[]; original: readonly StamRow[] };
export type StamdataEditorMsg =
| { tag: 'Loading' }
| { tag: 'Loaded'; table: StamTable; rows: StamRow[] }
| { tag: 'LoadFailed'; reason: string }
| { tag: 'CellEdited'; row: number; column: string; value: string }
| { tag: 'RowAdded' }
| { tag: 'RowRemoved'; row: number }
| { tag: 'Seed'; state: StamdataEditorState }; // mount a specific state (stories/tests)
export const initial: StamdataEditorState = { tag: 'loading' };
const copy = (rows: readonly StamRow[]): StamRow[] => rows.map((r) => ({ ...r }));
export function reduce(s: StamdataEditorState, m: StamdataEditorMsg): StamdataEditorState {
switch (m.tag) {
case 'Loading':
return { tag: 'loading' };
case 'Loaded':
// original is an independent snapshot so later edits never mutate it (drives the diff).
return { tag: 'loaded', table: m.table, rows: copy(m.rows), original: copy(m.rows) };
case 'LoadFailed':
return { tag: 'failed', reason: m.reason };
case 'CellEdited':
if (s.tag !== 'loaded') return s;
return {
...s,
rows: s.rows.map((r, i) => (i === m.row ? { ...r, [m.column]: m.value } : r)),
};
case 'RowAdded':
return s.tag === 'loaded' ? { ...s, rows: [...s.rows, emptyRow(s.table)] } : s;
case 'RowRemoved':
return s.tag === 'loaded' ? { ...s, rows: s.rows.filter((_, i) => i !== m.row) } : s;
case 'Seed':
return m.state;
default:
return assertNever(m);
}
}
+96
View File
@@ -0,0 +1,96 @@
import { describe, it, expect } from 'vitest';
import { StamTable, activeOn, changeCounts, isValid, rowErrors, toJson } from './stamdata';
const professions: StamTable = {
id: 'professions',
label: 'Opleiding → beroep',
temporal: true,
columns: [
{ name: 'program', type: 'text', isKey: true, options: [] },
{ name: 'beroep', type: 'text', isKey: false, options: [] },
{ name: 'geldigVan', type: 'date', isKey: false, options: [] },
{ name: 'geldigTot', type: 'date', isKey: false, options: [] },
],
};
const row = (program: string, beroep: string, van: string, tot = ''): Record<string, string> => ({
program,
beroep,
geldigVan: van,
geldigTot: tot,
});
describe('activeOn (valid-time, half-open [van, tot))', () => {
it('includes a row whose window covers the date', () => {
expect(activeOn(professions, row('a', 'A', '2000-01-01'), '2020-01-01')).toBe(true);
});
it('excludes a row before its geldigVan', () => {
expect(activeOn(professions, row('a', 'A', '2000-01-01'), '1999-01-01')).toBe(false);
});
it('excludes on the geldigTot boundary (half-open)', () => {
expect(activeOn(professions, row('a', 'A', '2000-01-01', '2020-01-01'), '2020-01-01')).toBe(
false,
);
expect(activeOn(professions, row('a', 'A', '2000-01-01', '2020-01-01'), '2019-12-31')).toBe(
true,
);
});
});
describe('rowErrors / isValid (format only)', () => {
it('flags a blank key', () => {
expect(rowErrors(professions, [row('', 'A', '2000-01-01')])[0]).not.toBe('');
});
it('flags a missing geldigVan on a temporal table', () => {
expect(rowErrors(professions, [row('a', 'A', '')])[0]).not.toBe('');
});
it('flags geldigTot on or before geldigVan', () => {
expect(rowErrors(professions, [row('a', 'A', '2020-01-01', '2020-01-01')])[0]).not.toBe('');
});
it('passes a well-formed row', () => {
expect(isValid(professions, [row('a', 'A', '2000-01-01')])).toBe(true);
});
});
describe('changeCounts (diff against the loaded snapshot, by key)', () => {
const original = [row('a', 'A', '2000-01-01'), row('b', 'B', '2000-01-01')];
it('counts an added key', () => {
const draft = [...original, row('c', 'C', '2000-01-01')];
expect(changeCounts(professions, original, draft)).toEqual({ added: 1, removed: 0, edited: 0 });
});
it('counts a removed key', () => {
expect(changeCounts(professions, original, [original[0]])).toEqual({
added: 0,
removed: 1,
edited: 0,
});
});
it('counts an edited cell', () => {
const draft = [row('a', 'CHANGED', '2000-01-01'), original[1]];
expect(changeCounts(professions, original, draft)).toEqual({ added: 0, removed: 0, edited: 1 });
});
});
describe('toJson (draft → file shape)', () => {
it('reconstructs an open-ended geldigTot as null and pretty-prints', () => {
const json = toJson(professions, [row('a', 'Arts', '2000-01-01')]);
expect(JSON.parse(json)).toEqual([
{ program: 'a', beroep: 'Arts', geldigVan: '2000-01-01', geldigTot: null },
]);
expect(json.endsWith('\n')).toBe(true);
});
it('coerces a number column', () => {
const table: StamTable = {
id: 't',
label: 't',
temporal: false,
columns: [
{ name: 'code', type: 'text', isKey: true, options: [] },
{ name: 'jaar', type: 'number', isKey: false, options: [] },
],
};
expect(JSON.parse(toJson(table, [{ code: 'x', jaar: '2020' }]))).toEqual([
{ code: 'x', jaar: 2020 },
]);
});
});
+130
View File
@@ -0,0 +1,130 @@
// Domain model for stamdata maintenance (ADR-0004). Pure TS, no Angular. A table is a
// reflected column schema + editable rows; the pure functions below cover validation
// (FORMAT only — the CI build + StamdataValidationTests stay the authority), the
// valid-time preview filter, the change diff, and serialization back to the file shape.
export type ColumnType = 'text' | 'date' | 'number' | 'enum';
export interface StamColumn {
name: string;
type: ColumnType;
isKey: boolean;
options: readonly string[];
}
export interface StamTable {
id: string;
label: string;
columns: readonly StamColumn[];
temporal: boolean;
}
/**
* An editable row: every cell is the text the user edits ('' = empty). Typed values
* (number, null geldigTot) are reconstructed at export time — see {@link toJson}.
*/
export type StamRow = Record<string, string>;
export interface ChangeCounts {
added: number;
removed: number;
edited: number;
}
const GELDIG_VAN = 'geldigVan';
const GELDIG_TOT = 'geldigTot';
export function keyColumn(table: StamTable): StamColumn {
return table.columns.find((c) => c.isKey) ?? table.columns[0];
}
export function keyOf(table: StamTable, row: StamRow): string {
return row[keyColumn(table).name] ?? '';
}
export function emptyRow(table: StamTable): StamRow {
const row: StamRow = {};
for (const c of table.columns) row[c.name] = '';
return row;
}
/**
* Valid-time membership, half-open [van, tot) — the same rule the backend applies, done
* client-side so the editor's "geldig op" preview is instant and never drops unsaved edits.
* ISO yyyy-MM-dd strings compare correctly lexicographically. Non-temporal tables: all rows.
*/
export function activeOn(table: StamTable, row: StamRow, on: string): boolean {
if (!table.temporal) return true;
const van = row[GELDIG_VAN] ?? '';
const tot = row[GELDIG_TOT] ?? '';
return van !== '' && van <= on && (tot === '' || on < tot);
}
/** Per-row FORMAT error (index-aligned; '' = valid). Cross-row overlap is the CI gate's job. */
export function rowErrors(table: StamTable, rows: readonly StamRow[]): string[] {
const key = keyColumn(table).name;
return rows.map((row) => {
if ((row[key] ?? '').trim() === '')
return $localize`:@@beheer.validation.key:Vul de sleutelkolom in.`;
if (table.temporal) {
const van = row[GELDIG_VAN] ?? '';
const tot = row[GELDIG_TOT] ?? '';
if (van === '') return $localize`:@@beheer.validation.van:Vul een 'geldig van'-datum in.`;
if (tot !== '' && tot <= van)
return $localize`:@@beheer.validation.range:'Geldig tot' moet ná 'geldig van' liggen.`;
}
return '';
});
}
export function isValid(table: StamTable, rows: readonly StamRow[]): boolean {
return rowErrors(table, rows).every((e) => e === '');
}
/** Diff draft against the loaded snapshot, matched by key value. */
export function changeCounts(
table: StamTable,
original: readonly StamRow[],
draft: readonly StamRow[],
): ChangeCounts {
const origByKey = new Map(original.map((r) => [keyOf(table, r), r]));
const draftKeys = new Set(draft.map((r) => keyOf(table, r)));
let added = 0;
let edited = 0;
for (const row of draft) {
const prev = origByKey.get(keyOf(table, row));
if (!prev) added++;
else if (!sameRow(table, prev, row)) edited++;
}
const removed = original.filter((r) => !draftKeys.has(keyOf(table, r))).length;
return { added, removed, edited };
}
function sameRow(table: StamTable, a: StamRow, b: StamRow): boolean {
return table.columns.every((c) => (a[c.name] ?? '') === (b[c.name] ?? ''));
}
/**
* Serialize the draft back to the data-file's JSON shape, reconstructing typed values per
* column: an empty date/number cell becomes null (an open-ended geldigTot), a number cell
* becomes a number, everything else a string. This is the file the admin drops into the
* repo — the existing CI build re-validates it (a bad edit fails the build, never prod).
*/
export function toJson(table: StamTable, rows: readonly StamRow[]): string {
const objects = rows.map((row) => {
const out: Record<string, string | number | null> = {};
for (const c of table.columns) {
const cell = (row[c.name] ?? '').trim();
out[c.name] =
cell === ''
? c.type === 'text' || c.type === 'enum'
? ''
: null
: c.type === 'number'
? Number(cell)
: cell;
}
return out;
});
return JSON.stringify(objects, null, 2) + '\n';
}
@@ -0,0 +1,45 @@
import { Injectable, inject } from '@angular/core';
import { Result, ok, err } from '@shared/kernel/fp';
import { ApiClient } from '@shared/infrastructure/api-client';
import type { AuthzAuditDto } from '@shared/infrastructure/api-client';
import { AuditEntry } from '@beheer/domain/audit-entry';
/**
* Infrastructure adapter for the admin authz/PII-reveal audit trail (`GET /admin/audit`,
* WP-41). The single place the ApiClient lives for audit; the store parses at the boundary.
*/
@Injectable({ providedIn: 'root' })
export class AuditAdapter {
private client = inject(ApiClient);
list(): Promise<AuthzAuditDto[]> {
return this.client.audit();
}
}
/** Trust-boundary parse of the audit rows. */
export function parseAuditEntries(json: unknown): Result<string, AuditEntry[]> {
if (!Array.isArray(json)) return err('audit: not an array');
const out: AuditEntry[] = [];
for (const item of json) {
if (typeof item !== 'object' || item === null) return err('audit: row not an object');
const d = item as AuthzAuditDto;
if (
typeof d.at !== 'string' ||
typeof d.action !== 'string' ||
typeof d.resource !== 'string' ||
typeof d.role !== 'string' ||
typeof d.correlationId !== 'string'
)
return err('audit: missing fields');
out.push({
at: d.at,
action: d.action,
resource: d.resource,
decision: d.decision === 'allow' ? 'allow' : 'deny',
role: d.role,
correlationId: d.correlationId,
});
}
return ok(out);
}
@@ -0,0 +1,45 @@
import { describe, it, expect } from 'vitest';
import { parseStamdataTable } from './stamdata.adapter';
const wire = {
id: 'professions',
label: 'Opleiding → beroep',
temporal: true,
columns: [
{ name: 'program', type: 'text', isKey: true },
{ name: 'beroep', type: 'text', isKey: false },
{ name: 'geldigVan', type: 'date', isKey: false },
{ name: 'geldigTot', type: 'date', isKey: false },
],
rows: [{ program: 'geneeskunde', beroep: 'Arts', geldigVan: '2000-01-01', geldigTot: null }],
};
describe('parseStamdataTable', () => {
it('maps schema + rows and turns a null cell into empty text', () => {
const r = parseStamdataTable(wire);
expect(r.ok).toBe(true);
if (!r.ok) return;
expect(r.value.table.temporal).toBe(true);
expect(r.value.table.columns[0]).toMatchObject({ name: 'program', isKey: true, type: 'text' });
expect(r.value.rows[0]).toEqual({
program: 'geneeskunde',
beroep: 'Arts',
geldigVan: '2000-01-01',
geldigTot: '', // null → '' so the editor renders an empty (open-ended) cell
});
});
it('falls back to text for an unknown column type', () => {
const r = parseStamdataTable({
...wire,
columns: [{ name: 'x', type: 'weird', isKey: true }],
rows: [],
});
if (!r.ok) return;
expect(r.value.table.columns[0].type).toBe('text');
});
it('rejects a response with no columns', () => {
expect(parseStamdataTable({ id: 't', columns: [], rows: [] }).ok).toBe(false);
});
});
@@ -0,0 +1,99 @@
import { Injectable, inject } from '@angular/core';
import { Result, ok, err } from '@shared/kernel/fp';
import { runSubmit } from '@shared/application/submit';
import { ApiClient, StamdataColumnDto } from '@shared/infrastructure/api-client';
import { ColumnType, StamColumn, StamRow, StamTable } from '@beheer/domain/stamdata';
/** A loaded table: its schema plus the rows for editing (or the peildatum-filtered view). */
export interface LoadedTable {
table: StamTable;
rows: StamRow[];
}
const FAILED = $localize`:@@beheer.load.failed:De stamdata kon niet worden geladen.`;
const COLUMN_TYPES: readonly ColumnType[] = ['text', 'date', 'number', 'enum'];
/**
* The only place stamdata HTTP lives (ADR-0001 boundary). Both endpoints are reads; the
* generic `parse*` narrows the untrusted wire shape (schema + opaque rows) into the domain
* model. There is no write method — the edit is downloaded and lands as a PR.
*/
@Injectable({ providedIn: 'root' })
export class StamdataAdapter {
private client = inject(ApiClient);
/** The tables in the catalog (schema only, no rows) — for the table switcher. */
async list(): Promise<Result<string, StamTable[]>> {
const r = await runSubmit(() => this.client.stamdataTables(), FAILED);
if (!r.ok) return r;
const out: StamTable[] = [];
for (const t of r.value ?? []) {
const parsed = parseTable(t);
if (!parsed.ok) return parsed;
out.push(parsed.value);
}
return ok(out);
}
/** One table's schema + rows. `peildatum` (yyyy-MM-dd) asks the server for only the rows
valid on that date; the editor uses it for a server-side cross-check, previewing
locally for instant feedback (see `activeOn`). */
async load(tableId: string, peildatum?: string): Promise<Result<string, LoadedTable>> {
const r = await runSubmit(() => this.client.stamdataTable(tableId, peildatum), FAILED);
return r.ok ? parseStamdataTable(r.value) : r;
}
}
// --- parse: wire → domain, validating at the boundary ---
/** Trust-boundary parse for one table response: schema + rows → domain. Exported so its
spec can exercise it without HTTP (the house `parse*` seam, ADR-0001). */
export function parseStamdataTable(dto: {
id?: string;
label?: string;
columns?: StamdataColumnDto[];
temporal?: boolean;
rows?: readonly unknown[];
}): Result<string, LoadedTable> {
const table = parseTable(dto);
if (!table.ok) return table;
return ok({ table: table.value, rows: parseRows(dto.rows ?? [], table.value.columns) });
}
function parseColumn(dto: StamdataColumnDto): Result<string, StamColumn> {
if (typeof dto.name !== 'string' || dto.name === '') return err('stamdata column: bad name');
const raw = dto.type ?? '';
const type = (COLUMN_TYPES as string[]).includes(raw) ? (raw as ColumnType) : 'text';
return ok({ name: dto.name, type, isKey: dto.isKey === true, options: dto.options ?? [] });
}
function parseTable(dto: {
id?: string;
label?: string;
columns?: StamdataColumnDto[];
temporal?: boolean;
}): Result<string, StamTable> {
if (typeof dto.id !== 'string' || !Array.isArray(dto.columns))
return err('stamdata table: bad shape');
const columns: StamColumn[] = [];
for (const c of dto.columns) {
const parsed = parseColumn(c);
if (!parsed.ok) return parsed;
columns.push(parsed.value);
}
if (columns.length === 0) return err('stamdata table: no columns');
return ok({ id: dto.id, label: dto.label ?? dto.id, columns, temporal: dto.temporal === true });
}
/** Every cell becomes editable text: null → '' (open-ended), number/bool → its string form. */
function parseRows(rows: readonly unknown[], columns: readonly StamColumn[]): StamRow[] {
return rows.map((raw) => {
const row: StamRow = {};
const obj = (raw ?? {}) as Record<string, unknown>;
for (const c of columns) {
const v = obj[c.name];
row[c.name] = v === null || v === undefined ? '' : String(v);
}
return row;
});
}
+2
View File
@@ -0,0 +1,2 @@
// ponytail: see libs/shared/src/test-entry.ts's comment — same reason, same fix.
export {};
+128
View File
@@ -0,0 +1,128 @@
import { Component, computed, effect, inject } from '@angular/core';
import { DatePipe } from '@angular/common';
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 { ASYNC } from '@shared/ui/async/async.component';
import { AccessStore } from '@shared/application/access.store';
import { AuditStore } from '@beheer/application/audit.store';
/**
* Admin page: the persisted authz/PII-reveal audit trail (WP-41/42) — data-minimised, no PII.
* Deny-by-default capability gate (`cases:manage`, reused for admin audit read). Read-only table.
*/
@Component({
selector: 'app-audit-page',
imports: [PageShellComponent, AlertComponent, ButtonComponent, DatePipe, ...ASYNC],
styles: [
`
.scroll {
overflow-x: auto;
}
table {
width: 100%;
border-collapse: collapse;
font-size: var(--rhc-text-font-size-sm);
}
th,
td {
text-align: left;
padding: var(--rhc-space-max-sm) var(--rhc-space-max-md);
border-block-end: var(--rhc-border-width-sm) solid var(--rhc-color-cool-grey-200);
white-space: nowrap;
}
th {
font-weight: var(--rhc-text-font-weight-semi-bold);
}
.deny {
color: var(--rhc-color-rood-600, #a30000);
font-weight: var(--rhc-text-font-weight-semi-bold);
}
`,
],
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 (!canRead()) {
<app-alert type="error">{{ deniedText }}</app-alert>
} @else {
<app-async [data]="store.entries()">
<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 (entries().length === 0) {
<app-alert type="info">{{ emptyText }}</app-alert>
} @else {
<div class="scroll">
<table>
<thead>
<tr>
<th>{{ colTijd }}</th>
<th>{{ colActie }}</th>
<th>{{ colResource }}</th>
<th>{{ colBesluit }}</th>
<th>{{ colRol }}</th>
<th>{{ colCid }}</th>
</tr>
</thead>
<tbody>
@for (e of entries(); track e.at + e.action + e.correlationId) {
<tr>
<td>{{ e.at | date: 'short' }}</td>
<td>{{ e.action }}</td>
<td>{{ e.resource }}</td>
<td [class.deny]="e.decision === 'deny'">{{ e.decision }}</td>
<td>{{ e.role }}</td>
<td>{{ e.correlationId }}</td>
</tr>
}
</tbody>
</table>
</div>
}
</ng-template>
</app-async>
}
</app-page-shell>
`,
})
export class AuditPage {
protected store = inject(AuditStore);
protected access = inject(AccessStore);
protected canRead = computed(() => this.access.can('cases:manage'));
protected entries = computed(() => {
const rd = this.store.entries();
return rd.tag === 'Success' ? rd.value : [];
});
protected heading = $localize`:@@audit.heading:Auditlog`;
protected intro = $localize`:@@audit.intro:Toegangs- en inzagebeslissingen (autorisatie en het tonen van afgeschermde gegevens). Vastgelegd zonder persoonsgegevens.`;
protected deniedText = $localize`:@@audit.denied:U hebt geen rechten om de auditlog te bekijken.`;
protected failedText = $localize`:@@audit.failed:De auditlog kon niet worden geladen.`;
protected emptyText = $localize`:@@audit.empty:Nog geen auditregels.`;
protected retryText = $localize`:@@audit.retry:Opnieuw proberen`;
protected colTijd = $localize`:@@audit.col.tijd:Tijd`;
protected colActie = $localize`:@@audit.col.actie:Actie`;
protected colResource = $localize`:@@audit.col.resource:Resource`;
protected colBesluit = $localize`:@@audit.col.besluit:Besluit`;
protected colRol = $localize`:@@audit.col.rol:Rol`;
protected colCid = $localize`:@@audit.col.cid:Correlatie-id`;
private loadRequested = false;
constructor() {
effect(() => {
if (this.canRead() && !this.loadRequested) {
this.loadRequested = true;
void this.store.load();
}
});
}
protected reload() {
void this.store.load();
}
}
+98
View File
@@ -0,0 +1,98 @@
import { Component, computed, 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 { ASYNC } from '@shared/ui/async/async.component';
import { AccessStore } from '@shared/application/access.store';
import { FeatureFlagStore } from '@shared/application/feature-flags.store';
/**
* Admin page: toggle runtime feature flags (WP-47). Deny-by-default capability gate
* (`flags:manage`). The catalog is server-owned (code); this only flips the on/off state, which
* the whole app reads via the same `FeatureFlagStore`.
*/
@Component({
selector: 'app-feature-flags-page',
imports: [PageShellComponent, AlertComponent, ButtonComponent, ...ASYNC],
styles: [
`
.flag {
display: flex;
align-items: center;
justify-content: space-between;
gap: var(--rhc-space-max-lg);
padding: var(--rhc-space-max-md) 0;
border-block-end: var(--rhc-border-width-sm) solid var(--rhc-color-cool-grey-200);
}
.flag .meta {
min-inline-size: 0;
}
.flag .key {
font-family: monospace;
font-size: var(--rhc-text-font-size-sm);
color: var(--rhc-color-grijs-700);
}
.state {
font-weight: var(--rhc-text-font-weight-semi-bold);
margin-inline-end: var(--rhc-space-max-md);
}
`,
],
template: `
<app-page-shell [heading]="heading" [intro]="intro" backLink="/dashboard">
@if (!access.ready()) {
<!-- wait for /me before deciding -->
} @else if (!canManage()) {
<app-alert type="error">{{ deniedText }}</app-alert>
} @else {
<app-async [data]="store.flags()">
<ng-template appAsyncError>
<app-alert type="error">{{ failedText }}</app-alert>
<app-button variant="secondary" (click)="reload()">{{ retryText }}</app-button>
</ng-template>
<ng-template appAsyncLoaded>
@for (f of store.all(); track f.key) {
<div class="flag">
<div class="meta">
<div>{{ f.description }}</div>
<div class="key">{{ f.key }}</div>
</div>
<div>
<span class="state">{{ f.enabled ? onText : offText }}</span>
<app-button
[variant]="f.enabled ? 'secondary' : 'primary'"
(click)="toggle(f.key, !f.enabled)"
>{{ f.enabled ? disableText : enableText }}</app-button
>
</div>
</div>
}
</ng-template>
</app-async>
}
</app-page-shell>
`,
})
export class FeatureFlagsPage {
protected store = inject(FeatureFlagStore);
protected access = inject(AccessStore);
protected canManage = computed(() => this.access.can('flags:manage'));
protected heading = $localize`:@@flags.heading:Functievlaggen`;
protected intro = $localize`:@@flags.intro:Zet functionaliteit aan of uit tijdens runtime. De catalogus staat vast in code; hier beheert u de status.`;
protected deniedText = $localize`:@@flags.denied:U hebt geen rechten om functievlaggen te beheren.`;
protected failedText = $localize`:@@flags.failed:De functievlaggen konden niet worden geladen.`;
protected retryText = $localize`:@@flags.retry:Opnieuw proberen`;
protected onText = $localize`:@@flags.on:Aan`;
protected offText = $localize`:@@flags.off:Uit`;
protected enableText = $localize`:@@flags.enable:Aanzetten`;
protected disableText = $localize`:@@flags.disable:Uitzetten`;
protected toggle(key: string, enabled: boolean) {
void this.store.set(key, enabled);
}
protected reload() {
void this.store.load();
}
}
@@ -0,0 +1,262 @@
import { Component, computed, input, output } from '@angular/core';
import { ButtonComponent } from '@shared/ui/button/button.component';
import { ChangeCounts, StamColumn, StamRow, StamTable, activeOn } from '@beheer/domain/stamdata';
interface DisplayRow {
row: StamRow;
index: number;
}
/**
* Organism: the GENERIC stamdata grid. It renders entirely from the reflected column
* schema — one input per column type (native `date`/`number`, `enum` select, text) — so a
* new stamdata table needs zero UI code here. The "geldig op" control filters to the rows
* valid on a date (read-only preview); edits and download work on the full set. Emits
* intent; the store owns state (CLAUDE.md §1).
*/
@Component({
selector: 'app-stamdata-table-editor',
imports: [ButtonComponent],
styles: [
`
:host {
display: block;
}
.toolbar {
display: flex;
flex-wrap: wrap;
gap: 1rem;
align-items: end;
margin-block-end: 1rem;
}
.field label {
display: block;
font-size: 0.85em;
color: var(--rhc-color-foreground-subtle);
}
table {
inline-size: 100%;
}
.err {
color: var(--rhc-color-rood-500);
font-size: 0.85em;
}
.footer {
display: flex;
flex-wrap: wrap;
gap: 1rem;
align-items: center;
margin-block-start: 1rem;
}
.counts {
color: var(--rhc-color-foreground-subtle);
}
.hint {
margin-block-start: 0.5rem;
color: var(--rhc-color-foreground-subtle);
font-size: 0.9em;
}
`,
],
template: `
<div class="toolbar">
@if (tables().length > 1) {
<div class="field">
<label for="stamdata-table">{{ tableLabel }}</label>
<select
id="stamdata-table"
class="form-select"
[value]="selectedTableId()"
(change)="selectTable.emit(asValue($event))"
>
@for (t of tables(); track t.id) {
<option [value]="t.id">{{ t.label }}</option>
}
</select>
</div>
}
@if (table().temporal) {
<div class="field">
<label for="stamdata-peildatum">{{ peildatumLabel }}</label>
<input
id="stamdata-peildatum"
type="date"
class="form-control"
[value]="previewDate()"
(input)="previewDateChanged.emit(asValue($event))"
/>
</div>
@if (previewing()) {
<app-button variant="subtle" (click)="previewDateChanged.emit('')">{{
showAll
}}</app-button>
}
}
</div>
@if (previewing()) {
<p class="hint">{{ previewNote }}</p>
}
<table class="table">
<thead>
<tr>
@for (col of table().columns; track col.name) {
<th scope="col">{{ col.name }}</th>
}
<th scope="col">{{ previewing() ? '' : actionsLabel }}</th>
</tr>
</thead>
<tbody>
@for (item of display(); track item.index) {
<tr>
@for (col of table().columns; track col.name) {
<td>
@if (col.type === 'enum') {
<select
class="form-select"
[value]="item.row[col.name]"
[disabled]="previewing()"
[attr.aria-label]="cellLabel(col, item.index)"
(change)="
cellEdited.emit({ row: item.index, column: col.name, value: asValue($event) })
"
>
<option value=""></option>
@for (opt of col.options; track opt) {
<option [value]="opt">{{ opt }}</option>
}
</select>
} @else {
<input
class="form-control"
[type]="inputType(col)"
[value]="item.row[col.name]"
[class.is-invalid]="!!errors()[item.index]"
[disabled]="previewing()"
[attr.aria-label]="cellLabel(col, item.index)"
(input)="
cellEdited.emit({ row: item.index, column: col.name, value: asValue($event) })
"
/>
}
</td>
}
<td>
@if (!previewing()) {
@if (table().temporal) {
<app-button variant="subtle" (click)="onExpire(item.index)">{{
expireLabel
}}</app-button>
}
<app-button
variant="subtle"
[attr.aria-label]="removeLabel"
(click)="onRemove(item.index)"
>{{ removeLabel }}</app-button
>
}
@if (errors()[item.index]) {
<span class="err">{{ errors()[item.index] }}</span>
}
</td>
</tr>
}
</tbody>
</table>
@if (!previewing()) {
<div class="footer">
<app-button variant="subtle" [disabled]="!canUndo()" (click)="undo.emit()">{{
undoLabel
}}</app-button>
<app-button variant="subtle" [disabled]="!canRedo()" (click)="redo.emit()">{{
redoLabel
}}</app-button>
<app-button variant="secondary" (click)="rowAdded.emit()">{{ addRowLabel }}</app-button>
<span class="counts">{{ countsLabel() }}</span>
<app-button variant="primary" [disabled]="!canDownload()" (click)="download.emit()">{{
downloadLabel
}}</app-button>
</div>
<p class="hint">{{ applyHint }}</p>
}
`,
})
export class StamdataTableEditorComponent {
table = input.required<StamTable>();
rows = input.required<readonly StamRow[]>();
errors = input.required<readonly string[]>();
counts = input.required<ChangeCounts>();
previewDate = input('');
canDownload = input(false);
canUndo = input(false);
canRedo = input(false);
tables = input<readonly StamTable[]>([]);
selectedTableId = input<string | null>(null);
selectTable = output<string>();
cellEdited = output<{ row: number; column: string; value: string }>();
rowAdded = output<void>();
rowRemoved = output<number>();
previewDateChanged = output<string>();
download = output<void>();
undo = output<void>();
redo = output<void>();
protected previewing = computed(() => this.previewDate() !== '');
protected display = computed<DisplayRow[]>(() =>
this.rows()
.map((row, index) => ({ row, index }))
.filter(({ row }) => !this.previewing() || activeOn(this.table(), row, this.previewDate())),
);
protected inputType(col: StamColumn): string {
return col.type === 'date' ? 'date' : col.type === 'number' ? 'number' : 'text';
}
protected cellLabel(col: StamColumn, index: number): string {
return `${col.name} — rij ${index + 1}`;
}
protected asValue(e: Event): string {
return (e.target as HTMLInputElement | HTMLSelectElement).value;
}
private addedWord = $localize`:@@beheer.added:toegevoegd`;
private editedWord = $localize`:@@beheer.edited:gewijzigd`;
private removedWord = $localize`:@@beheer.removed:verwijderd`;
protected countsLabel = computed(() => {
const c = this.counts();
return `${c.added} ${this.addedWord} · ${c.edited} ${this.editedWord} · ${c.removed} ${this.removedWord}`;
});
protected tableLabel = $localize`:@@beheer.table:Tabel`;
protected peildatumLabel = $localize`:@@beheer.peildatum:Toon geldig op`;
protected showAll = $localize`:@@beheer.showAll:Toon alles`;
protected previewNote = $localize`:@@beheer.previewNote:Voorbeeld: alleen de rijen die op deze datum geldig zijn. Bewerken staat uit.`;
protected actionsLabel = $localize`:@@beheer.actions:Acties`;
protected removeLabel = $localize`:@@beheer.remove:Verwijderen`;
protected expireLabel = $localize`:@@beheer.expire:Sluiten per vandaag`;
private removeConfirm = $localize`:@@beheer.removeConfirm:Rij verwijderen? Als andere gegevens ernaar verwijzen, faalt de build-controle (CI). Bij een tabel met een geldigheidsperiode kunt u de rij beter sluiten (geldig tot) in plaats van verwijderen.`;
/** Deletions can orphan a reference (the CI gate catches it); confirm first (WP-48). */
protected onRemove(index: number) {
if (confirm(this.removeConfirm)) this.rowRemoved.emit(index);
}
/** Steer temporal tables toward expiring (close the validity per today) over hard delete —
preserves history and can't orphan a reference that was valid earlier (WP-48). */
protected onExpire(index: number) {
const col = this.table().columns.find((c) => /geldigtot/i.test(c.name));
if (col) this.cellEdited.emit({ row: index, column: col.name, value: this.today });
}
private today = new Date().toISOString().slice(0, 10);
protected undoLabel = $localize`:@@beheer.undo:Ongedaan maken`;
protected redoLabel = $localize`:@@beheer.redo:Opnieuw uitvoeren`;
protected addRowLabel = $localize`:@@beheer.addRow:Rij toevoegen`;
protected downloadLabel = $localize`:@@beheer.download:Download JSON`;
protected applyHint = $localize`:@@beheer.applyHint:Wijzigingen worden als JSON-bestand gedownload en via een pull request toegepast — de build (CI) controleert ze.`;
}
@@ -0,0 +1,69 @@
import type { Meta, StoryObj } from '@storybook/angular';
import { StamdataTableEditorComponent } from './stamdata-table-editor.component';
import { StamRow, StamTable, changeCounts, rowErrors } from '@beheer/domain/stamdata';
const table: StamTable = {
id: 'professions',
label: 'Opleiding → beroep',
temporal: true,
columns: [
{ name: 'program', type: 'text', isKey: true, options: [] },
{ name: 'beroep', type: 'text', isKey: false, options: [] },
{ name: 'geldigVan', type: 'date', isKey: false, options: [] },
{ name: 'geldigTot', type: 'date', isKey: false, options: [] },
],
};
const rows: StamRow[] = [
{ program: 'geneeskunde', beroep: 'Arts', geldigVan: '2000-01-01', geldigTot: '' },
{ program: 'verpleegkunde', beroep: 'Verpleegkundige', geldigVan: '2000-01-01', geldigTot: '' },
{
program: 'fysiotherapie',
beroep: 'Fysiotherapeut',
geldigVan: '2000-01-01',
geldigTot: '2020-01-01',
},
];
const meta: Meta<StamdataTableEditorComponent> = {
title: 'Domein/Beheer/Stamdata Table Editor',
component: StamdataTableEditorComponent,
args: {
table,
rows,
errors: rowErrors(table, rows),
counts: changeCounts(table, rows, rows),
previewDate: '',
canDownload: false,
tables: [table],
selectedTableId: 'professions',
},
};
export default meta;
type Story = StoryObj<StamdataTableEditorComponent>;
export const Editing: Story = {};
export const Dirty: Story = {
args: {
counts: { added: 1, edited: 1, removed: 0 },
canDownload: true,
},
};
export const Invalid: Story = {
args: {
rows: [
{ program: '', beroep: 'Arts', geldigVan: '2000-01-01', geldigTot: '' },
...rows.slice(1),
],
errors: rowErrors(table, [
{ program: '', beroep: 'Arts', geldigVan: '2000-01-01', geldigTot: '' },
...rows.slice(1),
]),
},
};
export const PeildatumPreview: Story = {
args: { previewDate: '2021-01-01' },
};
+105
View File
@@ -0,0 +1,105 @@
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 { ASYNC } from '@shared/ui/async/async.component';
import { AccessStore } from '@shared/application/access.store';
import { StamdataStore } from '@beheer/application/stamdata.store';
import { StamdataTableEditorComponent } from '@beheer/ui/stamdata-table-editor/stamdata-table-editor.component';
/**
* Page: thin container for the stamdata maintenance editor (ADR-0004). Deny-by-default
* capability gate (`stamdata:edit`) — a denial alert for non-admins, the generic grid for
* admins. Loads once the capability resolves; wires store commands to the organism.
*/
@Component({
selector: 'app-stamdata-page',
host: { '(document:keydown)': 'onKeydown($event)' },
imports: [
PageShellComponent,
AlertComponent,
ButtonComponent,
...ASYNC,
StamdataTableEditorComponent,
],
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 (!canEdit()) {
<app-alert type="error">{{ deniedText }}</app-alert>
} @else {
<app-async [data]="store.remoteData()">
<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 (store.table(); as table) {
<app-stamdata-table-editor
[table]="table"
[rows]="store.rows()"
[errors]="store.errors()"
[counts]="store.counts()"
[previewDate]="store.previewDate()"
[canDownload]="store.canDownload()"
[canUndo]="store.canUndo()"
[canRedo]="store.canRedo()"
[tables]="store.tables()"
[selectedTableId]="store.selectedTableId()"
(selectTable)="store.selectTable($event)"
(cellEdited)="store.editCell($event.row, $event.column, $event.value)"
(rowAdded)="store.addRow()"
(rowRemoved)="store.removeRow($event)"
(previewDateChanged)="store.setPreviewDate($event)"
(download)="store.download()"
(undo)="store.undo()"
(redo)="store.redo()"
/>
}
</ng-template>
</app-async>
}
</app-page-shell>
`,
})
export class StamdataPage {
protected store = inject(StamdataStore);
protected access = inject(AccessStore);
protected canEdit = computed(() => this.access.can('stamdata:edit'));
protected heading = $localize`:@@beheer.page.heading:Stamdata onderhouden`;
protected intro = $localize`:@@beheer.page.intro:Beheer de business-tabellen die de registratie stuurt. Wijzigingen worden als JSON gedownload en via een pull request toegepast; de build blijft de bewaker.`;
protected deniedText = $localize`:@@beheer.page.denied:U hebt geen rechten om stamdata te onderhouden.`;
protected failedText = $localize`:@@beheer.page.failed:De stamdata kon niet worden geladen.`;
protected retryText = $localize`:@@beheer.page.retry:Opnieuw proberen`;
private loadRequested = false;
constructor() {
// Load once the capability resolves to `allowed` (a 403 GET would be wasted otherwise).
// Depends only on canEdit() + a plain flag — never on the store model, so dispatching
// `Loading` inside load() can't retrigger this effect (the WP-26 runaway-loop lesson).
effect(() => {
if (this.canEdit() && !this.loadRequested) {
this.loadRequested = true;
void this.store.load();
}
});
}
protected reload() {
void this.store.load();
}
/** Ctrl/Cmd+Z undo, Ctrl/Cmd+Shift+Z redo (WP-32). Ignored while focus is in a grid
cell input so the browser's native text-undo still works there (mirrors brief.page). */
protected onKeydown(e: KeyboardEvent) {
if (!this.canEdit() || !(e.ctrlKey || e.metaKey) || (e.key !== 'z' && e.key !== 'Z')) return;
const t = e.target as HTMLElement | null;
if (t && (t.isContentEditable || ['INPUT', 'SELECT', 'TEXTAREA'].includes(t.tagName))) return;
e.preventDefault();
if (e.shiftKey) this.store.redo();
else this.store.undo();
}
}