All files / src/app/api/activity-report route.ts

100% Statements 15/15
83.33% Branches 5/6
100% Functions 1/1
100% Lines 14/14

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                                2x                         5x 5x 4x 4x 4x   4x   4x                                                                                                                                                                                                       3x                       3x 1x                     2x   1x 1x                  
import { NextRequest, NextResponse } from "next/server";
import { requireAuth, isAuthError } from "@/lib/auth-guard";
import { runQuery } from "@/lib/neo4j";
import {
  buildActivityReport,
  reportPeriod,
  toMarkdown,
  type AccessRow,
  type ApplicationRow,
  type BodyRow,
  type LabelRow,
  type MeasureRow,
  type RequestRow,
  type ResultReportRow,
} from "@/lib/activity-report";
 
export const dynamic = "force-dynamic";
 
/**
 * GET /api/activity-report[?from=YYYY-MM-DD&to=YYYY-MM-DD&format=md]
 *
 * The activity report of the health data access body, Regulation (EU)
 * 2025/327 Art. 59(1)(a) to (k), generated from the graph for the period
 * (default: the last 24 months). The regulation wants the report published
 * on the body's website; Every API route needs a session since #404 (ADR-044), so it is
 * served to any signed-in participant. Nothing personal leaves this route:
 * organisations, counts, dates and reasons. Issue #206, M6.
 */
