All files / src/app/api/tasks route.ts

90.54% Statements 67/74
74.24% Branches 49/66
100% Functions 13/13
92.85% Lines 65/70

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      1x     1x           56x             1x                 10x 10x       18x                                                                             10x 10x   10x   10x       9x   2x     7x       7x   7x 7x 7x   7x                     1x                     1x       7x 7x 9x 9x 9x 9x       9x                               7x 7x 4x 4x 4x     4x     4x 4x 4x 4x 1x 3x                 4x       4x       4x   4x                                       9x     7x 10x 10x       13x                                           7x   13x         7x       13x 13x         3x     3x 3x 3x     3x 1x 1x             2x 2x 2x               2x                    
import { NextResponse } from "next/server";
import { edcClient, EDC_CONTEXT } from "@/lib/edc";
import { requireAuth, isAuthError } from "@/lib/auth-guard";
import { promises as fs } from "fs";
import path from "path";
 
export const dynamic = "force-dynamic";
 
/* ── Helpers ── */
 
/** Read a field from an EDC object that may be edc:-prefixed or unprefixed */
function f(obj: Record<string, unknown>, field: string): string {
  return (obj[field] ?? obj[`edc:${field}`] ?? "") as string;
}
 
/**
 * Approved fictional participants — DID slug → display name.
 * Matches the lookup in participants/route.ts and negotiate/page.tsx.
 */
const SLUG_NAMES: Record<string, string> = {
  "alpha-klinik": "AlphaKlinik Berlin",
  pharmaco: "PharmaCo Research AG",
  medreg: "MedReg DE",
  lmc: "Limburg Medical Centre",
  irs: "Institut de Recherche Santé",
};
 
function didToName(did: string): string {
  const slug = decodeURIComponent(did).split(":").pop()?.toLowerCase() ?? "";
  return SLUG_NAMES[slug] || slug || did.slice(0, 16);
}
 
function assetLabel(id: string): string {
  return id.replace(/-/g, " ").replace(/\b\w/g, (c) => c.toUpperCase());
}
 
/* ── Types ── */
 
interface Task {
  id: string;
  type: "negotiation" | "transfer";
  participant: string; // human-readable participant name
  participantId: string; // UUID context ID
  asset: string; // human-readable asset name
  assetId: string; // raw asset ID
  state: string; // DSP state (REQUESTED, STARTED, FINALIZED, COMPLETED, etc.)
  counterParty: string; // human-readable counter-party name
  timestamp: number; // last state update
  contractId?: string; // contract agreement ID (if available)
  transferType?: string; // e.g. HttpData-PULL
  edrAvailable?: boolean; // DPS: true when contentDataAddress has an endpoint (transfer STARTED)
}
 
interface EdcParticipant {
  "@id": string;
  participantId?: string;
  identity?: string;
  [key: string]: unknown;
}
 
/**
 * GET /api/tasks — Aggregate all negotiations and transfers across
 * all participant contexts into a unified task list.
 *
 * Aligns with the EDC Data Plane Signaling (DPS) framework:
 * - Negotiations follow DSP: REQUESTED → OFFERED → ACCEPTED → AGREED → VERIFIED → FINALIZED
 * - Transfers follow DSP: REQUESTED → STARTED → SUSPENDED → COMPLETED
 * - EDR availability is checked for STARTED transfers via contentDataAddress
 *
 * Returns: { tasks: Task[], counts: { total, negotiations, transfers, active } }
 */
