Add MiniGIM data sources, DSO API with geometry, dataspace UI, and access toggle

- 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 <noreply@anthropic.com>
This commit is contained in:
robbertjanssen85
2026-03-06 14:28:49 +01:00
co-authored by Claude Opus 4.6
parent cd8e46529c
commit efa09bf3bd
26 changed files with 2806 additions and 16 deletions
+69
View File
@@ -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
+5 -1
View File
@@ -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"
}
}
+132
View File
@@ -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<string, string> = {
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);
});
+154
View File
@@ -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<GeoJSON.Geometry | null> {
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<string, { doc: DSODocument; rdPoint: [number, number] }>();
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" } }
);
}
}
+14
View File
@@ -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 });
}
}
+30
View File
@@ -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 });
}
}
+25
View File
@@ -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 });
}
}
+19
View File
@@ -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 });
}
}
@@ -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 });
}
}
+25
View File
@@ -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 });
}
}
+25
View File
@@ -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 });
}
}
+54
View File
@@ -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,
});
}
}
+66
View File
@@ -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,
});
}
+25
View File
@@ -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 });
}
}
+52
View File
@@ -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<TabId>("dashboard");
return (
<div className="h-full overflow-auto">
<div className="mx-auto max-w-7xl px-4 py-8 space-y-6">
<div>
<h1 className="text-2xl font-bold tracking-tight">Dataspace</h1>
<p className="mt-1 text-sm text-muted-foreground">
Eclipse Dataspace Connector — publiceer datasets en consumeer data
van externe connectors via het Dataspace Protocol.
</p>
</div>
{/* Tab navigation */}
<div className="flex gap-2">
{TABS.map((tab) => (
<Badge
key={tab.id}
variant={activeTab === tab.id ? "default" : "outline"}
className="cursor-pointer select-none"
onClick={() => setActiveTab(tab.id)}
>
{tab.label}
</Badge>
))}
</div>
{/* Tab content */}
{activeTab === "dashboard" && <Dashboard />}
{activeTab === "provider" && <ProviderView />}
{activeTab === "consumer" && <ConsumerView />}
</div>
</div>
);
}
+12 -1
View File
@@ -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<BasemapId>("dark");
const [showBasemapPicker, setShowBasemapPicker] = useState(false);
const [flyTarget, setFlyTarget] = useState<FlyTarget | null>(null);
const isMobile = useIsMobile();
// Close sidebar on first mobile detection
@@ -104,6 +106,14 @@ export default function Home() {
</div>
)}
{/* Address search */}
<div className="absolute left-1/2 top-3 z-10 -translate-x-1/2">
<AddressSearch
onSelect={(lng, lat) => setFlyTarget({ lng, lat, zoom: 17 })}
onClear={() => setFlyTarget(null)}
/>
</div>
{/* Layer count badge */}
<div className="absolute right-3 top-3 z-10 flex items-center gap-1.5 rounded-md bg-background/90 px-3 py-1.5 text-xs shadow-md backdrop-blur-sm">
<Layers className="h-3.5 w-3.5" />
@@ -148,6 +158,7 @@ export default function Home() {
visibleLayers={stableVisibleLayers}
basemapId={basemapId}
onFeatureClick={handleFeatureClick}
flyTarget={flyTarget}
/>
{/* Feature detail panel */}
+203
View File
@@ -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<Suggestion[]>([]);
const [open, setOpen] = useState(false);
const [activeIndex, setActiveIndex] = useState(-1);
const containerRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLInputElement>(null);
const abortRef = useRef<AbortController | null>(null);
const timerRef = useRef<ReturnType<typeof setTimeout> | 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 (
<div ref={containerRef} className="relative w-[min(calc(100vw-7rem),400px)]">
<div className="flex items-center gap-1.5 rounded-md bg-background/90 px-3 py-1.5 shadow-md backdrop-blur-sm">
<Search className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
<input
ref={inputRef}
type="text"
value={query}
onChange={(e) => {
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 && (
<button
onClick={handleClear}
className="shrink-0 rounded-sm p-0.5 hover:bg-accent"
>
<X className="h-3 w-3" />
</button>
)}
</div>
{open && suggestions.length > 0 && (
<div className="absolute left-0 right-0 top-full z-50 mt-1 overflow-hidden rounded-md bg-background/95 shadow-xl backdrop-blur-md border">
{suggestions.map((s, i) => (
<button
key={s.id}
onMouseDown={(e) => e.preventDefault()}
onClick={() => handleSelect(s)}
onMouseEnter={() => setActiveIndex(i)}
className={`flex w-full items-center gap-2 px-3 py-2 text-left text-xs transition-colors ${
i === activeIndex ? "bg-accent" : "hover:bg-accent/50"
}`}
>
<span className="flex-1 truncate">{s.weergavenaam}</span>
<span className="shrink-0 rounded bg-muted px-1.5 py-0.5 text-[10px] text-muted-foreground">
{s.type}
</span>
</button>
))}
</div>
)}
</div>
);
}
+312
View File
@@ -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<string, unknown> | Record<string, unknown>[];
[key: string]: unknown;
}
interface Negotiation {
"@id": string;
state: string;
counterPartyAddress: string;
contractAgreementId?: string;
}
const STATE_CONFIG: Record<string, { icon: typeof Clock; color: string; label: string }> = {
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<CatalogDataset[]>([]);
const [catalogLoading, setCatalogLoading] = useState(false);
const [catalogError, setCatalogError] = useState<string | null>(null);
const [negotiations, setNegotiations] = useState<Negotiation[]>([]);
const [negotiating, setNegotiating] = useState<Set<string>>(new Set());
const [transferring, setTransferring] = useState<Set<string>>(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 (
<div className="space-y-8">
{/* Catalog query */}
<div className="space-y-3">
<h3 className="text-sm font-medium">Externe catalogus ophalen</h3>
<div className="flex gap-2 max-w-2xl">
<div className="relative flex-1">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<input
type="text"
placeholder="Connector DSP URL..."
value={connectorUrl}
onChange={(e) => 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"
/>
</div>
<Button
size="sm"
className="h-9 text-xs gap-1.5"
onClick={queryCatalog}
disabled={catalogLoading || !connectorUrl.trim()}
>
{catalogLoading ? (
<RefreshCw className="h-3.5 w-3.5 animate-spin" />
) : (
<ArrowRight className="h-3.5 w-3.5" />
)}
Catalogus ophalen
</Button>
</div>
{catalogError && (
<p className="text-xs text-red-500">{catalogError}</p>
)}
</div>
{/* Catalog results */}
{datasets.length > 0 && (
<div className="space-y-3">
<h3 className="text-sm font-medium">
Catalogus resultaten
<span className="ml-2 text-muted-foreground font-normal">
{datasets.length} datasets
</span>
</h3>
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
{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 (
<Card key={ds["@id"]} className="gap-2 py-3">
<CardHeader className="gap-1 px-4">
<CardTitle className="text-sm">{name}</CardTitle>
{desc && (
<CardDescription className="text-xs line-clamp-2">
{desc}
</CardDescription>
)}
</CardHeader>
<CardContent className="px-4 flex items-center justify-between">
<code className="text-[10px] text-muted-foreground truncate mr-2">
{ds["@id"]}
</code>
<Button
variant="outline"
size="sm"
className="h-7 text-xs gap-1 shrink-0"
onClick={() => negotiate(ds)}
disabled={isNegotiating}
>
{isNegotiating ? (
<RefreshCw className="h-3 w-3 animate-spin" />
) : (
<ArrowRight className="h-3 w-3" />
)}
Negotiate
</Button>
</CardContent>
</Card>
);
})}
</div>
</div>
)}
{/* Active negotiations */}
<div className="space-y-3">
<div className="flex items-center justify-between">
<h3 className="text-sm font-medium">Onderhandelingen</h3>
<Button
variant="ghost"
size="sm"
className="h-7 text-xs gap-1"
onClick={fetchNegotiations}
>
<RefreshCw className="h-3 w-3" />
Vernieuwen
</Button>
</div>
{negotiations.length === 0 ? (
<p className="text-xs text-muted-foreground py-4 text-center">
Nog geen onderhandelingen gestart.
</p>
) : (
<div className="space-y-2">
{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 (
<Card key={neg["@id"]} className="py-2">
<CardContent className="px-4 flex items-center gap-3">
<StateIcon className={cn("h-4 w-4 shrink-0", cfg.color)} />
<div className="flex-1 min-w-0">
<p className="text-xs font-medium truncate">{neg["@id"]}</p>
<p className="text-[10px] text-muted-foreground">
{neg.counterPartyAddress}
</p>
</div>
<Badge variant="outline" className="text-[10px] shrink-0">
{cfg.label}
</Badge>
{canTransfer && (
<Button
variant="outline"
size="sm"
className="h-6 text-[10px] gap-1 shrink-0"
onClick={() => initiateTransfer(neg)}
disabled={transferring.has(neg["@id"])}
>
{transferring.has(neg["@id"]) ? (
<RefreshCw className="h-3 w-3 animate-spin" />
) : (
<ArrowRight className="h-3 w-3" />
)}
Transfer
</Button>
)}
</CardContent>
</Card>
);
})}
</div>
)}
</div>
</div>
);
}
+113
View File
@@ -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<StatusData | null>(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 (
<div className="space-y-6">
{/* Connection status */}
<div className="flex items-center justify-between">
<div className="flex items-center gap-3">
<div
className={cn(
"h-2.5 w-2.5 rounded-full",
loading
? "bg-yellow-500 animate-pulse"
: status?.connected
? "bg-green-500"
: "bg-red-500"
)}
/>
<span className="text-sm font-medium">
{loading
? "Verbinding controleren..."
: status?.connected
? "EDC Connector verbonden"
: "EDC Connector niet bereikbaar"}
</span>
</div>
<Button
variant="outline"
size="sm"
className="h-7 text-xs gap-1.5"
onClick={fetchStatus}
disabled={loading}
>
<RefreshCw className={cn("h-3 w-3", loading && "animate-spin")} />
Vernieuwen
</Button>
</div>
{/* Stats grid */}
<div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
{stats.map(({ label, value, icon: Icon }) => (
<Card key={label} className="py-4">
<CardHeader className="flex flex-row items-center justify-between px-4 pb-1">
<CardTitle className="text-xs font-medium text-muted-foreground">
{label}
</CardTitle>
<Icon className="h-4 w-4 text-muted-foreground" />
</CardHeader>
<CardContent className="px-4">
<div className="text-2xl font-bold">{loading ? "–" : value}</div>
</CardContent>
</Card>
))}
</div>
{/* Info box */}
{!loading && !status?.connected && (
<Card className="border-dashed py-4">
<CardContent className="px-4 text-sm text-muted-foreground">
<p className="font-medium text-foreground mb-1">EDC Connector starten</p>
<p>
Start de EDC containers met{" "}
<code className="rounded bg-muted px-1.5 py-0.5 text-xs">npm run edc:up</code>
{" "}en registreer de assets met{" "}
<code className="rounded bg-muted px-1.5 py-0.5 text-xs">npm run edc:register</code>.
</p>
</CardContent>
</Card>
)}
</div>
);
}
+210
View File
@@ -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<string, unknown>;
}
const CATEGORY_LABELS: Record<string, string> = {
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<EdcAsset[]>([]);
const [loading, setLoading] = useState(true);
const [syncing, setSyncing] = useState(false);
const [syncResult, setSyncResult] = useState<string | null>(null);
const [search, setSearch] = useState("");
const [selectedCategory, setSelectedCategory] = useState<string | null>(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<string, number> = {};
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 (
<div className="space-y-6">
{/* Header actions */}
<div className="flex flex-wrap items-center gap-3">
<Button
variant="default"
size="sm"
className="h-8 text-xs gap-1.5"
onClick={handleSync}
disabled={syncing}
>
<RefreshCw className={cn("h-3.5 w-3.5", syncing && "animate-spin")} />
Synchroniseer
</Button>
{syncResult && (
<span className="text-xs text-muted-foreground">{syncResult}</span>
)}
</div>
{/* Search */}
<div className="relative max-w-md">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-muted-foreground" />
<input
type="text"
placeholder="Zoek assets..."
value={search}
onChange={(e) => 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"
/>
</div>
{/* Category filter */}
<div className="flex flex-wrap gap-2">
<Badge
variant={selectedCategory === null ? "default" : "outline"}
className="cursor-pointer select-none"
onClick={() => setSelectedCategory(null)}
>
Alles
</Badge>
{categories.map((cat) => (
<Badge
key={cat.id}
variant={selectedCategory === cat.id ? "default" : "outline"}
className="cursor-pointer select-none"
onClick={() =>
setSelectedCategory(selectedCategory === cat.id ? null : cat.id)
}
>
{cat.label}
<span className="ml-1 opacity-60">{cat.count}</span>
</Badge>
))}
</div>
{/* Count */}
<p className="text-xs text-muted-foreground">
{filtered.length} {filtered.length === 1 ? "asset" : "assets"}
{loading ? " laden..." : " gevonden"}
</p>
{/* Asset grid */}
{loading ? (
<div className="text-center py-12 text-sm text-muted-foreground">
Assets laden...
</div>
) : filtered.length === 0 ? (
<div className="text-center py-12 text-sm text-muted-foreground">
Geen assets gevonden.{" "}
{assets.length === 0 && (
<span>Klik &quot;Synchroniseer&quot; om layers te registreren.</span>
)}
</div>
) : (
<div className="grid gap-3 sm:grid-cols-2 lg:grid-cols-3">
{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 (
<Card key={asset["@id"]} className="gap-2 py-3">
<CardHeader className="gap-1 px-4">
<div className="flex items-start justify-between gap-2">
<CardTitle className="text-sm flex items-center gap-1.5">
<Package className="h-3.5 w-3.5 text-muted-foreground shrink-0" />
{name}
</CardTitle>
{catLabel && (
<Badge variant="secondary" className="text-[10px] shrink-0">
{catLabel}
</Badge>
)}
</div>
<CardDescription className="text-xs line-clamp-2">
{desc}
</CardDescription>
</CardHeader>
<CardContent className="px-4">
<code className="text-[10px] text-muted-foreground">
{asset["@id"]}
</code>
</CardContent>
</Card>
);
})}
</div>
)}
</div>
);
}
+33
View File
@@ -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<HTMLDivElement>(null);
const mapRef = useRef<maplibregl.Map | null>(null);
@@ -542,6 +550,31 @@ export default function MapView({
}
}, [visibleLayers]);
// Fly to target and show marker
const markerRef = useRef<maplibregl.Marker | null>(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 (
<div className="relative h-full w-full">
<div ref={containerRef} className="absolute inset-0" />
+2 -1
View File
@@ -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;
+40 -2
View File
@@ -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<string, LucideIcon> = {
Ship,
GraduationCap,
ShoppingCart,
Truck,
};
interface SidebarProps {
@@ -185,6 +188,9 @@ const LayerRow = memo(function LayerRow({
<LayerIcon className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
<span className="flex-1 truncate text-xs">
{layer.name}
{layer.isNew && (
<span className="ml-1 text-amber-400 font-bold" title="Nieuw (MiniGIM)">✦</span>
)}
</span>
{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 }:
</div>
</div>
{/* Access type filter */}
<div className="shrink-0 border-b px-3 py-2">
<div className="flex items-center gap-1 rounded-lg bg-muted p-0.5">
{([
{ 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 }) => (
<button
key={value}
onClick={() => setAccessFilter(value)}
className={`flex flex-1 items-center justify-center gap-1 rounded-md px-2 py-1 text-[10px] font-medium transition-colors ${
accessFilter === value
? "bg-background text-foreground shadow-sm"
: "text-muted-foreground hover:text-foreground"
}`}
>
{Icon && <Icon className="h-3 w-3" />}
{label}
</button>
))}
</div>
</div>
{/* Layers - native scroll for reliable scrolling */}
<div className="flex-1 min-h-0 overflow-y-auto overscroll-contain">
<div className="px-2 py-2">
+819 -11
View File
@@ -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<string, [number, number, number, number]>;
@@ -85,9 +90,23 @@ async function fetchPDOKOGCAPI(
limit = 1000,
full = false
): Promise<GeoJSON.FeatureCollection> {
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<GeoJSON.FeatureCollection> {
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<GeoJSON.FeatureCollection> {
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<GeoJSON.FeatureCollection> {
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<string, string> = {
"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,
})
);
+98
View File
@@ -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<LayerCategory, string> = {
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);
}
+253
View File
@@ -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<T = unknown>(
path: string,
init?: RequestInit
): Promise<T> {
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<T = unknown>(path: string, body: unknown) {
return edcFetch<T>(path, { method: "POST", body: JSON.stringify(body) });
}
function del(path: string) {
return edcFetch<void>(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<string, unknown>;
dataAddress: Record<string, unknown>;
}
export const edcAssets = {
list: (offset = 0, limit = 200) =>
post<EdcAsset[]>("/v2/assets/request", querySpec(offset, limit)),
get: (id: string) => edcFetch<EdcAsset>(`/v2/assets/${encodeURIComponent(id)}`),
create: (asset: Record<string, unknown>) =>
post<EdcAsset>("/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<CatalogResponse>("/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<EdcNegotiation[]>("/v2/contractnegotiations/request", querySpec(offset, limit)),
get: (id: string) =>
edcFetch<EdcNegotiation>(`/v2/contractnegotiations/${encodeURIComponent(id)}`),
initiate: (body: {
counterPartyAddress: string;
counterPartyId?: string;
protocol?: string;
policy: Record<string, unknown>;
}) =>
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<EdcTransfer[]>("/v2/transferprocesses/request", querySpec(offset, limit)),
get: (id: string) =>
edcFetch<EdcTransfer>(`/v2/transferprocesses/${encodeURIComponent(id)}`),
initiate: (body: {
counterPartyAddress: string;
contractId: string;
assetId: string;
protocol?: string;
transferType?: string;
dataDestination?: Record<string, unknown>;
}) =>
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<EdcAgreement[]>("/v2/contractagreements/request", querySpec(offset, limit)),
get: (id: string) =>
edcFetch<EdcAgreement>(`/v2/contractagreements/${encodeURIComponent(id)}`),
};
// ── Policy Definitions ───────────────────────────────────────────────
export interface EdcPolicy {
"@id": string;
"@type": string;
policy: Record<string, unknown>;
[key: string]: unknown;
}
export const edcPolicies = {
list: (offset = 0, limit = 50) =>
post<EdcPolicy[]>("/v2/policydefinitions/request", querySpec(offset, limit)),
get: (id: string) =>
edcFetch<EdcPolicy>(`/v2/policydefinitions/${encodeURIComponent(id)}`),
create: (policyDef: Record<string, unknown>) =>
post<EdcPolicy>("/v2/policydefinitions", policyDef),
};
// ── Contract Definitions ─────────────────────────────────────────────
export interface EdcContractDef {
"@id": string;
"@type": string;
[key: string]: unknown;
}
export const edcContractDefs = {
list: (offset = 0, limit = 50) =>
post<EdcContractDef[]>("/v2/contractdefinitions/request", querySpec(offset, limit)),
create: (contractDef: Record<string, unknown>) =>
post<EdcContractDef>("/v2/contractdefinitions", contractDef),
};
// ── Health / status ──────────────────────────────────────────────────
export async function edcHealthCheck(): Promise<boolean> {
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;
}
}