From efa09bf3bdc2df91c2e10ea6e7f0c74c0b393a0f Mon Sep 17 00:00:00 2001 From: robbertjanssen85 <91183957+robbertjanssen85@users.noreply.github.com> Date: Fri, 6 Mar 2026 14:28:49 +0100 Subject: [PATCH] Add MiniGIM data sources, DSO API with geometry, dataspace UI, and access toggle MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add 15 new data layers from MiniGIM dataset (BGT, NWB, BRO, IMWA, RIVM, RCE) with ✦ indicator for new layers - Add DSO bestemmingsplannen layer with actual polygon geometry via geometrieopvragen v1 API for Omgevingsplannen - Add open/restricted access type toggle in sidebar to filter layers by API key requirement - Add address search component with PDOK locatieserver - Add Eclipse Dataspace Connector (EDC) integration with consumer/provider views - Add dataspace page with dashboard, catalog browser, and asset management Co-Authored-By: Claude Opus 4.6 --- docker-compose.yml | 69 ++ package.json | 6 +- scripts/register-edc-assets.ts | 132 +++ src/app/api/dso/plannen/route.ts | 154 ++++ src/app/api/edc/agreements/route.ts | 14 + src/app/api/edc/assets/[assetId]/route.ts | 30 + src/app/api/edc/assets/route.ts | 25 + src/app/api/edc/catalog/route.ts | 19 + .../edc/negotiations/[negotiationId]/route.ts | 16 + src/app/api/edc/negotiations/route.ts | 25 + src/app/api/edc/policies/route.ts | 25 + src/app/api/edc/status/route.ts | 54 ++ src/app/api/edc/sync/route.ts | 66 ++ src/app/api/edc/transfers/route.ts | 25 + src/app/dataspace/page.tsx | 52 ++ src/app/page.tsx | 13 +- src/components/address-search.tsx | 203 +++++ src/components/dataspace/consumer-view.tsx | 312 +++++++ src/components/dataspace/dashboard.tsx | 113 +++ src/components/dataspace/provider-view.tsx | 210 +++++ src/components/map-view.tsx | 33 + src/components/nav-bar.tsx | 3 +- src/components/sidebar.tsx | 42 +- src/lib/data-sources.ts | 830 +++++++++++++++++- src/lib/edc-asset-mapper.ts | 98 +++ src/lib/edc-client.ts | 253 ++++++ 26 files changed, 2806 insertions(+), 16 deletions(-) create mode 100644 docker-compose.yml create mode 100644 scripts/register-edc-assets.ts create mode 100644 src/app/api/dso/plannen/route.ts create mode 100644 src/app/api/edc/agreements/route.ts create mode 100644 src/app/api/edc/assets/[assetId]/route.ts create mode 100644 src/app/api/edc/assets/route.ts create mode 100644 src/app/api/edc/catalog/route.ts create mode 100644 src/app/api/edc/negotiations/[negotiationId]/route.ts create mode 100644 src/app/api/edc/negotiations/route.ts create mode 100644 src/app/api/edc/policies/route.ts create mode 100644 src/app/api/edc/status/route.ts create mode 100644 src/app/api/edc/sync/route.ts create mode 100644 src/app/api/edc/transfers/route.ts create mode 100644 src/app/dataspace/page.tsx create mode 100644 src/components/address-search.tsx create mode 100644 src/components/dataspace/consumer-view.tsx create mode 100644 src/components/dataspace/dashboard.tsx create mode 100644 src/components/dataspace/provider-view.tsx create mode 100644 src/lib/edc-asset-mapper.ts create mode 100644 src/lib/edc-client.ts diff --git a/docker-compose.yml b/docker-compose.yml new file mode 100644 index 0000000..576c428 --- /dev/null +++ b/docker-compose.yml @@ -0,0 +1,69 @@ +services: + control-plane: + image: tractusx/edc-controlplane-memory-hashicorp-vault:0.5.4 + depends_on: + - vault + environment: + EDC_PARTICIPANT_ID: ${EDC_PARTICIPANT_ID:-zwolle-data-viewer} + EDC_API_AUTH_KEY: ${EDC_API_AUTH_KEY:-password} + EDC_DSP_CALLBACK_ADDRESS: http://control-plane:8282/protocol + # Management API + WEB_HTTP_PORT: 8080 + WEB_HTTP_PATH: /api + WEB_HTTP_MANAGEMENT_PORT: 8181 + WEB_HTTP_MANAGEMENT_PATH: /management + WEB_HTTP_PROTOCOL_PORT: 8282 + WEB_HTTP_PROTOCOL_PATH: /protocol + WEB_HTTP_CONTROL_PORT: 8283 + WEB_HTTP_CONTROL_PATH: /control + # Vault + EDC_VAULT_HASHICORP_URL: http://vault:8200 + EDC_VAULT_HASHICORP_TOKEN: ${VAULT_TOKEN:-root} + # Encryption + EDC_DATA_ENCRYPTION_KEYS_ALIAS: data-encryption-key + EDC_DATA_ENCRYPTION_ALGORITHM: AES + # SSI / MIW (stub values for local development) + TX_SSI_OAUTH_TOKEN_URL: http://vault:8200/v1/identity/oidc/token + TX_SSI_OAUTH_CLIENT_ID: zwolle-data-viewer + TX_SSI_OAUTH_CLIENT_SECRET_ALIAS: client-secret + TX_SSI_MIW_URL: http://localhost:8080 + TX_SSI_MIW_AUTHORITY_ID: BPNL000000000001 + TX_SSI_ENDPOINT_AUDIENCE: http://localhost:8282/protocol + # Data plane selector + EDC_DATAPLANE_SELECTOR_DEFAULTPLANE_URL: http://data-plane:8185/control/transfer + EDC_DATAPLANE_SELECTOR_DEFAULTPLANE_SOURCETYPES: HttpData + EDC_DATAPLANE_SELECTOR_DEFAULTPLANE_DESTINATIONTYPES: HttpProxy,HttpData + EDC_DATAPLANE_SELECTOR_DEFAULTPLANE_PROPERTIES: '{"publicApiUrl":"http://localhost:8185/public"}' + ports: + - "8181:8181" # Management API + - "8282:8282" # DSP Protocol + - "8283:8283" # Control API + + data-plane: + image: tractusx/edc-dataplane-hashicorp-vault:0.5.4 + depends_on: + - control-plane + environment: + EDC_API_AUTH_KEY: ${EDC_API_AUTH_KEY:-password} + WEB_HTTP_PORT: 8080 + WEB_HTTP_PATH: /api + WEB_HTTP_PUBLIC_PORT: 8185 + WEB_HTTP_PUBLIC_PATH: /public + WEB_HTTP_CONTROL_PORT: 8185 + WEB_HTTP_CONTROL_PATH: /control + EDC_DATAPLANE_TOKEN_VALIDATION_ENDPOINT: http://control-plane:8283/control/token + # Vault + EDC_VAULT_HASHICORP_URL: http://vault:8200 + EDC_VAULT_HASHICORP_TOKEN: ${VAULT_TOKEN:-root} + ports: + - "8185:8185" # Public API + + vault: + image: hashicorp/vault:1.15 + environment: + VAULT_DEV_ROOT_TOKEN_ID: ${VAULT_TOKEN:-root} + VAULT_DEV_LISTEN_ADDRESS: 0.0.0.0:8200 + ports: + - "8200:8200" + cap_add: + - IPC_LOCK diff --git a/package.json b/package.json index 790f594..1ef9360 100644 --- a/package.json +++ b/package.json @@ -6,7 +6,10 @@ "dev": "next dev", "build": "next build", "start": "next start", - "lint": "eslint" + "lint": "eslint", + "edc:up": "docker compose up -d", + "edc:down": "docker compose down", + "edc:register": "npx tsx scripts/register-edc-assets.ts" }, "dependencies": { "@deck.gl/geo-layers": "^9.2.7", @@ -38,6 +41,7 @@ "shadcn": "^3.8.4", "tailwindcss": "^4", "tw-animate-css": "^1.4.0", + "tsx": "^4.19.0", "typescript": "^5" } } diff --git a/scripts/register-edc-assets.ts b/scripts/register-edc-assets.ts new file mode 100644 index 0000000..89409d4 --- /dev/null +++ b/scripts/register-edc-assets.ts @@ -0,0 +1,132 @@ +/** + * Standalone script to register all Zwolle layers as EDC assets. + * Run: npx tsx scripts/register-edc-assets.ts + * + * Requires EDC_MANAGEMENT_URL and EDC_API_AUTH_KEY env vars (or defaults). + */ + +const EDC_URL = process.env.EDC_MANAGEMENT_URL ?? "http://localhost:8181/management"; +const API_KEY = process.env.EDC_API_AUTH_KEY ?? "password"; +const APP_URL = process.env.NEXT_PUBLIC_APP_URL ?? "http://localhost:3000"; + +const EDC_CONTEXT = { "@vocab": "https://w3id.org/edc/v0.0.1/ns/" }; +const OPEN_POLICY_ID = "open-data-policy"; + +async function edcPost(path: string, body: unknown) { + const res = await fetch(`${EDC_URL}${path}`, { + method: "POST", + headers: { + "Content-Type": "application/json", + "X-Api-Key": API_KEY, + }, + body: JSON.stringify(body), + }); + return { status: res.status, body: await res.text() }; +} + +async function main() { + // Dynamically import the layer metadata + const { LAYER_METADATA, CATEGORIES } = await import("../src/lib/data-sources"); + + console.log(`\nRegistering ${LAYER_METADATA.length} layers to EDC at ${EDC_URL}`); + console.log(`Categories: ${Object.keys(CATEGORIES).join(", ")}\n`); + + // 1. Create open data policy + console.log("Creating open data policy..."); + const policyRes = await edcPost("/v2/policydefinitions", { + "@context": EDC_CONTEXT, + "@id": OPEN_POLICY_ID, + policy: { + "@context": "http://www.w3.org/ns/odrl.jsonld", + "@type": "Set", + permission: [{ action: "use", constraint: [] }], + }, + }); + if (policyRes.status === 200 || policyRes.status === 201) { + console.log(" Policy created"); + } else if (policyRes.status === 409) { + console.log(" Policy already exists"); + } else { + console.error(` Failed: ${policyRes.status} ${policyRes.body}`); + } + + // 2. Register assets + contract definitions + let created = 0; + let skipped = 0; + let failed = 0; + + const CATEGORY_THEME: Record = { + verkeer: "TRAN", + gebouwen: "GOVE", + "openbare-ruimte": "ENVI", + grenzen: "REGI", + milieu: "ENVI", + voorzieningen: "EDUC", + }; + + for (const layer of LAYER_METADATA) { + const assetId = `zwolle-${layer.id}`; + + // Create asset (v2 API requires wrapping in "asset" key) + const assetRes = await edcPost("/v2/assets", { + "@context": EDC_CONTEXT, + asset: { + "@id": assetId, + properties: { + name: layer.name, + description: layer.description, + contenttype: "application/geo+json", + version: "1.0", + theme: CATEGORY_THEME[layer.category] ?? "GOVE", + category: layer.category, + source: layer.source, + icon: layer.icon, + }, + }, + dataAddress: { + "@type": "DataAddress", + type: "HttpData", + baseUrl: `${APP_URL}/api/v1/layers/${layer.id}`, + proxyPath: "true", + proxyQueryParams: "true", + }, + }); + + if (assetRes.status === 200 || assetRes.status === 201) { + // Create contract definition + const cdRes = await edcPost("/v2/contractdefinitions", { + "@context": EDC_CONTEXT, + "@id": `cd-zwolle-${layer.id}`, + accessPolicyId: OPEN_POLICY_ID, + contractPolicyId: OPEN_POLICY_ID, + assetsSelector: { + "@type": "CriterionDto", + operandLeft: "https://w3id.org/edc/v0.0.1/ns/id", + operator: "=", + operandRight: assetId, + }, + }); + + if (cdRes.status === 200 || cdRes.status === 201) { + created++; + process.stdout.write("."); + } else { + failed++; + console.error(`\n Contract def failed for ${layer.id}: ${cdRes.status}`); + } + } else if (assetRes.status === 409) { + skipped++; + process.stdout.write("s"); + } else { + failed++; + console.error(`\n Asset failed for ${layer.id}: ${assetRes.status}`); + } + } + + console.log(`\n\nDone: ${created} created, ${skipped} skipped, ${failed} failed`); +} + +main().catch((err) => { + console.error("Fatal error:", err); + process.exit(1); +}); diff --git a/src/app/api/dso/plannen/route.ts b/src/app/api/dso/plannen/route.ts new file mode 100644 index 0000000..524402d --- /dev/null +++ b/src/app/api/dso/plannen/route.ts @@ -0,0 +1,154 @@ +import { NextResponse } from "next/server"; + +export const dynamic = "force-dynamic"; +export const fetchCache = "force-no-store"; + +const DSO_API_KEY = process.env.DSO_API_KEY || ""; +const DSO_BASE = + "https://service.omgevingswet.overheid.nl/publiek/omgevingsinformatie/api/ontsluiten/v2"; +const GEOM_BASE = + "https://service.omgevingswet.overheid.nl/publiek/omgevingsdocumenten/api/geometrieopvragen/v1"; + +// Grid of sample points across Zwolle in RD (EPSG:28992) coordinates +const ZWOLLE_SAMPLE_POINTS: [number, number][] = [ + [199500, 501500], [200000, 501500], [200500, 501500], [201000, 501500], + [199500, 502000], [200000, 502000], [200500, 502000], [201000, 502000], + [199500, 502500], [200000, 502500], [200500, 502500], [201000, 502500], + [200000, 503000], [200500, 503000], [201000, 503000], [201500, 503000], + [200500, 503500], [201000, 503500], +]; + +// Approximate RD -> WGS84 for Zwolle area +function rdToWgs84(x: number, y: number): [number, number] { + const lon = 6.1 + ((x - 200500) / 111320) * (1 / Math.cos(52.51 * Math.PI / 180)); + const lat = 52.51 + (y - 502500) / 111320; + return [lon, lat]; +} + +interface DSODocument { + identificatie: string; + titel: string; + type: string; + geometrieIdentificaties?: string[]; + imroDocumentMetadata?: { + regelStatus?: string; + planstatusInfo?: { planstatus?: string; datum?: string }; + isHistorisch?: boolean; + }; + aangeleverdDoorEen?: { naam?: string; code?: string }; + geldigVanaf?: string; +} + +async function fetchGeometry(geometrieId: string): Promise { + try { + const res = await fetch( + `${GEOM_BASE}/geometrieen/${encodeURIComponent(geometrieId)}?crs=${encodeURIComponent("http://www.opengis.net/def/crs/EPSG/0/4258")}`, + { headers: { "X-Api-Key": DSO_API_KEY } } + ); + if (!res.ok) return null; + const data = await res.json(); + // The API returns { geometrie: { type, coordinates } } or { type, coordinates } directly + const geom = data.geometrie || data; + if (geom?.type && geom?.coordinates) return geom as GeoJSON.Geometry; + return null; + } catch { + return null; + } +} + +/** + * Proxy for DSO Omgevingsinformatie Ontsluiten API. + * Searches for bestemmingsplannen covering Zwolle via sample points. + * Fetches actual polygon geometry where available (OW plans). + */ +export async function GET() { + if (!DSO_API_KEY) { + return NextResponse.json( + { type: "FeatureCollection", features: [] }, + { headers: { "Cache-Control": "public, max-age=3600" } } + ); + } + + try { + const planMap = new Map(); + + const fetchPoint = async (coords: [number, number]) => { + const res = await fetch(`${DSO_BASE}/documenten/_zoek?size=50`, { + method: "POST", + headers: { + "X-Api-Key": DSO_API_KEY, + "Content-Type": "application/json", + "Content-Crs": "http://www.opengis.net/def/crs/EPSG/0/28992", + }, + body: JSON.stringify({ + bestuurslaag: "GEMEENTE", + regelgevingOfOverig: "REGELGEVING", + geometrie: { type: "Point", coordinates: coords }, + }), + }); + if (!res.ok) return; + const data = await res.json(); + const docs = (data?._embedded?.documenten || []) as DSODocument[]; + for (const doc of docs) { + if (!planMap.has(doc.identificatie)) { + planMap.set(doc.identificatie, { doc, rdPoint: coords }); + } + } + }; + + // Batch 3 at a time + for (let i = 0; i < ZWOLLE_SAMPLE_POINTS.length; i += 3) { + const batch = ZWOLLE_SAMPLE_POINTS.slice(i, i + 3); + await Promise.all(batch.map(fetchPoint)); + } + + const features: GeoJSON.Feature[] = []; + + for (const [, { doc, rdPoint }] of planMap) { + if (doc.imroDocumentMetadata?.isHistorisch) continue; + + // Try to fetch actual geometry for non-IMRO plans (OW geometry IDs) + let geometry: GeoJSON.Geometry | null = null; + const geomIds = doc.geometrieIdentificaties || []; + for (const gid of geomIds) { + if (!gid.startsWith("NL.IMRO")) { + geometry = await fetchGeometry(gid); + if (geometry) break; + } + } + + // Fall back to sample point location + if (!geometry) { + const [lon, lat] = rdToWgs84(rdPoint[0], rdPoint[1]); + geometry = { type: "Point", coordinates: [lon, lat] }; + } + + features.push({ + type: "Feature", + geometry, + properties: { + naam: doc.titel, + identificatie: doc.identificatie, + type: doc.type, + status: doc.imroDocumentMetadata?.regelStatus || "", + planstatus: doc.imroDocumentMetadata?.planstatusInfo?.planstatus || "", + datum: doc.imroDocumentMetadata?.planstatusInfo?.datum || "", + bevoegdGezag: doc.aangeleverdDoorEen?.naam || "", + geldigVanaf: doc.geldigVanaf || "", + hasGeometry: geometry.type !== "Point", + }, + }); + } + + return NextResponse.json( + { type: "FeatureCollection" as const, features }, + { headers: { "Cache-Control": "no-cache" } } + ); + } catch (err) { + console.error("DSO API error:", err); + return NextResponse.json( + { type: "FeatureCollection", features: [] }, + { headers: { "Cache-Control": "public, max-age=60" } } + ); + } +} diff --git a/src/app/api/edc/agreements/route.ts b/src/app/api/edc/agreements/route.ts new file mode 100644 index 0000000..28f5b8b --- /dev/null +++ b/src/app/api/edc/agreements/route.ts @@ -0,0 +1,14 @@ +import { NextRequest, NextResponse } from "next/server"; +import { edcAgreements } from "@/lib/edc-client"; + +export async function GET(request: NextRequest) { + try { + const offset = Number(request.nextUrl.searchParams.get("offset") ?? 0); + const limit = Number(request.nextUrl.searchParams.get("limit") ?? 50); + const agreements = await edcAgreements.list(offset, limit); + return NextResponse.json(agreements); + } catch (err) { + const msg = err instanceof Error ? err.message : "Failed to list agreements"; + return NextResponse.json({ error: msg }, { status: 502 }); + } +} diff --git a/src/app/api/edc/assets/[assetId]/route.ts b/src/app/api/edc/assets/[assetId]/route.ts new file mode 100644 index 0000000..5286194 --- /dev/null +++ b/src/app/api/edc/assets/[assetId]/route.ts @@ -0,0 +1,30 @@ +import { NextRequest, NextResponse } from "next/server"; +import { edcAssets } from "@/lib/edc-client"; + +export async function GET( + _request: NextRequest, + { params }: { params: Promise<{ assetId: string }> } +) { + try { + const { assetId } = await params; + const asset = await edcAssets.get(assetId); + return NextResponse.json(asset); + } catch (err) { + const msg = err instanceof Error ? err.message : "Failed to get asset"; + return NextResponse.json({ error: msg }, { status: 502 }); + } +} + +export async function DELETE( + _request: NextRequest, + { params }: { params: Promise<{ assetId: string }> } +) { + try { + const { assetId } = await params; + await edcAssets.delete(assetId); + return new NextResponse(null, { status: 204 }); + } catch (err) { + const msg = err instanceof Error ? err.message : "Failed to delete asset"; + return NextResponse.json({ error: msg }, { status: 502 }); + } +} diff --git a/src/app/api/edc/assets/route.ts b/src/app/api/edc/assets/route.ts new file mode 100644 index 0000000..ae753e2 --- /dev/null +++ b/src/app/api/edc/assets/route.ts @@ -0,0 +1,25 @@ +import { NextRequest, NextResponse } from "next/server"; +import { edcAssets } from "@/lib/edc-client"; + +export async function GET(request: NextRequest) { + try { + const offset = Number(request.nextUrl.searchParams.get("offset") ?? 0); + const limit = Number(request.nextUrl.searchParams.get("limit") ?? 200); + const assets = await edcAssets.list(offset, limit); + return NextResponse.json(assets); + } catch (err) { + const msg = err instanceof Error ? err.message : "Failed to list assets"; + return NextResponse.json({ error: msg }, { status: 502 }); + } +} + +export async function POST(request: NextRequest) { + try { + const body = await request.json(); + const result = await edcAssets.create(body); + return NextResponse.json(result, { status: 201 }); + } catch (err) { + const msg = err instanceof Error ? err.message : "Failed to create asset"; + return NextResponse.json({ error: msg }, { status: 502 }); + } +} diff --git a/src/app/api/edc/catalog/route.ts b/src/app/api/edc/catalog/route.ts new file mode 100644 index 0000000..936e5f5 --- /dev/null +++ b/src/app/api/edc/catalog/route.ts @@ -0,0 +1,19 @@ +import { NextRequest, NextResponse } from "next/server"; +import { edcCatalog } from "@/lib/edc-client"; + +export async function POST(request: NextRequest) { + try { + const { counterPartyAddress, counterPartyId } = await request.json(); + if (!counterPartyAddress) { + return NextResponse.json( + { error: "counterPartyAddress is required" }, + { status: 400 } + ); + } + const catalog = await edcCatalog.query(counterPartyAddress, counterPartyId); + return NextResponse.json(catalog); + } catch (err) { + const msg = err instanceof Error ? err.message : "Failed to query catalog"; + return NextResponse.json({ error: msg }, { status: 502 }); + } +} diff --git a/src/app/api/edc/negotiations/[negotiationId]/route.ts b/src/app/api/edc/negotiations/[negotiationId]/route.ts new file mode 100644 index 0000000..bb39f46 --- /dev/null +++ b/src/app/api/edc/negotiations/[negotiationId]/route.ts @@ -0,0 +1,16 @@ +import { NextRequest, NextResponse } from "next/server"; +import { edcNegotiations } from "@/lib/edc-client"; + +export async function GET( + _request: NextRequest, + { params }: { params: Promise<{ negotiationId: string }> } +) { + try { + const { negotiationId } = await params; + const negotiation = await edcNegotiations.get(negotiationId); + return NextResponse.json(negotiation); + } catch (err) { + const msg = err instanceof Error ? err.message : "Failed to get negotiation"; + return NextResponse.json({ error: msg }, { status: 502 }); + } +} diff --git a/src/app/api/edc/negotiations/route.ts b/src/app/api/edc/negotiations/route.ts new file mode 100644 index 0000000..fdc3e71 --- /dev/null +++ b/src/app/api/edc/negotiations/route.ts @@ -0,0 +1,25 @@ +import { NextRequest, NextResponse } from "next/server"; +import { edcNegotiations } from "@/lib/edc-client"; + +export async function GET(request: NextRequest) { + try { + const offset = Number(request.nextUrl.searchParams.get("offset") ?? 0); + const limit = Number(request.nextUrl.searchParams.get("limit") ?? 50); + const negotiations = await edcNegotiations.list(offset, limit); + return NextResponse.json(negotiations); + } catch (err) { + const msg = err instanceof Error ? err.message : "Failed to list negotiations"; + return NextResponse.json({ error: msg }, { status: 502 }); + } +} + +export async function POST(request: NextRequest) { + try { + const body = await request.json(); + const result = await edcNegotiations.initiate(body); + return NextResponse.json(result, { status: 201 }); + } catch (err) { + const msg = err instanceof Error ? err.message : "Failed to initiate negotiation"; + return NextResponse.json({ error: msg }, { status: 502 }); + } +} diff --git a/src/app/api/edc/policies/route.ts b/src/app/api/edc/policies/route.ts new file mode 100644 index 0000000..8233de8 --- /dev/null +++ b/src/app/api/edc/policies/route.ts @@ -0,0 +1,25 @@ +import { NextRequest, NextResponse } from "next/server"; +import { edcPolicies } from "@/lib/edc-client"; + +export async function GET(request: NextRequest) { + try { + const offset = Number(request.nextUrl.searchParams.get("offset") ?? 0); + const limit = Number(request.nextUrl.searchParams.get("limit") ?? 50); + const policies = await edcPolicies.list(offset, limit); + return NextResponse.json(policies); + } catch (err) { + const msg = err instanceof Error ? err.message : "Failed to list policies"; + return NextResponse.json({ error: msg }, { status: 502 }); + } +} + +export async function POST(request: NextRequest) { + try { + const body = await request.json(); + const result = await edcPolicies.create(body); + return NextResponse.json(result, { status: 201 }); + } catch (err) { + const msg = err instanceof Error ? err.message : "Failed to create policy"; + return NextResponse.json({ error: msg }, { status: 502 }); + } +} diff --git a/src/app/api/edc/status/route.ts b/src/app/api/edc/status/route.ts new file mode 100644 index 0000000..e511664 --- /dev/null +++ b/src/app/api/edc/status/route.ts @@ -0,0 +1,54 @@ +import { NextResponse } from "next/server"; +import { + edcHealthCheck, + edcAssets, + edcAgreements, + edcNegotiations, + edcTransfers, +} from "@/lib/edc-client"; + +export async function GET() { + const healthy = await edcHealthCheck(); + + if (!healthy) { + return NextResponse.json({ + connected: false, + assets: 0, + agreements: 0, + negotiations: 0, + transfers: 0, + }); + } + + try { + const [assets, agreements, negotiations, transfers] = await Promise.all([ + edcAssets.list(0, 1).then((a) => (Array.isArray(a) ? a : [])), + edcAgreements.list(0, 1).then((a) => (Array.isArray(a) ? a : [])), + edcNegotiations.list(0, 1).then((n) => (Array.isArray(n) ? n : [])), + edcTransfers.list(0, 1).then((t) => (Array.isArray(t) ? t : [])), + ]); + + // EDC query endpoints don't return total count directly; + // do a larger fetch to count published assets + const allAssets = await edcAssets.list(0, 500).then((a) => (Array.isArray(a) ? a : [])); + const allAgreements = await edcAgreements.list(0, 500).then((a) => (Array.isArray(a) ? a : [])); + const allNegotiations = await edcNegotiations.list(0, 500).then((n) => (Array.isArray(n) ? n : [])); + const allTransfers = await edcTransfers.list(0, 500).then((t) => (Array.isArray(t) ? t : [])); + + return NextResponse.json({ + connected: true, + assets: allAssets.length, + agreements: allAgreements.length, + negotiations: allNegotiations.length, + transfers: allTransfers.length, + }); + } catch { + return NextResponse.json({ + connected: true, + assets: 0, + agreements: 0, + negotiations: 0, + transfers: 0, + }); + } +} diff --git a/src/app/api/edc/sync/route.ts b/src/app/api/edc/sync/route.ts new file mode 100644 index 0000000..faa3032 --- /dev/null +++ b/src/app/api/edc/sync/route.ts @@ -0,0 +1,66 @@ +import { NextResponse } from "next/server"; +import { LAYER_METADATA } from "@/lib/data-sources"; +import { edcAssets, edcPolicies, edcContractDefs } from "@/lib/edc-client"; +import { + layerToEdcAsset, + layerToEdcContractDef, + createOpenDataPolicy, +} from "@/lib/edc-asset-mapper"; + +export async function POST() { + const results = { + policy: { success: false, error: null as string | null }, + assets: { created: 0, skipped: 0, failed: 0, errors: [] as string[] }, + contractDefs: { created: 0, skipped: 0, failed: 0, errors: [] as string[] }, + }; + + // 1. Create open data policy (ignore if already exists) + try { + await edcPolicies.create(createOpenDataPolicy()); + results.policy.success = true; + } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + if (msg.includes("409") || msg.includes("already exists") || msg.includes("duplicate")) { + results.policy.success = true; // already exists + } else { + results.policy.error = msg; + } + } + + // 2. Register each layer as an asset + contract definition + for (const layer of LAYER_METADATA) { + // Asset + try { + await edcAssets.create(layerToEdcAsset(layer)); + results.assets.created++; + } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + if (msg.includes("409") || msg.includes("already exists") || msg.includes("duplicate")) { + results.assets.skipped++; + } else { + results.assets.failed++; + results.assets.errors.push(`${layer.id}: ${msg}`); + } + } + + // Contract definition + try { + await edcContractDefs.create(layerToEdcContractDef(layer)); + results.contractDefs.created++; + } catch (err) { + const msg = err instanceof Error ? err.message : String(err); + if (msg.includes("409") || msg.includes("already exists") || msg.includes("duplicate")) { + results.contractDefs.skipped++; + } else { + results.contractDefs.failed++; + results.contractDefs.errors.push(`${layer.id}: ${msg}`); + } + } + } + + const total = LAYER_METADATA.length; + return NextResponse.json({ + total, + ...results, + }); +} diff --git a/src/app/api/edc/transfers/route.ts b/src/app/api/edc/transfers/route.ts new file mode 100644 index 0000000..ffe74ab --- /dev/null +++ b/src/app/api/edc/transfers/route.ts @@ -0,0 +1,25 @@ +import { NextRequest, NextResponse } from "next/server"; +import { edcTransfers } from "@/lib/edc-client"; + +export async function GET(request: NextRequest) { + try { + const offset = Number(request.nextUrl.searchParams.get("offset") ?? 0); + const limit = Number(request.nextUrl.searchParams.get("limit") ?? 50); + const transfers = await edcTransfers.list(offset, limit); + return NextResponse.json(transfers); + } catch (err) { + const msg = err instanceof Error ? err.message : "Failed to list transfers"; + return NextResponse.json({ error: msg }, { status: 502 }); + } +} + +export async function POST(request: NextRequest) { + try { + const body = await request.json(); + const result = await edcTransfers.initiate(body); + return NextResponse.json(result, { status: 201 }); + } catch (err) { + const msg = err instanceof Error ? err.message : "Failed to initiate transfer"; + return NextResponse.json({ error: msg }, { status: 502 }); + } +} diff --git a/src/app/dataspace/page.tsx b/src/app/dataspace/page.tsx new file mode 100644 index 0000000..7bd469d --- /dev/null +++ b/src/app/dataspace/page.tsx @@ -0,0 +1,52 @@ +"use client"; + +import { useState } from "react"; +import { Badge } from "@/components/ui/badge"; +import Dashboard from "@/components/dataspace/dashboard"; +import ProviderView from "@/components/dataspace/provider-view"; +import ConsumerView from "@/components/dataspace/consumer-view"; + +const TABS = [ + { id: "dashboard", label: "Dashboard" }, + { id: "provider", label: "Provider" }, + { id: "consumer", label: "Consumer" }, +] as const; + +type TabId = (typeof TABS)[number]["id"]; + +export default function DataspacePage() { + const [activeTab, setActiveTab] = useState("dashboard"); + + return ( +
+
+
+

