diff --git a/VigilCareClinicalAPI.Tests/AlertLifecycleTests.cs b/VigilCareClinicalAPI.Tests/AlertLifecycleTests.cs index 2165831..178524c 100644 --- a/VigilCareClinicalAPI.Tests/AlertLifecycleTests.cs +++ b/VigilCareClinicalAPI.Tests/AlertLifecycleTests.cs @@ -64,7 +64,7 @@ public class AlertLifecycleTests : IAsyncLifetime body!.RootElement.GetProperty("data").GetProperty("status").GetString() .Should().Be("Acknowledged"); body.RootElement.GetProperty("data").GetProperty("acknowledgedBy").GetString() - .Should().Be("Test NURSE"); + .Should().Be("Test NURSE (NURSE)"); } [Fact] diff --git a/VigilCareClinicalAPI.Tests/GapAnalysisFixTests.cs b/VigilCareClinicalAPI.Tests/GapAnalysisFixTests.cs index fce93dd..0eb768e 100644 --- a/VigilCareClinicalAPI.Tests/GapAnalysisFixTests.cs +++ b/VigilCareClinicalAPI.Tests/GapAnalysisFixTests.cs @@ -274,8 +274,14 @@ public class GapAnalysisFixTests : IAsyncLifetime var data = resp.GetProperty("data"); data.GetProperty("totalCount").GetInt32().Should().BeGreaterThanOrEqualTo(1); - data.GetProperty("items").EnumerateArray().Should().Contain(b => - b.GetProperty("complianceStatus").GetString() == "IN_PROGRESS"); + var bundle = data.GetProperty("items").EnumerateArray() + .First(b => b.GetProperty("encounterId").GetGuid() == encounter.Id); + bundle.GetProperty("complianceStatus").GetString().Should().Be("IN_PROGRESS"); + bundle.GetProperty("firstName").GetString().Should().Be("List"); + bundle.GetProperty("lastName").GetString().Should().Be("Test"); + bundle.GetProperty("mrn").GetString().Should().Be("MRN-LIST-001"); + bundle.GetProperty("department").GetString().Should().Be("Icu"); + bundle.GetProperty("elements").EnumerateArray().Should().HaveCount(4); } // ------------------------------------------------------------------------- diff --git a/VigilCareClinicalAPI/Models/Records/Sepsis/SepsisBundleSummary.cs b/VigilCareClinicalAPI/Models/Records/Sepsis/SepsisBundleSummary.cs new file mode 100644 index 0000000..bfbd7d9 --- /dev/null +++ b/VigilCareClinicalAPI/Models/Records/Sepsis/SepsisBundleSummary.cs @@ -0,0 +1,20 @@ +public record SepsisBundleElementSummary( + Guid Id, + SepsisBundleElementType ElementType, + SepsisBundleElementStatus Status, + DateTimeOffset? CompletedAt); + +public record SepsisBundleSummary( + Guid Id, + Guid EncounterId, + string Mrn, + string FirstName, + string LastName, + string? RoomBed, + Department Department, + string TriggeringAlertType, + DateTimeOffset RecognizedAt, + DateTimeOffset DeadlineAt, + SepsisBundleComplianceStatus ComplianceStatus, + DateTimeOffset? CompletedAt, + IReadOnlyList Elements); diff --git a/VigilCareClinicalAPI/Services/AlertService.cs b/VigilCareClinicalAPI/Services/AlertService.cs index 267136b..5acc2a9 100644 --- a/VigilCareClinicalAPI/Services/AlertService.cs +++ b/VigilCareClinicalAPI/Services/AlertService.cs @@ -98,10 +98,14 @@ public class AlertService : IAlertService $"Alert cannot be acknowledged from status '{alert.Status}'.", "ALERT_NOT_ACKNOWLEDGEABLE"); + var roleLabel = _currentUser.Role?.ToDbString() ?? "UNKNOWN"; + var userId = _currentUser.UserId; + var acknowledgmentNote = FormatAcknowledgmentNote(roleLabel, displayName, req.Note); + var previousStatus = alert.Status; alert.Status = AlertStatus.Acknowledged; alert.AcknowledgedAt = DateTimeOffset.UtcNow; - alert.AcknowledgedBy = displayName; + alert.AcknowledgedBy = $"{displayName} ({roleLabel})"; // Write an outbox event so the Kafka consumer (Phase 6) can cancel the // pending RabbitMQ escalation timer when it sees this acknowledgment. @@ -113,9 +117,11 @@ public class AlertService : IAlertService { alertId = alert.Id, encounterId = alert.EncounterId, - acknowledgedBy = displayName, + acknowledgedBy = alert.AcknowledgedBy, + userId, + role = roleLabel, acknowledgedAt = alert.AcknowledgedAt, - note = req.Note + note = acknowledgmentNote }), PartitionKey = alert.EncounterId.ToString(), CreatedAt = DateTimeOffset.UtcNow @@ -141,8 +147,8 @@ public class AlertService : IAlertService "ClinicalAlert", alert.Id, previousValue: new { status = previousStatus.ToDbString() }, - newValue: new { status = alert.Status.ToDbString(), alert.AcknowledgedBy }, - reason: req.Note); + newValue: new { status = alert.Status.ToDbString(), alert.AcknowledgedBy, role = roleLabel, userId }, + reason: acknowledgmentNote); if (alert.AlertType.IsSuppressible()) { @@ -151,7 +157,7 @@ public class AlertService : IAlertService "ClinicalAlert", alert.Id, newValue: new { alert.AlertType, alert.EncounterId }, - reason: req.Note); + reason: acknowledgmentNote); } return alert; @@ -244,4 +250,10 @@ public class AlertService : IAlertService alert.ResolvedAt = resolve.ResolvedAt; await _db.SaveChangesAsync(ct); } + + private static string FormatAcknowledgmentNote(string roleLabel, string displayName, string? note) + { + var prefix = $"[{roleLabel}] Acknowledged by {displayName}."; + return string.IsNullOrWhiteSpace(note) ? prefix : $"{prefix} {note.Trim()}"; + } } \ No newline at end of file diff --git a/VigilCareClinicalAPI/Services/Interfaces/ISepsisBundleService.cs b/VigilCareClinicalAPI/Services/Interfaces/ISepsisBundleService.cs index d03b1a8..ac73b2d 100644 --- a/VigilCareClinicalAPI/Services/Interfaces/ISepsisBundleService.cs +++ b/VigilCareClinicalAPI/Services/Interfaces/ISepsisBundleService.cs @@ -4,6 +4,6 @@ public interface ISepsisBundleService Guid encounterId, Guid triggeringAlertId, AlertType alertType, CancellationToken ct = default); Task GetCurrentByEncounterAsync(Guid encounterId); Task GetByIdAsync(Guid id); - Task> ListAsync(SepsisBundleComplianceStatus? status, int page, int pageSize); + Task> ListAsync(SepsisBundleComplianceStatus? status, int page, int pageSize); Task OnOrderResultedAsync(Guid orderId, CancellationToken ct = default); } \ No newline at end of file diff --git a/VigilCareClinicalAPI/Services/SepsisBundleService.cs b/VigilCareClinicalAPI/Services/SepsisBundleService.cs index f661e55..63466e9 100644 --- a/VigilCareClinicalAPI/Services/SepsisBundleService.cs +++ b/VigilCareClinicalAPI/Services/SepsisBundleService.cs @@ -124,7 +124,7 @@ public class SepsisBundleService : ISepsisBundleService return bundle; } - public async Task> ListAsync( + public async Task> ListAsync( SepsisBundleComplianceStatus? status, int page, int pageSize) { pageSize = Math.Clamp(pageSize, 1, 100); @@ -132,19 +132,39 @@ public class SepsisBundleService : ISepsisBundleService var query = _db.SepsisBundles .AsNoTracking() .Include(b => b.Elements) + .Include(b => b.Encounter) + .ThenInclude(e => e.Patient) .AsQueryable(); if (status.HasValue) query = query.Where(b => b.ComplianceStatus == status.Value); var total = await query.CountAsync(); - var items = await query + var bundles = await query .OrderByDescending(b => b.RecognizedAt) .Skip((page - 1) * pageSize) .Take(pageSize) .ToListAsync(); - return new PagedResult(items, page, pageSize, total); + var items = bundles.Select(b => new SepsisBundleSummary( + b.Id, + b.EncounterId, + b.Encounter.Patient.Mrn, + b.Encounter.Patient.FirstName, + b.Encounter.Patient.LastName, + b.Encounter.RoomBed, + b.Encounter.Department, + b.TriggeringAlertType, + b.RecognizedAt, + b.DeadlineAt, + b.ComplianceStatus, + b.CompletedAt, + b.Elements + .Select(e => new SepsisBundleElementSummary(e.Id, e.ElementType, e.Status, e.CompletedAt)) + .ToList())) + .ToList(); + + return new PagedResult(items, page, pageSize, total); } public async Task OnOrderResultedAsync(Guid orderId, CancellationToken ct = default) diff --git a/docs/vigilcare-clinical-api-prd.md b/docs/vigilcare-clinical-api-prd.md index 0e212bc..a624060 100644 --- a/docs/vigilcare-clinical-api-prd.md +++ b/docs/vigilcare-clinical-api-prd.md @@ -2,13 +2,13 @@ ## Overview -A production-style clinical backend that models patient encounters, continuous observation ingest, and real-time clinical alerting. The system streams vital signs and lab results through Kafka, fans urgent notifications to clinicians through RabbitMQ, and maintains a searchable CQRS projection in Elasticsearch for patient dashboards and population analytics. Long-term data is archived as Parquet files in an S3-compatible object store — a regulatory requirement in healthcare that has no equivalent in most other domains. +A production-quality clinical backend built with ASP.NET Core 8, PostgreSQL, Apache Kafka, RabbitMQ, Elasticsearch, Redis, and MinIO. The system models patient encounters, continuous observation ingest, and real-time clinical alerting with composite scoring engines (NEWS2, GCS, SOFA), Sepsis-3 two-tier detection (qSOFA screening → SOFA confirmation → treatment bundle), trend analysis, and alert suppression. It streams vital signs and lab results through Kafka, fans urgent notifications to clinicians through RabbitMQ with DLQ-based escalation, and maintains a searchable CQRS projection in Elasticsearch for ward dashboards and population analytics. A Vue 3 ward dashboard provides real-time clinical views. Ward gateway edge nodes buffer observations locally during connectivity loss. A FHIR R4 facade enables EHR integration. JWT-based RBAC with clinical audit logging gates every endpoint. Long-term data is archived as Parquet files in MinIO — a regulatory requirement in healthcare that has no equivalent in most other domains. Twenty-nine phases are implemented and verified. The domain is deliberately different from the Digital Wallet API. Both projects use Kafka, RabbitMQ, and Elasticsearch, but the trade-off conversations are entirely different. In fintech the core question is "did the money move correctly?" In healthcare the core question is "did the right person get the right alert at the right time?" That distinction — correctness vs timeliness — produces different architectural decisions at every layer. This project maps to `sd-mid-009` (Outbox Pattern), `sd-mid-013` (CQRS), `sd-mid-043–048` (Kafka internals), `sd-senior-008` (Real-Time Event Processing), and `sd-senior-011` (Anomaly Detection in Streams). -**Stack:** .NET 8 Web API, PostgreSQL, Apache Kafka (KRaft), RabbitMQ, Elasticsearch, Redis, MinIO (Parquet archival), Serilog → Seq, Prometheus → Grafana, xUnit, Docker Compose. +**Stack:** .NET 8 Web API, PostgreSQL, Apache Kafka (KRaft), RabbitMQ, Elasticsearch, Redis, MinIO (Parquet archival), Serilog → Seq, Prometheus → Grafana, Vue 3 + Vite + Pinia + Tailwind CSS + Chart.js, Hl7.Fhir.R4 (Firely SDK), JWT + BCrypt, FluentValidation, xUnit + Testcontainers, Docker Compose. --- @@ -36,14 +36,19 @@ docker compose up -d - Model the observe-alert-acknowledge lifecycle that sits at the center of any clinical monitoring system - Demonstrate Kafka's multi-consumer log model in a healthcare context where the same observation event must reach the alert engine, the Elasticsearch projection, and the data lake independently - Show RabbitMQ's DLQ pattern as a clinical escalation mechanism — if a critical alert is not acknowledged in five minutes, the message routes through a dead-letter queue and re-delivers as an escalation to the on-call physician -- Build a stateful Kafka consumer that detects sepsis early warning signs by maintaining rolling windows of recent observations per patient in Redis +- Build stateful Kafka consumers that detect sepsis (qSOFA/SOFA), compute composite scores (NEWS2, GCS), and track trends by maintaining rolling windows of recent observations per patient in Redis +- Implement a two-tier sepsis detection pathway (Sepsis-3: qSOFA screen → SOFA confirmation → treatment bundle) that demonstrates clinical workflow automation +- Provide a Vue 3 ward dashboard with real-time clinical views, scoring history charts, and clinician feedback collection +- Enable EHR integration via a FHIR R4 inbound facade with LOINC/SNOMED code mapping +- Support edge deployment via ward gateway nodes with offline buffering and central sync +- Secure all endpoints with JWT-based RBAC and maintain an append-only clinical audit trail - Produce a project that supports senior trade-off conversations in healthcare, medtech, and any domain where real-time alerting and long-term archival coexist ## Non-Goals -- HL7 FHIR compliance (reference the standard; do not implement it) +- ~~HL7 FHIR compliance~~ → **Implemented in Phase 30** — FHIR R4 inbound facade with LOINC/SNOMED code mapping, transaction Bundles, and read/search endpoints; Mirth Connect integration guide - Integration with real medical devices or lab information systems -- Medication dispensing or pharmacy workflows +- ~~Medication dispensing or pharmacy workflows~~ → **Partially addressed in Phase 15** — medication administration recording with drug-vital correlation annotations on alerts - Patient billing or insurance claim adjudication - HIPAA-compliant deployment (model the patterns; don't configure real PHI) @@ -56,7 +61,7 @@ This is the same architectural question as the Digital Wallet — but the health **Kafka** is an append-only log. Every observation recorded by a bedside monitor, every lab result that arrives from the lab information system, is written to a Kafka topic and retained. Multiple independent consumer groups read the same observation stream at their own pace: - The Elasticsearch indexer maintains a searchable patient dashboard -- The sepsis detection engine analyzes rolling windows for SIRS criteria +- The sepsis detection engine analyzes rolling windows for qSOFA/SOFA criteria (Sepsis-3) - The data lake writer archives observations as Parquet for long-term regulatory retention - A future billing consumer could derive charges from observation codes without touching the operational database @@ -247,11 +252,16 @@ open → acknowledged → resolved | Topic | Producer | Consumers | |---|---|---| -| `observation.recorded` | Outbox relay | Elasticsearch indexer, Sepsis engine, Data lake writer | -| `alert.generated` | Outbox relay | Elasticsearch indexer, Notification worker, Data lake writer | -| `encounter.status.changed` | Outbox relay | Elasticsearch indexer, Data lake writer | +| `observation.recorded` | Outbox relay | `es-indexer`, `sepsis-engine` (qSOFA), `warning-evaluator`, `news2-scoring`, `gcs-scoring`, `sofa-scoring`, `trend-analyzer`, `data-lake-writer` | +| `alert.generated` | Outbox relay | `es-indexer`, `notification-publisher`, `data-lake-writer` | +| `encounter.status.changed` | Outbox relay | `es-indexer`, `data-lake-writer` | +| `gcs.scored` | Outbox relay (via GcsDetector) | `sofa-scoring` (CNS organ-system re-scoring) | +| `sepsis.bundle.created` | Outbox relay | `es-indexer` | +| `sepsis.bundle.updated` | Outbox relay | `es-indexer` | -**Partition key:** `encounter_id` for `observation.recorded` and `alert.generated`. All events for the same encounter land on the same partition, preserving per-encounter ordering. This is important for the sepsis engine: observations for the same patient must be processed in arrival order. +All topics use 6 partitions. `KAFKA_AUTO_CREATE_TOPICS_ENABLE=false` — topics are provisioned explicitly by `KafkaTopicProvisioner`. + +**Partition key:** `encounter_id` for all topics. All events for the same encounter land on the same partition, preserving per-encounter ordering. This is important for the sepsis engine: observations for the same patient must be processed in arrival order. **Consumer group isolation:** `es-indexer`, `sepsis-engine`, and `data-lake-writer` are separate consumer groups. Each maintains its own committed offset. The sepsis engine processing slowly does not affect the Elasticsearch indexer. @@ -308,43 +318,50 @@ open → acknowledged → resolved --- -### 7. Sepsis Early Warning Engine +### 7. Sepsis Detection Engine (Sepsis-3: qSOFA Screen → SOFA Confirmation) -**Description:** A Kafka consumer that reads the `observation.recorded` stream and detects SIRS (Systemic Inflammatory Response Syndrome) criteria per patient in near real-time. SIRS is a simplified clinical proxy for sepsis risk — when two or more criteria are met simultaneously, a `SEPSIS_WARNING` alert is generated. State is maintained in Redis as a rolling window of recent observations per encounter. +**Description:** A two-tier sepsis detection pathway following the Sepsis-3 consensus (2016), replacing the original SIRS-based approach. The first tier is a bedside qSOFA screening engine (`SepsisEngineService`) that evaluates three organ-dysfunction criteria per patient in near real-time. The second tier is the SOFA organ-dysfunction scoring engine (`SofaScoringService`) that confirms sepsis and triggers the treatment bundle. State is maintained in Redis as rolling windows of recent observations per encounter. -**SIRS criteria (simplified for this project):** +> **Historical note:** The original PRD specified SIRS criteria (temperature, heart rate, respiratory rate, WBC). Phase 27 replaced SIRS with qSOFA/SOFA per Sepsis-3 consensus — SIRS criteria were too non-specific, triggering bundles for post-surgical inflammation, anxiety, and viral infections. The legacy `SEPSIS_WARNING` alert type is retained `[Obsolete]` for historical queries but can no longer be created. + +**Tier 1 — qSOFA screening criteria:** | Criterion | Observation Code | Trigger | |---|---|---| -| Fever or hypothermia | `TEMP_C` | > 38.3°C or < 36.0°C | -| Tachycardia | `HEART_RATE` | > 90 bpm | -| Tachypnea | `RESP_RATE` | > 20 breaths/min | -| Abnormal WBC | `WBC_K_UL` | > 12.0 or < 4.0 k/µL | +| Tachypnea | `RESP_RATE` | ≥ 22 breaths/min | +| Hypotension | `SYSTOLIC_BP` | ≤ 100 mmHg | +| Altered mentation | `GCS` / `AVPU` | GCS < 15 or AVPU ≥ 1 | -**Redis state per encounter:** +**Redis state per encounter (qSOFA):** ``` -sirs:{encounterId}:TEMP_C → "1" (TTL: 30 minutes) -sirs:{encounterId}:HEART_RATE → "1" (TTL: 30 minutes) -sirs:{encounterId}:RESP_RATE → "1" (TTL: 30 minutes) -sirs:{encounterId}:WBC_K_UL → "1" (TTL: 30 minutes) +qsofa:{encounterId}:RESP_RATE → "1" (TTL: 30 minutes) +qsofa:{encounterId}:SYSTOLIC_BP → "1" (TTL: 30 minutes) +qsofa:{encounterId}:MENTATION → "1" (TTL: 30 minutes) ``` -**Detection logic per observation event:** +**Tier 1 detection logic per observation event:** ``` -1. Evaluate the incoming observation against SIRS criteria -2. If criterion met: SET sirs:{encounterId}:{code} = "1" EX 1800 -3. If criterion not met: DEL sirs:{encounterId}:{code} -4. Count active SIRS keys for this encounter (KEYS pattern or MGET) -5. If count >= 2 and no open SEPSIS_WARNING alert exists for this encounter: - a. Write clinical_alert to PostgreSQL (SEPSIS_WARNING, CRITICAL) +1. Evaluate the incoming observation against qSOFA criteria +2. If criterion met: SET qsofa:{encounterId}:{code} EX 1800 +3. If criterion normalized: DEL qsofa:{encounterId}:{code} +4. MGET all three qSOFA keys for this encounter +5. Persist evaluation to qsofa_evaluations table +6. If count >= 2 and no open QSOFA_SCREEN alert exists for this encounter: + a. Write clinical_alert (QSOFA_SCREEN, WARNING) — recommends ordering SOFA labs b. Write outbox event → Kafka alert.generated ``` -**Why Redis here and not PostgreSQL:** The SIRS evaluation runs on every observation event, potentially multiple times per minute per patient. Checking "which SIRS criteria were met in the last 30 minutes" against PostgreSQL on every event would require a query against the observations table with a time range filter per encounter — under load, this creates read pressure that competes with ingest writes. Redis's O(1) key operations with TTL-based expiry are correct and fast. The TTL handles the sliding window automatically: a heart rate measurement that was abnormal 31 minutes ago stops contributing to the SIRS count without any cleanup job. +**Tier 2 — SOFA organ-dysfunction scoring:** -**Idempotency:** If the consumer crashes between detecting SIRS and committing the Kafka offset, it will re-process the same observation on restart. The alert creation query checks for an existing open `SEPSIS_WARNING` alert before inserting — a duplicate is impossible even with at-least-once delivery. +`SofaScoringService` subscribes to `observation.recorded` and `gcs.scored` Kafka topics. It scores six organ systems (respiratory, coagulation, liver, cardiovascular, CNS, renal) from Redis lab cache with carry-forward semantics. When SOFA delta ≥ 2 from baseline, a `SOFA_SEPSIS` (CRITICAL) alert fires and triggers a four-element sepsis treatment bundle via `SepsisAlertHandler` → `SepsisBundleService`. Delta = 1 creates `SOFA_WARNING`. -**Concepts practiced:** Stateful stream processing with Redis as the state store (sd-senior-011), TTL as a sliding window mechanism, idempotent alert creation, why Kafka consumer + Redis is appropriate here vs a dedicated stream processor like Flink (at the scale of a single hospital, the overhead of a full stream processing framework is not justified — this is a defensible trade-off to articulate in an interview). +**Sepsis bundle compliance (SEP-1):** On `SOFA_SEPSIS`, four treatment orders (blood cultures, serum lactate, broad-spectrum antibiotics, IV fluid resuscitation) are auto-created with a one-hour compliance deadline. As orders are resulted, bundle elements complete. `SepsisBundleMonitorService` marks overdue bundles `NON_COMPLIANT`. + +**Why Redis here and not PostgreSQL:** The qSOFA evaluation runs on every observation event, potentially multiple times per minute per patient. Redis's O(1) key operations with TTL-based expiry are correct and fast. The 30-minute TTL is a clinical parameter — a respiratory rate that was abnormal 31 minutes ago stops contributing to the qSOFA count without any cleanup job. + +**Idempotency:** Alert creation uses `INSERT WHERE NOT EXISTS` — a duplicate is impossible even with at-least-once Kafka delivery. Only one in-progress sepsis bundle can exist per encounter, enforced by a partial unique index. + +**Concepts practiced:** Stateful stream processing with Redis as the state store (sd-senior-011), TTL as a sliding window mechanism, two-tier clinical detection (screen → confirm → treat), idempotent alert creation, why Kafka consumer + Redis is appropriate here vs a dedicated stream processor like Flink (at the scale of a single hospital, the overhead of a full stream processing framework is not justified). --- @@ -355,11 +372,12 @@ sirs:{encounterId}:WBC_K_UL → "1" (TTL: 30 minutes) **Exchange topology:** ``` clinical.notifications.exchange (direct) - ├── alerts.paging.queue (physician paging, prefetch=3) - ├── alerts.paging.dlq (unacknowledged pages → escalation) - ├── alerts.escalation.queue (on-call backup paging) - ├── notifications.discharge.queue (discharge summary PDF jobs) - └── notifications.appointment.queue (appointment reminders) + ├── alerts.paging.queue (physician paging, prefetch=3) + ├── alerts.paging.dlq (unacknowledged pages → escalation, x-message-ttl=300000ms) + ├── alerts.escalation.queue (on-call backup paging) + ├── notifications.discharge.queue (discharge summary PDF → MinIO) + ├── notifications.reconciliation.queue (reconciliation safety findings) + └── notifications.appointment.queue (appointment reminder SMS) ``` **Escalation flow:** @@ -431,19 +449,37 @@ Each check creates a `reconciliation_alerts` row and publishes a job to RabbitMQ **Metrics (Prometheus → Grafana):** -| Metric | Description | -|---|---| -| `observations_ingested_total` | Counter, labeled by source and observation_code | -| `observation_ingest_duration_seconds` | Histogram of ingest latency (includes threshold evaluation) | -| `clinical_alerts_total` | Counter, labeled by alert_type and severity | -| `alerts_unacknowledged_gauge` | Gauge — open CRITICAL alerts older than 5 minutes | -| `kafka_consumer_lag` | Per consumer group (es-indexer, sepsis-engine, data-lake-writer) | -| `outbox_pending_events` | Gauge — unprocessed outbox rows | -| `sirs_detections_total` | Counter — how many SEPSIS_WARNING alerts the engine generated | -| `escalations_total` | Counter — how many pages went through DLQ escalation | +| Metric | Type | Labels | Description | +|---|---|---|---| +| `observations_ingested_total` | Counter | `observation_code`, `source` | Per committed observation | +| `observation_ingest_duration_seconds` | Histogram | — | Full ingest transaction to COMMIT | +| `clinical_alerts_total` | Counter | `alert_type`, `severity` | All alert sources (threshold, qSOFA, NEWS2, GCS, SOFA, trend, warning) | +| `alerts_unacknowledged_gauge` | Gauge | — | Open CRITICAL alerts older than 5 minutes | +| `kafka_consumer_lag` | Gauge | `consumer_group` | Per consumer group lag | +| `outbox_pending_events` | Gauge | — | Unprocessed outbox rows | +| `qsofa_detections_total` | Counter | — | Successful qSOFA SCREEN alert inserts | +| `sepsis_bundle_compliance_total` | Counter | `status` | Bundle completion (`COMPLIANT`, `NON_COMPLIANT`) | +| `news2_scores_total` | Counter | `risk_level` | Per persisted NEWS2 score | +| `news2_scoring_duration_seconds` | Histogram | — | Redis update through score persistence | +| `gcs_scores_total` | Counter | `classification` | Per persisted GCS score (`MILD`, `MODERATE`, `SEVERE`) | +| `sofa_scores_total` | Counter | `has_delta_alert` | Per persisted SOFA score | +| `sofa_scoring_duration_seconds` | Histogram | — | Full SOFA compose + persist | +| `trend_alerts_total` | Counter | `observation_code` | Per `RAPID_DETERIORATION` alert | +| `trend_analysis_duration_seconds` | Histogram | — | Per-observation trend evaluation | +| `alert_suppressions_total` | Counter | `alert_type` | Per suppression window set | +| `escalations_total` | Counter | — | DLQ escalation pages | +| `fhir_ingest_total` | Counter | `resource_type`, `outcome` | Per FHIR resource ingest | +| `fhir_read_total` | Counter | `resource_type`, `interaction`, `outcome` | Per FHIR read/search | +| `fhir_mapping_errors_total` | Counter | `resource_type` | FHIR mapping/validation failures | +| `authorization_failures_total` | Counter | `permission`, `role` | RBAC authorization denials | +| `ward_gateways_offline_gauge` | Gauge | `site_code` | Offline/degraded gateways per site | +| `ward_gateway_buffer_depth` | Gauge | `gateway_code`, `department` | Unsynced events per gateway | +| `kafka_poison_pills_skipped_total` | Counter | `consumer_group`, `topic` | Permanently un-processable messages | **The `alerts_unacknowledged_gauge` panel** is the most clinically significant metric. If this gauge rises, a nurse station monitor or alerting dashboard must surface it immediately. In a real deployment, this panel would be connected to a paging system. In the portfolio, it demonstrates that you understand which metrics have patient safety implications vs which are purely operational. +**Background collectors:** `AlertsUnacknowledgedCollector` (open CRITICAL alerts > 5 min), `OutboxPendingCollector` (unprocessed outbox rows), `KafkaConsumerLagCollector` (four consumer groups), `WardGatewayMetricsCollector` (gateway status/buffer depth) — all poll every 30–60 seconds. + **Concepts practiced:** The four golden signals in a clinical context, which metrics are operational (Kafka lag, outbox pending) vs which are patient safety indicators (unacknowledged critical alerts), log enrichment with `correlationId`, `encounterId`, `patientId` on every alert path log line. --- @@ -467,34 +503,121 @@ Each check creates a `reconciliation_alerts` row and publishes a job to RabbitMQ --- +### 12. Clinical Data Expansion and Warning Alerts (Phases 10–11) + +**Description:** Expands the clinical data model and alert pipeline. Patient entities gain optional clinical fields (blood type, allergies, emergency contact). Encounters gain room/bed assignment, admission reason, and discharge diagnosis. Five new observation codes (`SYSTOLIC_BP`, `DIASTOLIC_BP`, `LACTATE_MMOL_L`, `AVPU`, `SUPPLEMENTAL_O2`) and `GLUCOSE_MG_DL` join the original six for 12 total seeded thresholds. + +The `WarningAlertService` (consumer group `warning-evaluator`) reads `observation.recorded` from Kafka and creates `WARNING`-severity alerts for values that breach warning thresholds but not critical thresholds. Warning alerts are idempotent (`INSERT WHERE NOT EXISTS`) per encounter and alert type while status is `OPEN` or `ACKNOWLEDGED`. Warning alerts are indexed in Elasticsearch but not published to the RabbitMQ paging queue. + +An Orders API (`OrdersController`, `OrderService`) supports clinical order management with a status machine (`Pending → InProgress → Resulted`, terminal `Cancelled`). FluentValidation is applied to all request DTOs. + +--- + +### 13. NEWS2 Composite Scoring Engine (Phase 12) + +**Description:** The NEWS2 (National Early Warning Score 2) engine evaluates seven vital parameters per encounter using Redis keys with a 4-hour TTL. When all seven are present, computes the official NEWS2 aggregate score, persists to `news2_scores`, and creates `NEWS2_WARNING` (score 5–6 or single param = 3) or `NEWS2_EMERGENCY` (score ≥ 7) alerts idempotently. + +**Parameters:** `RESP_RATE`, `SPO2`, `SYSTOLIC_BP`, `HEART_RATE`, `AVPU`, `TEMP_C`, `SUPPLEMENTAL_O2` — each scored 0–3 per official lookup tables. Consciousness resolves GCS-first with AVPU fallback. `GET /encounters/:id/news2/current` and `/history` expose score history. + +--- + +### 14. Trend Detection and Alert Suppression (Phase 13) + +**Description:** `TrendAnalyzerService` (consumer group `trend-analyzer`) tracks rate-of-change for five vital parameters using Redis sliding-window history. When velocity exceeds configured thresholds (e.g. 72→95 bpm in 30 min), creates a `RAPID_DETERIORATION` alert even if the current value is below warning thresholds. + +Alert suppression windows prevent warning fatigue. Acknowledging a suppressible alert sets a Redis key `suppress:{encounterId}:{alertType}` with a configurable TTL (default 30 min). `WarningEvaluator` and `News2Detector` check suppression before creating new warning alerts. Critical alerts are never suppressed. + +--- + +### 15. Medication Administration and Correlation (Phase 15) + +**Description:** Records drug administrations per encounter. `MedicationCorrelationHelper` annotates warning and NEWS2 alert details when a correlated drug was administered within a configurable window (default 90 min). Annotations provide clinical context — e.g. `— note: metoprolol 25mg (PO) administered 45 min ago` — but never suppress alerts. + +--- + +### 16. Glasgow Coma Scale and SOFA Scoring (Phases 25–26) + +**Description:** GCS scores three components (Eye 1–4, Verbal 1–5, Motor 1–6) tracked in Redis. When all three are present, computes total (3–15), classification (`MILD`/`MODERATE`/`SEVERE`), creates alerts (≤ 8 `GCS_CRITICAL`, 9–12 `GCS_WARNING`), and publishes `gcs.scored` via outbox for SOFA CNS re-scoring. + +SOFA scoring evaluates six organ systems (respiratory, coagulation, liver, cardiovascular, CNS, renal) with Redis lab cache, carry-forward semantics, MAP derivation, SpO₂/FiO₂ fallback, and vasopressor detection. Baseline established when ≥ 4 organ systems have data. Delta ≥ 2 from baseline triggers `SOFA_SEPSIS` → sepsis bundle. + +--- + +### 17. FHIR R4 Integration (Phase 30) + +**Description:** Inbound FHIR R4 facade accepts resources from integration engines (Mirth Connect, Rhapsody). Per-resource endpoints (`POST /fhir/R4/{Patient,Encounter,Observation,MedicationAdministration}`) and transaction Bundles (Patient → Encounter → Observation in dependency order). 19 LOINC codes + 3 SNOMED CT fallbacks mapped to internal observation codes. Fahrenheit-to-Celsius conversion. `ExternalResourceIdentifier` table links hospital MRNs and visit numbers to internal UUIDs for idempotent upserts. Read/search endpoints (`GET /fhir/R4/Patient/{id}`, `GET /fhir/R4/Patient`, `GET /fhir/R4/Encounter/{id}`, `GET /fhir/R4/Encounter`) return FHIR R4 JSON. + +--- + +### 18. RBAC and Clinical Audit Logging (Phase 31) + +**Description:** JWT bearer authentication with four clinical roles (`Nurse`, `Physician`, `Admin`, `Integration`) and 17 granular permissions. `AuthorizePermission` attribute on every controller action. `PermissionAuthorizationHandler` resolves role → permission at runtime. `CurrentUserService` extracts authenticated identity from JWT claims. + +Append-only `clinical_audit_logs` table records write actions with user identity, entity type/ID, before/after state (JSONB), reason, IP address, and correlation ID. Ten audit actions tracked. FHIR endpoints accept both JWT and `X-Api-Key` authentication for integration engine compatibility. + +--- + +### 19. Site & Gateway Registry and Ward Gateway (Phases 20–21) + +**Description:** `ClinicalSite` and `WardGateway` entities model ward edge nodes. Dual authentication — JWT + RBAC for admin CRUD, `GatewayApiKeyAuthenticationHandler` for gateway heartbeat and sync. `VigilCare.ClinicalContracts` shared class library defines sync DTOs. + +`VigilCare.WardGateway` is a standalone ASP.NET Core deployable with its own PostgreSQL, Redis, and RabbitMQ. Observations are ingested locally with threshold evaluation and critical alert creation, then buffered for upload to central API when the network link recovers. Background services replicate encounter/patient data, report heartbeat status, and batch-upload buffered sync items. + +--- + +### 20. Ward Dashboard (Phases 17–19, 22, 28) + +**Description:** Vue 3 SPA (`vigilcare-dashboard/`) with Vite, Pinia, Tailwind CSS v4, and Chart.js. Virtual ward table (NEWS2-sorted, department filter), patient detail view (vitals, scores, alerts, orders, sepsis bundle, GCS entry form, SOFA score panel, patient banner with demographics, encounter timeline), and alert center (global acknowledge/resolve). + +Chart components: five vital sign trend charts with medication administration markers, NEWS2 history, SOFA history with organ-system breakdown, GCS history with component tracking, qSOFA evaluation history. Local replay scrubbing, alert reasoning with medication context, and clinician feedback mode (six ratings per alert, Feedback Summary with JSON/CSV export). + +Phase 22 gap analysis fixes: `SofaHistory.vue`, `GcsHistory.vue`, `QsofaHistory.vue`, `PatientBanner.vue`, `EncounterTimeline.vue`, medication marker Chart.js plugin. Backend additions: `GET /gcs/history`, `GET /qsofa/history` APIs, `qsofa_evaluations` table. + +--- + +### 21. Console Replay Simulator (Phase 16, 29) + +**Description:** Standalone `VigilCare.Simulator` .NET console app replays JSON scenario files against the live API with configurable speed. Commands: `replay`, `replay-all`, `validate`, `dry-run`. Optional `--poll` shows alerts, NEWS2, GCS, SOFA, and sepsis bundle state during replay. Eleven sample scenarios including GCS neurological decline, SOFA sepsis progression, and SpO₂/FiO₂ fallback. + +--- + ## Database Schema and Indexing Plan ```sql CREATE TABLE patients ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - mrn VARCHAR(20) NOT NULL UNIQUE, - first_name VARCHAR(100) NOT NULL, - last_name VARCHAR(100) NOT NULL, - date_of_birth DATE NOT NULL, - gender VARCHAR(10) NOT NULL, - status VARCHAR(20) NOT NULL DEFAULT 'active', - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + mrn VARCHAR(20) NOT NULL UNIQUE, + first_name VARCHAR(100) NOT NULL, + last_name VARCHAR(100) NOT NULL, + date_of_birth DATE NOT NULL, + gender VARCHAR(10) NOT NULL, + blood_type VARCHAR(5) NULL, -- Phase 10: A+, O-, AB-, etc. + allergies TEXT NULL, -- Phase 10: free-text allergy list + emergency_contact_name VARCHAR(200) NULL, -- Phase 10 + emergency_contact_phone VARCHAR(30) NULL, -- Phase 10 + status VARCHAR(20) NOT NULL DEFAULT 'active', + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() ); CREATE TABLE encounters ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - patient_id UUID NOT NULL REFERENCES patients(id), - encounter_type VARCHAR(20) NOT NULL, - status VARCHAR(20) NOT NULL DEFAULT 'scheduled', - department VARCHAR(100) NOT NULL, - attending_physician VARCHAR(200) NOT NULL, - admitted_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - discharged_at TIMESTAMPTZ NULL, - created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + patient_id UUID NOT NULL REFERENCES patients(id), + encounter_type VARCHAR(20) NOT NULL, + status VARCHAR(20) NOT NULL DEFAULT 'scheduled', + department VARCHAR(100) NOT NULL, + attending_physician VARCHAR(200) NOT NULL, + room_bed VARCHAR(50) NULL, -- Phase 10: ward/bed assignment + admission_reason TEXT NULL, -- Phase 10 + discharge_diagnosis TEXT NULL, -- Phase 10: set on discharge + admitted_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + discharged_at TIMESTAMPTZ NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW() ); CREATE INDEX idx_encounters_patient ON encounters (patient_id, admitted_at DESC); CREATE INDEX idx_encounters_active ON encounters (status, admitted_at DESC) WHERE status = 'active'; +CREATE UNIQUE INDEX ix_encounters_patient_active_type + ON encounters (patient_id, encounter_type) WHERE status = 'ACTIVE'; CREATE TABLE alert_thresholds ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), @@ -527,34 +650,37 @@ CREATE INDEX idx_observations_encounter_time ON observations (encounter_id, observation_code, recorded_at DESC); CREATE TABLE clinical_alerts ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - encounter_id UUID NOT NULL REFERENCES encounters(id), - patient_id UUID NOT NULL REFERENCES patients(id), - observation_id UUID NULL REFERENCES observations(id), - alert_type VARCHAR(50) NOT NULL, - severity VARCHAR(20) NOT NULL, - details TEXT NOT NULL, - status VARCHAR(20) NOT NULL DEFAULT 'open', - acknowledged_at TIMESTAMPTZ NULL, - acknowledged_by VARCHAR(200) NULL, - resolved_at TIMESTAMPTZ NULL, - triggered_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + encounter_id UUID NOT NULL REFERENCES encounters(id), + patient_id UUID NOT NULL REFERENCES patients(id), + observation_id UUID NULL REFERENCES observations(id), + alert_type VARCHAR(50) NOT NULL, + severity VARCHAR(20) NOT NULL, + details TEXT NOT NULL, + observation_code VARCHAR(50) NULL, -- enables direct lookups without LIKE pattern matching + status VARCHAR(20) NOT NULL DEFAULT 'open', + acknowledged_at TIMESTAMPTZ NULL, + acknowledged_by VARCHAR(200) NULL, + resolved_at TIMESTAMPTZ NULL, + triggered_at TIMESTAMPTZ NOT NULL DEFAULT NOW() ); CREATE INDEX idx_alerts_encounter ON clinical_alerts (encounter_id, triggered_at DESC); CREATE INDEX idx_alerts_patient ON clinical_alerts (patient_id, triggered_at DESC); CREATE INDEX idx_alerts_open ON clinical_alerts (severity, triggered_at DESC) WHERE status = 'open'; +CREATE INDEX idx_alerts_enc_code ON clinical_alerts (encounter_id, observation_code, status); CREATE TABLE orders ( - id UUID PRIMARY KEY DEFAULT gen_random_uuid(), - encounter_id UUID NOT NULL REFERENCES encounters(id), - order_type VARCHAR(20) NOT NULL, - description VARCHAR(500) NOT NULL, - ordered_by VARCHAR(200) NOT NULL, - status VARCHAR(20) NOT NULL DEFAULT 'pending', - ordered_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - resulted_at TIMESTAMPTZ NULL + id UUID PRIMARY KEY DEFAULT gen_random_uuid(), + encounter_id UUID NOT NULL REFERENCES encounters(id), + order_type VARCHAR(20) NOT NULL, + description VARCHAR(500) NOT NULL, + ordered_by VARCHAR(200) NOT NULL, + status VARCHAR(20) NOT NULL DEFAULT 'pending', + ordered_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + resulted_at TIMESTAMPTZ NULL, + result_summary TEXT NULL -- free-text result summary ); CREATE INDEX idx_orders_encounter ON orders (encounter_id, ordered_at DESC); @@ -564,13 +690,17 @@ CREATE INDEX idx_orders_pending ON orders (status, ordered_at) CREATE TABLE outbox_events ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), topic VARCHAR(200) NOT NULL, + partition_key VARCHAR(100) NULL, -- encounterId for per-encounter ordering payload JSONB NOT NULL, created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), - processed_at TIMESTAMPTZ NULL + processed_at TIMESTAMPTZ NULL, + retry_count INT NOT NULL DEFAULT 0, -- Kafka produce attempt counter + last_error TEXT NULL, -- last failure reason + failed_at TIMESTAMPTZ NULL -- set when retryCount exceeds OutboxMaxRetries ); CREATE INDEX idx_outbox_pending ON outbox_events (created_at) - WHERE processed_at IS NULL; + WHERE processed_at IS NULL AND failed_at IS NULL; CREATE TABLE reconciliation_alerts ( id UUID PRIMARY KEY DEFAULT gen_random_uuid(), @@ -583,6 +713,23 @@ CREATE TABLE reconciliation_alerts ( ); ``` +**Tables added in Phases 10–31** (managed by EF Core migrations — see `README.md` Data Models for full column definitions): + +| Table | Phase | Purpose | +|---|---|---| +| `news2_scores` | 12 | NEWS2 composite scores with seven component scores and risk level | +| `gcs_scores` | 25 | GCS eye/verbal/motor components, total score, classification | +| `sofa_scores` | 26 | Six organ-system scores, baseline flag, delta from baseline, staleness metadata | +| `qsofa_evaluations` | 22 | Per-evaluation qSOFA record: criteria count, values, screen alert fired | +| `sepsis_bundles` | 14 | Four-element treatment bundles with 1-hour compliance deadline | +| `sepsis_bundle_elements` | 14 | Individual bundle elements linked to clinical orders | +| `medication_administrations` | 15 | Drug administration records per encounter | +| `external_resource_identifiers` | 30 | Links hospital MRNs and visit numbers to internal UUIDs for FHIR | +| `clinical_users` | 31 | Username, BCrypt password hash, display name, role | +| `clinical_audit_logs` | 31 | Append-only audit trail: action, entity, user, before/after JSONB, IP, correlation ID | +| `clinical_sites` | 20 | Hospital sites with site code, name, address | +| `ward_gateways` | 20 | Ward edge nodes with status, buffer depth, heartbeat, sync timestamps | + --- ## Design Decisions @@ -626,23 +773,43 @@ Observations, alerts, and orders belong to an encounter, not directly to a patie | Alert acknowledgment | All open CRITICAL alerts must be detectable via the reconciliation job within 30 minutes | | Replay | Deleting and rebuilding the Elasticsearch index from Kafka offset 0 must be demonstrable | | Retention | Data lake writer must write observations to MinIO; nothing is deleted from the lake | -| Testing | Integration tests: critical value ingest → alert created; SIRS criteria met across 3 observations → sepsis alert; duplicate idempotency key → no duplicate; encounter discharge → RabbitMQ job published | +| Testing | Integration tests: critical value ingest → alert created; qSOFA criteria met → screening alert; SOFA delta ≥ 2 → sepsis bundle; duplicate idempotency key → no duplicate; encounter discharge → RabbitMQ job published | --- ## Build Order -| Phase | Focus | -|---|---| -| 1 | Schema, migrations, patient/encounter CRUD, alert threshold CRUD, seed data | -| 2 | Observation ingest + synchronous critical value detection + alert lifecycle API | -| 3 | Outbox relay + Kafka topics + producer | -| 4 | Elasticsearch CQRS projection + clinical search + analytics endpoints | -| 5 | Sepsis detection engine (Kafka consumer + Redis SIRS state) | -| 6 | RabbitMQ notification workers + DLQ escalation | -| 7 | Reconciliation jobs (three checks) | -| 8 | Prometheus metrics + Grafana dashboards + Seq logging | -| 9 | MinIO data lake writer (Parquet, partitioned) | +| Phase | Focus | Status | +|---|---|---| +| 1 | Schema, migrations, patient/encounter CRUD, alert threshold CRUD, seed data | Done | +| 2 | Observation ingest + synchronous critical value detection + alert lifecycle API | Done | +| 3 | Outbox relay + Kafka topics + producer | Done | +| 4 | Elasticsearch CQRS projection + clinical search + analytics endpoints | Done | +| 5 | Sepsis detection engine (Kafka consumer + Redis qSOFA state) | Done | +| 6 | RabbitMQ notification workers + DLQ escalation | Done | +| 7 | Reconciliation jobs (three checks) | Done | +| 8 | Prometheus metrics + Grafana dashboards + Seq logging | Done | +| 9 | MinIO data lake writer (Parquet, partitioned) | Done | +| 10 | Clinical data model expansion — patient demographics, encounter enrichment, 12 observation codes | Done | +| 11 | Warning alert consumer (`warning-evaluator`) + Orders API + FluentValidation | Done | +| 12 | NEWS2 composite scoring engine (seven vitals → aggregate score → alerts) | Done | +| 13 | Trend detection (rate-of-change alerts) + alert suppression windows | Done | +| 14 | qSOFA bedside screening + sepsis bundle compliance (SEP-1) | Done | +| 15 | Medication administration + drug-vital correlation annotations on alerts | Done | +| 16 | Console replay simulator (scenario JSON files, speed multiplier, API polling) | Done | +| 17 | Ward dashboard shell — Vue 3 + Vite + Pinia + Tailwind; virtual ward table, patient detail, alert center | Done | +| 18 | Clinical review mode — vital trend charts, NEWS2 history, replay controls, alert reasoning | Done | +| 19 | Clinician feedback mode — six ratings per alert, Feedback Summary with export | Done | +| 20 | Site & Gateway Registry + Clinical Sync Contracts (shared class library) | Done | +| 21 | Ward Gateway Service — local-first clinical path with offline buffering and central sync | Done | +| 22 | Dashboard gap analysis fixes — SOFA/GCS/qSOFA history charts, patient banner, encounter timeline, medication markers | Done | +| 25 | Glasgow Coma Scale (GCS) scoring — three components → total → alerts → SOFA CNS | Done | +| 26 | SOFA organ-dysfunction scoring — six organ systems, baseline tracking, delta sepsis alerts | Done | +| 27 | Sepsis-3 clinical refactor — SIRS removed, qSOFA screening, SOFA bundle trigger | Done | +| 28 | Frontend GCS entry form + SOFA score panel + sepsis UI refactor | Done | +| 29 | Simulator scenario expansion + clinical validation (end-to-end qSOFA → SOFA → bundle) | Done | +| 30 | FHIR R4 Inbound Facade — per-resource ingest, transaction Bundles, read/search, LOINC mapping | Done | +| 31 | RBAC + Clinical Audit Logging — JWT auth, four roles, 17 permissions, append-only audit trail | Done | --- @@ -691,7 +858,7 @@ The split between synchronous (critical) and asynchronous (warning) detection is 5. Introduce the outbox bug deliberately: make two separate commits (one for the observation, one for the outbox event) and observe the data loss when the process crashes between them. Fix it. This step is not optional — seeing the failure mode is the fastest path to internalizing the pattern. **Why:** -The per-encounter partition key is important for the sepsis engine. If observations from the same patient land on different partitions, they may be processed out of order, and SIRS criteria that arrived simultaneously could be missed. Document this in the code. +The per-encounter partition key is important for the sepsis engine. If observations from the same patient land on different partitions, they may be processed out of order, and qSOFA criteria that arrived simultaneously could be missed. Document this in the code. --- @@ -710,15 +877,19 @@ The replay is the proof that Elasticsearch is a projection and not a source of t ### Phase 5 — Sepsis Detection Engine +> **Updated for Sepsis-3 (Phase 27 refactor):** The original Phase 5 implemented SIRS-based detection. Phase 27 replaced SIRS with the two-tier qSOFA → SOFA pathway per the 2016 Sepsis-3 consensus. The steps below reflect the current implementation. + **What to do:** 1. Build the `sepsis-engine` consumer group reading `observation.recorded`. -2. Implement the Redis SIRS state as described in the Features section: `SET sirs:{encounterId}:{code} EX 1800` on criterion met, `DEL` on criterion not met. -3. Use `MGET` on all four SIRS keys per encounter after each observation — four O(1) operations, not a scan. -4. On SIRS count >= 2: check for an existing open `SEPSIS_WARNING` alert for this encounter before inserting. The check and insert are one round-trip: `INSERT INTO clinical_alerts ... WHERE NOT EXISTS (SELECT 1 FROM clinical_alerts WHERE encounter_id = ? AND alert_type = 'SEPSIS_WARNING' AND status = 'open')`. -5. Write an integration test: ingest three observations that meet two SIRS criteria for the same encounter within 30 minutes → verify one `SEPSIS_WARNING` alert is created. Ingest a normal temperature immediately after → verify the TTL key is deleted but the alert remains open until acknowledged. +2. Implement the Redis qSOFA state: `SET qsofa:{encounterId}:{code} EX 1800` on criterion met, `DEL` on criterion normalized. +3. Use `MGET` on all three qSOFA keys per encounter after each observation — three O(1) operations, not a scan. +4. Persist every evaluation to `qsofa_evaluations` table with criteria values and screen-alert-fired flag. +5. On qSOFA count >= 2: check for an existing open `QSOFA_SCREEN` alert for this encounter before inserting. The check and insert are one round-trip: `INSERT INTO clinical_alerts ... WHERE NOT EXISTS (SELECT 1 FROM clinical_alerts WHERE encounter_id = ? AND alert_type = 'QSOFA_SCREEN' AND status IN ('open', 'acknowledged'))`. +6. SOFA scoring (`sofa-scoring` consumer) scores six organ systems and triggers `SOFA_SEPSIS` on delta ≥ 2 from baseline → sepsis bundle creation. +7. Write integration tests: ingest observations meeting two qSOFA criteria → verify `QSOFA_SCREEN` alert created. Verify normalization deletes Redis key. Verify SOFA delta ≥ 2 triggers sepsis bundle. **Why:** -The TTL is doing real work here. Without it, a patient who had a fever yesterday would still have `sirs:{encounterId}:TEMP_C = "1"` in Redis today and could trigger a false sepsis alert from a fast heart rate alone. The 30-minute TTL matches the clinical window for SIRS evaluation. Understand this before the interview — the TTL is not an arbitrary expiry, it is a clinical parameter encoded in the data layer. +The 30-minute TTL matches the clinical window for qSOFA evaluation — a respiratory rate that was abnormal 31 minutes ago stops contributing without any cleanup job. SIRS was removed because it was too non-specific (triggering on post-surgical inflammation, anxiety, viral infections). qSOFA measures organ dysfunction at the bedside; SOFA confirms it with lab values. This two-tier approach prevents false-positive bundle activations. --- @@ -752,3 +923,9 @@ Check 3 is the one unique to clinical systems. A financial reconciliation job ch ### Phases 8 and 9 — Observability and Data Lake Follow the same Prometheus/Grafana and MinIO/Parquet approach as described in the Features section. The `alerts_unacknowledged_gauge` panel is the single most important panel in the Grafana dashboard — build it first and make sure it updates in near real-time (poll the database every 30 seconds). + +--- + +### Phases 10–31 — Extended Feature Phases + +See the [Build Order](#build-order) table for all implemented phases and the [Features](#features) section (items 12–21) for detailed descriptions. Per-phase implementation plans and verification guides are in `docs/plans/`. Integration tests and verification scripts cover all phases — see `README.md` for the full test table and script listing. diff --git a/vigilcare-dashboard/src/__tests__/AcknowledgeModal.test.js b/vigilcare-dashboard/src/__tests__/AcknowledgeModal.test.js new file mode 100644 index 0000000..b369965 --- /dev/null +++ b/vigilcare-dashboard/src/__tests__/AcknowledgeModal.test.js @@ -0,0 +1,67 @@ +import { describe, it, expect, beforeEach } from 'vitest' +import { mount } from '@vue/test-utils' +import { createPinia, setActivePinia } from 'pinia' +import AcknowledgeModal from '@/components/alerts/AcknowledgeModal.vue' +import { useAuthStore } from '@/stores/auth' + +const alert = { + id: 'alert-1', + alertType: 'SofaSepsis', + severity: 'Critical', + status: 'Open', + details: 'SOFA delta >= 2', +} + +describe('AcknowledgeModal', () => { + beforeEach(() => { + setActivePinia(createPinia()) + const auth = useAuthStore() + auth.$patch({ + user: { + userId: '11111111-1111-1111-1111-111111111111', + username: 'nurse.demo', + displayName: 'Demo Nurse', + role: 'NURSE', + }, + }) + }) + + it('showsAuthenticatedUserAndRoleContext', () => { + const wrapper = mount(AcknowledgeModal, { + props: { open: true, alert }, + global: { + stubs: { + Modal: { + props: ['open', 'title'], + template: '
', + }, + }, + }, + }) + + expect(wrapper.text()).toContain('Demo Nurse') + expect(wrapper.text()).toContain('Nurse') + expect(wrapper.text()).toContain('documenting awareness') + expect(wrapper.text()).toContain('[NURSE] Acknowledged by Demo Nurse.') + }) + + it('emitsOptionalNoteOnConfirm', async () => { + const wrapper = mount(AcknowledgeModal, { + props: { open: true, alert }, + global: { + stubs: { + Modal: { + props: ['open', 'title'], + template: '
', + }, + }, + }, + }) + + await wrapper.find('textarea').setValue('Will reassess in 30 minutes') + const ackButton = wrapper.findAll('button').find(button => button.text() === 'Acknowledge') + await ackButton.trigger('click') + + expect(wrapper.emitted('confirm')).toEqual([['Will reassess in 30 minutes']]) + }) +}) diff --git a/vigilcare-dashboard/src/__tests__/AlertCard.test.js b/vigilcare-dashboard/src/__tests__/AlertCard.test.js index c72a859..c080d33 100644 --- a/vigilcare-dashboard/src/__tests__/AlertCard.test.js +++ b/vigilcare-dashboard/src/__tests__/AlertCard.test.js @@ -36,6 +36,20 @@ describe('AlertCard', () => { expect(wrapper.emitted('acknowledge')).toHaveLength(1) }) + it('showsAcknowledgedByWhenPresent', () => { + const wrapper = mount(AlertCard, { + props: { + alert: { + ...openAlert, + status: 'Acknowledged', + acknowledgedBy: 'Demo Nurse (NURSE)', + acknowledgedAt: '2026-06-19T12:30:00Z', + }, + }, + }) + expect(wrapper.text()).toContain('Acknowledged by Demo Nurse (Nurse)') + }) + it('resolvedAlertHidesActions', () => { const wrapper = mount(AlertCard, { props: { alert: resolvedAlert } }) const actionButtons = wrapper.findAll('button').filter(b => ['Acknowledge', 'Resolve'].includes(b.text())) diff --git a/vigilcare-dashboard/src/__tests__/CriticalAlertBanner.test.js b/vigilcare-dashboard/src/__tests__/CriticalAlertBanner.test.js new file mode 100644 index 0000000..c9c40fb --- /dev/null +++ b/vigilcare-dashboard/src/__tests__/CriticalAlertBanner.test.js @@ -0,0 +1,35 @@ +import { describe, it, expect, vi } from 'vitest' +import { mount } from '@vue/test-utils' +import { createPinia, setActivePinia } from 'pinia' +import CriticalAlertBanner from '@/components/alerts/CriticalAlertBanner.vue' +import { useAlertStore } from '@/stores/alerts' + +const { mockPush } = vi.hoisted(() => ({ + mockPush: vi.fn(), +})) + +vi.mock('vue-router', () => ({ + useRouter: () => ({ push: mockPush }), +})) + +describe('CriticalAlertBanner', () => { + it('rendersCriticalAlertsAndDismisses', async () => { + setActivePinia(createPinia()) + const alertStore = useAlertStore() + alertStore.bannerAlerts = [{ + id: 'alert-1', + alertType: 'SofaSepsis', + severity: 'Critical', + status: 'Open', + details: 'SOFA delta >= 2', + }] + + const wrapper = mount(CriticalAlertBanner) + expect(wrapper.text()).toContain('Sepsis Alert (SOFA)') + expect(wrapper.text()).toContain('SOFA delta >= 2') + + const dismissButton = wrapper.findAll('button').find(button => button.text() === 'Dismiss') + await dismissButton.trigger('click') + expect(alertStore.bannerAlerts).toEqual([]) + }) +}) diff --git a/vigilcare-dashboard/src/__tests__/DepartmentOverviewView.test.js b/vigilcare-dashboard/src/__tests__/DepartmentOverviewView.test.js new file mode 100644 index 0000000..d98c637 --- /dev/null +++ b/vigilcare-dashboard/src/__tests__/DepartmentOverviewView.test.js @@ -0,0 +1,54 @@ +import { describe, it, expect, vi } from 'vitest' +import { mount } from '@vue/test-utils' +import { createPinia, setActivePinia } from 'pinia' +import DepartmentOverviewView from '@/views/DepartmentOverviewView.vue' + +const { mockPush } = vi.hoisted(() => ({ + mockPush: vi.fn(), +})) + +vi.mock('vue-router', () => ({ + useRouter: () => ({ push: mockPush }), +})) + +vi.mock('@/composables/usePolling', () => ({ + usePolling: (fn) => { + fn() + }, +})) + +vi.mock('@/api/encounters', () => ({ + fetchAllActiveEncounters: vi.fn(() => Promise.resolve([ + { + department: 'ICU', + news2Score: 8, + openAlertCount: 2, + sepsisActive: true, + sepsisBundleStatus: 'IN_PROGRESS', + }, + { + department: 'GENERAL_MEDICINE', + news2Score: 3, + openAlertCount: 0, + sepsisActive: false, + }, + ])), +})) + +vi.mock('@/api/analytics', () => ({ + fetchAlertSummary: vi.fn(() => Promise.resolve({ + summary: [{ department: 'ICU', total: 5 }], + })), +})) + +describe('DepartmentOverviewView', () => { + it('rendersDepartmentCardsAndTotals', async () => { + setActivePinia(createPinia()) + const wrapper = mount(DepartmentOverviewView) + await vi.waitFor(() => expect(wrapper.text()).toContain('1 active patient')) + + expect(wrapper.text()).toContain('Department Overview') + expect(wrapper.text()).toContain('Critical (NEWS2 ≥ 7)') + expect(wrapper.text()).toContain('Alert volume') + }) +}) diff --git a/vigilcare-dashboard/src/__tests__/SepsisBoardView.test.js b/vigilcare-dashboard/src/__tests__/SepsisBoardView.test.js new file mode 100644 index 0000000..72073cd --- /dev/null +++ b/vigilcare-dashboard/src/__tests__/SepsisBoardView.test.js @@ -0,0 +1,49 @@ +import { describe, it, expect, vi } from 'vitest' +import { mount } from '@vue/test-utils' +import { createPinia, setActivePinia } from 'pinia' +import SepsisBoardView from '@/views/SepsisBoardView.vue' + +const { mockPush } = vi.hoisted(() => ({ + mockPush: vi.fn(), +})) + +vi.mock('vue-router', () => ({ + useRouter: () => ({ push: mockPush }), +})) + +vi.mock('@/composables/usePolling', () => ({ + usePolling: () => {}, +})) + +const bundles = [ + { + id: 'b1', + encounterId: 'enc-1', + firstName: 'Alice', + lastName: 'A', + mrn: 'M1', + department: 'Icu', + roomBed: '101', + recognizedAt: '2026-06-23T12:00:00Z', + deadlineAt: '2026-06-23T15:00:00Z', + complianceStatus: 'IN_PROGRESS', + elements: [ + { id: 'e1', elementType: 'BloodCultures', status: 'Completed' }, + { id: 'e2', elementType: 'SerumLactate', status: 'Pending' }, + ], + }, +] + +vi.mock('@/api/sepsis', () => ({ + fetchSepsisBundles: vi.fn(() => Promise.resolve({ items: bundles, totalCount: 1 })), +})) + +describe('SepsisBoardView', () => { + it('rendersBundleBoardWithSummary', async () => { + setActivePinia(createPinia()) + const wrapper = mount(SepsisBoardView) + await vi.waitFor(() => expect(wrapper.text()).toContain('Alice A')) + expect(wrapper.text()).toContain('Sepsis Bundle Board') + expect(wrapper.text()).toContain('Serum lactate') + }) +}) diff --git a/vigilcare-dashboard/src/__tests__/WardTable.test.js b/vigilcare-dashboard/src/__tests__/WardTable.test.js index 855e16f..03ca9c7 100644 --- a/vigilcare-dashboard/src/__tests__/WardTable.test.js +++ b/vigilcare-dashboard/src/__tests__/WardTable.test.js @@ -68,14 +68,19 @@ const patients = [ ] describe('WardTable', () => { + const sortProps = { + sortField: 'news2Score', + sortDirection: 'desc', + } + it('rendersAllPatientRows', () => { - const wrapper = mount(WardTable, { props: { patients } }) + const wrapper = mount(WardTable, { props: { patients, ...sortProps } }) expect(wrapper.findAll('tbody tr')).toHaveLength(3) }) it('emitsClickWithEncounterId', async () => { mockPush.mockClear() - const wrapper = mount(WardTable, { props: { patients } }) + const wrapper = mount(WardTable, { props: { patients, ...sortProps } }) await wrapper.findAll('tbody tr')[2].trigger('click') expect(mockPush).toHaveBeenCalledWith({ name: 'PatientDetail', @@ -84,18 +89,26 @@ describe('WardTable', () => { }) it('showsCriticalBadgeForHighNews2', () => { - const wrapper = mount(WardTable, { props: { patients } }) + const wrapper = mount(WardTable, { props: { patients, ...sortProps } }) const highRiskRow = wrapper.findAll('tbody tr')[2] expect(highRiskRow.html()).toContain('text-severity-critical') }) it('showsExtendedClinicalColumns', () => { - const wrapper = mount(WardTable, { props: { patients } }) + const wrapper = mount(WardTable, { props: { patients, ...sortProps } }) const header = wrapper.find('thead').text() expect(header).toContain('SOFA') expect(header).toContain('GCS') + expect(header).toContain('Department') expect(header).toContain('Last vitals') expect(wrapper.text()).toContain('Dr. C') expect(wrapper.text()).toContain('Δ+2') }) + + it('emitsSortWhenHeaderClicked', async () => { + const wrapper = mount(WardTable, { props: { patients, ...sortProps } }) + const roomHeader = wrapper.findAll('thead button').find(button => button.text().includes('Room')) + await roomHeader.trigger('click') + expect(wrapper.emitted('sort')).toEqual([['roomBed']]) + }) }) diff --git a/vigilcare-dashboard/src/__tests__/alertAcknowledge.test.js b/vigilcare-dashboard/src/__tests__/alertAcknowledge.test.js new file mode 100644 index 0000000..0fd65f8 --- /dev/null +++ b/vigilcare-dashboard/src/__tests__/alertAcknowledge.test.js @@ -0,0 +1,21 @@ +import { describe, it, expect } from 'vitest' +import { + formatAcknowledgedByDisplay, + previewAcknowledgmentNote, + roleAcknowledgmentMessage, +} from '@/composables/alertAcknowledge' + +describe('alertAcknowledge', () => { + it('buildsRoleAwareNotePreview', () => { + expect(previewAcknowledgmentNote('NURSE', 'Demo Nurse', 'Escalating to physician')) + .toBe('[NURSE] Acknowledged by Demo Nurse. Escalating to physician') + }) + + it('usesRoleSpecificAcknowledgmentMessage', () => { + expect(roleAcknowledgmentMessage('PHYSICIAN')).toContain('physician') + }) + + it('formatsAcknowledgedByDisplay', () => { + expect(formatAcknowledgedByDisplay('Demo Nurse (NURSE)')).toBe('Demo Nurse (Nurse)') + }) +}) diff --git a/vigilcare-dashboard/src/__tests__/criticalAlertDetect.test.js b/vigilcare-dashboard/src/__tests__/criticalAlertDetect.test.js new file mode 100644 index 0000000..aa920a0 --- /dev/null +++ b/vigilcare-dashboard/src/__tests__/criticalAlertDetect.test.js @@ -0,0 +1,48 @@ +import { describe, it, expect } from 'vitest' +import { detectNewCriticalAlerts, isNotifiableCriticalAlert } from '@/composables/criticalAlertDetect' + +const criticalOpen = { + id: 'a1', + severity: 'Critical', + status: 'Open', + alertType: 'SofaSepsis', +} + +const criticalAcknowledged = { + id: 'a2', + severity: 'Critical', + status: 'Acknowledged', + alertType: 'News2Emergency', +} + +const warningOpen = { + id: 'a3', + severity: 'Warning', + status: 'Open', + alertType: 'News2Warning', +} + +describe('criticalAlertDetect', () => { + it('identifiesNotifiableCriticalAlerts', () => { + expect(isNotifiableCriticalAlert(criticalOpen)).toBe(true) + expect(isNotifiableCriticalAlert(criticalAcknowledged)).toBe(false) + expect(isNotifiableCriticalAlert(warningOpen)).toBe(false) + }) + + it('seedsSeenIdsOnFirstPoll', () => { + const result = detectNewCriticalAlerts([criticalOpen, warningOpen], [], false) + expect(result.newAlerts).toEqual([]) + expect(result.nextSeenIds).toEqual(['a1']) + expect(result.seeded).toBe(true) + }) + + it('detectsNewCriticalAlertsAfterSeed', () => { + const seeded = detectNewCriticalAlerts([criticalOpen], [], false) + const next = detectNewCriticalAlerts( + [criticalOpen, { ...criticalOpen, id: 'a4', alertType: 'GcsCritical' }], + seeded.nextSeenIds, + seeded.seeded, + ) + expect(next.newAlerts.map(alert => alert.id)).toEqual(['a4']) + }) +}) diff --git a/vigilcare-dashboard/src/__tests__/departmentFormat.test.js b/vigilcare-dashboard/src/__tests__/departmentFormat.test.js new file mode 100644 index 0000000..56491a9 --- /dev/null +++ b/vigilcare-dashboard/src/__tests__/departmentFormat.test.js @@ -0,0 +1,87 @@ +import { describe, it, expect } from 'vitest' +import { + aggregateByDepartment, + news2AcuityTier, + normalizeDepartmentKey, + summarizeDepartments, +} from '@/composables/departmentFormat' + +const encounters = [ + { + department: 'ICU', + news2Score: 8, + openAlertCount: 2, + sepsisActive: true, + sepsisBundleStatus: 'IN_PROGRESS', + }, + { + department: 'Icu', + news2Score: 5, + openAlertCount: 1, + sepsisActive: false, + sepsisBundleStatus: null, + }, + { + department: 'GENERAL_MEDICINE', + news2Score: 2, + openAlertCount: 0, + sepsisActive: false, + sepsisBundleStatus: null, + }, + { + department: 'Surgery', + news2Score: 6, + openAlertCount: 3, + sepsisActive: true, + sepsisBundleStatus: 'IN_PROGRESS', + }, +] + +describe('departmentFormat', () => { + it('normalizesDepartmentKeys', () => { + expect(normalizeDepartmentKey('Icu')).toBe('ICU') + expect(normalizeDepartmentKey('GeneralMedicine')).toBe('GENERAL_MEDICINE') + }) + + it('classifiesNews2Acuity', () => { + expect(news2AcuityTier(2)).toBe('low') + expect(news2AcuityTier(5)).toBe('medium') + expect(news2AcuityTier(7)).toBe('high') + }) + + it('aggregatesByDepartment', () => { + const departments = aggregateByDepartment(encounters, [ + { department: 'ICU', total: 10 }, + { department: 'SURGERY', total: 4 }, + ]) + + const icu = departments.find(d => d.key === 'ICU') + const surgery = departments.find(d => d.key === 'SURGERY') + const general = departments.find(d => d.key === 'GENERAL_MEDICINE') + + expect(icu.patientCount).toBe(2) + expect(icu.acuity.high).toBe(1) + expect(icu.acuity.medium).toBe(1) + expect(icu.activeBundleCount).toBe(1) + expect(icu.openAlertCount).toBe(3) + expect(icu.averageNews2).toBe(6.5) + expect(icu.alertVolume).toBe(10) + + expect(surgery.patientCount).toBe(1) + expect(surgery.activeBundleCount).toBe(1) + expect(surgery.alertVolume).toBe(4) + + expect(general.patientCount).toBe(1) + expect(general.acuity.low).toBe(1) + }) + + it('summarizesTotals', () => { + const departments = aggregateByDepartment(encounters) + expect(summarizeDepartments(departments)).toEqual({ + patientCount: 4, + criticalCount: 1, + activeBundleCount: 2, + openAlertCount: 6, + }) + }) +}) diff --git a/vigilcare-dashboard/src/__tests__/sepsisFormat.test.js b/vigilcare-dashboard/src/__tests__/sepsisFormat.test.js new file mode 100644 index 0000000..865562e --- /dev/null +++ b/vigilcare-dashboard/src/__tests__/sepsisFormat.test.js @@ -0,0 +1,56 @@ +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest' +import { + bundleUrgency, + formatCountdown, + sortBundlesByUrgency, + summarizeBundles, +} from '@/composables/sepsisFormat' + +const baseBundle = { + complianceStatus: 'IN_PROGRESS', + deadlineAt: '2026-06-23T15:00:00Z', +} + +describe('sepsisFormat', () => { + const now = new Date('2026-06-23T14:00:00Z').getTime() + + beforeEach(() => { + vi.useFakeTimers() + vi.setSystemTime(now) + }) + + afterEach(() => { + vi.useRealTimers() + }) + + it('classifiesUrgency', () => { + expect(bundleUrgency({ ...baseBundle, deadlineAt: '2026-06-23T15:00:00Z' }, now)).toBe('on_track') + expect(bundleUrgency({ ...baseBundle, deadlineAt: '2026-06-23T14:20:00Z' }, now)).toBe('at_risk') + expect(bundleUrgency({ ...baseBundle, deadlineAt: '2026-06-23T13:00:00Z' }, now)).toBe('overdue') + expect(bundleUrgency({ complianceStatus: 'NON_COMPLIANT', deadlineAt: '2026-06-23T15:00:00Z' }, now)).toBe('overdue') + }) + + it('formatsCountdown', () => { + expect(formatCountdown('2026-06-23T14:45:00Z', now)).toBe('45:00') + expect(formatCountdown('2026-06-23T13:00:00Z', now)).toBe('0:00') + }) + + it('sortsByUrgency', () => { + const bundles = [ + { id: 'a', complianceStatus: 'IN_PROGRESS', deadlineAt: '2026-06-23T15:00:00Z' }, + { id: 'b', complianceStatus: 'IN_PROGRESS', deadlineAt: '2026-06-23T13:00:00Z' }, + { id: 'c', complianceStatus: 'IN_PROGRESS', deadlineAt: '2026-06-23T14:20:00Z' }, + ] + const sorted = sortBundlesByUrgency(bundles, now) + expect(sorted.map(b => b.id)).toEqual(['b', 'c', 'a']) + }) + + it('summarizesBundles', () => { + const bundles = [ + { complianceStatus: 'IN_PROGRESS', deadlineAt: '2026-06-23T15:00:00Z' }, + { complianceStatus: 'IN_PROGRESS', deadlineAt: '2026-06-23T14:20:00Z' }, + { complianceStatus: 'IN_PROGRESS', deadlineAt: '2026-06-23T13:00:00Z' }, + ] + expect(summarizeBundles(bundles, now)).toEqual({ on_track: 1, at_risk: 1, overdue: 1 }) + }) +}) diff --git a/vigilcare-dashboard/src/__tests__/useAlertStore.test.js b/vigilcare-dashboard/src/__tests__/useAlertStore.test.js new file mode 100644 index 0000000..dddd58e --- /dev/null +++ b/vigilcare-dashboard/src/__tests__/useAlertStore.test.js @@ -0,0 +1,39 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest' +import { createPinia, setActivePinia } from 'pinia' +import { useAlertStore } from '@/stores/alerts' + +describe('alert store notifications', () => { + beforeEach(() => { + setActivePinia(createPinia()) + }) + + it('queuesBannerAlertsForNewCriticalItems', () => { + const store = useAlertStore() + const critical = { + id: 'alert-1', + severity: 'Critical', + status: 'Open', + alertType: 'SofaSepsis', + } + + expect(store.applyPollResults([critical])).toEqual([]) + expect(store.bannerAlerts).toEqual([]) + + const next = { + id: 'alert-2', + severity: 'Critical', + status: 'Open', + alertType: 'GcsCritical', + } + const newAlerts = store.applyPollResults([critical, next]) + expect(newAlerts.map(alert => alert.id)).toEqual(['alert-2']) + expect(store.bannerAlerts.map(alert => alert.id)).toEqual(['alert-2']) + }) + + it('dismissesBannerAlert', () => { + const store = useAlertStore() + store.bannerAlerts = [{ id: 'alert-1' }] + store.dismissBannerAlert('alert-1') + expect(store.bannerAlerts).toEqual([]) + }) +}) diff --git a/vigilcare-dashboard/src/__tests__/useWardStore.test.js b/vigilcare-dashboard/src/__tests__/useWardStore.test.js new file mode 100644 index 0000000..c4d7b90 --- /dev/null +++ b/vigilcare-dashboard/src/__tests__/useWardStore.test.js @@ -0,0 +1,49 @@ +import { describe, it, expect, beforeEach } from 'vitest' +import { createPinia, setActivePinia } from 'pinia' +import { useSettingsStore } from '@/stores/settings' +import { useWardStore } from '@/stores/ward' + +describe('ward store sort', () => { + beforeEach(() => { + localStorage.clear() + setActivePinia(createPinia()) + }) + + it('persistsSortPreference', () => { + const settings = useSettingsStore() + const ward = useWardStore() + + ward.setSort('name') + expect(settings.wardSortField).toBe('name') + expect(settings.wardSortDirection).toBe('asc') + expect(localStorage.getItem('wardSortField')).toBe('name') + + ward.setSort('name') + expect(settings.wardSortDirection).toBe('desc') + expect(localStorage.getItem('wardSortDirection')).toBe('desc') + }) +}) + +describe('ward store filters', () => { + beforeEach(() => { + localStorage.clear() + setActivePinia(createPinia()) + }) + + it('filtersEncountersForDisplay', () => { + const ward = useWardStore() + ward.encounters = [ + { encounterId: '1', firstName: 'Alice', lastName: 'A', mrn: 'M1', news2Score: 8, openAlertCount: 1 }, + { encounterId: '2', firstName: 'Bob', lastName: 'B', mrn: 'M2', news2Score: 3, openAlertCount: 0 }, + ] + + ward.toggleFilter('critical') + expect(ward.displayEncounters.map(e => e.encounterId)).toEqual(['1']) + + ward.toggleFilter('hasAlerts') + expect(ward.displayEncounters.map(e => e.encounterId)).toEqual(['1']) + + ward.clearFilters() + expect(ward.displayEncounters.map(e => e.encounterId)).toEqual(['1', '2']) + }) +}) diff --git a/vigilcare-dashboard/src/__tests__/wardFilter.test.js b/vigilcare-dashboard/src/__tests__/wardFilter.test.js new file mode 100644 index 0000000..d25290c --- /dev/null +++ b/vigilcare-dashboard/src/__tests__/wardFilter.test.js @@ -0,0 +1,72 @@ +import { describe, it, expect } from 'vitest' +import { filterEncounters, matchesPatientSearch } from '@/composables/wardFilter' + +const patients = [ + { + encounterId: '1', + firstName: 'Alice', + lastName: 'Anderson', + mrn: 'MRN-100', + news2Score: 8, + openAlertCount: 2, + sepsisActive: true, + sepsisBundleStatus: 'IN_PROGRESS', + }, + { + encounterId: '2', + firstName: 'Bob', + lastName: 'Baker', + mrn: 'MRN-200', + news2Score: 4, + openAlertCount: 0, + sepsisActive: false, + }, + { + encounterId: '3', + firstName: 'Carol', + lastName: 'Clark', + mrn: 'MRN-300', + news2Score: 7, + openAlertCount: 1, + sepsisActive: false, + sepsisBundleStatus: 'IN_PROGRESS', + }, +] + +describe('wardFilter', () => { + it('matchesNameOrMrn', () => { + expect(matchesPatientSearch(patients[0], 'alice')).toBe(true) + expect(matchesPatientSearch(patients[0], 'MRN-100')).toBe(true) + expect(matchesPatientSearch(patients[0], 'anderson')).toBe(true) + expect(matchesPatientSearch(patients[0], 'xyz')).toBe(false) + }) + + it('filtersBySearch', () => { + const result = filterEncounters(patients, { search: 'baker' }) + expect(result.map(p => p.encounterId)).toEqual(['2']) + }) + + it('filtersByHasAlerts', () => { + const result = filterEncounters(patients, { hasAlerts: true }) + expect(result.map(p => p.encounterId)).toEqual(['1', '3']) + }) + + it('filtersBySepsisActive', () => { + const result = filterEncounters(patients, { sepsisActive: true }) + expect(result.map(p => p.encounterId)).toEqual(['1', '3']) + }) + + it('filtersByCriticalNews2', () => { + const result = filterEncounters(patients, { critical: true }) + expect(result.map(p => p.encounterId)).toEqual(['1', '3']) + }) + + it('combinesSearchAndFilters', () => { + const result = filterEncounters(patients, { + search: 'carol', + hasAlerts: true, + critical: true, + }) + expect(result.map(p => p.encounterId)).toEqual(['3']) + }) +}) diff --git a/vigilcare-dashboard/src/__tests__/wardSort.test.js b/vigilcare-dashboard/src/__tests__/wardSort.test.js new file mode 100644 index 0000000..228e699 --- /dev/null +++ b/vigilcare-dashboard/src/__tests__/wardSort.test.js @@ -0,0 +1,78 @@ +import { describe, it, expect, beforeEach } from 'vitest' +import { + defaultSortDirection, + sortEncounters, +} from '@/composables/wardSort' + +const patients = [ + { + encounterId: '1', + firstName: 'Bob', + lastName: 'B', + roomBed: '202', + department: 'SURGERY', + news2Score: 5, + qsofaScore: 1, + sepsisActive: false, + openAlertCount: 1, + }, + { + encounterId: '2', + firstName: 'Alice', + lastName: 'A', + roomBed: '101', + department: 'ICU', + news2Score: 8, + qsofaScore: 2, + sepsisActive: true, + sepsisBundleStatus: 'IN_PROGRESS', + openAlertCount: 3, + }, + { + encounterId: '3', + firstName: 'Carol', + lastName: 'C', + roomBed: '103', + department: 'GENERAL_MEDICINE', + news2Score: 2, + qsofaScore: 0, + sepsisActive: false, + openAlertCount: 0, + }, +] + +describe('wardSort', () => { + beforeEach(() => { + localStorage.clear() + }) + + it('defaultsTextFieldsToAscending', () => { + expect(defaultSortDirection('name')).toBe('asc') + expect(defaultSortDirection('news2Score')).toBe('desc') + }) + + it('sortsByNews2DescendingByDefault', () => { + const sorted = sortEncounters(patients, 'news2Score', 'desc') + expect(sorted.map(p => p.encounterId)).toEqual(['2', '1', '3']) + }) + + it('sortsByPatientNameAscending', () => { + const sorted = sortEncounters(patients, 'name', 'asc') + expect(sorted.map(p => p.firstName)).toEqual(['Alice', 'Bob', 'Carol']) + }) + + it('sortsByRoomBedAscending', () => { + const sorted = sortEncounters(patients, 'roomBed', 'asc') + expect(sorted.map(p => p.roomBed)).toEqual(['101', '103', '202']) + }) + + it('sortsByOpenAlertCountDescending', () => { + const sorted = sortEncounters(patients, 'openAlertCount', 'desc') + expect(sorted.map(p => p.encounterId)).toEqual(['2', '1', '3']) + }) + + it('sortsBySepsisStatusDescending', () => { + const sorted = sortEncounters(patients, 'sepsis', 'desc') + expect(sorted[0].encounterId).toBe('2') + }) +}) diff --git a/vigilcare-dashboard/src/api/alerts.js b/vigilcare-dashboard/src/api/alerts.js index 6bf8ce3..bf7b710 100644 --- a/vigilcare-dashboard/src/api/alerts.js +++ b/vigilcare-dashboard/src/api/alerts.js @@ -12,6 +12,26 @@ export function fetchAllAlerts(status) { return api.get(`/api/v1/alerts?${params}`) } +export async function fetchAllOpenAlerts() { + const items = [] + let page = 1 + let totalCount = 0 + + do { + const params = new URLSearchParams({ + status: 'OPEN', + page: String(page), + pageSize: '100', + }) + const data = await api.get(`/api/v1/alerts?${params}`) + items.push(...(data.items ?? [])) + totalCount = data.totalCount ?? items.length + page += 1 + } while (items.length < totalCount) + + return items +} + export function acknowledgeAlert(alertId, note) { return api.post(`/api/v1/alerts/${alertId}/acknowledge`, { note }) } diff --git a/vigilcare-dashboard/src/api/analytics.js b/vigilcare-dashboard/src/api/analytics.js new file mode 100644 index 0000000..65670ac --- /dev/null +++ b/vigilcare-dashboard/src/api/analytics.js @@ -0,0 +1,11 @@ +import { api } from './client' + +export function fetchAlertSummary({ severity, department, from, to } = {}) { + const params = new URLSearchParams() + if (severity) params.set('severity', severity) + if (department) params.set('department', department) + if (from) params.set('from', from) + if (to) params.set('to', to) + const qs = params.toString() + return api.get(`/api/v1/analytics/alerts/summary${qs ? `?${qs}` : ''}`) +} diff --git a/vigilcare-dashboard/src/api/encounters.js b/vigilcare-dashboard/src/api/encounters.js index e1e6733..1e6d83b 100644 --- a/vigilcare-dashboard/src/api/encounters.js +++ b/vigilcare-dashboard/src/api/encounters.js @@ -1,11 +1,30 @@ import { api } from './client' -export function fetchActiveEncounters(department) { - const params = new URLSearchParams({ status: 'ACTIVE' }) +export function fetchActiveEncounters(department, { page = 1, pageSize = 20 } = {}) { + const params = new URLSearchParams({ + status: 'ACTIVE', + page: String(page), + pageSize: String(pageSize), + }) if (department) params.set('department', department) return api.get(`/api/v1/encounters?${params}`) } +export async function fetchAllActiveEncounters(department) { + const items = [] + let page = 1 + let totalCount = 0 + + do { + const data = await fetchActiveEncounters(department, { page, pageSize: 100 }) + items.push(...(data.items ?? [])) + totalCount = data.totalCount ?? items.length + page += 1 + } while (items.length < totalCount) + + return items +} + export function fetchEncounter(id) { return api.get(`/api/v1/encounters/${id}`) } diff --git a/vigilcare-dashboard/src/api/sepsis.js b/vigilcare-dashboard/src/api/sepsis.js new file mode 100644 index 0000000..0627f75 --- /dev/null +++ b/vigilcare-dashboard/src/api/sepsis.js @@ -0,0 +1,10 @@ +import { api } from './client' + +export function fetchSepsisBundles({ status = 'IN_PROGRESS', page = 1, pageSize = 100 } = {}) { + const params = new URLSearchParams({ + page: String(page), + pageSize: String(pageSize), + }) + if (status) params.set('status', status) + return api.get(`/api/v1/sepsis-bundles?${params}`) +} diff --git a/vigilcare-dashboard/src/components/alerts/AcknowledgeModal.vue b/vigilcare-dashboard/src/components/alerts/AcknowledgeModal.vue index cca8fdf..6452bc2 100644 --- a/vigilcare-dashboard/src/components/alerts/AcknowledgeModal.vue +++ b/vigilcare-dashboard/src/components/alerts/AcknowledgeModal.vue @@ -1,19 +1,45 @@