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

100% Statements 9/9
66.66% Branches 4/6
100% Functions 2/2
100% Lines 8/8

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                        2x                         3x 3x 2x 2x                                                                                                                                                 1x       1x                                         1x            
import { NextResponse } from "next/server";
import { requireAuth, isAuthError } from "@/lib/auth-guard";
import { runQuery } from "@/lib/neo4j";
import {
  BODY_FEES,
  CATEGORY_REDUCTION,
  HOLDER_FEES,
  REQUEST_FEE_EUR,
} from "@/lib/fees";
import { RETENTION_MONTHS } from "@/lib/retention";
import { resultsDeadline, type ResultRow } from "@/lib/results";
 
export const dynamic = "force-dynamic";
 
/**
 * GET /api/information: what the access body tells the public about
 * secondary use, Regulation (EU) 2025/327 Art. 58(1). Any signed-in
 * participant: Every API route needs a session since #404 (ADR-044). The
 * fixed parts (legal basis, safeguards, rights, how to exercise them) are on
 * the page; this route serves what comes from the graph: the access bodies
 * and their contact (e), who has been granted access to which datasets and
 * for what purpose (f), the results of the projects (g), the fee schedule
 * (Art. 62) and the number of persons who opted out (Art. 71). Issue #206, M6.
 */
export async function GET() {
  const auth = await requireAuth();
  if (isAuthError(auth)) return auth;
  try {
    const [bodies, access, results, optOuts] = await Promise.all([
      runQuery<{
        name: string;
        did: string;
        country: string | null;
        contactName: string | null;
        contactEmail: string | null;
      }>(
        `MATCH (h:Participant)
         WHERE toUpper(coalesce(h.participantType, '')) = 'HDAB'
            OR coalesce(h.participantId, h.id) ENDS WITH ':hdab'
         RETURN h.name AS name,
                coalesce(h.participantId, h.id) AS did,
                h.country AS country,
                h.complianceOfficerName AS contactName,
                h.complianceOfficerEmail AS contactEmail
         ORDER BY h.name`,
      ),
      runQuery<{
        permitId: string;
        applicant: string | null;
        applicantCountry: string | null;
        datasetId: string | null;
        datasetTitle: string | null;
        holder: string | null;
        purpose: string | null;
        validFrom: string | null;
        validUntil: string | null;
        status: string;
      }>(
        `MATCH (permit:HDABApproval)
         WHERE toUpper(coalesce(permit.status, '')) IN ['APPROVED', 'REVOKED']
         OPTIONAL MATCH (permit)-[:APPROVES]->(app:AccessApplication)
         OPTIONAL MATCH (p:Participant)-[:SUBMITTED]->(app)
         OPTIONAL MATCH (permit)-[:GRANTS_ACCESS_TO]->(ds:HealthDataset)
         OPTIONAL MATCH (holder:Participant)-[:OFFERS]->(:DataProduct)-[:DESCRIBED_BY]->(ds)
         RETURN permit.approvalId AS permitId,
                p.name AS applicant,
                p.country AS applicantCountry,
                coalesce(ds.datasetId, ds.id, app.datasetId) AS datasetId,
                coalesce(ds.title, ds.name) AS datasetTitle,
                head(collect(DISTINCT holder.name)) AS holder,
                coalesce(permit.permittedPurpose, app.requestedPurpose) AS purpose,
                toString(coalesce(permit.validFrom, permit.approvedAt, permit.decidedAt)) AS validFrom,
                toString(permit.validUntil) AS validUntil,
                toUpper(permit.status) AS status
         ORDER BY validFrom DESC`,
      ),
      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`,
      ),
      runQuery<{ optedOut: number; patients: number }>(
        // The persons with an open Art. 71 opt-out (ADR-062). It used to count
        // PatientConsent fields nothing writes, so a live graph always said 0.
        `OPTIONAL MATCH (o:OptOutRecord)
           WHERE o.reversedAt IS NULL
         WITH count(DISTINCT o.patientId) AS optedOut
         OPTIONAL MATCH (p:Patient)
         RETURN optedOut, count(p) AS patients`,
      ),
    ]);
    return NextResponse.json({
      article: "Regulation (EU) 2025/327, Art. 58(1)",
      generatedAt: new Date().toISOString(),
      bodies,
      access: access.map((a) => ({
        ...a,
        resultsDue: resultsDeadline(a.validUntil),
      })),
      results,
      optOut: {
        article: "Art. 71",
        optedOut: Number(optOuts[0]?.optedOut ?? 0),
        patients: Number(optOuts[0]?.patients ?? 0),
      },
      retention: { months: RETENTION_MONTHS, article: "Art. 73(1)(e)" },
      fees: {
        article: "Art. 62",
        currency: "EUR",
        body: BODY_FEES,
        holder: HOLDER_FEES,
        requestEur: REQUEST_FEE_EUR,
        reductions: CATEGORY_REDUCTION,
      },
    });
  } catch (err) {
    return NextResponse.json(
      { error: "Neo4j unavailable", detail: String(err) },
      { status: 502 },
    );
  }
}