All files / src/app/api/compliance/requests/decide route.ts

86.95% Statements 40/46
81.66% Branches 49/60
100% Functions 1/1
86.66% Lines 39/45

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                  2x                             10x 10x     9x 9x         9x 10x   10x 10x           9x 1x           8x 8x       10x 10x 10x       10x 10x 10x     3x                     3x           3x 2x                 1x     6x                                                                         6x 1x         5x   5x 3x                               2x   10x 10x 2x                       2x                                               2x 2x 2x                                         2x                                              
import { NextRequest, NextResponse } from "next/server";
import { requireAuth, isAuthError } from "@/lib/auth-guard";
import { runQuery } from "@/lib/neo4j";
import { resolveOdrlScope, userToParticipantId } from "@/lib/odrl-engine";
import { PUBLISH_WORKING_DAYS, addWorkingDays } from "@/lib/permits";
import { REQUEST_FEE_EUR } from "@/lib/fees";
import { toStatisticalAnswer, type NlqAnswer } from "@/lib/statistics";
import { NEO4J_PROXY_URL, callerHeaders } from "@/lib/proxy";
 
export const dynamic = "force-dynamic";
 
/**
 * POST /api/compliance/requests/decide: the access body decides on a health
 * data request (Regulation (EU) 2025/327, Art. 69(3) and (4)).
 *
 * On approval the question is run once, here, in the applicant's name
 * against the graph, and only the anonymised statistical result is kept on
 * the request. The applicant never receives the query, the records or any
 * count below the k-anonymity threshold (Art. 69(1)). The run is recorded by
 * the proxy as an access event under the request id. Issue #206, M5.
 */
