All files / src/app/api/compliance/results route.ts

89.47% Statements 34/38
78.94% Branches 30/38
100% Functions 2/2
91.66% Lines 33/36

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                        2x                             5x         5x     5x 5x         5x 5x 5x 5x   5x     5x 1x                   4x 4x       5x                               4x           4x 4x       1x         3x 1x           2x 2x   2x     5x 5x       5x                                                               2x                                     2x 2x 1x 1x                                         1x                        
import { NextRequest, NextResponse } from "next/server";
import { requireAuth, isAuthError } from "@/lib/auth-guard";
import { runQuery } from "@/lib/neo4j";
import { userToParticipantId } from "@/lib/odrl-engine";
import { parseGraphTime } from "@/lib/permits";
import {
  RESULT_KINDS,
  resultsDeadline,
  type ResultKind,
  type ResultRow,
} from "@/lib/results";
 
export const dynamic = "force-dynamic";
 
/**
 * Results communicated by data users, Regulation (EU) 2025/327 Art. 61(4).
 *
 * POST: the holder of a data permit reports what came of the use: a
 * publication, a policy document, a regulatory procedure, an IT product. The
 * deadline is 18 months after the end of the processing (the permit's
 * validity end); the record says whether it was met. GET: every result,
 * because the access body publishes them (Art. 57(1)(j)(v)) and reports them
 * (Art. 59(1)(j), (k)), to any signed-in participant: every API route needs
 * a session since #404 (ADR-044). Issue #206, M6.
 */
 
export async function POST(req: NextRequest) {
  const auth = await requireAuth([
    "DATA_USER",
    "EDC_USER_PARTICIPANT",
    "EDC_ADMIN",
  ]);
  Iif (isAuthError(auth)) return auth;
 
  let body: Record<string, unknown>;
  try {
    body = (await req.json()) as Record<string, unknown>;
  } catch {
    return NextResponse.json({ error: "Body must be JSON" }, { status: 400 });
  }
  const permitId =
    typeof body.permitId === "string" ? body.permitId.trim() : "";
  const kind = String(body.kind ?? "").toUpperCase() as ResultKind;
  const title = typeof body.title === "string" ? body.title.trim() : "";
  const summary = typeof body.summary === "string" ? body.summary.trim() : "";
  const url =
    typeof body.url === "string" && /^https?:\/\//.test(body.url.trim())
      ? body.url.trim()
      : null;
  if (!permitId || !RESULT_KINDS.includes(kind) || !title) {
    return NextResponse.json(
      {
        error: `permitId, kind (${RESULT_KINDS.join(
          ", ",
        )}) and title are required (Art. 61(4))`,
      },
      { status: 400 },
    );
  }
 
  const { session } = auth;
  const callerDid = userToParticipantId(
    session.user.email ?? session.user.name ?? session.user.id,
    session.roles,
  );
  const found = await runQuery<{
    permitId: string;
    status: string;
    applicantId: string | null;
    validUntil: string | null;
  }>(
    `MATCH (permit:HDABApproval {approvalId: $permitId})
     OPTIONAL MATCH (permit)-[:APPROVES]->(app:AccessApplication)
     OPTIONAL MATCH (p:Participant)-[:SUBMITTED]->(app)
     RETURN permit.approvalId AS permitId,
            toUpper(coalesce(permit.status, '')) AS status,
            coalesce(app.applicantId, p.participantId, p.id) AS applicantId,
            toString(permit.validUntil) AS validUntil
     LIMIT 1`,
    { permitId },
  );
  Iif (found.length === 0) {
    return NextResponse.json(
      { error: `Data permit ${permitId} is not in the graph` },
      { status: 404 },
    );
  }
  const permit = found[0];
  if (
    permit.applicantId !== callerDid &&
    !session.roles.includes("EDC_ADMIN")
  ) {
    return NextResponse.json(
      { error: "Only the holder of the permit communicates its results" },
      { status: 403 },
    );
  }
  if (!["APPROVED", "REVOKED"].includes(permit.status)) {
    return NextResponse.json(
      { error: "No data permit was issued on this application" },
      { status: 409 },
    );
  }
 
  const communicatedAt = new Date();
  const deadline = resultsDeadline(permit.validUntil);
  const onTime =
    deadline !== null
      ? communicatedAt.getTime() <= (parseGraphTime(deadline) ?? 0)
      : null;
  const stamp = communicatedAt.toISOString().slice(0, 10).replace(/-/g, "");
  const resultId = `result-${permitId.replace(
    /^permit-/,
    "",
  )}-${stamp}-${Math.random().toString(36).slice(2, 6)}`;
  await runQuery(
    `MATCH (permit:HDABApproval {approvalId: $permitId})
     MERGE (rc:ResultCommunication {resultId: $resultId})
     SET rc.permitId       = $permitId,
         rc.applicantId    = $applicantId,
         rc.kind           = $kind,
         rc.title          = $title,
         rc.summary        = $summary,
         rc.url            = $url,
         rc.communicatedAt = datetime($communicatedAt),
         rc.deadline       = CASE WHEN $deadline IS NULL THEN null ELSE datetime($deadline) END,
         rc.onTime         = $onTime,
         rc.ehdsArticle    = 'Art. 61(4)'
     MERGE (rc)-[:RESULT_OF]->(permit)
     WITH rc
     OPTIONAL MATCH (p:Participant)
       WHERE coalesce(p.participantId, p.id) = $applicantId
     FOREACH (_ IN CASE WHEN p IS NOT NULL THEN [1] ELSE [] END |
       MERGE (p)-[:COMMUNICATED]->(rc))`,
    {
      permitId,
      resultId,
      applicantId: permit.applicantId,
      kind,
      title,
      summary,
      url,
      communicatedAt: communicatedAt.toISOString(),
      deadline,
      onTime,
    },
  );
  return NextResponse.json(
    {
      resultId,
      permitId,
      kind,
      title,
      communicatedAt: communicatedAt.toISOString(),
      deadline,
      onTime,
      article:
        onTime === false
          ? "Regulation (EU) 2025/327, Art. 61(4): results communicated after the 18 months"
          : "Regulation (EU) 2025/327, Art. 61(4): results communicated within the 18 months; published under Art. 57(1)(j)(v)",
    },
    { status: 201 },
  );
}
 
