feat(brief): letter composition + two-person approval (teaching slice)

New `brief` context — a letter-composition feature with a drafter/approver
approval workflow, built as a teaching vertical slice on the repo's existing
FP + Elm + atomic-design patterns (see plan in ~/.claude/plans).

Domain (pure):
- Rich text as a serialisable value tree (placeholders are first-class nodes),
  moved to @shared/kernel/rich-text.ts so the shared editor can use it.
- lintPlaceholders: a pure, total content -> Diagnostic[] linter, derived never stored.
- brief.machine.ts: status sum-type with guarded transitions; frozen-snapshot =
  deep value copy; derived diagnostics/editability. Full specs.

Backend (.NET stub):
- BriefStore + seed, GET/PUT /brief and submit/approve/reject/send endpoints,
  role via X-Role header (mirrors X-Admin), transition + approver!=drafter guards,
  audit logging. Regenerated typed client via gen:api. +6 backend tests.

Seam:
- brief.adapter.ts maps flat wire unions <-> domain discriminated unions at the
  parse boundary (+ spec).

UI (atomic):
- shared atoms: checkbox, placeholder-chip; molecule: rich-text-editor (no-dep
  contenteditable, DOM<->RichTextBlock round-trip tested).
- brief/ui: letter-block, passage-picker, diagnostics-panel, rejection-comments,
  letter-section, letter-composer, letter-preview, brief.page + /brief route.
- Dev-only ?role=drafter|approver toggle + roleInterceptor; dashboard nav link.

