using System.Net.Http.Headers; using System.Net.Http.Json; using System.Text.Json.Serialization; using Acl.Application; namespace Acl.Infrastructure; /// The only code that talks to OpenZaak's Zaken API (ADR-0001). 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 OpenZaakAsync(ZaakRequest request, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(request); using var message = new HttpRequestMessage( HttpMethod.Post, new Uri(options.BaseUrl, "/zaken/api/v1/zaken")) { Content = JsonContent.Create(new ZaakDto( request.Bronorganisatie, request.Zaaktype.ToString(), request.VerantwoordelijkeOrganisatie, request.Startdatum.ToString("yyyy-MM-dd"), request.Vertrouwelijkheidaanduiding, request.Identificatie)), }; message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", ZgwToken.Mint(options.ClientId, options.Secret)); // ZRC is a geo API; it requires the CRS headers. message.Headers.Add("Accept-Crs", "EPSG:4326"); message.Content.Headers.Add("Content-Crs", "EPSG:4326"); // OpenZaak runs behind uwsgi, which rejects a chunked request body with 400. // JsonContent streams without a known length (→ Transfer-Encoding: chunked), // so buffer it first to send a Content-Length instead. Only a real OpenZaak // surfaces this — a stubbed HttpMessageHandler accepts either framing. await message.Content.LoadIntoBufferAsync(ct); using var response = await http.SendAsync(message, ct); response.EnsureSuccessStatusCode(); var created = await response.Content.ReadFromJsonAsync(ct) ?? throw new InvalidOperationException("OpenZaak returned an empty zaak response"); return new Uri(created.Url); } public async Task SetZaakToEindstatusAsync(Uri zaakUrl, Uri zaaktypeUrl, DateOnly datumStatusGezet, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(zaakUrl); ArgumentNullException.ThrowIfNull(zaaktypeUrl); var eindstatus = await ResolveEindstatusAsync(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 // ("resultaat-does-not-exist"), so record the resultaat first, then the status. await PostAsync("/zaken/api/v1/resultaten", new ResultaatDto(zaakUrl.ToString(), resultaattype.ToString()), "Setting the zaak resultaat", ct); await PostAsync("/zaken/api/v1/statussen", // datumStatusGezet is a ZGW date-time; set it at the start of the given day (UTC). new StatusDto(zaakUrl.ToString(), eindstatus.ToString(), datumStatusGezet.ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc).ToString("yyyy-MM-ddTHH:mm:ssZ")), "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 GetZaakIdentificatieAsync(Uri zaakUrl, CancellationToken ct = default) { ArgumentNullException.ThrowIfNull(zaakUrl); using var message = new HttpRequestMessage(HttpMethod.Get, zaakUrl); message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", ZgwToken.Mint(options.ClientId, options.Secret)); // The zaak is a geo resource; the Zaken API requires the CRS header even on GET. message.Headers.Add("Accept-Crs", "EPSG:4326"); using var response = await http.SendAsync(message, ct); await EnsureSuccessAsync(response, "Reading the zaak", ct); var zaak = await response.Content.ReadFromJsonAsync(ct) ?? throw new InvalidOperationException("OpenZaak returned an empty zaak response"); return zaak.Identificatie; } public async Task 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; } public async Task ResolveZaaktypeUrlAsync(string identificatie, CancellationToken ct = default) { ArgumentException.ThrowIfNullOrWhiteSpace(identificatie); // The published zaaktype with this identificatie; status=definitief excludes concepts. var page = await GetAsync( "/catalogi/api/v1/zaaktypen?status=definitief&identificatie=" + Uri.EscapeDataString(identificatie), "zaaktypen", ct); var match = (page.Results ?? []).FirstOrDefault() ?? throw new InvalidOperationException( $"No published zaaktype with identificatie '{identificatie}' found in OpenZaak — is the BIG catalogus seeded and published?"); return new Uri(match.Url); } public async Task ResolveInformatieobjecttypeUrlAsync(string omschrijving, CancellationToken ct = default) { ArgumentException.ThrowIfNullOrWhiteSpace(omschrijving); // The informatieobjecttypen collection has no omschrijving filter, so match client-side over the // published ones. var page = await GetAsync( "/catalogi/api/v1/informatieobjecttypen?status=definitief", "informatieobjecttypen", ct); var match = (page.Results ?? []).FirstOrDefault(i => i.Omschrijving == omschrijving) ?? throw new InvalidOperationException( $"No published informatieobjecttype '{omschrijving}' found in OpenZaak — is the BIG catalogus seeded and published?"); return new Uri(match.Url); } public async Task> ListZaaktypenAsync(CancellationToken ct = default) { // Only published zaaktypen (status=definitief excludes concepts) — the read-only catalogus the // beheer portal shows. Public-safe fields only. var page = await GetAsync("/catalogi/api/v1/zaaktypen?status=definitief", "zaaktypen", ct); return (page.Results ?? []) .Select(z => new ZaaktypeSummary(z.Identificatie ?? "", z.Omschrijving ?? "", new Uri(z.Url))) .ToList(); } // GETs an absolute-by-path ZGW resource with auth (no CRS — catalogi is not a geo API). private async Task GetAsync(string pathAndQuery, string label, CancellationToken ct) { using var message = new HttpRequestMessage(HttpMethod.Get, new Uri(options.BaseUrl, pathAndQuery)); message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", ZgwToken.Mint(options.ClientId, options.Secret)); using var response = await http.SendAsync(message, ct); await EnsureSuccessAsync(response, $"Querying {label}", ct); return await response.Content.ReadFromJsonAsync(ct) ?? throw new InvalidOperationException($"OpenZaak returned an empty {label} response"); } // 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) { 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); } // 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 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(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) { if (response.IsSuccessStatusCode) return; var body = await response.Content.ReadAsStringAsync(ct); throw new HttpRequestException($"{action} failed: {(int)response.StatusCode} {response.ReasonPhrase}. {body}"); } /// Resolve the zaaktype's eindstatus (the terminal statustype) from the catalogus. private async Task ResolveEindstatusAsync(Uri zaaktypeUrl, CancellationToken ct) { var page = await GetCatalogusAsync("statustypen", zaaktypeUrl, "statustypen", ct); var results = page.Results ?? []; // OpenZaak flags the terminal statustype (highest volgnummer) as isEindstatus; fall back to the // highest volgnummer if the flag is absent. var eindstatus = results.FirstOrDefault(s => s.IsEindstatus) ?? results.OrderByDescending(s => s.Volgnummer).FirstOrDefault() ?? throw new InvalidOperationException($"No statustypen found for zaaktype {zaaktypeUrl}"); return new Uri(eindstatus.Url); } /// Resolve a specific statustype from the catalogus by its omschrijving (e.g. "Geannuleerd"). private async Task ResolveStatustypeByOmschrijvingAsync(Uri zaaktypeUrl, string omschrijving, CancellationToken ct) { var page = await GetCatalogusAsync("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); } /// Resolve a specific resultaattype from the catalogus by its omschrijving (the seed defines /// "Geregistreerd" for approval and "Vervallen" for a document-timeout cancellation). private async Task ResolveResultaattypeByOmschrijvingAsync(Uri zaaktypeUrl, string omschrijving, CancellationToken ct) { var page = await GetCatalogusAsync("resultaattypen", zaaktypeUrl, "resultaattypen", ct); var match = (page.Results ?? []).FirstOrDefault(r => r.Omschrijving == omschrijving) ?? throw new InvalidOperationException($"No '{omschrijving}' resultaattype found for zaaktype {zaaktypeUrl}"); return new Uri(match.Url); } // GETs a catalogus collection filtered by zaaktype (status=alles includes concept + published). private async Task GetCatalogusAsync(string resource, Uri zaaktypeUrl, string label, CancellationToken ct) { var query = new Uri(options.BaseUrl, $"/catalogi/api/v1/{resource}?status=alles&zaaktype=" + Uri.EscapeDataString(zaaktypeUrl.ToString())); using var message = new HttpRequestMessage(HttpMethod.Get, query); message.Headers.Authorization = new AuthenticationHeaderValue("Bearer", ZgwToken.Mint(options.ClientId, options.Secret)); using var response = await http.SendAsync(message, ct); await EnsureSuccessAsync(response, $"Querying {label}", ct); return await response.Content.ReadFromJsonAsync(ct) ?? throw new InvalidOperationException($"OpenZaak returned an empty {label} response"); } private sealed record ZaakDto( [property: JsonPropertyName("bronorganisatie")] string Bronorganisatie, [property: JsonPropertyName("zaaktype")] string Zaaktype, [property: JsonPropertyName("verantwoordelijkeOrganisatie")] string VerantwoordelijkeOrganisatie, [property: JsonPropertyName("startdatum")] string Startdatum, [property: JsonPropertyName("vertrouwelijkheidaanduiding")] string Vertrouwelijkheidaanduiding, [property: JsonPropertyName("identificatie")] string Identificatie); private sealed record ZaakCreatedDto( [property: JsonPropertyName("url")] string Url); private sealed record ZaakReadDto( [property: JsonPropertyName("identificatie")] string Identificatie); private sealed record StatusDto( [property: JsonPropertyName("zaak")] string Zaak, [property: JsonPropertyName("statustype")] string Statustype, [property: JsonPropertyName("datumStatusGezet")] string DatumStatusGezet); private sealed record StatustypePage( [property: JsonPropertyName("results")] IReadOnlyList? Results); private sealed record StatustypeDto( [property: JsonPropertyName("url")] string Url, [property: JsonPropertyName("volgnummer")] int Volgnummer, [property: JsonPropertyName("isEindstatus")] bool IsEindstatus, [property: JsonPropertyName("omschrijving")] string? Omschrijving); private sealed record ResultaatDto( [property: JsonPropertyName("zaak")] string Zaak, [property: JsonPropertyName("resultaattype")] string Resultaattype); private sealed record ResultaattypePage( [property: JsonPropertyName("results")] IReadOnlyList? Results); private sealed record ResultaattypeDto( [property: JsonPropertyName("url")] string Url, [property: JsonPropertyName("omschrijving")] string? Omschrijving); 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); private sealed record ZaaktypePage( [property: JsonPropertyName("results")] IReadOnlyList? Results); private sealed record ZaaktypeDto( [property: JsonPropertyName("url")] string Url, [property: JsonPropertyName("identificatie")] string? Identificatie, [property: JsonPropertyName("omschrijving")] string? Omschrijving = null); private sealed record InformatieobjecttypePage( [property: JsonPropertyName("results")] IReadOnlyList? Results); private sealed record InformatieobjecttypeDto( [property: JsonPropertyName("url")] string Url, [property: JsonPropertyName("omschrijving")] string? Omschrijving); }