Add ASP.NET Core backend hosting business rules; FE consumes via typed client
Move the authoritative business rules off the frontend into a real backend,
realising the BFF-lite + decision-DTO design (ADR-0001) that until now lived
only in static mock JSON.
Backend (backend/):
- ASP.NET Core (.NET 10) minimal API, contract-first, Swagger UI at /swagger.
- DDD Domain/ rules layer: profession derivation + applicable policy questions
(DiplomaRules), herregistratie eligibility + reason (HerregistratieRule),
scholing threshold (IntakePolicy), submit rejections + reference generation
(SubmissionRules). In-memory seeded data, ProblemDetails (RFC 7807) errors.
- 27 xUnit tests: rule units + endpoint integration incl. BRP no-address and
DUO not-found fallbacks and 422 submit paths.
Frontend (only infrastructure/ + contracts/ change, as the architecture promised):
- NSwag-generated typed client (api-client.ts), routed through Angular HttpClient
via a small fetch adapter so the ?scenario= interceptor still applies.
- GET adapters use resource({ loader: client.x }); submit commands call the client
and map ProblemDetails -> err. The hardcoded uren==0 / manual-diploma rules are
deleted (now server-side). Domain, stores, UI and format validators unchanged.
- Deleted the now-dead public/mock/*.json.
Tooling/docs:
- npm start proxies /api -> backend; npm run gen:api regenerates the client;
docker compose up runs both (bind mounts use :z for SELinux/Fedora).
- backend/README.md walkthrough: adding a policy question is a one-file backend
change, no FE change, no client regen. Updated CLAUDE.md + ARCHITECTURE.md.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
49
src/app/shared/infrastructure/api-client.provider.ts
Normal file
49
src/app/shared/infrastructure/api-client.provider.ts
Normal file
@@ -0,0 +1,49 @@
|
||||
import { Provider } from '@angular/core';
|
||||
import { HttpClient, HttpErrorResponse } from '@angular/common/http';
|
||||
import { firstValueFrom } from 'rxjs';
|
||||
import { ApiClient, ProblemDetails } from './api-client';
|
||||
|
||||
/**
|
||||
* Adapts Angular's HttpClient to the fetch-shaped interface the NSwag-generated
|
||||
* client expects, so every API call flows through HttpClient interceptors — the
|
||||
* `?scenario=` toggle (scenario.interceptor.ts) and any future auth header. The
|
||||
* generated client is the only place HTTP shapes are known; this is the only
|
||||
* place it meets Angular's HTTP stack.
|
||||
*/
|
||||
function httpClientFetch(http: HttpClient) {
|
||||
return {
|
||||
async fetch(url: RequestInfo, init?: RequestInit): Promise<Response> {
|
||||
const method = (init?.method ?? 'GET').toUpperCase();
|
||||
const headers = (init?.headers ?? {}) as Record<string, string>;
|
||||
try {
|
||||
const res = await firstValueFrom(
|
||||
http.request(method, url as string, {
|
||||
body: init?.body as string | undefined,
|
||||
headers,
|
||||
observe: 'response',
|
||||
responseType: 'text',
|
||||
}),
|
||||
);
|
||||
return new Response(res.body ?? '', { status: res.status || 200 });
|
||||
} catch (e) {
|
||||
const err = e as HttpErrorResponse;
|
||||
const body = typeof err.error === 'string' ? err.error : JSON.stringify(err.error ?? {});
|
||||
// ponytail: clamp to a Response-constructible status (an aborted/interceptor
|
||||
// request reports status 0, which `new Response` rejects).
|
||||
const status = err.status >= 200 && err.status <= 599 ? err.status : 500;
|
||||
return new Response(body, { status });
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** Provide a root ApiClient that talks through HttpClient (relative `/api` base URL). */
|
||||
export function provideApiClient(): Provider {
|
||||
return {
|
||||
provide: ApiClient,
|
||||
useFactory: (http: HttpClient) => new ApiClient('', httpClientFetch(http)),
|
||||
deps: [HttpClient],
|
||||
};
|
||||
}
|
||||
|
||||
export type { ProblemDetails };
|
||||
474
src/app/shared/infrastructure/api-client.ts
Normal file
474
src/app/shared/infrastructure/api-client.ts
Normal file
@@ -0,0 +1,474 @@
|
||||
//----------------------
|
||||
// <auto-generated>
|
||||
// Generated using the NSwag toolchain v14.7.1.0 (NJsonSchema v11.6.1.0 (Newtonsoft.Json v13.0.0.0)) (http://NSwag.org)
|
||||
// </auto-generated>
|
||||
//----------------------
|
||||
|
||||
/* eslint-disable */
|
||||
// ReSharper disable InconsistentNaming
|
||||
|
||||
export class ApiClient {
|
||||
private http: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> };
|
||||
private baseUrl: string;
|
||||
protected jsonParseReviver: ((key: string, value: any) => any) | undefined = undefined;
|
||||
|
||||
constructor(baseUrl?: string, http?: { fetch(url: RequestInfo, init?: RequestInit): Promise<Response> }) {
|
||||
this.http = http ? http : window as any;
|
||||
this.baseUrl = baseUrl ?? "";
|
||||
}
|
||||
|
||||
/**
|
||||
* @return OK
|
||||
*/
|
||||
dashboardView(): Promise<DashboardViewDto> {
|
||||
let url_ = this.baseUrl + "/api/dashboard-view";
|
||||
url_ = url_.replace(/[?&]$/, "");
|
||||
|
||||
let options_: RequestInit = {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Accept": "application/json"
|
||||
}
|
||||
};
|
||||
|
||||
return this.http.fetch(url_, options_).then((_response: Response) => {
|
||||
return this.processDashboardView(_response);
|
||||
});
|
||||
}
|
||||
|
||||
protected processDashboardView(response: Response): Promise<DashboardViewDto> {
|
||||
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 DashboardViewDto;
|
||||
return result200;
|
||||
});
|
||||
} else if (status !== 200 && status !== 204) {
|
||||
return response.text().then((_responseText) => {
|
||||
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
|
||||
});
|
||||
}
|
||||
return Promise.resolve<DashboardViewDto>(null as any);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return OK
|
||||
*/
|
||||
notes(): Promise<AantekeningDto[]> {
|
||||
let url_ = this.baseUrl + "/api/notes";
|
||||
url_ = url_.replace(/[?&]$/, "");
|
||||
|
||||
let options_: RequestInit = {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Accept": "application/json"
|
||||
}
|
||||
};
|
||||
|
||||
return this.http.fetch(url_, options_).then((_response: Response) => {
|
||||
return this.processNotes(_response);
|
||||
});
|
||||
}
|
||||
|
||||
protected processNotes(response: Response): Promise<AantekeningDto[]> {
|
||||
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 AantekeningDto[];
|
||||
return result200;
|
||||
});
|
||||
} else if (status !== 200 && status !== 204) {
|
||||
return response.text().then((_responseText) => {
|
||||
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
|
||||
});
|
||||
}
|
||||
return Promise.resolve<AantekeningDto[]>(null as any);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return OK
|
||||
*/
|
||||
address(): Promise<BrpAddressDto> {
|
||||
let url_ = this.baseUrl + "/api/brp/address";
|
||||
url_ = url_.replace(/[?&]$/, "");
|
||||
|
||||
let options_: RequestInit = {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Accept": "application/json"
|
||||
}
|
||||
};
|
||||
|
||||
return this.http.fetch(url_, options_).then((_response: Response) => {
|
||||
return this.processAddress(_response);
|
||||
});
|
||||
}
|
||||
|
||||
protected processAddress(response: Response): Promise<BrpAddressDto> {
|
||||
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 BrpAddressDto;
|
||||
return result200;
|
||||
});
|
||||
} else if (status !== 200 && status !== 204) {
|
||||
return response.text().then((_responseText) => {
|
||||
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
|
||||
});
|
||||
}
|
||||
return Promise.resolve<BrpAddressDto>(null as any);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return OK
|
||||
*/
|
||||
diplomas(): Promise<DuoLookupDto> {
|
||||
let url_ = this.baseUrl + "/api/duo/diplomas";
|
||||
url_ = url_.replace(/[?&]$/, "");
|
||||
|
||||
let options_: RequestInit = {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Accept": "application/json"
|
||||
}
|
||||
};
|
||||
|
||||
return this.http.fetch(url_, options_).then((_response: Response) => {
|
||||
return this.processDiplomas(_response);
|
||||
});
|
||||
}
|
||||
|
||||
protected processDiplomas(response: Response): Promise<DuoLookupDto> {
|
||||
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 DuoLookupDto;
|
||||
return result200;
|
||||
});
|
||||
} else if (status !== 200 && status !== 204) {
|
||||
return response.text().then((_responseText) => {
|
||||
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
|
||||
});
|
||||
}
|
||||
return Promise.resolve<DuoLookupDto>(null as any);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return OK
|
||||
*/
|
||||
policy(): Promise<IntakePolicyDto> {
|
||||
let url_ = this.baseUrl + "/api/intake/policy";
|
||||
url_ = url_.replace(/[?&]$/, "");
|
||||
|
||||
let options_: RequestInit = {
|
||||
method: "GET",
|
||||
headers: {
|
||||
"Accept": "application/json"
|
||||
}
|
||||
};
|
||||
|
||||
return this.http.fetch(url_, options_).then((_response: Response) => {
|
||||
return this.processPolicy(_response);
|
||||
});
|
||||
}
|
||||
|
||||
protected processPolicy(response: Response): Promise<IntakePolicyDto> {
|
||||
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 IntakePolicyDto;
|
||||
return result200;
|
||||
});
|
||||
} else if (status !== 200 && status !== 204) {
|
||||
return response.text().then((_responseText) => {
|
||||
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
|
||||
});
|
||||
}
|
||||
return Promise.resolve<IntakePolicyDto>(null as any);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return OK
|
||||
*/
|
||||
registrations(body: RegistratieRequest): Promise<ReferentieResponse> {
|
||||
let url_ = this.baseUrl + "/api/registrations";
|
||||
url_ = url_.replace(/[?&]$/, "");
|
||||
|
||||
const content_ = JSON.stringify(body);
|
||||
|
||||
let options_: RequestInit = {
|
||||
body: content_,
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json"
|
||||
}
|
||||
};
|
||||
|
||||
return this.http.fetch(url_, options_).then((_response: Response) => {
|
||||
return this.processRegistrations(_response);
|
||||
});
|
||||
}
|
||||
|
||||
protected processRegistrations(response: Response): Promise<ReferentieResponse> {
|
||||
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 ReferentieResponse;
|
||||
return result200;
|
||||
});
|
||||
} else if (status === 422) {
|
||||
return response.text().then((_responseText) => {
|
||||
let result422: any = null;
|
||||
result422 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver) as ProblemDetails;
|
||||
return throwException("Unprocessable Content", status, _responseText, _headers, result422);
|
||||
});
|
||||
} else if (status !== 200 && status !== 204) {
|
||||
return response.text().then((_responseText) => {
|
||||
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
|
||||
});
|
||||
}
|
||||
return Promise.resolve<ReferentieResponse>(null as any);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return OK
|
||||
*/
|
||||
herregistraties(body: HerregistratieRequest): Promise<ReferentieResponse> {
|
||||
let url_ = this.baseUrl + "/api/herregistraties";
|
||||
url_ = url_.replace(/[?&]$/, "");
|
||||
|
||||
const content_ = JSON.stringify(body);
|
||||
|
||||
let options_: RequestInit = {
|
||||
body: content_,
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json"
|
||||
}
|
||||
};
|
||||
|
||||
return this.http.fetch(url_, options_).then((_response: Response) => {
|
||||
return this.processHerregistraties(_response);
|
||||
});
|
||||
}
|
||||
|
||||
protected processHerregistraties(response: Response): Promise<ReferentieResponse> {
|
||||
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 ReferentieResponse;
|
||||
return result200;
|
||||
});
|
||||
} else if (status === 422) {
|
||||
return response.text().then((_responseText) => {
|
||||
let result422: any = null;
|
||||
result422 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver) as ProblemDetails;
|
||||
return throwException("Unprocessable Content", status, _responseText, _headers, result422);
|
||||
});
|
||||
} else if (status !== 200 && status !== 204) {
|
||||
return response.text().then((_responseText) => {
|
||||
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
|
||||
});
|
||||
}
|
||||
return Promise.resolve<ReferentieResponse>(null as any);
|
||||
}
|
||||
|
||||
/**
|
||||
* @return OK
|
||||
*/
|
||||
intakes(body: IntakeRequest): Promise<ReferentieResponse> {
|
||||
let url_ = this.baseUrl + "/api/intakes";
|
||||
url_ = url_.replace(/[?&]$/, "");
|
||||
|
||||
const content_ = JSON.stringify(body);
|
||||
|
||||
let options_: RequestInit = {
|
||||
body: content_,
|
||||
method: "POST",
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
"Accept": "application/json"
|
||||
}
|
||||
};
|
||||
|
||||
return this.http.fetch(url_, options_).then((_response: Response) => {
|
||||
return this.processIntakes(_response);
|
||||
});
|
||||
}
|
||||
|
||||
protected processIntakes(response: Response): Promise<ReferentieResponse> {
|
||||
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 ReferentieResponse;
|
||||
return result200;
|
||||
});
|
||||
} else if (status === 422) {
|
||||
return response.text().then((_responseText) => {
|
||||
let result422: any = null;
|
||||
result422 = _responseText === "" ? null : JSON.parse(_responseText, this.jsonParseReviver) as ProblemDetails;
|
||||
return throwException("Unprocessable Content", status, _responseText, _headers, result422);
|
||||
});
|
||||
} else if (status !== 200 && status !== 204) {
|
||||
return response.text().then((_responseText) => {
|
||||
return throwException("An unexpected server error occurred.", status, _responseText, _headers);
|
||||
});
|
||||
}
|
||||
return Promise.resolve<ReferentieResponse>(null as any);
|
||||
}
|
||||
}
|
||||
|
||||
export interface AantekeningDto {
|
||||
type?: string | undefined;
|
||||
omschrijving?: string | undefined;
|
||||
datum?: string | undefined;
|
||||
}
|
||||
|
||||
export interface AdresDto {
|
||||
straat?: string | undefined;
|
||||
postcode?: string | undefined;
|
||||
woonplaats?: string | undefined;
|
||||
}
|
||||
|
||||
export interface BrpAddressDto {
|
||||
gevonden?: boolean;
|
||||
adres?: AdresDto;
|
||||
}
|
||||
|
||||
export interface DashboardViewDto {
|
||||
registration?: RegistrationDto;
|
||||
person?: PersonDto;
|
||||
decisions?: HerregistratieDecisionsDto;
|
||||
}
|
||||
|
||||
export interface DuoDiplomaDto {
|
||||
id?: string | undefined;
|
||||
naam?: string | undefined;
|
||||
instelling?: string | undefined;
|
||||
jaar?: number;
|
||||
beroep?: string | undefined;
|
||||
policyQuestions?: PolicyQuestionDto[] | undefined;
|
||||
}
|
||||
|
||||
export interface DuoLookupDto {
|
||||
diplomas?: DuoDiplomaDto[] | undefined;
|
||||
handmatig?: ManualDiplomaPolicyDto;
|
||||
}
|
||||
|
||||
export interface HerregistratieDecisionsDto {
|
||||
eligibleForHerregistratie?: boolean;
|
||||
herregistratieReason?: string | undefined;
|
||||
}
|
||||
|
||||
export interface HerregistratieRequest {
|
||||
uren?: number;
|
||||
}
|
||||
|
||||
export interface IntakePolicyDto {
|
||||
scholingThreshold?: number;
|
||||
}
|
||||
|
||||
export interface IntakeRequest {
|
||||
uren?: number;
|
||||
}
|
||||
|
||||
export interface ManualDiplomaPolicyDto {
|
||||
beroepen?: string[] | undefined;
|
||||
policyQuestions?: PolicyQuestionDto[] | undefined;
|
||||
}
|
||||
|
||||
export interface PersonDto {
|
||||
naam?: string | undefined;
|
||||
geboortedatum?: string | undefined;
|
||||
adres?: AdresDto;
|
||||
}
|
||||
|
||||
export interface PolicyQuestionDto {
|
||||
id?: string | undefined;
|
||||
vraag?: string | undefined;
|
||||
type?: string | undefined;
|
||||
}
|
||||
|
||||
export interface ProblemDetails {
|
||||
type?: string | undefined;
|
||||
title?: string | undefined;
|
||||
status?: number | undefined;
|
||||
detail?: string | undefined;
|
||||
instance?: string | undefined;
|
||||
|
||||
[key: string]: any;
|
||||
}
|
||||
|
||||
export interface ReferentieResponse {
|
||||
referentie?: string | undefined;
|
||||
}
|
||||
|
||||
export interface RegistratieRequest {
|
||||
diplomaHerkomst?: string | undefined;
|
||||
}
|
||||
|
||||
export interface RegistrationDto {
|
||||
bigNummer?: string | undefined;
|
||||
naam?: string | undefined;
|
||||
beroep?: string | undefined;
|
||||
registratiedatum?: string | undefined;
|
||||
geboortedatum?: string | undefined;
|
||||
status?: RegistrationStatusDto;
|
||||
}
|
||||
|
||||
export interface RegistrationStatusDto {
|
||||
tag?: string | undefined;
|
||||
herregistratieDatum?: string | undefined;
|
||||
geschorstTot?: string | undefined;
|
||||
reden?: string | undefined;
|
||||
doorgehaaldOp?: string | undefined;
|
||||
}
|
||||
|
||||
export class SwaggerException extends Error {
|
||||
override message: string;
|
||||
status: number;
|
||||
response: string;
|
||||
headers: { [key: string]: any; };
|
||||
result: any;
|
||||
|
||||
constructor(message: string, status: number, response: string, headers: { [key: string]: any; }, result: any) {
|
||||
super();
|
||||
|
||||
this.message = message;
|
||||
this.status = status;
|
||||
this.response = response;
|
||||
this.headers = headers;
|
||||
this.result = result;
|
||||
}
|
||||
|
||||
protected isSwaggerException = true;
|
||||
|
||||
static isSwaggerException(obj: any): obj is SwaggerException {
|
||||
return obj.isSwaggerException === true;
|
||||
}
|
||||
}
|
||||
|
||||
function throwException(message: string, status: number, response: string, headers: { [key: string]: any; }, result?: any): any {
|
||||
if (result !== null && result !== undefined)
|
||||
throw result;
|
||||
else
|
||||
throw new SwaggerException(message, status, response, headers, null);
|
||||
}
|
||||
14
src/app/shared/infrastructure/api-error.spec.ts
Normal file
14
src/app/shared/infrastructure/api-error.spec.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { problemDetail } from './api-error';
|
||||
|
||||
describe('problemDetail', () => {
|
||||
it('extracts the detail from an RFC-7807 ProblemDetails', () => {
|
||||
expect(problemDetail({ detail: 'Afgewezen: 0 uren.', status: 422 }, 'fallback')).toBe('Afgewezen: 0 uren.');
|
||||
});
|
||||
|
||||
it('falls back when there is no detail', () => {
|
||||
expect(problemDetail(new Error('boom'), 'fallback')).toBe('fallback');
|
||||
expect(problemDetail({ status: 500 }, 'fallback')).toBe('fallback');
|
||||
expect(problemDetail(undefined, 'fallback')).toBe('fallback');
|
||||
});
|
||||
});
|
||||
14
src/app/shared/infrastructure/api-error.ts
Normal file
14
src/app/shared/infrastructure/api-error.ts
Normal file
@@ -0,0 +1,14 @@
|
||||
import { ProblemDetails } from './api-client';
|
||||
|
||||
/**
|
||||
* Extract a human-readable message from a rejected API call. A 4xx/5xx with a
|
||||
* ProblemDetails body (RFC 7807) is thrown by the generated client as the parsed
|
||||
* object; anything else falls back to the given message.
|
||||
*/
|
||||
export function problemDetail(e: unknown, fallback: string): string {
|
||||
if (e && typeof e === 'object' && 'detail' in e) {
|
||||
const detail = (e as ProblemDetails).detail;
|
||||
if (typeof detail === 'string' && detail) return detail;
|
||||
}
|
||||
return fallback;
|
||||
}
|
||||
@@ -4,12 +4,12 @@ import { delay } from 'rxjs/operators';
|
||||
import { currentScenario } from './scenario';
|
||||
|
||||
/**
|
||||
* Demo-only: rewrites the timing/outcome of mock data requests based on
|
||||
* Demo-only: rewrites the timing/outcome of API data requests based on
|
||||
* ?scenario= so loading / empty / error states can be shown on demand.
|
||||
* Real requests are untouched.
|
||||
* Non-API requests are untouched.
|
||||
*/
|
||||
export const scenarioInterceptor: HttpInterceptorFn = (req, next) => {
|
||||
if (!req.url.includes('mock/')) return next(req);
|
||||
if (!req.url.includes('/api/')) return next(req);
|
||||
|
||||
switch (currentScenario()) {
|
||||
case 'slow':
|
||||
@@ -17,7 +17,8 @@ export const scenarioInterceptor: HttpInterceptorFn = (req, next) => {
|
||||
case 'loading':
|
||||
return next(req).pipe(delay(600_000)); // effectively never resolves
|
||||
case 'empty':
|
||||
return of(new HttpResponse({ status: 200, body: [] })).pipe(delay(400));
|
||||
// '[]' so the typed client parses it to an empty array (notes → Empty state).
|
||||
return of(new HttpResponse({ status: 200, body: '[]' })).pipe(delay(400));
|
||||
case 'error':
|
||||
return timer(400).pipe(
|
||||
switchMap(() => throwError(() =>
|
||||
|
||||
115
src/app/shared/layout/wizard-shell/wizard-shell.component.ts
Normal file
115
src/app/shared/layout/wizard-shell/wizard-shell.component.ts
Normal file
@@ -0,0 +1,115 @@
|
||||
import { Component, ElementRef, effect, input, output, untracked, viewChild } from '@angular/core';
|
||||
import { ButtonComponent } from '@shared/ui/button/button.component';
|
||||
import { AlertComponent } from '@shared/ui/alert/alert.component';
|
||||
import { SpinnerComponent } from '@shared/ui/spinner/spinner.component';
|
||||
import { StepperComponent } from '@shared/ui/stepper/stepper.component';
|
||||
|
||||
/** A flat validation error pointing at a field: `id` matches the field's anchor. */
|
||||
export interface WizardError {
|
||||
readonly id: string;
|
||||
readonly message: string;
|
||||
}
|
||||
|
||||
export type WizardStatus = 'editing' | 'submitting' | 'submitted' | 'failed';
|
||||
|
||||
/**
|
||||
* Template: the canonical shell every wizard renders into, so they cannot drift.
|
||||
* It owns the consistent outline — stepper + focusable step heading + error
|
||||
* summary + the <form> + the Back/Next/Cancel action bar + the submitting/
|
||||
* submitted/failed states — and the a11y focus management.
|
||||
*
|
||||
* Presentational and unidirectional: all state stays in the wizard container
|
||||
* (the Elm-style store). Inputs flow down; the container reacts to the outputs
|
||||
* and dispatches messages. The step's own fields are projected as the default
|
||||
* slot; the success screen is projected via [wizardSuccess].
|
||||
*/
|
||||
@Component({
|
||||
selector: 'app-wizard-shell',
|
||||
imports: [ButtonComponent, AlertComponent, SpinnerComponent, StepperComponent],
|
||||
styles: [`
|
||||
.es-title{margin:0 0 var(--rhc-space-max-sm)}
|
||||
.es-list{margin:0;padding-inline-start:var(--rhc-space-max-xl)}
|
||||
`],
|
||||
template: `
|
||||
@switch (status()) {
|
||||
@case ('editing') {
|
||||
<app-stepper class="app-section" [steps]="steps()" [current]="current()" />
|
||||
<h2 #stepHeading tabindex="-1" class="rhc-heading nl-heading--level-2 app-section">{{ stepTitle() }}</h2>
|
||||
@if (errors().length) {
|
||||
<div #errorSummary tabindex="-1" role="alert" aria-labelledby="wizard-error-title" class="app-section">
|
||||
<app-alert type="error">
|
||||
<h3 id="wizard-error-title" class="rhc-heading nl-heading--level-3 es-title">Er ging iets mis met uw invoer</h3>
|
||||
<ul class="es-list">
|
||||
@for (e of errors(); track e.id) {
|
||||
<li><a [href]="'#' + e.id">{{ e.message }}</a></li>
|
||||
}
|
||||
</ul>
|
||||
</app-alert>
|
||||
</div>
|
||||
}
|
||||
<form (ngSubmit)="primary.emit()" class="app-form">
|
||||
<ng-content />
|
||||
<div class="app-button-row app-button-row--spaced">
|
||||
@if (canGoBack()) {
|
||||
<app-button type="button" variant="secondary" (click)="back.emit()">Vorige</app-button>
|
||||
}
|
||||
<app-button type="submit" variant="primary">{{ primaryLabel() }}</app-button>
|
||||
<app-button type="button" variant="subtle" (click)="cancel.emit()">Annuleren</app-button>
|
||||
</div>
|
||||
</form>
|
||||
}
|
||||
@case ('submitting') {
|
||||
<app-spinner /> <span>{{ submittingLabel() }}</span>
|
||||
}
|
||||
@case ('submitted') {
|
||||
<ng-content select="[wizardSuccess]" />
|
||||
}
|
||||
@case ('failed') {
|
||||
<app-alert type="error">{{ errorMessage() }}</app-alert>
|
||||
<div class="app-section">
|
||||
<app-button variant="secondary" (click)="retry.emit()">Opnieuw proberen</app-button>
|
||||
</div>
|
||||
}
|
||||
}
|
||||
`,
|
||||
})
|
||||
export class WizardShellComponent {
|
||||
steps = input.required<string[]>();
|
||||
current = input.required<number>();
|
||||
stepTitle = input.required<string>();
|
||||
status = input.required<WizardStatus>();
|
||||
primaryLabel = input.required<string>();
|
||||
canGoBack = input(false);
|
||||
errors = input<readonly WizardError[]>([]);
|
||||
errorMessage = input('');
|
||||
submittingLabel = input('Aanvraag wordt verwerkt…');
|
||||
|
||||
primary = output<void>();
|
||||
back = output<void>();
|
||||
cancel = output<void>();
|
||||
retry = output<void>();
|
||||
|
||||
private stepHeading = viewChild<ElementRef<HTMLElement>>('stepHeading');
|
||||
private errorSummary = viewChild<ElementRef<HTMLElement>>('errorSummary');
|
||||
|
||||
constructor() {
|
||||
// A11y: move focus to the step heading when the step changes (skip first run
|
||||
// so we don't grab focus on initial load). Tracks current(), which is value-
|
||||
// stable across keystrokes, so typing never steals focus.
|
||||
let firstStep = true;
|
||||
effect(() => {
|
||||
this.current();
|
||||
if (firstStep) { firstStep = false; return; }
|
||||
untracked(() => queueMicrotask(() => this.stepHeading()?.nativeElement.focus()));
|
||||
});
|
||||
// A11y: when validation errors appear (after a failed submit), move focus to
|
||||
// the error summary so it's announced. The reducer returns a fresh errors
|
||||
// object per attempt, so resubmitting the same invalid step re-announces.
|
||||
let firstErr = true;
|
||||
effect(() => {
|
||||
const has = this.errors().length > 0;
|
||||
if (firstErr) { firstErr = false; return; }
|
||||
if (has) untracked(() => queueMicrotask(() => this.errorSummary()?.nativeElement.focus()));
|
||||
});
|
||||
}
|
||||
}
|
||||
37
src/app/shared/layout/wizard-shell/wizard-shell.stories.ts
Normal file
37
src/app/shared/layout/wizard-shell/wizard-shell.stories.ts
Normal file
@@ -0,0 +1,37 @@
|
||||
import type { Meta, StoryObj } from '@storybook/angular';
|
||||
import { WizardShellComponent } from './wizard-shell.component';
|
||||
|
||||
const meta: Meta<WizardShellComponent> = {
|
||||
title: 'Templates/WizardShell',
|
||||
component: WizardShellComponent,
|
||||
render: (args) => ({
|
||||
props: args,
|
||||
template: `
|
||||
<app-wizard-shell
|
||||
[steps]="steps" [current]="current" [stepTitle]="stepTitle" [status]="status"
|
||||
[primaryLabel]="primaryLabel" [canGoBack]="canGoBack" [errors]="errors" [errorMessage]="errorMessage">
|
||||
<p class="rhc-paragraph">Voorbeeld-stapinhoud (de stapvelden worden hier geprojecteerd).</p>
|
||||
<div wizardSuccess><p class="rhc-paragraph">Uw aanvraag is ontvangen.</p></div>
|
||||
</app-wizard-shell>`,
|
||||
}),
|
||||
};
|
||||
export default meta;
|
||||
type Story = StoryObj<WizardShellComponent>;
|
||||
|
||||
const steps = ['Adres', 'Beroep', 'Controle'];
|
||||
const base = { steps, current: 1, stepTitle: 'Beroep op basis van uw diploma', primaryLabel: 'Volgende', canGoBack: true, errors: [], errorMessage: '' };
|
||||
|
||||
export const Editing: Story = { args: { ...base, status: 'editing' } };
|
||||
export const EditingMetFouten: Story = {
|
||||
args: {
|
||||
...base,
|
||||
status: 'editing',
|
||||
errors: [
|
||||
{ id: 'uren', message: 'Vul het aantal gewerkte uren in.' },
|
||||
{ id: 'diploma', message: 'Kies een diploma.' },
|
||||
],
|
||||
},
|
||||
};
|
||||
export const Submitting: Story = { args: { ...base, status: 'submitting' } };
|
||||
export const Submitted: Story = { args: { ...base, status: 'submitted' } };
|
||||
export const Failed: Story = { args: { ...base, status: 'failed', errorMessage: 'Het indienen is niet gelukt: netwerkfout.' } };
|
||||
Reference in New Issue
Block a user