feat(WP-67): merge behandelportal into this repo as a monorepo
Restructures into apps/ssp + apps/behandelportal (two Angular projects) plus libs/shared + libs/beheer (cross-app libraries), replacing WP-61's separate sibling repo. That split had already produced real drift: a hand-vendored copy of the backend's OpenAPI doc, a shared/ui+layout tree forked and silently diverging (7 files), and beheer + the styles.scss token bridge duplicated byte-for-byte across both repos. - git mv the SSP's src/app/* into apps/ssp/; fold shared/, beheer/, environments/, the Storybook docs/*.mdx, and styles.scss into libs/shared + libs/beheer (all confirmed identical between the two repos before merging). auth stays deliberately duplicated per ADR-0002 (actor-specific, expected to diverge) - amended there. - One generated API client (libs/shared), no more vendored swagger.json. - .dependency-cruiser split into a base factory + one config per app, and Storybook into .storybook-ssp/.storybook-behandelportal - both forced by the @auth/* alias resolving to different directories per app. - SiteHeaderComponent/ShellComponent gained HEADER_NAV_ITEMS/ HEADER_ADMIN_LINKS/DEBUG_PANEL injection tokens so each app supplies its own nav/admin-links/dev-panel instead of one being hardcoded. - CLAUDE.md, ARCHITECTURE.md, dependencies.md, and ADR-0002 updated; WP-67 backlog entry documents the full decision trail. npm run ci green (lint, dep:check x2, 360 tests across ssp/ behandelportal/shared/beheer, both localized builds, backend tests, snippet + api-client drift); both dev servers, both Storybook instances, and docker compose verified working. The old sibling repo (/home/eho/repos/behandelportal) is left untouched, not deleted. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,340 @@
|
||||
import { TestBed } from '@angular/core/testing';
|
||||
import { describe, it, expect, vi, afterEach } from 'vitest';
|
||||
import { Result } from '@shared/kernel/fp';
|
||||
import { Brief, BriefDecisions, CaseContext, LetterBlock } from '@brief/domain/brief';
|
||||
import { OrgTemplate } from '@brief/domain/org-template';
|
||||
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 { BriefStore } from './brief.store';
|
||||
|
||||
const decisions: BriefDecisions = {
|
||||
canEdit: true,
|
||||
canApprove: true,
|
||||
canReject: true,
|
||||
canSend: true,
|
||||
canRevealBigNummer: true,
|
||||
};
|
||||
|
||||
const brief: Brief = {
|
||||
briefId: 'b1',
|
||||
beroep: 'arts',
|
||||
templateId: 't1',
|
||||
placeholders: [],
|
||||
sections: [],
|
||||
status: { tag: 'draft' },
|
||||
drafterId: 'u1',
|
||||
};
|
||||
|
||||
const orgTemplate: OrgTemplate = {
|
||||
subOrgId: 'cibg-registers',
|
||||
orgName: 'CIBG — Registers',
|
||||
returnAddress: 'Postbus 00000\n2500 AA Den Haag',
|
||||
footerContact: 'info@voorbeeld.example',
|
||||
footerLegal: 'KvK 00000000',
|
||||
signatureName: 'A. de Vries',
|
||||
signatureRole: 'Hoofd Registratie',
|
||||
signatureClosing: 'Met vriendelijke groet,',
|
||||
margins: { topMm: 25, rightMm: 25, bottomMm: 25, leftMm: 25 },
|
||||
version: 1,
|
||||
};
|
||||
|
||||
const caseContext: CaseContext = {
|
||||
zorgverlenerNaam: 'Dr. A. (Anna) de Vries',
|
||||
bigNummer: '19012345601',
|
||||
beroep: 'arts',
|
||||
aanvraagReferentie: 'HER-2026-000842',
|
||||
};
|
||||
|
||||
const view: BriefView = { brief, availablePassages: [], decisions, orgTemplate, caseContext };
|
||||
|
||||
function setup(adapter: Partial<BriefAdapter>): BriefStore {
|
||||
TestBed.configureTestingModule({ providers: [{ provide: BriefAdapter, useValue: adapter }] });
|
||||
return TestBed.inject(BriefStore);
|
||||
}
|
||||
|
||||
describe('BriefStore action state (Idle | Busy | Failed)', () => {
|
||||
it('is Busy synchronously once a transition starts', async () => {
|
||||
const approved: BriefView = {
|
||||
...view,
|
||||
brief: { ...brief, status: { tag: 'approved', approvedBy: 'u2', approvedAt: 't' } },
|
||||
};
|
||||
const store = setup({
|
||||
load: (): Promise<Result<string, BriefView>> => Promise.resolve({ ok: true, value: view }),
|
||||
save: (): Promise<Result<string, BriefView>> => Promise.resolve({ ok: true, value: view }),
|
||||
approve: (): Promise<Result<string, BriefView>> =>
|
||||
Promise.resolve({ ok: true, value: approved }),
|
||||
});
|
||||
await store.load();
|
||||
|
||||
const pending = store.approve();
|
||||
expect(store.busy()).toBe(true); // set synchronously, before any await resolves
|
||||
|
||||
await pending; // settle before the test ends
|
||||
});
|
||||
|
||||
it('settles to Idle on a successful transition', async () => {
|
||||
const approved: BriefView = {
|
||||
...view,
|
||||
brief: { ...brief, status: { tag: 'approved', approvedBy: 'u2', approvedAt: 't' } },
|
||||
};
|
||||
const store = setup({
|
||||
load: (): Promise<Result<string, BriefView>> => Promise.resolve({ ok: true, value: view }),
|
||||
save: (): Promise<Result<string, BriefView>> => Promise.resolve({ ok: true, value: view }),
|
||||
approve: (): Promise<Result<string, BriefView>> =>
|
||||
Promise.resolve({ ok: true, value: approved }),
|
||||
});
|
||||
await store.load();
|
||||
|
||||
await store.approve();
|
||||
expect(store.busy()).toBe(false);
|
||||
expect(store.lastError()).toBeNull();
|
||||
});
|
||||
|
||||
it('goes Busy then Failed on a failing transition, surfacing the error', async () => {
|
||||
const store = setup({
|
||||
load: (): Promise<Result<string, BriefView>> => Promise.resolve({ ok: true, value: view }),
|
||||
save: (): Promise<Result<string, BriefView>> => Promise.resolve({ ok: true, value: view }),
|
||||
approve: (): Promise<Result<string, BriefView>> =>
|
||||
Promise.resolve({ ok: false, error: 'niet toegestaan' }),
|
||||
});
|
||||
await store.load();
|
||||
|
||||
await store.approve();
|
||||
expect(store.busy()).toBe(false);
|
||||
expect(store.lastError()).toBe('niet toegestaan');
|
||||
});
|
||||
|
||||
it('a subsequent successful transition clears a prior Failed state', async () => {
|
||||
let approveResult: Result<string, BriefView> = { ok: false, error: 'eerste poging mislukt' };
|
||||
const store = setup({
|
||||
load: (): Promise<Result<string, BriefView>> => Promise.resolve({ ok: true, value: view }),
|
||||
save: (): Promise<Result<string, BriefView>> => Promise.resolve({ ok: true, value: view }),
|
||||
approve: (): Promise<Result<string, BriefView>> => Promise.resolve(approveResult),
|
||||
});
|
||||
await store.load();
|
||||
|
||||
await store.approve();
|
||||
expect(store.lastError()).toBe('eerste poging mislukt');
|
||||
|
||||
approveResult = {
|
||||
ok: true,
|
||||
value: {
|
||||
...view,
|
||||
brief: { ...brief, status: { tag: 'approved', approvedBy: 'u2', approvedAt: 't' } },
|
||||
},
|
||||
};
|
||||
await store.approve();
|
||||
expect(store.busy()).toBe(false);
|
||||
expect(store.lastError()).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
// --- WP-27: undo/redo history + rejection diff ---
|
||||
|
||||
function block(id: string, text: string): LetterBlock {
|
||||
return {
|
||||
type: 'freeText',
|
||||
blockId: id,
|
||||
content: { paragraphs: [{ nodes: [{ type: 'text', text }] }] },
|
||||
};
|
||||
}
|
||||
const kern = (blocks: LetterBlock[]) => ({
|
||||
sectionKey: 'kern',
|
||||
title: 'Kern',
|
||||
required: true,
|
||||
locked: false,
|
||||
blocks,
|
||||
});
|
||||
const filledBrief: Brief = { ...brief, sections: [kern([block('local-1', 'x')])] };
|
||||
const filledView: BriefView = { ...view, brief: filledBrief };
|
||||
|
||||
function loadedBrief(store: BriefStore): Brief {
|
||||
const s = store.model();
|
||||
if (s.tag !== 'loaded') throw new Error('not loaded');
|
||||
return s.brief;
|
||||
}
|
||||
|
||||
async function loadedStore(over: Partial<BriefAdapter> = {}): Promise<BriefStore> {
|
||||
const ok = (v: BriefView): Promise<Result<string, BriefView>> =>
|
||||
Promise.resolve({ ok: true, value: v });
|
||||
const store = setup({ load: () => ok(filledView), save: () => ok(filledView), ...over });
|
||||
await store.load();
|
||||
return store;
|
||||
}
|
||||
|
||||
describe('BriefStore undo/redo history', () => {
|
||||
it('records an edit, undoes and redoes it; buttons mirror; a no-op edit is not recorded', async () => {
|
||||
const store = await loadedStore();
|
||||
expect(store.canUndo()).toBe(false);
|
||||
|
||||
store.edit({ tag: 'BlockRemoved', blockId: 'local-1' });
|
||||
expect(loadedBrief(store).sections[0].blocks.length).toBe(0);
|
||||
expect(store.canUndo()).toBe(true);
|
||||
|
||||
store.undo();
|
||||
expect(loadedBrief(store).sections[0].blocks.length).toBe(1);
|
||||
expect(store.canRedo()).toBe(true);
|
||||
|
||||
store.redo();
|
||||
expect(loadedBrief(store).sections[0].blocks.length).toBe(0);
|
||||
|
||||
// A no-op edit (unknown block) changes nothing → leaves no dead history step.
|
||||
store.undo(); // back to 1 block, redo available
|
||||
store.edit({ tag: 'BlockRemoved', blockId: 'does-not-exist' });
|
||||
expect(store.canRedo()).toBe(true); // future NOT cleared by a no-op
|
||||
});
|
||||
|
||||
it('a new edit clears the redo future', async () => {
|
||||
const store = await loadedStore();
|
||||
store.edit({ tag: 'FreeTextBlockAdded', sectionKey: 'kern' });
|
||||
store.undo();
|
||||
expect(store.canRedo()).toBe(true);
|
||||
store.edit({ tag: 'FreeTextBlockAdded', sectionKey: 'kern' });
|
||||
expect(store.canRedo()).toBe(false);
|
||||
});
|
||||
|
||||
it('caps history at 50 snapshots', async () => {
|
||||
const store = await loadedStore();
|
||||
for (let i = 0; i < 55; i++) store.edit({ tag: 'FreeTextBlockAdded', sectionKey: 'kern' });
|
||||
let undos = 0;
|
||||
while (store.canUndo()) {
|
||||
store.undo();
|
||||
undos++;
|
||||
}
|
||||
expect(undos).toBe(50);
|
||||
});
|
||||
});
|
||||
|
||||
describe('BriefStore rejection diff', () => {
|
||||
it('captures the rejected letter and diffs a subsequent edit against it', async () => {
|
||||
const submitted: Brief = {
|
||||
...filledBrief,
|
||||
status: { tag: 'submitted', submittedBy: 'u', submittedAt: 't' },
|
||||
};
|
||||
const rejected: Brief = {
|
||||
...filledBrief,
|
||||
status: { tag: 'rejected', rejectedBy: 'u2', rejectedAt: 't', comments: 'nee' },
|
||||
};
|
||||
const ok = (v: BriefView): Promise<Result<string, BriefView>> =>
|
||||
Promise.resolve({ ok: true, value: v });
|
||||
const store = setup({
|
||||
load: () => ok({ ...filledView, brief: submitted }),
|
||||
save: () => ok(filledView),
|
||||
reject: () => ok({ ...filledView, brief: rejected }),
|
||||
});
|
||||
await store.load();
|
||||
await store.reject('nee');
|
||||
expect(store.hasRejectionDiff()).toBe(false); // nothing changed yet
|
||||
|
||||
store.edit({
|
||||
tag: 'BlockContentEdited',
|
||||
blockId: 'local-1',
|
||||
content: { paragraphs: [{ nodes: [{ type: 'text', text: 'CHANGED' }] }] },
|
||||
});
|
||||
expect(store.blockDiffs().get('local-1')).toBe('changed');
|
||||
expect(store.removedSinceReject()).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('BriefStore.previewLetter', () => {
|
||||
// vi.spyOn reuses an existing spy (and its call history) if one is already on
|
||||
// the property — window.open/URL.createObjectURL must be restored between tests.
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
it('opens the composed letter in a new tab on success', async () => {
|
||||
const store = setup({
|
||||
load: (): Promise<Result<string, BriefView>> => Promise.resolve({ ok: true, value: view }),
|
||||
});
|
||||
await store.load();
|
||||
const blob = new Blob(['<html></html>'], { type: 'text/html' });
|
||||
vi.spyOn(URL, 'createObjectURL').mockReturnValue('blob:mock');
|
||||
const open = vi.spyOn(window, 'open').mockImplementation(() => null);
|
||||
vi.spyOn(TestBed.inject(LetterPreviewAdapter), 'preview').mockResolvedValue({
|
||||
ok: true,
|
||||
value: blob,
|
||||
});
|
||||
|
||||
await store.previewLetter();
|
||||
expect(open).toHaveBeenCalledWith('blob:mock', '_blank');
|
||||
expect(store.lastError()).toBeNull();
|
||||
});
|
||||
|
||||
it('surfaces the error without opening a tab on failure', async () => {
|
||||
const store = setup({
|
||||
load: (): Promise<Result<string, BriefView>> => Promise.resolve({ ok: true, value: view }),
|
||||
});
|
||||
await store.load();
|
||||
const open = vi.spyOn(window, 'open').mockImplementation(() => null);
|
||||
vi.spyOn(TestBed.inject(LetterPreviewAdapter), 'preview').mockResolvedValue({
|
||||
ok: false,
|
||||
error: 'De voorvertoning kon niet worden geopend.',
|
||||
});
|
||||
|
||||
await store.previewLetter();
|
||||
expect(open).not.toHaveBeenCalled();
|
||||
expect(store.lastError()).toBe('De voorvertoning kon niet worden geopend.');
|
||||
});
|
||||
});
|
||||
|
||||
describe('BriefStore.revealBigNummer (PRD-0002 §5c)', () => {
|
||||
afterEach(() => vi.restoreAllMocks());
|
||||
|
||||
// Loaded with a MASKED BIG-nummer, as the server ships it by default.
|
||||
const maskedView: BriefView = {
|
||||
...view,
|
||||
caseContext: { ...caseContext, bigNummer: '********601' },
|
||||
};
|
||||
|
||||
it('swaps the masked value for the revealed one on success', async () => {
|
||||
const store = setup({ load: () => Promise.resolve({ ok: true, value: maskedView }) });
|
||||
await store.load();
|
||||
expect(store.caseContext()?.bigNummer).toBe('********601');
|
||||
vi.spyOn(TestBed.inject(RevealBigNummerAdapter), 'reveal').mockResolvedValue({
|
||||
ok: true,
|
||||
value: '19012345601',
|
||||
});
|
||||
|
||||
await store.revealBigNummer();
|
||||
expect(store.caseContext()?.bigNummer).toBe('19012345601');
|
||||
expect(store.lastError()).toBeNull();
|
||||
});
|
||||
|
||||
it('keeps the value masked and surfaces the error on failure', async () => {
|
||||
const store = setup({ load: () => Promise.resolve({ ok: true, value: maskedView }) });
|
||||
await store.load();
|
||||
vi.spyOn(TestBed.inject(RevealBigNummerAdapter), 'reveal').mockResolvedValue({
|
||||
ok: false,
|
||||
error: 'geweigerd',
|
||||
});
|
||||
|
||||
await store.revealBigNummer();
|
||||
expect(store.caseContext()?.bigNummer).toBe('********601'); // unchanged
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,294 @@
|
||||
import { Injectable, computed, inject, signal } from '@angular/core';
|
||||
import { Result } from '@shared/kernel/fp';
|
||||
import { createStore } from '@shared/application/store';
|
||||
import { ActionState, SaveState } from '@shared/application/action-state';
|
||||
import { createHistory } from '@shared/application/history';
|
||||
import { createDebouncedSave } from '@shared/application/debounced-save';
|
||||
import { machineRemoteData } from '@shared/application/machine-remote-data';
|
||||
import {
|
||||
Brief,
|
||||
CaseContext,
|
||||
allDiagnostics,
|
||||
canSubmit,
|
||||
hasBlockingErrors,
|
||||
unresolvedPlaceholders,
|
||||
} from '@brief/domain/brief';
|
||||
import { BriefMsg, BriefState, initial, reduce } from '@brief/domain/brief.machine';
|
||||
import { BlockDiffKind, changedBlocks, diffBlocks } from '@brief/domain/brief-diff';
|
||||
import { OrgTemplate } from '@brief/domain/org-template';
|
||||
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';
|
||||
|
||||
/**
|
||||
* Root singleton for the letter: the Elm store (Model + dispatch), the derived
|
||||
* read-model, and the commands (effects) that call the adapter and dispatch the
|
||||
* outcome. Mirrors `BigProfileStore`. All of `canEdit`/`canApprove`/`canReject`/
|
||||
* `canSend`, `diagnostics`, `unresolved`, `canSubmit` are DERIVED here — never
|
||||
* stored. The permission flags come from the server's decision DTO (PRD-0002 phase
|
||||
* P1) via `BriefState.loaded.decisions` — this store never computes them itself.
|
||||
*/
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class BriefStore implements PendingSave {
|
||||
private adapter = inject(BriefAdapter);
|
||||
private previewAdapter = inject(LetterPreviewAdapter);
|
||||
private revealAdapter = inject(RevealBigNummerAdapter);
|
||||
private store = createStore<BriefState, BriefMsg>(initial, reduce);
|
||||
|
||||
readonly model = this.store.model;
|
||||
|
||||
private actionState = signal<ActionState>({ tag: 'Idle' });
|
||||
readonly busy = computed(() => this.actionState().tag === 'Busy');
|
||||
readonly lastError = computed(() => {
|
||||
const s = this.actionState();
|
||||
return s.tag === 'Failed' ? s.error : null;
|
||||
});
|
||||
|
||||
/** Surfaced autosave state for the indicator + aria-live region. */
|
||||
readonly saveState = signal<SaveState>({ tag: 'Idle' });
|
||||
|
||||
/** Undo/redo is SHELL state, not machine state (WP-27): a `createHistory` stack of
|
||||
`Brief` snapshots (WP-31 extracted the mechanics). Only CONTENT edits are recorded
|
||||
(they flow through `edit()`); status transitions never enter history, or undo would
|
||||
replay workflow state. Restore re-dispatches the existing `Seed` Msg — zero machine
|
||||
changes. */
|
||||
private history = createHistory<Brief>(50);
|
||||
readonly canUndo = this.history.canUndo;
|
||||
readonly canRedo = this.history.canRedo;
|
||||
|
||||
/** The letter as it stood when it was REJECTED, captured shell-side (WP-27). The
|
||||
approver diffs it against the resubmitted letter. POC limit: in-memory only, so a
|
||||
full page reload loses it — a real system would persist the rejected revision. */
|
||||
private rejectionSnapshot = signal<Brief | null>(null);
|
||||
/** Changed/added/removed blocks since rejection — a pure fold over two snapshots. */
|
||||
readonly blockDiffs = computed<ReadonlyMap<string, BlockDiffKind>>(() => {
|
||||
const before = this.rejectionSnapshot();
|
||||
const after = this.brief();
|
||||
return before && after ? changedBlocks(diffBlocks(before, after)) : new Map();
|
||||
});
|
||||
/** Count of blocks removed since rejection — badged as a summary, since a removed
|
||||
block no longer renders inline. */
|
||||
readonly removedSinceReject = computed(
|
||||
() => [...this.blockDiffs().values()].filter((k) => k === 'removed').length,
|
||||
);
|
||||
readonly hasRejectionDiff = computed(() => this.blockDiffs().size > 0);
|
||||
|
||||
/** The org template the letter renders with (WP-24). Server-owned appearance data,
|
||||
not letter state — held beside the machine, never inside it (`brief.machine.ts`
|
||||
stays untouched by design). Set from every server view that carries it. */
|
||||
readonly orgTemplate = signal<OrgTemplate | null>(null);
|
||||
|
||||
/** The case (zorgverlener + aanvraag) this letter concerns — server-joined context for
|
||||
the behandel scherm header, not letter state. Set from every server view. */
|
||||
readonly caseContext = signal<CaseContext | null>(null);
|
||||
|
||||
/** The org logo's content URL for the letterhead, or null when the template has none. */
|
||||
readonly logoUrl = computed<string | null>(() => {
|
||||
const id = this.orgTemplate()?.logoDocumentId;
|
||||
return id ? uploadContentUrl(id) : null;
|
||||
});
|
||||
|
||||
/** The load lifecycle as `RemoteData`, for `<app-async>` — the machine keeps
|
||||
owning the letter's own domain lifecycle (draft/submitted/approved/…); this is
|
||||
purely a projection of its loading/failed tags onto the shared async seam. */
|
||||
readonly remoteData = computed(() => machineRemoteData(this.model()));
|
||||
|
||||
private brief = computed<Brief | null>(() => {
|
||||
const s = this.model();
|
||||
return s.tag === 'loaded' ? s.brief : null;
|
||||
});
|
||||
|
||||
readonly canEdit = computed(() => this.decisions()?.canEdit ?? false);
|
||||
readonly canApprove = computed(() => this.decisions()?.canApprove ?? false);
|
||||
readonly canReject = computed(() => this.decisions()?.canReject ?? false);
|
||||
readonly canSend = computed(() => this.decisions()?.canSend ?? false);
|
||||
/** Field-level PII reveal (PRD-0002 §5c), deny-by-default like the action gates. */
|
||||
readonly canRevealBigNummer = computed(() => this.decisions()?.canRevealBigNummer ?? false);
|
||||
|
||||
private decisions = computed(() => {
|
||||
const s = this.model();
|
||||
return s.tag === 'loaded' ? s.decisions : null;
|
||||
});
|
||||
readonly diagnostics = computed(() => (this.brief() ? allDiagnostics(this.brief()!) : []));
|
||||
readonly unresolved = computed(() => (this.brief() ? unresolvedPlaceholders(this.brief()!) : []));
|
||||
/** Submit is allowed only when required sections are filled AND no blocking errors. */
|
||||
readonly canSubmit = computed(() => {
|
||||
const b = this.brief();
|
||||
return !!b && canSubmit(b) && !hasBlockingErrors(this.diagnostics());
|
||||
});
|
||||
|
||||
async load() {
|
||||
const r = await this.adapter.load();
|
||||
if (r.ok) {
|
||||
this.orgTemplate.set(r.value.orgTemplate);
|
||||
this.caseContext.set(r.value.caseContext);
|
||||
this.history.clear();
|
||||
this.store.dispatch({ tag: 'BriefLoaded', ...r.value });
|
||||
} else {
|
||||
this.store.dispatch({ tag: 'BriefLoadFailed', reason: r.error });
|
||||
}
|
||||
}
|
||||
|
||||
/** An edit: apply it optimistically in the pure reducer, then debounce-save. Records
|
||||
an undo step only when the reducer actually changed the brief (a no-op edit — e.g.
|
||||
a locked section — returns the same value and leaves no dead history step). */
|
||||
edit(msg: BriefMsg) {
|
||||
const before = this.brief();
|
||||
this.store.dispatch(msg);
|
||||
const after = this.brief();
|
||||
// Record only a real change: a no-op edit (e.g. a locked section) returns the same
|
||||
// value and leaves no dead history step.
|
||||
if (before && after && after !== before) this.history.record(before);
|
||||
this.debouncedSave.schedule();
|
||||
}
|
||||
|
||||
/** Undo/redo: restore a snapshot via the existing `Seed` Msg, then autosave. */
|
||||
undo() {
|
||||
this.restore((current) => this.history.undo(current));
|
||||
}
|
||||
redo() {
|
||||
this.restore((current) => this.history.redo(current));
|
||||
}
|
||||
private restore(step: (current: Brief) => Brief | undefined) {
|
||||
const s = this.model();
|
||||
if (s.tag !== 'loaded') return;
|
||||
const target = step(s.brief);
|
||||
if (target === undefined) return;
|
||||
this.store.dispatch({ tag: 'Seed', state: { ...s, brief: target } });
|
||||
this.debouncedSave.schedule();
|
||||
}
|
||||
|
||||
constructor() {
|
||||
// Register so the CanDeactivate guard / beforeunload handler can flush a pending
|
||||
// debounced edit before navigation or unload (see pending-saves.ts).
|
||||
registerPendingSave(this);
|
||||
}
|
||||
|
||||
// 600ms debounced autosave (the server is the store of record). Timer mechanics live in
|
||||
// the shared helper; `flushSave` below is the store-specific write + save-state (WP-31).
|
||||
private debouncedSave = createDebouncedSave({
|
||||
canSave: () => this.canEdit(),
|
||||
flush: () => this.flushSave(),
|
||||
});
|
||||
/** PendingSave: delegate to the debounce helper so the guard/unload can flush. */
|
||||
hasPendingSave = () => this.debouncedSave.hasPendingSave();
|
||||
flushPending = () => this.debouncedSave.flushPending();
|
||||
private async flushSave() {
|
||||
const b = this.brief();
|
||||
if (!b) return;
|
||||
this.saveState.set({ tag: 'Saving' });
|
||||
const r = await this.adapter.save(b.sections);
|
||||
if (r.ok) {
|
||||
this.saveState.set({ tag: 'Saved' });
|
||||
} else {
|
||||
this.actionState.set({ tag: 'Failed', error: r.error });
|
||||
this.saveState.set({ tag: 'Error' });
|
||||
}
|
||||
}
|
||||
|
||||
/** Retry a failed autosave — reuses the existing flush path, no new state (WP-27). */
|
||||
retrySave() {
|
||||
void this.flushSave();
|
||||
}
|
||||
|
||||
/** Demo "start over": recreate the brief server-side and load the fresh view. */
|
||||
async resetDemo() {
|
||||
this.actionState.set({ tag: 'Busy' });
|
||||
this.debouncedSave.cancel();
|
||||
const r = await this.adapter.reset();
|
||||
this.saveState.set({ tag: 'Idle' });
|
||||
if (r.ok) {
|
||||
this.actionState.set({ tag: 'Idle' });
|
||||
this.orgTemplate.set(r.value.orgTemplate);
|
||||
this.caseContext.set(r.value.caseContext);
|
||||
this.history.clear();
|
||||
this.rejectionSnapshot.set(null);
|
||||
this.store.dispatch({ tag: 'BriefLoaded', ...r.value });
|
||||
} else {
|
||||
this.actionState.set({ tag: 'Failed', error: r.error });
|
||||
}
|
||||
}
|
||||
|
||||
submit = () => this.transition(() => this.adapter.submit());
|
||||
approve = () => this.transition(() => this.adapter.approve());
|
||||
reject = (comments: string) => this.transition(() => this.adapter.reject(comments));
|
||||
send = () => this.transition(() => this.adapter.send());
|
||||
|
||||
/** Explicit action, never a live re-render (PRD §8): opens the server-composed
|
||||
letter in a new tab. ponytail: the blob URL is never revoked — it's cheap and
|
||||
the tab outlives this call; not worth a teardown hook for a POC. */
|
||||
async previewLetter() {
|
||||
this.actionState.set({ tag: 'Busy' });
|
||||
const r = await this.previewAdapter.preview();
|
||||
if (!r.ok) {
|
||||
this.actionState.set({ tag: 'Failed', error: r.error });
|
||||
return;
|
||||
}
|
||||
this.actionState.set({ tag: 'Idle' });
|
||||
window.open(URL.createObjectURL(r.value), '_blank');
|
||||
}
|
||||
|
||||
/** Reveal the masked case BIG-nummer (PRD-0002 §5c). Server re-checks the capability
|
||||
+ step-up and audits the attempt; on success we swap the masked value in the
|
||||
already-loaded caseContext (a field update, not a reload). The step-up gesture
|
||||
itself is the UI's concern — this command just runs the audited server call. */
|
||||
async revealBigNummer() {
|
||||
const r = await this.revealAdapter.reveal();
|
||||
if (!r.ok) {
|
||||
this.actionState.set({ tag: 'Failed', error: r.error });
|
||||
return;
|
||||
}
|
||||
this.caseContext.update((c) => (c ? { ...c, bigNummer: r.value } : c));
|
||||
}
|
||||
|
||||
// A transition: flush any pending save, call the server (authoritative), then mirror
|
||||
// the returned status through the pure reducer's guarded transition.
|
||||
private async transition(action: () => Promise<Result<string, BriefView>>) {
|
||||
this.actionState.set({ tag: 'Busy' });
|
||||
this.debouncedSave.cancel();
|
||||
await this.flushSave();
|
||||
const r = await action();
|
||||
if (!r.ok) {
|
||||
this.actionState.set({ tag: 'Failed', error: r.error });
|
||||
return;
|
||||
}
|
||||
this.actionState.set({ tag: 'Idle' });
|
||||
this.applyServerStatus(r.value);
|
||||
}
|
||||
|
||||
private applyServerStatus(view: BriefView) {
|
||||
// `send` pins the org-template version server-side — mirror whatever came back.
|
||||
this.orgTemplate.set(view.orgTemplate);
|
||||
this.caseContext.set(view.caseContext);
|
||||
const { brief, decisions } = view;
|
||||
const s = brief.status;
|
||||
switch (s.tag) {
|
||||
case 'submitted':
|
||||
this.store.dispatch({ tag: 'Submitted', by: s.submittedBy, at: s.submittedAt, decisions });
|
||||
break;
|
||||
case 'approved':
|
||||
this.store.dispatch({ tag: 'Approved', by: s.approvedBy, at: s.approvedAt, decisions });
|
||||
break;
|
||||
case 'rejected':
|
||||
// Capture the letter as-rejected for the resubmission diff (WP-27). This is the
|
||||
// "before" snapshot the approver later compares against.
|
||||
this.rejectionSnapshot.set(brief);
|
||||
this.store.dispatch({
|
||||
tag: 'Rejected',
|
||||
by: s.rejectedBy,
|
||||
at: s.rejectedAt,
|
||||
comments: s.comments,
|
||||
decisions,
|
||||
});
|
||||
break;
|
||||
case 'sent':
|
||||
this.store.dispatch({ tag: 'Sent', at: s.sentAt, decisions });
|
||||
break;
|
||||
case 'draft':
|
||||
// reopened by a save on a rejected letter — reducer already handled it locally.
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,273 @@
|
||||
import { Injectable, computed, effect, inject, signal } from '@angular/core';
|
||||
import { createStore } from '@shared/application/store';
|
||||
import { ActionState, SaveState } from '@shared/application/action-state';
|
||||
import { createDebouncedSave } from '@shared/application/debounced-save';
|
||||
import { machineRemoteData } from '@shared/application/machine-remote-data';
|
||||
import { UploadAdapter } from '@shared/upload/upload.adapter';
|
||||
import { UploadShellService } from '@shared/upload/upload-shell.service';
|
||||
import { UploadMsg, initialUpload, rejectReason } from '@shared/upload/upload.machine';
|
||||
import {
|
||||
MARGIN_MAX_MM,
|
||||
MARGIN_MIN_MM,
|
||||
OrgTemplate,
|
||||
SubOrgSummary,
|
||||
} from '@brief/domain/org-template';
|
||||
import {
|
||||
OrgTemplateMsg,
|
||||
OrgTemplateState,
|
||||
initial,
|
||||
reduce,
|
||||
} from '@brief/domain/org-template.machine';
|
||||
import { OrgTemplateAdapter } from '@brief/infrastructure/org-template.adapter';
|
||||
import { PendingSave, registerPendingSave } from '@shared/application/pending-saves';
|
||||
|
||||
type LoadedState = Extract<OrgTemplateState, { tag: 'loaded' }>;
|
||||
|
||||
const LOGO_CATEGORY = 'org-logo';
|
||||
const NO_SUBORGS = $localize`:@@orgTemplate.noSubOrgs:Er zijn geen organisatiesjablonen om te beheren.`;
|
||||
|
||||
/**
|
||||
* Root singleton for the admin org-template editor (WP-26). The Elm machine owns the
|
||||
* editable draft; commands here do the debounced save, publish (impact-confirm),
|
||||
* rollback and proefbrief, then dispatch the outcome — the reducer stays pure. The
|
||||
* logo upload reuses the shared upload transport; its completion mutates the draft
|
||||
* (in the reducer) and triggers a save (here). Mirrors `BriefStore`.
|
||||
*/
|
||||
@Injectable({ providedIn: 'root' })
|
||||
export class OrgTemplateStore implements PendingSave {
|
||||
private adapter = inject(OrgTemplateAdapter);
|
||||
private uploadAdapter = inject(UploadAdapter);
|
||||
private shell = inject(UploadShellService);
|
||||
private store = createStore<OrgTemplateState, OrgTemplateMsg>(initial, reduce);
|
||||
|
||||
readonly model = this.store.model;
|
||||
|
||||
readonly subOrgs = signal<readonly SubOrgSummary[]>([]);
|
||||
readonly selectedSubOrgId = signal<string | null>(null);
|
||||
|
||||
private actionState = signal<ActionState>({ tag: 'Idle' });
|
||||
readonly busy = computed(() => this.actionState().tag === 'Busy');
|
||||
readonly lastError = computed(() => {
|
||||
const s = this.actionState();
|
||||
return s.tag === 'Failed' ? s.error : null;
|
||||
});
|
||||
readonly saveState = signal<SaveState>({ tag: 'Idle' });
|
||||
|
||||
/** The publish impact-confirm gate (PRD §7h: show N affected letters before POST). */
|
||||
readonly pendingPublish = signal(false);
|
||||
|
||||
readonly remoteData = computed(() => machineRemoteData(this.model()));
|
||||
|
||||
private loaded = computed<LoadedState | null>(() => {
|
||||
const s = this.model();
|
||||
return s.tag === 'loaded' ? s : null;
|
||||
});
|
||||
readonly draft = computed<OrgTemplate | null>(() => this.loaded()?.draft ?? null);
|
||||
readonly uploadState = computed(() => this.loaded()?.upload ?? initialUpload);
|
||||
readonly history = computed(() => this.loaded()?.history ?? []);
|
||||
readonly publishedVersion = computed(() => this.loaded()?.publishedVersion ?? 0);
|
||||
readonly unsentBriefs = computed(() => this.loaded()?.unsentBriefs ?? 0);
|
||||
readonly logoUrl = computed<string | null>(() => {
|
||||
const id = this.draft()?.logoDocumentId;
|
||||
return id ? this.uploadAdapter.contentUrl(id) : null;
|
||||
});
|
||||
|
||||
/** Client-side mirror of the server rules (`OrgTemplateRules`) for instant feedback;
|
||||
the server re-validates and stays the authority — publish is gated on this. */
|
||||
readonly draftValid = computed(() => {
|
||||
const d = this.draft();
|
||||
if (!d) return false;
|
||||
const marginsOk = [
|
||||
d.margins.topMm,
|
||||
d.margins.rightMm,
|
||||
d.margins.bottomMm,
|
||||
d.margins.leftMm,
|
||||
].every((v) => v >= MARGIN_MIN_MM && v <= MARGIN_MAX_MM);
|
||||
return d.orgName.trim().length > 0 && d.signatureName.trim().length > 0 && marginsOk;
|
||||
});
|
||||
|
||||
// Live File blobs keyed by localId — needed to retry a failed upload (a reducer can't hold these).
|
||||
private files = new Map<string, File>();
|
||||
private categoriesRes = this.uploadAdapter.categoriesResource('org-template');
|
||||
|
||||
constructor() {
|
||||
// Feed the logo category into the machine's upload sub-state once loaded. Tracks
|
||||
// `model()` so it re-fires after a sub-org switch reseeds an empty upload state;
|
||||
// the length guard makes it idempotent (no dispatch loop).
|
||||
effect(() => {
|
||||
const s = this.model();
|
||||
if (s.tag !== 'loaded' || s.upload.categories.length > 0) return;
|
||||
const status = this.categoriesRes.status();
|
||||
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() {
|
||||
this.store.dispatch({ tag: 'Loading' });
|
||||
const list = await this.adapter.list();
|
||||
if (!list.ok) {
|
||||
this.store.dispatch({ tag: 'LoadFailed', reason: list.error });
|
||||
return;
|
||||
}
|
||||
this.subOrgs.set(list.value);
|
||||
const first = list.value[0];
|
||||
if (!first) {
|
||||
this.store.dispatch({ tag: 'LoadFailed', reason: NO_SUBORGS });
|
||||
return;
|
||||
}
|
||||
await this.selectSubOrg(first.subOrgId);
|
||||
}
|
||||
|
||||
async selectSubOrg(subOrgId: string) {
|
||||
this.selectedSubOrgId.set(subOrgId);
|
||||
this.saveState.set({ tag: 'Idle' });
|
||||
this.debouncedSave.cancel();
|
||||
this.store.dispatch({ tag: 'Loading' });
|
||||
const r = await this.adapter.load(subOrgId);
|
||||
if (r.ok) this.store.dispatch({ tag: 'DraftLoaded', view: r.value });
|
||||
else this.store.dispatch({ tag: 'LoadFailed', reason: r.error });
|
||||
}
|
||||
|
||||
/** An in-place canvas or margin edit: apply optimistically, then debounce-save. */
|
||||
edit(msg: OrgTemplateMsg) {
|
||||
this.store.dispatch(msg);
|
||||
this.debouncedSave.schedule();
|
||||
}
|
||||
|
||||
// 600ms debounced autosave (same idiom as BriefStore, WP-31). Timer mechanics live in the
|
||||
// shared helper; `flushSave` below is the store-specific write + save-state.
|
||||
private debouncedSave = createDebouncedSave({
|
||||
canSave: () => this.loaded() !== null,
|
||||
flush: () => this.flushSave(),
|
||||
});
|
||||
/** PendingSave: delegate to the debounce helper so the guard/unload can flush. */
|
||||
hasPendingSave = () => this.debouncedSave.hasPendingSave();
|
||||
flushPending = () => this.debouncedSave.flushPending();
|
||||
private async flushSave() {
|
||||
const s = this.loaded();
|
||||
if (!s || !s.dirty) return;
|
||||
const { subOrgId, draft } = s;
|
||||
this.saveState.set({ tag: 'Saving' });
|
||||
const r = await this.adapter.save(subOrgId, draft);
|
||||
if (r.ok) {
|
||||
this.saveState.set({ tag: 'Saved' });
|
||||
this.store.dispatch({ tag: 'DraftSaved', savedDraft: draft });
|
||||
} else {
|
||||
this.saveState.set({ tag: 'Error' });
|
||||
this.actionState.set({ tag: 'Failed', error: r.error });
|
||||
}
|
||||
}
|
||||
|
||||
// --- publish (impact-confirm) / rollback / proefbrief ---
|
||||
|
||||
requestPublish() {
|
||||
this.pendingPublish.set(true);
|
||||
}
|
||||
cancelPublish() {
|
||||
this.pendingPublish.set(false);
|
||||
}
|
||||
async confirmPublish() {
|
||||
const s = this.loaded();
|
||||
if (!s) return;
|
||||
this.pendingPublish.set(false);
|
||||
this.actionState.set({ tag: 'Busy' });
|
||||
this.debouncedSave.cancel();
|
||||
await this.flushSave(); // publish the saved draft — flush any pending edit first
|
||||
const r = await this.adapter.publish(s.subOrgId);
|
||||
if (!r.ok) {
|
||||
this.actionState.set({ tag: 'Failed', error: r.error });
|
||||
return;
|
||||
}
|
||||
this.actionState.set({ tag: 'Idle' });
|
||||
await this.selectSubOrg(s.subOrgId); // reload: new version, history, unsentBriefs = 0
|
||||
}
|
||||
|
||||
async rollback(version: number) {
|
||||
const s = this.loaded();
|
||||
if (!s) return;
|
||||
this.actionState.set({ tag: 'Busy' });
|
||||
this.debouncedSave.cancel();
|
||||
const r = await this.adapter.rollback(s.subOrgId, version);
|
||||
if (!r.ok) {
|
||||
this.actionState.set({ tag: 'Failed', error: r.error });
|
||||
return;
|
||||
}
|
||||
this.actionState.set({ tag: 'Idle' });
|
||||
this.store.dispatch({ tag: 'DraftLoaded', view: r.value }); // old version copied into draft
|
||||
}
|
||||
|
||||
async proefbrief() {
|
||||
const s = this.loaded();
|
||||
if (!s) return;
|
||||
this.actionState.set({ tag: 'Busy' });
|
||||
this.debouncedSave.cancel();
|
||||
await this.flushSave(); // the proefbrief renders the server's draft
|
||||
const r = await this.adapter.proefbrief(s.subOrgId);
|
||||
if (!r.ok) {
|
||||
this.actionState.set({ tag: 'Failed', error: r.error });
|
||||
return;
|
||||
}
|
||||
this.actionState.set({ tag: 'Idle' });
|
||||
window.open(URL.createObjectURL(r.value), '_blank');
|
||||
}
|
||||
|
||||
// --- logo upload (reuses the shared upload transport; single `org-logo` file) ---
|
||||
|
||||
onLogoSelected(files: File[]) {
|
||||
const s = this.loaded();
|
||||
const cat = s?.upload.categories.find((c) => c.categoryId === LOGO_CATEGORY);
|
||||
const file = files[0];
|
||||
if (!s || !cat || !file) return;
|
||||
const reason = rejectReason(cat, { type: file.type, sizeMb: file.size / 1e6 });
|
||||
if (reason) {
|
||||
this.dispatchUpload({ type: 'FileRejected', categoryId: cat.categoryId, reason });
|
||||
return;
|
||||
}
|
||||
const localId = crypto.randomUUID();
|
||||
this.files.set(localId, file);
|
||||
this.dispatchUpload({
|
||||
type: 'FileSelected',
|
||||
categoryId: cat.categoryId,
|
||||
localId,
|
||||
fileName: file.name,
|
||||
fileSizeMb: file.size / 1e6,
|
||||
});
|
||||
this.shell.upload(
|
||||
{ localId, categoryId: cat.categoryId, wizardId: 'org-template', file },
|
||||
(m) => this.onUploadMsg(m),
|
||||
);
|
||||
}
|
||||
|
||||
onLogoRemoved(localId: string) {
|
||||
this.shell.cancel([localId]);
|
||||
this.files.delete(localId);
|
||||
this.onUploadMsg({ type: 'UploadRemoved', localId });
|
||||
}
|
||||
|
||||
onLogoRetry(localId: string) {
|
||||
const file = this.files.get(localId);
|
||||
const up = this.loaded()?.upload.uploads.find((u) => u.localId === localId);
|
||||
if (!file || !up) return;
|
||||
this.dispatchUpload({ type: 'UploadRetried', localId });
|
||||
this.shell.upload({ localId, categoryId: up.categoryId, wizardId: 'org-template', file }, (m) =>
|
||||
this.onUploadMsg(m),
|
||||
);
|
||||
}
|
||||
|
||||
private dispatchUpload(msg: UploadMsg) {
|
||||
this.store.dispatch({ tag: 'Upload', msg });
|
||||
}
|
||||
/** Upload effects arriving from the transport: a finished/removed logo edits the
|
||||
draft (in the reducer) and needs persisting. */
|
||||
private onUploadMsg(msg: UploadMsg) {
|
||||
this.dispatchUpload(msg);
|
||||
if (msg.type === 'UploadComplete' || msg.type === 'UploadRemoved')
|
||||
this.debouncedSave.schedule();
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user