Enforcement: @brief/* alias + eslint layer boundary (brief depends only on shared).

Also included (same session):
- Value-object specs (postcode/uren/big-nummer) — closes the "domain must have a spec" gap.
- src/docs/ Storybook MDX foundation pages (atomic design, tokens, FP-in-UI).
- .storybook/tsconfig.json: add @angular/localize to types (Storybook was fully
  broken — $localize unresolved — dev + build).

Verified: 168 FE tests, 68 backend tests, lint/build/check:tokens green,
Storybook boots, end-to-end HTTP smoke (self-approve 403, approver 200, full flow).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-07-01 21:32:22 +02:00
parent 0aada9037e
commit 053160c5c9
49 changed files with 13963 additions and 573 deletions

View File

@@ -0,0 +1,134 @@
import { describe, it, expect } from 'vitest';
import { Brief, BriefStatus, LibraryPassage } from './brief';
import { RichTextBlock } from '@shared/kernel/rich-text';
import { PlaceholderDef } from './placeholders';
import { BriefState, BriefMsg, reduce } from './brief.machine';
const placeholders: PlaceholderDef[] = [
{ key: 'naam', label: 'Naam', autoResolvable: true },
{ key: 'reden', label: 'Reden', autoResolvable: false },
];
const text = (t: string): RichTextBlock => ({ paragraphs: [{ nodes: [{ type: 'text', text: t }] }] });
const libPassage = (id: string, sectionKey: string): LibraryPassage => ({
passageId: id,
scope: 'global',
sectionKey,
label: `Passage ${id}`,
content: text(`inhoud ${id}`),
version: 3,
});
function briefWith(status: BriefStatus, sections?: Brief['sections']): Brief {
return {
briefId: 'b1',
beroep: 'arts',
templateId: 't1',
placeholders,
sections: sections ?? [
{ sectionKey: 'aanhef', title: 'Aanhef', required: true, blocks: [] },
{ sectionKey: 'slot', title: 'Slot', required: false, blocks: [] },
],
status,
drafterId: 'u1',
};
}
const loaded = (status: BriefStatus = { tag: 'draft' }, sections?: Brief['sections']): BriefState => ({
tag: 'loaded',
brief: briefWith(status, sections),
availablePassages: [libPassage('p1', 'aanhef'), libPassage('p2', 'aanhef')],
});
const sectionBlocks = (s: BriefState, key: string) =>
s.tag === 'loaded' ? s.brief.sections.find((x) => x.sectionKey === key)!.blocks : [];
describe('brief.machine reduce', () => {
it('BriefLoaded / BriefLoadFailed / Seed set state directly', () => {
expect(reduce(initialLoading(), { tag: 'BriefLoaded', brief: briefWith({ tag: 'draft' }), availablePassages: [] }).tag).toBe('loaded');
expect(reduce(initialLoading(), { tag: 'BriefLoadFailed', reason: 'x' })).toEqual({ tag: 'failed', reason: 'x' });
const seeded = loaded();
expect(reduce(initialLoading(), { tag: 'Seed', state: seeded })).toBe(seeded);
});
it('PassagesInserted creates one frozen block per passage, in order, with local ids', () => {
const s = reduce(loaded(), { tag: 'PassagesInserted', sectionKey: 'aanhef', passages: [libPassage('p1', 'aanhef'), libPassage('p2', 'aanhef')] });
const blocks = sectionBlocks(s, 'aanhef');
expect(blocks.map((b) => b.blockId)).toEqual(['local-1', 'local-2']);
expect(blocks.every((b) => b.type === 'passage' && b.edited === false)).toBe(true);
expect(blocks[0].type === 'passage' && blocks[0].sourcePassageId).toBe('p1');
});
it('PassagesInserted deep-copies content — later library mutation does not leak in', () => {
const passage = libPassage('p1', 'aanhef');
const s = reduce(loaded(), { tag: 'PassagesInserted', sectionKey: 'aanhef', passages: [passage] });
// Mutate the source passage object after insertion.
(passage.content.paragraphs[0].nodes as { type: 'text'; text: string }[])[0].text = 'HACKED';
const block = sectionBlocks(s, 'aanhef')[0];
expect(block.content.paragraphs[0].nodes[0]).toEqual({ type: 'text', text: 'inhoud p1' });
});
it('FreeTextBlockAdded appends an empty free-text block', () => {
const s = reduce(loaded(), { tag: 'FreeTextBlockAdded', sectionKey: 'slot' });
const blocks = sectionBlocks(s, 'slot');
expect(blocks).toHaveLength(1);
expect(blocks[0].type).toBe('freeText');
});
it('BlockContentEdited replaces content and marks a passage block edited', () => {
let s = reduce(loaded(), { tag: 'PassagesInserted', sectionKey: 'aanhef', passages: [libPassage('p1', 'aanhef')] });
s = reduce(s, { tag: 'BlockContentEdited', blockId: 'local-1', content: text('aangepast') });
const block = sectionBlocks(s, 'aanhef')[0];
expect(block.type === 'passage' && block.edited).toBe(true);
expect(block.content).toEqual(text('aangepast'));
});
it('BlockRemoved and BlockMovedWithinSection reorder within a section', () => {
let s = reduce(loaded(), { tag: 'PassagesInserted', sectionKey: 'aanhef', passages: [libPassage('p1', 'aanhef'), libPassage('p2', 'aanhef')] });
s = reduce(s, { tag: 'BlockMovedWithinSection', blockId: 'local-1', toIndex: 1 });
expect(sectionBlocks(s, 'aanhef').map((b) => b.blockId)).toEqual(['local-2', 'local-1']);
s = reduce(s, { tag: 'BlockRemoved', blockId: 'local-2' });
expect(sectionBlocks(s, 'aanhef').map((b) => b.blockId)).toEqual(['local-1']);
});
it('edits are no-ops once submitted (status invariant)', () => {
const s = loaded({ tag: 'submitted', submittedBy: 'u1', submittedAt: 't' });
expect(reduce(s, { tag: 'FreeTextBlockAdded', sectionKey: 'slot' })).toBe(s);
});
it('editing a rejected letter reopens it to draft', () => {
const s = loaded({ tag: 'rejected', rejectedBy: 'u2', rejectedAt: 't', comments: 'graag aanpassen' });
const next = reduce(s, { tag: 'FreeTextBlockAdded', sectionKey: 'slot' });
expect(next.tag === 'loaded' && next.brief.status.tag).toBe('draft');
expect(sectionBlocks(next, 'slot')).toHaveLength(1);
});
it('Submitted fires only from draft and only when required sections are filled', () => {
// required 'aanhef' empty → no-op
expect(reduce(loaded(), { tag: 'Submitted', by: 'u1', at: 't' })).toEqual(loaded());
// fill the required section, then submit
const filled = reduce(loaded(), { tag: 'FreeTextBlockAdded', sectionKey: 'aanhef' });
const submitted = reduce(filled, { tag: 'Submitted', by: 'u1', at: 't' });
expect(submitted.tag === 'loaded' && submitted.brief.status).toEqual({ tag: 'submitted', submittedBy: 'u1', submittedAt: 't' });
});
it('approve/reject fire only from submitted; send only from approved', () => {
const submitted = loaded({ tag: 'submitted', submittedBy: 'u1', submittedAt: 't' });
// approve from draft is a no-op
expect(reduce(loaded(), { tag: 'Approved', by: 'u2', at: 't' })).toEqual(loaded());
const approved = reduce(submitted, { tag: 'Approved', by: 'u2', at: 't2' });
expect(approved.tag === 'loaded' && approved.brief.status).toEqual({ tag: 'approved', approvedBy: 'u2', approvedAt: 't2' });
// reject carries comments
const rejected = reduce(submitted, { tag: 'Rejected', by: 'u2', at: 't2', comments: 'nee' });
expect(rejected.tag === 'loaded' && rejected.brief.status).toEqual({ tag: 'rejected', rejectedBy: 'u2', rejectedAt: 't2', comments: 'nee' });
// send only from approved
expect(reduce(submitted, { tag: 'Sent', at: 't' })).toBe(submitted);
const sent = reduce(approved, { tag: 'Sent', at: 't3' });
expect(sent.tag === 'loaded' && sent.brief.status).toEqual({ tag: 'sent', sentAt: 't3' });
});
});
function initialLoading(): BriefState {
return { tag: 'loading' };
}

View File

@@ -0,0 +1,168 @@
import { assertNever } from '@shared/kernel/fp';
import { Brief, BriefStatus, LetterBlock, LetterSection, LibraryPassage, allBlocks, canSubmit } from './brief';
import { RichTextBlock, deepCopyBlock, emptyBlock } from '@shared/kernel/rich-text';
/**
* The letter composition state machine (Model + Msg + pure reduce), modeled on
* `herregistratie/domain/intake.machine.ts`.
*
* Two invariants are enforced *here*, not in the UI:
* - Status transitions are total and guarded — an out-of-order transition Msg is a
* no-op (`draft→submitted→approved/rejected→draft`, `approved→sent`).
* - Edits are only possible in `draft`/`rejected`; editing a `rejected` letter flips
* it back to `draft`. Sections can never be added, removed, or reordered — there
* is no Msg for it, so it is unrepresentable.
*
* Role (drafter vs approver) is NOT a reducer concern: the UI derives `editable` from
* role+status and simply doesn't dispatch edits when the actor may not edit. The
* reducer guards the status invariant; the UI guards the role invariant.
*
* Note: there is no `PlaceholderInserted` Msg. The editor inserts a placeholder NODE
* at the caret and emits the whole new block via `BlockContentEdited`; its insert menu
* only offers keys from `brief.placeholders`, so inserting an unknown key is
* structurally impossible (a pasted `{{…}}` is caught by the linter as `malformed`).
*/
export type BriefState =
| { tag: 'loading' }
| { tag: 'loaded'; brief: Brief; availablePassages: readonly LibraryPassage[] }
| { tag: 'failed'; reason: string };
export const initial: BriefState = { tag: 'loading' };
export type BriefMsg =
| { tag: 'BriefLoaded'; brief: Brief; availablePassages: readonly LibraryPassage[] }
| { tag: 'BriefLoadFailed'; reason: string }
| { tag: 'PassagesInserted'; sectionKey: string; passages: readonly LibraryPassage[] } // multi-select
| { tag: 'FreeTextBlockAdded'; sectionKey: string }
| { tag: 'BlockContentEdited'; blockId: string; content: RichTextBlock }
| { tag: 'BlockRemoved'; blockId: string }
| { tag: 'BlockMovedWithinSection'; blockId: string; toIndex: number }
| { tag: 'Submitted'; by: string; at: string } // draft → submitted
| { tag: 'Approved'; by: string; at: string } // submitted → approved
| { tag: 'Rejected'; by: string; at: string; comments: string } // submitted → rejected
| { tag: 'Sent'; at: string } // approved → sent
| { tag: 'Seed'; state: BriefState };
/** Edits are allowed only in these statuses; editing a rejected letter reopens it. */
function isEditable(status: BriefStatus): boolean {
return status.tag === 'draft' || status.tag === 'rejected';
}
/** Next `local-N` block id — DERIVED from existing ids (max + 1), not a stored counter. */
function nextLocalIndex(brief: Brief): number {
let max = 0;
for (const b of allBlocks(brief)) {
const m = /^local-(\d+)$/.exec(b.blockId);
if (m) max = Math.max(max, Number(m[1]));
}
return max + 1;
}
function mapSection(brief: Brief, sectionKey: string, f: (s: LetterSection) => LetterSection): Brief {
return { ...brief, sections: brief.sections.map((s) => (s.sectionKey === sectionKey ? f(s) : s)) };
}
function mapBlocks(brief: Brief, f: (blocks: readonly LetterBlock[]) => LetterBlock[]): Brief {
return { ...brief, sections: brief.sections.map((s) => ({ ...s, blocks: f(s.blocks) })) };
}
/** Apply an edit to the brief, guarded by status. A rejected letter reopens to draft. */
function withEdit(s: BriefState, f: (b: Brief) => Brief): BriefState {
if (s.tag !== 'loaded' || !isEditable(s.brief.status)) return s;
let brief = f(s.brief);
if (brief.status.tag === 'rejected') brief = { ...brief, status: { tag: 'draft' } };
return { ...s, brief };
}
function insertPassages(brief: Brief, sectionKey: string, passages: readonly LibraryPassage[]): Brief {
let idx = nextLocalIndex(brief);
// The freeze happens HERE: each block gets a deep VALUE copy of the library content,
// so later library edits can never mutate this letter (frozen snapshot).
const newBlocks: LetterBlock[] = passages.map((p) => ({
type: 'passage',
blockId: `local-${idx++}`,
sourcePassageId: p.passageId,
sourceVersion: p.version,
content: deepCopyBlock(p.content),
edited: false,
}));
return mapSection(brief, sectionKey, (s) => ({ ...s, blocks: [...s.blocks, ...newBlocks] }));
}
function addFreeText(brief: Brief, sectionKey: string): Brief {
const block: LetterBlock = { type: 'freeText', blockId: `local-${nextLocalIndex(brief)}`, content: emptyBlock() };
return mapSection(brief, sectionKey, (s) => ({ ...s, blocks: [...s.blocks, block] }));
}
function editBlockContent(brief: Brief, blockId: string, content: RichTextBlock): Brief {
return mapBlocks(brief, (blocks) =>
blocks.map((b) =>
b.blockId !== blockId
? b
: b.type === 'passage'
? { ...b, content, edited: true } // editing a snapshot marks it, keeps provenance
: { ...b, content },
),
);
}
function moveWithinSection(blocks: readonly LetterBlock[], blockId: string, toIndex: number): LetterBlock[] {
const from = blocks.findIndex((b) => b.blockId === blockId);
if (from === -1) return [...blocks];
const clamped = Math.max(0, Math.min(toIndex, blocks.length - 1));
const next = [...blocks];
const [moved] = next.splice(from, 1);
next.splice(clamped, 0, moved);
return next;
}
export function reduce(s: BriefState, m: BriefMsg): BriefState {
switch (m.tag) {
case 'BriefLoaded':
return { tag: 'loaded', brief: m.brief, availablePassages: m.availablePassages };
case 'BriefLoadFailed':
return { tag: 'failed', reason: m.reason };
case 'Seed':
return m.state;
case 'PassagesInserted':
return withEdit(s, (b) => insertPassages(b, m.sectionKey, m.passages));
case 'FreeTextBlockAdded':
return withEdit(s, (b) => addFreeText(b, m.sectionKey));
case 'BlockContentEdited':
return withEdit(s, (b) => editBlockContent(b, m.blockId, m.content));
case 'BlockRemoved':
return withEdit(s, (b) => mapBlocks(b, (blocks) => blocks.filter((x) => x.blockId !== m.blockId)));
case 'BlockMovedWithinSection':
return withEdit(s, (b) =>
mapBlocks(b, (blocks) =>
blocks.some((x) => x.blockId === m.blockId) ? moveWithinSection(blocks, m.blockId, m.toIndex) : [...blocks],
),
);
case 'Submitted':
// Guard the transition AND the completeness invariant.
return transition(s, 'draft', () => ({ tag: 'submitted', submittedBy: m.by, submittedAt: m.at }), canSubmit);
case 'Approved':
return transition(s, 'submitted', () => ({ tag: 'approved', approvedBy: m.by, approvedAt: m.at }));
case 'Rejected':
return transition(s, 'submitted', () => ({ tag: 'rejected', rejectedBy: m.by, rejectedAt: m.at, comments: m.comments }));
case 'Sent':
return transition(s, 'approved', () => ({ tag: 'sent', sentAt: m.at }));
default:
return assertNever(m);
}
}
/** A guarded status transition: only fires from `from`, and only if `guard` passes. */
function transition(
s: BriefState,
from: BriefStatus['tag'],
next: () => BriefStatus,
guard: (b: Brief) => boolean = () => true,
): BriefState {
if (s.tag !== 'loaded' || s.brief.status.tag !== from || !guard(s.brief)) return s;
return { ...s, brief: { ...s.brief, status: next() } };
}