export async function GET(request: NextRequest) {
  const auth = await requireAuth();
  if (isAuthError(auth)) return auth;
  const params = request.nextUrl.searchParams;
  const { from, to } = reportPeriod(params.get("from"), params.get("to"));
  const window = { from: from.toISOString(), to: to.toISOString() };
 
  try {
    const [bodies, applications, requests, access, labels, results, measures] =
      await Promise.all([
        runQuery<BodyRow>(
          `MATCH (h:Participant)
           WHERE toUpper(coalesce(h.participantType, '')) = 'HDAB'
           RETURN h.name AS name,
                  coalesce(h.participantId, h.id) AS did,
                  h.country AS country
           ORDER BY h.name`,
        ),
        runQuery<ApplicationRow>(
          `MATCH (app:AccessApplication)
           OPTIONAL MATCH (p:Participant)-[:SUBMITTED]->(app)
           OPTIONAL MATCH (permit:HDABApproval)-[:APPROVES]->(app)
           OPTIONAL MATCH (permit)-[:GRANTS_ACCESS_TO]->(granted:HealthDataset)
           OPTIONAL MATCH (requested:HealthDataset)
             WHERE coalesce(requested.datasetId, requested.id) = app.datasetId
           OPTIONAL MATCH (t:DataTransfer)-[:UNDER_PERMIT]->(permit)
           OPTIONAL MATCH (te:TransferEvent)-[:UNDER_PERMIT]->(permit)
           WITH app, p, permit, granted, requested,
                collect(DISTINCT toString(t.timestamp)) + collect(DISTINCT toString(te.timestamp)) AS accessTimes
           RETURN app.applicationId AS applicationId,
                  p.name AS applicant,
                  p.participantType AS applicantType,
                  coalesce(permit.permittedPurpose, app.requestedPurpose) AS purpose,
                  toString(app.submittedAt) AS submittedAt,
                  permit.approvalId AS permitId,
                  permit.status AS permitStatus,
                  toString(coalesce(permit.decidedAt, permit.approvedAt)) AS decidedAt,
                  toString(permit.revokedAt) AS revokedAt,
                  permit.revocationReason AS revocationReason,
                  coalesce(granted.datasetId, granted.id, app.datasetId) AS datasetId,
                  coalesce(granted.title, requested.title, granted.name, requested.name) AS datasetTitle,
                  permit.feeEur AS feeEur,
                  reduce(m = null, x IN accessTimes |
                    CASE WHEN x IS NULL OR x = 'null' THEN m
                         WHEN m IS NULL OR x < m THEN x ELSE m END) AS firstAccessAt
           ORDER BY app.submittedAt`,
        ),
        runQuery<RequestRow>(
          `MATCH (r:HealthDataRequest)
           RETURN r.requestId AS requestId,
                  r.status AS status,
                  r.purpose AS purpose,
                  toString(r.submittedAt) AS submittedAt,
                  r.feeEur AS feeEur`,
        ),
        runQuery<AccessRow>(
          `MATCH (te:TransferEvent)
           WHERE te.timestamp IS NULL
              OR (datetime(toString(te.timestamp)) >= datetime($from)
                  AND datetime(toString(te.timestamp)) <= datetime($to))
           WITH coalesce(te.consumerDid, te.participant, 'unknown') AS consumer, te
           OPTIONAL MATCH (c:Participant)
             WHERE coalesce(c.participantId, c.id) = consumer
           RETURN consumer,
                  head(collect(DISTINCT c.name)) AS consumerName,
                  count(te) AS events,
                  count(te.permitId) AS underPermit,
                  count(CASE WHEN toInteger(te.statusCode) = 403 THEN 1 END) AS refused,
                  count(DISTINCT te.permitId) AS permits
           ORDER BY events DESC`,
          window,
        ),
        runQuery<LabelRow>(
          `MATCH (vc:VerifiableCredential {credentialType: 'DataQualityLabelCredential'})
           OPTIONAL MATCH (holder:Participant)-[:HOLDS_CREDENTIAL]->(vc)
           RETURN vc.credentialId AS credentialId,
                  vc.datasetId AS datasetId,
                  head(collect(DISTINCT holder.name)) AS holder,
                  vc.completeness AS completeness,
                  vc.conformance AS conformance,
                  vc.timeliness AS timeliness,
                  vc.eehrxfCoverage AS coverage,
                  toString(vc.assessmentDate) AS assessmentDate,
                  vc.status AS status
           ORDER BY vc.credentialId`,
        ),
        // Art. 61(4): results communicated by data users, for (a), (j) and (k)
        runQuery<ResultReportRow>(
          `MATCH (rc:ResultCommunication)
           OPTIONAL MATCH (p:Participant)
             WHERE coalesce(p.participantId, p.id) = rc.applicantId
           RETURN rc.resultId AS resultId, rc.permitId AS permitId,
                  p.name AS applicant, rc.kind AS kind, rc.title AS title,
                  rc.url AS url, toString(rc.communicatedAt) AS communicatedAt,
                  rc.onTime AS onTime
           ORDER BY rc.communicatedAt`,
        ),
        // Art. 63(3), Art. 64: measures on closed findings, for (b)
        runQuery<MeasureRow>(
          `MATCH (f:NonComplianceFinding)
           WHERE toUpper(coalesce(f.status, '')) = 'CLOSED'
           OPTIONAL MATCH (f)-[:AGAINST]->(party:Participant)
           RETURN f.findingId AS findingId, party.name AS party,
                  f.measure AS measure, f.measureNote AS note,
                  f.fineEur AS fineEur, toString(f.closedAt) AS closedAt
           ORDER BY f.closedAt`,
        ),
      ]);
 
    const report = buildActivityReport({
      bodies,
      applications,
      requests,
      access,
      labels,
      results,
      measures,
      from,
      to,
    });
 
    if (params.get("format") === "md") {
      return new NextResponse(toMarkdown(report), {
        status: 200,
        headers: {
          "Content-Type": "text/markdown; charset=utf-8",
          "Content-Disposition": `inline; filename="activity-report-${report.period.to.slice(
            0,
            10,
          )}.md"`,
        },
      });
    }
    return NextResponse.json(report);
  } catch (err) {
    console.error("GET /api/activity-report error:", err);
    return NextResponse.json(
      {
        error: "Neo4j unavailable",
        detail: err instanceof Error ? err.message : String(err),
      },
      { status: 502 },
    );
  }
}