feat(stamdata): admin stamdata maintenance editor (beheer)

Realizes ADR-0004's "future low-code editor that commits a PR": an
admin-only stamdata maintenance editor built on the stamdata-as-code
foundation.

Backend: `professions` moves from a hardcoded C# dictionary to an embedded
`professions.json` data-file (typed as `ProfessionMapping`) with valid-time
(geldigVan/geldigTot, half-open). A generic, reflection-driven
StamdataCatalog/StamdataTable/StamdataFile describes every table so one
endpoint pair + one grid editor serve all of them; add a table in one line.
Two read-only, admin-gated endpoints (GET /stamdata, GET /stamdata/{table}
?peildatum=) — no runtime write path. Generic build gate
`Every_catalog_table_is_valid` (keys non-blank, no overlapping validity,
well-formed windows).

Frontend: new `beheer` context (route beheer/stamdata, capabilityGuard
'stamdata:edit'). A schema-driven grid editor edits rows locally; download()
emits {table}.json for the admin to commit as a reviewed PR (no mutation
command — the CI build + StamdataValidationTests stay the authority).

Full gate GREEN both sides; gen:api leaves no drift; new stamdata story
passes axe. See WP-29 + ADR-0004.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
eho
2026-07-21 13:43:51 +02:00
co-authored by Claude Opus 4.8
parent c459fa0a60
commit 0e77faf351
32 changed files with 7822 additions and 2284 deletions
+8
View File
@@ -60,6 +60,14 @@ export const routes: Routes = [
loadComponent: () =>
import('@brief/ui/org-template.page').then((m) => m.OrgTemplatePage),
},
{
path: 'beheer/stamdata',
// Admin-only stamdata maintenance editor (ADR-0004): capabilityGuard denies-by-default
// unless GET /me resolved `stamdata:edit` (Admin role). Backend re-enforces via the
// StamdataAdmin gate — the guard just avoids loading a page that would 403.
canActivate: [capabilityGuard('stamdata:edit')],
loadComponent: () => import('@beheer/ui/stamdata.page').then((m) => m.StamdataPage),
},
{
path: 'concepts',
loadComponent: () => import('./showcase/concepts.page').then((m) => m.ConceptsPage),
@@ -0,0 +1,132 @@
import { Injectable, computed, inject, signal } from '@angular/core';
import { RemoteData } from '@shared/application/remote-data';
import { createStore } from '@shared/application/store';
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<RemoteData<Error | undefined, LoadedState>>(() => {
const s = this.model();
switch (s.tag) {
case 'loading':
return { tag: 'Loading' };
case 'failed':
return { tag: 'Failure', error: new Error(s.reason) };
case 'loaded':
return { tag: 'Success', value: s };
}
});
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.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);
}
editCell(row: number, column: string, value: string) {
this.store.dispatch({ tag: 'CellEdited', row, column, value });
}
addRow() {
this.store.dispatch({ tag: 'RowAdded' });
}
removeRow(row: number) {
this.store.dispatch({ tag: 'RowRemoved', row });
}
/** 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[];
}
@@ -0,0 +1,57 @@
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);
}
}
+86
View File
@@ -0,0 +1,86 @@
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 }]);
});
});
+126
View File
@@ -0,0 +1,126 @@
// 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,41 @@
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,94 @@
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;
});
}
@@ -0,0 +1,230 @@
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()) {
<app-button
variant="subtle"
[attr.aria-label]="removeLabel"
(click)="rowRemoved.emit(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="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);
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>();
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 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,61 @@
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' },
};
+83
View File
@@ -0,0 +1,83 @@
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',
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()"
[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()"
/>
}
</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();
}
}
+6 -1
View File
@@ -2,4 +2,9 @@
* A stable, namespaced capability string (PRD-0002 §5a), e.g. `brief:approve`.
* Server-resolved and opaque to the FE — never derived from a role client-side.
*/
export type Capability = 'brief:approve' | 'brief:reject' | 'brief:send' | 'orgtemplate:edit';
export type Capability =
| 'brief:approve'
| 'brief:reject'
| 'brief:send'
| 'orgtemplate:edit'
| 'stamdata:edit';
+118
View File
@@ -263,6 +263,102 @@ export class ApiClient {
return Promise.resolve<IntakePolicyDto>(null as any);
}
/**
* @return OK
*/
stamdataTables(): Promise<StamdataTableSummaryDto[]> {
let url_ = this.baseUrl + "/api/v1/stamdata";
url_ = url_.replace(/[?&]$/, "");
let options_: RequestInit = {
method: "GET",
headers: {
"Accept": "application/json"
}
};
return this.http.fetch(url_, options_).then((_response: Response) => {
return this.processStamdataTables(_response);
});
}
protected processStamdataTables(response: Response): Promise<StamdataTableSummaryDto[]> {
const status = response.status;
let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); };
if (status === 200) {
return response.text().then((_responseText) => {
let result200: any = null;
result200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver) as StamdataTableSummaryDto[];
return result200;
});
} else if (status === 403) {
return response.text().then((_responseText) => {
let result403: any = null;
result403 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver) as ProblemDetails;
return throwException("Forbidden", status, _responseText, _headers, result403);
});
} else if (status !== 200 && status !== 204) {
return response.text().then((_responseText) => {
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
});
}
return Promise.resolve<StamdataTableSummaryDto[]>(null as any);
}
/**
* @param peildatum (optional)
* @return OK
*/
stamdataTable(table: string, peildatum?: string | undefined): Promise<StamdataTableDto> {
let url_ = this.baseUrl + "/api/v1/stamdata/{table}?";
if (table === undefined || table === null)
throw new globalThis.Error("The parameter 'table' must be defined.");
url_ = url_.replace("{table}", encodeURIComponent("" + table));
if (peildatum === null)
throw new globalThis.Error("The parameter 'peildatum' cannot be null.");
else if (peildatum !== undefined)
url_ += "peildatum=" + encodeURIComponent("" + peildatum) + "&";
url_ = url_.replace(/[?&]$/, "");
let options_: RequestInit = {
method: "GET",
headers: {
"Accept": "application/json"
}
};
return this.http.fetch(url_, options_).then((_response: Response) => {
return this.processStamdataTable(_response);
});
}
protected processStamdataTable(response: Response): Promise<StamdataTableDto> {
const status = response.status;
let _headers: any = {}; if (response.headers && response.headers.forEach) { response.headers.forEach((v: any, k: any) => _headers[k] = v); };
if (status === 200) {
return response.text().then((_responseText) => {
let result200: any = null;
result200 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver) as StamdataTableDto;
return result200;
});
} else if (status === 403) {
return response.text().then((_responseText) => {
let result403: any = null;
result403 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver) as ProblemDetails;
return throwException("Forbidden", status, _responseText, _headers, result403);
});
} else if (status === 404) {
return response.text().then((_responseText) => {
return throwException("Not Found", status, _responseText, _headers);
});
} else if (status !== 200 && status !== 204) {
return response.text().then((_responseText) => {
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
});
}
return Promise.resolve<StamdataTableDto>(null as any);
}
/**
* @return OK
*/
@@ -1858,6 +1954,28 @@ export interface SaveOrgTemplateRequest {
draft?: OrgTemplateDto;
}
export interface StamdataColumnDto {
name?: string | undefined;
type?: string | undefined;
isKey?: boolean;
options?: string[] | undefined;
}
export interface StamdataTableDto {
id?: string | undefined;
label?: string | undefined;
columns?: StamdataColumnDto[] | undefined;
temporal?: boolean;
rows?: any[] | undefined;
}
export interface StamdataTableSummaryDto {
id?: string | undefined;
label?: string | undefined;
columns?: StamdataColumnDto[] | undefined;
temporal?: boolean;
}
export interface SubOrgSummaryDto {
subOrgId?: string | undefined;
orgName?: string | undefined;
@@ -8,6 +8,7 @@ const KNOWN: readonly Capability[] = [
'brief:reject',
'brief:send',
'orgtemplate:edit',
'stamdata:edit',
];
/**