export async function GET() {
  const auth = await requireAuth();
  Iif (isAuthError(auth)) return auth;
 
  try {
    // 1. List all participant contexts
    const participants = await edcClient.management<EdcParticipant[]>(
      "/v5alpha/participants",
    );
 
    if (!Array.isArray(participants) || participants.length === 0) {
      // No participant contexts in EDC-V — fall through to mock data
      throw new Error("No participant contexts in EDC-V");
    }
 
    const tasks: Task[] = [];
 
    // 2. For each participant, fetch negotiations + transfers in parallel
    //    (all participants included — HDABs can have negotiations too)
    await Promise.all(
      participants.map(async (p) => {
        const ctxId = p["@id"];
        const did = (p.participantId || p.identity || ctxId) as string;
        const pName = didToName(did);
 
        const [negotiations, transfers] = await Promise.all([
          edcClient
            .management<Record<string, unknown>[]>(
              `/v5alpha/participants/${ctxId}/contractnegotiations/request`,
              "POST",
              {
                "@context": [EDC_CONTEXT],
                "@type": "QuerySpec",
                filterExpression: [],
              },
            )
            .catch(() => []),
          edcClient
            .management<Record<string, unknown>[]>(
              `/v5alpha/participants/${ctxId}/transferprocesses/request`,
              "POST",
              {
                "@context": [EDC_CONTEXT],
                "@type": "QuerySpec",
                filterExpression: [],
              },
            )
            .catch(() => []),
        ]);
 
        // Map negotiations → tasks
        Eif (Array.isArray(negotiations)) {
          for (const n of negotiations) {
            const state = f(n, "state");
            const assetId = f(n, "assetId");
            const counterPartyId = f(n, "counterPartyId");
            const ts = (n.stateTimestamp ??
              n["edc:stateTimestamp"] ??
              0) as number;
 
            tasks.push({
              id: n["@id"] as string,
              type: "negotiation",
              participant: pName,
              participantId: ctxId,
              asset: assetId ? assetLabel(assetId) : "Unknown Asset",
              assetId,
              state,
              counterParty: counterPartyId ? didToName(counterPartyId) : "—",
              timestamp: ts,
              contractId: f(n, "contractAgreementId") || undefined,
            });
          }
        }
 
        // Map transfers → tasks (with DPS EDR indicator)
        Eif (Array.isArray(transfers)) {
          for (const t of transfers) {
            const state = f(t, "state");
            const assetId = (t.assetId as string) || f(t, "assetId");
            const ts = (t.stateTimestamp ??
              t["edc:stateTimestamp"] ??
              0) as number;
            const contractId = f(t, "contractId");
 
            // Resolve counter-party from the transfer's counterPartyAddress or correlationId
            const counterPartyAddr = f(t, "counterPartyAddress");
            const counterPartyId = f(t, "counterPartyId");
            let counterParty = "—";
            if (counterPartyId) {
              counterParty = didToName(counterPartyId);
            I} else if (counterPartyAddr) {
              // Extract DID-like slug from DSP address
              const match = counterPartyAddr.match(/\/([^/]+)\/dsp/);
              if (match) counterParty = match[1];
            }
 
            // DPS: Check contentDataAddress for EDR availability
            // When the Control Plane signals the Data Plane via DPS /api/control/v1/dataflows,
            // the Data Plane writes back an EDR with endpoint + authorization token
            const cda = t.contentDataAddress as
              | Record<string, unknown>
              | undefined;
            const edrEndpoint =
              cda?.["https://w3id.org/edc/v0.0.1/ns/endpoint"] ??
              cda?.["edc:endpoint"] ??
              cda?.endpoint;
            const edrAvailable =
              !!edrEndpoint && state?.toUpperCase() === "STARTED";
 
            tasks.push({
              id: t["@id"] as string,
              type: "transfer",
              participant: pName,
              participantId: ctxId,
              asset: assetId ? assetLabel(assetId) : "Unknown Asset",
              assetId,
              state,
              counterParty,
              timestamp: ts,
              contractId: contractId || undefined,
              transferType: f(t, "transferType") || "HttpData-PULL",
              edrAvailable,
            });
          }
        }
      }),
    );
 
    // 3. Sort by timestamp descending (newest first)
    tasks.sort((a, b) => b.timestamp - a.timestamp);
 
    // 4. Sync tasks to persistent storage (neo4j-proxy → PostgreSQL)
    const NEO4J_PROXY = process.env.NEO4J_PROXY_URL ?? "http://localhost:9090";
    try {
      await fetch(`${NEO4J_PROXY}/tasks/sync`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
          tasks: tasks.map((t) => ({
            id: t.id,
            type: t.type,
            participant: t.participant,
            participant_id: t.participantId,
            asset: t.asset,
            asset_id: t.assetId,
            state: t.state,
            counter_party: t.counterParty,
            timestamp_ms: t.timestamp,
            contract_id: t.contractId ?? null,
            transfer_type: t.transferType ?? null,
            edr_available: t.edrAvailable ?? false,
          })),
        }),
        signal: AbortSignal.timeout(5000),
      });
    } catch {
      // Sync best-effort — don't fail the request
    }
 
    // 5. Compute counts
    const active = tasks.filter(
      (t) =>
        !["FINALIZED", "COMPLETED", "TERMINATED", "ERROR"].includes(
          t.state?.toUpperCase() || "",
        ),
    ).length;
 
    return NextResponse.json({
      tasks,
      counts: {
        total: tasks.length,
        negotiations: tasks.filter((t) => t.type === "negotiation").length,
        transfers: tasks.filter((t) => t.type === "transfer").length,
        active,
      },
    });
  } catch (err) {
    console.error("Failed to aggregate tasks from EDC-V:", err);
 
    // Fall back to persistent task storage (PostgreSQL via neo4j-proxy)
    const NEO4J_PROXY = process.env.NEO4J_PROXY_URL ?? "http://localhost:9090";
    try {
      const fallbackRes = await fetch(`${NEO4J_PROXY}/tasks`, {
        signal: AbortSignal.timeout(5000),
      });
      if (fallbackRes.ok) {
        const data = await fallbackRes.json();
        return NextResponse.json(data);
      }
    } catch {
      // Both EDC-V and persistent storage unavailable
    }
 
    // Fall back to bundled mock data so the UI works offline
    try {
      const mockPath = path.join(process.cwd(), "public", "mock", "tasks.json");
      const raw = await fs.readFile(mockPath, "utf-8");
      const mock = JSON.parse(raw);
      console.warn("EDC-V offline — serving mock tasks");
      return NextResponse.json(mock);
    } catch {
      // Mock file not available either
    }
 
    return NextResponse.json(
      {
        error: "Failed to aggregate tasks",
        tasks: [],
        counts: { total: 0, negotiations: 0, transfers: 0, active: 0 },
      },
      { status: 502 },
    );
  }
}