Dataspace

+

+ Eclipse Dataspace Connector — publiceer datasets en consumeer data + van externe connectors via het Dataspace Protocol. +

+
+ + {/* Tab navigation */} +
+ {TABS.map((tab) => ( + setActiveTab(tab.id)} + > + {tab.label} + + ))} +
+ + {/* Tab content */} + {activeTab === "dashboard" && } + {activeTab === "provider" && } + {activeTab === "consumer" && } +
+
+ ); +} diff --git a/src/app/page.tsx b/src/app/page.tsx index 463b213..77e1c15 100644 --- a/src/app/page.tsx +++ b/src/app/page.tsx @@ -19,8 +19,9 @@ import Sidebar from "@/components/sidebar"; import FeaturePanel from "@/components/feature-panel"; import { useLayers } from "@/lib/use-layers"; import { useIsMobile } from "@/lib/use-mobile"; -import type { FeatureInfo, BasemapId } from "@/components/map-view"; +import type { FeatureInfo, BasemapId, FlyTarget } from "@/components/map-view"; import { BASEMAPS } from "@/components/map-view"; +import AddressSearch from "@/components/address-search"; const MapView = dynamic(() => import("@/components/map-view"), { ssr: false, @@ -39,6 +40,7 @@ export default function Home() { ); const [basemapId, setBasemapId] = useState("dark"); const [showBasemapPicker, setShowBasemapPicker] = useState(false); + const [flyTarget, setFlyTarget] = useState(null); const isMobile = useIsMobile(); // Close sidebar on first mobile detection @@ -104,6 +106,14 @@ export default function Home() { )} + {/* Address search */} +
+ setFlyTarget({ lng, lat, zoom: 17 })} + onClear={() => setFlyTarget(null)} + /> +
+ {/* Layer count badge */}
@@ -148,6 +158,7 @@ export default function Home() { visibleLayers={stableVisibleLayers} basemapId={basemapId} onFeatureClick={handleFeatureClick} + flyTarget={flyTarget} /> {/* Feature detail panel */} diff --git a/src/components/address-search.tsx b/src/components/address-search.tsx new file mode 100644 index 0000000..be1426b --- /dev/null +++ b/src/components/address-search.tsx @@ -0,0 +1,203 @@ +"use client"; + +import { useState, useRef, useEffect, useCallback } from "react"; +import { Search, X } from "lucide-react"; + +interface Suggestion { + weergavenaam: string; + type: string; + centroide_ll?: string; + id: string; +} + +interface AddressSearchProps { + onSelect: (lng: number, lat: number) => void; + onClear?: () => void; +} + +function parseWKTPoint(wkt: string | undefined): [number, number] | null { + if (!wkt) return null; + const match = wkt.match(/POINT\(([^ ]+) ([^ ]+)\)/); + if (!match) return null; + return [parseFloat(match[1]), parseFloat(match[2])]; +} + +export default function AddressSearch({ onSelect, onClear }: AddressSearchProps) { + const [query, setQuery] = useState(""); + const [suggestions, setSuggestions] = useState([]); + const [open, setOpen] = useState(false); + const [activeIndex, setActiveIndex] = useState(-1); + const containerRef = useRef(null); + const inputRef = useRef(null); + const abortRef = useRef(null); + const timerRef = useRef | null>(null); + + const fetchSuggestions = useCallback((q: string) => { + if (timerRef.current) clearTimeout(timerRef.current); + if (abortRef.current) abortRef.current.abort(); + + if (q.trim().length < 2) { + setSuggestions([]); + setOpen(false); + return; + } + + timerRef.current = setTimeout(async () => { + const controller = new AbortController(); + abortRef.current = controller; + try { + const res = await fetch( + `https://api.pdok.nl/bzk/locatieserver/search/v3_1/suggest?q=${encodeURIComponent(q)}&rows=7`, + { signal: controller.signal } + ); + if (!res.ok) return; + const data = await res.json(); + const docs: Suggestion[] = (data.response?.docs ?? []).map( + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (d: any) => ({ + weergavenaam: d.weergavenaam, + type: d.type, + centroide_ll: d.centroide_ll, + id: d.id, + }) + ); + setSuggestions(docs); + setOpen(docs.length > 0); + setActiveIndex(-1); + } catch { + // aborted or network error — ignore + } + }, 300); + }, []); + + const handleSelect = useCallback( + async (suggestion: Suggestion) => { + setQuery(suggestion.weergavenaam); + setOpen(false); + setSuggestions([]); + + // Try parsing coordinates from the suggestion itself + let coords = parseWKTPoint(suggestion.centroide_ll); + + // Fall back to the lookup endpoint when centroide_ll is missing + if (!coords) { + try { + const res = await fetch( + `https://api.pdok.nl/bzk/locatieserver/search/v3_1/lookup?id=${encodeURIComponent(suggestion.id)}` + ); + if (res.ok) { + const data = await res.json(); + coords = parseWKTPoint(data.response?.docs?.[0]?.centroide_ll); + } + } catch { + // network error — ignore + } + } + + if (coords) onSelect(coords[0], coords[1]); + }, + [onSelect] + ); + + const handleClear = useCallback(() => { + setQuery(""); + setSuggestions([]); + setOpen(false); + onClear?.(); + inputRef.current?.focus(); + }, [onClear]); + + const handleKeyDown = useCallback( + (e: React.KeyboardEvent) => { + if (e.key === "Escape") { + setOpen(false); + inputRef.current?.blur(); + return; + } + if (!open || suggestions.length === 0) return; + + if (e.key === "ArrowDown") { + e.preventDefault(); + setActiveIndex((i) => (i < suggestions.length - 1 ? i + 1 : 0)); + } else if (e.key === "ArrowUp") { + e.preventDefault(); + setActiveIndex((i) => (i > 0 ? i - 1 : suggestions.length - 1)); + } else if (e.key === "Enter" && activeIndex >= 0) { + e.preventDefault(); + handleSelect(suggestions[activeIndex]); + } + }, + [open, suggestions, activeIndex, handleSelect] + ); + + // Close on outside click + useEffect(() => { + function handleClick(e: MouseEvent) { + if (containerRef.current && !containerRef.current.contains(e.target as Node)) { + setOpen(false); + } + } + document.addEventListener("mousedown", handleClick); + return () => document.removeEventListener("mousedown", handleClick); + }, []); + + // Cleanup on unmount + useEffect(() => { + return () => { + if (timerRef.current) clearTimeout(timerRef.current); + if (abortRef.current) abortRef.current.abort(); + }; + }, []); + + return ( +
+
+ + { + setQuery(e.target.value); + fetchSuggestions(e.target.value); + }} + onFocus={() => { + if (suggestions.length > 0) setOpen(true); + }} + onKeyDown={handleKeyDown} + placeholder="Zoek adres of locatie..." + className="flex-1 bg-transparent text-xs outline-none placeholder:text-muted-foreground" + /> + {query && ( + + )} +
+ + {open && suggestions.length > 0 && ( +
+ {suggestions.map((s, i) => ( + + ))} +
+ )} +
+ ); +} diff --git a/src/components/dataspace/consumer-view.tsx b/src/components/dataspace/consumer-view.tsx new file mode 100644 index 0000000..b5dee16 --- /dev/null +++ b/src/components/dataspace/consumer-view.tsx @@ -0,0 +1,312 @@ +"use client"; + +import { useState, useEffect } from "react"; +import { Search, ArrowRight, RefreshCw, CheckCircle2, Clock, XCircle } from "lucide-react"; +import { Card, CardHeader, CardTitle, CardDescription, CardContent } from "@/components/ui/card"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { cn } from "@/lib/utils"; + +interface CatalogDataset { + "@id": string; + "@type"?: string; + name?: string; + description?: string; + "odrl:hasPolicy"?: Record | Record[]; + [key: string]: unknown; +} + +interface Negotiation { + "@id": string; + state: string; + counterPartyAddress: string; + contractAgreementId?: string; +} + +const STATE_CONFIG: Record = { + FINALIZED: { icon: CheckCircle2, color: "text-green-500", label: "Afgerond" }, + VERIFIED: { icon: CheckCircle2, color: "text-green-500", label: "Geverifieerd" }, + AGREED: { icon: CheckCircle2, color: "text-green-500", label: "Akkoord" }, + REQUESTED: { icon: Clock, color: "text-yellow-500", label: "Aangevraagd" }, + OFFERING: { icon: Clock, color: "text-yellow-500", label: "Aanbod" }, + ACCEPTED: { icon: Clock, color: "text-blue-500", label: "Geaccepteerd" }, + TERMINATED: { icon: XCircle, color: "text-red-500", label: "Beëindigd" }, + ERROR: { icon: XCircle, color: "text-red-500", label: "Fout" }, +}; + +export default function ConsumerView() { + const [connectorUrl, setConnectorUrl] = useState("http://localhost:8282/protocol"); + const [datasets, setDatasets] = useState([]); + const [catalogLoading, setCatalogLoading] = useState(false); + const [catalogError, setCatalogError] = useState(null); + const [negotiations, setNegotiations] = useState([]); + const [negotiating, setNegotiating] = useState>(new Set()); + const [transferring, setTransferring] = useState>(new Set()); + + // Fetch negotiations on mount + useEffect(() => { + fetchNegotiations(); + }, []); + + const fetchNegotiations = async () => { + try { + const res = await fetch("/api/edc/negotiations"); + const data = await res.json(); + setNegotiations(Array.isArray(data) ? data : []); + } catch { + // ignore + } + }; + + const queryCatalog = async () => { + if (!connectorUrl.trim()) return; + setCatalogLoading(true); + setCatalogError(null); + setDatasets([]); + try { + const res = await fetch("/api/edc/catalog", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ counterPartyAddress: connectorUrl }), + }); + if (!res.ok) throw new Error(`HTTP ${res.status}`); + const catalog = await res.json(); + const ds = catalog["dcat:dataset"]; + if (Array.isArray(ds)) { + setDatasets(ds); + } else if (ds) { + setDatasets([ds]); + } else { + setDatasets([]); + } + } catch (err) { + setCatalogError(err instanceof Error ? err.message : "Catalogus ophalen mislukt"); + } finally { + setCatalogLoading(false); + } + }; + + const negotiate = async (dataset: CatalogDataset) => { + const id = dataset["@id"]; + setNegotiating((prev) => new Set(prev).add(id)); + + try { + // Extract policy from dataset + const policies = dataset["odrl:hasPolicy"]; + const policy = Array.isArray(policies) ? policies[0] : policies; + if (!policy) throw new Error("Geen beleid gevonden in dataset"); + + await fetch("/api/edc/negotiations", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + counterPartyAddress: connectorUrl, + policy: { + ...policy, + "@type": "odrl:Offer", + "odrl:target": id, + }, + }), + }); + + // Refresh negotiations list + await fetchNegotiations(); + } catch { + // Error handled by UI showing negotiation didn't appear + } finally { + setNegotiating((prev) => { + const next = new Set(prev); + next.delete(id); + return next; + }); + } + }; + + const initiateTransfer = async (negotiation: Negotiation) => { + if (!negotiation.contractAgreementId) return; + const id = negotiation["@id"]; + setTransferring((prev) => new Set(prev).add(id)); + + try { + await fetch("/api/edc/transfers", { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + counterPartyAddress: negotiation.counterPartyAddress, + contractId: negotiation.contractAgreementId, + assetId: id, + }), + }); + } catch { + // ignore + } finally { + setTransferring((prev) => { + const next = new Set(prev); + next.delete(id); + return next; + }); + } + }; + + return ( +
+ {/* Catalog query */} +
+

Externe catalogus ophalen

+
+
+ + setConnectorUrl(e.target.value)} + className="w-full rounded-md border bg-background py-2 pl-9 pr-3 text-sm outline-none focus:ring-2 focus:ring-ring" + /> +
+ +
+ {catalogError && ( +

{catalogError}

+ )} +
+ + {/* Catalog results */} + {datasets.length > 0 && ( +
+

+ Catalogus resultaten + + {datasets.length} datasets + +

+
+ {datasets.map((ds) => { + const name = + (ds.name as string) ?? + (ds["https://w3id.org/edc/v0.0.1/ns/name"] as string) ?? + ds["@id"]; + const desc = + (ds.description as string) ?? + (ds["https://w3id.org/edc/v0.0.1/ns/description"] as string) ?? + ""; + const isNegotiating = negotiating.has(ds["@id"]); + + return ( + + + {name} + {desc && ( + + {desc} + + )} + + + + {ds["@id"]} + + + + + ); + })} +
+
+ )} + + {/* Active negotiations */} +
+
+

Onderhandelingen

+ +
+ {negotiations.length === 0 ? ( +

+ Nog geen onderhandelingen gestart. +

+ ) : ( +
+ {negotiations.map((neg) => { + const cfg = STATE_CONFIG[neg.state] ?? { + icon: Clock, + color: "text-muted-foreground", + label: neg.state, + }; + const StateIcon = cfg.icon; + const canTransfer = + (neg.state === "FINALIZED" || neg.state === "VERIFIED") && + !!neg.contractAgreementId; + + return ( + + + +
+

{neg["@id"]}

+

+ {neg.counterPartyAddress} +

+
+ + {cfg.label} + + {canTransfer && ( + + )} +
+
+ ); + })} +
+ )} +
+
+ ); +} diff --git a/src/components/dataspace/dashboard.tsx b/src/components/dataspace/dashboard.tsx new file mode 100644 index 0000000..20ea7ce --- /dev/null +++ b/src/components/dataspace/dashboard.tsx @@ -0,0 +1,113 @@ +"use client"; + +import { useState, useEffect } from "react"; +import { Card, CardHeader, CardTitle, CardContent } from "@/components/ui/card"; +import { RefreshCw, Package, FileCheck, Handshake, ArrowRightLeft } from "lucide-react"; +import { Button } from "@/components/ui/button"; +import { cn } from "@/lib/utils"; + +interface StatusData { + connected: boolean; + assets: number; + agreements: number; + negotiations: number; + transfers: number; +} + +export default function Dashboard() { + const [status, setStatus] = useState(null); + const [loading, setLoading] = useState(true); + + const fetchStatus = async () => { + setLoading(true); + try { + const res = await fetch("/api/edc/status"); + const data = await res.json(); + setStatus(data); + } catch { + setStatus(null); + } finally { + setLoading(false); + } + }; + + useEffect(() => { + fetchStatus(); + }, []); + + const stats = [ + { label: "Gepubliceerde assets", value: status?.assets ?? 0, icon: Package }, + { label: "Contracten", value: status?.agreements ?? 0, icon: FileCheck }, + { label: "Onderhandelingen", value: status?.negotiations ?? 0, icon: Handshake }, + { label: "Transfers", value: status?.transfers ?? 0, icon: ArrowRightLeft }, + ]; + + return ( +
+ {/* Connection status */} +
+
+
+ + {loading + ? "Verbinding controleren..." + : status?.connected + ? "EDC Connector verbonden" + : "EDC Connector niet bereikbaar"} + +
+ +
+ + {/* Stats grid */} +
+ {stats.map(({ label, value, icon: Icon }) => ( + + + + {label} + + + + +
{loading ? "–" : value}
+
+
+ ))} +
+ + {/* Info box */} + {!loading && !status?.connected && ( + + +

EDC Connector starten

+

+ Start de EDC containers met{" "} + npm run edc:up + {" "}en registreer de assets met{" "} + npm run edc:register. +

+
+
+ )} +
+ ); +} diff --git a/src/components/dataspace/provider-view.tsx b/src/components/dataspace/provider-view.tsx new file mode 100644 index 0000000..5da04e8 --- /dev/null +++ b/src/components/dataspace/provider-view.tsx @@ -0,0 +1,210 @@ +"use client"; + +import { useState, useEffect, useMemo } from "react"; +import { Search, RefreshCw, Package } from "lucide-react"; +import { Card, CardHeader, CardTitle, CardDescription, CardContent } from "@/components/ui/card"; +import { Badge } from "@/components/ui/badge"; +import { Button } from "@/components/ui/button"; +import { cn } from "@/lib/utils"; + +interface EdcAsset { + "@id": string; + properties: Record; +} + +const CATEGORY_LABELS: Record = { + verkeer: "Verkeer & Transport", + gebouwen: "Gebouwen & Adressen", + "openbare-ruimte": "Openbare Ruimte", + grenzen: "Grenzen & Gebieden", + milieu: "Milieu & Klimaat", + voorzieningen: "Voorzieningen", +}; + +export default function ProviderView() { + const [assets, setAssets] = useState([]); + const [loading, setLoading] = useState(true); + const [syncing, setSyncing] = useState(false); + const [syncResult, setSyncResult] = useState(null); + const [search, setSearch] = useState(""); + const [selectedCategory, setSelectedCategory] = useState(null); + + const fetchAssets = async () => { + setLoading(true); + try { + const res = await fetch("/api/edc/assets"); + const data = await res.json(); + setAssets(Array.isArray(data) ? data : []); + } catch { + setAssets([]); + } finally { + setLoading(false); + } + }; + + useEffect(() => { + fetchAssets(); + }, []); + + const handleSync = async () => { + setSyncing(true); + setSyncResult(null); + try { + const res = await fetch("/api/edc/sync", { method: "POST" }); + const data = await res.json(); + setSyncResult( + `${data.assets.created} aangemaakt, ${data.assets.skipped} overgeslagen, ${data.assets.failed} mislukt` + ); + await fetchAssets(); + } catch (err) { + setSyncResult(err instanceof Error ? err.message : "Synchronisatie mislukt"); + } finally { + setSyncing(false); + } + }; + + // Collect categories from assets + const categories = useMemo(() => { + const counts: Record = {}; + for (const a of assets) { + const cat = (a.properties?.["zwolle:category"] as string) ?? "overig"; + counts[cat] = (counts[cat] ?? 0) + 1; + } + return Object.entries(counts).map(([id, count]) => ({ + id, + label: CATEGORY_LABELS[id] ?? id, + count, + })); + }, [assets]); + + const filtered = useMemo(() => { + let result = assets; + if (selectedCategory) { + result = result.filter( + (a) => (a.properties?.["zwolle:category"] as string) === selectedCategory + ); + } + if (search) { + const q = search.toLowerCase(); + result = result.filter((a) => { + const name = ((a.properties?.name as string) ?? "").toLowerCase(); + const desc = ((a.properties?.description as string) ?? "").toLowerCase(); + const id = (a["@id"] ?? "").toLowerCase(); + return name.includes(q) || desc.includes(q) || id.includes(q); + }); + } + return result; + }, [assets, selectedCategory, search]); + + return ( +
+ {/* Header actions */} +
+ + {syncResult && ( + {syncResult} + )} +
+ + {/* Search */} +
+ + setSearch(e.target.value)} + className="w-full rounded-md border bg-background py-2 pl-9 pr-3 text-sm outline-none focus:ring-2 focus:ring-ring" + /> +
+ + {/* Category filter */} +
+ setSelectedCategory(null)} + > + Alles + + {categories.map((cat) => ( + + setSelectedCategory(selectedCategory === cat.id ? null : cat.id) + } + > + {cat.label} + {cat.count} + + ))} +
+ + {/* Count */} +

+ {filtered.length} {filtered.length === 1 ? "asset" : "assets"} + {loading ? " laden..." : " gevonden"} +

+ + {/* Asset grid */} + {loading ? ( +
+ Assets laden... +
+ ) : filtered.length === 0 ? ( +
+ Geen assets gevonden.{" "} + {assets.length === 0 && ( + Klik "Synchroniseer" om layers te registreren. + )} +
+ ) : ( +
+ {filtered.map((asset) => { + const name = (asset.properties?.name as string) ?? asset["@id"]; + const desc = (asset.properties?.description as string) ?? ""; + const cat = (asset.properties?.["zwolle:category"] as string) ?? ""; + const catLabel = CATEGORY_LABELS[cat] ?? cat; + + return ( + + +
+ + + {name} + + {catLabel && ( + + {catLabel} + + )} +
+ + {desc} + +
+ + + {asset["@id"]} + + +
+ ); + })} +
+ )} +
+ ); +} diff --git a/src/components/map-view.tsx b/src/components/map-view.tsx index 0c98273..6426830 100644 --- a/src/components/map-view.tsx +++ b/src/components/map-view.tsx @@ -166,10 +166,17 @@ const INITIAL_VIEW = { bearing: 0, }; +export interface FlyTarget { + lng: number; + lat: number; + zoom: number; +} + interface MapViewProps { visibleLayers: LayerState[]; basemapId: BasemapId; onFeatureClick?: (info: FeatureInfo | null) => void; + flyTarget?: FlyTarget | null; } export interface FeatureInfo { @@ -182,6 +189,7 @@ export default function MapView({ visibleLayers, basemapId, onFeatureClick, + flyTarget, }: MapViewProps) { const containerRef = useRef(null); const mapRef = useRef(null); @@ -542,6 +550,31 @@ export default function MapView({ } }, [visibleLayers]); + // Fly to target and show marker + const markerRef = useRef(null); + useEffect(() => { + const map = mapRef.current; + if (!map) return; + + // Remove previous marker + if (markerRef.current) { + markerRef.current.remove(); + markerRef.current = null; + } + + if (!flyTarget) return; + + map.flyTo({ + center: [flyTarget.lng, flyTarget.lat], + zoom: flyTarget.zoom, + duration: 1500, + }); + + markerRef.current = new maplibregl.Marker({ color: "#3b82f6" }) + .setLngLat([flyTarget.lng, flyTarget.lat]) + .addTo(map); + }, [flyTarget]); + return (
diff --git a/src/components/nav-bar.tsx b/src/components/nav-bar.tsx index 95acd64..1130139 100644 --- a/src/components/nav-bar.tsx +++ b/src/components/nav-bar.tsx @@ -2,12 +2,13 @@ import Link from "next/link"; import { usePathname } from "next/navigation"; -import { Map, Database, BookOpen } from "lucide-react"; +import { Map, Database, Network, BookOpen } from "lucide-react"; import { cn } from "@/lib/utils"; const NAV_LINKS = [ { href: "/", label: "Kaart", icon: Map }, { href: "/api-gateway", label: "API Gateway", icon: Database }, + { href: "/dataspace", label: "Dataspace", icon: Network }, { href: "/handleiding", label: "Handleiding", icon: BookOpen }, ] as const; diff --git a/src/components/sidebar.tsx b/src/components/sidebar.tsx index 435c64b..68ffe10 100644 --- a/src/components/sidebar.tsx +++ b/src/components/sidebar.tsx @@ -54,6 +54,7 @@ import { Ship, GraduationCap, ShoppingCart, + Truck, X, ChevronsUpDown, ChevronsDownUp, @@ -63,6 +64,7 @@ import { CheckCircle2, type LucideIcon, } from "lucide-react"; +import { Lock, Unlock } from "lucide-react"; import { memo, useState, useCallback, useMemo } from "react"; import { Badge } from "@/components/ui/badge"; import { Switch } from "@/components/ui/switch"; @@ -123,6 +125,7 @@ const ICON_MAP: Record = { Ship, GraduationCap, ShoppingCart, + Truck, }; interface SidebarProps { @@ -185,6 +188,9 @@ const LayerRow = memo(function LayerRow({ {layer.name} + {layer.isNew && ( + ✦ + )} {layer.loading && ( @@ -283,6 +289,7 @@ export default function Sidebar({ layers, toggleLayer, fetchFullLayer, stats }: >(new Set(Object.keys(CATEGORIES) as LayerCategory[])); const [searchQuery, setSearchQuery] = useState(""); const [sortOrder, setSortOrder] = useState<"default" | "az" | "za">("default"); + const [accessFilter, setAccessFilter] = useState<"all" | "open" | "restricted">("all"); const toggleCategory = useCallback((cat: LayerCategory) => { setExpandedCategories((prev) => { @@ -306,7 +313,14 @@ export default function Sidebar({ layers, toggleLayer, fetchFullLayer, stats }: const grouped = useMemo(() => { const query = searchQuery.toLowerCase().trim(); return allCategories.map((cat) => { - const catLayers = layers.filter((l) => l.category === cat); + let catLayers = layers.filter((l) => l.category === cat); + if (accessFilter !== "all") { + catLayers = catLayers.filter((l) => + accessFilter === "restricted" + ? l.accessType === "restricted" + : (l.accessType ?? "open") === "open" + ); + } const filteredLayers = query ? catLayers.filter( (l) => @@ -327,7 +341,7 @@ export default function Sidebar({ layers, toggleLayer, fetchFullLayer, stats }: layers: sortedLayers, }; }); - }, [layers, searchQuery, allCategories, sortOrder]); + }, [layers, searchQuery, allCategories, sortOrder, accessFilter]); const isSearching = searchQuery.trim().length > 0; @@ -445,6 +459,30 @@ export default function Sidebar({ layers, toggleLayer, fetchFullLayer, stats }:
+ {/* Access type filter */} +
+
+ {([ + { value: "all", label: "Alle", icon: null }, + { value: "open", label: "Open", icon: Unlock }, + { value: "restricted", label: "API-key", icon: Lock }, + ] as const).map(({ value, label, icon: Icon }) => ( + + ))} +
+
+ {/* Layers - native scroll for reliable scrolling */}
diff --git a/src/lib/data-sources.ts b/src/lib/data-sources.ts index 7d15bb2..a3b021f 100644 --- a/src/lib/data-sources.ts +++ b/src/lib/data-sources.ts @@ -4,7 +4,10 @@ export type LayerCategory = | "openbare-ruimte" | "grenzen" | "milieu" - | "voorzieningen"; + | "voorzieningen" + | "sociaal" + | "wonen" + | "gezondheid"; export interface DataSource { id: string; @@ -28,6 +31,8 @@ export interface DataSource { extruded?: boolean; getElevation?: number; renderAs?: "msi-icon" | "speed-point"; + isNew?: boolean; + accessType?: "open" | "restricted"; colorMap?: { property: string; values: Record; @@ -85,9 +90,23 @@ async function fetchPDOKOGCAPI( limit = 1000, full = false ): Promise { - const count = full ? 50000 : limit; - const url = `${baseUrl}/collections/${collection}/items?limit=${count}&bbox=${ZWOLLE_BBOX}&f=json`; - return fetchGeoJSON(url); + const pageSize = Math.min(full ? 1000 : limit, 1000); // OGC APIs typically cap at 1000 + const url = `${baseUrl}/collections/${collection}/items?limit=${pageSize}&bbox=${ZWOLLE_BBOX}&f=json`; + const first = await fetchGeoJSON(url); + if (!full || first.features.length < pageSize) return first; + + // Paginate to fetch all features + const allFeatures = [...first.features]; + let offset = pageSize; + const maxPages = 20; // Safety limit + for (let page = 1; page < maxPages; page++) { + const pageUrl = `${baseUrl}/collections/${collection}/items?limit=${pageSize}&offset=${offset}&bbox=${ZWOLLE_BBOX}&f=json`; + const next = await fetchGeoJSON(pageUrl); + allFeatures.push(...next.features); + if (next.features.length < pageSize) break; + offset += pageSize; + } + return { type: "FeatureCollection", features: allFeatures }; } async function fetchOverijsselWFS( @@ -134,9 +153,55 @@ export const CATEGORIES: Record< grenzen: { label: "Grenzen & Gebieden", icon: "MapPin" }, milieu: { label: "Milieu & Klimaat", icon: "Leaf" }, voorzieningen: { label: "Voorzieningen", icon: "Store" }, + sociaal: { label: "Sociaal Domein", icon: "Users" }, + wonen: { label: "Wonen & WOZ", icon: "Home" }, + gezondheid: { label: "Gezondheid & Nabijheid", icon: "HeartPulse" }, }; // Cached fetch for pakketpunten (shared across point + buffer layers) +// CBS WFS helper — cleans sentinel values (-99995, -99997, -99998, -99999) +const CBS_SENTINELS = new Set([-99995, -99997, -99998, -99999]); +function cleanCBSProperties( + fc: GeoJSON.FeatureCollection +): GeoJSON.FeatureCollection { + return { + ...fc, + features: fc.features.map((f) => ({ + ...f, + properties: Object.fromEntries( + Object.entries(f.properties || {}).map(([k, v]) => [ + k, + typeof v === "number" && CBS_SENTINELS.has(v) ? null : v, + ]) + ), + })), + }; +} + +async function fetchCBSBuurten( + full = false +): Promise { + const data = await fetchPDOKWFS( + "wijkenbuurten:buurten", + "https://service.pdok.nl/cbs/wijkenbuurten/2024/wfs/v1_0", + 200, + full + ); + return cleanCBSProperties(data); +} + +async function fetchCBSWijken( + full = false +): Promise { + const data = await fetchPDOKWFS( + "wijkenbuurten:wijken", + "https://service.pdok.nl/cbs/wijkenbuurten/2024/wfs/v1_0", + 100, + full + ); + return cleanCBSProperties(data); +} + let pakketpuntenCache: GeoJSON.FeatureCollection | null = null; async function fetchPakketpunten(): Promise { if (pakketpuntenCache) return pakketpuntenCache; @@ -702,7 +767,7 @@ export const DATA_SOURCES: DataSource[] = [ source: "Gemeente Zwolle GIS", description: "Openbare afvalbakken", category: "openbare-ruimte", - color: [160, 160, 160, 200], + color: [140, 160, 110, 200], icon: "Trash2", visible: false, loading: false, @@ -1021,7 +1086,7 @@ export const DATA_SOURCES: DataSource[] = [ source: "Gemeente Zwolle GIS", description: "Rioolputten in Zwolle", category: "voorzieningen", - color: [100, 100, 100, 180], + color: [180, 130, 70, 200], icon: "CircleDot", visible: false, loading: false, @@ -1038,7 +1103,7 @@ export const DATA_SOURCES: DataSource[] = [ source: "Gemeente Zwolle GIS", description: "Rioolstrengen / leidingen", category: "voorzieningen", - color: [80, 80, 80, 160], + color: [160, 110, 60, 180], icon: "Route", visible: false, loading: false, @@ -1572,7 +1637,7 @@ export const DATA_SOURCES: DataSource[] = [ { id: "cbs-buurten", name: "CBS Buurten (Demografie)", - endpoint: "service.pdok.nl/cbs/wijkenbuurten/2023/wfs/v1_0", + endpoint: "service.pdok.nl/cbs/wijkenbuurten/2024/wfs/v1_0", source: "PDOK / CBS", description: "Buurten met demografische gegevens (bevolking, inkomen, woningen, afstanden)", @@ -1588,7 +1653,7 @@ export const DATA_SOURCES: DataSource[] = [ fetchData: async (full) => fetchPDOKWFS( "wijkenbuurten:buurten", - "https://service.pdok.nl/cbs/wijkenbuurten/2023/wfs/v1_0", + "https://service.pdok.nl/cbs/wijkenbuurten/2024/wfs/v1_0", 200, full ), @@ -2055,6 +2120,26 @@ export const DATA_SOURCES: DataSource[] = [ "https://data.ndw.nu/api/rest/static-road-data/traffic-signs/v4/current-state?countyCode=GM0193" ), }, + { + id: "ndw-verkeersborden-e7", + name: "Verkeersborden E7 – Laden/Lossen (NDW)", + endpoint: + "data.ndw.nu/api/rest/static-road-data/traffic-signs/v4/current-state?rvvCode=E7&countyCode=GM0193", + source: "NDW", + description: + "E7-verkeersborden in Zwolle: zones voor laden en lossen", + category: "verkeer", + color: [0, 180, 255, 220], + icon: "Truck", + visible: false, + loading: false, + pointType: "scatterplot", + radius: 5, + fetchData: async () => + fetchGeoJSON( + "https://data.ndw.nu/api/rest/static-road-data/traffic-signs/v4/current-state?rvvCode=E7&countyCode=GM0193" + ), + }, // --- NDW Situatieberichten / Incidenten --- { @@ -2352,6 +2437,720 @@ export const DATA_SOURCES: DataSource[] = [ fetchData: async (full) => fetchZwolleGIS("TOR_stadsdelen", 0, "FeatureServer", 2000, full), }, + + // ═══════════════════════════════════════ + // SOCIAAL DOMEIN (CBS Wijken & Buurten) + // ═══════════════════════════════════════ + { + id: "cbs-wmo", + name: "Wmo Clienten (per buurt)", + endpoint: "service.pdok.nl/cbs/wijkenbuurten/2024/wfs/v1_0", + source: "PDOK / CBS", + description: + "Aantal Wmo-clienten en Wmo-clienten per 1.000 inwoners per buurt (Wet maatschappelijke ondersteuning)", + category: "sociaal", + color: [0, 150, 200, 100], + icon: "Users", + visible: false, + loading: false, + filled: true, + stroked: true, + lineWidth: 1, + defaultLimit: 200, + fetchData: async (full) => fetchCBSBuurten(full), + }, + { + id: "cbs-jeugdzorg", + name: "Jeugdzorg (per buurt)", + endpoint: "service.pdok.nl/cbs/wijkenbuurten/2024/wfs/v1_0", + source: "PDOK / CBS", + description: + "Jongeren met jeugdzorg in natura: aantal en percentage per buurt", + category: "sociaal", + color: [180, 100, 220, 100], + icon: "Users", + visible: false, + loading: false, + filled: true, + stroked: true, + lineWidth: 1, + defaultLimit: 200, + fetchData: async (full) => fetchCBSBuurten(full), + }, + { + id: "cbs-bijstand", + name: "Bijstand / Participatiewet (per buurt)", + endpoint: "service.pdok.nl/cbs/wijkenbuurten/2024/wfs/v1_0", + source: "PDOK / CBS", + description: + "Personen met bijstandsuitkering, AO-uitkering en WW-uitkering per buurt", + category: "sociaal", + color: [220, 120, 60, 100], + icon: "Users", + visible: false, + loading: false, + filled: true, + stroked: true, + lineWidth: 1, + defaultLimit: 200, + fetchData: async (full) => fetchCBSBuurten(full), + }, + { + id: "cbs-sociaal-minimum", + name: "Sociaal Minimum (per buurt)", + endpoint: "service.pdok.nl/cbs/wijkenbuurten/2024/wfs/v1_0", + source: "PDOK / CBS", + description: + "Huishoudens onder/rond sociaal minimum, tot 110% en 120% van sociaal minimum per buurt", + category: "sociaal", + color: [200, 80, 80, 100], + icon: "Users", + visible: false, + loading: false, + filled: true, + stroked: true, + lineWidth: 1, + defaultLimit: 200, + fetchData: async (full) => fetchCBSBuurten(full), + }, + { + id: "cbs-arbeidsparticipatie", + name: "Arbeidsparticipatie (per buurt)", + endpoint: "service.pdok.nl/cbs/wijkenbuurten/2024/wfs/v1_0", + source: "PDOK / CBS", + description: + "Netto arbeidsparticipatie, percentage werknemers en zelfstandigen per buurt", + category: "sociaal", + color: [60, 160, 120, 100], + icon: "Users", + visible: false, + loading: false, + filled: true, + stroked: true, + lineWidth: 1, + defaultLimit: 200, + fetchData: async (full) => fetchCBSBuurten(full), + }, + { + id: "cbs-wijken-sociaal", + name: "Sociaal Domein (per wijk)", + endpoint: "service.pdok.nl/cbs/wijkenbuurten/2024/wfs/v1_0", + source: "PDOK / CBS", + description: + "Wmo, jeugdzorg, bijstand, uitkeringen en sociaal minimum geaggregeerd per wijk", + category: "sociaal", + color: [0, 130, 180, 80], + icon: "Users", + visible: false, + loading: false, + filled: true, + stroked: true, + lineWidth: 2, + defaultLimit: 100, + fetchData: async (full) => fetchCBSWijken(full), + }, + + // ═══════════════════════════════════════ + // WONEN & WOZ (CBS Wijken & Buurten) + // ═══════════════════════════════════════ + { + id: "cbs-woz", + name: "WOZ Woningwaarde (per buurt)", + endpoint: "service.pdok.nl/cbs/wijkenbuurten/2024/wfs/v1_0", + source: "PDOK / CBS", + description: + "Gemiddelde WOZ-waarde van woningen per buurt", + category: "wonen", + color: [220, 180, 40, 100], + icon: "Home", + visible: false, + loading: false, + filled: true, + stroked: true, + lineWidth: 1, + defaultLimit: 200, + fetchData: async (full) => fetchCBSBuurten(full), + }, + { + id: "cbs-woningvoorraad", + name: "Woningvoorraad (per buurt)", + endpoint: "service.pdok.nl/cbs/wijkenbuurten/2024/wfs/v1_0", + source: "PDOK / CBS", + description: + "Aantal woningen, percentage eengezins/meergezins, bouwjaarklasse en leegstand per buurt", + category: "wonen", + color: [160, 120, 200, 100], + icon: "Home", + visible: false, + loading: false, + filled: true, + stroked: true, + lineWidth: 1, + defaultLimit: 200, + fetchData: async (full) => fetchCBSBuurten(full), + }, + { + id: "cbs-huur-koop", + name: "Huur vs Koop (per buurt)", + endpoint: "service.pdok.nl/cbs/wijkenbuurten/2024/wfs/v1_0", + source: "PDOK / CBS", + description: + "Percentage huurwoningen, koopwoningen en woningcorporatiebezit per buurt", + category: "wonen", + color: [100, 160, 60, 100], + icon: "Home", + visible: false, + loading: false, + filled: true, + stroked: true, + lineWidth: 1, + defaultLimit: 200, + fetchData: async (full) => fetchCBSBuurten(full), + }, + { + id: "cbs-energie-verbruik", + name: "Energieverbruik Woningen (per buurt)", + endpoint: "service.pdok.nl/cbs/wijkenbuurten/2024/wfs/v1_0", + source: "PDOK / CBS", + description: + "Gemiddeld gas- en elektriciteitsverbruik per woningtype per buurt", + category: "wonen", + color: [255, 180, 0, 100], + icon: "Zap", + visible: false, + loading: false, + filled: true, + stroked: true, + lineWidth: 1, + defaultLimit: 200, + fetchData: async (full) => fetchCBSBuurten(full), + }, + { + id: "cbs-wijken-wonen", + name: "WOZ & Woningen (per wijk)", + endpoint: "service.pdok.nl/cbs/wijkenbuurten/2024/wfs/v1_0", + source: "PDOK / CBS", + description: + "WOZ-waarde, woningvoorraad, huur/koop en energieverbruik geaggregeerd per wijk", + category: "wonen", + color: [200, 160, 40, 80], + icon: "Home", + visible: false, + loading: false, + filled: true, + stroked: true, + lineWidth: 2, + defaultLimit: 100, + fetchData: async (full) => fetchCBSWijken(full), + }, + { + id: "cbs-vierkant-100m", + name: "CBS Vierkant 100m (Woningen)", + endpoint: "service.pdok.nl/cbs/vierkantstatistieken100m/2024/wfs/v1_0", + source: "PDOK / CBS", + description: + "Aantal inwoners en woningen per 100m gridcel — zeer fijnmazig", + category: "wonen", + color: [140, 100, 200, 80], + icon: "LayoutGrid", + visible: false, + loading: false, + filled: true, + stroked: false, + defaultLimit: 500, + fetchData: async (full) => { + const data = await fetchPDOKWFS( + "vierkantstatistieken100m:vierkant_100m", + "https://service.pdok.nl/cbs/vierkantstatistieken100m/2024/wfs/v1_0", + 500, + full + ); + return cleanCBSProperties(data); + }, + }, + { + id: "cbs-vierkant-500m", + name: "CBS Vierkant 500m (Woningen)", + endpoint: "service.pdok.nl/cbs/vierkantstatistieken500m/2024/wfs/v1_0", + source: "PDOK / CBS", + description: + "Inwoners, woningen, demografische en nabijheidsgegevens per 500m gridcel", + category: "wonen", + color: [120, 80, 180, 80], + icon: "LayoutGrid", + visible: false, + loading: false, + filled: true, + stroked: false, + defaultLimit: 200, + fetchData: async (full) => { + const data = await fetchPDOKWFS( + "vierkantstatistieken500m:Vierkant500M2024", + "https://service.pdok.nl/cbs/vierkantstatistieken500m/2024/wfs/v1_0", + 200, + full + ); + return cleanCBSProperties(data); + }, + }, + + // ═══════════════════════════════════════ + // GEZONDHEID & NABIJHEID (CBS) + // ═══════════════════════════════════════ + { + id: "cbs-nabijheid-huisarts", + name: "Nabijheid Huisarts (per buurt)", + endpoint: "service.pdok.nl/cbs/wijkenbuurten/2024/wfs/v1_0", + source: "PDOK / CBS", + description: + "Gemiddelde afstand tot huisartsenpraktijk en huisartsenpost, aantal binnen 1/3/5 km per buurt", + category: "gezondheid", + color: [255, 80, 80, 100], + icon: "HeartPulse", + visible: false, + loading: false, + filled: true, + stroked: true, + lineWidth: 1, + defaultLimit: 200, + fetchData: async (full) => fetchCBSBuurten(full), + }, + { + id: "cbs-nabijheid-ziekenhuis", + name: "Nabijheid Ziekenhuis (per buurt)", + endpoint: "service.pdok.nl/cbs/wijkenbuurten/2024/wfs/v1_0", + source: "PDOK / CBS", + description: + "Gemiddelde afstand tot ziekenhuis (incl/excl buitenpoli), aantal binnen 5/10/20 km per buurt", + category: "gezondheid", + color: [200, 60, 60, 100], + icon: "HeartPulse", + visible: false, + loading: false, + filled: true, + stroked: true, + lineWidth: 1, + defaultLimit: 200, + fetchData: async (full) => fetchCBSBuurten(full), + }, + { + id: "cbs-nabijheid-apotheek", + name: "Nabijheid Apotheek (per buurt)", + endpoint: "service.pdok.nl/cbs/wijkenbuurten/2024/wfs/v1_0", + source: "PDOK / CBS", + description: + "Gemiddelde afstand tot apotheek per buurt", + category: "gezondheid", + color: [60, 180, 120, 100], + icon: "HeartPulse", + visible: false, + loading: false, + filled: true, + stroked: true, + lineWidth: 1, + defaultLimit: 200, + fetchData: async (full) => fetchCBSBuurten(full), + }, + { + id: "cbs-nabijheid-onderwijs", + name: "Nabijheid Onderwijs (per buurt)", + endpoint: "service.pdok.nl/cbs/wijkenbuurten/2024/wfs/v1_0", + source: "PDOK / CBS", + description: + "Afstand tot basisonderwijs, voortgezet onderwijs (VMBO, HAVO/VWO) en kinderopvang per buurt", + category: "gezondheid", + color: [100, 100, 220, 100], + icon: "GraduationCap", + visible: false, + loading: false, + filled: true, + stroked: true, + lineWidth: 1, + defaultLimit: 200, + fetchData: async (full) => fetchCBSBuurten(full), + }, + { + id: "cbs-nabijheid-voorzieningen", + name: "Nabijheid Dagelijkse Voorzieningen (per buurt)", + endpoint: "service.pdok.nl/cbs/wijkenbuurten/2024/wfs/v1_0", + source: "PDOK / CBS", + description: + "Afstand tot supermarkt, warenhuis, bibliotheek, brandweer, treinstation en OV-overstap per buurt", + category: "gezondheid", + color: [160, 140, 60, 100], + icon: "Store", + visible: false, + loading: false, + filled: true, + stroked: true, + lineWidth: 1, + defaultLimit: 200, + fetchData: async (full) => fetchCBSBuurten(full), + }, + { + id: "cbs-wijken-gezondheid", + name: "Nabijheid & Gezondheid (per wijk)", + endpoint: "service.pdok.nl/cbs/wijkenbuurten/2024/wfs/v1_0", + source: "PDOK / CBS", + description: + "Nabijheid huisarts, ziekenhuis, apotheek, onderwijs en voorzieningen geaggregeerd per wijk", + category: "gezondheid", + color: [220, 100, 80, 80], + icon: "HeartPulse", + visible: false, + loading: false, + filled: true, + stroked: true, + lineWidth: 2, + defaultLimit: 100, + fetchData: async (full) => fetchCBSWijken(full), + }, + + // ═══════════════════════════════════════ + // NIEUW: MINIGIIM DATASETS + // ═══════════════════════════════════════ + + // --- BGT Topografie (extra collecties) --- + { + id: "bgt-wegdeel", + name: "BGT Wegdeel", + endpoint: "api.pdok.nl/lv/bgt/ogc/v1/collections/wegdeel/items", + source: "PDOK (BGT)", + description: "Wegen en paden uit de Basisregistratie Grootschalige Topografie", + category: "verkeer", + color: [180, 180, 180, 120], + icon: "Route", + visible: false, + loading: false, + filled: true, + stroked: true, + lineWidth: 1, + defaultLimit: 500, + isNew: true, + fetchData: async (full) => + fetchPDOKOGCAPI("https://api.pdok.nl/lv/bgt/ogc/v1", "wegdeel", 500, full), + }, + { + id: "bgt-begroeidterreindeel", + name: "BGT Begroeid Terreindeel", + endpoint: "api.pdok.nl/lv/bgt/ogc/v1/collections/begroeidterreindeel/items", + source: "PDOK (BGT)", + description: "Groengebieden: gras, bos, struiken en overig begroeid terrein", + category: "openbare-ruimte", + color: [80, 180, 60, 100], + icon: "TreePine", + visible: false, + loading: false, + filled: true, + stroked: false, + defaultLimit: 500, + isNew: true, + fetchData: async (full) => + fetchPDOKOGCAPI("https://api.pdok.nl/lv/bgt/ogc/v1", "begroeidterreindeel", 500, full), + }, + { + id: "bgt-onbegroeidterreindeel", + name: "BGT Onbegroeid Terreindeel", + endpoint: "api.pdok.nl/lv/bgt/ogc/v1/collections/onbegroeidterreindeel/items", + source: "PDOK (BGT)", + description: "Onverharde en verharde terreindelen (zand, klinkers, asfalt, etc.)", + category: "openbare-ruimte", + color: [200, 180, 140, 100], + icon: "LayoutGrid", + visible: false, + loading: false, + filled: true, + stroked: false, + defaultLimit: 500, + isNew: true, + fetchData: async (full) => + fetchPDOKOGCAPI("https://api.pdok.nl/lv/bgt/ogc/v1", "onbegroeidterreindeel", 500, full), + }, + { + id: "bgt-ondersteunendwegdeel", + name: "BGT Ondersteunend Wegdeel", + endpoint: "api.pdok.nl/lv/bgt/ogc/v1/collections/ondersteunendwegdeel/items", + source: "PDOK (BGT)", + description: "Bermen, verkeerseilanden en andere ondersteunende wegdelen", + category: "verkeer", + color: [160, 200, 140, 100], + icon: "Route", + visible: false, + loading: false, + filled: true, + stroked: false, + defaultLimit: 500, + isNew: true, + fetchData: async (full) => + fetchPDOKOGCAPI("https://api.pdok.nl/lv/bgt/ogc/v1", "ondersteunendwegdeel", 500, full), + }, + { + id: "bgt-pand", + name: "BGT Pand", + endpoint: "api.pdok.nl/lv/bgt/ogc/v1/collections/pand/items", + source: "PDOK (BGT)", + description: "Gebouwen uit de BGT (nauwkeuriger dan BAG voor topografie)", + category: "gebouwen", + color: [160, 100, 140, 120], + icon: "Building2", + visible: false, + loading: false, + filled: true, + stroked: true, + lineWidth: 1, + defaultLimit: 500, + isNew: true, + fetchData: async (full) => + fetchPDOKOGCAPI("https://api.pdok.nl/lv/bgt/ogc/v1", "pand", 500, full), + }, + + // --- Nationaal Wegenbestand (NWB) --- + { + id: "nwb-wegvakken", + name: "Nationaal Wegenbestand (NWB)", + endpoint: "service.pdok.nl/rws/nationaal-wegenbestand-wegen/wfs/v1_0", + source: "PDOK / Rijkswaterstaat", + description: "Alle wegen in Nederland met wegtype, straatnaam en wegbeheerder", + category: "verkeer", + color: [200, 160, 80, 160], + icon: "Route", + visible: false, + loading: false, + filled: false, + stroked: true, + lineWidth: 2, + defaultLimit: 500, + isNew: true, + fetchData: async (full) => + fetchPDOKWFS( + "nwbwegen:wegvakken", + "https://service.pdok.nl/rws/nationaal-wegenbestand-wegen/wfs/v1_0", + 500, + full + ), + }, + { + id: "nwb-hectopunten", + name: "Hectometerpalen (NWB)", + endpoint: "service.pdok.nl/rws/nationaal-wegenbestand-wegen/wfs/v1_0", + source: "PDOK / Rijkswaterstaat", + description: "Hectometerpalen langs rijkswegen", + category: "verkeer", + color: [180, 180, 60, 180], + icon: "MapPin", + visible: false, + loading: false, + pointType: "scatterplot", + radius: 3, + defaultLimit: 500, // 339 in Zwolle — all fit in initial load + isNew: true, + fetchData: async (full) => + fetchPDOKWFS( + "nwbwegen:hectopunten", + "https://service.pdok.nl/rws/nationaal-wegenbestand-wegen/wfs/v1_0", + 500, + full + ), + }, + + // --- BRO Grondwater --- + { + id: "bro-grondwaterput", + name: "Grondwatermonitoringputten (BRO)", + endpoint: "api.pdok.nl/bzk/bro-gminsamenhang-karakteristieken/ogc/v1/collections/gm_gmw/items", + source: "PDOK / BRO", + description: "Grondwatermonitoringputten uit de Basisregistratie Ondergrond", + category: "milieu", + color: [40, 120, 200, 180], + icon: "Droplets", + visible: false, + loading: false, + pointType: "scatterplot", + radius: 5, + defaultLimit: 200, + isNew: true, + fetchData: async (full) => + fetchPDOKOGCAPI( + "https://api.pdok.nl/bzk/bro-gminsamenhang-karakteristieken/ogc/v1", + "gm_gmw", + 200, + full + ), + }, + { + id: "bro-grondwaterstand", + name: "Grondwaterstandonderzoek (BRO)", + endpoint: "api.pdok.nl/bzk/bro-gminsamenhang-karakteristieken/ogc/v1/collections/gm_gld/items", + source: "PDOK / BRO", + description: "Grondwaterstandonderzoeken met meetreeksen uit de BRO", + category: "milieu", + color: [30, 100, 180, 180], + icon: "Droplets", + visible: false, + loading: false, + pointType: "scatterplot", + radius: 4, + defaultLimit: 200, + isNew: true, + fetchData: async (full) => + fetchPDOKOGCAPI( + "https://api.pdok.nl/bzk/bro-gminsamenhang-karakteristieken/ogc/v1", + "gm_gld", + 200, + full + ), + }, + + // --- Waterkeringen --- + { + id: "waterkeringen", + name: "Waterkeringen (IMWA)", + endpoint: "service.pdok.nl/hwh/waterschappen-keringen-imwa/wfs/v3_0", + source: "PDOK / Waterschappen", + description: "Dijken, kades en andere waterkeringen van waterschappen", + category: "milieu", + color: [40, 80, 180, 140], + icon: "Waves", + visible: false, + loading: false, + filled: false, + stroked: true, + lineWidth: 3, + defaultLimit: 200, + isNew: true, + fetchData: async (full) => + fetchPDOKWFS( + "waterschappen-keringen-imwa:waterkering", + "https://service.pdok.nl/hwh/waterschappen-keringen-imwa/wfs/v3_0", + 200, + full + ), + }, + + // --- RIVM Geluidsbelasting (nationaal, per buurt) --- + { + id: "rivm-geluidhinder-verkeer", + name: "Geluidhinder Wegverkeer (RIVM)", + endpoint: "data.rivm.nl/geo/wfs", + source: "RIVM / Atlas Leefomgeving", + description: "Ernstige geluidhinder door wegverkeer >50 dB per buurt (RIVM 2020)", + category: "milieu", + color: [255, 120, 80, 100], + icon: "Volume2", + visible: false, + loading: false, + filled: true, + stroked: true, + lineWidth: 1, + defaultLimit: 200, + isNew: true, + fetchData: async (full) => + fetchPDOKWFS( + "alo:rivm_20230201_geluidhinder_bu_gt50_2020", + "https://data.rivm.nl/geo/wfs", + 200, + full + ), + }, + { + id: "rivm-geluidhinder-trein", + name: "Geluidhinder Treinverkeer (RIVM)", + endpoint: "data.rivm.nl/geo/wfs", + source: "RIVM / Atlas Leefomgeving", + description: "Ernstige geluidhinder door treinverkeer per buurt (RIVM 2020)", + category: "milieu", + color: [200, 100, 200, 100], + icon: "Volume2", + visible: false, + loading: false, + filled: true, + stroked: true, + lineWidth: 1, + defaultLimit: 200, + isNew: true, + fetchData: async (full) => + fetchPDOKWFS( + "alo:rivm_20230201_geluidhinder_bu_trein_2020", + "https://data.rivm.nl/geo/wfs", + 200, + full + ), + }, + + // --- Cultureel Erfgoed (RCE) --- + { + id: "rce-rijksmonumenten", + name: "Rijksmonumenten (RCE)", + endpoint: "data.geo.cultureelerfgoed.nl/openbaar/wfs", + source: "RCE / Cultureelerfgoed", + description: "Rijksmonumentencontouren uit de landelijke database van de Rijksdienst voor het Cultureel Erfgoed", + category: "gebouwen", + color: [220, 170, 60, 140], + icon: "Landmark", + visible: false, + loading: false, + filled: true, + stroked: true, + lineWidth: 2, + defaultLimit: 500, + isNew: true, + fetchData: async (full) => + fetchPDOKWFS( + "openbaar:rijksmonumentcontouren", + "https://data.geo.cultureelerfgoed.nl/openbaar/wfs", + 500, + full + ), + }, + { + id: "rce-archeologie", + name: "Archeologische Monumenten (RCE)", + endpoint: "data.geo.cultureelerfgoed.nl/openbaar/wfs", + source: "RCE / Cultureelerfgoed", + description: "Archeologische monumentenkaart (ARCHIS/AMK gebieden)", + category: "grenzen", + color: [180, 140, 80, 100], + icon: "Search", + visible: false, + loading: false, + filled: true, + stroked: true, + lineWidth: 1, + defaultLimit: 200, + isNew: true, + fetchData: async (full) => + fetchPDOKWFS( + "openbaar:Archeologische_Monumentenkaart_2014", + "https://data.geo.cultureelerfgoed.nl/openbaar/wfs", + 200, + full + ), + }, + + // --- DSO Bestemmingsplan (Omgevingswet) --- + { + id: "dso-bestemmingsplan", + name: "Bestemmingsplannen (DSO)", + endpoint: "service.pdok.nl/kadaster/bestuurlijkegrenzen/wfs/v1_0", + source: "DSO / Omgevingsloket", + description: "Bestemmingsplangebieden via het Digitaal Stelsel Omgevingswet (DSO API-key vereist)", + category: "grenzen", + color: [150, 100, 255, 140], + icon: "Map", + visible: false, + loading: false, + filled: true, + stroked: true, + lineWidth: 3, + defaultLimit: 50, + isNew: true, + accessType: "restricted", + fetchData: async () => { + const res = await fetch("/api/dso/plannen"); + if (!res.ok) throw new Error(`DSO laden mislukt: ${res.status}`); + return res.json(); + }, + }, ]; // Derive a general source URL per provider @@ -2362,13 +3161,18 @@ const SOURCE_URLS: Record = { "Gemeente Zwolle GIS / Enexis": "https://gisservices.zwolle.nl/ArcGIS/rest/services", "PDOK": "https://www.pdok.nl", "PDOK (BGT)": "https://www.pdok.nl/introductie/-/article/basisregistratie-grootschalige-topografie-bgt-", - "PDOK / CBS": "https://www.cbs.nl/nl-nl/dossier/nederland-regionaal/geografische-data/wijk-en-buurtkaart-2023", + "PDOK / CBS": "https://www.cbs.nl/nl-nl/dossier/nederland-regionaal/geografische-data/wijk-en-buurtkaart-2024", "PDOK / ProRail": "https://www.prorail.nl", "PDOK / Rijkswaterstaat": "https://www.rijkswaterstaat.nl", "PDOK / RWS (WKD)": "https://www.rijkswaterstaat.nl", "PDOK / RVO": "https://www.rvo.nl/onderwerpen/natura-2000", "PDOK / Kadaster": "https://www.kadaster.nl", "PDOK / LVNL": "https://www.lvnl.nl", + "PDOK / BRO": "https://www.broloket.nl", + "PDOK / Waterschappen": "https://www.pdok.nl", + "RIVM / Atlas Leefomgeving": "https://www.atlasleefomgeving.nl", + "RCE / Cultureelerfgoed": "https://www.cultureelerfgoed.nl", + "DSO / Omgevingsloket": "https://omgevingswet.overheid.nl", "Geoportaal Overijssel": "https://www.geodataoverijssel.nl", "OpenStreetMap": "https://www.openstreetmap.org", "NDW": "https://opendata.ndw.nu", @@ -2397,10 +3201,12 @@ export interface LayerMetadata { endpoint: string; category: LayerCategory; icon: string; + isNew?: boolean; + accessType?: "open" | "restricted"; } export const LAYER_METADATA: LayerMetadata[] = DATA_SOURCES.map( - ({ id, name, description, source, sourceUrl, endpoint, category, icon }) => ({ + ({ id, name, description, source, sourceUrl, endpoint, category, icon, isNew, accessType }) => ({ id, name, description, @@ -2409,5 +3215,7 @@ export const LAYER_METADATA: LayerMetadata[] = DATA_SOURCES.map( endpoint, category, icon, + isNew, + accessType, }) ); diff --git a/src/lib/edc-asset-mapper.ts b/src/lib/edc-asset-mapper.ts new file mode 100644 index 0000000..dfa908d --- /dev/null +++ b/src/lib/edc-asset-mapper.ts @@ -0,0 +1,98 @@ +/** + * Pure functions mapping LayerMetadata → EDC Management API payloads. + */ + +import type { LayerMetadata, LayerCategory } from "./data-sources"; + +const APP_URL = process.env.NEXT_PUBLIC_APP_URL ?? "http://localhost:3000"; + +const EDC_CONTEXT = { "@vocab": "https://w3id.org/edc/v0.0.1/ns/" } as const; +const OPEN_POLICY_ID = "open-data-policy"; +const CONTRACT_DEF_PREFIX = "cd-zwolle-"; + +// ── Category → DCAT theme mapping ──────────────────────────────────── + +const CATEGORY_THEME: Record = { + verkeer: "TRAN", + gebouwen: "GOVE", + "openbare-ruimte": "ENVI", + grenzen: "REGI", + milieu: "ENVI", + voorzieningen: "EDUC", + sociaal: "SOCI", + wonen: "GOVE", + gezondheid: "HEAL", +}; + +// ── Asset creation ─────────────────────────────────────────────────── + +export function layerToEdcAsset(layer: LayerMetadata) { + return { + "@context": EDC_CONTEXT, + "@id": `zwolle-${layer.id}`, + properties: { + name: layer.name, + description: layer.description, + contenttype: "application/geo+json", + version: "1.0", + "dcat:theme": CATEGORY_THEME[layer.category] ?? "GOVE", + "zwolle:category": layer.category, + "zwolle:source": layer.source, + "zwolle:icon": layer.icon, + }, + dataAddress: { + "@type": "DataAddress", + type: "HttpData", + baseUrl: `${APP_URL}/api/v1/layers/${layer.id}`, + proxyPath: "true", + proxyQueryParams: "true", + }, + }; +} + +// ── Open data policy ───────────────────────────────────────────────── + +export function createOpenDataPolicy() { + return { + "@context": EDC_CONTEXT, + "@id": OPEN_POLICY_ID, + policy: { + "@context": "http://www.w3.org/ns/odrl.jsonld", + "@type": "Set", + permission: [ + { + action: "use", + constraint: [], + }, + ], + }, + }; +} + +// ── Contract definition ────────────────────────────────────────────── + +export function layerToEdcContractDef(layer: LayerMetadata) { + const assetId = `zwolle-${layer.id}`; + return { + "@context": EDC_CONTEXT, + "@id": `${CONTRACT_DEF_PREFIX}${layer.id}`, + accessPolicyId: OPEN_POLICY_ID, + contractPolicyId: OPEN_POLICY_ID, + assetsSelector: { + "@type": "CriterionDto", + operandLeft: "https://w3id.org/edc/v0.0.1/ns/id", + operator: "=", + operandRight: assetId, + }, + }; +} + +// ── Batch helpers ──────────────────────────────────────────────────── + +export function layersToEdcAssets(layers: LayerMetadata[]) { + return layers.map(layerToEdcAsset); +} + +export function layersToEdcContractDefs(layers: LayerMetadata[]) { + return layers.map(layerToEdcContractDef); +} diff --git a/src/lib/edc-client.ts b/src/lib/edc-client.ts new file mode 100644 index 0000000..5f74f6e --- /dev/null +++ b/src/lib/edc-client.ts @@ -0,0 +1,253 @@ +/** + * Server-side EDC Management API v2 client. + * Wraps authentication, URL construction, and error handling. + */ + +const EDC_MANAGEMENT_URL = + process.env.EDC_MANAGEMENT_URL ?? "http://localhost:8181/management"; +const EDC_API_KEY = process.env.EDC_API_AUTH_KEY ?? "password"; + +// ── helpers ────────────────────────────────────────────────────────── + +async function edcFetch( + path: string, + init?: RequestInit +): Promise { + const url = `${EDC_MANAGEMENT_URL}${path}`; + const res = await fetch(url, { + ...init, + headers: { + "Content-Type": "application/json", + "X-Api-Key": EDC_API_KEY, + ...init?.headers, + }, + cache: "no-store", + }); + + if (!res.ok) { + const body = await res.text().catch(() => ""); + throw new Error(`EDC ${init?.method ?? "GET"} ${path} → ${res.status}: ${body}`); + } + + const text = await res.text(); + return text ? (JSON.parse(text) as T) : (undefined as unknown as T); +} + +function post(path: string, body: unknown) { + return edcFetch(path, { method: "POST", body: JSON.stringify(body) }); +} + +function del(path: string) { + return edcFetch(path, { method: "DELETE" }); +} + +// ── EDC request body builders ──────────────────────────────────────── + +function querySpec( + offset = 0, + limit = 50, + filterExpression?: Array<{ operandLeft: string; operator: string; operandRight: unknown }> +) { + return { + "@context": { "@vocab": "https://w3id.org/edc/v0.0.1/ns/" }, + "@type": "QuerySpec", + offset, + limit, + ...(filterExpression ? { filterExpression } : {}), + }; +} + +// ── Assets ─────────────────────────────────────────────────────────── + +export interface EdcAsset { + "@id": string; + "@type": string; + properties: Record; + dataAddress: Record; +} + +export const edcAssets = { + list: (offset = 0, limit = 200) => + post("/v2/assets/request", querySpec(offset, limit)), + + get: (id: string) => edcFetch(`/v2/assets/${encodeURIComponent(id)}`), + + create: (asset: Record) => + post("/v2/assets", asset), + + delete: (id: string) => del(`/v2/assets/${encodeURIComponent(id)}`), +}; + +// ── Catalog ────────────────────────────────────────────────────────── + +export interface CatalogDataset { + "@id": string; + "@type": string; + [key: string]: unknown; +} + +export interface CatalogResponse { + "@type": string; + "dcat:dataset": CatalogDataset | CatalogDataset[]; + [key: string]: unknown; +} + +export const edcCatalog = { + query: (counterPartyAddress: string, counterPartyId?: string) => + post("/v2/catalog/request", { + "@context": { "@vocab": "https://w3id.org/edc/v0.0.1/ns/" }, + "@type": "CatalogRequest", + counterPartyAddress, + ...(counterPartyId ? { counterPartyId } : {}), + protocol: "dataspace-protocol-http", + querySpec: { offset: 0, limit: 500 }, + }), +}; + +// ── Contract Negotiations ──────────────────────────────────────────── + +export interface EdcNegotiation { + "@id": string; + "@type": string; + state: string; + counterPartyAddress: string; + contractAgreementId?: string; + [key: string]: unknown; +} + +export const edcNegotiations = { + list: (offset = 0, limit = 50) => + post("/v2/contractnegotiations/request", querySpec(offset, limit)), + + get: (id: string) => + edcFetch(`/v2/contractnegotiations/${encodeURIComponent(id)}`), + + initiate: (body: { + counterPartyAddress: string; + counterPartyId?: string; + protocol?: string; + policy: Record; + }) => + post<{ "@id": string }>("/v2/contractnegotiations", { + "@context": { "@vocab": "https://w3id.org/edc/v0.0.1/ns/" }, + "@type": "ContractRequest", + counterPartyAddress: body.counterPartyAddress, + ...(body.counterPartyId ? { counterPartyId: body.counterPartyId } : {}), + protocol: body.protocol ?? "dataspace-protocol-http", + policy: body.policy, + }), +}; + +// ── Transfers ──────────────────────────────────────────────────────── + +export interface EdcTransfer { + "@id": string; + "@type": string; + state: string; + [key: string]: unknown; +} + +export const edcTransfers = { + list: (offset = 0, limit = 50) => + post("/v2/transferprocesses/request", querySpec(offset, limit)), + + get: (id: string) => + edcFetch(`/v2/transferprocesses/${encodeURIComponent(id)}`), + + initiate: (body: { + counterPartyAddress: string; + contractId: string; + assetId: string; + protocol?: string; + transferType?: string; + dataDestination?: Record; + }) => + post<{ "@id": string }>("/v2/transferprocesses", { + "@context": { "@vocab": "https://w3id.org/edc/v0.0.1/ns/" }, + "@type": "TransferRequestDto", + counterPartyAddress: body.counterPartyAddress, + contractId: body.contractId, + assetId: body.assetId, + protocol: body.protocol ?? "dataspace-protocol-http", + transferType: body.transferType ?? "HttpData-PULL", + dataDestination: body.dataDestination ?? { "@type": "DataAddress", type: "HttpProxy" }, + }), +}; + +// ── Contract Agreements ────────────────────────────────────────────── + +export interface EdcAgreement { + "@id": string; + "@type": string; + assetId: string; + [key: string]: unknown; +} + +export const edcAgreements = { + list: (offset = 0, limit = 50) => + post("/v2/contractagreements/request", querySpec(offset, limit)), + + get: (id: string) => + edcFetch(`/v2/contractagreements/${encodeURIComponent(id)}`), +}; + +// ── Policy Definitions ─────────────────────────────────────────────── + +export interface EdcPolicy { + "@id": string; + "@type": string; + policy: Record; + [key: string]: unknown; +} + +export const edcPolicies = { + list: (offset = 0, limit = 50) => + post("/v2/policydefinitions/request", querySpec(offset, limit)), + + get: (id: string) => + edcFetch(`/v2/policydefinitions/${encodeURIComponent(id)}`), + + create: (policyDef: Record) => + post("/v2/policydefinitions", policyDef), +}; + +// ── Contract Definitions ───────────────────────────────────────────── + +export interface EdcContractDef { + "@id": string; + "@type": string; + [key: string]: unknown; +} + +export const edcContractDefs = { + list: (offset = 0, limit = 50) => + post("/v2/contractdefinitions/request", querySpec(offset, limit)), + + create: (contractDef: Record) => + post("/v2/contractdefinitions", contractDef), +}; + +// ── Health / status ────────────────────────────────────────────────── + +export async function edcHealthCheck(): Promise { + try { + const res = await fetch(`${EDC_MANAGEMENT_URL}/v2/assets/request`, { + method: "POST", + headers: { + "Content-Type": "application/json", + "X-Api-Key": EDC_API_KEY, + }, + body: JSON.stringify({ + "@context": { "@vocab": "https://w3id.org/edc/v0.0.1/ns/" }, + "@type": "QuerySpec", + offset: 0, + limit: 1, + }), + cache: "no-store", + signal: AbortSignal.timeout(3000), + }); + return res.ok; + } catch { + return false; + } +}