Compare commits

...
Author SHA1 Message Date
not dcd24d17a3 Merge branch 'main' into fix/110-compose-local-flow
CI / unit (pull_request) Successful in 1m12s
CI / lint (pull_request) Successful in 1m17s
CI / build (pull_request) Successful in 59s
CI / frontend (pull_request) Successful in 2m39s
CI / mutation (pull_request) Successful in 5m43s
CI / verify-stack (pull_request) Successful in 7m57s
2026-07-22 14:04:26 +02:00
not d5e5fa254c fix(e2e): run Playwright single-worker to stop OOM page-crash in verify-stack (closes #115) (#116)
CI / lint (push) Successful in 1m22s
CI / build (push) Successful in 1m1s
CI / unit (push) Successful in 1m14s
CI / frontend (push) Successful in 2m43s
CI / mutation (push) Successful in 5m53s
CI / verify-stack (push) Has been cancelled
## What & why

`verify-stack` was failing intermittently on the Playwright e2e with `Page crashed` mid-action (`locator.fill`) and 90s timeouts — the run logged **"2 workers"**, i.e. two full `channel: 'chromium'` browsers running alongside the entire compose stack on the 8 GB self-hosted runner. The renderer gets OOM-killed. Tests passed only when a retry happened to run alone.

Fix: pin `workers: 1` in `tests/e2e/playwright.config.ts` (there are only two long-running happy-path specs, so serial costs little) and add `--disable-dev-shm-usage`. This removes the memory contention at the source rather than leaning on `retries` (CLAUDE.md §15 — flaky tests are fixed, not retried).

Closes #115

## Definition of Done

- [x] Linked Gitea issue (#115).
- [ ] Failing test committed first — N/A: the "red" is the observed `verify-stack` e2e crash (`Page crashed`, 2 workers); this changes test-harness config to fix it. Verified green by re-running the e2e (see notes).
- [x] Conventional Commit referencing the issue (`refs #115`).
- [ ] CI green — the point of the change; `verify-stack` e2e should stop OOM-crashing.
- [x] Docs — none needed (test-config only; rationale in an inline comment).
- [ ] ADR — N/A.

## Notes for reviewers

- One-line-of-behaviour change: `workers: 1` + `--disable-dev-shm-usage`; no product or spec changes.
- `Page crashed` is a renderer OOM, not a product defect — the happy path passes when a browser runs alone (the flaky retries already showed this). Single-worker makes that the normal case.
- Independent of #110 (that PR fixes `docker-compose.local.yml`; this fixes the CI `verify-stack` e2e). Landing this first unblocks #110's `verify-stack`.

Reviewed-on: #116
2026-07-22 12:03:59 +00:00
notandClaude Opus 4.8 a693137c7c docs(infra): ADR-0020 + demo note for the local-stack self-seed (refs #110)
CI / lint (pull_request) Successful in 1m19s
CI / build (pull_request) Successful in 56s
CI / unit (pull_request) Successful in 1m6s
CI / frontend (pull_request) Successful in 2m31s
CI / mutation (pull_request) Successful in 6m0s
CI / verify-stack (pull_request) Failing after 10m33s
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-22 11:34:36 +02:00
notandClaude Opus 4.8 a940a6c9ce fix(infra): docker-compose.local self-seeds zaaktype, DMN + NRC abonnement (refs #110)
A fresh `make local` now completes the whole flow with no manual seeding, closing
the three S-B04 gaps in the host-browser stack:

- flowable-init also deploys diploma-eligibility.dmn (was BPMN-only), so completing
  WachtOpDocumenten routes through the DMN to Beoordelen instead of 404ing.
- a local-seed one-shot seeds + publishes the BIG zaaktype (server-assigned URL) and
  writes it to seed-env:/acl.env; the ACL sources it on startup (entrypoint override),
  since the UUID isn't knowable at compose-write time.
- an nrc-subscribe one-shot registers the `zaken` abonnement at the event-subscriber
  callback, so notifications reach the projection and the openbaar register.

Both one-shots reach OpenZaak/NRC by container IP (a single-label host fails their
Django URLValidator), mirroring the CI verify scripts. Asserted by `make verify-local`.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-22 11:34:08 +02:00
notandClaude Opus 4.8 97ef3b9535 test(infra): acceptance check that make local completes the flow unseeded (refs #110)
Adds infra/run-local-flow-check.sh (+ `make verify-local`): submits a
registration against a fresh local stack and asserts it opens a zaak, reaches
the werkbak after documents, and appears in the openbaar register — all with no
manual seeding. Fails today (ACL points at a placeholder zaaktype; the DMN is
undeployed; no NRC abonnement is registered), covering the three S-B04 gaps.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-22 11:28:15 +02:00
not bf234e1322 docs(backlog): add S-26 self-service resume slice (refs #111) (#112)
CI / verify-stack (push) Successful in 11m16s
CI / lint (push) Successful in 1m22s
CI / build (push) Successful in 1m6s
CI / unit (push) Successful in 1m18s
CI / frontend (push) Successful in 3m7s
CI / mutation (push) Successful in 5m58s
## What & why

Mirror the new self-service **"resume after refresh"** slice into the Iteration 2 section of the curated backlog (`BACKLOG.md`), keeping it in sync with Gitea. Tracked as #111 (S-26).

Refs #111 — **does not close it**: the backlog is the curated mirror, the slice itself stays open for implementation.

## Definition of Done

- [x] Linked Gitea issue (#111).
- [ ] Failing test committed before the implementation — N/A (docs-only backlog mirror).
- [ ] Implementation makes the test pass; refactor commit if structure improved — N/A.
- [x] Conventional Commits referencing the issue (`refs #111`).
- [ ] CI green — no code paths touched; only `BACKLOG.md`.
- [ ] `docker compose up` reaches green health checks — N/A.
- [x] Docs updated (this IS the docs change).
- [ ] ADR added — N/A.
- [ ] Demo note in `docs/demo-script.md` — N/A (backlog entry, not a shipped user-visible change).

## Notes for reviewers

Single-file change: adds the `S-26` entry (Outcome + Acceptance) after S-14 in Iteration 2, matching the surrounding slice format. The `S-B04` local-stack bug (#110) is intentionally **not** added — the `S-B0N` bug-slices have never been mirrored in `BACKLOG.md` (they live only in Gitea).

Reviewed-on: #112
2026-07-22 09:12:19 +00:00
not c8fdfbb699 feat(acl,domain): cancel the ZGW zaak on document-timeout expiry (S-10c, closes #106) (#109)
CI / lint (push) Successful in 1m22s
CI / build (push) Successful in 1m1s
CI / frontend (push) Successful in 2m27s
CI / mutation (push) Successful in 5m34s
CI / verify-stack (push) Successful in 8m0s
CI / unit (push) Successful in 1m17s
## S-10c · Close the ZGW zaak on document-timeout expiry (closes #106)

Completes the S-10a/S-10b boundary flagged in ADR-0017: when a registration's 30-day document term lapses, the domain now cancels the **ZGW zaak** as well as marking the aggregate `Verlopen`, so OpenZaak and the register no longer diverge.

### What it does
On expiry the `ExpireRegistrationWorker` calls the ACL to set the zaak to a distinct, non-terminal **`Geannuleerd`** status with a **`Vervallen`** resultaat (vs the approval `Afgehandeld` + `Geregistreerd`), resolved **by omschrijving** in the ACL — the ACL-first ordering mirrors approval so a failed ZGW call leaves the job for redelivery rather than diverging the two.

**Path:** Flowable P30D timer → `RegistratieVerlopen` job → domain `ExpireRegistrationWorker` → ACL `POST /annuleringen` → ZGW `resultaten` + `statussen` (Geannuleerd) → aggregate `Verlopen`.

### Layers touched (each red→green)
- **ACL gateway** — `SetZaakToCancellationStatusAsync` (Geannuleerd + Vervallen by name); approval now resolves its `Geregistreerd` resultaat by name too (a second resultaattype now exists).
- **ACL service/API** — `AclService.CancelZaakAsync` + `POST /annuleringen`.
- **Domain** — `IAclClient.CancelZaakAsync` + client; expiry worker cancels the zaak before advancing to `Verlopen`, guarded against redelivery double-cancel.
- **Seed** — non-terminal `Geannuleerd` statustype (volgnummer 2; `Afgehandeld` → 3) + `Vervallen` resultaattype, both idempotent by omschrijving and sharing the zaaktype's procestype.
- **Verify/integration** — ACL↔OpenZaak integration test (live `Geannuleerd` + resultaat); `run-domain-check.sh` fires the real P30D timer and asserts the zaak reaches `Geannuleerd` end-to-end; BDD scenario asserts cancel-on-timeout vs untouched-when-in-time.
- **Docs** — ADR-0019 (cancellation modelling decision), demo-script, BACKLOG.

### Design note (ADR-0019)
ZGW allows only one eindstatus per zaaktype, so `Geannuleerd` is modelled as a **non-terminal** status (it records a cancellation status + resultaat but does not set `einddatum`). This follows the issue's explicit "distinct statustype + resultaat" outcome; the shared-eindstatus alternative is recorded in the ADR.

### Tests
Unit + acceptance all green locally (Acl 38, Big 134, Acceptance 17, Bff 33, EventSubscriber 19). Integration + verify-stack run in CI (need live OpenZaak + selectielijst egress).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Reviewed-on: #109
2026-07-21 13:58:15 +00:00
not 0904df8db0 feat(acl): diploma upload stored in the ZGW Documenten API (S-10b, closes #103) (#108)
CI / lint (push) Successful in 1m21s
CI / build (push) Successful in 1m4s
CI / unit (push) Successful in 1m12s
CI / frontend (push) Successful in 2m40s
CI / mutation (push) Successful in 5m31s
CI / verify-stack (push) Successful in 7m56s
## What & why

S-10b: the self-service **diploma upload** is now real. After submitting, the citizen picks a PDF and
uploads it; the portal base64-encodes it client-side → BFF → domain → **ACL**, which stores it in the
ZGW **Documenten (DRC) API** as an `enkelvoudiginformatieobject` and relates it to the zaak, then the
`WachtOpDocumenten` wait completes and the case advances to beoordeling. Per §8.1 only the ACL talks to
ZGW.

Closes #103

Mechanism in **ADR-0018** (proposal #107). Builds on S-10a (#102). The zaak-close-on-expiry item is
carved to **#106 (S-10c)**.

## Definition of Done

- [x] Linked Gitea issue (above).
- [x] Failing test committed before the implementation (red→green per layer).
- [x] Conventional Commits referencing the issue (`refs #103`).
- [ ] CI green — all Gitea Actions jobs (pending on this PR).
- [x] `docker compose up` health unaffected (ACL boots on a placeholder informatieobjecttype URL; the real one is injected by verify-domain).
- [x] Docs updated (ADR-0018, demo-script, BACKLOG + S-10c).
- [x] ADR added (`docs/architecture/adr-0018-diploma-upload-via-acl-documenten.md`).
- [x] Demo note in `docs/demo-script.md`.

## Notes for reviewers

- **ACL** (`OpenZaakGateway.StoreDocumentAsync` + `AclService.StoreDiplomaAsync` + `POST /documenten`) reuses the existing gateway patterns (ZGW Bearer, buffered non-chunked body, **no CRS** — Documenten isn't geo). Unit-tested via the stub handler; an **integration test** stores a real document against live OpenZaak (verify-acl).
- **Transport:** base64 JSON on every hop (portal encodes client-side) — I deviated from proposal #107's multipart to keep one contract shape and avoid `IFormFile`/antiforgery/multipart-client plumbing; fine at diploma size (ADR-0018 §Alternatives).
- **Infra:** `seed_catalogus.py` seeds + publishes a "Diploma" `informatieobjecttype` and relates it to the zaaktype (while both concept); `verify-domain` injects its URL into the ACL. No new ZGW scopes (seed applicatie has `heeft_alle_autorisaties`).
- **e2e:** uploads a real PDF (`setInputFiles`) after the openbaar INGEDIEND row confirms the zaak is open (so storage doesn't race the OpenZaak worker).
- **Scope boundary:** the ZGW zaak is not set to a cancellation status on 30-day expiry — that's #106 (S-10c).

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Reviewed-on: #108
2026-07-21 12:15:33 +00:00
49 changed files with 1816 additions and 128 deletions
+14 -2
View File
@@ -209,9 +209,15 @@ Split (issue #11 closed) into two independently-demoable slices per §13 — the
#### S-10b · Real diploma upload stored via the ACL Documenten API — #103 #### S-10b · Real diploma upload stored via the ACL Documenten API — #103
**Outcome:** the self-service "Documenten aanleveren" action becomes a real file upload; the document is stored in the ZGW Documenten (DRC) API and related to the zaak, with all document calls routed through the ACL (§8.1), and the zaak is set to a cancellation status on timeout expiry. Builds on the S-10a trigger/wait. Depends on #102. **Outcome:** the self-service "Documenten aanleveren" action becomes a real file upload; the file (base64-encoded end-to-end) is stored in the ZGW Documenten (DRC) API as an `enkelvoudiginformatieobject` and related to the zaak, with all document calls routed through the ACL (§8.1, ADR-0018). Builds on the S-10a trigger/wait. Depends on #102.
**Acceptance:** ACL Documenten gateway integration test; Playwright e2e uploads a real document; the openbaar/zaak reflects the stored document. **Acceptance:** ACL Documenten gateway integration test (real OpenZaak); Playwright e2e uploads a real PDF.
#### S-10c · Close the ZGW zaak on document-timeout expiry — #106
**Outcome:** when the 30-day term lapses (S-10a `RegistratieVerlopen`), the ZGW zaak is set to a distinct non-terminal `Geannuleerd` status + `Vervallen` resultaat (not just the domain aggregate → `Verlopen`), resolved by name in the ACL. Adds the cancellation statustype/resultaattype to the seed + an ACL `CancelZaakAsync`/`POST /annuleringen` + expiry-worker wiring. Carved from S-10b (ADR-0017/0018/0019). Depends on #103.
**Acceptance:** ACL↔OpenZaak integration test (cancellation records `Geannuleerd` + a resultaat, live); the domain verify script fires the P30D timer and asserts the zaak reaches `Geannuleerd` end-to-end; BDD asserts the zaak is cancelled on timeout but untouched when documents arrive in time.
### S-11 · Withdrawal (Flow 3) ### S-11 · Withdrawal (Flow 3)
@@ -233,6 +239,12 @@ Split (issue #11 closed) into two independently-demoable slices per §13 — the
**Outcome:** Boundary timer on beoordeling user task — 14 days. On timeout, reassigns to a teamlead role. **Outcome:** Boundary timer on beoordeling user task — 14 days. On timeout, reassigns to a teamlead role.
### S-26 · Self-service — resume an existing registration after refresh — #111
**Outcome:** a signed-in zorgprofessional who reloads the self-service portal (or returns later) gets back to their in-flight registration and its actions (Documenten aanleveren, Trek aanvraag in), instead of a blank submit form with the reference lost. Today all post-submit state lives in in-memory signals, the reference is not in the URL, and there is no self-service read endpoint — so a reload strands the registration. Adds an owner-scoped (DigiD bsn) `GET /self-service/registrations` on the BFF/domain and a load-on-init/route restore in the portal.
**Acceptance:** BDD — resume after refresh shows the existing registration; lookup is owner-scoped (never another citizen's); a user with no in-flight registration still sees the submit form. Playwright e2e reloads mid-flow and asserts the actions remain reachable.
--- ---
## Iteration 3 — Maintenance portal and observability *(milestone: `Iteration 3 — Beheer & Observability`)* ## Iteration 3 — Maintenance portal and observability *(milestone: `Iteration 3 — Beheer & Observability`)*
+6 -1
View File
@@ -43,7 +43,7 @@ export DOCKER_HOST := unix://$(PODMAN_SOCK)
endif endif
endif endif
.PHONY: ci lint build unit mutation frontend integration verify verify-up verify-acl verify-nrc verify-projection verify-bff verify-domain verify-notifications smoke up down local local-down changelog openzaak-up openzaak-smoke openzaak-seed openzaak-down stack-up stack-smoke stack-down keycloak-up keycloak-smoke keycloak-down flowable-up flowable-smoke flowable-down help .PHONY: ci lint build unit mutation frontend integration verify verify-up verify-acl verify-nrc verify-projection verify-bff verify-domain verify-notifications smoke up down local verify-local local-down changelog openzaak-up openzaak-smoke openzaak-seed openzaak-down stack-up stack-smoke stack-down keycloak-up keycloak-smoke keycloak-down flowable-up flowable-smoke flowable-down help
## ci: run the full pipeline — lint, build, unit, mutation, frontend, verify (mirrors Gitea Actions) ## ci: run the full pipeline — lint, build, unit, mutation, frontend, verify (mirrors Gitea Actions)
## `verify` is the live-stack stage (full stack up once → ACL + notification checks). ## `verify` is the live-stack stage (full stack up once → ACL + notification checks).
@@ -114,6 +114,11 @@ local:
docker compose -f $(LOCAL_COMPOSE) up -d --build docker compose -f $(LOCAL_COMPOSE) up -d --build
WAIT_TIMEOUT=420 bash infra/wait-healthy.sh $(WAIT_SVCS) WAIT_TIMEOUT=420 bash infra/wait-healthy.sh $(WAIT_SVCS)
## verify-local: acceptance check for the local stack (S-B04) — a fresh `make local` completes the
## whole flow (zaaktype seeded + DMN deployed + NRC abonnement) with NO manual seeding.
verify-local:
bash infra/run-local-flow-check.sh
## local-down: stop and remove the bind-mount stack ## local-down: stop and remove the bind-mount stack
local-down: local-down:
docker compose -f $(LOCAL_COMPOSE) down --volumes docker compose -f $(LOCAL_COMPOSE) down --volumes
@@ -19,11 +19,20 @@
Het aanleveren van uw documenten is niet gelukt. Probeer het opnieuw. Het aanleveren van uw documenten is niet gelukt. Probeer het opnieuw.
</p> </p>
} }
<p utrecht-paragraph>Lever uw diploma aan (PDF).</p>
<label utrecht-form-label for="diploma">Diploma</label>
<input
id="diploma"
type="file"
accept="application/pdf"
[disabled]="providingDocuments()"
(change)="onFileSelected($event)"
/>
<button <button
utrecht-button utrecht-button
appearance="primary-action-button" appearance="primary-action-button"
type="button" type="button"
[disabled]="providingDocuments()" [disabled]="providingDocuments() || !selectedFile()"
(click)="provideDocuments()" (click)="provideDocuments()"
> >
Documenten aanleveren Documenten aanleveren
@@ -83,21 +83,29 @@ describe('RegistrationPage', () => {
expect(await screen.findByText(/ingetrokken/i)).toBeTruthy(); expect(await screen.findByText(/ingetrokken/i)).toBeTruthy();
}); });
it('offers to provide documents after submitting, and doing so confirms', async () => { // A small PDF file the citizen "uploads"; the component base64-encodes it client-side.
const diploma = () => new File([new Uint8Array([1, 2, 3])], 'diploma.pdf', { type: 'application/pdf' });
it('uploads a chosen diploma after submitting, and doing so confirms', async () => {
const { provideDocuments, providers: p } = providers(); const { provideDocuments, providers: p } = providers();
await render(RegistrationPage, { providers: p }); await render(RegistrationPage, { providers: p });
fireEvent.click(screen.getByRole('button', { name: /indienen/i })); fireEvent.click(screen.getByRole('button', { name: /indienen/i }));
await screen.findByText(/ontvangen/i); await screen.findByText(/ontvangen/i);
// Choose the file, then upload it.
fireEvent.change(screen.getByLabelText(/diploma/i), { target: { files: [diploma()] } });
fireEvent.click(await screen.findByRole('button', { name: /documenten aanleveren/i })); fireEvent.click(await screen.findByRole('button', { name: /documenten aanleveren/i }));
// The provide-documents call is keyed by the reference the submit returned, and the page confirms. // The upload is keyed by the reference and carries the base64 file + its name; the page confirms.
expect(provideDocuments).toHaveBeenCalledWith('reg-9');
expect(await screen.findByText(/documenten.*aangeleverd/i)).toBeTruthy(); expect(await screen.findByText(/documenten.*aangeleverd/i)).toBeTruthy();
expect(provideDocuments).toHaveBeenCalledWith(
'reg-9',
expect.objectContaining({ fileName: 'diploma.pdf', contentType: 'application/pdf', contentBase64: expect.any(String) }),
);
}); });
it('surfaces a provide-documents failure and keeps the action available', async () => { it('surfaces a diploma-upload failure and keeps the action available', async () => {
const { providers: p } = providers( const { providers: p } = providers(
vi.fn().mockReturnValue(of({ registrationId: 'reg-9', status: 'Ingediend' })), vi.fn().mockReturnValue(of({ registrationId: 'reg-9', status: 'Ingediend' })),
vi.fn().mockReturnValue(of(undefined)), vi.fn().mockReturnValue(of(undefined)),
@@ -107,6 +115,7 @@ describe('RegistrationPage', () => {
fireEvent.click(screen.getByRole('button', { name: /indienen/i })); fireEvent.click(screen.getByRole('button', { name: /indienen/i }));
await screen.findByText(/ontvangen/i); await screen.findByText(/ontvangen/i);
fireEvent.change(screen.getByLabelText(/diploma/i), { target: { files: [diploma()] } });
fireEvent.click(await screen.findByRole('button', { name: /documenten aanleveren/i })); fireEvent.click(await screen.findByRole('button', { name: /documenten aanleveren/i }));
expect(await screen.findByRole('alert')).toBeTruthy(); expect(await screen.findByRole('alert')).toBeTruthy();
@@ -29,6 +29,7 @@ export class RegistrationPage {
protected readonly providingDocuments = signal(false); protected readonly providingDocuments = signal(false);
protected readonly documentsProvided = signal(false); protected readonly documentsProvided = signal(false);
protected readonly provideDocumentsFailed = signal(false); protected readonly provideDocumentsFailed = signal(false);
protected readonly selectedFile = signal<File | undefined>(undefined);
submit(): void { submit(): void {
this.submitting.set(true); this.submitting.set(true);
@@ -47,14 +48,34 @@ export class RegistrationPage {
}); });
} }
provideDocuments(): void { onFileSelected(event: Event): void {
const input = event.target as HTMLInputElement;
this.selectedFile.set(input.files?.[0] ?? undefined);
}
async provideDocuments(): Promise<void> {
const reference = this.reference(); const reference = this.reference();
if (!reference) { const file = this.selectedFile();
if (!reference || !file) {
return; return;
} }
this.providingDocuments.set(true); this.providingDocuments.set(true);
this.provideDocumentsFailed.set(false); this.provideDocumentsFailed.set(false);
this.bff.postSelfServiceRegistrationsIdDocuments(reference).subscribe({ let contentBase64: string;
try {
contentBase64 = await readAsBase64(file);
} catch {
this.provideDocumentsFailed.set(true);
this.providingDocuments.set(false);
return;
}
this.bff
.postSelfServiceRegistrationsIdDocuments(reference, {
contentBase64,
fileName: file.name,
contentType: file.type || 'application/pdf',
})
.subscribe({
next: () => { next: () => {
this.documentsProvided.set(true); this.documentsProvided.set(true);
this.providingDocuments.set(false); this.providingDocuments.set(false);
@@ -87,3 +108,13 @@ export class RegistrationPage {
}); });
} }
} }
/** Read a file's bytes as a base64 string (without the `data:...;base64,` prefix). */
function readAsBase64(file: File): Promise<string> {
return new Promise<string>((resolve, reject) => {
const reader = new FileReader();
reader.onload = () => resolve(((reader.result as string) ?? '').split(',', 2)[1] ?? '');
reader.onerror = () => reject(reader.error ?? new Error('Could not read the file.'));
reader.readAsDataURL(file);
});
}
@@ -0,0 +1,74 @@
# ADR-0018: Diploma upload is stored in the ZGW Documenten API, fronted by the ACL
- **Status:** Accepted
- **Date:** 2026-07-20
- **Deciders:** Respellion engineering
- **Relates to:** S-10b (#103); proposal #107. Builds on ADR-0001 (ACL is the only ZGW caller),
ADR-0003 (ACL default-fill), ADR-0017 (document-wait + provision trigger). Carves the zaak-close on
expiry to #106 (S-10c).
## Context
S-10a wired the "documenten aanleveren" trigger (portal → BFF → domain → complete the WachtOpDocumenten
wait) with the file itself stubbed. S-10b makes the upload real: the diploma must be **stored in the
ZGW Documenten (DRC) API** and related to the zaak. §8.1 makes the ACL the only code that talks to ZGW.
The DRC API is served by the same OpenZaak container as the Zaken/Catalogi APIs.
## Decision
**The ACL fronts the Documenten API: it creates an `enkelvoudiginformatieobject` and relates it to the
zaak. The file travels base64-encoded in JSON across every hop (the portal encodes it client-side); a
"Diploma" `informatieobjecttype` is seeded in the catalogus and injected into the ACL like the
zaaktype.**
- **ACL gateway.** `OpenZaakGateway.StoreDocumentAsync` POSTs the `enkelvoudiginformatieobject`
(`/documenten/api/v1/enkelvoudiginformatieobjecten`, base64 `inhoud`, `bestandsomvang`,
`status=definitief`) then relates it to the zaak (`/zaken/api/v1/zaakinformatieobjecten`), reusing the
established gateway patterns (ZGW Bearer JWT, buffered non-chunked body for uwsgi, **no CRS headers** —
the Documenten API is not geo, unlike zaak-create). `AclService.StoreDiplomaAsync` default-fills the
ZGW-mandatory fields (informatieobjecttype, bronorganisatie, vertrouwelijkheidaanduiding, `taal=nld`,
creatiedatum); the domain hands over only the zaak, the bytes, and the file's name/type. No new ZGW
scopes were needed — the seed applicatie holds `heeft_alle_autorisaties`.
- **The file travels as base64 JSON end-to-end.** The portal reads the chosen file client-side
(`FileReader`) and posts `{ contentBase64, fileName, contentType }` as JSON to the BFF; the BFF
forwards it to the domain, and the domain to the ACL, all as JSON. This deviates from proposal #107's
"multipart on the portal→BFF hop": base64 JSON keeps **one** contract shape across all four services
(no `IFormFile`/antiforgery plumbing, no multipart in the generated client), and a diploma is a small
placeholder PDF, so the ~33% base64 overhead is immaterial. The ACL turns the base64 back into the
ZGW `inhoud`.
- **Storing precedes completing the wait.** `ProvideDocuments` (from S-10a) now stores the diploma via
the ACL — once the zaak is opened — and then completes the `WachtOpDocumenten` task, so a registration
reaches beoordeling only after its diploma is stored. Both steps stay best-effort about missing
preconditions (no zaak yet → skip storage; no process yet → skip completion), mirroring withdrawal.
- **Catalogus.** `seed_catalogus.py` (OZ_PUBLISH) creates a "Diploma" `informatieobjecttype`, relates it
to the zaaktype (`zaaktype-informatieobjecttypen`, while both concept), publishes both, and prints
`INFORMATIEOBJECTTYPE_URL`; verify-domain injects it as `Acl__Defaults__InformatieobjecttypeUrl`
(a zeros-uuid placeholder otherwise, so the ACL still boots).
## Consequences
**Positive**
- §8.1 stays intact: the ACL is still the only ZGW caller; the portal only talks to the BFF; the domain
only crosses the ACL boundary. Adding a document was almost entirely additive (one gateway method, one
default, one seed block).
- One JSON contract shape across portal/BFF/domain/ACL keeps the generated client and the service
contracts uniform; the upload is exercised live (ACL integration test against real OpenZaak; the
Playwright journey uploads a real PDF).
**Negative / costs**
- Base64 inflates the payload ~33% and holds the whole file in memory at each hop — fine for a small
diploma, but not a pattern to reuse for large documents without streaming/multipart.
- The zaak is **not** set to a cancellation status when the 30-day term lapses — carved to #106 (S-10c),
which adds the cancellation statustype/resultaattype + ACL method + expiry-worker wiring.
- Providing documents before the zaak is opened silently skips storage (best-effort); the e2e/live flow
avoids this by uploading only after the openbaar register shows the zaak (INGEDIEND).
## Alternatives considered
- **Multipart on the portal→BFF hop** (proposal #107). Rejected: it splits the transport into two shapes
(multipart then JSON), needs `IFormFile` + antiforgery handling and a multipart method in the generated
client, for no benefit at diploma size.
- **The domain talks to the Documenten API directly.** Rejected outright: violates §8.1 (only the ACL
talks to ZGW).
@@ -0,0 +1,81 @@
# ADR-0019: A timed-out zaak is cancelled with a distinct status + resultaat, resolved by name
- **Status:** Accepted
- **Date:** 2026-07-21
- **Deciders:** Respellion engineering
- **Relates to:** S-10c (#106). Completes the S-10a/S-10b boundary noted in ADR-0017 (§Consequences) and
reuses the ACL close-zaak machinery from S-09b (approval) and the Documenten work in ADR-0018.
## Context
ADR-0017 (S-10a) cancels the *process* and marks the domain aggregate `Verlopen` when the 30-day
document term lapses, but explicitly deferred setting the ZGW **zaak** to a cancellation status. Left
open, a timed-out zaak stays open in OpenZaak while the register shows the registration as lapsed — the
two diverge. S-10c closes that gap: on expiry the domain must also cancel the zaak through the ACL
(§8.1, the only code that talks to ZGW).
The non-obvious part is *how to represent "cancelled" in ZGW* alongside the existing "approved" close.
The approval path (S-09b) sets the zaak's **eindstatus** (the terminal statustype) plus a resultaat. In
ZGW a zaaktype has exactly one eindstatus — the highest-`volgnummer` statustype — and setting it is what
closes the zaak (`einddatum`). A second *terminal* status would collide with that single-eindstatus rule.
## Decision
**Model cancellation as a distinct, non-terminal `Geannuleerd` statustype plus a distinct `Vervallen`
resultaat, and resolve both the approval and cancellation statustype/resultaat by their omschrijving
(name) rather than by position or the eindstatus flag alone.**
- **Seed.** `Geannuleerd` is seeded at `volgnummer` 2 — between `Ontvangen` (1) and the `Afgehandeld`
eindstatus (3) — so it is a *non-terminal* status and never displaces the eindstatus the approval path
resolves. A second resultaattype `Vervallen` (archiefnominatie `vernietigen`) is seeded beside the
approval `Geregistreerd` (`blijvend_bewaren`); both draw their `selectielijstklasse` from the
zaaktype's single `selectielijstProcestype` so they validate on publish.
- **The ACL owns the mapping.** `OpenZaakGateway.SetZaakToCancellationStatusAsync` resolves `Geannuleerd`
+ `Vervallen` by omschrijving and POSTs the resultaat then the status (OpenZaak requires a resultaat
before a closing/terminal status), mirroring `SetZaakToEindstatusAsync`. Exposed as
`AclService.CancelZaakAsync` behind the ACL endpoint `POST /annuleringen`. The omschrijvingen live as
constants in the gateway — the ACL, not the domain, knows which ZGW status means what (§8.1).
- **Approval now resolves its resultaat by name too.** With two resultaattypen present, taking the first
is ambiguous (the Zaken API does not guarantee order), so the approval path resolves `Geregistreerd`
by omschrijving. Its statustype resolution is unchanged (still the eindstatus).
- **Domain wiring.** The `ExpireRegistrationWorker` calls `IAclClient.CancelZaakAsync(zaakUrl)` **before**
advancing the aggregate to `Verlopen` (ACL-first, mirroring approval): if the ACL call fails the job is
redelivered (§8.6) rather than leaving the aggregate `Verlopen` with an open zaak. The existing
open-state guard stops a redelivered job from cancelling twice (a second resultaat would be a 400); a
registration that lapsed before its zaak was opened has nothing to cancel.
## Consequences
**Positive**
- The domain aggregate and the ZGW zaak no longer diverge on timeout — both reflect the cancellation.
- Reuses the approval close machinery (resultaat-then-status, ACL endpoint shape, ACL-first ordering), so
the change is additive and §8 stays clean (only the ACL talks to ZGW).
- Verified at two levels: an ACL↔OpenZaak integration test asserts the live zaak reaches `Geannuleerd`
with a resultaat, and the domain verify script fires the real P30D timer and confirms the zaak is
cancelled end-to-end.
**Negative / costs**
- `Geannuleerd` is non-terminal, so the cancelled zaak's `einddatum` is not set — it carries a
cancellation status + resultaat but is not formally "closed" in ZGW. Accepted: the register reads the
domain aggregate's status, and a single eindstatus per zaaktype is a ZGW constraint we chose not to
fight. Formally closing a cancelled zaak (a second eindstatus, or reusing `Afgehandeld` with a
`Vervallen` resultaat) is a possible follow-up.
- The ACL couples to the seeded omschrijvingen (`Geregistreerd`/`Geannuleerd`/`Vervallen`) by string
constants. This mirrors the existing implicit coupling to the catalogus (zaaktype URL, eindstatus) and
is documented in the gateway.
- Renumbering `Afgehandeld` from `volgnummer` 2 to 3 means a *stale* local catalogus must have its
OpenZaak volumes reset for the change to take effect; CI reseeds a fresh catalogus each run.
## Alternatives considered
- **Shared eindstatus, distinct resultaat only** (reuse `Afgehandeld`, distinguish approval vs
cancellation purely by the resultaat). ZGW-idiomatic and would set `einddatum` on cancellation too, but
the register would show no visibly distinct cancellation *status*. Rejected in favour of the issue's
explicit "distinct statustype + resultaattype" outcome, which makes the cancellation legible in ZGW.
- **A second terminal (eindstatus) `Geannuleerd`.** Rejected: ZGW allows only one eindstatus per
zaaktype (highest volgnummer); a second terminal status would either not close the zaak or collide with
the approval eindstatus resolution.
- **Passing the target omschrijvingen from the domain.** Rejected: which ZGW status means "cancelled" is
ZGW vocabulary the ACL owns (§8.1); the domain says only "cancel this zaak".
@@ -0,0 +1,92 @@
# ADR-0020: The local stack self-seeds the zaaktype, DMN, and NRC abonnement at bring-up
- **Status:** Accepted
- **Date:** 2026-07-22
- **Deciders:** Respellion engineering
- **Relates to:** S-B04 (#110). Local-stack twin of the seeding the verify-* scripts do for CI
(`infra/run-domain-check.sh`, `infra/verify-notification-driver.py`). Superseded in part by S-27
(#113), which would let the ACL resolve its zaaktype by identificatie and remove the URL injection.
## Context
`infra/docker-compose.local.yml` is the host-browser-friendly stack (`make local`) — the one a
developer clicks through the portals with. It had drifted behind three slices, so a fresh bring-up
could not complete the flow:
1. The ACL pointed at a placeholder zaaktype (`…/00000000-…`), so zaak creation failed with OpenZaak
`400` and the registratie process stuck at `OpenZaakAanmaken` (S-05).
2. `flowable-init` deployed only `registratie.bpmn`, not `diploma-eligibility.dmn`, so completing
`WachtOpDocumenten` 404'd on the missing decision and never reached `Beoordelen` (S-10a/S-13).
3. No NRC abonnement was registered, so notifications reached NRC and went nowhere — the projection
and the openbaar register stayed empty (S-06).
The CI stack (`infra/docker-compose.yml`) does not hit this because its `verify-*` scripts seed the
zaaktype, deploy the DMN, and register the abonnement at *test* time. The local stack has no such
harness — a developer just runs `make local` and browses. The non-obvious wrinkle is (1): the
zaaktype **UUID is assigned by OpenZaak at creation**, so the ACL's zaaktype URL is not knowable when
the compose file is written and cannot be a static value.
## Decision
**Make the local stack self-seed at bring-up via one-shot init containers, and hand the ACL its
server-assigned zaaktype URL through a shared-volume env file it sources on startup.**
- **DMN (gap 2).** `flowable-init` now deploys `diploma-eligibility.dmn` to the DMN engine
(`/flowable-rest/dmn-api/dmn-repository/deployments`) as a separate deployment alongside the BPMN —
identical to the CI `flowable-init`. Idempotent.
- **Zaaktype + ACL wiring (gap 1).** A `local-seed` one-shot runs the existing
`infra/openzaak/seed_catalogus.py` (`OZ_PUBLISH=1`) against OpenZaak and writes the resulting
`Acl__Defaults__ZaaktypeUrl` / `…InformatieobjecttypeUrl` / `Acl__OpenZaak__BaseUrl` into
`seed-env:/out/acl.env`. The ACL mounts that volume read-only and overrides its entrypoint to
`sh -c 'set -a; . /seed/acl.env; set +a; exec dotnet Acl.Api.dll'`, so the real values override the
compose placeholders before the app reads config. The ACL `depends_on: local-seed
(service_completed_successfully)`.
- **Abonnement (gap 3).** A `nrc-subscribe` one-shot registers an abonnement on the `zaken` kanaal
pointing at the event-subscriber's `/notifications` callback (`infra/local/register-abonnement.py`).
It is a leaf — nothing depends on it — so it can wait for the event-subscriber without forming a
cycle with the ACL bootstrap.
- **Reach OpenZaak/NRC by container IP, not service name.** Both the seed's ZTC calls and the
abonnement's `callbackUrl` are validated by Django's URLValidator, which rejects a single-label host
like `openzaak` / `event-subscriber`. The scripts resolve the target's container IP at runtime (as
`infra/run-domain-check.sh` does), keeping the seeded URLs valid **and** host-consistent — the ACL's
base URL is set to the same OpenZaak IP that owns the zaaktype URL.
- **Acceptance.** `make verify-local` (`infra/run-local-flow-check.sh`) submits against a fresh stack
and asserts the zaak opens, the case reaches the werkbak after documents, and the reference appears
in the openbaar register — the red-to-green test for all three gaps.
## Consequences
**Positive**
- A fresh `make local` completes the full demo (submit → werkbak → openbaar) with no manual seeding —
the slice's stated outcome.
- Reuses the proven CI mechanisms (`seed_catalogus.py`, the DMN deploy, the abonnement driver) rather
than inventing new ones; the only genuinely new piece is the entrypoint-sourced env file.
- No service code changes — the fix is entirely in `infra/` (compose + two small scripts), so the ACL
image and the CI stack are untouched.
**Negative / costs**
- The two compose files diverge further: the CI stack seeds at test time, the local stack at bring-up.
Mitigated by reusing the same underlying scripts and cross-referencing them.
- The ACL entrypoint override couples the local ACL to the seed-written file path (`/seed/acl.env`);
if the seed fails, the ACL fails to start (loud, healthcheck-visible — preferred over silently
running with a placeholder).
- Container-IP-based URLs are re-derived on each bring-up; a keep-volumes restart with a changed
OpenZaak IP relies on OpenZaak rebuilding hyperlinked URLs from the request host (it does) so the
idempotent re-seed reports current-IP URLs.
## Alternatives considered
- **ACL resolves its zaaktype by identificatie (`BIG-REGISTRATIE`) at startup.** The cleaner,
less-brittle design — no server-assigned URL to capture — and it would help the CI stack too. But it
changes a service's runtime behaviour and its config contract, needs new ACL tests + mutation
coverage, and still needs a seed step to *create* the zaaktype. Deliberately split out as its own
slice with its own ADR (S-27 / #113) rather than folded into this infra-only fix.
- **A documented `make local-seed` step run after `make local`.** Smallest change, but it fails the
slice's "no manual seeding" outcome — the local stack is exactly the one meant to just work in a
browser. Rejected.
- **Fixed zaaktype UUID via OpenZaak `setup_configuration`/fixtures.** OpenZaak assigns UUIDs on POST;
declaratively creating a fully *published* zaaktype (statustypen + resultaattypen validated against
the Selectielijst + roltypen + iot relations) is not something `setup_configuration` supports
cleanly in 1.28.2. Rejected as more fragile than reusing `seed_catalogus.py`.
+75
View File
@@ -5,6 +5,33 @@ copy-pasteable walkthrough against a local `make up` stack.
--- ---
## S-B04 — `make local` completes the whole flow with no manual seeding (#110, ADR-0020)
**Outcome:** the host-browser stack (`make local`) now self-seeds at bring-up — it publishes the BIG
zaaktype and wires the ACL to it, deploys the `diploma-eligibility` DMN, and registers the NRC
abonnement — so a fresh bring-up runs submit → werkbak → openbaar without the manual seeding the
`verify-*` scripts do for CI. (Previously the process stuck at `OpenZaakAanmaken`, the werkbak stayed
empty, and the openbaar register showed nothing.)
```bash
# 1. Fresh bring-up (self-seeding init containers: local-seed, nrc-subscribe; DMN in flowable-init).
make local
# 2. Assert the whole flow works with no manual seeding — submit opens a zaak, documents route it to
# the werkbak, and the reference appears in the openbaar register:
make verify-local # → "OK — a fresh local stack completed the flow with no manual seeding ..."
# 3. Or by hand in the browser: log in at http://localhost:8140 (jan-burger / test123), submit +
# upload a PDF, then approve it in the werkbak at http://localhost:8142 (merel-behandelaar /
# test123); it shows as INGESCHREVEN in the openbaar register at http://localhost:8141.
```
> The zaaktype UUID is server-assigned, so `local-seed` writes the real URL into a shared volume as
> `acl.env` and the ACL sources it on startup (ADR-0020). The cleaner long-term fix — the ACL
> resolving its zaaktype by `identificatie` — is tracked separately as S-27 (#113).
---
## S-08d — Walking skeleton complete: browser → submit, end-to-end ## S-08d — Walking skeleton complete: browser → submit, end-to-end
**Outcome:** the self-service portal is served in the stack and the full front-of-house happy path **Outcome:** the self-service portal is served in the stack and the full front-of-house happy path
@@ -434,3 +461,51 @@ routing → `Beoordelen`), OR the `P30D` interrupting timer fires → `Registrat
> Both branches are covered by the `Een documenttermijn laten verlopen` acceptance scenarios (worker + > Both branches are covered by the `Een documenttermijn laten verlopen` acceptance scenarios (worker +
> aggregate) and unit tests; the wait completion and the 30-day timer firing are asserted live by the > aggregate) and unit tests; the wait completion and the 30-day timer firing are asserted live by the
> verify-domain check. > verify-domain check.
## S-10b — Diploma upload stored in the ZGW Documenten API (#103, ADR-0018)
The self-service "Documenten aanleveren" action (S-10a) is now a **real file upload**: after submitting,
the citizen picks a PDF and uploads it. The portal base64-encodes the file client-side and posts it to
the BFF; the BFF forwards it to the domain, which stores it via the **ACL** as a ZGW
`enkelvoudiginformatieobject` in the **Documenten (DRC) API** and relates it to the zaak — then completes
the `WachtOpDocumenten` wait so beoordeling can proceed. Per §8.1 only the ACL talks to ZGW.
```bash
make up
# 1. Log in as jan-burger / test123, submit, then — once the openbaar register shows the row —
# choose a PDF under "Documenten aanleveren" and upload it. The page confirms "aangeleverd".
open http://localhost:8140
#
# 2. Automated: the walking-skeleton e2e now uploads a real PDF before the behandelaar approves.
make verify-e2e
#
# 3. The ACL integration test proves the document is really created in the Documenten API and
# related to the zaak (against a live OpenZaak):
make verify-acl # → "Storing a diploma creates a real informatieobject related to the zaak"
```
**The path:** portal (base64) → BFF `POST /self-service/registrations/{id}/documents` → domain
`ProvideDocuments` → ACL `POST /documenten` → ZGW `enkelvoudiginformatieobjecten` +
`zaakinformatieobjecten`; the wait is then completed and the case advances to Beoordelen (§8.1, ADR-0018).
## S-10c — the ZGW zaak is cancelled when the document term lapses (#106)
When the 30-day document term lapses (S-10a), the domain no longer only marks the aggregate `Verlopen` —
it now also cancels the **ZGW zaak** through the ACL, so OpenZaak and the register agree. The zaak is set
to a distinct, non-terminal **`Geannuleerd`** status with a **`Vervallen`** resultaat (as opposed to the
approval `Afgehandeld` + `Geregistreerd`), resolved by name in the ACL (§8.1, ADR-0019).
```bash
# 1. The ACL integration test proves cancellation records the Geannuleerd status + a resultaat
# against a live OpenZaak:
make verify-acl # → "Cancelling a zaak records the geannuleerd status and a resultaat"
#
# 2. End-to-end: the domain check submits a registration, fires its 30-day timer early, and asserts
# the timeout worker both expires the registration (VERLOPEN) and cancels its zaak (Geannuleerd):
make verify-domain # → "the timed-out registration's zaak was cancelled to Geannuleerd in OpenZaak"
```
**The path:** Flowable P30D timer → `RegistratieVerlopen` job → domain `ExpireRegistrationWorker` → ACL
`POST /annuleringen` → ZGW `resultaten` + `statussen` (Geannuleerd); the aggregate then moves to
`Verlopen`. The ACL cancels the zaak **before** the aggregate is expired, so a failed ZGW call leaves the
job for redelivery rather than diverging the two (ADR-0019).
+81 -7
View File
@@ -1,7 +1,12 @@
# LOCAL development stack — runs with a plain `docker compose up`, no make / no # LOCAL development stack — runs with a plain `docker compose up`, no make / no
# seed step / no bash. Use this on a local engine (Docker Desktop on Windows or # external seed step / no bash. Use this on a local engine (Docker Desktop on Windows or
# macOS, or rootless Podman on Linux). # macOS, or rootless Podman on Linux).
# #
# Self-seeding (S-B04, #110, ADR-0020): unlike the CI stack — where the verify-* scripts seed the
# zaaktype and register the NRC abonnement at test time — this stack does that itself, via one-shot
# init containers (local-seed, nrc-subscribe) + a DMN deploy in flowable-init, so a fresh bring-up
# completes the whole flow with no manual steps. `make verify-local` asserts it.
#
# docker compose -f infra/docker-compose.local.yml up -d --build # podman # docker compose -f infra/docker-compose.local.yml up -d --build # podman
# docker compose -f infra/docker-compose.local.yml up -d --build --wait # Docker Desktop # docker compose -f infra/docker-compose.local.yml up -d --build --wait # Docker Desktop
# docker compose -f infra/docker-compose.local.yml down --volumes # docker compose -f infra/docker-compose.local.yml down --volumes
@@ -257,28 +262,65 @@ services:
restart: "no" restart: "no"
volumes: volumes:
- ../workflows/registratie.bpmn:/work/registratie.bpmn:ro,z - ../workflows/registratie.bpmn:/work/registratie.bpmn:ro,z
- ../workflows/diploma-eligibility.dmn:/work/diploma-eligibility.dmn:ro,z
command: command:
- sh - sh
- -c - -c
- | - |
base=http://flowable-rest:8080/flowable-rest/service/repository/deployments svc=http://flowable-rest:8080/flowable-rest/service/repository/deployments
until curl -sf -u rest-admin:test "$$base" >/dev/null 2>&1; do echo "waiting for flowable-rest..."; sleep 3; done dmn=http://flowable-rest:8080/flowable-rest/dmn-api/dmn-repository/deployments
if curl -s -u rest-admin:test "$$base?name=registratie" | grep -q '"name":"registratie"'; then until curl -sf -u rest-admin:test "$$svc" >/dev/null 2>&1; do echo "waiting for flowable-rest..."; sleep 3; done
echo "registratie already deployed; skip" # Deploy the DMN to the DMN engine and the BPMN to the process engine as SEPARATE deployments:
# flowable-rest does NOT cascade a .dmn bundled in a process .bar into the DMN engine, so the DMN
# must go via dmn-api. The registratie process's DMN service task then resolves the decision across
# deployments by key (S-13, ADR-0016). Without this the WachtOpDocumenten completion 404s on the
# missing decision and the case never reaches Beoordelen (S-B04). Both steps are idempotent.
if curl -s -u rest-admin:test "$$dmn" | grep -q '"name":"diploma-eligibility.dmn"'; then
echo "diploma-eligibility DMN already deployed; skip"
else else
curl -sf -u rest-admin:test -F 'file=@/work/registratie.bpmn;filename=registratie.bpmn' "$$base" >/dev/null && echo "deployed registratie" curl -sf -u rest-admin:test -F 'file=@/work/diploma-eligibility.dmn;filename=diploma-eligibility.dmn' "$$dmn" >/dev/null && echo "deployed diploma-eligibility DMN"
fi
if curl -s -u rest-admin:test "$$svc?name=registratie" | grep -q '"name":"registratie"'; then
echo "registratie BPMN already deployed; skip"
else
curl -sf -u rest-admin:test -F 'file=@/work/registratie.bpmn;filename=registratie.bpmn' "$$svc" >/dev/null && echo "deployed registratie BPMN"
fi fi
depends_on: depends_on:
flowable-rest: flowable-rest:
condition: service_started condition: service_started
networks: [cg] networks: [cg]
# ── Local bootstrap: seed the zaaktype + wire the ACL (S-B04, #110, ADR-0020) ─────────────────
# The zaaktype UUID is assigned by OpenZaak at creation, so it can't be a static value in this
# file. This one-shot seeds + publishes the BIG zaaktype (and the Diploma informatieobjecttype)
# and writes their server-assigned URLs into a shared volume as acl.env, which the ACL sources on
# startup (below). It is the local-stack equivalent of what infra/run-domain-check.sh does for CI.
# Reaches OpenZaak by its container IP because a single-label host fails OpenZaak's URLValidator.
local-seed:
image: docker.io/library/python:3-slim
restart: "no"
volumes:
- ./openzaak/seed_catalogus.py:/work/seed_catalogus.py:ro,z
- ./local/seed-zaaktype.sh:/work/seed-zaaktype.sh:ro,z
- seed-env:/out
command: ["sh", "/work/seed-zaaktype.sh"]
depends_on:
openzaak:
condition: service_healthy
networks: [cg]
# ── ACL ────────────────────────────────────────────────────────────────── # ── ACL ──────────────────────────────────────────────────────────────────
acl: acl:
build: build:
context: ../services/acl context: ../services/acl
dockerfile: Dockerfile dockerfile: Dockerfile
image: register-referentie/acl:dev image: register-referentie/acl:dev
# The base/zaaktype/informatieobjecttype below are PLACEHOLDERS. The real, server-assigned
# values are written by the local-seed one-shot into seed-env:/seed/acl.env, which the entrypoint
# sources (set -a) so they override these before the app starts (S-B04, #110, ADR-0020). Sourcing
# a runtime-generated env file is why we override the entrypoint here rather than use `env_file:`
# (which compose reads at parse time, before the seed has run).
entrypoint: ["/bin/sh", "-c", "set -a; . /seed/acl.env; set +a; exec dotnet Acl.Api.dll"]
environment: environment:
Acl__OpenZaak__BaseUrl: http://openzaak:8000/ Acl__OpenZaak__BaseUrl: http://openzaak:8000/
Acl__OpenZaak__ClientId: big-reference-seed Acl__OpenZaak__ClientId: big-reference-seed
@@ -286,9 +328,12 @@ services:
Acl__Defaults__Bronorganisatie: "517439943" Acl__Defaults__Bronorganisatie: "517439943"
Acl__Defaults__VerantwoordelijkeOrganisatie: "517439943" Acl__Defaults__VerantwoordelijkeOrganisatie: "517439943"
Acl__Defaults__Vertrouwelijkheidaanduiding: openbaar Acl__Defaults__Vertrouwelijkheidaanduiding: openbaar
Acl__Defaults__ZaaktypeUrl: ${ACL_ZAAKTYPE_URL:-http://openzaak:8000/catalogi/api/v1/zaaktypen/00000000-0000-0000-0000-000000000000} Acl__Defaults__ZaaktypeUrl: http://openzaak:8000/catalogi/api/v1/zaaktypen/00000000-0000-0000-0000-000000000000
Acl__Defaults__InformatieobjecttypeUrl: http://openzaak:8000/catalogi/api/v1/informatieobjecttypen/00000000-0000-0000-0000-000000000000
ports: ports:
- "8100:8080" - "8100:8080"
volumes:
- seed-env:/seed:ro
healthcheck: healthcheck:
test: ["CMD", "curl", "-fsS", "http://localhost:8080/health"] test: ["CMD", "curl", "-fsS", "http://localhost:8080/health"]
interval: 5s interval: 5s
@@ -298,6 +343,8 @@ services:
depends_on: depends_on:
openzaak: openzaak:
condition: service_healthy condition: service_healthy
local-seed:
condition: service_completed_successfully
networks: [cg] networks: [cg]
# ── BFF ────────────────────────────────────────────────────────────────── # ── BFF ──────────────────────────────────────────────────────────────────
@@ -400,6 +447,31 @@ services:
condition: service_healthy condition: service_healthy
networks: [cg] networks: [cg]
# ── Local bootstrap: register the NRC abonnement (S-B04, #110, ADR-0020) ──────────────────────
# Without a subscription, OpenZaak's notifications reach NRC and are delivered nowhere, so the
# projection (and the openbaar register) stay empty. This one-shot registers an abonnement on the
# `zaken` kanaal pointing at the event-subscriber's /notifications callback — the CI equivalent is
# infra/verify-notification-driver.py. The callback uses the event-subscriber's container IP (a
# single-label host fails NRC's URLValidator). It is a leaf (nothing depends on it), so it can wait
# for the event-subscriber without creating a cycle with the ACL bootstrap.
nrc-subscribe:
image: docker.io/library/python:3-slim
restart: "no"
volumes:
- ./local/register-abonnement.py:/work/register-abonnement.py:ro,z
environment:
NRC_BASE: http://nrc-web:8000
SINK_HOST: event-subscriber
SINK_PORT: "8080"
SINK_AUTH: ${NOTIFICATION_WEBHOOK_TOKEN:-Bearer big-reference-notifications}
command: ["python", "/work/register-abonnement.py"]
depends_on:
nrc-web:
condition: service_healthy
event-subscriber:
condition: service_started
networks: [cg]
projection-api: projection-api:
build: build:
context: .. context: ..
@@ -492,6 +564,8 @@ volumes:
nrc-db: nrc-db:
flowable-db: flowable-db:
projection-db: projection-db:
# Carries the seed-generated acl.env (server-assigned zaaktype URLs) from local-seed to the ACL.
seed-env:
networks: networks:
cg: cg:
+3
View File
@@ -306,6 +306,9 @@ services:
Acl__Defaults__Vertrouwelijkheidaanduiding: openbaar Acl__Defaults__Vertrouwelijkheidaanduiding: openbaar
# Override with the real zaaktype URL after running seed_catalogus.py. # Override with the real zaaktype URL after running seed_catalogus.py.
Acl__Defaults__ZaaktypeUrl: ${ACL_ZAAKTYPE_URL:-http://openzaak:8000/catalogi/api/v1/zaaktypen/00000000-0000-0000-0000-000000000000} Acl__Defaults__ZaaktypeUrl: ${ACL_ZAAKTYPE_URL:-http://openzaak:8000/catalogi/api/v1/zaaktypen/00000000-0000-0000-0000-000000000000}
# The informatieobjecttype a diploma is filed under (S-10b). Placeholder until seed_catalogus.py
# (OZ_PUBLISH=1) reports the real URL, which verify-domain injects like the zaaktype URL.
Acl__Defaults__InformatieobjecttypeUrl: ${ACL_INFORMATIEOBJECTTYPE_URL:-http://openzaak:8000/catalogi/api/v1/informatieobjecttypen/00000000-0000-0000-0000-000000000000}
ports: ports:
- "8100:8080" - "8100:8080"
healthcheck: healthcheck:
+78
View File
@@ -0,0 +1,78 @@
#!/usr/bin/env python3
"""Local-stack bootstrap (S-B04, #110, ADR-0020) — register the NRC abonnement.
Runs as the `nrc-subscribe` init container of infra/docker-compose.local.yml. Registers an
abonnement on the `zaken` kanaal pointing at the event-subscriber's /notifications callback, so
OpenZaak's notifications (zaak create + status set) reach the projection — without this the openbaar
(public) register stays empty. This is what infra/verify-notification-driver.py does for CI (minus
the test zaak it also creates).
The callback host is the event-subscriber's resolved **container IP**, not `event-subscriber`, because
NRC validates callbackUrl with Django's URLValidator (a single-label host is rejected — same reason the
zaaktype seed uses OpenZaak's IP). Idempotent + restart-safe: it removes any stale /notifications
abonnement first, then registers one for the current IP. Stdlib only.
Env: NRC_BASE, SINK_HOST, SINK_PORT, SINK_AUTH, OZ_CLIENT_ID, OZ_SECRET.
"""
import base64, hashlib, hmac, json, os, socket, sys, time, urllib.error, urllib.request
NRC = os.environ.get("NRC_BASE", "http://nrc-web:8000").rstrip("/")
SINK_HOST = os.environ.get("SINK_HOST", "event-subscriber")
SINK_PORT = os.environ.get("SINK_PORT", "8080")
SINK_AUTH = os.environ.get("SINK_AUTH", "Bearer big-reference-notifications")
CID = os.environ.get("OZ_CLIENT_ID", "big-reference-seed")
SECRET = os.environ.get("OZ_SECRET", "insecure-dev-secret-change-me")
def token():
b64 = lambda b: base64.urlsafe_b64encode(b).rstrip(b"=")
seg = (
b64(json.dumps({"alg": "HS256", "typ": "JWT"}, separators=(",", ":")).encode())
+ b"."
+ b64(json.dumps(
{"iss": CID, "iat": int(time.time()), "client_id": CID,
"user_id": "local-seed", "user_representation": "local-seed"},
separators=(",", ":")).encode())
)
return (seg + b"." + b64(hmac.new(SECRET.encode(), seg, hashlib.sha256).digest())).decode()
def call(method, url, body=None):
data = json.dumps(body).encode() if body is not None else None
req = urllib.request.Request(url, data=data, method=method, headers={
"Authorization": "Bearer " + token(),
"Content-Type": "application/json", "Accept": "application/json"})
try:
with urllib.request.urlopen(req, timeout=30) as r:
raw = r.read()
return r.status, (json.loads(raw) if raw else None)
except urllib.error.HTTPError as e:
raw = e.read()
return e.code, (json.loads(raw) if raw else None)
def main():
ip = socket.gethostbyname(SINK_HOST)
callback = f"http://{ip}:{SINK_PORT}/notifications"
# Restart-safe: drop any prior /notifications abonnement (its IP may be stale) before creating a
# fresh one for the current event-subscriber IP.
status, body = call("GET", f"{NRC}/api/v1/abonnement")
for ab in (body or []) if status == 200 else []:
if str(ab.get("callbackUrl", "")).endswith("/notifications"):
if ab.get("callbackUrl") == callback:
print(f"abonnement already current: {ab['url']}")
return
call("DELETE", ab["url"])
print(f"removed stale abonnement {ab['url']}")
status, ab = call("POST", f"{NRC}/api/v1/abonnement", {
"callbackUrl": callback, "auth": SINK_AUTH,
"kanalen": [{"naam": "zaken", "filters": {}}]})
if status != 201:
sys.exit(f"create abonnement -> {status}: {json.dumps(ab)}")
print(f"abonnement registered: {ab['url']} -> {callback}")
if __name__ == "__main__":
main()
+35
View File
@@ -0,0 +1,35 @@
#!/bin/sh
# Local-stack bootstrap (S-B04, #110, ADR-0020) — the "seed zaaktype + wire the ACL" step.
#
# Runs as the `local-seed` init container of infra/docker-compose.local.yml. It seeds + publishes
# the BIG zaaktype (and the Diploma informatieobjecttype) into OpenZaak, then writes the resulting
# **server-assigned** URLs into /out/acl.env, which the ACL entrypoint sources before starting. This
# is the local-stack equivalent of what infra/run-domain-check.sh does for CI: the zaaktype UUID is
# assigned by OpenZaak at creation, so it can't be a static value in the compose file.
#
# Why the container IP and not the `openzaak` service name: OpenZaak validates URL query params
# (e.g. ?catalogus=) with Django's URLValidator, which rejects a single-label host like `openzaak`.
# Seeding against the resolved IP keeps the seeded URLs valid AND host-consistent with the ACL, which
# we point at the same IP below. See docs/runbooks/gitea-actions-gotchas.md and ADR-0020.
set -eu
oz_ip="$(python3 -c "import socket;print(socket.gethostbyname('openzaak'))")"
OZ_BASE="http://${oz_ip}:8000"
export OZ_BASE OZ_PUBLISH=1
echo ">> seeding + publishing the BIG zaaktype at ${OZ_BASE} (idempotent)"
out="$(python3 /work/seed_catalogus.py)"
echo "$out"
zt="$(printf '%s\n' "$out" | sed -n 's/^ZAAKTYPE_URL //p' | head -1)"
iot="$(printf '%s\n' "$out" | sed -n 's/^INFORMATIEOBJECTTYPE_URL //p' | head -1)"
[ -n "$zt" ] || { echo "ERROR: seed did not report a ZAAKTYPE_URL" >&2; exit 1; }
[ -n "$iot" ] || { echo "ERROR: seed did not report an INFORMATIEOBJECTTYPE_URL" >&2; exit 1; }
# The ACL entrypoint sources this; these keys override the placeholder defaults in the compose file.
cat > /out/acl.env <<EOF
Acl__OpenZaak__BaseUrl=${OZ_BASE}/
Acl__Defaults__ZaaktypeUrl=${zt}
Acl__Defaults__InformatieobjecttypeUrl=${iot}
EOF
echo ">> wrote /out/acl.env (base=${OZ_BASE}/ zaaktype=${zt})"
+96 -13
View File
@@ -10,7 +10,7 @@ Creates (if absent):
Auth uses the JWT client provisioned by setup_configuration (see ADR-0002). Auth uses the JWT client provisioned by setup_configuration (see ADR-0002).
Stdlib only — no pip deps. Re-running is safe (matches existing by identifier). Stdlib only — no pip deps. Re-running is safe (matches existing by identifier).
""" """
import base64, hashlib, hmac, json, os, sys, time, urllib.error, urllib.request import base64, hashlib, hmac, json, os, sys, time, urllib.error, urllib.parse, urllib.request
BASE = os.environ.get("OZ_BASE", "http://localhost:8000") BASE = os.environ.get("OZ_BASE", "http://localhost:8000")
CLIENT_ID = os.environ.get("OZ_CLIENT_ID", "big-reference-seed") CLIENT_ID = os.environ.get("OZ_CLIENT_ID", "big-reference-seed")
@@ -77,8 +77,12 @@ def publish_zaaktype(zt):
Selectielijst `selectielijstklasse` whose procestype matches the zaaktype's Selectielijst `selectielijstklasse` whose procestype matches the zaaktype's
`selectielijstProcestype`, plus a `resultaattypeomschrijving`. `selectielijstProcestype`, plus a `resultaattypeomschrijving`.
""" """
# Ontvangen (begin) → Afgehandeld (eind, highest volgnummer). "Geannuleerd" (S-10c) sits between
# them: a non-terminal status the document-timeout branch sets, so it never displaces the Afgehandeld
# eindstatus the approval path resolves. Keyed by volgnummer on a fresh catalogus (CI reseeds); a
# stale local stack must reset its OpenZaak volumes for the renumbering to take effect.
have_st = {s.get("volgnummer") for s in find(f"/statustypen?zaaktype={zt['url']}&status=alles")} have_st = {s.get("volgnummer") for s in find(f"/statustypen?zaaktype={zt['url']}&status=alles")}
for volgnummer, omschrijving in [(1, "Ontvangen"), (2, "Afgehandeld")]: for volgnummer, omschrijving in [(1, "Ontvangen"), (2, "Geannuleerd"), (3, "Afgehandeld")]:
if volgnummer not in have_st: if volgnummer not in have_st:
st, body = api("POST", "/statustypen", { st, body = api("POST", "/statustypen", {
"omschrijving": omschrijving, "zaaktype": zt["url"], "volgnummer": volgnummer}) "omschrijving": omschrijving, "zaaktype": zt["url"], "volgnummer": volgnummer})
@@ -95,25 +99,42 @@ def publish_zaaktype(zt):
sys.exit(f"create roltype -> {st}: {json.dumps(body, indent=2)}") sys.exit(f"create roltype -> {st}: {json.dumps(body, indent=2)}")
print("create roltype Aanvrager") print("create roltype Aanvrager")
if find(f"/resultaattypen?zaaktype={zt['url']}&status=alles"): # Two resultaattypen, keyed by omschrijving so each is created independently (idempotent):
print("skip resultaattype Geregistreerd") # "Geregistreerd" — the approval outcome (S-09b)
# "Vervallen" — the document-timeout cancellation outcome (S-10c)
# Both selectielijstklassen must share the zaaktype's selectielijstProcestype, so pick two
# Selectielijst resultaten from a single procestype and set that procestype on the zaaktype.
have_rt = {r.get("omschrijving") for r in find(f"/resultaattypen?zaaktype={zt['url']}&status=alles")}
wanted = [("Geregistreerd", "blijvend_bewaren"), ("Vervallen", "vernietigen")]
if all(naam in have_rt for naam, _ in wanted):
print("skip resultaattypen Geregistreerd + Vervallen")
else: else:
resultaat = selectielijst("/resultaten?pageSize=1")["results"][0] # Anchor on the procestype of an arbitrary resultaat, then fetch that procestype's resultaten so
# both klassen validate against the zaaktype's selectielijstProcestype.
procestype = selectielijst("/resultaten?pageSize=1")["results"][0]["procesType"]
resultaten = selectielijst(f"/resultaten?procesType={urllib.parse.quote(procestype, safe='')}")["results"]
if len(resultaten) < len(wanted):
sys.exit(f"selectielijst procestype has too few resultaten ({len(resultaten)}) for {len(wanted)} resultaattypen")
omschrijvingen = selectielijst("/resultaattypeomschrijvingen") omschrijvingen = selectielijst("/resultaattypeomschrijvingen")
oms = (omschrijvingen if isinstance(omschrijvingen, list) else omschrijvingen["results"])[0]["url"] oms_list = omschrijvingen if isinstance(omschrijvingen, list) else omschrijvingen["results"]
# The selectielijstklasse and the zaaktype must share a procestype.
st, body = api("PATCH", zt["url"], {"selectielijstProcestype": resultaat["procesType"]}) st, body = api("PATCH", zt["url"], {"selectielijstProcestype": procestype})
if st != 200: if st != 200:
sys.exit(f"set procestype -> {st}: {json.dumps(body, indent=2)}") sys.exit(f"set procestype -> {st}: {json.dumps(body, indent=2)}")
for i, (naam, archiefnominatie) in enumerate(wanted):
if naam in have_rt:
print(f"skip resultaattype {naam}")
continue
st, body = api("POST", "/resultaattypen", { st, body = api("POST", "/resultaattypen", {
"zaaktype": zt["url"], "omschrijving": "Geregistreerd", "zaaktype": zt["url"], "omschrijving": naam,
"resultaattypeomschrijving": oms, "selectielijstklasse": resultaat["url"], "resultaattypeomschrijving": oms_list[i]["url"], "selectielijstklasse": resultaten[i]["url"],
"archiefnominatie": "blijvend_bewaren", "archiefnominatie": archiefnominatie,
"brondatumArchiefprocedure": {"afleidingswijze": "afgehandeld"}, "brondatumArchiefprocedure": {"afleidingswijze": "afgehandeld"},
}) })
if st != 201: if st != 201:
sys.exit(f"create resultaattype -> {st}: {json.dumps(body, indent=2)}") sys.exit(f"create resultaattype {naam} -> {st}: {json.dumps(body, indent=2)}")
print("create resultaattype Geregistreerd") print(f"create resultaattype {naam}")
if zt.get("concept", True): if zt.get("concept", True):
st, body = api("POST", f"{zt['url']}/publish") st, body = api("POST", f"{zt['url']}/publish")
@@ -124,6 +145,58 @@ def publish_zaaktype(zt):
print("skip publish (already published)") print("skip publish (already published)")
def seed_informatieobjecttype(cat, zt):
"""Create the "Diploma" informatieobjecttype and relate it to the zaaktype (both idempotent).
A diploma uploaded in S-10b is filed under this informatieobjecttype; OpenZaak only accepts a
document (and its zaak relation) once the informatieobjecttype is published AND allowed for the
zaak's zaaktype (a zaaktype-informatieobjecttype relation). Both the relation and this call must run
while the zaaktype is still a concept, so seed this *before* publishing the zaaktype. Returns the
informatieobjecttype dict.
"""
iots = [i for i in find(f"/informatieobjecttypen?catalogus={cat['url']}&status=alles")
if i.get("omschrijving") == "Diploma"]
if iots:
iot = iots[0]
print(f"skip informatieobjecttype Diploma ({iot['url']}) concept={iot.get('concept')}")
else:
st, iot = api("POST", "/informatieobjecttypen", {
"catalogus": cat["url"],
"omschrijving": "Diploma",
"vertrouwelijkheidaanduiding": "openbaar",
"informatieobjectcategorie": "diploma",
"beginGeldigheid": "2026-01-01",
})
if st != 201:
sys.exit(f"create informatieobjecttype -> {st}: {json.dumps(iot, indent=2)}")
print(f"create informatieobjecttype Diploma ({iot['url']})")
# Relate it to the zaaktype (must be done while both are concept).
relations = find(f"/zaaktype-informatieobjecttypen?zaaktype={zt['url']}&status=alles")
if any(r.get("informatieobjecttype") == iot["url"] for r in relations):
print("skip zaaktype-informatieobjecttype Diploma")
else:
st, body = api("POST", "/zaaktype-informatieobjecttypen", {
"zaaktype": zt["url"], "informatieobjecttype": iot["url"],
"volgnummer": 1, "richting": "inkomend"})
if st != 201:
sys.exit(f"relate zaaktype-informatieobjecttype -> {st}: {json.dumps(body, indent=2)}")
print("create zaaktype-informatieobjecttype Diploma")
return iot
def publish_informatieobjecttype(iot):
"""Publish the informatieobjecttype (idempotent) so documents may reference it."""
if iot.get("concept", True):
st, body = api("POST", f"{iot['url']}/publish")
if st != 200:
sys.exit(f"publish informatieobjecttype -> {st}: {json.dumps(body, indent=2)}")
print(f"publish informatieobjecttype Diploma ({iot['url']})")
else:
print("skip publish informatieobjecttype (already published)")
def main(): def main():
# 1. Catalogus # 1. Catalogus
existing = [c for c in find(f"/catalogussen?domein=BIG") if c.get("domein") == "BIG"] existing = [c for c in find(f"/catalogussen?domein=BIG") if c.get("domein") == "BIG"]
@@ -198,10 +271,16 @@ def main():
# schema-mandatory" zaaktype S-01 asks for (ADR-0002). Set OZ_PUBLISH=1 to add # schema-mandatory" zaaktype S-01 asks for (ADR-0002). Set OZ_PUBLISH=1 to add
# those relations and publish — needed so a real zaak POST is accepted, which # those relations and publish — needed so a real zaak POST is accepted, which
# the ACL integration test (S-04a, #46) exercises. See ADR-0006. # the ACL integration test (S-04a, #46) exercises. See ADR-0006.
iot = None
if PUBLISH: if PUBLISH:
# Re-fetch: the bsn-eigenschap branch above may hold a stale concept flag. # Re-fetch: the bsn-eigenschap branch above may hold a stale concept flag.
zt = next(z for z in find(f"/zaaktypen?catalogus={cat['url']}&status=alles") zt = next(z for z in find(f"/zaaktypen?catalogus={cat['url']}&status=alles")
if z.get("identificatie") == "BIG-REGISTRATIE") if z.get("identificatie") == "BIG-REGISTRATIE")
# Seed + relate the Diploma informatieobjecttype (S-10b) while the zaaktype is still concept,
# then publish both. Publish the informatieobjecttype before the zaaktype so the zaaktype's
# relations reference a published type.
iot = seed_informatieobjecttype(cat, zt)
publish_informatieobjecttype(iot)
publish_zaaktype(zt) publish_zaaktype(zt)
# 5. Verify the JWT client can list the zaaktype (concepts included). # 5. Verify the JWT client can list the zaaktype (concepts included).
@@ -214,6 +293,10 @@ def main():
# zaaktype URL to configure the ACL's default-fill (ADR-0003/0009). # zaaktype URL to configure the ACL's default-fill (ADR-0003/0009).
zt_url = next(z["url"] for z in zaaktypen if z.get("identificatie") == "BIG-REGISTRATIE") zt_url = next(z["url"] for z in zaaktypen if z.get("identificatie") == "BIG-REGISTRATIE")
print(f"ZAAKTYPE_URL {zt_url}") print(f"ZAAKTYPE_URL {zt_url}")
# Machine-readable informatieobjecttype URL (S-10b) so callers can configure the ACL's document
# default-fill. Only emitted when publishing — a concept informatieobjecttype can't back a document.
if iot is not None:
print(f"INFORMATIEOBJECTTYPE_URL {iot['url']}")
print(f"OK — BIG catalogus seeded (BIG-REGISTRATIE {state} + bsn eigenschap)") print(f"OK — BIG catalogus seeded (BIG-REGISTRATIE {state} + bsn eigenschap)")
+56 -7
View File
@@ -33,13 +33,18 @@ echo ">> openzaak=$oz_ip domain=$dom_ip network=$net"
echo ">> seeding a published BIG zaaktype (idempotent) and capturing its URL" echo ">> seeding a published BIG zaaktype (idempotent) and capturing its URL"
sid="$(docker create --network "$net" -e "OZ_BASE=$oz_base" -e OZ_PUBLISH=1 python:3-slim python /seed.py)" sid="$(docker create --network "$net" -e "OZ_BASE=$oz_base" -e OZ_PUBLISH=1 python:3-slim python /seed.py)"
docker cp "$here/openzaak/seed_catalogus.py" "$sid:/seed.py" >/dev/null docker cp "$here/openzaak/seed_catalogus.py" "$sid:/seed.py" >/dev/null
zt_url="$(docker start -a "$sid" | sed -n 's/^ZAAKTYPE_URL //p' | head -1)" seed_out="$(docker start -a "$sid")"
zt_url="$(printf '%s\n' "$seed_out" | sed -n 's/^ZAAKTYPE_URL //p' | head -1)"
iot_url="$(printf '%s\n' "$seed_out" | sed -n 's/^INFORMATIEOBJECTTYPE_URL //p' | head -1)"
docker rm -f "$sid" >/dev/null docker rm -f "$sid" >/dev/null
[ -n "$zt_url" ] || { echo "ERROR: seed did not report a ZAAKTYPE_URL" >&2; exit 1; } [ -n "$zt_url" ] || { echo "ERROR: seed did not report a ZAAKTYPE_URL" >&2; exit 1; }
[ -n "$iot_url" ] || { echo "ERROR: seed did not report an INFORMATIEOBJECTTYPE_URL" >&2; exit 1; }
echo ">> zaaktype: $zt_url" echo ">> zaaktype: $zt_url"
echo ">> informatieobjecttype: $iot_url"
echo ">> recreating the acl service pointed at the seeded zaaktype (host-consistent)" echo ">> recreating the acl service pointed at the seeded zaaktype + informatieobjecttype (host-consistent)"
ACL_ZAAKTYPE_URL="$zt_url" ACL_OPENZAAK_BASEURL="$oz_base/" docker compose -f "$compose" up -d acl ACL_ZAAKTYPE_URL="$zt_url" ACL_INFORMATIEOBJECTTYPE_URL="$iot_url" ACL_OPENZAAK_BASEURL="$oz_base/" \
docker compose -f "$compose" up -d acl
WAIT_TIMEOUT="${WAIT_TIMEOUT:-120}" bash "$here/wait-healthy.sh" acl WAIT_TIMEOUT="${WAIT_TIMEOUT:-120}" bash "$here/wait-healthy.sh" acl
echo ">> submitting a registration to the domain" echo ">> submitting a registration to the domain"
@@ -304,10 +309,11 @@ done
[ -n "$escalated" ] || { echo "FAIL — Beoordelen task not reassigned to teamlead (candidate groups: '$groups')" >&2; docker logs "$dom" 2>&1 | tail -15 >&2; exit 1; } [ -n "$escalated" ] || { echo "FAIL — Beoordelen task not reassigned to teamlead (candidate groups: '$groups')" >&2; docker logs "$dom" 2>&1 | tail -15 >&2; exit 1; }
echo "OK — the 14-day timer escalated the still-open Beoordelen task to the teamlead" echo "OK — the 14-day timer escalated the still-open Beoordelen task to the teamlead"
# ── S-10a: document timeout. A registration parks at WachtOpDocumenten and — unlike every block above — # ── S-10a/S-10c: document timeout. A registration parks at WachtOpDocumenten and — unlike every block
# its documents never arrive. We fire its 30-day boundary timer early via the management API; the # above — its documents never arrive. We fire its 30-day boundary timer early via the management API;
# INTERRUPTING timer cancels the wait and routes a token to the RegistratieVerlopen external task. The # the INTERRUPTING timer cancels the wait and routes a token to the RegistratieVerlopen external task.
# domain's timeout worker acquires it and expires the registration to VERLOPEN (ADR-0017). ──────────── # The domain's timeout worker acquires it, cancels the ZGW zaak via the ACL (S-10c), and expires the
# registration to VERLOPEN (ADR-0017). ─────────────────────────────────────────────────────────────
echo ">> submitting a registration to let its document term lapse" echo ">> submitting a registration to let its document term lapse"
locv="$(docker run --rm --network "$net" curlimages/curl:latest \ locv="$(docker run --rm --network "$net" curlimages/curl:latest \
-fsS -D - -o /dev/null -X POST "http://$dom_ip:8080/registrations" \ -fsS -D - -o /dev/null -X POST "http://$dom_ip:8080/registrations" \
@@ -349,4 +355,47 @@ for _ in $(seq 1 30); do
done done
[ -n "$verlopen" ] || { echo "FAIL — registration $reg_idv not VERLOPEN after the document timer fired (body: $body)" >&2; docker logs "$dom" 2>&1 | tail -15 >&2; exit 1; } [ -n "$verlopen" ] || { echo "FAIL — registration $reg_idv not VERLOPEN after the document timer fired (body: $body)" >&2; docker logs "$dom" 2>&1 | tail -15 >&2; exit 1; }
echo "OK — the 30-day document timer expired the registration to VERLOPEN" echo "OK — the 30-day document timer expired the registration to VERLOPEN"
# S-10c: the worker cancels the ZGW zaak (ACL-first, before it expires the aggregate), so a VERLOPEN
# registration must carry a zaak whose current status is "Geannuleerd". Read it back from OpenZaak with
# a ZGW token minted like the seed's client (the same client OpenZaak trusts for this stack).
zaak_url_v="$(printf '%s' "$body" | grep -oiE 'http://[^"]*/zaken/api/v1/zaken/[a-f0-9-]+' | head -1)"
[ -n "$zaak_url_v" ] || { echo "FAIL — VERLOPEN registration $reg_idv exposes no zaak URL (body: $body)" >&2; exit 1; }
echo ">> confirming the zaak $zaak_url_v reached the Geannuleerd status in OpenZaak"
read_zaak_status() {
# -i so the heredoc reaches `python -` on the container's stdin (without it the script is empty).
docker run --rm -i --network "$net" \
-e OZ_CLIENT_ID="${OZ_CLIENT_ID:-big-reference-seed}" \
-e OZ_SECRET="${OZ_SECRET:-insecure-dev-secret-change-me}" \
python:3-slim python - "$1" <<'PY'
import base64, hashlib, hmac, json, os, sys, time, urllib.request
cid, sec = os.environ["OZ_CLIENT_ID"], os.environ["OZ_SECRET"]
b64 = lambda b: base64.urlsafe_b64encode(b).rstrip(b"=")
def token():
hdr = {"alg": "HS256", "typ": "JWT"}
pl = {"iss": cid, "iat": int(time.time()), "client_id": cid, "user_id": "verify", "user_representation": "verify"}
seg = b64(json.dumps(hdr, separators=(",", ":")).encode()) + b"." + b64(json.dumps(pl, separators=(",", ":")).encode())
return (seg + b"." + b64(hmac.new(sec.encode(), seg, hashlib.sha256).digest())).decode()
def get(url):
req = urllib.request.Request(url, headers={
"Authorization": "Bearer " + token(), "Accept": "application/json", "Accept-Crs": "EPSG:4326"})
with urllib.request.urlopen(req, timeout=30) as r:
return json.loads(r.read())
zaak = get(sys.argv[1])
status_url = zaak.get("status")
if not status_url:
print(""); sys.exit(0)
print(get(get(status_url)["statustype"]).get("omschrijving", ""))
PY
}
geannuleerd=""
for _ in $(seq 1 15); do
oms="$(read_zaak_status "$zaak_url_v" 2>/dev/null | tr -d '\r' || true)"
[ "$oms" = "Geannuleerd" ] && { geannuleerd=1; break; }
sleep 2
done
[ -n "$geannuleerd" ] || { echo "FAIL — zaak $zaak_url_v not Geannuleerd after timeout (current status omschrijving: '$oms')" >&2; docker logs "$dom" 2>&1 | tail -15 >&2; exit 1; }
echo "OK — the timed-out registration's zaak was cancelled to Geannuleerd in OpenZaak"
exit 0 exit 0
+67
View File
@@ -0,0 +1,67 @@
#!/usr/bin/env bash
#
# Acceptance check for the local stack (S-B04, #110): a fresh `make local` must complete the whole
# flow with NO manual seeding. Run against an already-up local stack (infra/docker-compose.local.yml)
# via the host-published ports. It exercises, and thereby covers, the three bring-up gaps the slice
# fixes:
#
# 1. zaaktype seeded + ACL wired -> a submitted registration opens a zaak (zaakUrl gets filled).
# 2. diploma-eligibility DMN deployed -> providing documents completes WachtOpDocumenten, routes
# through the DMN, and the case lands on Beoordelen (visible in the behandel werkbak).
# 3. NRC abonnement registered -> the zaak shows up in the openbaar (public) register.
#
# Before the fix this fails at step 1 (ACL points at a placeholder zaaktype -> OpenZaak 400).
set -euo pipefail
DOM=${DOM:-http://localhost:8130} # domain
BFF=${BFF:-http://localhost:8080} # bff (openbaar register)
BSN=${BSN:-123456782}
# A minimal, valid PDF, base64-encoded (the diploma upload).
PDF_B64="$(printf '%%PDF-1.4\n1 0 obj<</Type/Catalog>>endobj\ntrailer<</Root 1 0 R>>\n%%%%EOF\n' | base64 | tr -d '\n')"
echo ">> 1. submit a registration (no manual seeding expected)"
loc="$(curl -fsS -D - -o /dev/null -X POST "$DOM/registrations" \
-H 'Content-Type: application/json' -d "{\"bsn\":\"$BSN\"}" \
| sed -n 's/\r$//; s/^[Ll]ocation: //p' | head -1)"
[ -n "$loc" ] || { echo "FAIL: POST /registrations returned no Location" >&2; exit 1; }
id="${loc##*/}"
echo " accepted: $id"
echo ">> 2. poll until the ACL opens the zaak (proves the zaaktype is seeded + wired)"
zaak=""
for _ in $(seq 1 30); do
zaak="$(curl -fsS "$DOM$loc" | python3 -c 'import sys,json;print(json.load(sys.stdin).get("zaakUrl") or "")' 2>/dev/null || true)"
[ -n "$zaak" ] && break
sleep 3
done
[ -n "$zaak" ] || { echo "FAIL: zaak never opened — ACL zaaktype not wired (gap 1)" >&2; exit 1; }
echo " zaak opened: $zaak"
echo ">> 3. provide documents (proves the diploma-eligibility DMN is deployed)"
code="$(curl -s -o /dev/null -w '%{http_code}' -X POST "$DOM/registrations/$id/documents" \
-H 'Content-Type: application/json' \
-d "{\"bsn\":\"$BSN\",\"contentBase64\":\"$PDF_B64\",\"fileName\":\"diploma.pdf\",\"contentType\":\"application/pdf\"}")"
[ "$code" = "204" ] || { echo "FAIL: provide documents -> $code (DMN missing routes WachtOpDocumenten to a 404 — gap 2)" >&2; exit 1; }
echo " documents accepted (204)"
echo ">> 4. poll the werkbak until the registration awaits beoordeling (reached Beoordelen)"
in_werkbak=""
for _ in $(seq 1 20); do
in_werkbak="$(curl -fsS "$DOM/behandel/werkbak" | python3 -c "import sys,json;print(any(r.get('registrationId')=='$id' for r in json.load(sys.stdin)))" 2>/dev/null || true)"
[ "$in_werkbak" = "True" ] && break
sleep 3
done
[ "$in_werkbak" = "True" ] || { echo "FAIL: registration never reached the werkbak (gap 2)" >&2; exit 1; }
echo " in the werkbak"
echo ">> 5. poll the openbaar register until the reference is publicly visible (proves NRC abonnement)"
public=""
for _ in $(seq 1 30); do
public="$(curl -fsS "$BFF/openbaar/register" | python3 -c "import sys,json;print(any(r.get('reference')=='$id' for r in json.load(sys.stdin)))" 2>/dev/null || true)"
[ "$public" = "True" ] && break
sleep 3
done
[ "$public" = "True" ] || { echo "FAIL: reference never appeared in the openbaar register — NRC abonnement not registered (gap 3)" >&2; exit 1; }
echo " visible in the openbaar register"
echo "OK — a fresh local stack completed the flow with no manual seeding (zaaktype + DMN + abonnement)"
+19 -7
View File
@@ -35,6 +35,14 @@ export interface OpenbaarEntry {
reference: string | null; reference: string | null;
} }
export interface ProvideDocumentsRequest {
contentBase64: string;
/** @nullable */
fileName?: string | null;
/** @nullable */
contentType?: string | null;
}
export interface SubmitAccepted { export interface SubmitAccepted {
registrationId: string; registrationId: string;
status: string; status: string;
@@ -226,15 +234,19 @@ export class BffApiV1Service {
); );
} }
postSelfServiceRegistrationsIdDocuments<TData = void>(id: string, options?: HttpClientBodyOptions): Observable<TData>; postSelfServiceRegistrationsIdDocuments<TData = void>(id: string,
postSelfServiceRegistrationsIdDocuments<TData = void>(id: string, options?: HttpClientEventOptions): Observable<HttpEvent<TData>>; provideDocumentsRequest: ProvideDocumentsRequest, options?: HttpClientBodyOptions): Observable<TData>;
postSelfServiceRegistrationsIdDocuments<TData = void>(id: string, options?: HttpClientResponseOptions): Observable<AngularHttpResponse<TData>>; postSelfServiceRegistrationsIdDocuments<TData = void>(id: string,
provideDocumentsRequest: ProvideDocumentsRequest, options?: HttpClientEventOptions): Observable<HttpEvent<TData>>;
postSelfServiceRegistrationsIdDocuments<TData = void>(id: string,
provideDocumentsRequest: ProvideDocumentsRequest, options?: HttpClientResponseOptions): Observable<AngularHttpResponse<TData>>;
postSelfServiceRegistrationsIdDocuments<TData = void>( postSelfServiceRegistrationsIdDocuments<TData = void>(
id: string, options?: HttpClientObserveOptions): Observable<TData | HttpEvent<TData> | AngularHttpResponse<TData>> { id: string,
provideDocumentsRequest: ProvideDocumentsRequest, options?: HttpClientObserveOptions): Observable<TData | HttpEvent<TData> | AngularHttpResponse<TData>> {
if (options?.observe === 'events') { if (options?.observe === 'events') {
return this.http.post<TData>( return this.http.post<TData>(
`/self-service/registrations/${id}/documents`, `/self-service/registrations/${id}/documents`,
undefined,{ provideDocumentsRequest,{
...(options as Omit<NonNullable<typeof options>, 'observe'>), ...(options as Omit<NonNullable<typeof options>, 'observe'>),
observe: 'events', observe: 'events',
} }
@@ -244,7 +256,7 @@ export class BffApiV1Service {
if (options?.observe === 'response') { if (options?.observe === 'response') {
return this.http.post<TData>( return this.http.post<TData>(
`/self-service/registrations/${id}/documents`, `/self-service/registrations/${id}/documents`,
undefined,{ provideDocumentsRequest,{
...(options as Omit<NonNullable<typeof options>, 'observe'>), ...(options as Omit<NonNullable<typeof options>, 'observe'>),
observe: 'response', observe: 'response',
} }
@@ -253,7 +265,7 @@ export class BffApiV1Service {
return this.http.post<TData>( return this.http.post<TData>(
`/self-service/registrations/${id}/documents`, `/self-service/registrations/${id}/documents`,
undefined,{ provideDocumentsRequest,{
...(options as Omit<NonNullable<typeof options>, 'observe'>), ...(options as Omit<NonNullable<typeof options>, 'observe'>),
observe: 'body', observe: 'body',
} }
+21
View File
@@ -32,6 +32,14 @@ app.MapPost("/statussen", async (SetStatusRequest body, AclService acl, Cancella
return Results.NoContent(); return Results.NoContent();
}); });
// Cancel a zaak on document-timeout expiry (S-10c): set it to its zaaktype's cancellation statustype
// + resultaat. The domain hands over only the zaak URL; the ACL owns the ZGW resolution (§8.1).
app.MapPost("/annuleringen", async (CancelZaakRequest body, AclService acl, CancellationToken ct) =>
{
await acl.CancelZaakAsync(new Uri(body.ZaakUrl), ct);
return Results.NoContent();
});
// Read a zaak's public-safe reference (its identificatie). The Event Subscriber calls this to enrich // Read a zaak's public-safe reference (its identificatie). The Event Subscriber calls this to enrich
// the read projection without reading ZGW itself (§8.1, #78). // the read projection without reading ZGW itself (§8.1, #78).
app.MapPost("/zaken/reference", async (ZaakReferenceRequest body, AclService acl, CancellationToken ct) => app.MapPost("/zaken/reference", async (ZaakReferenceRequest body, AclService acl, CancellationToken ct) =>
@@ -40,12 +48,25 @@ app.MapPost("/zaken/reference", async (ZaakReferenceRequest body, AclService acl
return Results.Ok(new { reference }); return Results.Ok(new { reference });
}); });
// Store an uploaded diploma against a zaak (S-10b): the domain sends the file as base64; the ACL
// creates the ZGW enkelvoudiginformatieobject and relates it to the zaak (§8.1). Returns its URL.
app.MapPost("/documenten", async (StoreDocumentRequest body, AclService acl, CancellationToken ct) =>
{
var url = await acl.StoreDiplomaAsync(
new Uri(body.ZaakUrl), Convert.FromBase64String(body.ContentBase64), body.FileName, body.ContentType, ct);
return Results.Ok(new { informatieobjectUrl = url.ToString() });
});
app.Run(); app.Run();
public sealed record OpenZaakRequest(string Bsn, string Reference); public sealed record OpenZaakRequest(string Bsn, string Reference);
public sealed record SetStatusRequest(string ZaakUrl); public sealed record SetStatusRequest(string ZaakUrl);
public sealed record CancelZaakRequest(string ZaakUrl);
public sealed record ZaakReferenceRequest(string ZaakUrl); public sealed record ZaakReferenceRequest(string ZaakUrl);
public sealed record StoreDocumentRequest(string ZaakUrl, string ContentBase64, string FileName, string ContentType);
public partial class Program; public partial class Program;
@@ -7,4 +7,8 @@ public sealed class AclDefaults
public required string VerantwoordelijkeOrganisatie { get; init; } public required string VerantwoordelijkeOrganisatie { get; init; }
public required string Vertrouwelijkheidaanduiding { get; init; } public required string Vertrouwelijkheidaanduiding { get; init; }
public required Uri ZaaktypeUrl { get; init; } public required Uri ZaaktypeUrl { get; init; }
/// <summary>The informatieobjecttype an uploaded diploma is filed under (S-10b). Seeded in the
/// catalogus and injected like <see cref="ZaaktypeUrl"/>.</summary>
public required Uri InformatieobjecttypeUrl { get; init; }
} }
@@ -30,6 +30,18 @@ public sealed class AclService(IZaakGateway gateway, AclDefaults defaults, ICloc
return gateway.SetZaakToEindstatusAsync(zaakUrl, defaults.ZaaktypeUrl, clock.Today, ct); return gateway.SetZaakToEindstatusAsync(zaakUrl, defaults.ZaaktypeUrl, clock.Today, ct);
} }
/// <summary>
/// Cancel a zaak on document-timeout expiry (S-10c): set it to the configured BIG zaaktype's
/// cancellation statustype + resultaat. The domain hands over only the zaak URL; the ACL owns which
/// statustype/resultaat means "cancelled" (§8.1).
/// </summary>
public Task CancelZaakAsync(Uri zaakUrl, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(zaakUrl);
return gateway.SetZaakToCancellationStatusAsync(zaakUrl, defaults.ZaaktypeUrl, clock.Today, ct);
}
/// <summary>The zaak's reference (its ZGW identificatie), for the read projection (#78).</summary> /// <summary>The zaak's reference (its ZGW identificatie), for the read projection (#78).</summary>
public Task<string> GetZaakReferenceAsync(Uri zaakUrl, CancellationToken ct = default) public Task<string> GetZaakReferenceAsync(Uri zaakUrl, CancellationToken ct = default)
{ {
@@ -37,4 +49,33 @@ public sealed class AclService(IZaakGateway gateway, AclDefaults defaults, ICloc
return gateway.GetZaakIdentificatieAsync(zaakUrl, ct); return gateway.GetZaakIdentificatieAsync(zaakUrl, ct);
} }
/// <summary>
/// Store an uploaded diploma against the zaak (S-10b): default-fill the ZGW-mandatory document
/// fields (informatieobjecttype, bronorganisatie, vertrouwelijkheidaanduiding, taal, creatiedatum)
/// and hand the file to the gateway, which creates the informatieobject and relates it to the zaak.
/// The domain supplies only the zaak, the bytes, and the file's name/type (§8.1).
/// </summary>
public Task<Uri> StoreDiplomaAsync(Uri zaakUrl, byte[] content, string fileName, string contentType, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(zaakUrl);
ArgumentNullException.ThrowIfNull(content);
ArgumentException.ThrowIfNullOrWhiteSpace(fileName);
ArgumentException.ThrowIfNullOrWhiteSpace(contentType);
var request = new DocumentRequest(
defaults.Bronorganisatie,
defaults.InformatieobjecttypeUrl,
defaults.Vertrouwelijkheidaanduiding,
zaakUrl,
clock.Today,
Titel: "Diploma",
Auteur: "zorgprofessional",
Taal: "nld",
Bestandsnaam: fileName,
Formaat: contentType,
Inhoud: content);
return gateway.StoreDocumentAsync(request, ct);
}
} }
@@ -0,0 +1,17 @@
namespace Acl.Application;
/// <summary>The fully default-filled diploma document the gateway will create in the ZGW Documenten
/// API and relate to the zaak (S-10b). <see cref="Inhoud"/> is the raw file content; the gateway
/// base64-encodes it into the ZGW <c>inhoud</c> field.</summary>
public sealed record DocumentRequest(
string Bronorganisatie,
Uri Informatieobjecttype,
string Vertrouwelijkheidaanduiding,
Uri Zaak,
DateOnly Creatiedatum,
string Titel,
string Auteur,
string Taal,
string Bestandsnaam,
string Formaat,
byte[] Inhoud);
@@ -13,7 +13,23 @@ public interface IZaakGateway
/// </summary> /// </summary>
Task SetZaakToEindstatusAsync(Uri zaakUrl, Uri zaaktypeUrl, DateOnly datumStatusGezet, CancellationToken ct = default); Task SetZaakToEindstatusAsync(Uri zaakUrl, Uri zaaktypeUrl, DateOnly datumStatusGezet, CancellationToken ct = default);
/// <summary>
/// Set the given zaak to the <em>cancellation</em> statustype ("Geannuleerd") and record the
/// matching cancellation resultaat ("Vervallen") — the ZGW translation of "the 30-day document term
/// lapsed" (S-10c). Distinct from <see cref="SetZaakToEindstatusAsync"/> (approval): the gateway
/// resolves both the cancellation statustype and resultaattype from the catalogus by their
/// omschrijving, POSTs the resultaat then the status, dated <paramref name="datumStatusGezet"/>.
/// </summary>
Task SetZaakToCancellationStatusAsync(Uri zaakUrl, Uri zaaktypeUrl, DateOnly datumStatusGezet, CancellationToken ct = default);
/// <summary>Read the zaak's <c>identificatie</c> — the public-safe reference the register shows. /// <summary>Read the zaak's <c>identificatie</c> — the public-safe reference the register shows.
/// The Event Subscriber calls this through the ACL rather than reading ZGW itself (§8.1, #78).</summary> /// The Event Subscriber calls this through the ACL rather than reading ZGW itself (§8.1, #78).</summary>
Task<string> GetZaakIdentificatieAsync(Uri zaakUrl, CancellationToken ct = default); Task<string> GetZaakIdentificatieAsync(Uri zaakUrl, CancellationToken ct = default);
/// <summary>
/// Store a diploma document (S-10b): create an <c>enkelvoudiginformatieobject</c> in the ZGW
/// Documenten API and relate it to the zaak via a <c>zaakinformatieobject</c>. Returns the URL of
/// the created informatieobject.
/// </summary>
Task<Uri> StoreDocumentAsync(DocumentRequest request, CancellationToken ct = default);
} }
@@ -8,6 +8,12 @@ namespace Acl.Infrastructure;
/// <summary>The only code that talks to OpenZaak's Zaken API (ADR-0001).</summary> /// <summary>The only code that talks to OpenZaak's Zaken API (ADR-0001).</summary>
public sealed class OpenZaakGateway(HttpClient http, OpenZaakOptions options) : IZaakGateway public sealed class OpenZaakGateway(HttpClient http, OpenZaakOptions options) : IZaakGateway
{ {
// The ACL owns which ZGW statustype/resultaat carries each domain outcome (§8.1). These
// omschrijvingen match the seeded BIG catalogus (infra/openzaak/seed_catalogus.py).
private const string GeregistreerdResultaat = "Geregistreerd"; // approval outcome
private const string GeannuleerdStatus = "Geannuleerd"; // document-timeout cancellation status (S-10c)
private const string VervallenResultaat = "Vervallen"; // document-timeout cancellation outcome (S-10c)
public async Task<Uri> OpenZaakAsync(ZaakRequest request, CancellationToken ct = default) public async Task<Uri> OpenZaakAsync(ZaakRequest request, CancellationToken ct = default)
{ {
ArgumentNullException.ThrowIfNull(request); ArgumentNullException.ThrowIfNull(request);
@@ -48,7 +54,9 @@ public sealed class OpenZaakGateway(HttpClient http, OpenZaakOptions options) :
ArgumentNullException.ThrowIfNull(zaaktypeUrl); ArgumentNullException.ThrowIfNull(zaaktypeUrl);
var eindstatus = await ResolveEindstatusAsync(zaaktypeUrl, ct); var eindstatus = await ResolveEindstatusAsync(zaaktypeUrl, ct);
var resultaattype = await ResolveResultaattypeAsync(zaaktypeUrl, ct); // Resolve the approval resultaat by name: once S-10c adds the Vervallen resultaattype, taking
// the first would be ambiguous (the Zaken API does not guarantee order).
var resultaattype = await ResolveResultaattypeByOmschrijvingAsync(zaaktypeUrl, GeregistreerdResultaat, ct);
// OpenZaak refuses to set a zaak's eindstatus unless the zaak has a resultaat // OpenZaak refuses to set a zaak's eindstatus unless the zaak has a resultaat
// ("resultaat-does-not-exist"), so record the resultaat first, then the status. // ("resultaat-does-not-exist"), so record the resultaat first, then the status.
@@ -62,6 +70,27 @@ public sealed class OpenZaakGateway(HttpClient http, OpenZaakOptions options) :
"Setting the zaak status", ct); "Setting the zaak status", ct);
} }
public async Task SetZaakToCancellationStatusAsync(Uri zaakUrl, Uri zaaktypeUrl, DateOnly datumStatusGezet, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(zaakUrl);
ArgumentNullException.ThrowIfNull(zaaktypeUrl);
// Distinct from approval: resolve the cancellation statustype + resultaat by name (Geannuleerd
// is a non-terminal statustype, so it is never the eindstatus the approval path resolves).
var cancellationStatus = await ResolveStatustypeByOmschrijvingAsync(zaaktypeUrl, GeannuleerdStatus, ct);
var cancellationResultaat = await ResolveResultaattypeByOmschrijvingAsync(zaaktypeUrl, VervallenResultaat, ct);
// As with approval, OpenZaak wants the resultaat recorded before the status.
await PostAsync("/zaken/api/v1/resultaten",
new ResultaatDto(zaakUrl.ToString(), cancellationResultaat.ToString()),
"Setting the zaak cancellation resultaat", ct);
await PostAsync("/zaken/api/v1/statussen",
new StatusDto(zaakUrl.ToString(), cancellationStatus.ToString(),
datumStatusGezet.ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc).ToString("yyyy-MM-ddTHH:mm:ssZ")),
"Setting the zaak cancellation status", ct);
}
public async Task<string> GetZaakIdentificatieAsync(Uri zaakUrl, CancellationToken ct = default) public async Task<string> GetZaakIdentificatieAsync(Uri zaakUrl, CancellationToken ct = default)
{ {
ArgumentNullException.ThrowIfNull(zaakUrl); ArgumentNullException.ThrowIfNull(zaakUrl);
@@ -80,6 +109,39 @@ public sealed class OpenZaakGateway(HttpClient http, OpenZaakOptions options) :
return zaak.Identificatie; return zaak.Identificatie;
} }
public async Task<Uri> StoreDocumentAsync(DocumentRequest request, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(request);
// 1. Create the enkelvoudiginformatieobject in the Documenten API (not a geo API — no CRS).
var created = await PostForUrlAsync(
"/documenten/api/v1/enkelvoudiginformatieobjecten",
new EnkelvoudigInformatieobjectDto(
request.Bronorganisatie,
request.Creatiedatum.ToString("yyyy-MM-dd"),
request.Titel,
request.Auteur,
request.Taal,
request.Informatieobjecttype.ToString(),
Convert.ToBase64String(request.Inhoud),
request.Bestandsnaam,
request.Inhoud.Length,
request.Vertrouwelijkheidaanduiding,
request.Formaat,
"definitief",
// No usage-rights restrictions apply. Left null, OpenZaak rejects closing the related
// zaak with "indicatiegebruiksrecht-unset"; false records the deliberate "none" answer.
false),
"Creating the informatieobject", ct);
// 2. Relate it to the zaak (Zaken API — no CRS).
await PostAsync("/zaken/api/v1/zaakinformatieobjecten",
new ZaakInformatieobjectDto(request.Zaak.ToString(), created.ToString()),
"Relating the informatieobject to the zaak", ct);
return created;
}
// POSTs a non-geo ZGW resource (resultaat/status — no CRS headers). Buffers the body so uwsgi gets // POSTs a non-geo ZGW resource (resultaat/status — no CRS headers). Buffers the body so uwsgi gets
// a Content-Length instead of a chunked body (as with zaak-create). // a Content-Length instead of a chunked body (as with zaak-create).
private async Task PostAsync(string path, object dto, string action, CancellationToken ct) private async Task PostAsync(string path, object dto, string action, CancellationToken ct)
@@ -96,6 +158,26 @@ public sealed class OpenZaakGateway(HttpClient http, OpenZaakOptions options) :
await EnsureSuccessAsync(response, action, ct); await EnsureSuccessAsync(response, action, ct);
} }
// POSTs a non-geo ZGW resource and returns the created resource's URL (as PostAsync, but reads back
// the `url` of the created object). Buffers the body so uwsgi gets a Content-Length.
private async Task<Uri> PostForUrlAsync(string path, object dto, string action, CancellationToken ct)
{
using var message = new HttpRequestMessage(HttpMethod.Post, new Uri(options.BaseUrl, path))
{
Content = JsonContent.Create(dto),
};
message.Headers.Authorization =
new AuthenticationHeaderValue("Bearer", ZgwToken.Mint(options.ClientId, options.Secret));
await message.Content.LoadIntoBufferAsync(ct);
using var response = await http.SendAsync(message, ct);
await EnsureSuccessAsync(response, action, ct);
var created = await response.Content.ReadFromJsonAsync<CreatedDto>(ct)
?? throw new InvalidOperationException($"OpenZaak returned an empty response for {action}");
return new Uri(created.Url);
}
// EnsureSuccessStatusCode discards the response body; ZGW returns a JSON problem detail on 400 that // EnsureSuccessStatusCode discards the response body; ZGW returns a JSON problem detail on 400 that
// is essential for diagnosing a rejected request, so surface it in the exception. // is essential for diagnosing a rejected request, so surface it in the exception.
private static async Task EnsureSuccessAsync(HttpResponseMessage response, string action, CancellationToken ct) private static async Task EnsureSuccessAsync(HttpResponseMessage response, string action, CancellationToken ct)
@@ -121,13 +203,23 @@ public sealed class OpenZaakGateway(HttpClient http, OpenZaakOptions options) :
return new Uri(eindstatus.Url); return new Uri(eindstatus.Url);
} }
/// <summary>Resolve the zaaktype's resultaattype from the catalogus (the seed defines one).</summary> /// <summary>Resolve a specific statustype from the catalogus by its omschrijving (e.g. "Geannuleerd").</summary>
private async Task<Uri> ResolveResultaattypeAsync(Uri zaaktypeUrl, CancellationToken ct) private async Task<Uri> ResolveStatustypeByOmschrijvingAsync(Uri zaaktypeUrl, string omschrijving, CancellationToken ct)
{
var page = await GetCatalogusAsync<StatustypePage>("statustypen", zaaktypeUrl, "statustypen", ct);
var match = (page.Results ?? []).FirstOrDefault(s => s.Omschrijving == omschrijving)
?? throw new InvalidOperationException($"No '{omschrijving}' statustype found for zaaktype {zaaktypeUrl}");
return new Uri(match.Url);
}
/// <summary>Resolve a specific resultaattype from the catalogus by its omschrijving (the seed defines
/// "Geregistreerd" for approval and "Vervallen" for a document-timeout cancellation).</summary>
private async Task<Uri> ResolveResultaattypeByOmschrijvingAsync(Uri zaaktypeUrl, string omschrijving, CancellationToken ct)
{ {
var page = await GetCatalogusAsync<ResultaattypePage>("resultaattypen", zaaktypeUrl, "resultaattypen", ct); var page = await GetCatalogusAsync<ResultaattypePage>("resultaattypen", zaaktypeUrl, "resultaattypen", ct);
var resultaattype = (page.Results ?? []).FirstOrDefault() var match = (page.Results ?? []).FirstOrDefault(r => r.Omschrijving == omschrijving)
?? throw new InvalidOperationException($"No resultaattypen found for zaaktype {zaaktypeUrl}"); ?? throw new InvalidOperationException($"No '{omschrijving}' resultaattype found for zaaktype {zaaktypeUrl}");
return new Uri(resultaattype.Url); return new Uri(match.Url);
} }
// GETs a catalogus collection filtered by zaaktype (status=alles includes concept + published). // GETs a catalogus collection filtered by zaaktype (status=alles includes concept + published).
@@ -171,7 +263,8 @@ public sealed class OpenZaakGateway(HttpClient http, OpenZaakOptions options) :
private sealed record StatustypeDto( private sealed record StatustypeDto(
[property: JsonPropertyName("url")] string Url, [property: JsonPropertyName("url")] string Url,
[property: JsonPropertyName("volgnummer")] int Volgnummer, [property: JsonPropertyName("volgnummer")] int Volgnummer,
[property: JsonPropertyName("isEindstatus")] bool IsEindstatus); [property: JsonPropertyName("isEindstatus")] bool IsEindstatus,
[property: JsonPropertyName("omschrijving")] string? Omschrijving);
private sealed record ResultaatDto( private sealed record ResultaatDto(
[property: JsonPropertyName("zaak")] string Zaak, [property: JsonPropertyName("zaak")] string Zaak,
@@ -181,5 +274,28 @@ public sealed class OpenZaakGateway(HttpClient http, OpenZaakOptions options) :
[property: JsonPropertyName("results")] IReadOnlyList<ResultaattypeDto>? Results); [property: JsonPropertyName("results")] IReadOnlyList<ResultaattypeDto>? Results);
private sealed record ResultaattypeDto( private sealed record ResultaattypeDto(
[property: JsonPropertyName("url")] string Url,
[property: JsonPropertyName("omschrijving")] string? Omschrijving);
private sealed record CreatedDto(
[property: JsonPropertyName("url")] string Url); [property: JsonPropertyName("url")] string Url);
private sealed record EnkelvoudigInformatieobjectDto(
[property: JsonPropertyName("bronorganisatie")] string Bronorganisatie,
[property: JsonPropertyName("creatiedatum")] string Creatiedatum,
[property: JsonPropertyName("titel")] string Titel,
[property: JsonPropertyName("auteur")] string Auteur,
[property: JsonPropertyName("taal")] string Taal,
[property: JsonPropertyName("informatieobjecttype")] string Informatieobjecttype,
[property: JsonPropertyName("inhoud")] string Inhoud,
[property: JsonPropertyName("bestandsnaam")] string Bestandsnaam,
[property: JsonPropertyName("bestandsomvang")] int Bestandsomvang,
[property: JsonPropertyName("vertrouwelijkheidaanduiding")] string Vertrouwelijkheidaanduiding,
[property: JsonPropertyName("formaat")] string Formaat,
[property: JsonPropertyName("status")] string Status,
[property: JsonPropertyName("indicatieGebruiksrecht")] bool IndicatieGebruiksrecht);
private sealed record ZaakInformatieobjectDto(
[property: JsonPropertyName("zaak")] string Zaak,
[property: JsonPropertyName("informatieobject")] string Informatieobject);
} }
@@ -77,6 +77,18 @@ public sealed class OpenZaakFixture : IDisposable
return JsonDocument.Parse(json).RootElement.Clone(); return JsonDocument.Parse(json).RootElement.Clone();
} }
/// <summary>The URL of the published "Diploma" informatieobjecttype (S-10b), or null when the
/// stack has not been seeded with OZ_PUBLISH=1. `status=definitief` returns published types only.</summary>
public async Task<Uri?> FindPublishedDiplomaInformatieobjecttypeAsync(CancellationToken ct = default)
{
var query = new Uri(BaseUrl, "/catalogi/api/v1/informatieobjecttypen?status=definitief");
var page = await GetJsonAsync(query, ct);
foreach (var iot in page.GetProperty("results").EnumerateArray())
if (iot.TryGetProperty("omschrijving", out var o) && o.GetString() == "Diploma")
return new Uri(iot.GetProperty("url").GetString()!);
return null;
}
/// <summary>The zaaktype's eindstatus (terminal statustype) URL — the one an approval sets.</summary> /// <summary>The zaaktype's eindstatus (terminal statustype) URL — the one an approval sets.</summary>
public async Task<Uri> FindEindstatustypeAsync(Uri zaaktypeUrl, CancellationToken ct = default) public async Task<Uri> FindEindstatustypeAsync(Uri zaaktypeUrl, CancellationToken ct = default)
{ {
@@ -102,6 +114,19 @@ public sealed class OpenZaakFixture : IDisposable
return fallback ?? throw new InvalidOperationException($"No statustypen for zaaktype {zaaktypeUrl}"); return fallback ?? throw new InvalidOperationException($"No statustypen for zaaktype {zaaktypeUrl}");
} }
/// <summary>Resolve a statustype by its omschrijving (e.g. the S-10c "Geannuleerd" cancellation status).</summary>
public async Task<Uri> FindStatustypeByOmschrijvingAsync(Uri zaaktypeUrl, string omschrijving, CancellationToken ct = default)
{
var query = new Uri(BaseUrl,
"/catalogi/api/v1/statustypen?status=alles&zaaktype=" + Uri.EscapeDataString(zaaktypeUrl.ToString()));
var page = await GetJsonAsync(query, ct);
foreach (var st in page.GetProperty("results").EnumerateArray())
if (st.TryGetProperty("omschrijving", out var o) && o.GetString() == omschrijving)
return new Uri(st.GetProperty("url").GetString()!);
throw new InvalidOperationException($"No '{omschrijving}' statustype for zaaktype {zaaktypeUrl}");
}
// A ZGW (vng-api-common) HS256 JWT, mirroring the seed's client. Minted here // A ZGW (vng-api-common) HS256 JWT, mirroring the seed's client. Minted here
// rather than reusing Acl.Infrastructure's internal minter to keep that internal. // rather than reusing Acl.Infrastructure's internal minter to keep that internal.
private string MintToken() private string MintToken()
@@ -74,4 +74,91 @@ public sealed class OpenZaakGatewayIntegrationTests(OpenZaakFixture stack)
var eindstatustype = await stack.FindEindstatustypeAsync(zaaktype!); var eindstatustype = await stack.FindEindstatustypeAsync(zaaktype!);
Assert.Equal(eindstatustype.ToString(), status.GetProperty("statustype").GetString()); Assert.Equal(eindstatustype.ToString(), status.GetProperty("statustype").GetString());
} }
[Fact]
public async Task Cancelling_a_zaak_records_the_geannuleerd_status_and_a_resultaat()
{
var zaaktype = await stack.FindPublishedBigZaaktypeAsync();
Assert.True(zaaktype is not null,
"No published BIG-REGISTRATIE zaaktype found in OpenZaak — bring the stack up and " +
"seed it with OZ_PUBLISH=1 (`make integration` does this).");
var gateway = new OpenZaakGateway(stack.Http, stack.Options);
var zaakUrl = await gateway.OpenZaakAsync(new ZaakRequest(
Bronorganisatie: "517439943",
VerantwoordelijkeOrganisatie: "517439943",
Vertrouwelijkheidaanduiding: "openbaar",
Zaaktype: zaaktype!,
Startdatum: DateOnly.FromDateTime(DateTime.UtcNow),
Identificatie: Guid.NewGuid().ToString()));
await gateway.SetZaakToCancellationStatusAsync(zaakUrl, zaaktype!, DateOnly.FromDateTime(DateTime.UtcNow));
// The zaak's current status is the Geannuleerd statustype — distinct from the approval eindstatus.
var zaak = await stack.GetZaakAsync(zaakUrl);
var statusUrl = zaak.GetProperty("status").GetString();
Assert.False(string.IsNullOrEmpty(statusUrl), "the cancelled zaak has no current status");
var status = await stack.GetJsonAsync(new Uri(statusUrl!));
var geannuleerd = await stack.FindStatustypeByOmschrijvingAsync(zaaktype!, "Geannuleerd");
Assert.Equal(geannuleerd.ToString(), status.GetProperty("statustype").GetString());
// ...and a resultaat is recorded (OpenZaak requires it before a closing/terminal status).
Assert.False(string.IsNullOrEmpty(zaak.GetProperty("resultaat").GetString()),
"the cancelled zaak has no resultaat");
}
[Fact]
public async Task Storing_a_diploma_creates_a_real_informatieobject_related_to_the_zaak()
{
var zaaktype = await stack.FindPublishedBigZaaktypeAsync();
Assert.True(zaaktype is not null,
"No published BIG-REGISTRATIE zaaktype found — seed the stack with OZ_PUBLISH=1.");
var informatieobjecttype = await stack.FindPublishedDiplomaInformatieobjecttypeAsync();
Assert.True(informatieobjecttype is not null,
"No published Diploma informatieobjecttype found — seed the stack with OZ_PUBLISH=1.");
var gateway = new OpenZaakGateway(stack.Http, stack.Options);
var zaakUrl = await gateway.OpenZaakAsync(new ZaakRequest(
Bronorganisatie: "517439943",
VerantwoordelijkeOrganisatie: "517439943",
Vertrouwelijkheidaanduiding: "openbaar",
Zaaktype: zaaktype!,
Startdatum: DateOnly.FromDateTime(DateTime.UtcNow),
Identificatie: Guid.NewGuid().ToString()));
var content = System.Text.Encoding.UTF8.GetBytes("%PDF-1.4 synthetic diploma\n");
var documentUrl = await gateway.StoreDocumentAsync(new DocumentRequest(
Bronorganisatie: "517439943",
Informatieobjecttype: informatieobjecttype!,
Vertrouwelijkheidaanduiding: "openbaar",
Zaak: zaakUrl,
Creatiedatum: DateOnly.FromDateTime(DateTime.UtcNow),
Titel: "Diploma",
Auteur: "zorgprofessional",
Taal: "nld",
Bestandsnaam: "diploma.pdf",
Formaat: "application/pdf",
Inhoud: content));
// The gateway returns the canonical informatieobject URL...
Assert.StartsWith(
new Uri(stack.BaseUrl, "/documenten/api/v1/enkelvoudiginformatieobjecten/").ToString(),
documentUrl.ToString());
// ...the document is really persisted with the default-filled fields...
var doc = await stack.GetJsonAsync(documentUrl);
Assert.Equal("diploma.pdf", doc.GetProperty("bestandsnaam").GetString());
Assert.Equal(informatieobjecttype.ToString(), doc.GetProperty("informatieobjecttype").GetString());
Assert.Equal(content.Length, doc.GetProperty("bestandsomvang").GetInt32());
// indicatieGebruiksrecht is recorded as "no restrictions"; left null, OpenZaak would refuse to
// close the zaak this document is related to (the S-10b regression that broke the e2e flow).
Assert.False(doc.GetProperty("indicatieGebruiksrecht").GetBoolean());
// ...and it is related to the zaak (a zaakinformatieobject links the two).
var relations = await stack.GetJsonAsync(new Uri(stack.BaseUrl,
"/zaken/api/v1/zaakinformatieobjecten?informatieobject=" + Uri.EscapeDataString(documentUrl.ToString())));
Assert.Contains(relations.EnumerateArray(),
r => r.GetProperty("zaak").GetString() == zaakUrl.ToString());
}
} }
+83
View File
@@ -23,6 +23,14 @@ public class AclServiceTests
return Task.CompletedTask; return Task.CompletedTask;
} }
public (Uri Zaak, Uri Zaaktype, DateOnly Datum)? Cancelled;
public Task SetZaakToCancellationStatusAsync(Uri zaakUrl, Uri zaaktypeUrl, DateOnly datumStatusGezet, CancellationToken ct = default)
{
Cancelled = (zaakUrl, zaaktypeUrl, datumStatusGezet);
return Task.CompletedTask;
}
public Uri? ReadReferenceFor; public Uri? ReadReferenceFor;
public Task<string> GetZaakIdentificatieAsync(Uri zaakUrl, CancellationToken ct = default) public Task<string> GetZaakIdentificatieAsync(Uri zaakUrl, CancellationToken ct = default)
@@ -30,6 +38,15 @@ public class AclServiceTests
ReadReferenceFor = zaakUrl; ReadReferenceFor = zaakUrl;
return Task.FromResult("REG-FROM-ZAAK"); return Task.FromResult("REG-FROM-ZAAK");
} }
public DocumentRequest? StoredDocument;
public Uri DocumentResult { get; } = new("http://openzaak/documenten/api/v1/enkelvoudiginformatieobjecten/doc-1");
public Task<Uri> StoreDocumentAsync(DocumentRequest request, CancellationToken ct = default)
{
StoredDocument = request;
return Task.FromResult(DocumentResult);
}
} }
private static AclDefaults Defaults() => new() private static AclDefaults Defaults() => new()
@@ -38,6 +55,7 @@ public class AclServiceTests
VerantwoordelijkeOrganisatie = "517439943", VerantwoordelijkeOrganisatie = "517439943",
Vertrouwelijkheidaanduiding = "openbaar", Vertrouwelijkheidaanduiding = "openbaar",
ZaaktypeUrl = new("http://openzaak/catalogi/api/v1/zaaktypen/big"), ZaaktypeUrl = new("http://openzaak/catalogi/api/v1/zaaktypen/big"),
InformatieobjecttypeUrl = new("http://openzaak/catalogi/api/v1/informatieobjecttypen/dip"),
}; };
private sealed class FixedClock(DateOnly today) : IClock private sealed class FixedClock(DateOnly today) : IClock
@@ -55,6 +73,7 @@ public class AclServiceTests
VerantwoordelijkeOrganisatie = "517439943", VerantwoordelijkeOrganisatie = "517439943",
Vertrouwelijkheidaanduiding = "openbaar", Vertrouwelijkheidaanduiding = "openbaar",
ZaaktypeUrl = new("http://openzaak/catalogi/api/v1/zaaktypen/big"), ZaaktypeUrl = new("http://openzaak/catalogi/api/v1/zaaktypen/big"),
InformatieobjecttypeUrl = new("http://openzaak/catalogi/api/v1/informatieobjecttypen/dip"),
}; };
var service = new AclService(gateway, defaults, new FixedClock(new DateOnly(2026, 6, 4))); var service = new AclService(gateway, defaults, new FixedClock(new DateOnly(2026, 6, 4)));
@@ -81,6 +100,7 @@ public class AclServiceTests
VerantwoordelijkeOrganisatie = "517439943", VerantwoordelijkeOrganisatie = "517439943",
Vertrouwelijkheidaanduiding = "openbaar", Vertrouwelijkheidaanduiding = "openbaar",
ZaaktypeUrl = new("http://openzaak/catalogi/api/v1/zaaktypen/big"), ZaaktypeUrl = new("http://openzaak/catalogi/api/v1/zaaktypen/big"),
InformatieobjecttypeUrl = new("http://openzaak/catalogi/api/v1/informatieobjecttypen/dip"),
}; };
var service = new AclService(gateway, defaults, new FixedClock(new DateOnly(2026, 6, 4))); var service = new AclService(gateway, defaults, new FixedClock(new DateOnly(2026, 6, 4)));
@@ -114,6 +134,69 @@ public class AclServiceTests
Assert.Null(gateway.Approved); Assert.Null(gateway.Approved);
} }
[Fact]
public async Task Cancelling_a_zaak_sets_it_to_the_cancellation_status_dated_today()
{
var gateway = new FakeGateway();
var defaults = Defaults();
var service = new AclService(gateway, defaults, new FixedClock(new DateOnly(2026, 6, 4)));
var zaak = new Uri("http://openzaak/zaken/api/v1/zaken/abc");
await service.CancelZaakAsync(zaak);
Assert.NotNull(gateway.Cancelled);
Assert.Equal(zaak, gateway.Cancelled!.Value.Zaak);
Assert.Equal(defaults.ZaaktypeUrl, gateway.Cancelled.Value.Zaaktype);
Assert.Equal(new DateOnly(2026, 6, 4), gateway.Cancelled.Value.Datum);
// Cancellation must not touch the approval path.
Assert.Null(gateway.Approved);
}
[Fact]
public async Task Cancelling_a_null_zaak_is_rejected_without_touching_the_gateway()
{
var gateway = new FakeGateway();
var service = new AclService(gateway, Defaults(), new FixedClock(new DateOnly(2026, 6, 4)));
await Assert.ThrowsAsync<ArgumentNullException>(() => service.CancelZaakAsync(null!));
Assert.Null(gateway.Cancelled);
}
[Fact]
public async Task Storing_a_diploma_default_fills_the_document_fields_and_returns_its_url()
{
var gateway = new FakeGateway();
var defaults = Defaults();
var service = new AclService(gateway, defaults, new FixedClock(new DateOnly(2026, 6, 4)));
var zaak = new Uri("http://openzaak/zaken/api/v1/zaken/abc");
var url = await service.StoreDiplomaAsync(zaak, [1, 2, 3], "diploma.pdf", "application/pdf");
Assert.Equal(gateway.DocumentResult, url);
var req = gateway.StoredDocument!;
Assert.Equal(zaak, req.Zaak);
Assert.Equal(defaults.InformatieobjecttypeUrl, req.Informatieobjecttype);
Assert.Equal("517439943", req.Bronorganisatie);
Assert.Equal("openbaar", req.Vertrouwelijkheidaanduiding);
Assert.Equal(new DateOnly(2026, 6, 4), req.Creatiedatum);
Assert.Equal("nld", req.Taal);
Assert.Equal("diploma.pdf", req.Bestandsnaam);
Assert.Equal("application/pdf", req.Formaat);
Assert.Equal(new byte[] { 1, 2, 3 }, req.Inhoud);
}
[Fact]
public async Task Storing_a_diploma_rejects_null_or_blank_arguments()
{
var service = new AclService(new FakeGateway(), Defaults(), new FixedClock(new DateOnly(2026, 6, 4)));
var zaak = new Uri("http://openzaak/zaken/api/v1/zaken/abc");
await Assert.ThrowsAsync<ArgumentNullException>(() => service.StoreDiplomaAsync(null!, [1], "d.pdf", "application/pdf"));
await Assert.ThrowsAsync<ArgumentNullException>(() => service.StoreDiplomaAsync(zaak, null!, "d.pdf", "application/pdf"));
await Assert.ThrowsAnyAsync<ArgumentException>(() => service.StoreDiplomaAsync(zaak, [1], " ", "application/pdf"));
await Assert.ThrowsAnyAsync<ArgumentException>(() => service.StoreDiplomaAsync(zaak, [1], "d.pdf", " "));
}
[Fact] [Fact]
public async Task Reading_a_zaak_reference_returns_the_zaaks_identificatie() public async Task Reading_a_zaak_reference_returns_the_zaaks_identificatie()
{ {
+245 -2
View File
@@ -173,7 +173,8 @@ public class OpenZaakGatewayTests
private sealed class OzRoutes private sealed class OzRoutes
{ {
public string StatustypenJson { get; init; } = StatustypenPage(withEindstatusFlag: true); public string StatustypenJson { get; init; } = StatustypenPage(withEindstatusFlag: true);
public string ResultaattypenJson { get; init; } = """{"results":[{"url":"http://openzaak/catalogi/api/v1/resultaattypen/1"}]}"""; public string ResultaattypenJson { get; init; } =
"""{"results":[{"url":"http://openzaak/catalogi/api/v1/resultaattypen/1","omschrijving":"Geregistreerd"}]}""";
public HttpStatusCode StatustypenStatus { get; init; } = HttpStatusCode.OK; public HttpStatusCode StatustypenStatus { get; init; } = HttpStatusCode.OK;
public HttpStatusCode ResultaattypenStatus { get; init; } = HttpStatusCode.OK; public HttpStatusCode ResultaattypenStatus { get; init; } = HttpStatusCode.OK;
public HttpStatusCode ResultaatPostStatus { get; init; } = HttpStatusCode.Created; public HttpStatusCode ResultaatPostStatus { get; init; } = HttpStatusCode.Created;
@@ -251,6 +252,138 @@ public class OpenZaakGatewayTests
Assert.True(status.Length > 0); Assert.True(status.Length > 0);
} }
[Fact]
public async Task Approving_selects_the_geregistreerd_resultaat_by_name_when_several_exist()
{
// Once S-10c adds a second resultaattype (Vervallen), picking the first is ambiguous — the
// Zaken API does not guarantee order. Approval must resolve its resultaat by omschrijving.
var rec = new Recorder();
var twoResultaattypen = """
{"results":[
{"url":"http://openzaak/catalogi/api/v1/resultaattypen/vervallen","omschrijving":"Vervallen"},
{"url":"http://openzaak/catalogi/api/v1/resultaattypen/geregistreerd","omschrijving":"Geregistreerd"}
]}
""";
await Gateway(ApprovalStub(rec, new OzRoutes { ResultaattypenJson = twoResultaattypen }))
.SetZaakToEindstatusAsync(new Uri(ZaakUrl), Zaaktype, new DateOnly(2026, 6, 4));
Assert.Contains("\"resultaattype\":\"http://openzaak/catalogi/api/v1/resultaattypen/geregistreerd\"",
rec.Sent("/resultaten").Body);
}
// --- SetZaakToCancellationStatusAsync (document-timeout cancellation / S-10c) ---
// A catalogus with the three statustypen S-10c seeds (Geannuleerd is non-terminal, below the
// Afgehandeld eindstatus) and both resultaattypen. Cancellation must resolve "Geannuleerd" and
// "Vervallen" by omschrijving, never the approval pair.
private const string CancellationStatustypenJson = """
{"results":[
{"url":"http://openzaak/catalogi/api/v1/statustypen/ontvangen","volgnummer":1,"omschrijving":"Ontvangen","isEindstatus":false},
{"url":"http://openzaak/catalogi/api/v1/statustypen/geannuleerd","volgnummer":2,"omschrijving":"Geannuleerd","isEindstatus":false},
{"url":"http://openzaak/catalogi/api/v1/statustypen/afgehandeld","volgnummer":3,"omschrijving":"Afgehandeld","isEindstatus":true}
]}
""";
private const string CancellationResultaattypenJson = """
{"results":[
{"url":"http://openzaak/catalogi/api/v1/resultaattypen/geregistreerd","omschrijving":"Geregistreerd"},
{"url":"http://openzaak/catalogi/api/v1/resultaattypen/vervallen","omschrijving":"Vervallen"}
]}
""";
[Fact]
public async Task Cancelling_records_the_vervallen_resultaat_then_the_geannuleerd_status_against_the_zaak()
{
var rec = new Recorder();
await Gateway(ApprovalStub(rec, new OzRoutes
{
StatustypenJson = CancellationStatustypenJson,
ResultaattypenJson = CancellationResultaattypenJson,
})).SetZaakToCancellationStatusAsync(new Uri(ZaakUrl), Zaaktype, new DateOnly(2026, 6, 4));
// Resultaat precedes status (OpenZaak requires a resultaat before a closing/terminal status).
Assert.True(rec.IndexOf("/resultaten") < rec.IndexOf("/statussen"));
var resultaat = rec.Sent("/resultaten");
Assert.Contains("\"zaak\":\"" + ZaakUrl + "\"", resultaat.Body);
// The cancellation resultaat (Vervallen) is chosen by name — not the approval one (Geregistreerd).
Assert.Contains("\"resultaattype\":\"http://openzaak/catalogi/api/v1/resultaattypen/vervallen\"", resultaat.Body);
var status = rec.Sent("/statussen");
Assert.Contains("\"zaak\":\"" + ZaakUrl + "\"", status.Body);
// The Geannuleerd statustype is chosen by name — not the Afgehandeld eindstatus (approval).
Assert.Contains("\"statustype\":\"http://openzaak/catalogi/api/v1/statustypen/geannuleerd\"", status.Body);
Assert.Contains("\"datumStatusGezet\":\"2026-06-04T00:00:00Z\"", status.Body);
}
[Fact]
public async Task Cancelling_throws_when_the_zaaktype_has_no_geannuleerd_statustype()
{
var rec = new Recorder();
var ex = await Assert.ThrowsAsync<InvalidOperationException>(() =>
Gateway(ApprovalStub(rec, new OzRoutes
{
// Only the approval statustypen — no "Geannuleerd".
StatustypenJson = StatustypenPage(withEindstatusFlag: true),
ResultaattypenJson = CancellationResultaattypenJson,
})).SetZaakToCancellationStatusAsync(new Uri(ZaakUrl), Zaaktype, new DateOnly(2026, 6, 4)));
Assert.Contains("Geannuleerd", ex.Message);
}
[Fact]
public async Task Cancelling_rejects_a_null_zaak_without_calling_openzaak()
{
var handler = new StubHandler(_ => throw new InvalidOperationException("should not be sent"));
await Assert.ThrowsAsync<ArgumentNullException>(() =>
Gateway(handler).SetZaakToCancellationStatusAsync(null!, Zaaktype, new DateOnly(2026, 6, 4)));
}
[Fact]
public async Task Cancelling_rejects_a_null_zaaktype_without_calling_openzaak()
{
var handler = new StubHandler(_ => throw new InvalidOperationException("should not be sent"));
await Assert.ThrowsAsync<ArgumentNullException>(() =>
Gateway(handler).SetZaakToCancellationStatusAsync(new Uri(ZaakUrl), null!, new DateOnly(2026, 6, 4)));
}
[Fact]
public async Task Cancelling_surfaces_the_failure_when_recording_the_resultaat_is_rejected()
{
var rec = new Recorder();
var ex = await Assert.ThrowsAsync<HttpRequestException>(() =>
Gateway(ApprovalStub(rec, new OzRoutes
{
StatustypenJson = CancellationStatustypenJson,
ResultaattypenJson = CancellationResultaattypenJson,
ResultaatPostStatus = HttpStatusCode.BadRequest,
})).SetZaakToCancellationStatusAsync(new Uri(ZaakUrl), Zaaktype, new DateOnly(2026, 6, 4)));
Assert.Contains("cancellation resultaat", ex.Message);
// It fails on the resultaat, before it ever posts the status.
Assert.Equal(-1, rec.IndexOf("/statussen"));
}
[Fact]
public async Task Cancelling_surfaces_the_failure_when_recording_the_status_is_rejected()
{
var rec = new Recorder();
var ex = await Assert.ThrowsAsync<HttpRequestException>(() =>
Gateway(ApprovalStub(rec, new OzRoutes
{
StatustypenJson = CancellationStatustypenJson,
ResultaattypenJson = CancellationResultaattypenJson,
StatusPostStatus = HttpStatusCode.BadRequest,
})).SetZaakToCancellationStatusAsync(new Uri(ZaakUrl), Zaaktype, new DateOnly(2026, 6, 4)));
Assert.Contains("cancellation status", ex.Message);
}
[Fact] [Fact]
public async Task Approving_falls_back_to_the_highest_volgnummer_when_no_eindstatus_is_flagged() public async Task Approving_falls_back_to_the_highest_volgnummer_when_no_eindstatus_is_flagged()
{ {
@@ -325,7 +458,7 @@ public class OpenZaakGatewayTests
Gateway(ApprovalStub(rec, new OzRoutes { ResultaattypenJson = "{}" })) Gateway(ApprovalStub(rec, new OzRoutes { ResultaattypenJson = "{}" }))
.SetZaakToEindstatusAsync(new Uri(ZaakUrl), Zaaktype, new DateOnly(2026, 6, 4))); .SetZaakToEindstatusAsync(new Uri(ZaakUrl), Zaaktype, new DateOnly(2026, 6, 4)));
Assert.Contains("No resultaattypen found", ex.Message); Assert.Contains("'Geregistreerd' resultaattype", ex.Message);
// Resolved the eindstatus + queried resultaattypen, but posted nothing. // Resolved the eindstatus + queried resultaattypen, but posted nothing.
Assert.Equal(-1, rec.IndexOf("/resultaten")); Assert.Equal(-1, rec.IndexOf("/resultaten"));
Assert.Equal(-1, rec.IndexOf("/statussen")); Assert.Equal(-1, rec.IndexOf("/statussen"));
@@ -432,4 +565,114 @@ public class OpenZaakGatewayTests
b64 = (b64.Length % 4) switch { 2 => b64 + "==", 3 => b64 + "=", _ => b64 }; b64 = (b64.Length % 4) switch { 2 => b64 + "==", 3 => b64 + "=", _ => b64 };
return Encoding.UTF8.GetString(Convert.FromBase64String(b64)); return Encoding.UTF8.GetString(Convert.FromBase64String(b64));
} }
// --- StoreDocumentAsync (diploma upload / S-10b) ---
private static readonly Uri Informatieobjecttype =
new("http://openzaak/catalogi/api/v1/informatieobjecttypen/dip");
private static DocumentRequest SampleDocument(byte[]? inhoud = null) => new(
Bronorganisatie: "517439943",
Informatieobjecttype: Informatieobjecttype,
Vertrouwelijkheidaanduiding: "openbaar",
Zaak: new Uri(ZaakUrl),
Creatiedatum: new DateOnly(2026, 6, 4),
Titel: "Diploma",
Auteur: "zorgprofessional",
Taal: "nld",
Bestandsnaam: "diploma.pdf",
Formaat: "application/pdf",
Inhoud: inhoud ?? [1, 2, 3, 4]);
// Routes the two document calls: POST /enkelvoudiginformatieobjecten (documenten) then
// POST /zaakinformatieobjecten (zaken).
private static StubHandler DocumentStub(Recorder rec) => new(async req =>
{
rec.Requests.Add(req);
rec.ContentLengths.Add(req.Content?.Headers.ContentLength);
rec.Bodies.Add(req.Content is null ? null : await req.Content.ReadAsStringAsync());
return req.RequestUri!.ToString().Contains("/enkelvoudiginformatieobjecten")
? Json(HttpStatusCode.Created, """{"url":"http://openzaak/documenten/api/v1/enkelvoudiginformatieobjecten/doc-1"}""")
: Json(HttpStatusCode.Created, """{"url":"http://openzaak/zaken/api/v1/zaakinformatieobjecten/rel-1"}""");
});
[Fact]
public async Task Storing_a_document_creates_the_informatieobject_then_relates_it_to_the_zaak()
{
var rec = new Recorder();
var url = await Gateway(DocumentStub(rec)).StoreDocumentAsync(SampleDocument([10, 20, 30]));
Assert.Equal("http://openzaak/documenten/api/v1/enkelvoudiginformatieobjecten/doc-1", url.ToString());
// 1. Create the enkelvoudiginformatieobject in the Documenten API.
var create = rec.Sent("/enkelvoudiginformatieobjecten");
Assert.Equal(HttpMethod.Post, create.Request.Method);
Assert.Equal("http://openzaak/documenten/api/v1/enkelvoudiginformatieobjecten",
create.Request.RequestUri!.ToString());
Assert.Equal("Bearer", create.Request.Headers.Authorization!.Scheme);
Assert.Contains("\"bronorganisatie\":\"517439943\"", create.Body);
Assert.Contains("\"informatieobjecttype\":\"http://openzaak/catalogi/api/v1/informatieobjecttypen/dip\"", create.Body);
Assert.Contains("\"creatiedatum\":\"2026-06-04\"", create.Body);
Assert.Contains("\"titel\":\"Diploma\"", create.Body);
Assert.Contains("\"auteur\":\"zorgprofessional\"", create.Body);
Assert.Contains("\"taal\":\"nld\"", create.Body);
Assert.Contains("\"bestandsnaam\":\"diploma.pdf\"", create.Body);
Assert.Contains("\"formaat\":\"application/pdf\"", create.Body);
Assert.Contains("\"vertrouwelijkheidaanduiding\":\"openbaar\"", create.Body);
Assert.Contains("\"status\":\"definitief\"", create.Body);
// indicatieGebruiksrecht must be set explicitly (false = no usage restrictions); left null,
// OpenZaak refuses to close the zaak this document is related to ("indicatiegebruiksrecht-unset").
Assert.Contains("\"indicatieGebruiksrecht\":false", create.Body);
// The file content is base64-encoded into `inhoud`, with its byte length in `bestandsomvang`.
Assert.Contains($"\"inhoud\":\"{Convert.ToBase64String([10, 20, 30])}\"", create.Body);
Assert.Contains("\"bestandsomvang\":3", create.Body);
// 2. Relate that informatieobject to the zaak (Zaken API — no CRS).
var relate = rec.Sent("/zaakinformatieobjecten");
Assert.Equal(HttpMethod.Post, relate.Request.Method);
Assert.Equal("http://openzaak/zaken/api/v1/zaakinformatieobjecten",
relate.Request.RequestUri!.ToString());
Assert.Contains($"\"zaak\":\"{ZaakUrl}\"", relate.Body);
Assert.Contains("\"informatieobject\":\"http://openzaak/documenten/api/v1/enkelvoudiginformatieobjecten/doc-1\"", relate.Body);
}
[Fact]
public async Task Storing_a_document_buffers_the_body_and_sends_no_crs_headers()
{
// uwsgi rejects a chunked body (Content-Length must be present); the Documenten API is not a
// geo API, so no CRS headers (unlike the Zaken zaak-create).
var rec = new Recorder();
await Gateway(DocumentStub(rec)).StoreDocumentAsync(SampleDocument());
var create = rec.Sent("/enkelvoudiginformatieobjecten");
Assert.NotNull(create.Length);
Assert.True(create.Length > 0);
Assert.False(create.Request.Headers.Contains("Accept-Crs"));
Assert.False(create.Request.Content!.Headers.Contains("Content-Crs"));
}
[Fact]
public async Task Storing_a_document_surfaces_an_openzaak_rejection()
{
var handler = new StubHandler(_ =>
Task.FromResult(new HttpResponseMessage(HttpStatusCode.BadRequest)
{
Content = new StringContent("""{"detail":"bad"}""", Encoding.UTF8, "application/json"),
}));
var ex = await Assert.ThrowsAsync<HttpRequestException>(
() => Gateway(handler).StoreDocumentAsync(SampleDocument()));
Assert.Contains("bad", ex.Message);
}
[Fact]
public async Task Storing_a_document_rejects_a_null_request()
{
var handler = new StubHandler(_ => throw new InvalidOperationException("should not be sent"));
await Assert.ThrowsAsync<ArgumentNullException>(() => Gateway(handler).StoreDocumentAsync(null!));
}
} }
+9 -6
View File
@@ -27,10 +27,11 @@ public interface IDomainClient
/// unknown or not the caller's (404), so the BFF can relay a 404 rather than a 500.</summary> /// unknown or not the caller's (404), so the BFF can relay a 404 rather than a 500.</summary>
Task<bool> WithdrawRegistrationAsync(string registrationId, string bsn, CancellationToken ct = default); Task<bool> WithdrawRegistrationAsync(string registrationId, string bsn, CancellationToken ct = default);
/// <summary>Provide the documents the caller's own registration is waiting for ("documenten /// <summary>Provide (upload) the diploma the caller's own registration is waiting for ("documenten
/// aanleveren"). Owner-scoped by <paramref name="bsn"/>. Returns <c>false</c> when the domain /// aanleveren"). The file is carried base64-encoded. Owner-scoped by <paramref name="bsn"/>. Returns
/// reports the registration is unknown or not the caller's (404), so the BFF can relay a 404.</summary> /// <c>false</c> when the domain reports the registration is unknown or not the caller's (404).</summary>
Task<bool> ProvideDocumentsAsync(string registrationId, string bsn, CancellationToken ct = default); Task<bool> ProvideDocumentsAsync(
string registrationId, string bsn, string contentBase64, string? fileName, string? contentType, CancellationToken ct = default);
/// <summary>The behandelaar's werkbak — registrations awaiting beoordeling.</summary> /// <summary>The behandelaar's werkbak — registrations awaiting beoordeling.</summary>
Task<IReadOnlyList<WerkbakItem>> GetWerkbakAsync(CancellationToken ct = default); Task<IReadOnlyList<WerkbakItem>> GetWerkbakAsync(CancellationToken ct = default);
@@ -68,10 +69,12 @@ public sealed class DomainClient(HttpClient http) : IDomainClient
return true; return true;
} }
public async Task<bool> ProvideDocumentsAsync(string registrationId, string bsn, CancellationToken ct = default) public async Task<bool> ProvideDocumentsAsync(
string registrationId, string bsn, string contentBase64, string? fileName, string? contentType, CancellationToken ct = default)
{ {
using var response = await http.PostAsJsonAsync( using var response = await http.PostAsJsonAsync(
$"registrations/{registrationId}/documents", new { bsn }, ct); $"registrations/{registrationId}/documents",
new { bsn, contentBase64, fileName, contentType }, ct);
// The domain 404s an unknown or not-owned registration; relay that rather than fail hard. // The domain 404s an unknown or not-owned registration; relay that rather than fail hard.
if (response.StatusCode == System.Net.HttpStatusCode.NotFound) if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
return false; return false;
+8 -2
View File
@@ -109,13 +109,15 @@ app.MapPost("/self-service/registrations/{id}/withdraw", async (string id, Claim
// forwarded to the domain, which owner-scopes the action and completes the WachtOpDocumenten task; a // forwarded to the domain, which owner-scopes the action and completes the WachtOpDocumenten task; a
// registration that is unknown or not the caller's comes back 404. The real file upload + ZGW storage // registration that is unknown or not the caller's comes back 404. The real file upload + ZGW storage
// is S-10b — this is the trigger that unblocks the process. // is S-10b — this is the trigger that unblocks the process.
app.MapPost("/self-service/registrations/{id}/documents", async (string id, ClaimsPrincipal user, IDomainClient domain, CancellationToken ct) => app.MapPost("/self-service/registrations/{id}/documents", async (string id, ProvideDocumentsRequest body, ClaimsPrincipal user, IDomainClient domain, CancellationToken ct) =>
{ {
var bsn = user.FindFirstValue("bsn"); var bsn = user.FindFirstValue("bsn");
if (string.IsNullOrWhiteSpace(bsn)) if (string.IsNullOrWhiteSpace(bsn))
return Results.BadRequest("The token carries no bsn claim."); return Results.BadRequest("The token carries no bsn claim.");
if (string.IsNullOrWhiteSpace(body?.ContentBase64))
return Results.BadRequest("A document is required.");
var provided = await domain.ProvideDocumentsAsync(id, bsn, ct); var provided = await domain.ProvideDocumentsAsync(id, bsn, body.ContentBase64, body.FileName, body.ContentType, ct);
return provided ? Results.NoContent() : Results.NotFound(); return provided ? Results.NoContent() : Results.NotFound();
}) })
.RequireAuthorization() .RequireAuthorization()
@@ -163,6 +165,10 @@ app.Run();
/// <summary>The behandelaar's decision on a registration.</summary> /// <summary>The behandelaar's decision on a registration.</summary>
public sealed record DecideRequest(string Besluit); public sealed record DecideRequest(string Besluit);
/// <summary>A diploma upload from the self-service portal — the file base64-encoded client-side, with
/// its name and MIME type. The bsn is taken from the DigiD token, not this body.</summary>
public sealed record ProvideDocumentsRequest(string ContentBase64, string? FileName = null, string? ContentType = null);
// Behandel (medewerker-realm) authentication + authorization wiring (ADR-0013). // Behandel (medewerker-realm) authentication + authorization wiring (ADR-0013).
internal static class BehandelAuth internal static class BehandelAuth
{ {
+3 -3
View File
@@ -94,15 +94,15 @@ internal sealed class FakeDomainClient : IDomainClient
return Task.FromResult(WithdrawSucceeds); return Task.FromResult(WithdrawSucceeds);
} }
public (string RegistrationId, string Bsn)? DocumentsProvidedFor { get; private set; } public (string RegistrationId, string Bsn, string ContentBase64, string? FileName, string? ContentType)? DocumentsProvidedFor { get; private set; }
/// <summary>Whether the fake domain reports the provide-documents as done (true → 204) or /// <summary>Whether the fake domain reports the provide-documents as done (true → 204) or
/// not-found/not-owned (false → 404). Tests set this to exercise the relay.</summary> /// not-found/not-owned (false → 404). Tests set this to exercise the relay.</summary>
public bool ProvideDocumentsSucceeds { get; set; } = true; public bool ProvideDocumentsSucceeds { get; set; } = true;
public Task<bool> ProvideDocumentsAsync(string registrationId, string bsn, CancellationToken ct = default) public Task<bool> ProvideDocumentsAsync(string registrationId, string bsn, string contentBase64, string? fileName, string? contentType, CancellationToken ct = default)
{ {
DocumentsProvidedFor = (registrationId, bsn); DocumentsProvidedFor = (registrationId, bsn, contentBase64, fileName, contentType);
return Task.FromResult(ProvideDocumentsSucceeds); return Task.FromResult(ProvideDocumentsSucceeds);
} }
@@ -114,7 +114,17 @@ public class SelfServiceEndpointTests
private static HttpRequestMessage ProvideDocuments(string? bearer, string id = "reg-123") private static HttpRequestMessage ProvideDocuments(string? bearer, string id = "reg-123")
{ {
var request = new HttpRequestMessage(HttpMethod.Post, $"/self-service/registrations/{id}/documents"); var request = new HttpRequestMessage(HttpMethod.Post, $"/self-service/registrations/{id}/documents")
{
// The portal base64-encodes the file client-side and posts it as JSON (S-10b); the bsn is
// never in the body — it comes from the DigiD token.
Content = JsonContent.Create(new
{
contentBase64 = Convert.ToBase64String([1, 2, 3]),
fileName = "diploma.pdf",
contentType = "application/pdf",
}),
};
if (bearer is not null) if (bearer is not null)
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", bearer); request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", bearer);
return request; return request;
@@ -132,14 +142,19 @@ public class SelfServiceEndpointTests
} }
[Fact] [Fact]
public async Task Provides_documents_for_the_callers_registration_forwarding_the_id_and_bsn() public async Task Provides_documents_for_the_callers_registration_forwarding_id_bsn_and_file()
{ {
using var factory = new BffFactory(); using var factory = new BffFactory();
var response = await factory.CreateClient().SendAsync(ProvideDocuments(TestTokens.Valid("123456782"), "reg-9")); var response = await factory.CreateClient().SendAsync(ProvideDocuments(TestTokens.Valid("123456782"), "reg-9"));
Assert.Equal(HttpStatusCode.NoContent, response.StatusCode); Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);
Assert.Equal(("reg-9", "123456782"), factory.Domain.DocumentsProvidedFor); var provided = factory.Domain.DocumentsProvidedFor;
Assert.NotNull(provided);
Assert.Equal("reg-9", provided!.Value.RegistrationId);
Assert.Equal("123456782", provided.Value.Bsn);
Assert.Equal(Convert.ToBase64String([1, 2, 3]), provided.Value.ContentBase64);
Assert.Equal("diploma.pdf", provided.Value.FileName);
} }
[Fact] [Fact]
+33
View File
@@ -76,6 +76,16 @@
} }
} }
], ],
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ProvideDocumentsRequest"
}
}
},
"required": true
},
"responses": { "responses": {
"204": { "204": {
"description": "No Content" "description": "No Content"
@@ -228,6 +238,29 @@
} }
} }
}, },
"ProvideDocumentsRequest": {
"required": [
"contentBase64"
],
"type": "object",
"properties": {
"contentBase64": {
"type": "string"
},
"fileName": {
"type": [
"null",
"string"
]
},
"contentType": {
"type": [
"null",
"string"
]
}
}
},
"SubmitAccepted": { "SubmitAccepted": {
"required": [ "required": [
"registrationId", "registrationId",
+11 -2
View File
@@ -120,8 +120,17 @@ app.MapPost("/registrations/{id}/documents", async (string id, ProvideDocumentsR
if (string.IsNullOrWhiteSpace(body?.Bsn)) if (string.IsNullOrWhiteSpace(body?.Bsn))
return Results.BadRequest(new { error = "A bsn is required to provide documents." }); return Results.BadRequest(new { error = "A bsn is required to provide documents." });
if (string.IsNullOrWhiteSpace(body.ContentBase64))
return Results.BadRequest(new { error = "A document is required." });
var outcome = await provide.HandleAsync(new ProvideDocumentsCommand(new RegistrationId(guid), body.Bsn), ct); byte[] content;
try { content = Convert.FromBase64String(body.ContentBase64); }
catch (FormatException) { return Results.BadRequest(new { error = "The document content is not valid base64." }); }
var command = new ProvideDocumentsCommand(
new RegistrationId(guid), body.Bsn, content,
body.FileName ?? "diploma.pdf", body.ContentType ?? "application/pdf");
var outcome = await provide.HandleAsync(command, ct);
return outcome == ProvideDocumentsOutcome.Accepted ? Results.NoContent() : Results.NotFound(); return outcome == ProvideDocumentsOutcome.Accepted ? Results.NoContent() : Results.NotFound();
}); });
@@ -152,7 +161,7 @@ public sealed record DecideRequest(string Besluit);
public sealed record WithdrawRequest(string Bsn); public sealed record WithdrawRequest(string Bsn);
public sealed record ProvideDocumentsRequest(string Bsn); public sealed record ProvideDocumentsRequest(string Bsn, string ContentBase64, string? FileName = null, string? ContentType = null);
public sealed record RegistrationResponse(string RegistrationId, string Status, string? ZaakUrl); public sealed record RegistrationResponse(string RegistrationId, string Status, string? ZaakUrl);
@@ -9,7 +9,7 @@ namespace Big.Application;
/// nothing of Flowable. The polling loop that feeds it jobs lives in Infrastructure. Mirrors /// nothing of Flowable. The polling loop that feeds it jobs lives in Infrastructure. Mirrors
/// <see cref="OpenZaakWorker"/>. /// <see cref="OpenZaakWorker"/>.
/// </summary> /// </summary>
public sealed class ExpireRegistrationWorker(IRegistrationStore store) public sealed class ExpireRegistrationWorker(IRegistrationStore store, IAclClient acl)
{ {
/// <summary> /// <summary>
/// Process the job. Idempotent and tolerant of races (§8.6, at-least-once delivery): a job whose /// Process the job. Idempotent and tolerant of races (§8.6, at-least-once delivery): a job whose
@@ -31,6 +31,14 @@ public sealed class ExpireRegistrationWorker(IRegistrationStore store)
if (registration.Status is not (RegistrationStatus.Ingediend or RegistrationStatus.InBehandeling)) if (registration.Status is not (RegistrationStatus.Ingediend or RegistrationStatus.InBehandeling))
return; return;
// Cancel the ZGW zaak before advancing the aggregate (mirrors the approval path): if the ACL
// call fails it throws, the aggregate stays open, and the job is redelivered (§8.6) — rather
// than leaving the aggregate VERLOPEN while the zaak stays open. The status guard above stops a
// redelivered job from cancelling the zaak twice (a second resultaat would be a 400). A
// registration expired before its zaak was opened has nothing to cancel.
if (registration.ZaakUrl is not null)
await acl.CancelZaakAsync(registration.ZaakUrl, ct);
registration.Expire(); registration.Expire();
await store.SaveAsync(registration, ct); await store.SaveAsync(registration, ct);
} }
+13
View File
@@ -52,6 +52,19 @@ public interface IAclClient
/// the zaak's final status — which OpenZaak notifies over NRC; the domain never names statustypen. /// the zaak's final status — which OpenZaak notifies over NRC; the domain never names statustypen.
/// </summary> /// </summary>
Task ApproveZaakAsync(Uri zaakUrl, CancellationToken ct = default); Task ApproveZaakAsync(Uri zaakUrl, CancellationToken ct = default);
/// <summary>
/// Store an uploaded diploma against the zaak (S-10b). The domain hands over the zaak, the raw file
/// bytes, and the file's name/type; the ACL creates the ZGW informatieobject and relates it to the
/// zaak (§8.1). Returns the stored document's URL.
/// </summary>
Task<Uri> StoreDiplomaAsync(Uri zaakUrl, byte[] content, string fileName, string contentType, CancellationToken ct = default);
/// <summary>
/// Cancel the zaak on document-timeout expiry (S-10c): the 30-day document term lapsed, so the ACL
/// translates this to the ZGW cancellation status/resultaat. The domain never names statustypen.
/// </summary>
Task CancelZaakAsync(Uri zaakUrl, CancellationToken ct = default);
} }
/// <summary> /// <summary>
@@ -2,10 +2,12 @@ using Big.Domain;
namespace Big.Application; namespace Big.Application;
/// <summary>A zorgprofessional's signal that they have supplied the documents their registration is /// <summary>A zorgprofessional's upload of the diploma their registration is waiting for ("documenten
/// waiting for ("documenten aanleveren"). <paramref name="Bsn"/> is the authenticated caller (from the /// aanleveren"). <paramref name="Bsn"/> is the authenticated caller (from the DigiD token, forwarded by
/// DigiD token, forwarded by the BFF): only the registration's own bsn may provide its documents.</summary> /// the BFF): only the registration's own bsn may provide its documents. <paramref name="Content"/> is
public sealed record ProvideDocumentsCommand(RegistrationId RegistrationId, string Bsn); /// the raw file, with its <paramref name="FileName"/> and <paramref name="ContentType"/>.</summary>
public sealed record ProvideDocumentsCommand(
RegistrationId RegistrationId, string Bsn, byte[] Content, string FileName, string ContentType);
/// <summary>The outcome of a provide-documents request.</summary> /// <summary>The outcome of a provide-documents request.</summary>
public enum ProvideDocumentsOutcome public enum ProvideDocumentsOutcome
@@ -19,14 +21,14 @@ public enum ProvideDocumentsOutcome
} }
/// <summary> /// <summary>
/// The provide-documents use case (S-10a): a zorgprofessional supplies the documents their registration /// The provide-documents use case (S-10a/S-10b): a zorgprofessional uploads the diploma their
/// is parked waiting for, completing the WachtOpDocumenten task so the registratie process leaves the /// registration is parked waiting for. The document is stored in ZGW via the ACL (§8.1), then the
/// 30-day wait and continues to beoordeling (ADR-0017). Owner-scoped by bsn. Completing the wait is /// WachtOpDocumenten task is completed so the registratie process leaves the 30-day wait and continues
/// best-effort: if the registration never started a process (or already left the wait), the request /// to beoordeling (ADR-0017). Owner-scoped by bsn. Both steps are best-effort about missing preconditions
/// still stands, mirroring how <see cref="WithdrawRegistration"/> cancels best-effort. The actual file /// (mirroring <see cref="WithdrawRegistration"/>): storage needs an opened zaak, and completion needs a
/// upload and its ZGW storage via the ACL is S-10b; this is the trigger that unblocks the process. /// running process — a request that arrives before either still stands, storing/completing what it can.
/// </summary> /// </summary>
public sealed class ProvideDocuments(IRegistrationStore store, IWorkflowClient workflow) public sealed class ProvideDocuments(IRegistrationStore store, IWorkflowClient workflow, IAclClient acl)
{ {
public async Task<ProvideDocumentsOutcome> HandleAsync(ProvideDocumentsCommand command, CancellationToken ct = default) public async Task<ProvideDocumentsOutcome> HandleAsync(ProvideDocumentsCommand command, CancellationToken ct = default)
{ {
@@ -38,6 +40,11 @@ public sealed class ProvideDocuments(IRegistrationStore store, IWorkflowClient w
if (registration is null || registration.Bsn != command.Bsn) if (registration is null || registration.Bsn != command.Bsn)
return ProvideDocumentsOutcome.NotFound; return ProvideDocumentsOutcome.NotFound;
// Store the diploma against the zaak (once it is opened) — the ACL is the only ZGW caller (§8.1).
if (registration.ZaakUrl is not null)
await acl.StoreDiplomaAsync(
registration.ZaakUrl, command.Content, command.FileName, command.ContentType, ct);
// Complete the document wait (if a process is running) so beoordeling can proceed. // Complete the document wait (if a process is running) so beoordeling can proceed.
if (registration.ProcessInstanceId is not null) if (registration.ProcessInstanceId is not null)
await workflow.CompleteDocumentWaitAsync(registration.ProcessInstanceId, ct); await workflow.CompleteDocumentWaitAsync(registration.ProcessInstanceId, ct);
@@ -31,6 +31,32 @@ public sealed class AclHttpClient(HttpClient http, AclOptions options) : IAclCli
response.EnsureSuccessStatusCode(); response.EnsureSuccessStatusCode();
} }
public async Task CancelZaakAsync(Uri zaakUrl, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(zaakUrl);
using var response = await http.PostAsJsonAsync(
new Uri(options.BaseUrl, "annuleringen"), new CancelZaakRequest(zaakUrl.ToString()), ct);
response.EnsureSuccessStatusCode();
}
public async Task<Uri> StoreDiplomaAsync(Uri zaakUrl, byte[] content, string fileName, string contentType, CancellationToken ct = default)
{
ArgumentNullException.ThrowIfNull(zaakUrl);
ArgumentNullException.ThrowIfNull(content);
// The file crosses this boundary base64-encoded in JSON — the domain and ACL contracts are
// JSON, and a diploma is small (S-10b, ADR). The ACL turns it into a ZGW informatieobject.
using var response = await http.PostAsJsonAsync(
new Uri(options.BaseUrl, "documenten"),
new StoreDocumentRequest(zaakUrl.ToString(), Convert.ToBase64String(content), fileName, contentType), ct);
response.EnsureSuccessStatusCode();
var stored = await response.Content.ReadFromJsonAsync<StoreDocumentResponse>(ct)
?? throw new InvalidOperationException("The ACL returned an empty document response.");
return new Uri(stored.InformatieobjectUrl);
}
private sealed record OpenZaakRequest( private sealed record OpenZaakRequest(
[property: JsonPropertyName("bsn")] string Bsn, [property: JsonPropertyName("bsn")] string Bsn,
[property: JsonPropertyName("reference")] string Reference); [property: JsonPropertyName("reference")] string Reference);
@@ -38,4 +64,15 @@ public sealed class AclHttpClient(HttpClient http, AclOptions options) : IAclCli
private sealed record OpenZaakResponse([property: JsonPropertyName("zaakUrl")] string ZaakUrl); private sealed record OpenZaakResponse([property: JsonPropertyName("zaakUrl")] string ZaakUrl);
private sealed record SetStatusRequest([property: JsonPropertyName("zaakUrl")] string ZaakUrl); private sealed record SetStatusRequest([property: JsonPropertyName("zaakUrl")] string ZaakUrl);
private sealed record CancelZaakRequest([property: JsonPropertyName("zaakUrl")] string ZaakUrl);
private sealed record StoreDocumentRequest(
[property: JsonPropertyName("zaakUrl")] string ZaakUrl,
[property: JsonPropertyName("contentBase64")] string ContentBase64,
[property: JsonPropertyName("fileName")] string FileName,
[property: JsonPropertyName("contentType")] string ContentType);
private sealed record StoreDocumentResponse(
[property: JsonPropertyName("informatieobjectUrl")] string InformatieobjectUrl);
} }
@@ -10,10 +10,13 @@ public class ExpireRegistrationWorkerTests
{ {
private const string Bsn = "123456782"; private const string Bsn = "123456782";
private static Registration Submitted(string processInstanceId = "proc-1") // By the time the 30-day document timer fires, the zaak was opened long ago (OpenZaakAanmaken runs
// early in the flow), so a timed-out registration carries a zaak the worker can cancel.
private static Registration Submitted(string processInstanceId = "proc-1", Uri? zaakUrl = null)
{ {
var registration = Registration.Submit(Bsn); var registration = Registration.Submit(Bsn);
registration.RecordProcessStarted(processInstanceId); registration.RecordProcessStarted(processInstanceId);
registration.AttachZaak(zaakUrl ?? FakeAclClient.DefaultZaakUrl);
return registration; return registration;
} }
@@ -24,7 +27,7 @@ public class ExpireRegistrationWorkerTests
var registration = Submitted(); var registration = Submitted();
store.Seed(registration); store.Seed(registration);
await new ExpireRegistrationWorker(store).HandleAsync( await new ExpireRegistrationWorker(store, new FakeAclClient()).HandleAsync(
new RegistratieVerlopenJob("job-7", registration.Id)); new RegistratieVerlopenJob("job-7", registration.Id));
var saved = await store.GetAsync(registration.Id); var saved = await store.GetAsync(registration.Id);
@@ -33,37 +36,60 @@ public class ExpireRegistrationWorkerTests
} }
[Fact] [Fact]
public async Task An_already_verlopen_registration_is_not_persisted_again() public async Task Cancels_the_zaak_via_the_acl_when_expiring_a_still_open_registration()
{ {
// A redelivered job (§8.6) finds the aggregate already VERLOPEN: a no-op, not saved again. // S-10c: expiring the aggregate is not enough — the ZGW zaak must also be set to its
// cancellation status, which the ACL owns (§8.1). The worker hands the ACL the zaak URL.
var store = new FakeRegistrationStore();
var zaak = new Uri("http://openzaak/zaken/api/v1/zaken/timed-out");
var registration = Submitted(zaakUrl: zaak);
store.Seed(registration);
var acl = new FakeAclClient();
await new ExpireRegistrationWorker(store, acl).HandleAsync(
new RegistratieVerlopenJob("job-7", registration.Id));
Assert.Equal(1, acl.CancelCallCount);
Assert.Equal(zaak, acl.CancelledZaakUrl);
}
[Fact]
public async Task An_already_verlopen_registration_is_not_persisted_again_and_the_zaak_is_not_recancelled()
{
// A redelivered job (§8.6) finds the aggregate already VERLOPEN: a no-op, not saved again — and
// the ACL is not asked to cancel the zaak a second time (posting a second resultaat would 400).
var store = new FakeRegistrationStore(); var store = new FakeRegistrationStore();
var registration = Submitted(); var registration = Submitted();
registration.Expire(); registration.Expire();
store.Seed(registration); store.Seed(registration);
var acl = new FakeAclClient();
await new ExpireRegistrationWorker(store).HandleAsync( await new ExpireRegistrationWorker(store, acl).HandleAsync(
new RegistratieVerlopenJob("job-7", registration.Id)); new RegistratieVerlopenJob("job-7", registration.Id));
Assert.Equal(0, store.SaveCount); Assert.Equal(0, store.SaveCount);
Assert.Equal(0, acl.CancelCallCount);
Assert.Equal(RegistrationStatus.Verlopen, (await store.GetAsync(registration.Id))!.Status); Assert.Equal(RegistrationStatus.Verlopen, (await store.GetAsync(registration.Id))!.Status);
} }
[Fact] [Fact]
public async Task An_already_resolved_registration_is_left_alone_and_the_job_completes() public async Task An_already_resolved_registration_is_left_alone_and_the_zaak_is_not_cancelled()
{ {
// Race with S-11: the citizen withdrew while parked at WachtOpDocumenten, so the aggregate is // Race with S-11: the citizen withdrew while parked at WachtOpDocumenten, so the aggregate is
// already terminal (INGETROKKEN) when the timer's job arrives. Expiring it would violate the // already terminal (INGETROKKEN) when the timer's job arrives. Expiring it would violate the
// aggregate's invariant; the worker must instead no-op (and let the job complete), not throw // aggregate's invariant; the worker must instead no-op (and let the job complete), not throw
// into a redelivery loop. // into a redelivery loop — and it must not cancel the zaak of a registration it didn't expire.
var store = new FakeRegistrationStore(); var store = new FakeRegistrationStore();
var registration = Submitted(); var registration = Submitted();
registration.Withdraw(); registration.Withdraw();
store.Seed(registration); store.Seed(registration);
var acl = new FakeAclClient();
await new ExpireRegistrationWorker(store).HandleAsync( await new ExpireRegistrationWorker(store, acl).HandleAsync(
new RegistratieVerlopenJob("job-7", registration.Id)); new RegistratieVerlopenJob("job-7", registration.Id));
Assert.Equal(0, store.SaveCount); Assert.Equal(0, store.SaveCount);
Assert.Equal(0, acl.CancelCallCount);
Assert.Equal(RegistrationStatus.Ingetrokken, (await store.GetAsync(registration.Id))!.Status); Assert.Equal(RegistrationStatus.Ingetrokken, (await store.GetAsync(registration.Id))!.Status);
} }
@@ -73,12 +99,12 @@ public class ExpireRegistrationWorkerTests
var store = new FakeRegistrationStore(); var store = new FakeRegistrationStore();
await Assert.ThrowsAsync<InvalidOperationException>(() => await Assert.ThrowsAsync<InvalidOperationException>(() =>
new ExpireRegistrationWorker(store).HandleAsync( new ExpireRegistrationWorker(store, new FakeAclClient()).HandleAsync(
new RegistratieVerlopenJob("job-7", RegistrationId.New()))); new RegistratieVerlopenJob("job-7", RegistrationId.New())));
} }
[Fact] [Fact]
public async Task Rejects_a_null_job() public async Task Rejects_a_null_job()
=> await Assert.ThrowsAsync<ArgumentNullException>(() => => await Assert.ThrowsAsync<ArgumentNullException>(() =>
new ExpireRegistrationWorker(new FakeRegistrationStore()).HandleAsync(null!)); new ExpireRegistrationWorker(new FakeRegistrationStore(), new FakeAclClient()).HandleAsync(null!));
} }
+19
View File
@@ -110,4 +110,23 @@ internal sealed class FakeAclClient(Uri? zaakUrl = null) : IAclClient
ApprovedZaakUrl = zaakUrl; ApprovedZaakUrl = zaakUrl;
return Task.CompletedTask; return Task.CompletedTask;
} }
public (Uri ZaakUrl, byte[] Content, string FileName, string ContentType)? StoredDiploma { get; private set; }
public static readonly Uri DefaultDocumentUrl = new("http://openzaak/documenten/api/v1/enkelvoudiginformatieobjecten/doc");
public Task<Uri> StoreDiplomaAsync(Uri zaakUrl, byte[] content, string fileName, string contentType, CancellationToken ct = default)
{
StoredDiploma = (zaakUrl, content, fileName, contentType);
return Task.FromResult(DefaultDocumentUrl);
}
public Uri? CancelledZaakUrl { get; private set; }
public int CancelCallCount { get; private set; }
public Task CancelZaakAsync(Uri zaakUrl, CancellationToken ct = default)
{
CancelCallCount++;
CancelledZaakUrl = zaakUrl;
return Task.CompletedTask;
}
} }
@@ -3,52 +3,60 @@ using Big.Domain;
namespace Big.Tests; namespace Big.Tests;
// S-10a (#102): the "documents received" use case. A zorgprofessional supplies the documents their // S-10a/S-10b (#102/#103): the "documents received" use case. A zorgprofessional supplies the diploma
// registration is waiting for; the handler completes the WachtOpDocumenten task via the Workflow Client // their registration is waiting for; the handler stores it in ZGW via the ACL and completes the
// so the process leaves the 30-day wait and continues to beoordeling. Owner-scoped by the caller's bsn, // WachtOpDocumenten task via the Workflow Client so the process continues to beoordeling. Owner-scoped
// like WithdrawRegistration. (The real file upload + ZGW storage is S-10b; this is the trigger path.) // by the caller's bsn, like WithdrawRegistration.
public class ProvideDocumentsTests public class ProvideDocumentsTests
{ {
private const string Bsn = "123456782"; private const string Bsn = "123456782";
private static readonly Uri Zaak = new("http://openzaak/zaken/api/v1/zaken/abc");
private static Registration Submitted(string processInstanceId = "proc-1") private static Registration Submitted(string processInstanceId = "proc-1")
{ {
var registration = Registration.Submit(Bsn); var registration = Registration.Submit(Bsn);
registration.RecordProcessStarted(processInstanceId); registration.RecordProcessStarted(processInstanceId);
registration.AttachZaak(Zaak);
return registration; return registration;
} }
private static ProvideDocumentsCommand Command(RegistrationId id, string bsn = Bsn) => new(id, bsn); private static ProvideDocumentsCommand Command(RegistrationId id, string bsn = Bsn) =>
new(id, bsn, [1, 2, 3], "diploma.pdf", "application/pdf");
[Fact] [Fact]
public async Task Providing_documents_completes_the_document_wait() public async Task Providing_documents_stores_the_diploma_and_completes_the_wait()
{ {
var store = new FakeRegistrationStore(); var store = new FakeRegistrationStore();
var registration = Submitted("proc-42"); var registration = Submitted("proc-42");
store.Seed(registration); store.Seed(registration);
var workflow = new FakeWorkflowClient(); var workflow = new FakeWorkflowClient();
var handler = new ProvideDocuments(store, workflow); var acl = new FakeAclClient();
var handler = new ProvideDocuments(store, workflow, acl);
var outcome = await handler.HandleAsync(Command(registration.Id)); var outcome = await handler.HandleAsync(Command(registration.Id));
Assert.Equal(ProvideDocumentsOutcome.Accepted, outcome); Assert.Equal(ProvideDocumentsOutcome.Accepted, outcome);
// Stored against the registration's zaak, carrying the uploaded bytes + file metadata.
Assert.Equal((Zaak, new byte[] { 1, 2, 3 }, "diploma.pdf", "application/pdf"), acl.StoredDiploma);
// …and the wait is completed so beoordeling can proceed.
Assert.Equal("proc-42", workflow.CompletedDocumentWaitFor); Assert.Equal("proc-42", workflow.CompletedDocumentWaitFor);
} }
[Fact] [Fact]
public async Task A_different_bsn_cannot_provide_documents() public async Task A_different_bsn_cannot_provide_documents()
{ {
// Owner-scoping: only the registration's own bsn may supply its documents. Another bsn is told // Owner-scoping: another bsn is told NotFound; nothing is stored or completed.
// NotFound (existence not revealed) and the wait is not completed.
var store = new FakeRegistrationStore(); var store = new FakeRegistrationStore();
var registration = Submitted(); var registration = Submitted();
store.Seed(registration); store.Seed(registration);
var workflow = new FakeWorkflowClient(); var workflow = new FakeWorkflowClient();
var handler = new ProvideDocuments(store, workflow); var acl = new FakeAclClient();
var handler = new ProvideDocuments(store, workflow, acl);
var outcome = await handler.HandleAsync(Command(registration.Id, bsn: "999999990")); var outcome = await handler.HandleAsync(Command(registration.Id, bsn: "999999990"));
Assert.Equal(ProvideDocumentsOutcome.NotFound, outcome); Assert.Equal(ProvideDocumentsOutcome.NotFound, outcome);
Assert.Null(acl.StoredDiploma);
Assert.Null(workflow.CompletedDocumentWaitFor); Assert.Null(workflow.CompletedDocumentWaitFor);
} }
@@ -56,30 +64,33 @@ public class ProvideDocumentsTests
public async Task Providing_for_an_unknown_registration_is_not_found() public async Task Providing_for_an_unknown_registration_is_not_found()
{ {
var store = new FakeRegistrationStore(); var store = new FakeRegistrationStore();
var handler = new ProvideDocuments(store, new FakeWorkflowClient()); var handler = new ProvideDocuments(store, new FakeWorkflowClient(), new FakeAclClient());
Assert.Equal(ProvideDocumentsOutcome.NotFound, await handler.HandleAsync(Command(RegistrationId.New()))); Assert.Equal(ProvideDocumentsOutcome.NotFound, await handler.HandleAsync(Command(RegistrationId.New())));
} }
[Fact] [Fact]
public async Task Providing_before_a_process_started_is_accepted_without_calling_the_workflow() public async Task Providing_before_a_zaak_is_opened_does_not_store_but_still_completes_the_wait()
{ {
// No process yet → no wait task to complete; the request still stands (best-effort, mirroring // No zaak yet → nothing to file the document against, but the request still stands (best-effort,
// WithdrawRegistration) and the Workflow Client is not called. // mirroring WithdrawRegistration). The wait is completed if a process is running.
var store = new FakeRegistrationStore(); var store = new FakeRegistrationStore();
var registration = Registration.Submit(Bsn); // no RecordProcessStarted var registration = Registration.Submit(Bsn);
registration.RecordProcessStarted("proc-9"); // process started, but no zaak attached
store.Seed(registration); store.Seed(registration);
var workflow = new FakeWorkflowClient(); var workflow = new FakeWorkflowClient();
var handler = new ProvideDocuments(store, workflow); var acl = new FakeAclClient();
var handler = new ProvideDocuments(store, workflow, acl);
var outcome = await handler.HandleAsync(Command(registration.Id)); var outcome = await handler.HandleAsync(Command(registration.Id));
Assert.Equal(ProvideDocumentsOutcome.Accepted, outcome); Assert.Equal(ProvideDocumentsOutcome.Accepted, outcome);
Assert.Null(workflow.CompletedDocumentWaitFor); Assert.Null(acl.StoredDiploma);
Assert.Equal("proc-9", workflow.CompletedDocumentWaitFor);
} }
[Fact] [Fact]
public async Task Rejects_a_null_command() public async Task Rejects_a_null_command()
=> await Assert.ThrowsAsync<ArgumentNullException>(() => => await Assert.ThrowsAsync<ArgumentNullException>(() =>
new ProvideDocuments(new FakeRegistrationStore(), new FakeWorkflowClient()).HandleAsync(null!)); new ProvideDocuments(new FakeRegistrationStore(), new FakeWorkflowClient(), new FakeAclClient()).HandleAsync(null!));
} }
@@ -30,7 +30,7 @@ public class RegistratieVerlopenProcessorTests
} }
} }
private static ExpireRegistrationWorker Worker(FakeRegistrationStore store) => new(store); private static ExpireRegistrationWorker Worker(FakeRegistrationStore store) => new(store, new FakeAclClient());
[Fact] [Fact]
public async Task Acquires_a_job_expires_the_registration_and_completes_the_job() public async Task Acquires_a_job_expires_the_registration_and_completes_the_job()
@@ -14,6 +14,7 @@ Feature: Een documenttermijn laten verlopen
When the 30-day document timer fires When the 30-day document timer fires
And the document-timeout worker runs And the document-timeout worker runs
Then the registration is verlopen Then the registration is verlopen
And the zaak is cancelled in ZGW
Scenario: Tijdig aangeleverde documenten laten de registratie niet vervallen Scenario: Tijdig aangeleverde documenten laten de registratie niet vervallen
Given a registration parked at the WachtOpDocumenten task Given a registration parked at the WachtOpDocumenten task
@@ -21,3 +22,4 @@ Feature: Een documenttermijn laten verlopen
And the 30-day document timer fires And the 30-day document timer fires
And the document-timeout worker runs And the document-timeout worker runs
Then the registration is not verlopen Then the registration is not verlopen
And the zaak is not cancelled in ZGW
@@ -17,8 +17,11 @@ namespace Acceptance.Steps;
[Scope(Feature = "Een documenttermijn laten verlopen")] [Scope(Feature = "Een documenttermijn laten verlopen")]
public sealed class EenDocumentTermijnVerlopenSteps public sealed class EenDocumentTermijnVerlopenSteps
{ {
private static readonly Uri ZaakUrl = new("http://openzaak/zaken/api/v1/zaken/acc-timeout");
private readonly InMemoryDocumentTimeoutClient _flowable = new(); private readonly InMemoryDocumentTimeoutClient _flowable = new();
private readonly Support.InMemoryRegistrationStore _store = new(); private readonly Support.InMemoryRegistrationStore _store = new();
private readonly InMemoryAclClient _acl = new();
private Registration _registration = null!; private Registration _registration = null!;
private string _processInstanceId = ""; private string _processInstanceId = "";
@@ -26,6 +29,9 @@ public sealed class EenDocumentTermijnVerlopenSteps
public async Task GivenARegistrationParkedAtWachtOpDocumenten() public async Task GivenARegistrationParkedAtWachtOpDocumenten()
{ {
_registration = Registration.Submit("123456782"); _registration = Registration.Submit("123456782");
// By the time it parks at WachtOpDocumenten its zaak has been opened (OpenZaakAanmaken runs
// earlier), so a timeout has a zaak to cancel.
_registration.AttachZaak(ZaakUrl);
await _store.SaveAsync(_registration); await _store.SaveAsync(_registration);
_processInstanceId = _flowable.ParkWaitingForDocuments(_registration.Id); _processInstanceId = _flowable.ParkWaitingForDocuments(_registration.Id);
} }
@@ -39,7 +45,7 @@ public sealed class EenDocumentTermijnVerlopenSteps
[When("the document-timeout worker runs")] [When("the document-timeout worker runs")]
public async Task WhenTheTimeoutWorkerRuns() public async Task WhenTheTimeoutWorkerRuns()
=> await new RegistratieVerlopenProcessor( => await new RegistratieVerlopenProcessor(
_flowable, new ExpireRegistrationWorker(_store), _flowable, new ExpireRegistrationWorker(_store, _acl),
NullLogger<RegistratieVerlopenProcessor>.Instance).PumpOnceAsync(5); NullLogger<RegistratieVerlopenProcessor>.Instance).PumpOnceAsync(5);
[Then("the registration is verlopen")] [Then("the registration is verlopen")]
@@ -49,4 +55,10 @@ public sealed class EenDocumentTermijnVerlopenSteps
[Then("the registration is not verlopen")] [Then("the registration is not verlopen")]
public async Task ThenTheRegistrationIsNotVerlopen() public async Task ThenTheRegistrationIsNotVerlopen()
=> Assert.Equal(RegistrationStatus.Ingediend, (await _store.GetAsync(_registration.Id))!.Status); => Assert.Equal(RegistrationStatus.Ingediend, (await _store.GetAsync(_registration.Id))!.Status);
[Then("the zaak is cancelled in ZGW")]
public void ThenTheZaakIsCancelled() => Assert.Equal(ZaakUrl, _acl.CancelledZaakUrl);
[Then("the zaak is not cancelled in ZGW")]
public void ThenTheZaakIsNotCancelled() => Assert.Null(_acl.CancelledZaakUrl);
} }
@@ -30,6 +30,7 @@ public sealed class EenZaakOpenenSteps
VerantwoordelijkeOrganisatie = values["verantwoordelijkeOrganisatie"], VerantwoordelijkeOrganisatie = values["verantwoordelijkeOrganisatie"],
Vertrouwelijkheidaanduiding = values["vertrouwelijkheidaanduiding"], Vertrouwelijkheidaanduiding = values["vertrouwelijkheidaanduiding"],
ZaaktypeUrl = new Uri(values["zaaktype"]), ZaaktypeUrl = new Uri(values["zaaktype"]),
InformatieobjecttypeUrl = new Uri("http://openzaak/catalogi/api/v1/informatieobjecttypen/dip"),
}; };
} }
@@ -72,7 +72,8 @@ public sealed class CapturingDomainClient : IDomainClient
public Task<bool> WithdrawRegistrationAsync(string registrationId, string bsn, CancellationToken ct = default) public Task<bool> WithdrawRegistrationAsync(string registrationId, string bsn, CancellationToken ct = default)
=> Task.FromResult(true); => Task.FromResult(true);
public Task<bool> ProvideDocumentsAsync(string registrationId, string bsn, CancellationToken ct = default) public Task<bool> ProvideDocumentsAsync(
string registrationId, string bsn, string contentBase64, string? fileName, string? contentType, CancellationToken ct = default)
=> Task.FromResult(true); => Task.FromResult(true);
public Task<IReadOnlyList<WerkbakItem>> GetWerkbakAsync(CancellationToken ct = default) public Task<IReadOnlyList<WerkbakItem>> GetWerkbakAsync(CancellationToken ct = default)
@@ -59,6 +59,22 @@ public sealed class InMemoryAclClient : IAclClient
ApprovedZaakUrl = zaakUrl; ApprovedZaakUrl = zaakUrl;
return Task.CompletedTask; return Task.CompletedTask;
} }
public Uri? CancelledZaakUrl { get; private set; }
public Task CancelZaakAsync(Uri zaakUrl, CancellationToken ct = default)
{
CancelledZaakUrl = zaakUrl;
return Task.CompletedTask;
}
public (Uri ZaakUrl, string FileName)? StoredDiploma { get; private set; }
public Task<Uri> StoreDiplomaAsync(Uri zaakUrl, byte[] content, string fileName, string contentType, CancellationToken ct = default)
{
StoredDiploma = (zaakUrl, fileName);
return Task.FromResult(new Uri("http://openzaak/documenten/api/v1/enkelvoudiginformatieobjecten/acc-doc"));
}
} }
/// <summary>An in-memory user-task client for the beoordeling acceptance scenario: it holds one open /// <summary>An in-memory user-task client for the beoordeling acceptance scenario: it holds one open
@@ -12,6 +12,7 @@ public sealed class InMemoryZaakGateway : IZaakGateway
public ZaakRequest? Captured { get; private set; } public ZaakRequest? Captured { get; private set; }
public (Uri Zaak, Uri Zaaktype, DateOnly Datum)? Approved { get; private set; } public (Uri Zaak, Uri Zaaktype, DateOnly Datum)? Approved { get; private set; }
public (Uri Zaak, Uri Zaaktype, DateOnly Datum)? Cancelled { get; private set; }
public Task<Uri> OpenZaakAsync(ZaakRequest request, CancellationToken ct = default) public Task<Uri> OpenZaakAsync(ZaakRequest request, CancellationToken ct = default)
{ {
@@ -25,6 +26,15 @@ public sealed class InMemoryZaakGateway : IZaakGateway
return Task.CompletedTask; return Task.CompletedTask;
} }
public Task SetZaakToCancellationStatusAsync(Uri zaakUrl, Uri zaaktypeUrl, DateOnly datumStatusGezet, CancellationToken ct = default)
{
Cancelled = (zaakUrl, zaaktypeUrl, datumStatusGezet);
return Task.CompletedTask;
}
public Task<string> GetZaakIdentificatieAsync(Uri zaakUrl, CancellationToken ct = default) public Task<string> GetZaakIdentificatieAsync(Uri zaakUrl, CancellationToken ct = default)
=> Task.FromResult("ACC-REF-1"); => Task.FromResult("ACC-REF-1");
public Task<Uri> StoreDocumentAsync(DocumentRequest request, CancellationToken ct = default)
=> Task.FromResult(new Uri("http://openzaak/documenten/api/v1/enkelvoudiginformatieobjecten/acc-doc"));
} }
+13 -1
View File
@@ -12,6 +12,12 @@ export default defineConfig({
timeout: 90_000, timeout: 90_000,
expect: { timeout: 15_000 }, expect: { timeout: 15_000 },
retries: 1, retries: 1,
// Run the specs serially. Each spec drives a full `channel: 'chromium'` browser, and the e2e
// shares an 8 GB runner with the entire compose stack (OpenZaak, NRC, Keycloak, Flowable, 4×
// Postgres, every service + 3 portals). Two parallel browsers exhaust memory and the renderer is
// OOM-killed mid-action ("Page crashed") — fixing the flakiness at its source rather than leaning
// on `retries` (CLAUDE.md §15). Only two long-running happy-path specs, so serial costs little.
workers: 1,
reporter: [['list']], reporter: [['list']],
use: { use: {
baseURL, baseURL,
@@ -26,7 +32,13 @@ export default defineConfig({
// headless), not Playwright's default headless-shell, so pin `channel: 'chromium'`. // headless), not Playwright's default headless-shell, so pin `channel: 'chromium'`.
channel: 'chromium', channel: 'chromium',
launchOptions: { launchOptions: {
args: [`--unsafely-treat-insecure-origin-as-secure=${baseURL},${behandelURL}`], args: [
`--unsafely-treat-insecure-origin-as-secure=${baseURL},${behandelURL}`,
// Write Chromium's shared memory to /tmp instead of the container's small /dev/shm, so a
// large DOM/heap can't crash the renderer on the memory-constrained runner (belt-and-braces
// alongside the single worker above).
'--disable-dev-shm-usage',
],
}, },
}, },
projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }], projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }],
+5
View File
@@ -56,6 +56,11 @@ test('DigiD submit → public INGEDIEND → documenten → behandelaar goedkeurt
// why we supply the documents here rather than right after submit, when the trigger would race the // why we supply the documents here rather than right after submit, when the trigger would race the
// wait and no-op. (S-10b turns this into a real file upload; here it is the trigger that unblocks // wait and no-op. (S-10b turns this into a real file upload; here it is the trigger that unblocks
// beoordeling.) // beoordeling.)
await page.setInputFiles('#diploma', {
name: 'diploma.pdf',
mimeType: 'application/pdf',
buffer: Buffer.from('%PDF-1.4 synthetic diploma\n'),
});
await page.getByRole('button', { name: /documenten aanleveren/i }).click(); await page.getByRole('button', { name: /documenten aanleveren/i }).click();
await expect(page.getByText(/documenten zijn aangeleverd/i)).toBeVisible(); await expect(page.getByText(/documenten zijn aangeleverd/i)).toBeVisible();