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

84.21% Statements 16/19
82.35% Branches 14/17
100% Functions 3/3
88.88% Lines 16/18

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              2x     7x 7x         7x 7x       7x         7x 1x   6x                               7x 2x 7x 36x       7x               7x                                                                                                                     6x                                          
import { NextResponse } from "next/server";
import { runQuery } from "@/lib/neo4j";
import { requireAuth, isAuthError } from "@/lib/auth-guard";
import { userToParticipantId } from "@/lib/odrl-engine";
import { gateSecondaryUse } from "@/lib/permit-gate";
import { forRoles, secondaryUseView } from "@/lib/opt-out";
 
export const dynamic = "force-dynamic";
 
export async function GET() {
  const auth = await requireAuth();
  Iif (isAuthError(auth)) return auth;
 
  // The cohort statistics are secondary use; a data user sees them only
  // under a data permit (Art. 61(1), issue #206 M3). The response names the
  // permit it ran under so the page can show it.
  const { session } = auth;
  const participantId = userToParticipantId(
    session.user.email ?? session.user.name ?? session.user.id,
    session.roles,
  );
  const gate = await gateSecondaryUse({
    consumerDid: participantId,
    roles: session.roles,
    what: "analysis",
  });
  if (!gate.allowed) {
    return NextResponse.json(gate.body, { status: gate.status });
  }
  const permit = gate.check
    ? {
        permitId: gate.check.permitId,
        datasetId: gate.check.datasetId,
        purpose: gate.check.purpose,
        validUntil: gate.check.validUntil,
        article: gate.check.article,
      }
    : null;
 
  // Art. 71 (ADR-062): for a data user, an access body or a trust centre
  // the statistics leave out the persons who opted out of secondary use.
  // A patient may read them too (decided in #951, J313): aggregate counts of
  // the demo cohort, no person in them, and without the persons who opted
  // out, since for a patient these are other people's records, not their own.
  const patientOnly =
    session.roles.includes("PATIENT") &&
    !session.roles.some((r) => r === "EDC_ADMIN" || r === "DATA_HOLDER");
  const query = <T>(cypher: string) =>
    runQuery<T>(
      patientOnly ? secondaryUseView(cypher) : forRoles(cypher, session.roles),
    );
 
  try {
    const [
      summary,
      topConditions,
      topDrugs,
      topMeasurements,
      topProcedures,
      genderBreakdown,
    ] = await Promise.all([
      query<{
        persons: number;
        conditions: number;
        drugs: number;
        measurements: number;
        procedures: number;
        visits: number;
      }>(
        `MATCH (op:OMOPPerson)
         WITH count(op) AS persons
         MATCH (oc:OMOPConditionOccurrence)
         WITH persons, count(oc) AS conditions
         MATCH (od:OMOPDrugExposure)
         WITH persons, conditions, count(od) AS drugs
         MATCH (om:OMOPMeasurement)
         WITH persons, conditions, drugs, count(om) AS measurements
         OPTIONAL MATCH (opo:OMOPProcedureOccurrence)
         WITH persons, conditions, drugs, measurements, count(opo) AS procedures
         MATCH (ov:OMOPVisitOccurrence)
         RETURN persons, conditions, drugs, measurements, procedures, count(ov) AS visits`,
      ),
 
      query<{ label: string; count: number }>(
        `MATCH (oc:OMOPConditionOccurrence)
         RETURN oc.name AS label, count(oc) AS count
         ORDER BY count DESC LIMIT 15`,
      ),
 
      query<{ label: string; count: number }>(
        `MATCH (od:OMOPDrugExposure)
         RETURN od.name AS label, count(od) AS count
         ORDER BY count DESC LIMIT 15`,
      ),
 
      query<{ label: string; count: number }>(
        `MATCH (om:OMOPMeasurement)
         RETURN om.name AS label, count(om) AS count
         ORDER BY count DESC LIMIT 15`,
      ),
 
      query<{ label: string; count: number }>(
        `MATCH (opo:OMOPProcedureOccurrence)
         RETURN opo.name AS label, count(opo) AS count
         ORDER BY count DESC LIMIT 15`,
      ),
 
      query<{ gender: string; count: number }>(
        `MATCH (op:OMOPPerson)
         RETURN CASE op.genderConceptId
                  WHEN 8507 THEN 'Male'
                  WHEN 8532 THEN 'Female'
                  ELSE 'Unknown'
                END AS gender,
                count(op) AS count
         ORDER BY count DESC`,
      ),
    ]);
 
    return NextResponse.json({
      summary: summary[0] ?? {
        persons: 0,
        conditions: 0,
        drugs: 0,
        measurements: 0,
        procedures: 0,
        visits: 0,
      },
      topConditions,
      topDrugs,
      topMeasurements,
      topProcedures,
      genderBreakdown,
      permit,
    });
  } catch (err) {
    console.error("GET /api/analytics error:", err);
    return NextResponse.json({ error: "Neo4j unavailable" }, { status: 502 });
  }
}