export async function POST(req: NextRequest) {
  // The access body decides (Art. 69(3)); so does a trusted data holder for a
  // request on its own dataset, under the body's supervision (Art. 72).
  const auth = await requireAuth(["HDAB_AUTHORITY", "DATA_HOLDER"]);
  if (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 requestId =
    typeof body.requestId === "string" ? body.requestId.trim() : "";
  const decision = String(body.decision ?? "").toUpperCase();
  const justification =
    typeof body.justification === "string" ? body.justification.trim() : "";
  Iif (!requestId || !["APPROVED", "REJECTED"].includes(decision)) {
    return NextResponse.json(
      { error: "requestId and decision (APPROVED or REJECTED) are required" },
      { status: 400 },
    );
  }
  if (decision === "REJECTED" && !justification) {
    return NextResponse.json(
      { error: "A refusal needs a written justification (Art. 57(1)(j)(iii))" },
      { status: 400 },
    );
  }
 
  const { session } = auth;
  const decidedBy = userToParticipantId(
    session.user.email ?? session.user.name ?? session.user.id,
    session.roles,
  );
  const officer = session.user.name ?? session.user.email ?? session.user.id;
  const decidedAt = new Date();
  const publishBy = addWorkingDays(decidedAt, PUBLISH_WORKING_DAYS)
    .toISOString()
    .slice(0, 10);
 
  const isBody = session.roles.includes("HDAB_AUTHORITY");
  let decidedUnder = "Art. 69(3)";
  if (!isBody) {
    // Art. 72: a trusted data holder answers requests on the datasets it
    // offers; anything else stays with the access body.
    const trusted = await runQuery<{ trusted: boolean; own: boolean }>(
      `MATCH (r:HealthDataRequest {requestId: $requestId})
       OPTIONAL MATCH (holder:Participant)
         WHERE coalesce(holder.participantId, holder.id) = $decidedBy
       OPTIONAL MATCH (holder)-[:OFFERS]->(:DataProduct)-[:DESCRIBED_BY]->(ds:HealthDataset)
         WHERE coalesce(ds.datasetId, ds.id) = r.datasetId
       RETURN coalesce(holder.trustedHolder, false) AS trusted,
              count(ds) > 0 AS own
       LIMIT 1`,
      { requestId, decidedBy },
    );
    Iif (trusted.length === 0) {
      return NextResponse.json(
        { error: `Health data request ${requestId} is not in the graph` },
        { status: 404 },
      );
    }
    if (!trusted[0].trusted || !trusted[0].own) {
      return NextResponse.json(
        {
          error: trusted[0].trusted
            ? "A trusted data holder decides only on requests for the datasets it offers (Art. 72)"
            : "Only the health data access body, or a trusted data holder for its own datasets, decides (Art. 69(3), Art. 72)",
        },
        { status: 403 },
      );
    }
    decidedUnder = "Art. 72";
  }
 
  const found = await runQuery<{
    requestId: string;
    applicantId: string | null;
    question: string | null;
    purpose: string | null;
    datasetId: string | null;
  }>(
    `MATCH (r:HealthDataRequest {requestId: $requestId})
     SET r.status        = $decision,
         r.decidedAt     = datetime($decidedAt),
         r.decidedBy     = $decidedBy,
         r.decidedUnder  = $decidedUnder,
         r.simplifiedProcedure = $decidedUnder = 'Art. 72',
         r.officer       = $officer,
         r.justification = $justification,
         r.feeEur        = CASE WHEN $decision = 'APPROVED' THEN $feeEur ELSE null END,
         r.publishBy     = date($publishBy)
     WITH r
     OPTIONAL MATCH (hdab:Participant)
       WHERE coalesce(hdab.participantId, hdab.id) = $decidedBy
     FOREACH (_ IN CASE WHEN hdab IS NOT NULL THEN [1] ELSE [] END |
       MERGE (hdab)-[:DECIDED]->(r))
     RETURN r.requestId AS requestId, r.applicantId AS applicantId,
            r.question AS question, r.purpose AS purpose, r.datasetId AS datasetId
     LIMIT 1`,
    {
      requestId,
      decision,
      decidedAt: decidedAt.toISOString(),
      decidedBy,
      decidedUnder,
      officer,
      justification,
      feeEur: REQUEST_FEE_EUR,
      publishBy,
    },
  );
  if (found.length === 0) {
    return NextResponse.json(
      { error: `Health data request ${requestId} is not in the graph` },
      { status: 404 },
    );
  }
  const request = found[0];
 
  if (decision === "REJECTED") {
    return NextResponse.json({
      requestId,
      decision,
      decidedAt: decidedAt.toISOString(),
      decidedBy,
      decidedUnder,
      justification,
      publishBy,
      article:
        decidedUnder === "Art. 72"
          ? "Regulation (EU) 2025/327, Art. 72: request refused by the trusted data holder"
          : "Regulation (EU) 2025/327, Art. 69(3): request refused",
    });
  }
 
  // Approved: produce the statistic in the applicant's name, once, here.
  const applicantId = request.applicantId ?? "";
  let nlq: NlqAnswer;
  try {
    const odrlScope = await resolveOdrlScope(applicantId);
    const resp = await fetch(`${NEO4J_PROXY_URL}/nlq`, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        "X-Participant": applicantId,
        ...callerHeaders(auth.session),
        "X-Request": requestId,
        "X-Purpose": request.purpose ?? "",
        ...(request.datasetId ? { "X-Dataset": request.datasetId } : {}),
      },
      body: JSON.stringify({ question: request.question, odrlScope }),
    });
    nlq = (await resp.json()) as NlqAnswer;
  } catch (err) {
    const detail = err instanceof Error ? err.message : String(err);
    await runQuery(
      `MATCH (r:HealthDataRequest {requestId: $requestId})
       SET r.answerError = $answerError`,
      {
        requestId,
        answerError: `The statistical service was unreachable: ${detail}`,
      },
    );
    return NextResponse.json({
      requestId,
      decision,
      decidedAt: decidedAt.toISOString(),
      decidedBy,
      publishBy,
      answered: false,
      answerError: `The statistical service was unreachable: ${detail}`,
      article:
        "Regulation (EU) 2025/327, Art. 69(3): request approved, answer pending",
    });
  }
 
  const stat = toStatisticalAnswer(nlq);
  const answeredAt = new Date();
  await runQuery(
    `MATCH (r:HealthDataRequest {requestId: $requestId})
     SET r.status         = $status,
         r.answer         = $answer,
         r.answerTemplate = $answerTemplate,
         r.answerError    = $answerError,
         r.answeredAt     = CASE WHEN $answer IS NULL THEN null ELSE datetime($answeredAt) END,
         r.suppressedCells = $suppressedCells,
         r.kAnonymity     = $kAnonymity`,
    {
      requestId,
      status: stat.ok ? "ANSWERED" : "APPROVED",
      answer: stat.ok ? JSON.stringify(stat.rows) : null,
      answerTemplate: stat.templateName,
      answerError: stat.ok ? null : stat.reason,
      answeredAt: answeredAt.toISOString(),
      suppressedCells: stat.suppressedCells,
      kAnonymity: stat.kAnonymity,
    },
  );
 
  return NextResponse.json({
    requestId,
    decision,
    decidedAt: decidedAt.toISOString(),
    decidedBy,
    decidedUnder,
    feeEur: REQUEST_FEE_EUR,
    publishBy,
    answered: stat.ok,
    answer: stat.ok ? stat.rows : null,
    answerTemplate: stat.templateName,
    answerError: stat.ok ? null : stat.reason,
    suppressedCells: stat.suppressedCells,
    kAnonymity: stat.kAnonymity,
    article: stat.ok
      ? `Regulation (EU) 2025/327, Art. 69(1): answered in anonymised statistical format${
          decidedUnder === "Art. 72"
            ? " by the trusted data holder (Art. 72)"
            : ""
        }`
      : "Regulation (EU) 2025/327, Art. 69(1): approved, but the question yields no statistical answer",
  });
}