/** * Dashboard page logic. * Reads ?session= (set by the backend after a successful OAuth2 token exchange), * calls GET /api/smart/dashboard?session=, and renders the single launched patient's data. * The browser never sees the FHIR access token - only this opaque session id. */ (async function () { const params = new URLSearchParams(window.location.search); const sessionId = params.get("session"); const el = (id) => document.getElementById(id); const loading = el("loading"); const errorState = el("error-state"); const dashboard = el("dashboard"); const patientChip = el("patient-chip"); const patientAvatar = el("patient-avatar"); const patientChipText = el("patient-chip-text"); const logoutBtn = el("logout-btn"); logoutBtn.addEventListener("click", async () => { logoutBtn.disabled = true; logoutBtn.textContent = "Logging out…"; try { await fetch(`${window.APP_CONFIG.apiBaseUrl}/logout?session=${encodeURIComponent(sessionId)}`, { method: "POST" }); } catch (err) { // Even if the network call fails, still forward to Medplum below - the // local session reference is gone from the URL either way. } // launch.html requires ?iss=&launch= (a real EHR launch context), which // we don't have here, so it would just show an error instead of reaching // Medplum. /login is the same redirect launch.html's own fallback link // uses, and takes the browser straight to Medplum's authorize screen. window.location.href = `${window.APP_CONFIG.apiBaseUrl}/login`; }); function showError(message) { loading.classList.add("hidden"); errorState.textContent = message; errorState.classList.remove("hidden"); } if (!sessionId) { // Common misconfiguration: the EHR's "Launch URI" points at index.html instead of // launch.html, so we land here with ?iss=..&launch=.. instead of ?session=.. // Forward to the real launch entry point rather than dead-ending on an error. const iss = params.get("iss"); const launch = params.get("launch"); if (iss && launch) { window.location.replace(`launch.html?iss=${encodeURIComponent(iss)}&launch=${encodeURIComponent(launch)}`); return; } showError("No active session. Please launch this app from a patient chart in Medplum."); return; } try { const res = await fetch(`${window.APP_CONFIG.apiBaseUrl}/dashboard?session=${encodeURIComponent(sessionId)}`); const data = await res.json(); if (!res.ok) { showError(data.error || "Failed to load patient dashboard."); return; } render(data); } catch (err) { showError("Could not reach the backend API. Is it running at " + window.APP_CONFIG.apiBaseUrl + "?"); } function render(data) { loading.classList.add("hidden"); dashboard.classList.remove("hidden"); // Header chip - only include parts we actually have, so missing FHIR fields // (common on local/test servers) don't show as a string of "—" placeholders. // "Unknown Patient" is the backend's fallback when Medplum has no name on // file for this patient (see FhirBundleMapper.MapPatient) — showing the // Patient ID instead is more useful than that generic label. const displayName = data.patient.name && data.patient.name !== "Unknown Patient" ? data.patient.name : `Patient ${data.patient.id}`; const chipParts = [displayName]; if (data.patient.gender) chipParts.push(data.patient.gender); if (data.patient.age != null) chipParts.push(`Age ${data.patient.age}`); patientChipText.textContent = chipParts.join(" · "); patientAvatar.textContent = initials(data.patient.name); patientChip.classList.remove("hidden"); logoutBtn.classList.remove("hidden"); renderPatient(data.patient); renderRisk(data.computedRisk); renderList("cds-alerts", data.cdsAlerts, renderAlertItem, "No open CDS alerts for this patient."); renderList("conditions", data.conditions, renderConditionItem, "No recorded conditions."); renderList("medications", data.medicationRequests, renderMedicationItem, "No active medications."); renderList("observations", data.observations, renderObservationItem, "No observations found."); renderList("allergies", data.allergies, renderAllergyItem, "No known allergies recorded."); renderList("careplans", data.carePlans, renderCarePlanItem, "No care plans found."); renderList("riskassessments", data.riskAssessments, renderRiskAssessmentItem, "No prior RiskAssessment resources on file."); } function initials(name) { if (!name) return "?"; const parts = name.trim().split(/\s+/).filter(Boolean); if (parts.length === 0) return "?"; return (parts[0][0] + (parts.length > 1 ? parts[parts.length - 1][0] : "")).toUpperCase(); } function renderPatient(p) { el("patient-summary").innerHTML = `
Name${escapeHtml(p.name)}
Patient ID${escapeHtml(p.id)}
Gender${escapeHtml(p.gender ?? "—")}
Birth date${escapeHtml(p.birthDate ?? "—")}
Age${p.age ?? "—"}
Identifier${escapeHtml(p.mrnOrIdentifier ?? "—")}
`; } function renderRisk(risk) { const levelClass = risk.level === "High" ? "risk-high" : risk.level === "Medium" ? "risk-medium" : "risk-low"; const pct = Math.max(0, Math.min(100, risk.score)); el("risk-summary").innerHTML = `
${risk.score}
${escapeHtml(risk.level)} risk
`; } function renderList(containerId, items, itemRenderer, emptyText) { const container = el(containerId); if (!items || items.length === 0) { container.innerHTML = `

${emptyText}

`; return; } container.innerHTML = items.map(itemRenderer).join(""); } function renderAlertItem(a) { const cls = a.severity === "high" ? "badge-high" : a.severity === "low" ? "badge-low" : "badge-medium"; return `
${escapeHtml(a.severity)} ${escapeHtml(a.detail)}
`; } function renderConditionItem(c) { return `
${escapeHtml(c.display)}
${escapeHtml(c.clinicalStatus ?? "")} ${c.severity ? "· " + escapeHtml(c.severity) : ""} ${c.onsetDate ? "· onset " + escapeHtml(c.onsetDate) : ""}
`; } function renderMedicationItem(m) { return `
${escapeHtml(m.display)}
${escapeHtml(m.status ?? "")} ${m.dosage ? "· " + escapeHtml(m.dosage) : ""}
`; } function renderObservationItem(o) { return `
${escapeHtml(o.display)}
${escapeHtml(o.valueText ?? "—")} ${o.referenceRangeText ? "· ref " + escapeHtml(o.referenceRangeText) : ""} ${o.isAbnormal ? "· ABNORMAL" : ""}
`; } function renderAllergyItem(a) { return `
${escapeHtml(a.display)}
${escapeHtml(a.criticality ?? "")}
`; } function renderCarePlanItem(cp) { return `
${escapeHtml(cp.title)}
${escapeHtml(cp.status ?? "")}
${cp.activities && cp.activities.length ? `
    ${cp.activities.map((a) => `
  • ${escapeHtml(a)}
  • `).join("")}
` : ""}
`; } function renderRiskAssessmentItem(r) { return `
${escapeHtml(r.prediction ?? r.method ?? "Risk Assessment")}
${r.probabilityPercent != null ? r.probabilityPercent.toFixed(0) + "%" : ""} ${r.date ? "· " + escapeHtml(r.date) : ""}
`; } function escapeHtml(str) { if (str === null || str === undefined) return ""; return String(str) .replace(/&/g, "&") .replace(//g, ">") .replace(/"/g, """); } })();