View File

@@ -0,0 +1,49 @@
import { describe, it, expect } from 'vitest';
import { Brief, LetterBlock, allDiagnostics, canSubmit, hasBlockingErrors, unresolvedPlaceholders } from './brief';
import { PlaceholderDef } from './placeholders';
import { RichTextBlock } from '@shared/kernel/rich-text';
const placeholders: PlaceholderDef[] = [
{ key: 'naam', label: 'Naam', autoResolvable: true },
{ key: 'reden', label: 'Reden', autoResolvable: false },
];
const content = (...keys: string[]): RichTextBlock => ({
paragraphs: [{ nodes: keys.map((key) => ({ type: 'placeholder', key })) }],
});
const passage = (blockId: string, ...keys: string[]): LetterBlock => ({
type: 'freeText',
blockId,
content: content(...keys),
});
function brief(sections: Brief['sections']): Brief {
return { briefId: 'b1', beroep: 'arts', templateId: 't1', placeholders, sections, status: { tag: 'draft' }, drafterId: 'u1' };
}
describe('brief selectors', () => {
it('unresolvedPlaceholders returns deduped manual keys only (auto excluded)', () => {
const b = brief([
{ sectionKey: 's1', title: 'S1', required: true, blocks: [passage('local-1', 'naam', 'reden')] },
{ sectionKey: 's2', title: 'S2', required: false, blocks: [passage('local-2', 'reden')] },
]);
expect(unresolvedPlaceholders(b)).toEqual(['reden']); // 'naam' is auto; 'reden' deduped
});
it('allDiagnostics flattens across sections and blocks', () => {
const b = brief([
{ sectionKey: 's1', title: 'S1', required: true, blocks: [passage('local-1', 'reden', 'onbekend')] },
]);
const codes = allDiagnostics(b).map((d) => d.code);
expect(codes).toContain('unresolved-at-send'); // reden
expect(codes).toContain('unknown-placeholder'); // onbekend
expect(hasBlockingErrors(allDiagnostics(b))).toBe(true); // unknown is an error
});
it('canSubmit is false when a required section is empty, true otherwise', () => {
expect(canSubmit(brief([{ sectionKey: 's1', title: 'S1', required: true, blocks: [] }]))).toBe(false);
expect(canSubmit(brief([{ sectionKey: 's1', title: 'S1', required: false, blocks: [] }]))).toBe(true);
expect(canSubmit(brief([{ sectionKey: 's1', title: 'S1', required: true, blocks: [passage('local-1')] }]))).toBe(true);
});
});

