This commit is contained in:
nisha.meshram 2026-09-02 11:57:36 +00:00
parent cbc4ac186e
commit 29a1f73b8a

View File

@ -0,0 +1,170 @@
/**
* Dashboard page logic.
* Reads ?session=<id> (set by the backend after a successful OAuth2 token exchange),
* calls GET /api/smart/dashboard?session=<id>, 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 logoutBtn = el("logout-btn");
logoutBtn.addEventListener("click", () => {
// Full page navigation (not fetch) — sends the browser back through
// Medplum's own login/authorize screen, same as SmartController.Login().
window.location.href = `${window.APP_CONFIG.apiBaseUrl}/login`;
});
function showError(message) {
loading.classList.add("hidden");
errorState.textContent = message;
errorState.classList.remove("hidden");
}
if (!sessionId) {
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 — falls back to the Patient ID when Medplum has no name
// on file for this patient (data.patient.name is "Unknown Patient" in
// that case), since showing the id is more useful than that label.
const chipName = data.patient.name && data.patient.name !== "Unknown Patient"
? data.patient.name
: `Patient ${data.patient.id}`;
patientChip.textContent = `${chipName} · ${data.patient.gender ?? "—"} · Age ${data.patient.age ?? "—"}`;
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 renderPatient(p) {
el("patient-summary").innerHTML = `
<div class="kv"><span>Name</span><strong>${escapeHtml(p.name)}</strong></div>
<div class="kv"><span>Patient ID</span><strong>${escapeHtml(p.id)}</strong></div>
<div class="kv"><span>Gender</span><strong>${escapeHtml(p.gender ?? "—")}</strong></div>
<div class="kv"><span>Birth date</span><strong>${escapeHtml(p.birthDate ?? "—")}</strong></div>
<div class="kv"><span>Age</span><strong>${p.age ?? "—"}</strong></div>
<div class="kv"><span>Identifier</span><strong>${escapeHtml(p.mrnOrIdentifier ?? "—")}</strong></div>
`;
}
function renderRisk(risk) {
const levelClass = risk.level === "High" ? "risk-high" : risk.level === "Medium" ? "risk-medium" : "risk-low";
const ringColor = risk.level === "High" ? "var(--high)" : risk.level === "Medium" ? "var(--medium)" : "var(--low)";
const pct = Math.max(0, Math.min(100, Number(risk.score) || 0));
el("risk-summary").innerHTML = `
<div class="risk-score ${levelClass}">
<div class="risk-ring" style="--pct:${pct}; --ring-color:${ringColor}">
<div class="risk-ring-inner"><div class="risk-number">${risk.score}</div></div>
</div>
<div class="risk-level">${risk.level} risk</div>
</div>
<ul class="risk-factors">
${risk.factors.map((f) => `<li>${escapeHtml(f)}</li>`).join("")}
</ul>
`;
}
function renderList(containerId, items, itemRenderer, emptyText) {
const container = el(containerId);
if (!items || items.length === 0) {
container.innerHTML = `<p class="empty">${emptyText}</p>`;
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 `<div class="list-item alert-item">
<span class="badge ${cls}">${escapeHtml(a.severity)}</span>
<span>${escapeHtml(a.detail)}</span>
</div>`;
}
function renderConditionItem(c) {
return `<div class="list-item">
<strong>${escapeHtml(c.display)}</strong>
<div class="muted">${escapeHtml(c.clinicalStatus ?? "")} ${c.severity ? "· " + escapeHtml(c.severity) : ""} ${c.onsetDate ? "· onset " + escapeHtml(c.onsetDate) : ""}</div>
</div>`;
}
function renderMedicationItem(m) {
return `<div class="list-item">
<strong>${escapeHtml(m.display)}</strong>
<div class="muted">${escapeHtml(m.status ?? "")} ${m.dosage ? "· " + escapeHtml(m.dosage) : ""}</div>
</div>`;
}
function renderObservationItem(o) {
return `<div class="list-item ${o.isAbnormal ? "abnormal" : ""}">
<strong>${escapeHtml(o.display)}</strong>
<div class="muted">${escapeHtml(o.valueText ?? "—")} ${o.referenceRangeText ? "· ref " + escapeHtml(o.referenceRangeText) : ""} ${o.isAbnormal ? "· <span class=\"flag\">ABNORMAL</span>" : ""}</div>
</div>`;
}
function renderAllergyItem(a) {
return `<div class="list-item">
<strong>${escapeHtml(a.display)}</strong>
<div class="muted">${escapeHtml(a.criticality ?? "")}</div>
</div>`;
}
function renderCarePlanItem(cp) {
return `<div class="list-item">
<strong>${escapeHtml(cp.title)}</strong>
<div class="muted">${escapeHtml(cp.status ?? "")}</div>
${cp.activities && cp.activities.length ? `<ul>${cp.activities.map((a) => `<li>${escapeHtml(a)}</li>`).join("")}</ul>` : ""}
</div>`;
}
function renderRiskAssessmentItem(r) {
return `<div class="list-item">
<strong>${escapeHtml(r.prediction ?? r.method ?? "Risk Assessment")}</strong>
<div class="muted">${r.probabilityPercent != null ? r.probabilityPercent.toFixed(0) + "%" : ""} ${r.date ? "· " + escapeHtml(r.date) : ""}</div>
</div>`;
}
function escapeHtml(str) {
if (str === null || str === undefined) return "";
return String(str)
.replace(/&/g, "&amp;")
.replace(/</g, "&lt;")
.replace(/>/g, "&gt;")
.replace(/"/g, "&quot;");
}
})();