All files / src/app/api/patient/insights route.ts

100% Statements 14/14
100% Branches 12/12
100% Functions 1/1
100% Lines 12/12

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                  2x                                 13x 13x   11x 11x   11x 10x 10x     10x                                                                                                                           10x                                                 13x   13x                                  
import { NextResponse } from "next/server";
import { runQuery } from "@/lib/neo4j";
import { requireAuth, isAuthError } from "@/lib/auth-guard";
import { refuseForeignRecord } from "@/lib/patient/own-record";
import {
  recommendationsFor,
  type PatientCondition,
} from "@/lib/patient/recommendations";
 
export const dynamic = "force-dynamic";
 
/**
 * GET /api/patient/insights?patientId=<id>
 *
 * Patients receive anonymised aggregate findings from studies their data
 * went into (EHDS Art. 58(1)(g); results leave the SPE only as
 * non-personal data, Art. 73). Never returns pseudonym IDs or
 * individual-level results (k-anonymity enforced by SPE).
 *
 * Returns:
 *  - Active donations (studies currently using patient's data)
 *  - Aggregate findings from completed studies
 *  - Recommendations chosen by the patient's own conditions, or one general
 *    recommendation when none matches (no patientId: the general one)
 */
export async function GET(req: Request) {
  const auth = await requireAuth(["PATIENT", "EDC_ADMIN"]);
  if (isAuthError(auth)) return auth;
 
  const { searchParams } = new URL(req.url);
  const patientId = searchParams.get("patientId");
  // A patient reads their own consents only (#475).
  if (patientId) {
    const foreign = await refuseForeignRecord(auth.session.roles, patientId);
    if (foreign) return foreign;
  }
 
  const [consentRows, insightRows, speRows, conditionRows] = await Promise.all([
    // Patient's active consents → studies using their data
    patientId
      ? runQuery<{
          studyId: string;
          studyName: string;
          grantedAt: string;
          status: string;
        }>(
          `MATCH (pc:PatientConsent {patientId: $patientId, revoked: false})
           OPTIONAL MATCH (pc)-[:FOR_STUDY]->(dp:DataProduct)
           RETURN pc.studyId AS studyId,
                  coalesce(dp.name, pc.studyId, 'Research Study') AS studyName,
                  toString(pc.grantedAt) AS grantedAt,
                  coalesce(dp.status, 'active') AS status`,
          { patientId },
        )
      : Promise.resolve([]),
 
    // Research insights from neo4j (seeded aggregate findings)
    runQuery<{
      insightId: string;
      studyId: string;
      finding: string;
      relevantConditions: string[];
      recommendation: string;
      evidenceLevel: string;
    }>(
      `MATCH (ri:ResearchInsight)
       RETURN ri.insightId AS insightId,
              ri.studyId AS studyId,
              ri.finding AS finding,
              coalesce(ri.relevantConditions, []) AS relevantConditions,
              coalesce(ri.recommendation, '') AS recommendation,
              coalesce(ri.evidenceLevel, 'moderate') AS evidenceLevel
       ORDER BY ri.studyId
       LIMIT 10`,
    ),
 
    // SPE sessions (anonymised — only aggregate stats shown to patient)
    runQuery<{ studyId: string; outputPolicy: string; status: string }>(
      `MATCH (ss:SPESession)
       RETURN ss.studyId AS studyId,
              coalesce(ss.outputPolicy, 'aggregate-only') AS outputPolicy,
              coalesce(ss.status, 'active') AS status
       LIMIT 5`,
    ),
 
    // The patient's conditions, which choose the recommendations below
    patientId
      ? runQuery<PatientCondition>(
          `MATCH (p:Patient)-[:HAS_CONDITION]->(c:Condition)
           WHERE coalesce(p.id, p.resourceId, elementId(p)) = $patientId
           RETURN coalesce(c.code, '') AS code,
                  coalesce(c.display, '') AS display`,
          { patientId },
        )
      : Promise.resolve([]),
  ]);
 
  // Merge seeded insights with demo insights (for empty-graph fallback)
  const allInsights =
    insightRows.length > 0
      ? insightRows
      : [
          {
            insightId: "demo-insight-001",
            studyId: "study-diabetes-de-nl-2025",
            finding:
              "Patients with Type 2 Diabetes on Metformin showed 18% lower cardiovascular event rate compared to non-treated cohort (n=1,240, p<0.01)",
            relevantConditions: ["E11.9", "I10", "44054006"],
            recommendation:
              "Discuss cardiovascular screening schedule and Metformin continuation with your physician",
            evidenceLevel: "high",
          },
          {
            insightId: "demo-insight-002",
            studyId: "study-cardio-nl-2025",
            finding:
              "Regular HbA1c monitoring (≥2×/year) correlated with 22% reduction in hospitalisation risk in the NL cohort",
            relevantConditions: ["E11", "4548-4"],
            recommendation: "Ensure bi-annual HbA1c tests are scheduled",
            evidenceLevel: "moderate",
          },
        ];
 
  // Only what the patient's own conditions call for, never one list for all
  const recommendations = recommendationsFor(conditionRows);
 
  return NextResponse.json({
    patientId,
    activeDonations: consentRows.length,
    activeStudies: speRows.length,
    donatedStudies: consentRows,
    findings: allInsights,
    recommendations,
    privacyNote:
      "All findings are aggregate results (k ≥ 5). Your individual data is never shared with researchers — only pseudonymised summaries reach the Secure Processing Environment.",
    ehdsArticles: {
      primaryAccess: "EHDS Art. 3",
      secondaryConsent:
        "EHDS Art. 71 — secondary use is the default, with an opt-out; joining a study is a separate GDPR consent",
      speProtection: "EHDS Art. 73",
    },
  });
}