View File

@@ -0,0 +1,99 @@
import { RichTextBlock, placeholderKeysIn } from '@shared/kernel/rich-text';
import { Diagnostic, lintPlaceholders, PlaceholderDef } from './placeholders';
/**
* The `Brief` (letter) entity and its derived selectors.
*
* A letter has a FIXED section structure (from a template, server-instantiated); the
* drafter fills a skeleton, never reorders sections. Each block is either a frozen
* snapshot of a library passage (provenance kept) or free text. Everything the UI
* needs beyond the stored shape — diagnostics, unresolved placeholders, whether it
* can be submitted — is DERIVED here, never stored.
*/
export type PassageScope = 'global' | 'beroep';
// Re-export placeholderKeysIn for one-import convenience at call sites.
export { placeholderKeysIn };
/** A passage in the library (the source). Snapshotted into a letter on insert. */
export interface LibraryPassage {
readonly passageId: string;
readonly scope: PassageScope;
readonly beroep?: string; // set when scope === 'beroep'
readonly sectionKey: string;
readonly label: string;
readonly content: RichTextBlock;
readonly version: number; // library version, for provenance only
}
/** A block inside a letter section: a frozen passage snapshot, or free text. */
export type LetterBlock =
| {
readonly type: 'passage';
readonly blockId: string;
readonly sourcePassageId: string; // provenance
readonly sourceVersion: number; // library version at snapshot time (audit only)
readonly content: RichTextBlock; // FROZEN, possibly edited — source of truth for this block
readonly edited: boolean; // changed from the snapshot?
}
| {
readonly type: 'freeText';
readonly blockId: string;
readonly content: RichTextBlock;
};
export interface LetterSection {
readonly sectionKey: string;
readonly title: string;
readonly required: boolean;
readonly blocks: readonly LetterBlock[];
}
/** The approval state machine as a sum type — transitions are total and guarded in
`brief.machine.ts`; illegal transitions are unrepresentable. */
export type BriefStatus =
| { readonly tag: 'draft' }
| { readonly tag: 'submitted'; readonly submittedBy: string; readonly submittedAt: string }
| { readonly tag: 'approved'; readonly approvedBy: string; readonly approvedAt: string }
| { readonly tag: 'rejected'; readonly rejectedBy: string; readonly rejectedAt: string; readonly comments: string }
| { readonly tag: 'sent'; readonly sentAt: string };
export interface Brief {
readonly briefId: string;
readonly beroep: string; // drives which beroep-scoped passages apply
readonly templateId: string;
readonly placeholders: readonly PlaceholderDef[]; // valid fields for this letter
readonly sections: readonly LetterSection[]; // instantiated from the template, in order
readonly status: BriefStatus;
readonly drafterId: string;
}
// --- Derived selectors (pure; recomputed, never stored) ---
export function allBlocks(brief: Brief): LetterBlock[] {
return brief.sections.flatMap((s) => s.blocks);
}
/** Every diagnostic in the letter, in section→block→node order. This is what the
diagnostics panel renders and what the send gate checks. */
export function allDiagnostics(brief: Brief): Diagnostic[] {
return allBlocks(brief).flatMap((b) => lintPlaceholders(b.content, brief.placeholders, b.blockId));
}
export function hasBlockingErrors(diagnostics: readonly Diagnostic[]): boolean {
return diagnostics.some((d) => d.severity === 'error');
}
/** Manual (non-auto-resolvable) placeholder keys still present, deduped. These are the
`unresolved-at-send` warnings, surfaced as a completeness list. */
export function unresolvedPlaceholders(brief: Brief): string[] {
const auto = new Set(brief.placeholders.filter((p) => p.autoResolvable).map((p) => p.key));
const used = allBlocks(brief).flatMap((b) => placeholderKeysIn(b.content));
return [...new Set(used.filter((k) => !auto.has(k)))];
}
/** A letter can be submitted only when every REQUIRED section has at least one block. */
export function canSubmit(brief: Brief): boolean {
return brief.sections.every((s) => !s.required || s.blocks.length > 0);
}

