feat(acl): diploma upload stored in the ZGW Documenten API (S-10b, closes #103) #108

Merged
not merged 15 commits from feat/103-diploma-upload-documenten into main 2026-07-21 12:15:35 +00:00
36 changed files with 823 additions and 76 deletions
+6 -2
View File
@@ -209,9 +209,13 @@ Split (issue #11 closed) into two independently-demoable slices per §13 — the
#### 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 cancellation status (not just the domain aggregate → `Verlopen`). Adds a cancellation statustype/resultaattype to the seed + an ACL method + expiry-worker wiring. Carved from S-10b (ADR-0017/0018). Depends on #103.
### S-11 · Withdrawal (Flow 3)
@@ -19,11 +19,20 @@
Het aanleveren van uw documenten is niet gelukt. Probeer het opnieuw.
</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
utrecht-button
appearance="primary-action-button"
type="button"
[disabled]="providingDocuments()"
[disabled]="providingDocuments() || !selectedFile()"
(click)="provideDocuments()"
>
Documenten aanleveren
@@ -83,21 +83,29 @@ describe('RegistrationPage', () => {
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();
await render(RegistrationPage, { providers: p });
fireEvent.click(screen.getByRole('button', { name: /indienen/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 }));
// The provide-documents call is keyed by the reference the submit returned, and the page confirms.
expect(provideDocuments).toHaveBeenCalledWith('reg-9');
// The upload is keyed by the reference and carries the base64 file + its name; the page confirms.
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(
vi.fn().mockReturnValue(of({ registrationId: 'reg-9', status: 'Ingediend' })),
vi.fn().mockReturnValue(of(undefined)),
@@ -107,6 +115,7 @@ describe('RegistrationPage', () => {
fireEvent.click(screen.getByRole('button', { name: /indienen/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 }));
expect(await screen.findByRole('alert')).toBeTruthy();
@@ -29,6 +29,7 @@ export class RegistrationPage {
protected readonly providingDocuments = signal(false);
protected readonly documentsProvided = signal(false);
protected readonly provideDocumentsFailed = signal(false);
protected readonly selectedFile = signal<File | undefined>(undefined);
submit(): void {
this.submitting.set(true);
@@ -47,24 +48,44 @@ 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();
if (!reference) {
const file = this.selectedFile();
if (!reference || !file) {
return;
}
this.providingDocuments.set(true);
this.provideDocumentsFailed.set(false);
this.bff.postSelfServiceRegistrationsIdDocuments(reference).subscribe({
next: () => {
this.documentsProvided.set(true);
this.providingDocuments.set(false);
},
// Surface the failure instead of swallowing it: keep the action so the user can retry.
error: () => {
this.provideDocumentsFailed.set(true);
this.providingDocuments.set(false);
},
});
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: () => {
this.documentsProvided.set(true);
this.providingDocuments.set(false);
},
// Surface the failure instead of swallowing it: keep the action so the user can retry.
error: () => {
this.provideDocumentsFailed.set(true);
this.providingDocuments.set(false);
},
});
}
withdraw(): void {
@@ -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).
+28
View File
@@ -434,3 +434,31 @@ routing → `Beoordelen`), OR the `P30D` interrupting timer fires → `Registrat
> 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
> 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).
> Setting the ZGW zaak to a cancellation status on 30-day expiry is a follow-up (S-10c, #106).
+3
View File
@@ -306,6 +306,9 @@ services:
Acl__Defaults__Vertrouwelijkheidaanduiding: openbaar
# 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}
# 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:
- "8100:8080"
healthcheck:
+62
View File
@@ -124,6 +124,58 @@ def publish_zaaktype(zt):
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():
# 1. Catalogus
existing = [c for c in find(f"/catalogussen?domein=BIG") if c.get("domein") == "BIG"]
@@ -198,10 +250,16 @@ def main():
# 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
# the ACL integration test (S-04a, #46) exercises. See ADR-0006.
iot = None
if PUBLISH:
# 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")
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)
# 5. Verify the JWT client can list the zaaktype (concepts included).
@@ -214,6 +272,10 @@ def main():
# 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")
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)")
+8 -3
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"
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
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
[ -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 ">> informatieobjecttype: $iot_url"
echo ">> recreating the acl service pointed at the seeded zaaktype (host-consistent)"
ACL_ZAAKTYPE_URL="$zt_url" ACL_OPENZAAK_BASEURL="$oz_base/" docker compose -f "$compose" up -d acl
echo ">> recreating the acl service pointed at the seeded zaaktype + informatieobjecttype (host-consistent)"
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
echo ">> submitting a registration to the domain"
+19 -7
View File
@@ -35,6 +35,14 @@ export interface OpenbaarEntry {
reference: string | null;
}
export interface ProvideDocumentsRequest {
contentBase64: string;
/** @nullable */
fileName?: string | null;
/** @nullable */
contentType?: string | null;
}
export interface SubmitAccepted {
registrationId: string;
status: string;
@@ -226,15 +234,19 @@ export class BffApiV1Service {
);
}
postSelfServiceRegistrationsIdDocuments<TData = void>(id: string, options?: HttpClientBodyOptions): Observable<TData>;
postSelfServiceRegistrationsIdDocuments<TData = void>(id: string, options?: HttpClientEventOptions): Observable<HttpEvent<TData>>;
postSelfServiceRegistrationsIdDocuments<TData = void>(id: string, options?: HttpClientResponseOptions): Observable<AngularHttpResponse<TData>>;
postSelfServiceRegistrationsIdDocuments<TData = void>(id: string,
provideDocumentsRequest: ProvideDocumentsRequest, options?: HttpClientBodyOptions): Observable<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>(
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') {
return this.http.post<TData>(
`/self-service/registrations/${id}/documents`,
undefined,{
provideDocumentsRequest,{
...(options as Omit<NonNullable<typeof options>, 'observe'>),
observe: 'events',
}
@@ -244,7 +256,7 @@ export class BffApiV1Service {
if (options?.observe === 'response') {
return this.http.post<TData>(
`/self-service/registrations/${id}/documents`,
undefined,{
provideDocumentsRequest,{
...(options as Omit<NonNullable<typeof options>, 'observe'>),
observe: 'response',
}
@@ -253,7 +265,7 @@ export class BffApiV1Service {
return this.http.post<TData>(
`/self-service/registrations/${id}/documents`,
undefined,{
provideDocumentsRequest,{
...(options as Omit<NonNullable<typeof options>, 'observe'>),
observe: 'body',
}
+11
View File
@@ -40,6 +40,15 @@ app.MapPost("/zaken/reference", async (ZaakReferenceRequest body, AclService acl
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();
public sealed record OpenZaakRequest(string Bsn, string Reference);
@@ -48,4 +57,6 @@ public sealed record SetStatusRequest(string ZaakUrl);
public sealed record ZaakReferenceRequest(string ZaakUrl);
public sealed record StoreDocumentRequest(string ZaakUrl, string ContentBase64, string FileName, string ContentType);
public partial class Program;
@@ -7,4 +7,8 @@ public sealed class AclDefaults
public required string VerantwoordelijkeOrganisatie { get; init; }
public required string Vertrouwelijkheidaanduiding { 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; }
}
@@ -37,4 +37,33 @@ public sealed class AclService(IZaakGateway gateway, AclDefaults defaults, ICloc
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);
@@ -16,4 +16,11 @@ public interface IZaakGateway
/// <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>
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);
}
@@ -80,6 +80,39 @@ public sealed class OpenZaakGateway(HttpClient http, OpenZaakOptions options) :
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
// a Content-Length instead of a chunked body (as with zaak-create).
private async Task PostAsync(string path, object dto, string action, CancellationToken ct)
@@ -96,6 +129,26 @@ public sealed class OpenZaakGateway(HttpClient http, OpenZaakOptions options) :
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
// is essential for diagnosing a rejected request, so surface it in the exception.
private static async Task EnsureSuccessAsync(HttpResponseMessage response, string action, CancellationToken ct)
@@ -182,4 +235,26 @@ public sealed class OpenZaakGateway(HttpClient http, OpenZaakOptions options) :
private sealed record ResultaattypeDto(
[property: JsonPropertyName("url")] string Url);
private sealed record CreatedDto(
[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();
}
/// <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>
public async Task<Uri> FindEindstatustypeAsync(Uri zaaktypeUrl, CancellationToken ct = default)
{
@@ -74,4 +74,58 @@ public sealed class OpenZaakGatewayIntegrationTests(OpenZaakFixture stack)
var eindstatustype = await stack.FindEindstatustypeAsync(zaaktype!);
Assert.Equal(eindstatustype.ToString(), status.GetProperty("statustype").GetString());
}
[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());
}
}
+47
View File
@@ -30,6 +30,15 @@ public class AclServiceTests
ReadReferenceFor = zaakUrl;
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()
@@ -38,6 +47,7 @@ public class AclServiceTests
VerantwoordelijkeOrganisatie = "517439943",
Vertrouwelijkheidaanduiding = "openbaar",
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
@@ -55,6 +65,7 @@ public class AclServiceTests
VerantwoordelijkeOrganisatie = "517439943",
Vertrouwelijkheidaanduiding = "openbaar",
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)));
@@ -81,6 +92,7 @@ public class AclServiceTests
VerantwoordelijkeOrganisatie = "517439943",
Vertrouwelijkheidaanduiding = "openbaar",
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)));
@@ -114,6 +126,41 @@ public class AclServiceTests
Assert.Null(gateway.Approved);
}
[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]
public async Task Reading_a_zaak_reference_returns_the_zaaks_identificatie()
{
@@ -432,4 +432,114 @@ public class OpenZaakGatewayTests
b64 = (b64.Length % 4) switch { 2 => b64 + "==", 3 => b64 + "=", _ => 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>
Task<bool> WithdrawRegistrationAsync(string registrationId, string bsn, CancellationToken ct = default);
/// <summary>Provide the documents the caller's own registration is waiting for ("documenten
/// aanleveren"). Owner-scoped by <paramref name="bsn"/>. Returns <c>false</c> when the domain
/// reports the registration is unknown or not the caller's (404), so the BFF can relay a 404.</summary>
Task<bool> ProvideDocumentsAsync(string registrationId, string bsn, CancellationToken ct = default);
/// <summary>Provide (upload) the diploma the caller's own registration is waiting for ("documenten
/// aanleveren"). The file is carried base64-encoded. Owner-scoped by <paramref name="bsn"/>. Returns
/// <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, string contentBase64, string? fileName, string? contentType, CancellationToken ct = default);
/// <summary>The behandelaar's werkbak — registrations awaiting beoordeling.</summary>
Task<IReadOnlyList<WerkbakItem>> GetWerkbakAsync(CancellationToken ct = default);
@@ -68,10 +69,12 @@ public sealed class DomainClient(HttpClient http) : IDomainClient
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(
$"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.
if (response.StatusCode == System.Net.HttpStatusCode.NotFound)
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
// 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.
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");
if (string.IsNullOrWhiteSpace(bsn))
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();
})
.RequireAuthorization()
@@ -163,6 +165,10 @@ app.Run();
/// <summary>The behandelaar's decision on a registration.</summary>
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).
internal static class BehandelAuth
{
+3 -3
View File
@@ -94,15 +94,15 @@ internal sealed class FakeDomainClient : IDomainClient
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
/// not-found/not-owned (false → 404). Tests set this to exercise the relay.</summary>
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);
}
@@ -114,7 +114,17 @@ public class SelfServiceEndpointTests
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)
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", bearer);
return request;
@@ -132,14 +142,19 @@ public class SelfServiceEndpointTests
}
[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();
var response = await factory.CreateClient().SendAsync(ProvideDocuments(TestTokens.Valid("123456782"), "reg-9"));
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]
+33
View File
@@ -76,6 +76,16 @@
}
}
],
"requestBody": {
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ProvideDocumentsRequest"
}
}
},
"required": true
},
"responses": {
"204": {
"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": {
"required": [
"registrationId",
+11 -2
View File
@@ -120,8 +120,17 @@ app.MapPost("/registrations/{id}/documents", async (string id, ProvideDocumentsR
if (string.IsNullOrWhiteSpace(body?.Bsn))
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();
});
@@ -152,7 +161,7 @@ public sealed record DecideRequest(string Besluit);
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);
+7
View File
@@ -52,6 +52,13 @@ public interface IAclClient
/// the zaak's final status — which OpenZaak notifies over NRC; the domain never names statustypen.
/// </summary>
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>
@@ -2,10 +2,12 @@ using Big.Domain;
namespace Big.Application;
/// <summary>A zorgprofessional's signal that they have supplied the documents their registration is
/// waiting for ("documenten aanleveren"). <paramref name="Bsn"/> is the authenticated caller (from the
/// DigiD token, forwarded by the BFF): only the registration's own bsn may provide its documents.</summary>
public sealed record ProvideDocumentsCommand(RegistrationId RegistrationId, string Bsn);
/// <summary>A zorgprofessional's upload of the diploma their registration is waiting for ("documenten
/// aanleveren"). <paramref name="Bsn"/> is the authenticated caller (from the DigiD token, forwarded by
/// the BFF): only the registration's own bsn may provide its documents. <paramref name="Content"/> is
/// 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>
public enum ProvideDocumentsOutcome
@@ -19,14 +21,14 @@ public enum ProvideDocumentsOutcome
}
/// <summary>
/// The provide-documents use case (S-10a): a zorgprofessional supplies the documents their registration
/// is parked waiting for, completing the WachtOpDocumenten task so the registratie process leaves the
/// 30-day wait and continues to beoordeling (ADR-0017). Owner-scoped by bsn. Completing the wait is
/// best-effort: if the registration never started a process (or already left the wait), the request
/// still stands, mirroring how <see cref="WithdrawRegistration"/> cancels best-effort. The actual file
/// upload and its ZGW storage via the ACL is S-10b; this is the trigger that unblocks the process.
/// The provide-documents use case (S-10a/S-10b): a zorgprofessional uploads the diploma their
/// registration is parked waiting for. The document is stored in ZGW via the ACL (§8.1), then the
/// WachtOpDocumenten task is completed so the registratie process leaves the 30-day wait and continues
/// to beoordeling (ADR-0017). Owner-scoped by bsn. Both steps are best-effort about missing preconditions
/// (mirroring <see cref="WithdrawRegistration"/>): storage needs an opened zaak, and completion needs a
/// running process — a request that arrives before either still stands, storing/completing what it can.
/// </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)
{
@@ -38,6 +40,11 @@ public sealed class ProvideDocuments(IRegistrationStore store, IWorkflowClient w
if (registration is null || registration.Bsn != command.Bsn)
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.
if (registration.ProcessInstanceId is not null)
await workflow.CompleteDocumentWaitAsync(registration.ProcessInstanceId, ct);
@@ -31,6 +31,23 @@ public sealed class AclHttpClient(HttpClient http, AclOptions options) : IAclCli
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(
[property: JsonPropertyName("bsn")] string Bsn,
[property: JsonPropertyName("reference")] string Reference);
@@ -38,4 +55,13 @@ public sealed class AclHttpClient(HttpClient http, AclOptions options) : IAclCli
private sealed record OpenZaakResponse([property: JsonPropertyName("zaakUrl")] string ZaakUrl);
private sealed record SetStatusRequest([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);
}
+9
View File
@@ -110,4 +110,13 @@ internal sealed class FakeAclClient(Uri? zaakUrl = null) : IAclClient
ApprovedZaakUrl = zaakUrl;
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);
}
}
@@ -3,52 +3,60 @@ using Big.Domain;
namespace Big.Tests;
// S-10a (#102): the "documents received" use case. A zorgprofessional supplies the documents their
// registration is waiting for; the handler completes the WachtOpDocumenten task via the Workflow Client
// so the process leaves the 30-day wait and continues to beoordeling. Owner-scoped by the caller's bsn,
// like WithdrawRegistration. (The real file upload + ZGW storage is S-10b; this is the trigger path.)
// S-10a/S-10b (#102/#103): the "documents received" use case. A zorgprofessional supplies the diploma
// their registration is waiting for; the handler stores it in ZGW via the ACL and completes the
// WachtOpDocumenten task via the Workflow Client so the process continues to beoordeling. Owner-scoped
// by the caller's bsn, like WithdrawRegistration.
public class ProvideDocumentsTests
{
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")
{
var registration = Registration.Submit(Bsn);
registration.RecordProcessStarted(processInstanceId);
registration.AttachZaak(Zaak);
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]
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 registration = Submitted("proc-42");
store.Seed(registration);
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));
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);
}
[Fact]
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
// NotFound (existence not revealed) and the wait is not completed.
// Owner-scoping: another bsn is told NotFound; nothing is stored or completed.
var store = new FakeRegistrationStore();
var registration = Submitted();
store.Seed(registration);
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"));
Assert.Equal(ProvideDocumentsOutcome.NotFound, outcome);
Assert.Null(acl.StoredDiploma);
Assert.Null(workflow.CompletedDocumentWaitFor);
}
@@ -56,30 +64,33 @@ public class ProvideDocumentsTests
public async Task Providing_for_an_unknown_registration_is_not_found()
{
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())));
}
[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
// WithdrawRegistration) and the Workflow Client is not called.
// No zaak yet → nothing to file the document against, but the request still stands (best-effort,
// mirroring WithdrawRegistration). The wait is completed if a process is running.
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);
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));
Assert.Equal(ProvideDocumentsOutcome.Accepted, outcome);
Assert.Null(workflow.CompletedDocumentWaitFor);
Assert.Null(acl.StoredDiploma);
Assert.Equal("proc-9", workflow.CompletedDocumentWaitFor);
}
[Fact]
public async Task Rejects_a_null_command()
=> await Assert.ThrowsAsync<ArgumentNullException>(() =>
new ProvideDocuments(new FakeRegistrationStore(), new FakeWorkflowClient()).HandleAsync(null!));
new ProvideDocuments(new FakeRegistrationStore(), new FakeWorkflowClient(), new FakeAclClient()).HandleAsync(null!));
}
@@ -30,6 +30,7 @@ public sealed class EenZaakOpenenSteps
VerantwoordelijkeOrganisatie = values["verantwoordelijkeOrganisatie"],
Vertrouwelijkheidaanduiding = values["vertrouwelijkheidaanduiding"],
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)
=> 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);
public Task<IReadOnlyList<WerkbakItem>> GetWerkbakAsync(CancellationToken ct = default)
@@ -59,6 +59,14 @@ public sealed class InMemoryAclClient : IAclClient
ApprovedZaakUrl = 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
@@ -27,4 +27,7 @@ public sealed class InMemoryZaakGateway : IZaakGateway
public Task<string> GetZaakIdentificatieAsync(Uri zaakUrl, CancellationToken ct = default)
=> 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"));
}
+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
// wait and no-op. (S-10b turns this into a real file upload; here it is the trigger that unblocks
// 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 expect(page.getByText(/documenten zijn aangeleverd/i)).toBeVisible();