Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
7dfbd4501f | ||
|
|
645fad088e | ||
|
|
e5edae4970 | ||
|
|
5968ef9030 | ||
|
|
0e77faf351 |
@@ -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
|
||||
|
||||
@@ -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 }
|
||||
]
|
||||
@@ -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())}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -73,6 +73,7 @@ for its existing violations, so every WP ends green.
|
||||
| [WP-26](WP-26-org-template-editor.md) | Admin org-template editor | 6 · Brief v2 | done |
|
||||
| [WP-27](WP-27-brief-ux-layer.md) | Brief UX layer (undo/redo, standaardbrief, diff) | 6 · Brief v2 | todo |
|
||||
| [WP-28](WP-28-brief-v2-demo-polish.md) | Brief v2 demo polish (scenarios, e2e, docs) | 6 · Brief v2 | todo |
|
||||
| [WP-29](WP-29-stamdata-beheer-editor.md) | Stamdata beheer editor (low-code, PR-emitting) | follow-on · ADR-0004 | done |
|
||||
|
||||
Sequencing dependencies (stated in the WPs too): 01 before 10–15 (axe covers story churn);
|
||||
03/04 before 05–09 (boundaries stop new violations during refactors); 06 before 07 (typed
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
# WP-29 — Stamdata beheer editor (low-code, PR-emitting)
|
||||
|
||||
Status: done (0e77faf)
|
||||
Phase: follow-on — ADR-0004 realization (not part of the 2026-07-02 showcase audit)
|
||||
|
||||
## Why
|
||||
|
||||
ADR-0004 (stamdata-as-code) named a **future low-code editor that commits a PR** as its
|
||||
mitigation for "a non-developer may need dev assistance to edit C#", and floated a
|
||||
**data-file format** as the alternative to typed-C# constants when hand-editing ergonomics
|
||||
outweigh maximal compile-time safety. This WP realizes both: an admin-only maintenance editor
|
||||
that reads the stamdata catalog, edits rows in a grid, and produces the edited JSON data-file
|
||||
the admin drops into the repo — the existing CI build + `StamdataValidationTests` stay the
|
||||
authority. No production database, no runtime write path (ADR-0004 unchanged).
|
||||
|
||||
## Read first
|
||||
|
||||
- ADR-0004 (`docs/reference/architecture/0004-stamdata-as-code.md`) — the model this obeys.
|
||||
- ADR-0001 (BFF-lite + decision DTOs) — the endpoints are screen-shaped, admin-gated reads.
|
||||
- `src/app/brief/**` (WP-23/26) — the org-template admin editor is the closest prior art
|
||||
(root store + machine + capability guard + admin role).
|
||||
|
||||
## Decisions (pre-made, don't relitigate)
|
||||
|
||||
- **Read-only endpoints only.** `GET /stamdata` (catalog) and `GET /stamdata/{table}?peildatum=`
|
||||
(schema + rows). No POST/PUT/DELETE — the edit lands as a reviewed PR, not a write. The
|
||||
`stamdata:edit` capability / `CanEditStamdata` gate the *reads* (naming is the enforce-twin
|
||||
of a future edit capability; deliberate).
|
||||
- **Generic, schema-driven.** One endpoint pair + one grid editor serve every table. Columns
|
||||
are reflected from the typed record (`StamdataTable.Of<T>`); the FE renders inputs by column
|
||||
type (`date`/`number`/`enum`/`text`). A new table is one line in `StamdataCatalog` — no new
|
||||
endpoint, UI, or test. (Catalog of one today; this is the shape ADR-0004 prescribed.)
|
||||
- **Data-file format for `professions`.** `professions.json` (embedded resource) replaces the
|
||||
hardcoded C# dictionary, deserialized into `ProfessionMapping`. This trades compile-time
|
||||
*value* checking (gate #1) for editor ergonomics — the value gate becomes
|
||||
`StamdataValidationTests` (gate #2), exactly the trade-off ADR-0004's consequences listed.
|
||||
- **Valid-time.** `geldigVan`/`geldigTot` (half-open `[van, tot)`); a table is temporal iff it
|
||||
has both columns. `peildatum` previews "which rows applied on date X". `Professions.ByProgram`
|
||||
preserves pre-valid-time behaviour by filtering to rows active today.
|
||||
- **Apply path = download → PR.** The editor's `download()` serializes the draft to
|
||||
`{table}.json`; the admin commits it. `mutation-command` is intentionally not used.
|
||||
- Admin-only, resource-independent authz — same shape as org-template management (role IS the
|
||||
decision), denials audited (no PII).
|
||||
|
||||
## Files
|
||||
|
||||
- Backend: `backend/src/BigRegister.Api/Stamdata/{StamdataCatalog,StamdataTable,StamdataFile,ProfessionMapping}.cs` (new), `Professions.cs` (now loads the data-file), `professions.json` (new), `BigRegister.Api.csproj` (embed `Stamdata\*.json`); `Program.cs` (two GET endpoints + `StamdataAdmin` gate), `Contracts/Dtos.cs` (3 DTOs), `Domain/Authorization/Authz.cs` (`stamdata:edit` + `CanEditStamdata`); tests `StamdataEndpointTests.cs` (new), `StamdataValidationTests.cs` (generic `Every_catalog_table_is_valid`).
|
||||
- Frontend: `src/app/beheer/**` (contracts / domain + specs / infrastructure + spec / application / ui + organism story); `app.routes.ts` (guarded lazy route), `shared/domain/capability.ts` + `shared/infrastructure/me.adapter.ts` (`stamdata:edit`), `eslint.config.mjs` (`beheer` boundary rules), `tsconfig.json` (`@beheer/*` alias); regenerated `backend/swagger.json` + `src/app/shared/infrastructure/api-client.ts`.
|
||||
|
||||
## Acceptance criteria
|
||||
|
||||
- [x] `GET /stamdata` and `GET /stamdata/{table}` return admin-only (403 + audit otherwise).
|
||||
- [x] `professions` served from `professions.json`; `ProfessionMapping` typed; behaviour of
|
||||
`Professions.ByProgram` unchanged for all-current rows.
|
||||
- [x] Generic build gate: `Every_catalog_table_is_valid` covers every catalog table (keys
|
||||
non-blank, no overlapping validity, well-formed windows).
|
||||
- [x] `beheer/stamdata` route capability-guarded; page shows denial for non-admin; grid
|
||||
renders from reflected schema; edits update dirty/change-count; `download()` yields a
|
||||
valid `{table}.json`; `peildatum` before 2000-01-01 → zero rows.
|
||||
- [x] Full gate GREEN both sides; `npm run gen:api` leaves no drift; new stamdata story passes axe.
|
||||
|
||||
## Verification
|
||||
|
||||
`cd backend && dotnet test && dotnet format --verify-no-changes`; `npm run lint && npm run
|
||||
check:tokens && npm test && npm run build && npm run build-storybook && npm run test-storybook:ci`;
|
||||
`npm run gen:api && git diff --exit-code -- backend/swagger.json src/app/shared/infrastructure/api-client.ts`.
|
||||
Live: `/beheer/stamdata?role=admin` renders + edits + downloads; without `?role=admin` denies.
|
||||
|
||||
## Out of scope
|
||||
|
||||
- Runtime persistence of edits (would contradict ADR-0004) — the download-to-PR path is the design.
|
||||
- Migrating `PolicyQuestions` / document-categories into the catalog (each is a later one-liner).
|
||||
- A write-back "commit a PR on the admin's behalf" integration (the `download()` seam is where it slots in).
|
||||
|
||||
## Risks
|
||||
|
||||
- Data-file weakens compile-time value safety for `professions` — mitigated by
|
||||
`StamdataValidationTests` running in CI (a bad value fails the build, never prod).
|
||||
- Generic reflection assumes the record's first property is the key and camelCase JSON names —
|
||||
documented conventions in `StamdataTable`; covered by the endpoint schema test.
|
||||
@@ -35,10 +35,17 @@ production database, never runtime-editable.
|
||||
|
||||
1. **One home, typed.** Business-editable reference data lives in the
|
||||
`BigRegister.Stamdata` namespace (`backend/src/BigRegister.Api/Stamdata/`), one file per
|
||||
concern, as plain typed C# data (records / dictionaries). Separate the **data** (what the
|
||||
business tunes) from the **rules** (dev-owned logic that consumes it): the profession
|
||||
*table* is `Stamdata.Professions`; the *rule* "an English diploma needs a B2 question"
|
||||
stays in `DiplomaRules`.
|
||||
concern. A table lives **either** as plain typed C# data (records / dictionaries) **or** as
|
||||
a typed JSON data-file deserialized into a record (`professions.json` → `ProfessionMapping`,
|
||||
loaded via `StamdataFile`). Both are checked-in config-as-code, gated the same way; the
|
||||
data-file trades the compiler's *value* check (gate #1 sees only the shape, not a wrong
|
||||
`beroep`) for hand-editing ergonomics and the low-code editor below — the value gate becomes
|
||||
`StamdataValidationTests`. Separate the **data** (what the business tunes) from the **rules**
|
||||
(dev-owned logic that consumes it): the profession *table* is `Stamdata.Professions`; the
|
||||
*rule* "an English diploma needs a B2 question" stays in `DiplomaRules`. Tables may carry
|
||||
**valid-time** (`geldigVan`/`geldigTot`, half-open `[van, tot)`); `StamdataCatalog` +
|
||||
`StamdataTable.Of<T>` describe every table generically (columns reflected from the record)
|
||||
so one endpoint pair and one grid editor serve all of them.
|
||||
2. **Served unchanged.** The existing BFF-lite endpoints keep serving this data
|
||||
(`/duo/diplomas`, `/intake/policy`, `/uploads/categories`, …). No frontend change — the
|
||||
FE still renders decisions.
|
||||
@@ -54,7 +61,7 @@ production database, never runtime-editable.
|
||||
|
||||
| Kind | Home | Gate |
|
||||
| --- | --- | --- |
|
||||
| Reference tables + tunable numbers (professions↔diplomas, thresholds, policy questions, document categories) | `Stamdata/` typed C# | compiler + `StamdataValidationTests` |
|
||||
| Reference tables + tunable numbers (professions↔diplomas, thresholds, policy questions, document categories) | `Stamdata/` typed C# **or** typed JSON data-file (`professions.json`), optionally valid-timed | compiler (shape; + values when C#) + `StamdataValidationTests` (values, references, validity windows) |
|
||||
| User-facing UI copy | `$localize` → `src/locale/*.xlf` | build (`i18nMissingTranslation: error`) |
|
||||
| Letter / brief passage content | config-as-code in the backend (seed content), **not** the DB | compiler + endpoint tests |
|
||||
|
||||
@@ -80,3 +87,9 @@ everyone. Stamdata (the rules and reference tables the whole register runs on) s
|
||||
which now consumes both (behaviour unchanged), guarded by `StamdataValidationTests`.
|
||||
Document-category definitions follow the same pattern as the obvious next step; not moved
|
||||
yet.
|
||||
- **Shipped as a follow-on (WP-29):** the "future low-code editor" and "data-file format" this
|
||||
ADR floated are now real. `professions` moved to `professions.json` (typed, valid-timed) and
|
||||
the generic `StamdataCatalog`/`StamdataTable`/`StamdataFile` model plus read-only, admin-gated
|
||||
`GET /stamdata` endpoints back an Angular `beheer/stamdata` editor. It is **not** a runtime
|
||||
write path: the admin edits a grid and downloads the edited JSON to commit as a reviewed PR —
|
||||
the compile/validation gate stays the authority, so this ADR's core decision is unchanged.
|
||||
|
||||
@@ -43,11 +43,11 @@ ever uses the level(s) below it — so anything you build is reusable by everyth
|
||||
|
||||
```mermaid
|
||||
graph TD
|
||||
P["<b>Pages</b><br/>dashboard.page · login.page · intake.page"]
|
||||
T["<b>Templates</b><br/>page-shell · shell"]
|
||||
O["<b>Organisms</b><br/>login-form · registration-table · intake-wizard"]
|
||||
M["<b>Molecules</b><br/>form-field · data-row · async"]
|
||||
A["<b>Atoms</b><br/>button · text-input · radio-group · alert · heading"]
|
||||
P["Pages<br>dashboard.page · login.page · intake.page"]
|
||||
T["Templates<br>page-shell · shell"]
|
||||
O["Organisms<br>login-form · registration-table · intake-wizard"]
|
||||
M["Molecules<br>form-field · data-row · async"]
|
||||
A["Atoms<br>button · text-input · radio-group · alert · heading"]
|
||||
P --> T --> O --> M --> A
|
||||
classDef l fill:#e5f1fb,stroke:#007bc7,color:#00567d;
|
||||
class P,T,O,M,A l;
|
||||
@@ -110,12 +110,12 @@ the 4 states that are real** — the illegal ones can't be expressed at all.
|
||||
graph LR
|
||||
subgraph bad["3 booleans = 8 states (most illegal)"]
|
||||
direction TB
|
||||
b1["loading ✓ · error ✗ · data ✗ ✅"]
|
||||
b2["loading ✗ · error ✓ · data ✗ ✅"]
|
||||
b3["loading ✗ · error ✗ · data ✓ ✅"]
|
||||
b4["loading ✓ · error ✓ · data ✓ ❌ nonsense"]
|
||||
b5["loading ✓ · error ✗ · data ✓ ❌ nonsense"]
|
||||
b6["… 3 more illegal combos ❌"]
|
||||
b1["loading ✓ · error ✗ · data ✗ — legal"]
|
||||
b2["loading ✗ · error ✓ · data ✗ — legal"]
|
||||
b3["loading ✗ · error ✗ · data ✓ — legal"]
|
||||
b4["loading ✓ · error ✓ · data ✓ — nonsense"]
|
||||
b5["loading ✓ · error ✗ · data ✓ — nonsense"]
|
||||
b6["… 3 more illegal combos"]
|
||||
end
|
||||
subgraph good["1 union = 4 legal states"]
|
||||
direction TB
|
||||
@@ -125,8 +125,10 @@ graph LR
|
||||
g4["Success (carries value)"]
|
||||
end
|
||||
bad -->|"choose a better type"| good
|
||||
classDef ok fill:#e8f5e9,stroke:#39870c; classDef no fill:#fdecea,stroke:#d52b1e;
|
||||
class b1,b2,b3,g1,g2,g3,g4 ok; class b4,b5,b6 no;
|
||||
classDef ok fill:#e8f5e9,stroke:#39870c;
|
||||
classDef no fill:#fdecea,stroke:#d52b1e;
|
||||
class b1,b2,b3,g1,g2,g3,g4 ok;
|
||||
class b4,b5,b6 no;
|
||||
```
|
||||
|
||||
The same argument applies to forms (a `submitting` boolean that can be true _with_
|
||||
@@ -175,7 +177,7 @@ stateDiagram-v2
|
||||
Loading --> Success: data arrived
|
||||
Loading --> Empty: arrived, but no rows
|
||||
Loading --> Failure: request failed
|
||||
Failure --> Loading: reload()
|
||||
Failure --> Loading: reload
|
||||
note right of Success
|
||||
value lives ONLY here
|
||||
end note
|
||||
@@ -230,15 +232,15 @@ _one_ function. No state is mutated anywhere else.
|
||||
```mermaid
|
||||
sequenceDiagram
|
||||
actor User
|
||||
participant View as View (template)
|
||||
participant Store as createStore (signal)
|
||||
participant Reduce as reduce() — PURE
|
||||
participant View
|
||||
participant Store
|
||||
participant Reduce
|
||||
User->>View: clicks / types
|
||||
View->>Store: dispatch(msg)
|
||||
Store->>Reduce: reduce(model, msg)
|
||||
Store->>Reduce: reduce(model, msg) — PURE
|
||||
Reduce-->>Store: next model
|
||||
Store-->>View: signal updates → re-render
|
||||
Note over Reduce: the ONLY place state changes;<br/>no HTTP, no timers, no mutation
|
||||
Store-->>View: signal updates, re-render
|
||||
Note over Reduce: the ONLY place state changes<br>no HTTP, no timers, no mutation
|
||||
```
|
||||
|
||||
Side effects (HTTP) sit _outside_ this loop: a command does the I/O, then `dispatch`es a
|
||||
@@ -366,6 +368,22 @@ So it _feels_ like save-on-blur only because you usually stop typing when you le
|
||||
field, and the debounce fires ~600 ms later. The trigger is **"stopped changing," not
|
||||
"lost focus."** Submit is a separate, explicit action (§2d).
|
||||
|
||||
**The last-mile guard (leaving mid-debounce).** A debounce means an edit made in the final
|
||||
<600 ms before you leave hasn't been written yet. Two seams close that window
|
||||
([`pending-saves.ts`](../../../src/app/shared/application/pending-saves.ts)): every autosave
|
||||
owner (the brief/org-template root stores and each wizard's `draft-sync`) registers in a
|
||||
`PendingSaves` registry, and
|
||||
|
||||
- **in-app navigation** — a `CanDeactivate` guard (`flushPendingGuard`, on the autosave
|
||||
routes) flushes the pending write and _awaits_ it before the route changes, so the page
|
||||
can't tear down with an unsaved keystroke;
|
||||
- **hard close / reload** — a `beforeunload` handler fires the flush best-effort and triggers
|
||||
the browser's native "unsaved changes" prompt. It is deliberately _not_ a guaranteed sync
|
||||
save: the HTTP seam is Angular `HttpClient` (no `keepalive`/`sendBeacon`), so an async write
|
||||
can't be promised to finish as the page unloads — the prompt lets the debounce land if the
|
||||
user stays. The authoritative _submit_ path already force-flushes first, so only unsent
|
||||
draft keystrokes are ever at risk.
|
||||
|
||||
---
|
||||
|
||||
## 3. "Parse, don't validate" — value objects
|
||||
@@ -443,11 +461,14 @@ where the user left off.
|
||||
```mermaid
|
||||
stateDiagram-v2
|
||||
[*] --> Answering
|
||||
Answering --> Answering: SetAnswer / Next / Back<br/>(steps re-derived each time)
|
||||
Answering --> Submitting: Submit (all answers valid)
|
||||
Answering --> Answering: SetAnswer / Next / Back
|
||||
Answering --> Submitting: Submit when all answers valid
|
||||
Submitting --> Submitted: ok
|
||||
Submitting --> Failed: error
|
||||
Failed --> Submitting: Retry
|
||||
note right of Answering
|
||||
steps re-derived each time
|
||||
end note
|
||||
```
|
||||
|
||||
See it live on `/concepts` (section 5) — the step list and the "stap N van M" counter
|
||||
|
||||
+6244
-2004
File diff suppressed because one or more lines are too long
+24
-4
@@ -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:
|
||||
|
||||
@@ -17,6 +17,7 @@ import { provideApiClient } from '@shared/infrastructure/api-client.provider';
|
||||
import { SESSION_PORT } from '@shared/application/session.port';
|
||||
import { SessionStore } from '@auth/application/session.store';
|
||||
import { provideRouteFocus } from '@shared/layout/route-focus';
|
||||
import { provideUnloadFlush } from '@shared/application/pending-saves';
|
||||
|
||||
registerLocaleData(localeNl);
|
||||
|
||||
@@ -51,5 +52,6 @@ export const appConfig: ApplicationConfig = {
|
||||
{ provide: SESSION_PORT, useExisting: SessionStore },
|
||||
{ provide: LOCALE_ID, useValue: 'nl' },
|
||||
provideRouteFocus(),
|
||||
provideUnloadFlush(),
|
||||
],
|
||||
};
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { Routes } from '@angular/router';
|
||||
import { ShellComponent } from '@shared/layout/shell/shell.component';
|
||||
import { authGuard, capabilityGuard } from '@auth/auth.guard';
|
||||
import { flushPendingGuard } from '@shared/application/pending-saves';
|
||||
|
||||
export const routes: Routes = [
|
||||
{
|
||||
@@ -32,23 +33,28 @@ export const routes: Routes = [
|
||||
{
|
||||
path: 'registreren',
|
||||
canActivate: [authGuard],
|
||||
// Autosave wizard: flush the pending debounced draft before leaving (pending-saves.ts).
|
||||
canDeactivate: [flushPendingGuard],
|
||||
loadComponent: () =>
|
||||
import('@registratie/ui/registratie.page').then((m) => m.RegistratiePage),
|
||||
},
|
||||
{
|
||||
path: 'herregistratie',
|
||||
canActivate: [authGuard],
|
||||
canDeactivate: [flushPendingGuard],
|
||||
loadComponent: () =>
|
||||
import('@herregistratie/ui/herregistratie.page').then((m) => m.HerregistratiePage),
|
||||
},
|
||||
{
|
||||
path: 'intake',
|
||||
canActivate: [authGuard],
|
||||
canDeactivate: [flushPendingGuard],
|
||||
loadComponent: () => import('@herregistratie/ui/intake.page').then((m) => m.IntakePage),
|
||||
},
|
||||
{
|
||||
path: 'brief',
|
||||
canActivate: [authGuard],
|
||||
canDeactivate: [flushPendingGuard],
|
||||
loadComponent: () => import('@brief/ui/brief.page').then((m) => m.BriefPage),
|
||||
},
|
||||
{
|
||||
@@ -57,9 +63,18 @@ export const routes: Routes = [
|
||||
// unless GET /me resolved `orgtemplate:edit` (Admin role). Backend re-enforces
|
||||
// via the OrgAdmin gate — the guard just avoids loading a page that would 403.
|
||||
canActivate: [capabilityGuard('orgtemplate:edit')],
|
||||
canDeactivate: [flushPendingGuard],
|
||||
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.`;
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
@@ -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 }]);
|
||||
});
|
||||
});
|
||||
@@ -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' },
|
||||
};
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -301,3 +301,28 @@ describe('BriefStore.revealBigNummer (PRD-0002 §5c)', () => {
|
||||
expect(store.lastError()).toBe('geweigerd');
|
||||
});
|
||||
});
|
||||
|
||||
describe('BriefStore.flushPending (CanDeactivate guard / beforeunload)', () => {
|
||||
const okSave = () =>
|
||||
vi.fn(() => Promise.resolve({ ok: true, value: filledView } as Result<string, BriefView>));
|
||||
|
||||
it('flushes a pending debounced edit immediately and clears the pending flag', async () => {
|
||||
const save = okSave();
|
||||
const store = await loadedStore({ save });
|
||||
expect(store.hasPendingSave()).toBe(false);
|
||||
|
||||
store.edit({ tag: 'FreeTextBlockAdded', sectionKey: 'kern' });
|
||||
expect(store.hasPendingSave()).toBe(true); // 600ms debounce armed, not yet fired
|
||||
|
||||
await store.flushPending();
|
||||
expect(save).toHaveBeenCalledTimes(1); // no timer wait needed
|
||||
expect(store.hasPendingSave()).toBe(false); // timer consumed
|
||||
});
|
||||
|
||||
it('is a no-op when no edit is pending', async () => {
|
||||
const save = okSave();
|
||||
const store = await loadedStore({ save });
|
||||
await store.flushPending();
|
||||
expect(save).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -17,6 +17,7 @@ import { BriefAdapter, BriefView } from '@brief/infrastructure/brief.adapter';
|
||||
import { LetterPreviewAdapter } from '@brief/infrastructure/letter-preview.adapter';
|
||||
import { RevealBigNummerAdapter } from '@brief/infrastructure/reveal-bignummer.adapter';
|
||||
import { uploadContentUrl } from '@shared/upload/upload.adapter';
|
||||
import { PendingSave, registerPendingSave } from '@shared/application/pending-saves';
|
||||
|
||||
/** Transient action state (submit/approve/reject/send/resetDemo) — one tagged union
|
||||
instead of a busy boolean + a nullable error sitting side by side. */
|
||||
@@ -38,7 +39,7 @@ type LoadedBriefState = Extract<BriefState, { tag: 'loaded' }>;
|
||||
* P1) via `BriefState.loaded.decisions` — this store never computes them itself.
|
||||
*/
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class BriefStore {
|
||||
export class BriefStore implements PendingSave {
|
||||
private adapter = inject(BriefAdapter);
|
||||
private previewAdapter = inject(LetterPreviewAdapter);
|
||||
private revealAdapter = inject(RevealBigNummerAdapter);
|
||||
@@ -188,12 +189,32 @@ export class BriefStore {
|
||||
this.future.set([]);
|
||||
}
|
||||
|
||||
constructor() {
|
||||
// Register so the CanDeactivate guard / beforeunload handler can flush a pending
|
||||
// debounced edit before navigation or unload (see pending-saves.ts).
|
||||
registerPendingSave(this);
|
||||
}
|
||||
|
||||
private saveTimer?: ReturnType<typeof setTimeout>;
|
||||
private scheduleSave() {
|
||||
if (!this.canEdit()) return;
|
||||
clearTimeout(this.saveTimer);
|
||||
// ponytail: 600ms debounce like the wizard draft-sync; the server is the store of record.
|
||||
this.saveTimer = setTimeout(() => void this.flushSave(), 600);
|
||||
// Null the handle when it fires so `hasPendingSave()` reflects "a write is still owed".
|
||||
this.saveTimer = setTimeout(() => {
|
||||
this.saveTimer = undefined;
|
||||
void this.flushSave();
|
||||
}, 600);
|
||||
}
|
||||
|
||||
/** True while a debounced edit hasn't been written yet (PendingSave). */
|
||||
hasPendingSave = () => this.saveTimer !== undefined;
|
||||
/** Flush a pending debounced save now and await it; no-op when nothing is pending. */
|
||||
async flushPending() {
|
||||
if (this.saveTimer === undefined) return;
|
||||
clearTimeout(this.saveTimer);
|
||||
this.saveTimer = undefined;
|
||||
await this.flushSave();
|
||||
}
|
||||
private async flushSave() {
|
||||
const b = this.brief();
|
||||
@@ -217,6 +238,7 @@ export class BriefStore {
|
||||
async resetDemo() {
|
||||
this.actionState.set({ tag: 'Busy' });
|
||||
clearTimeout(this.saveTimer);
|
||||
this.saveTimer = undefined;
|
||||
const r = await this.adapter.reset();
|
||||
this.saveState.set({ tag: 'Idle' });
|
||||
if (r.ok) {
|
||||
@@ -268,6 +290,7 @@ export class BriefStore {
|
||||
private async transition(action: () => Promise<Result<string, BriefView>>) {
|
||||
this.actionState.set({ tag: 'Busy' });
|
||||
clearTimeout(this.saveTimer);
|
||||
this.saveTimer = undefined;
|
||||
await this.flushSave();
|
||||
const r = await action();
|
||||
if (!r.ok) {
|
||||
|
||||
@@ -17,6 +17,7 @@ import {
|
||||
reduce,
|
||||
} from '@brief/domain/org-template.machine';
|
||||
import { OrgTemplateAdapter } from '@brief/infrastructure/org-template.adapter';
|
||||
import { PendingSave, registerPendingSave } from '@shared/application/pending-saves';
|
||||
|
||||
/** Transient action state for publish/rollback/proefbrief — the BriefStore idiom. */
|
||||
type ActionState = { tag: 'Idle' } | { tag: 'Busy' } | { tag: 'Failed'; error: string };
|
||||
@@ -34,7 +35,7 @@ const NO_SUBORGS = $localize`:@@orgTemplate.noSubOrgs:Er zijn geen organisatiesj
|
||||
* (in the reducer) and triggers a save (here). Mirrors `BriefStore`.
|
||||
*/
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class OrgTemplateStore {
|
||||
export class OrgTemplateStore implements PendingSave {
|
||||
private adapter = inject(OrgTemplateAdapter);
|
||||
private uploadAdapter = inject(UploadAdapter);
|
||||
private shell = inject(UploadShellService);
|
||||
@@ -108,6 +109,8 @@ export class OrgTemplateStore {
|
||||
if (status === 'resolved' || status === 'local')
|
||||
this.dispatchUpload({ type: 'CategoriesLoaded', categories: this.categoriesRes.value() ?? [] });
|
||||
});
|
||||
// Flush a pending debounced edit before navigation/unload (see pending-saves.ts).
|
||||
registerPendingSave(this);
|
||||
}
|
||||
|
||||
async load() {
|
||||
@@ -130,6 +133,7 @@ export class OrgTemplateStore {
|
||||
this.selectedSubOrgId.set(subOrgId);
|
||||
this.saveState.set({ tag: 'Idle' });
|
||||
clearTimeout(this.saveTimer);
|
||||
this.saveTimer = undefined;
|
||||
this.store.dispatch({ tag: 'Loading' });
|
||||
const r = await this.adapter.load(subOrgId);
|
||||
if (r.ok) this.store.dispatch({ tag: 'DraftLoaded', view: r.value });
|
||||
@@ -147,7 +151,21 @@ export class OrgTemplateStore {
|
||||
if (this.loaded() === null) return;
|
||||
clearTimeout(this.saveTimer);
|
||||
// ponytail: 600ms debounce, same as BriefStore; the server is the store of record.
|
||||
this.saveTimer = setTimeout(() => void this.flushSave(), 600);
|
||||
// Null the handle when it fires so `hasPendingSave()` reflects "a write is still owed".
|
||||
this.saveTimer = setTimeout(() => {
|
||||
this.saveTimer = undefined;
|
||||
void this.flushSave();
|
||||
}, 600);
|
||||
}
|
||||
|
||||
/** True while a debounced edit hasn't been written yet (PendingSave). */
|
||||
hasPendingSave = () => this.saveTimer !== undefined;
|
||||
/** Flush a pending debounced save now and await it; no-op when nothing is pending. */
|
||||
async flushPending() {
|
||||
if (this.saveTimer === undefined) return;
|
||||
clearTimeout(this.saveTimer);
|
||||
this.saveTimer = undefined;
|
||||
await this.flushSave();
|
||||
}
|
||||
private async flushSave() {
|
||||
const s = this.loaded();
|
||||
@@ -178,6 +196,7 @@ export class OrgTemplateStore {
|
||||
this.pendingPublish.set(false);
|
||||
this.actionState.set({ tag: 'Busy' });
|
||||
clearTimeout(this.saveTimer);
|
||||
this.saveTimer = undefined;
|
||||
await this.flushSave(); // publish the saved draft — flush any pending edit first
|
||||
const r = await this.adapter.publish(s.subOrgId);
|
||||
if (!r.ok) {
|
||||
@@ -193,6 +212,7 @@ export class OrgTemplateStore {
|
||||
if (!s) return;
|
||||
this.actionState.set({ tag: 'Busy' });
|
||||
clearTimeout(this.saveTimer);
|
||||
this.saveTimer = undefined;
|
||||
const r = await this.adapter.rollback(s.subOrgId, version);
|
||||
if (!r.ok) {
|
||||
this.actionState.set({ tag: 'Failed', error: r.error });
|
||||
@@ -207,6 +227,7 @@ export class OrgTemplateStore {
|
||||
if (!s) return;
|
||||
this.actionState.set({ tag: 'Busy' });
|
||||
clearTimeout(this.saveTimer);
|
||||
this.saveTimer = undefined;
|
||||
await this.flushSave(); // the proefbrief renders the server's draft
|
||||
const r = await this.adapter.proefbrief(s.subOrgId);
|
||||
if (!r.ok) {
|
||||
|
||||
@@ -92,12 +92,14 @@ const A4_HEIGHT_PX = (297 * 96) / 25.4;
|
||||
padding: 0 1.5mm;
|
||||
border-radius: var(--rhc-border-radius-sm);
|
||||
font-size: 7.5pt;
|
||||
/* dark text, not white: oranje-500/groen-500 fail 4.5:1 contrast with white (WP-27 axe). */
|
||||
/* changed = dark text on oranje-500 (4.79:1); white on oranje-500 fails (3.23:1). */
|
||||
color: var(--rhc-color-foreground-default);
|
||||
background: var(--rhc-color-oranje-500);
|
||||
}
|
||||
.diff-badge.added {
|
||||
background: var(--rhc-color-groen-500);
|
||||
/* added = white on groen-700 (6.4:1); dark text on any green fails 4.5:1 (WP-29 axe). */
|
||||
color: var(--rhc-color-wit);
|
||||
background: var(--rhc-color-groen-700);
|
||||
}
|
||||
/* Portal-side chrome around the letter surface (not part of the contract file). */
|
||||
.surface {
|
||||
|
||||
@@ -96,4 +96,39 @@ describe('createDraftSync', () => {
|
||||
expect(r.ok).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('flushPending (CanDeactivate guard / beforeunload)', () => {
|
||||
it('hasPendingSave reflects an armed debounce timer', () => {
|
||||
const { draftSync, snap } = setup({
|
||||
create: vi.fn().mockResolvedValue('a1'),
|
||||
syncDraft: vi.fn().mockResolvedValue(undefined),
|
||||
});
|
||||
expect(draftSync.hasPendingSave()).toBe(false);
|
||||
|
||||
snap.set({ draft: { step: 1 }, stepIndex: 0, stepCount: 3, documentIds: [] });
|
||||
tick(); // the effect arms the 600ms timer
|
||||
expect(draftSync.hasPendingSave()).toBe(true);
|
||||
});
|
||||
|
||||
it('flushPending writes the pending draft immediately, before the debounce fires', async () => {
|
||||
const create = vi.fn().mockResolvedValue('a1');
|
||||
const syncDraft = vi.fn().mockResolvedValue(undefined);
|
||||
const { draftSync, snap } = setup({ create, syncDraft });
|
||||
|
||||
snap.set({ draft: { step: 1 }, stepIndex: 0, stepCount: 3, documentIds: [] });
|
||||
tick();
|
||||
await draftSync.flushPending();
|
||||
|
||||
expect(syncDraft).toHaveBeenCalledTimes(1); // no timer advance needed
|
||||
expect(draftSync.hasPendingSave()).toBe(false); // timer consumed
|
||||
});
|
||||
|
||||
it('flushPending is a no-op when nothing is pending', async () => {
|
||||
const syncDraft = vi.fn().mockResolvedValue(undefined);
|
||||
const { draftSync } = setup({ create: vi.fn().mockResolvedValue('a1'), syncDraft });
|
||||
|
||||
await draftSync.flushPending();
|
||||
expect(syncDraft).not.toHaveBeenCalled();
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
@@ -2,6 +2,7 @@ import { DestroyRef, effect, inject } from '@angular/core';
|
||||
import { ActivatedRoute, Router } from '@angular/router';
|
||||
import { Result } from '@shared/kernel/fp';
|
||||
import { runSubmit, SUBMIT_FAILED } from '@shared/application/submit';
|
||||
import { registerPendingSave } from '@shared/application/pending-saves';
|
||||
import type {
|
||||
SubmitApplicationRequest,
|
||||
SubmitApplicationResponse,
|
||||
@@ -104,11 +105,26 @@ export function createDraftSync(deps: DraftSyncDeps) {
|
||||
const snap = deps.snapshot(); // tracked: fires on every machine change
|
||||
if (!snap) return;
|
||||
if (timer) clearTimeout(timer);
|
||||
timer = setTimeout(() => void flush(), DEBOUNCE_MS);
|
||||
// Null the handle when it fires so `hasPendingSave()` reflects "a write is still owed".
|
||||
timer = setTimeout(() => {
|
||||
timer = undefined;
|
||||
void flush();
|
||||
}, DEBOUNCE_MS);
|
||||
});
|
||||
|
||||
inject(DestroyRef).onDestroy(() => timer && clearTimeout(timer));
|
||||
|
||||
// Flush a pending debounced draft write before an in-app route change / unload (see
|
||||
// pending-saves.ts). onDestroy above only cancels the timer — this actually persists it.
|
||||
const hasPendingSave = () => timer !== undefined;
|
||||
const flushPending = async () => {
|
||||
if (timer === undefined) return;
|
||||
clearTimeout(timer);
|
||||
timer = undefined;
|
||||
await flush();
|
||||
};
|
||||
registerPendingSave({ hasPendingSave, flushPending });
|
||||
|
||||
// Attach to a specific Concept id and seed the machine from its draft. A non-Concept
|
||||
// (submitted/gone) id is treated as fresh so it can't reopen as an editable draft.
|
||||
const load = (linked: string): Promise<void> => {
|
||||
@@ -142,6 +158,11 @@ export function createDraftSync(deps: DraftSyncDeps) {
|
||||
};
|
||||
|
||||
return {
|
||||
/** True while a debounced draft write is still pending (PendingSave). */
|
||||
hasPendingSave,
|
||||
/** Flush the pending draft write now and await it; no-op when nothing is pending. */
|
||||
flushPending,
|
||||
|
||||
/** Resolve the initial state: a `?aanvraag` link wins; else resume this type's
|
||||
existing Concept; else start fresh (a Concept is created on first progress). */
|
||||
async resume() {
|
||||
|
||||
@@ -0,0 +1,86 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { PendingSave, PendingSaves, flushPendingGuard } from './pending-saves';
|
||||
|
||||
/** A fake autosave owner whose pending-ness and flush are controllable. */
|
||||
function fakeOwner(pending: boolean): PendingSave & { flushPending: ReturnType<typeof vi.fn> } {
|
||||
return {
|
||||
hasPendingSave: () => pending,
|
||||
flushPending: vi.fn().mockResolvedValue(undefined),
|
||||
};
|
||||
}
|
||||
|
||||
describe('PendingSaves registry', () => {
|
||||
it('hasPending is true only while some registered owner has a pending write', () => {
|
||||
const reg = new PendingSaves();
|
||||
const idle = fakeOwner(false);
|
||||
reg.register(idle);
|
||||
expect(reg.hasPending()).toBe(false);
|
||||
|
||||
const dirty = fakeOwner(true);
|
||||
reg.register(dirty);
|
||||
expect(reg.hasPending()).toBe(true);
|
||||
});
|
||||
|
||||
it('unregister removes an owner so it no longer counts', () => {
|
||||
const reg = new PendingSaves();
|
||||
const dirty = fakeOwner(true);
|
||||
const off = reg.register(dirty);
|
||||
expect(reg.hasPending()).toBe(true);
|
||||
off();
|
||||
expect(reg.hasPending()).toBe(false);
|
||||
});
|
||||
|
||||
it('flushAll flushes only the pending owners', async () => {
|
||||
const reg = new PendingSaves();
|
||||
const idle = fakeOwner(false);
|
||||
const dirty = fakeOwner(true);
|
||||
reg.register(idle);
|
||||
reg.register(dirty);
|
||||
|
||||
await reg.flushAll();
|
||||
|
||||
expect(dirty.flushPending).toHaveBeenCalledTimes(1);
|
||||
expect(idle.flushPending).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('flushAll awaits every owner and swallows a rejected flush', async () => {
|
||||
const reg = new PendingSaves();
|
||||
const failing = fakeOwner(true);
|
||||
failing.flushPending.mockRejectedValue(new Error('save failed'));
|
||||
const ok = fakeOwner(true);
|
||||
reg.register(failing);
|
||||
reg.register(ok);
|
||||
|
||||
await expect(reg.flushAll()).resolves.toBeUndefined(); // never rejects
|
||||
expect(ok.flushPending).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe('flushPendingGuard', () => {
|
||||
it('flushes then allows navigation when a write is pending', async () => {
|
||||
const dirty = fakeOwner(true);
|
||||
TestBed.configureTestingModule({});
|
||||
const reg = TestBed.inject(PendingSaves);
|
||||
reg.register(dirty);
|
||||
|
||||
const result = TestBed.runInInjectionContext(() =>
|
||||
// the guard ignores its route args
|
||||
(flushPendingGuard as (...a: unknown[]) => boolean | Promise<boolean>)(),
|
||||
);
|
||||
|
||||
await expect(result).resolves.toBe(true);
|
||||
expect(dirty.flushPending).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
it('allows navigation immediately when nothing is pending', () => {
|
||||
TestBed.configureTestingModule({});
|
||||
TestBed.inject(PendingSaves).register(fakeOwner(false));
|
||||
|
||||
const result = TestBed.runInInjectionContext(() =>
|
||||
(flushPendingGuard as (...a: unknown[]) => boolean | Promise<boolean>)(),
|
||||
);
|
||||
|
||||
expect(result).toBe(true); // synchronous, not a Promise
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,85 @@
|
||||
import {
|
||||
DestroyRef,
|
||||
ENVIRONMENT_INITIALIZER,
|
||||
Injectable,
|
||||
inject,
|
||||
} from '@angular/core';
|
||||
import { CanDeactivateFn } from '@angular/router';
|
||||
|
||||
/**
|
||||
* A source of debounced, not-yet-flushed writes (autosave). The two autosave owners in
|
||||
* this app have different lifetimes — root singleton stores (`BriefStore`,
|
||||
* `OrgTemplateStore`) and per-wizard `createDraftSync` controllers living inside child
|
||||
* organisms — so both register here instead of the guard/unload handler needing to know
|
||||
* which page or store owns the pending write.
|
||||
*/
|
||||
export interface PendingSave {
|
||||
/** True while a debounced edit hasn't been written to the backend yet. */
|
||||
hasPendingSave(): boolean;
|
||||
/** Flush that pending write now and await it. No-op when nothing is pending. */
|
||||
flushPending(): Promise<void>;
|
||||
}
|
||||
|
||||
/** Registry of every active autosave owner. The `CanDeactivate` guard and the
|
||||
`beforeunload` handler flush through this — one seam, both callers. */
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class PendingSaves {
|
||||
private readonly owners = new Set<PendingSave>();
|
||||
|
||||
/** Register an owner; returns an unregister function. */
|
||||
register(owner: PendingSave): () => void {
|
||||
this.owners.add(owner);
|
||||
return () => this.owners.delete(owner);
|
||||
}
|
||||
|
||||
hasPending(): boolean {
|
||||
return [...this.owners].some((o) => o.hasPendingSave());
|
||||
}
|
||||
|
||||
/** Flush every owner that has a pending write, awaiting all. Best-effort: a rejected
|
||||
flush is swallowed (a failed autosave surfaces its own error state; navigation must
|
||||
not be blocked by it). */
|
||||
async flushAll(): Promise<void> {
|
||||
await Promise.allSettled(
|
||||
[...this.owners].filter((o) => o.hasPendingSave()).map((o) => o.flushPending()),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/** Register the current injection context's owner for the life of its `DestroyRef`.
|
||||
Call from a constructor or field initializer (root store, or `createDraftSync`). */
|
||||
export function registerPendingSave(owner: PendingSave): void {
|
||||
const unregister = inject(PendingSaves).register(owner);
|
||||
inject(DestroyRef).onDestroy(unregister);
|
||||
}
|
||||
|
||||
/** `CanDeactivate` guard: flush any pending debounced write before an in-app route change,
|
||||
then allow navigation. Awaitable, so the write lands before the page tears down (which
|
||||
would otherwise drop a sub-debounce edit). We never block leaving — the flush is a
|
||||
guarantee of effort, not a gate. */
|
||||
export const flushPendingGuard: CanDeactivateFn<unknown> = () => {
|
||||
const pending = inject(PendingSaves);
|
||||
return pending.hasPending() ? pending.flushAll().then(() => true) : true;
|
||||
};
|
||||
|
||||
/** Wire a `beforeunload` handler that guards the last-mile save on a hard tab-close/reload.
|
||||
ponytail: the HTTP seam is Angular `HttpClient` (no `keepalive`/`sendBeacon`), so an
|
||||
async flush can't be guaranteed to finish as the page tears down — we fire it best-effort
|
||||
AND trigger the browser's native "unsaved changes" prompt, which lets the ~600ms debounce
|
||||
land if the user stays. Upgrade path: a `sendBeacon`/keepalive last-mile if this ever
|
||||
needs to be guaranteed. */
|
||||
export function provideUnloadFlush() {
|
||||
return {
|
||||
provide: ENVIRONMENT_INITIALIZER,
|
||||
multi: true,
|
||||
useValue: () => {
|
||||
const pending = inject(PendingSaves);
|
||||
window.addEventListener('beforeunload', (e) => {
|
||||
if (!pending.hasPending()) return;
|
||||
void pending.flushAll();
|
||||
e.preventDefault();
|
||||
e.returnValue = '';
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -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';
|
||||
|
||||
@@ -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
@@ -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": {
|
||||
|
||||
Reference in New Issue
Block a user