View File

@@ -0,0 +1,72 @@
import { describe, it, expect } from 'vitest';
import { RichTextBlock } from '@shared/kernel/rich-text';
import { PlaceholderDef, lintPlaceholders, severityOf } from './placeholders';
const valid: PlaceholderDef[] = [
{ key: 'naam', label: 'Naam', autoResolvable: true }, // clean when used
{ key: 'reden', label: 'Reden', autoResolvable: false }, // manual → unresolved-at-send
{ key: 'oud_veld', label: 'Oud veld', autoResolvable: true, deprecated: true },
{ key: 'niet_invulbaar', label: 'Niet invulbaar', autoResolvable: true, fillable: false },
];
const withPlaceholder = (key: string): RichTextBlock => ({ paragraphs: [{ nodes: [{ type: 'placeholder', key }] }] });
const withText = (text: string): RichTextBlock => ({ paragraphs: [{ nodes: [{ type: 'text', text }] }] });
describe('lintPlaceholders', () => {
it('clean content (auto-resolvable, fillable, current key) yields no diagnostics', () => {
expect(lintPlaceholders(withPlaceholder('naam'), valid, 'b1')).toEqual([]);
expect(lintPlaceholders(withText('gewone tekst'), valid, 'b1')).toEqual([]);
});
it('flags an unknown key as an error', () => {
const [d] = lintPlaceholders(withPlaceholder('onbekend'), valid, 'b1');
expect(d.code).toBe('unknown-placeholder');
expect(d.severity).toBe('error');
expect(d.placeholderKey).toBe('onbekend');
expect(d.location).toEqual({ blockId: 'b1', paragraphIndex: 0, nodeIndex: 0 });
});
it('flags a not-fillable key as an error', () => {
const [d] = lintPlaceholders(withPlaceholder('niet_invulbaar'), valid, 'b1');
expect(d.code).toBe('not-fillable');
expect(d.severity).toBe('error');
});
it('flags a deprecated key as a warning', () => {
const [d] = lintPlaceholders(withPlaceholder('oud_veld'), valid, 'b1');
expect(d.code).toBe('deprecated');
expect(d.severity).toBe('warning');
});
it('flags a manual placeholder as unresolved-at-send (warning)', () => {
const [d] = lintPlaceholders(withPlaceholder('reden'), valid, 'b1');
expect(d.code).toBe('unresolved-at-send');
expect(d.severity).toBe('warning');
});
it('flags raw braces in text as malformed (paste safety net)', () => {
const [d] = lintPlaceholders(withText('Beste {{naam'), valid, 'b1');
expect(d.code).toBe('malformed');
expect(d.severity).toBe('error');
expect(d.placeholderKey).toBeUndefined();
});
it('returns diagnostics in document order across paragraphs/nodes', () => {
const content: RichTextBlock = {
paragraphs: [
{ nodes: [{ type: 'placeholder', key: 'onbekend' }] },
{ nodes: [{ type: 'text', text: 'ok' }, { type: 'placeholder', key: 'reden' }] },
],
};
const codes = lintPlaceholders(content, valid, 'b1').map((d) => `${d.code}@${d.location.paragraphIndex}.${d.location.nodeIndex}`);
expect(codes).toEqual(['unknown-placeholder@0.0', 'unresolved-at-send@1.1']);
});
it('severityOf maps each code to its policy', () => {
expect(severityOf('malformed')).toBe('error');
expect(severityOf('unknown-placeholder')).toBe('error');
expect(severityOf('not-fillable')).toBe('error');
expect(severityOf('deprecated')).toBe('warning');
expect(severityOf('unresolved-at-send')).toBe('warning');
});
});