export async function GET() {
  const auth = await requireAuth();
  if (isAuthError(auth)) return auth;
  try {
    const rows = await runQuery<ResultRow>(
      `MATCH (rc:ResultCommunication)
       OPTIONAL MATCH (rc)-[:RESULT_OF]->(permit:HDABApproval)
       OPTIONAL MATCH (permit)-[:GRANTS_ACCESS_TO]->(ds:HealthDataset)
       OPTIONAL MATCH (p:Participant)
         WHERE coalesce(p.participantId, p.id) = rc.applicantId
       RETURN rc.resultId                   AS resultId,
              rc.permitId                   AS permitId,
              rc.applicantId                AS applicant,
              p.name                        AS applicantName,
              coalesce(ds.datasetId, ds.id) AS datasetId,
              coalesce(ds.title, ds.name)   AS datasetTitle,
              rc.kind                       AS kind,
              rc.title                      AS title,
              rc.summary                    AS summary,
              rc.url                        AS url,
              toString(rc.communicatedAt)   AS communicatedAt,
              toString(rc.deadline)         AS deadline,
              rc.onTime                     AS onTime
       ORDER BY rc.communicatedAt DESC`,
    );
    return NextResponse.json({
      results: rows,
      article:
        "Regulation (EU) 2025/327, Art. 61(4); published under Art. 57(1)(j)(v)",
    });
  } catch (err) {
    return NextResponse.json(
      { error: "Neo4j unavailable", detail: String(err) },
      { status: 502 },
    );
  }
}