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
@@ -6,6 +6,12 @@
<ImplicitUsings>enable</ImplicitUsings>
</PropertyGroup>
<ItemGroup>
<!-- Stamdata data-files (config-as-code, ADR-0004) are embedded so they read the
same from the running API and the test assembly — no cwd/docker-mount path fuss. -->
<EmbeddedResource Include="Stamdata\*.json" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="10.0.9">
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
@@ -46,6 +46,15 @@ public sealed record DuoLookupDto(IReadOnlyList<DuoDiplomaDto> Diplomas, ManualD
public sealed record IntakePolicyDto(int ScholingThreshold);
// --- Stamdata maintenance (ADR-0004): generic, schema-driven so ONE contract serves
// every business-editable table. Columns are reflected from the table's typed record;
// Rows are the raw JSON objects (opaque here — the editor renders them by column type).
public sealed record StamdataColumnDto(string Name, string Type, bool IsKey, IReadOnlyList<string>? Options);
public sealed record StamdataTableSummaryDto(string Id, string Label, IReadOnlyList<StamdataColumnDto> Columns, bool Temporal);
public sealed record StamdataTableDto(
string Id, string Label, IReadOnlyList<StamdataColumnDto> Columns, bool Temporal,
IReadOnlyList<System.Text.Json.JsonElement> Rows);
// --- Document upload contracts ---
public sealed record DocumentCategoryDto(
@@ -43,7 +43,7 @@ public static class Authz
public static IReadOnlyList<string> RoleCapabilities(Principal principal) => principal.Role switch
{
PrincipalRole.Approver => new[] { "brief:approve", "brief:reject", "brief:send" },
PrincipalRole.Admin => new[] { "orgtemplate:edit" },
PrincipalRole.Admin => new[] { "orgtemplate:edit", "stamdata:edit" },
_ => Array.Empty<string>(),
};
@@ -64,6 +64,11 @@ public static class Authz
/// have no per-resource state to weigh, so role IS the whole decision here.
public static bool CanManageOrgTemplates(Principal principal) => principal.Role == PrincipalRole.Admin;
/// Stamdata maintenance (ADR-0004): admin-only, resource-independent — same shape as
/// org-template management (role IS the decision). Gates the read-only /stamdata endpoints
/// the maintenance editor consumes; the actual edit lands as a reviewed PR, not a write here.
public static bool CanEditStamdata(Principal principal) => principal.Role == PrincipalRole.Admin;
/// Field-level PII (PRD-0002 §5c, phase P2): the case screen's BIG-nummer ships
/// masked by default; only the behandelaar (Drafter) composing the case — the actor
/// whose behandel-scherm shows the field — may reveal it. Role-based in the POC; a
+41
View File
@@ -9,6 +9,7 @@ using BigRegister.Domain.Intake;
using BigRegister.Domain.Letters;
using BigRegister.Domain.Registrations;
using BigRegister.Domain.Submissions;
using BigRegister.Stamdata;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Logging.Console;
@@ -100,6 +101,33 @@ api.MapGet("/duo/diplomas", () => new DuoLookupDto(
api.MapGet("/intake/policy", () => new IntakePolicyDto(IntakePolicy.ScholingThreshold));
// --- Stamdata maintenance (ADR-0004): generic, schema-driven reads for the admin editor.
// One pair of endpoints serves every business-editable table; the editor renders from the
// reflected column schema and produces an edited JSON file the admin drops into the repo
// (the existing CI build + StamdataValidationTests stay the authority — no write endpoint).
// Admin-gated, mirroring OrgAdmin. ---
api.MapGet("/stamdata", (HttpContext ctx) => StamdataAdmin(ctx, () =>
Results.Ok(StamdataCatalog.All.Select(t =>
new StamdataTableSummaryDto(t.Id, t.Label, t.Columns.Select(ToColumnDto).ToList(), t.Temporal)).ToList())))
.WithName("stamdataTables")
.Produces<List<StamdataTableSummaryDto>>()
.ProducesProblem(StatusCodes.Status403Forbidden);
// peildatum (optional): omitted = all rows (edit view); given = only rows valid on that
// date (the temporal preview — "which mappings applied on date X").
api.MapGet("/stamdata/{table}", (string table, string? peildatum, HttpContext ctx) => StamdataAdmin(ctx, () =>
{
var t = StamdataCatalog.Find(table);
if (t is null) return Results.NotFound();
var rows = peildatum is { Length: > 0 } p ? t.RowsOn(DateOnly.Parse(p)) : t.Rows();
return Results.Ok(new StamdataTableDto(t.Id, t.Label, t.Columns.Select(ToColumnDto).ToList(), t.Temporal, rows));
}))
.WithName("stamdataTable")
.Produces<StamdataTableDto>()
.ProducesProblem(StatusCodes.Status403Forbidden)
.Produces(StatusCodes.Status404NotFound);
// --- POST: submits. The server is the authority; it re-validates and decides. ---
api.MapPost("/registrations", (RegistratieRequest req, HttpContext ctx) =>
@@ -471,6 +499,19 @@ IResult OrgAdmin(HttpContext ctx, Func<IResult> action)
statusCode: StatusCodes.Status403Forbidden);
}
// One gate for every stamdata read endpoint — the enforce twin of the `stamdata:edit`
// capability RoleCapabilities emits (single Authz source). A denial is audited.
IResult StamdataAdmin(HttpContext ctx, Func<IResult> action)
{
var principal = Authz.ResolvePrincipal(ctx);
if (Authz.CanEditStamdata(principal)) return action();
AuditAuthz(ctx, "stamdata:edit", "stamdata", false, principal);
return Results.Problem(detail: "Alleen een beheerder mag stamdata onderhouden.",
statusCode: StatusCodes.Status403Forbidden);
}
static StamdataColumnDto ToColumnDto(StamdataColumn c) => new(c.Name, c.Type, c.IsKey, c.Options);
// Authorization audit (PRD-0002 §8): access-relevant decisions recorded with NO PII —
// action, resource ref, allow/deny, acting role, correlation id. Never the value that
// was (or wasn't) revealed. Mirrors the no-PII Submit audit below.
@@ -0,0 +1,14 @@
namespace BigRegister.Stamdata;
/// <summary>
/// One row of the profession↔program stamdata (config-as-code, ADR-0004): which BIG
/// profession (beroep) a study program (opleiding) leads to, and the period that mapping
/// is valid. The first property (<see cref="Program"/>) is the table key by convention
/// (see <c>StamdataTable</c>); <see cref="GeldigVan"/>/<see cref="GeldigTot"/> are the
/// valid-time window (half-open <c>[van, tot)</c>) — a null <see cref="GeldigTot"/> means
/// "still valid". A future <see cref="GeldigVan"/> pre-schedules a mapping.
///
/// This is the typed shape <c>professions.json</c> deserializes into, so every consumer
/// stays compile-typed; the authored values are gated by <c>StamdataValidationTests</c>.
/// </summary>
public sealed record ProfessionMapping(string Program, string Beroep, DateOnly GeldigVan, DateOnly? GeldigTot);
@@ -1,30 +1,30 @@
namespace BigRegister.Stamdata;
/// <summary>
/// BUSINESS-EDITABLE STAMDATA (config-as-code). Which BIG profession (beroep) each
/// study program (opleiding) maps to. This is the one table the business tunes when
/// a program starts or stops leading to a registered profession.
/// BUSINESS-EDITABLE STAMDATA (config-as-code). Which BIG profession (beroep) each study
/// program (opleiding) maps to, and when that mapping is valid. The one table the business
/// tunes when a program starts or stops leading to a registered profession.
///
/// Change it by editing this file and opening a PR — NOT via a production database.
/// The C# compiler catches shape/type mistakes; <c>StamdataValidationTests</c> catches
/// the referential integrity it can't (e.g. a seeded diploma whose program has no
/// profession here). So a bad edit fails the build, never prod. See ADR-0004
/// (docs/reference/architecture/0004-stamdata-as-code.md).
/// The data lives in <c>professions.json</c> (edit it and open a PR — NOT a production
/// database); it deserializes into <see cref="ProfessionMapping"/> here. The C# compiler
/// checks every consumer of this typed shape; <c>StamdataValidationTests</c> checks the
/// authored values (malformed rows, dangling references, overlapping validity). A bad edit
/// fails the build, never prod. See ADR-0004.
///
/// This is DATA, not logic: the rules that consume it (which questions a diploma needs,
/// how a manual diploma is treated) stay in <c>DiplomaRules</c>.
/// This is DATA, not logic: the rules that consume it (which questions a diploma needs, how
/// a manual diploma is treated) stay in <c>DiplomaRules</c>.
/// </summary>
public static class Professions
{
/// <summary>Every mapping in the data-file, typed.</summary>
public static readonly IReadOnlyList<ProfessionMapping> Mappings = StamdataFile.Load<ProfessionMapping>("professions");
/// <summary>The mappings valid today, as a program→beroep lookup. Consumers that don't
/// yet reason about a peildatum (e.g. <c>DiplomaRules.ProfessionFor</c>) use this — it
/// preserves the pre-valid-time behaviour exactly while the file's rows are all current.</summary>
public static readonly IReadOnlyDictionary<string, string> ByProgram =
new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
["geneeskunde"] = "Arts",
["verpleegkunde"] = "Verpleegkundige",
["fysiotherapie"] = "Fysiotherapeut",
["farmacie"] = "Apotheker",
["tandheelkunde"] = "Tandarts",
};
Mappings.Where(m => StamdataFile.ActiveOn(m.GeldigVan, m.GeldigTot, DateOnly.FromDateTime(DateTime.Today)))
.ToDictionary(m => m.Program, m => m.Beroep, StringComparer.OrdinalIgnoreCase);
/// <summary>Distinct professions, in declaration order — the list a user may declare
/// for a manual (unlisted) diploma.</summary>
@@ -0,0 +1,18 @@
namespace BigRegister.Stamdata;
/// <summary>
/// The registry of business-editable stamdata tables (ADR-0004). This is the ONE place a
/// new stamdata type is registered: add its JSON data-file + typed record, then one line
/// here — the generic <c>/stamdata</c> endpoints, the grid editor, and the validation gate
/// all pick it up with no further code.
/// </summary>
public static class StamdataCatalog
{
public static readonly IReadOnlyList<StamdataTable> All = new[]
{
StamdataTable.Of<ProfessionMapping>("professions", "Opleiding → beroep"),
// PolicyQuestions and future tables migrate here, same one-liner each.
};
public static StamdataTable? Find(string id) => All.FirstOrDefault(t => t.Id == id);
}
@@ -0,0 +1,38 @@
using System.Reflection;
using System.Text.Json;
namespace BigRegister.Stamdata;
/// <summary>
/// Reads a stamdata JSON data-file (config-as-code, ADR-0004). The files are embedded
/// resources (see BigRegister.Api.csproj), so the SAME read works from the running API
/// and from the test assembly with no file-path/cwd/docker-mount fuss — the assembly is
/// loaded either way. A business edit is a change to the `.json` in source → rebuild →
/// the compile/validation gate re-runs; there is no runtime write path.
/// </summary>
public static class StamdataFile
{
public static readonly JsonSerializerOptions Options = new() { PropertyNameCaseInsensitive = true };
/// <summary>Raw JSON text of the <c>Stamdata/{id}.json</c> data-file.</summary>
public static string Read(string id)
{
var asm = typeof(StamdataFile).Assembly;
// Match on the suffix rather than composing the full logical name so a RootNamespace
// change can't silently break the lookup.
var name = asm.GetManifestResourceNames().SingleOrDefault(n => n.EndsWith($".Stamdata.{id}.json", StringComparison.Ordinal))
?? throw new InvalidOperationException($"Stamdata data-file '{id}.json' is not embedded in {asm.GetName().Name}.");
using var stream = asm.GetManifestResourceStream(name)!;
using var reader = new StreamReader(stream);
return reader.ReadToEnd();
}
/// <summary>Deserialize a data-file into its typed rows.</summary>
public static IReadOnlyList<T> Load<T>(string id) =>
JsonSerializer.Deserialize<List<T>>(Read(id), Options)
?? throw new InvalidOperationException($"Stamdata data-file '{id}.json' deserialized to null.");
/// <summary>Valid-time membership, half-open <c>[van, tot)</c>: null <c>tot</c> = open-ended.</summary>
public static bool ActiveOn(DateOnly van, DateOnly? tot, DateOnly on) =>
van <= on && (tot is null || on < tot);
}
@@ -0,0 +1,119 @@
using System.Text.Json;
namespace BigRegister.Stamdata;
/// <summary>One editable column, derived by reflection from a stamdata record's property.</summary>
public sealed record StamdataColumn(string Name, string Type, bool IsKey, IReadOnlyList<string>? Options = null);
/// <summary>
/// A business-editable stamdata table, described generically so ONE endpoint and ONE grid
/// editor serve every table (the "add a type with zero UI code" goal, ADR-0004). The
/// column schema is reflected from the typed record <typeparamref name="T"/> via
/// <see cref="Of{T}"/>; rows come from the embedded JSON data-file; <see cref="Validate"/>
/// is the per-table half of the build-time gate.
///
/// Conventions: the record's FIRST property is the table key; a table is temporal iff it
/// has both a <c>geldigVan</c> and a <c>geldigTot</c> column (half-open <c>[van, tot)</c>).
/// </summary>
public sealed class StamdataTable
{
public string Id { get; }
public string Label { get; }
public IReadOnlyList<StamdataColumn> Columns { get; }
public bool Temporal { get; }
private readonly Action _assertParses; // throws if the file doesn't deserialize into T
private StamdataTable(string id, string label, IReadOnlyList<StamdataColumn> columns, Action assertParses)
{
Id = id;
Label = label;
Columns = columns;
_assertParses = assertParses;
Temporal = columns.Any(c => c.Name == "geldigVan") && columns.Any(c => c.Name == "geldigTot");
}
public static StamdataTable Of<T>(string id, string label)
{
var props = typeof(T).GetProperties();
var columns = props.Select((p, i) => new StamdataColumn(
Name: JsonNamingPolicy.CamelCase.ConvertName(p.Name),
Type: TypeOf(p.PropertyType, out var options),
IsKey: i == 0,
Options: options)).ToList();
return new StamdataTable(id, label, columns, () => StamdataFile.Load<T>(id));
}
private static string TypeOf(Type t, out IReadOnlyList<string>? options)
{
options = null;
var u = Nullable.GetUnderlyingType(t) ?? t;
if (u == typeof(DateOnly)) return "date";
if (u == typeof(int) || u == typeof(long)) return "number";
if (u.IsEnum) { options = Enum.GetNames(u); return "enum"; }
return "text";
}
/// <summary>All rows as generic JSON objects (edit view).</summary>
public JsonElement[] Rows() =>
JsonSerializer.Deserialize<JsonElement[]>(StamdataFile.Read(Id))!;
/// <summary>Rows valid on <paramref name="on"/> (temporal tables); all rows otherwise.</summary>
public JsonElement[] RowsOn(DateOnly on) =>
Temporal ? Rows().Where(r => ActiveOn(r, on)).ToArray() : Rows();
private static bool ActiveOn(JsonElement row, DateOnly on)
{
var van = DateOnly.Parse(row.GetProperty("geldigVan").GetString()!);
DateOnly? tot = row.TryGetProperty("geldigTot", out var t) && t.ValueKind != JsonValueKind.Null
? DateOnly.Parse(t.GetString()!) : null;
return StamdataFile.ActiveOn(van, tot, on);
}
/// <summary>Referential-integrity checks the C# type system can't express (ADR-0004's
/// second gate). Returns human-readable problems; empty = valid.</summary>
public IReadOnlyList<string> Validate()
{
try { _assertParses(); }
catch (Exception ex) { return new[] { $"{Id}.json failed to parse into its typed shape: {ex.Message}" }; }
var problems = new List<string>();
var key = Columns[0].Name;
var rows = Rows();
foreach (var (row, idx) in rows.Select((r, i) => (r, i)))
{
var k = row.TryGetProperty(key, out var kv) ? kv.GetString() : null;
if (string.IsNullOrWhiteSpace(k)) problems.Add($"{Id}.json row {idx} has a blank '{key}'.");
if (Temporal)
{
var van = DateOnly.Parse(row.GetProperty("geldigVan").GetString()!);
if (row.TryGetProperty("geldigTot", out var t) && t.ValueKind != JsonValueKind.Null
&& DateOnly.Parse(t.GetString()!) <= van)
problems.Add($"{Id}.json row {idx} ('{k}') has geldigTot <= geldigVan.");
}
}
// No key may have two mappings valid at the same time.
foreach (var g in rows.GroupBy(r => r.GetProperty(key).GetString()))
if (Overlaps(g))
problems.Add($"{Id}.json has overlapping validity periods for '{g.Key}'.");
return problems;
}
private bool Overlaps(IEnumerable<JsonElement> group)
{
if (!Temporal) return group.Count() > 1; // non-temporal: any duplicate key is a conflict
var periods = group.Select(r =>
{
var van = DateOnly.Parse(r.GetProperty("geldigVan").GetString()!);
DateOnly tot = r.TryGetProperty("geldigTot", out var t) && t.ValueKind != JsonValueKind.Null
? DateOnly.Parse(t.GetString()!) : DateOnly.MaxValue;
return (van, tot);
}).OrderBy(p => p.van).ToList();
for (var i = 1; i < periods.Count; i++)
if (periods[i].van < periods[i - 1].tot) return true; // half-open [van, tot)
return false;
}
}
@@ -0,0 +1,7 @@
[
{ "program": "geneeskunde", "beroep": "Arts", "geldigVan": "2000-01-01", "geldigTot": null },
{ "program": "verpleegkunde", "beroep": "Verpleegkundige", "geldigVan": "2000-01-01", "geldigTot": null },
{ "program": "fysiotherapie", "beroep": "Fysiotherapeut", "geldigVan": "2000-01-01", "geldigTot": null },
{ "program": "farmacie", "beroep": "Apotheker", "geldigVan": "2000-01-01", "geldigTot": null },
{ "program": "tandheelkunde", "beroep": "Tandarts", "geldigVan": "2000-01-01", "geldigTot": null }
]
+160
View File
@@ -127,6 +127,89 @@
}
}
},
"/api/v1/stamdata": {
"get": {
"tags": [
"BigRegister.Api, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
],
"operationId": "stamdataTables",
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"type": "array",
"items": {
"$ref": "#/components/schemas/StamdataTableSummaryDto"
}
}
}
}
},
"403": {
"description": "Forbidden",
"content": {
"application/problem+json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
}
}
}
}
}
},
"/api/v1/stamdata/{table}": {
"get": {
"tags": [
"BigRegister.Api, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
],
"operationId": "stamdataTable",
"parameters": [
{
"name": "table",
"in": "path",
"required": true,
"schema": {
"type": "string"
}
},
{
"name": "peildatum",
"in": "query",
"schema": {
"type": "string"
}
}
],
"responses": {
"200": {
"description": "OK",
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/StamdataTableDto"
}
}
}
},
"403": {
"description": "Forbidden",
"content": {
"application/problem+json": {
"schema": {
"$ref": "#/components/schemas/ProblemDetails"
}
}
}
},
"404": {
"description": "Not Found"
}
}
}
},
"/api/v1/registrations": {
"post": {
"tags": [
@@ -2178,6 +2261,83 @@
},
"additionalProperties": false
},
"StamdataColumnDto": {
"type": "object",
"properties": {
"name": {
"type": "string",
"nullable": true
},
"type": {
"type": "string",
"nullable": true
},
"isKey": {
"type": "boolean"
},
"options": {
"type": "array",
"items": {
"type": "string"
},
"nullable": true
}
},
"additionalProperties": false
},
"StamdataTableDto": {
"type": "object",
"properties": {
"id": {
"type": "string",
"nullable": true
},
"label": {
"type": "string",
"nullable": true
},
"columns": {
"type": "array",
"items": {
"$ref": "#/components/schemas/StamdataColumnDto"
},
"nullable": true
},
"temporal": {
"type": "boolean"
},
"rows": {
"type": "array",
"items": { },
"nullable": true
}
},
"additionalProperties": false
},
"StamdataTableSummaryDto": {
"type": "object",
"properties": {
"id": {
"type": "string",
"nullable": true
},
"label": {
"type": "string",
"nullable": true
},
"columns": {
"type": "array",
"items": {
"$ref": "#/components/schemas/StamdataColumnDto"
},
"nullable": true
},
"temporal": {
"type": "boolean"
}
},
"additionalProperties": false
},
"SubOrgSummaryDto": {
"type": "object",
"properties": {
@@ -201,7 +201,7 @@ public class OrgTemplateEndpointTests(TestWebApplicationFactory factory) : IClas
{
var res = await _client.SendAsync(Req(HttpMethod.Get, "/api/v1/me", role: "admin"));
var me = await res.Content.ReadFromJsonAsync<MeDto>();
Assert.Equal(new[] { "orgtemplate:edit" }, me!.Capabilities);
Assert.Equal(new[] { "orgtemplate:edit", "stamdata:edit" }, me!.Capabilities);
}
[Fact]
@@ -0,0 +1,68 @@
using System.Net;
using System.Net.Http.Json;
using BigRegister.Api.Contracts;
using Microsoft.AspNetCore.Mvc.Testing;
namespace BigRegister.Tests;
/// <summary>
/// The stamdata maintenance reads (ADR-0004): admin-only, generic (schema + rows), and the
/// valid-time peildatum filter. The editor consumes these; the edit itself lands as a PR.
/// </summary>
public class StamdataEndpointTests(TestWebApplicationFactory factory) : IClassFixture<TestWebApplicationFactory>
{
private readonly HttpClient _client = factory.CreateClient();
private HttpRequestMessage Req(HttpMethod method, string path, string? role = null)
{
var req = new HttpRequestMessage(method, path);
if (role is not null) req.Headers.Add("X-Role", role);
return req;
}
[Fact]
public async Task Stamdata_reads_are_admin_only()
{
Assert.Equal(HttpStatusCode.Forbidden, (await _client.SendAsync(Req(HttpMethod.Get, "/api/v1/stamdata"))).StatusCode);
Assert.Equal(HttpStatusCode.Forbidden, (await _client.SendAsync(Req(HttpMethod.Get, "/api/v1/stamdata/professions", role: "drafter"))).StatusCode);
}
[Fact]
public async Task Table_list_exposes_the_reflected_schema()
{
var res = await _client.SendAsync(Req(HttpMethod.Get, "/api/v1/stamdata", role: "admin"));
res.EnsureSuccessStatusCode();
var tables = (await res.Content.ReadFromJsonAsync<List<StamdataTableSummaryDto>>())!;
var professions = tables.Single(t => t.Id == "professions");
Assert.True(professions.Temporal);
Assert.True(professions.Columns[0].IsKey);
Assert.Equal("program", professions.Columns[0].Name);
Assert.Contains(professions.Columns, c => c.Name == "geldigVan" && c.Type == "date");
}
[Fact]
public async Task Table_returns_all_rows_without_a_peildatum()
{
var res = await _client.SendAsync(Req(HttpMethod.Get, "/api/v1/stamdata/professions", role: "admin"));
res.EnsureSuccessStatusCode();
var table = (await res.Content.ReadFromJsonAsync<StamdataTableDto>())!;
Assert.Equal(5, table.Rows.Count);
}
[Fact]
public async Task Peildatum_before_the_seed_windows_hides_every_row()
{
// Seed mappings start 2000-01-01; a 1999 peildatum yields none (valid-time filter works).
var res = await _client.SendAsync(Req(HttpMethod.Get, "/api/v1/stamdata/professions?peildatum=1999-01-01", role: "admin"));
res.EnsureSuccessStatusCode();
var table = (await res.Content.ReadFromJsonAsync<StamdataTableDto>())!;
Assert.Empty(table.Rows);
}
[Fact]
public async Task Unknown_table_is_404()
{
var res = await _client.SendAsync(Req(HttpMethod.Get, "/api/v1/stamdata/nope", role: "admin"));
Assert.Equal(HttpStatusCode.NotFound, res.StatusCode);
}
}
@@ -55,4 +55,16 @@ public class StamdataValidationTests
var ids = PolicyQuestions.ManualSet.Select(q => q.Id).ToList();
Assert.Equal(ids.Count, ids.Distinct().Count());
}
// The GENERIC gate (ADR-0004): every table registered in the catalog is validated the
// same way — its JSON deserializes into its typed record, keys are non-blank and don't
// overlap in time, and valid-time windows are well-formed. A new stamdata type is covered
// the moment it's added to StamdataCatalog; no new test needed. A bad edit fails the build.
[Fact]
public void Every_catalog_table_is_valid()
{
foreach (var table in StamdataCatalog.All)
Assert.True(table.Validate().Count == 0,
$"Stamdata table '{table.Id}' has problems: {string.Join("; ", table.Validate())}");
}
}
+6151 -2258
View File
File diff suppressed because one or more lines are too long
+24 -4
View File
@@ -76,7 +76,7 @@ export default [
{
patterns: [
{
group: ['@auth/*', '@registratie/*', '@herregistratie/*', '@brief/*'],
group: ['@auth/*', '@registratie/*', '@herregistratie/*', '@brief/*', '@beheer/*'],
message: 'shared/ must not depend on a feature context.',
},
],
@@ -94,7 +94,7 @@ export default [
{
patterns: [
{
group: ['@registratie/*', '@herregistratie/*', '@brief/*'],
group: ['@registratie/*', '@herregistratie/*', '@brief/*', '@beheer/*'],
message: 'auth/ may depend only on shared.',
},
],
@@ -112,7 +112,7 @@ export default [
{
patterns: [
{
group: ['@herregistratie/*', '@brief/*'],
group: ['@herregistratie/*', '@brief/*', '@beheer/*'],
message: 'Dependencies point herregistratie → registratie → shared, never back.',
},
],
@@ -130,7 +130,7 @@ export default [
{
patterns: [
{
group: ['@auth/*', '@registratie/*', '@herregistratie/*'],
group: ['@auth/*', '@registratie/*', '@herregistratie/*', '@beheer/*'],
message: 'brief/ may depend only on shared.',
},
],
@@ -139,6 +139,24 @@ export default [
},
},
// beheer/ (stamdata maintenance) is an independent leaf context: it may depend only on shared.
{
files: ['src/app/beheer/**/*.ts'],
rules: {
'no-restricted-imports': [
'error',
{
patterns: [
{
group: ['@auth/*', '@registratie/*', '@herregistratie/*', '@brief/*'],
message: 'beheer/ may depend only on shared.',
},
],
},
],
},
},
// contracts/ is the FE⇄BE wire seam: pure DTO shapes that must import NOTHING
// (CLAUDE.md §1, ADR-0001) — not Angular, not a context alias, not relative app
// code. Enums are inlined string-literal unions; the adapter's parse* maps them.
@@ -158,6 +176,7 @@ export default [
'@registratie/**',
'@herregistratie/**',
'@brief/**',
'@beheer/**',
'./*',
'../*',
'./**',
@@ -225,6 +244,7 @@ export default [
'@registratie/infrastructure/*',
'@herregistratie/infrastructure/*',
'@brief/infrastructure/*',
'@beheer/infrastructure/*',
],
allowTypeImports: true,
message:
+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',
];
/**
+2 -1
View File
@@ -21,7 +21,8 @@
"@auth/*": ["src/app/auth/*"],
"@registratie/*": ["src/app/registratie/*"],
"@herregistratie/*": ["src/app/herregistratie/*"],
"@brief/*": ["src/app/brief/*"]
"@brief/*": ["src/app/brief/*"],
"@beheer/*": ["src/app/beheer/*"]
}
},
"angularCompilerOptions": {