View File

@@ -0,0 +1,115 @@
import { RichTextBlock } from '@shared/kernel/rich-text';
/**
* Placeholder fields and the PURE linter over them.
*
* `lintPlaceholders` is a total, effect-free function of (content, valid set). It
* runs identically on the client (for live UX) and could run on the server (for
* authority) — same rules, same config, so the two agree by construction. The FE
* never STORES its output: diagnostics are a `computed()` over content (see
* `brief.ts` selectors), the same "derive, don't store" discipline as wizard step
* validity.
*/
/** A placeholder field the template knows about. `fillable`/`deprecated` default to
the healthy case; the seed flips them to exercise the not-fillable/deprecated rules. */
export interface PlaceholderDef {
readonly key: string; // e.g. 'naam_zorgverlener'
readonly label: string; // human label for the insert menu, e.g. 'Naam zorgverlener'
readonly autoResolvable: boolean; // server can fill from case data (name, date, …)
readonly fillable?: boolean; // default true; false → not resolvable for this beroep/case type
readonly deprecated?: boolean; // default false; true → retired but still referenceable in old snapshots
}
export type DiagnosticSeverity = 'error' | 'warning';
export type DiagnosticCode =
| 'malformed' // raw braces in a text node (a paste that should have been a chip)
| 'unknown-placeholder' // well-formed key not in the valid set
| 'not-fillable' // key exists but isn't resolvable for this case type / beroep
| 'deprecated' // key was valid once but the template no longer offers it
| 'unresolved-at-send'; // manual (non-auto-resolvable) placeholder still to be filled
export interface DiagnosticLocation {
readonly blockId: string;
readonly paragraphIndex: number;
readonly nodeIndex: number;
}
export interface Diagnostic {
readonly severity: DiagnosticSeverity;
readonly code: DiagnosticCode;
readonly placeholderKey?: string;
readonly location: DiagnosticLocation;
readonly message: string; // human-readable, Dutch
}
/** `error` blocks save (author time) and send (send time); `warning` is surfaced but allowed. */
export function severityOf(code: DiagnosticCode): DiagnosticSeverity {
switch (code) {
case 'malformed':
case 'unknown-placeholder':
case 'not-fillable':
return 'error';
case 'deprecated':
case 'unresolved-at-send':
return 'warning';
}
}
// Raw `{{` or `}}` in text — the only way a malformed placeholder can exist, since
// menu insertion always produces a proper placeholder NODE. Paste safety net.
const RAW_BRACES = /\{\{|\}\}/;
function messageFor(code: DiagnosticCode, key?: string): string {
switch (code) {
case 'malformed':
return $localize`:@@brief.lint.malformed:Deze tekst bevat losse accolades ({{ of }}). Voeg een veld toe via het menu in plaats van het te typen.`;
case 'unknown-placeholder':
return $localize`:@@brief.lint.unknown:Onbekend veld “${key}:key:”. Dit veld hoort niet bij dit sjabloon.`;
case 'not-fillable':
return $localize`:@@brief.lint.notFillable:Veld “${key}:key:” kan niet worden ingevuld voor dit beroep.`;
case 'deprecated':
return $localize`:@@brief.lint.deprecated:Veld “${key}:key:” is verouderd en wordt niet meer aangeboden.`;
case 'unresolved-at-send':
return $localize`:@@brief.lint.unresolved:Veld “${key}:key:” wordt handmatig ingevuld en is nog leeg.`;
}
}
function diag(code: DiagnosticCode, location: DiagnosticLocation, key?: string): Diagnostic {
return { severity: severityOf(code), code, placeholderKey: key, location, message: messageFor(code, key) };
}
/**
* Lint one block against the template's placeholder set. Pure: given the same
* content + valid set + blockId it always returns the same diagnostics, in
* document order. One diagnostic per node at most (most-severe wins).
*/
export function lintPlaceholders(
content: RichTextBlock,
valid: readonly PlaceholderDef[],
blockId: string,
): Diagnostic[] {
const byKey = new Map(valid.map((p) => [p.key, p]));
const out: Diagnostic[] = [];
content.paragraphs.forEach((p, paragraphIndex) => {
p.nodes.forEach((n, nodeIndex) => {
const location: DiagnosticLocation = { blockId, paragraphIndex, nodeIndex };
if (n.type === 'text') {
if (RAW_BRACES.test(n.text)) out.push(diag('malformed', location));
return;
}
if (n.type !== 'placeholder') return; // lineBreak — nothing to check
const def = byKey.get(n.key);
if (!def) out.push(diag('unknown-placeholder', location, n.key));
else if (def.fillable === false) out.push(diag('not-fillable', location, n.key));
else if (def.deprecated) out.push(diag('deprecated', location, n.key));
else if (!def.autoResolvable) out.push(diag('unresolved-at-send', location, n.key));
// auto-resolvable & fillable & not deprecated → clean (filled by the server at send)
});
});
return out;
}