Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 | 2x 47x 94x 47x 47x 47x 47x 3010x 874x 148x 69x 1974x 28x 28x 28x 28x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 47x 28x 2x 2x 24x 24x 24x 4x 20x 2x 18x 72x 72x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 406x 71x 68x 68x 68x 132x 68x 68x 67x 406x 71x 2x 2x 2x 2x 3x 2x 406x 18x 406x 72x 1x 1x 406x 141x 70x 70x 69x 69x 69x 406x 199x 70x 70x 70x 70x 70x 70x 70x 406x 30x 30x 30x 30x 30x 30x 30x 30x 30x 27x 27x 1x 1x 1x 28x 28x 1x 28x 28x 28x 2x 1x 30x 19x 19x 19x 19x 19x 19x 19x 19x 406x 406x 150x 8x 8x 8x 8x 8x 8x 8x 8x 14x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 406x 1x 1x 1x 1x 406x 15x 15x 15x 15x 15x 15x 15x 14x 13x 13x 13x 13x 8x 13x 13x 13x 13x 4x 13x 1x 1x 1x 1x 1x 15x 750x 750x 499x 251x 246x 5x 1073x 39x 1073x 406x 3x 3x 2x 708x 708x 365x 205x 19x 158x 750x 750x 750x 750x 750x | "use client";
import { fetchApi } from "@/lib/api";
import { buildDemoCatalog, type DemoAssetEntry } from "@/lib/demo-catalog";
import { DSP_PROTOCOL } from "@/lib/dsp-protocol";
import { didToName } from "@/lib/participant-name";
import { IS_STATIC } from "@/lib/static-export";
import OfferTerms from "@/components/OfferTerms";
import Link from "next/link";
import { Suspense, useEffect, useRef, useState } from "react";
import { useSearchParams } from "next/navigation";
import {
FileSignature,
Loader2,
CheckCircle2,
Clock,
XCircle,
ArrowRight,
Search,
AlertCircle,
BookOpen,
} from "lucide-react";
import PageIntro from "@/components/PageIntro";
import RowSourceBadge from "@/components/RowSourceBadge";
import type { RowSource } from "@/lib/row-provenance";
import { T, useT } from "@/lib/i18n/translate";
import { DEFAULT_PAGE_SIZE } from "@/lib/list-page";
interface ParticipantCtx {
"@id": string;
identity: string;
participantId?: string;
displayName?: string;
role?: string;
}
/** A HealthDCAT-AP dataset the catalog page sent here (`?dataset=`). */
interface RequestedDataset {
title: string;
publisher: string;
providers: string[];
}
interface CatalogOffer {
assetId: string;
offerId: string;
assignerDid: string;
name?: string;
description?: string;
contentType?: string;
/** The provider's DSP address, as the catalog's distribution names it. */
endpoint?: string;
/** The ODRL offer itself, shown as the terms the user agrees to (#876). */
policy?: Record<string, unknown>;
}
/** The first distribution's DSP endpoint, in either JSON-LD spelling. */
function datasetEndpoint(ds: Record<string, unknown>): string {
const one = (v: unknown) =>
(Array.isArray(v) ? v[0] : v) as Record<string, unknown> | undefined;
const dist = one(ds["distribution"] ?? ds["dcat:distribution"]);
const svc = one(dist?.["accessService"] ?? dist?.["dcat:accessService"]);
const url = svc?.["endpointURL"] ?? svc?.["dcat:endpointURL"] ?? "";
return typeof url === "string" ? url : "";
}
interface Negotiation {
"@id": string;
state?: string;
"edc:state"?: string;
contractAgreementId?: string;
"edc:contractAgreementId"?: string;
counterPartyId?: string;
"edc:counterPartyId"?: string;
assetId?: string;
[key: string]: unknown;
}
/** Read a negotiation field that may be edc:-prefixed or unprefixed */
function negField(n: Negotiation, field: string): string {
return ((n as Record<string, unknown>)[field] ??
(n as Record<string, unknown>)[`edc:${field}`] ??
"") as string;
}
/**
* Who can be asked for a catalog: anyone but the requester and a DATA_USER.
* A DATA_USER requests data under a permit; it holds none to offer (EHDS
* Art. 2). A context without a role (a live connector that does not say)
* stays in the list. #876
*/
function isProviderFor(p: ParticipantCtx, consumerId: string): boolean {
return p["@id"] !== consumerId && p.role !== "DATA_USER";
}
/** The provider to preselect: the first data holder, else any provider. */
function defaultProvider(
list: ParticipantCtx[],
consumerId: string,
): ParticipantCtx | undefined {
const providers = list.filter((p) => isProviderFor(p, consumerId));
return providers.find((p) => p.role === "DATA_HOLDER") ?? providers[0];
}
/** Pretty-print an asset ID as a title */
function assetLabel(id: string): string {
return id.replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
}
/** Parse ODRL offers from a DCAT catalog response (handles multiple JSON-LD shapes) */
function parseOffers(catalog: Record<string, unknown>): CatalogOffer[] {
const offers: CatalogOffer[] = [];
let datasets = catalog["dataset"] ?? catalog["dcat:dataset"] ?? [];
if (!Array.isArray(datasets)) datasets = [datasets];
for (const ds of datasets as Record<string, unknown>[]) {
const assetId = (ds["@id"] ?? ds["id"] ?? "") as string;
const name = (ds["name"] ?? ds["dct:title"] ?? ds["title"] ?? "") as string;
const description = (ds["description"] ??
ds["dct:description"] ??
"") as string;
const contentType = (ds["contenttype"] ?? "") as string;
const endpoint = datasetEndpoint(ds);
let policies = ds["hasPolicy"] ?? ds["odrl:hasPolicy"] ?? [];
if (!Array.isArray(policies)) policies = [policies];
for (const p of policies as Record<string, unknown>[]) {
const offerId = (p["@id"] ?? "") as string;
const assigner = p["assigner"] ?? p["odrl:assigner"] ?? "";
const assignerDid =
typeof assigner === "object"
? ((assigner as Record<string, unknown>)["@id"] as string) ?? ""
: (assigner as string);
Eif (assetId && offerId) {
offers.push({
assetId,
offerId,
assignerDid,
name,
description,
contentType,
...(endpoint ? { endpoint } : {}),
policy: p,
});
}
}
}
return offers;
}
/** How long the page follows a negotiation: every 3 s for two minutes. */
const TRACK_INTERVAL_MS = 3000;
const TRACK_POLLS = 40;
/**
* What happens after "Negotiation initiated": who has to act (nobody), the
* state the connectors have reached, and the way on to the transfer.
*/
function NegotiationProgress({
tracked,
provider,
consumerCtx,
}: {
tracked: {
state: string;
agreementId: string;
error: string;
gaveUp: boolean;
};
provider: string;
consumerCtx: string;
}) {
const t = useT("research");
const box = "mb-4 p-3 rounded text-sm flex gap-2";
if (tracked.state === "FINALIZED" && tracked.agreementId) {
return (
<div
data-testid="negotiation-progress"
className={`${box} items-center justify-between bg-(--badge-active-bg) border border-(--badge-active-border) text-(--badge-active-text)`}
>
<span className="flex gap-2">
<CheckCircle2 size={16} className="shrink-0 mt-0.5" />
{t("Contract agreed with {provider}. Next step: the transfer.", {
provider,
})}
</span>
<Link
href={`/data/transfer?participantId=${encodeURIComponent(
consumerCtx,
)}&contractId=${encodeURIComponent(tracked.agreementId)}`}
className="flex items-center gap-1 font-medium hover:underline whitespace-nowrap"
>
{t("Continue to transfer")} <ArrowRight size={14} />
</Link>
</div>
);
}
if (tracked.state === "TERMINATED") {
return (
<div
data-testid="negotiation-progress"
className={`${box} bg-(--badge-inactive-bg) border border-(--badge-inactive-border) text-(--badge-inactive-text)`}
>
<XCircle size={16} className="shrink-0 mt-0.5" />
{t("The negotiation ended without a contract: {detail}", {
detail: tracked.error || tracked.state,
})}
</div>
);
}
return (
<div
data-testid="negotiation-progress"
className={`${box} bg-(--surface-2) border border-(--border) text-(--text-secondary)`}
>
{tracked.gaveUp ? (
<AlertCircle size={16} className="shrink-0 mt-0.5" />
) : (
<Loader2 size={16} className="shrink-0 mt-0.5 animate-spin" />
)}
<span>
{tracked.gaveUp
? t(
"No answer from {provider} after two minutes. The negotiation stays in the history below; if it does not move, the provider's connector cannot be reached.",
{ provider },
)
: t(
"Waiting for {provider} to agree ({state}). Its connector checks the request against its offer and answers on its own: nobody at {provider} has to sign in.",
{ provider, state: tracked.state },
)}
</span>
</div>
);
}
export default function NegotiatePage() {
const tc = useT("common");
return (
<Suspense
fallback={
<div className="flex items-center gap-2 text-(--text-secondary) p-10">
<Loader2 size={16} className="animate-spin" />
{tc("Loading…")}
</div>
}
>
<NegotiateContent />
</Suspense>
);
}
function NegotiateContent() {
const t = useT("research");
const tn = useT("nav");
const searchParams = useSearchParams();
const preAssetId = searchParams.get("assetId") || "";
const preProviderId = searchParams.get("providerId") || "";
const preProviderDid = searchParams.get("providerDid") || "";
// The catalog's "Request Access" sends the HealthDCAT-AP dataset id. It is
// not a DSP asset id, so it cannot select an offer; it names the dataset
// and, through its publisher, the participant to ask. #876
const preDataset = searchParams.get("dataset") || "";
const [requested, setRequested] = useState<RequestedDataset | null>(null);
const datasetHolderApplied = useRef(false);
const [participants, setParticipants] = useState<ParticipantCtx[]>([]);
const [negotiations, setNegotiations] = useState<Negotiation[]>([]);
const [loading, setLoading] = useState(true);
const [selectedCtx, setSelectedCtx] = useState("");
// Step 1 — Catalog discovery
const [selectedProviderCtx, setSelectedProviderCtx] = useState(
preProviderId || "",
);
const [providerCtxId, setProviderCtxId] = useState(preProviderId);
const [providerDid, setProviderDid] = useState(preProviderDid);
const [catalogLoading, setCatalogLoading] = useState(false);
const [catalogError, setCatalogError] = useState<string | null>(null);
const [catalogNote, setCatalogNote] = useState<string | null>(null);
const [offers, setOffers] = useState<CatalogOffer[]>([]);
const [selectedOffer, setSelectedOffer] = useState<CatalogOffer | null>(null);
// Step 2 — Negotiation form (populated from selected offer)
const [assetId, setAssetId] = useState(preAssetId);
const [offerId, setOfferId] = useState("");
// The user has read the offer's terms and agrees to them (#876).
const [termsAccepted, setTermsAccepted] = useState(false);
// The offer a negotiation was started for. While it is the selected offer
// the page offers no second "Start Negotiation": the contract is under way
// or agreed, and another click would open a second one (#876).
const [negotiatedOffer, setNegotiatedOffer] = useState<string | null>(null);
const [initiating, setInitiating] = useState(false);
const [result, setResult] = useState<string | null>(null);
const [resultIsError, setResultIsError] = useState(false);
// The negotiation just started, followed until the provider answers. The
// provider's connector agrees on its own when the request matches its
// offer; nobody at the data holder signs in for it. Without this the page
// said "Negotiation initiated" and nothing more, and a demo user waited for
// a step that does not exist (#876).
const [tracked, setTracked] = useState<{
id: string;
state: string;
agreementId: string;
error: string;
gaveUp: boolean;
} | null>(null);
useEffect(() => {
fetchApi("/api/participants")
.then((r) => (r.ok ? r.json() : []))
.then((d) => {
const list: ParticipantCtx[] = Array.isArray(d)
? d
: d.participants ?? [];
setParticipants(list);
// The requester is a data user when there is one: they are the ones
// who negotiate access. The provider used to be list[0] as well, the
// requester itself, which the dropdown could not show (it leaves the
// requester out), so it displayed the next entry while the catalog
// request asked the requester for its own offers. #876
const consumer =
list.find((p) => p.role === "DATA_USER") ?? list[0] ?? undefined;
if (consumer) setSelectedCtx(consumer["@id"]);
if (consumer && !preProviderId) {
chooseProvider(defaultProvider(list, consumer["@id"]));
}
})
.catch(() => {});
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
useEffect(() => {
if (!preDataset) return;
fetchApi("/api/catalog")
.then((r) => (r.ok ? r.json() : []))
.then((d) => {
const list = (
Array.isArray(d) ? d : d.datasets ?? d.catalog ?? []
) as Record<string, unknown>[];
const ds = list.find(
(x) => x.id === preDataset || x.title === preDataset,
);
setRequested({
title: (ds?.title as string) || preDataset,
publisher: (ds?.publisher as string) || "",
providers: Array.isArray(ds?.providers)
? (ds.providers as string[])
: [],
});
})
.catch(() =>
setRequested({ title: preDataset, publisher: "", providers: [] }),
);
}, [preDataset]);
// The participant that holds the requested dataset, if it is one of ours
const datasetHolder = requested
? participants.find(
(p) =>
isProviderFor(p, selectedCtx) &&
!!p.displayName &&
[requested.publisher, ...requested.providers].includes(p.displayName),
)
: undefined;
useEffect(() => {
if (datasetHolderApplied.current || preProviderId || !datasetHolder) return;
datasetHolderApplied.current = true;
chooseProvider(datasetHolder);
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [datasetHolder]);
useEffect(() => {
if (!selectedCtx) return;
setLoading(true);
fetchApi(
`/api/negotiations?participantId=${selectedCtx}&limit=${DEFAULT_PAGE_SIZE}`,
)
.then((r) => (r.ok ? r.json() : []))
.then((d) => {
setNegotiations(Array.isArray(d) ? d : d.negotiations ?? []);
setLoading(false);
})
.catch(() => setLoading(false));
}, [selectedCtx]);
useEffect(() => {
Iif (preAssetId && offers.length > 0) {
const match = offers.find((o) => o.assetId === preAssetId);
if (match) selectOffer(match);
}
// eslint-disable-next-line react-hooks/exhaustive-deps
}, [offers]);
function chooseProvider(chosen: ParticipantCtx | undefined) {
setSelectedProviderCtx(chosen?.["@id"] ?? "");
setProviderCtxId(chosen?.["@id"] ?? "");
// identity holds the real DID; participantId is the UUID context ID
setProviderDid(chosen?.identity ?? "");
// Reset previous catalog results when provider changes
setOffers([]);
setSelectedOffer(null);
setCatalogError(null);
setCatalogNote(null);
}
/** Step 1: DCP catalog discovery via v1alpha participants/{ctxId}/catalog */
const handleDiscoverCatalog = async () => {
Iif (!selectedCtx || (!providerDid && !providerCtxId)) return;
setCatalogLoading(true);
setCatalogError(null);
setCatalogNote(null);
setOffers([]);
setSelectedOffer(null);
const did =
providerDid ||
`did:web:identityhub%3A7083:${providerCtxId
.toLowerCase()
.replace(/\s+/g, "-")}`;
try {
// The static build has no API route, and fetchApi() would answer the
// catalog request with negotiations.json. Build the same demo catalog
// the route falls back to on the hub, from the same assets file.
const res = IS_STATIC
? await fetchApi("/api/assets")
: await fetchApi(
`/api/negotiations?participantId=${selectedCtx}&catalog=true&providerDid=${encodeURIComponent(
did,
)}`,
);
const data = IS_STATIC
? buildDemoCatalog((await res.json()) as DemoAssetEntry[], did) ?? {
dataset: [],
}
: await res.json();
if (!res.ok) {
const errData = data as Record<string, unknown>;
setCatalogError(
(errData.detail as string) ||
(errData.error as string) ||
t("Failed to fetch catalog"),
);
return;
}
const payload = data as Record<string, unknown>;
if (payload.demo === true) {
setCatalogNote(
(payload.demoReason as string) ||
t(
"These offers come from the demonstrator's own catalogue, not from a live DSP request.",
),
);
}
const parsed = parseOffers(payload);
setOffers(parsed);
if (parsed.length === 0) {
setCatalogError(
t(
"No datasets with offers found. Ensure the provider has contract definitions and active participant contexts (VPAs in ACTIVE state).",
),
);
}
} catch {
setCatalogError(t("Network error fetching catalog"));
} finally {
setCatalogLoading(false);
}
};
function selectOffer(o: CatalogOffer) {
// Agreeing is per offer: a new offer has new terms.
Eif (o.offerId !== selectedOffer?.offerId) {
setTermsAccepted(false);
setNegotiatedOffer(null);
setTracked(null);
setResult(null);
}
setSelectedOffer(o);
setAssetId(o.assetId);
setOfferId(o.offerId);
}
/** Step 2: Submit DSP ContractRequest with real offer ID */
const trackedId = tracked?.id;
useEffect(() => {
if (!trackedId) return;
let polls = 0;
let stopped = false;
const check = async () => {
polls += 1;
try {
const res = await fetchApi(
`/api/negotiations?participantId=${selectedCtx}&limit=${DEFAULT_PAGE_SIZE}`,
);
const body = await res.json();
const list = (
Array.isArray(body) ? body : body.negotiations ?? []
) as Negotiation[];
const row = list.find((n) => n["@id"] === trackedId);
const state = row ? negField(row, "state").toUpperCase() : "";
const done = state === "FINALIZED" || state === "TERMINATED";
Iif (stopped) return;
setNegotiations(list);
setTracked((t) =>
t && t.id === trackedId
? {
...t,
state: state || t.state,
agreementId: row ? negField(row, "contractAgreementId") : "",
error: String(row?.errorDetail ?? ""),
gaveUp: !done && polls >= TRACK_POLLS,
}
: t,
);
if (done || polls >= TRACK_POLLS) stopped = true;
} catch {
// A failed poll is not an answer; the next one asks again.
}
};
void check();
const timer = setInterval(() => {
if (stopped) clearInterval(timer);
else void check();
}, TRACK_INTERVAL_MS);
return () => {
stopped = true;
clearInterval(timer);
};
}, [trackedId, selectedCtx]);
const negotiated =
!!selectedOffer && negotiatedOffer === selectedOffer.offerId;
/** Back to the agreement step for the same offer, on purpose. */
function negotiateAgain() {
setNegotiatedOffer(null);
setTracked(null);
setResult(null);
setTermsAccepted(false);
}
const handleNegotiate = async (e: React.FormEvent) => {
e.preventDefault();
setInitiating(true);
setResult(null);
setResultIsError(false);
setTracked(null);
try {
const res = await fetchApi("/api/negotiations", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({
participantId: selectedCtx,
assetId,
// The address the provider's catalog gave, else the server's own
// DSP base. Never a fixed host: http://controlplane does not
// resolve on Azure (#876).
counterPartyAddress: selectedOffer?.endpoint,
counterPartyId: providerCtxId,
providerDid: selectedOffer?.assignerDid || providerDid,
offerId,
// The terms the user agreed to, sent back whole (ADR-077).
policy: selectedOffer?.policy,
}),
});
if (res.ok) {
const data = (await res.json()) as Record<string, unknown>;
setNegotiatedOffer(offerId);
setResult(
data.demo === true
? t("Demo negotiation recorded: {id}. {reason}", {
id: String(data["@id"]),
reason: String(data.demoReason ?? ""),
})
: t("Negotiation initiated: {id}", {
id: String(data["@id"] || JSON.stringify(data)),
}),
);
if (data.demo !== true && !IS_STATIC && data["@id"]) {
setTracked({
id: String(data["@id"]),
state: "REQUESTED",
agreementId: "",
error: "",
gaveUp: false,
});
}
const updated = await fetchApi(
`/api/negotiations?participantId=${selectedCtx}&limit=${DEFAULT_PAGE_SIZE}`,
);
const ud = await updated.json();
const list = (Array.isArray(ud) ? ud : ud.negotiations ?? []) as
| Negotiation[]
| [];
// The API now keeps a demo negotiation in memory and returns it from this
// refetch, so prepend it only if the refetch did not carry it: the row can
// then neither vanish (which looks like a failure) nor appear twice.
const missing =
data.demo === true &&
!list.some((n) => n["@id"] === (data["@id"] as string));
setNegotiations(
missing ? [data as unknown as Negotiation, ...list] : list,
);
} else {
const err = (await res.json()) as Record<string, unknown>;
setResultIsError(true);
setResult(
t("Error: {detail}", {
detail:
(err.detail as string) ||
(err.error as string) ||
t("Negotiation failed"),
}),
);
}
} catch {
setResultIsError(true);
setResult(
t("Error: {detail}", {
detail: t("Failed to initiate negotiation"),
}),
);
} finally {
setInitiating(false);
}
};
function stateIcon(state: string) {
const s = state?.toUpperCase() || "";
if (s.includes("FINALIZED") || s.includes("AGREED"))
return <CheckCircle2 size={16} className="text-(--success-text)" />;
if (s.includes("TERMINATED") || s.includes("ERROR"))
return <XCircle size={16} className="text-(--danger-text)" />;
return <Clock size={16} className="text-(--warning-text)" />;
}
function displayId(p: ParticipantCtx) {
if (p.displayName) return p.displayName;
const did = p.participantId ?? p.identity ?? "";
return (
did.replace("did:web:", "").replace(/%3A/gi, ":").split(":").pop() ||
p["@id"].slice(0, 12)
);
}
return (
<div className="min-h-screen bg-(--bg)">
<div className="max-w-5xl mx-auto px-6 py-10">
<PageIntro
title={t("Contract Negotiation")}
icon={FileSignature}
description={t(
"Negotiate data access contracts via the Dataspace Protocol using ODRL policies. Select a consumer participant, choose a dataset, and initiate a contract negotiation request that the data holder can accept or reject.",
)}
prevStep={{ href: "/data/discover", label: t("Discover Data") }}
nextStep={{ href: "/data/transfer", label: t("Data Transfer") }}
infoText={t(
"Two steps: (1) choose a data provider and click Discover Offers to see what datasets are available; (2) select a dataset and click Start Negotiation to request access.",
)}
docLink={{
href: "https://eclipse-dataspace-protocol-base.github.io/DataspaceProtocol/2025-1/",
label: t("DSP Specification"),
external: true,
}}
/>
{/* Consumer context selector */}
<div className="mb-6">
<label className="text-xs text-(--text-secondary) mb-1 block">
{t("Requesting as (your participant)")}
</label>
<select
aria-label={t("Requesting as (your participant)")}
value={selectedCtx}
onChange={(e) => {
setSelectedCtx(e.target.value);
if (e.target.value === selectedProviderCtx) {
chooseProvider(defaultProvider(participants, e.target.value));
}
}}
className="w-full max-w-md px-3 py-2 bg-(--surface-2) border border-(--border-ui) rounded-sm text-sm"
>
{participants.map((p) => (
<option key={p["@id"]} value={p["@id"]}>
{displayId(p)}
{p.role ? ` [${p.role}]` : ""}
</option>
))}
</select>
</div>
{requested && (
<div
data-testid="requested-dataset"
className="mb-5 p-3 rounded-sm bg-(--surface-2)/60 border border-(--border) text-sm text-(--text-primary) flex gap-2"
>
<BookOpen size={16} className="shrink-0 mt-0.5" />
<span>
{datasetHolder
? t(
"You asked for access to “{title}”, published by {publisher}. In this demonstrator a catalogue dataset is requested through its holder's DSP offers, so {holder} is preselected below: discover the offers and choose the one that covers this dataset.",
{
title: requested.title,
publisher:
requested.publisher || datasetHolder.displayName || "",
holder: datasetHolder.displayName ?? "",
},
)
: t(
"No participant of this dataspace offers “{title}” yet, so there is nothing to negotiate for it. Choose a data provider below to see what can be negotiated.",
{ title: requested.title },
)}
</span>
</div>
)}
{/* ── Step 1: Catalog discovery ── */}
<div className="border border-(--border) rounded-xl p-5 mb-5">
<div className="flex items-center gap-2 mb-1">
<Search size={16} className="text-teal-800 dark:text-teal-300" />
<h2 className="font-semibold text-sm">
{t("Step 1: Choose Data Provider")}
</h2>
</div>
<p className="text-xs text-(--text-secondary) mb-4">
{t(
"Choose a data provider below; the catalog will be fetched automatically.",
)}
</p>
<div className="mb-4">
<label className="text-xs text-(--text-secondary) mb-1 block">
{t("Data Provider")}
</label>
<select
aria-label={t("Data Provider")}
value={selectedProviderCtx}
onChange={(e) => {
const chosen = participants.find(
(p) => p["@id"] === e.target.value,
);
if (chosen) chooseProvider(chosen);
}}
className="w-full max-w-md px-3 py-2 bg-(--surface-2) border border-(--border-ui) rounded-sm text-sm"
disabled={participants.length === 0}
>
{participants.length === 0 && (
<option value="">{t("Loading participants…")}</option>
)}
{participants
.filter((p) => isProviderFor(p, selectedCtx))
.map((p) => (
<option key={p["@id"]} value={p["@id"]}>
{displayId(p)}
{p.role ? ` [${p.role}]` : ""}
</option>
))}
</select>
</div>
<button
type="button"
disabled={catalogLoading || !selectedCtx || !selectedProviderCtx}
onClick={handleDiscoverCatalog}
className="flex items-center gap-2 px-4 py-2 bg-gray-700 text-white rounded-sm text-sm font-medium hover:bg-gray-600 disabled:opacity-50"
>
{catalogLoading ? (
<Loader2 size={14} className="animate-spin" />
) : (
<BookOpen size={14} />
)}
{t("Discover Offers")}
</button>
{catalogError && (
<div className="mt-3 p-3 rounded-sm bg-red-100 dark:bg-red-900/30 border border-red-300 dark:border-red-700 text-red-800 dark:text-red-300 text-xs flex gap-2">
<AlertCircle size={14} className="shrink-0 mt-0.5" />
<span>{catalogError}</span>
</div>
)}
{catalogNote && (
<div className="mt-3 p-3 rounded-sm bg-amber-100 dark:bg-amber-900/30 border border-amber-300 dark:border-amber-700 text-amber-900 dark:text-amber-200 text-xs flex gap-2">
<AlertCircle size={14} className="shrink-0 mt-0.5" />
<span>{catalogNote}</span>
</div>
)}
{offers.length > 0 && (
<div className="mt-4 space-y-2">
<p className="text-xs text-(--text-secondary) mb-2">
{t("{n} offer(s) found. Select one to negotiate:", {
n: offers.length,
})}
</p>
{offers.map((o) => (
<button
key={o.offerId}
type="button"
onClick={() => selectOffer(o)}
className={`w-full text-left p-3 rounded-lg border text-sm transition-colors ${
selectedOffer?.offerId === o.offerId
? "border-layer2 bg-layer2/10"
: "border-(--border) hover:border-gray-500 bg-(--surface-2)/50"
}`}
>
<div className="flex items-center justify-between">
<span className="font-medium text-(--text-primary)">
{o.name || assetLabel(o.assetId)}
</span>
<div className="flex items-center gap-2">
{o.contentType && (
<span className="text-[10px] px-1.5 py-0.5 rounded-sm bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-gray-200">
{o.contentType}
</span>
)}
{selectedOffer?.offerId === o.offerId && (
<CheckCircle2
size={14}
className="text-teal-800 dark:text-teal-300"
/>
)}
</div>
</div>
{o.description && (
<p className="text-xs text-(--text-secondary) mt-0.5 truncate">
{o.description}
</p>
)}
</button>
))}
</div>
)}
</div>
{/* ── Step 2: Negotiation ── */}
<div className="border border-(--border) rounded-xl p-5 mb-8">
<div className="flex items-center gap-2 mb-1">
<FileSignature
size={18}
className="text-teal-800 dark:text-teal-300"
/>
<h2 className="font-semibold text-sm">
{t("Step 2: Initiate Negotiation")}
</h2>
</div>
<p className="text-xs text-(--text-secondary) mb-4">
<T
area="research"
tags={{ c: <code className="text-(--text-secondary)" /> }}
>
{
"Submit a DSP <c>ContractRequest</c> with the selected ODRL offer. Protocol:"
}
</T>{" "}
<code className="text-(--text-secondary)">{DSP_PROTOCOL}</code>
</p>
{result && (
<div
className={`mb-4 p-3 rounded text-sm ${
resultIsError
? "bg-(--badge-inactive-bg) border border-(--badge-inactive-border) text-(--badge-inactive-text)"
: "bg-(--badge-active-bg) border border-(--badge-active-border) text-(--badge-active-text)"
}`}
>
{result}
</div>
)}
{tracked && (
<NegotiationProgress
tracked={tracked}
provider={didToName(providerDid)}
consumerCtx={selectedCtx}
/>
)}
{!selectedOffer && (
<div className="mb-4 p-3 rounded-sm bg-yellow-100 dark:bg-yellow-900/20 border border-yellow-300 dark:border-yellow-700/40 text-yellow-800 dark:text-yellow-400 text-xs flex gap-2">
<AlertCircle size={14} className="shrink-0 mt-0.5" />
<span>
{t(
"Complete Step 1 first: select a dataset offer above to negotiate.",
)}
</span>
</div>
)}
{selectedOffer && (
<div className="mb-4 p-3 rounded-sm bg-(--surface-2)/60 border border-(--border) text-sm">
<span className="text-(--text-secondary)">{t("Selected:")}</span>{" "}
<span className="text-(--text-primary) font-medium">
{selectedOffer.name || assetLabel(selectedOffer.assetId)}
</span>
{selectedOffer.contentType && (
<span className="ml-2 text-[10px] px-1.5 py-0.5 rounded-sm bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-gray-200">
{selectedOffer.contentType}
</span>
)}
</div>
)}
{selectedOffer?.policy && (
<OfferTerms
policy={selectedOffer.policy}
providerDid={selectedOffer.assignerDid || providerDid}
providerName={didToName(selectedOffer.assignerDid || providerDid)}
consumerName={
participants.find((p) => p["@id"] === selectedCtx)
?.displayName ?? didToName(selectedCtx)
}
accepted={termsAccepted}
onAcceptedChange={negotiated ? undefined : setTermsAccepted}
agreed={negotiated && tracked?.state === "FINALIZED"}
/>
)}
{negotiated ? (
<button
type="button"
data-testid="negotiate-again"
onClick={negotiateAgain}
className="text-xs text-(--text-secondary) underline hover:text-(--text-primary)"
>
{t("Negotiate this offer again")}
</button>
) : (
<form onSubmit={handleNegotiate} className="space-y-3">
{/* Hidden fields — populated automatically from Step 1 */}
<input type="hidden" value={assetId} />
<input type="hidden" value={offerId} />
<button
type="submit"
disabled={
initiating ||
!offerId ||
(!!selectedOffer?.policy && !termsAccepted)
}
className="flex items-center gap-2 px-4 py-2 bg-(--accent) text-white dark:text-gray-900 rounded-sm text-sm font-medium hover:bg-(--accent-hover) disabled:opacity-50"
>
{initiating ? (
<Loader2 size={14} className="animate-spin" />
) : (
<FileSignature size={14} />
)}
{t("Start Negotiation")}
</button>
</form>
)}
</div>
{/* Negotiation history */}
<h2 className="font-semibold text-sm mb-3">
{t("Negotiation History")}
</h2>
{loading ? (
<div className="flex items-center gap-2 text-(--text-secondary)">
<Loader2 size={16} className="animate-spin" />
{t("Loading negotiations…")}
</div>
) : negotiations.length === 0 ? (
<p className="text-(--text-secondary) text-sm">
{t("No negotiations found")}
</p>
) : (
<div className="grid gap-2">
{negotiations.map((n) => {
const agreementId = negField(n, "contractAgreementId");
const state = negField(n, "state");
const counterParty = negField(n, "counterPartyId");
// On a PROVIDER-side negotiation the counter-party is the one
// who asked, so it is the consumer, not the provider.
const counterPartyIsConsumer = negField(n, "type") === "PROVIDER";
return (
<div
key={n["@id"]}
className="flex items-center gap-3 p-3 border border-(--border) rounded-lg"
>
{stateIcon(state)}
<div className="flex-1 min-w-0">
<p className="text-sm font-medium text-(--text-primary) truncate">
{n.assetId
? assetLabel(n.assetId as string)
: n["@id"].slice(0, 12)}
</p>
<p className="text-xs text-(--text-secondary)">
{counterPartyIsConsumer ? t("Consumer:") : t("Provider:")}{" "}
{counterParty ? didToName(counterParty) : "—"}
{state === "FINALIZED" && ` · ${t("Agreement ready")}`}
</p>
</div>
<div className="flex items-center gap-2 shrink-0">
{/* A demo or sample negotiation is not one a DSP
counter-party agreed to. The row has to say so: an
unmarked FINALIZED badge in front of a regulator would
claim an agreement that nobody ever signed. #358 */}
<RowSourceBadge
source={
(n.source as RowSource | undefined) ??
(n.demo === true ? "demo" : undefined)
}
reason={n.demoReason as string | undefined}
/>
<span
className={`text-xs px-2 py-0.5 rounded-full ${
state.includes("FINALIZED")
? "bg-(--badge-active-bg) text-(--badge-active-text) border border-(--badge-active-border)"
: state.includes("ERROR")
? "bg-(--badge-inactive-bg) text-(--badge-inactive-text) border border-(--badge-inactive-border)"
: "bg-yellow-100 dark:bg-yellow-900/40 text-yellow-800 dark:text-yellow-400"
}`}
>
{state || "UNKNOWN"}
</span>
{agreementId && (
// A Link, not an <a>: Next adds the GitHub Pages base
// path to it, and a bare "/data/transfer" left the site
// for ma3u.github.io/data/transfer, a 404. #876
<Link
href={`/data/transfer?participantId=${encodeURIComponent(
selectedCtx,
)}&contractId=${encodeURIComponent(agreementId)}`}
className="flex items-center gap-1 text-xs text-teal-800 dark:text-teal-300 hover:underline"
>
{tn("Transfer")} <ArrowRight size={12} />
</Link>
)}
</div>
</div>
);
})}
</div>
)}
</div>
</div>
);
}
|