diff --git a/.claude/settings.json b/.claude/settings.json new file mode 100644 index 0000000..29ad246 --- /dev/null +++ b/.claude/settings.json @@ -0,0 +1,7 @@ +{ + "permissions": { + "allow": [ + "Bash(dotnet test *)" + ] + } +} diff --git a/VigilCareClinicalAPI.Tests/Helpers/DbResetHelper.cs b/VigilCareClinicalAPI.Tests/Helpers/DbResetHelper.cs index 5892725..4dc7025 100644 --- a/VigilCareClinicalAPI.Tests/Helpers/DbResetHelper.cs +++ b/VigilCareClinicalAPI.Tests/Helpers/DbResetHelper.cs @@ -6,11 +6,24 @@ public static class DbResetHelper // the database, and preserves the schema (migrations do not re-run). public static async Task ResetAsync(AppDbContext db) { - await db.Database.ExecuteSqlRawAsync(@" - TRUNCATE TABLE reconciliation_alerts, outbox_events, orders, - clinical_alerts, news2_scores, observations, encounters, - alert_thresholds, patients - RESTART IDENTITY CASCADE; - "); + for (var attempt = 0; ; attempt++) + { + try + { + await db.Database.ExecuteSqlRawAsync(@" + SET lock_timeout = '3s'; + TRUNCATE TABLE sepsis_bundle_elements, sepsis_bundles, + reconciliation_alerts, outbox_events, orders, + clinical_alerts, news2_scores, observations, encounters, + alert_thresholds, patients + RESTART IDENTITY CASCADE; + "); + return; + } + catch when (attempt < 5) + { + await Task.Delay(1000); + } + } } } \ No newline at end of file diff --git a/VigilCareClinicalAPI.Tests/QsofaCalculatorTests.cs b/VigilCareClinicalAPI.Tests/QsofaCalculatorTests.cs new file mode 100644 index 0000000..f644fb7 --- /dev/null +++ b/VigilCareClinicalAPI.Tests/QsofaCalculatorTests.cs @@ -0,0 +1,37 @@ +using FluentAssertions; +using StackExchange.Redis; + +public class QsofaCalculatorTests +{ + [Fact] + public void MeetsCriterion_RespRate22_ReturnsTrue() => + QsofaCalculator.MeetsCriterion("RESP_RATE", 22m).Should().BeTrue(); + + [Fact] + public void MeetsCriterion_RespRate21_ReturnsFalse() => + QsofaCalculator.MeetsCriterion("RESP_RATE", 21m).Should().BeFalse(); + + [Fact] + public void MeetsCriterion_SystolicBp100_ReturnsTrue() => + QsofaCalculator.MeetsCriterion("SYSTOLIC_BP", 100m).Should().BeTrue(); + + [Fact] + public void MeetsCriterion_SystolicBp101_ReturnsFalse() => + QsofaCalculator.MeetsCriterion("SYSTOLIC_BP", 101m).Should().BeFalse(); + + [Fact] + public void MeetsCriterion_Avpu1_ReturnsTrue() => + QsofaCalculator.MeetsCriterion("AVPU", 1m).Should().BeTrue(); + + [Fact] + public void MeetsCriterion_Avpu0_ReturnsFalse() => + QsofaCalculator.MeetsCriterion("AVPU", 0m).Should().BeFalse(); + + [Fact] + public void CountActiveCriteria_TwoOfThree_Returns2() + { + var values = new RedisValue[] { "24", RedisValue.Null, "95" }; + + QsofaCalculator.CountActiveCriteria(values).Should().Be(2); + } +} diff --git a/VigilCareClinicalAPI.Tests/QsofaDetectorTests.cs b/VigilCareClinicalAPI.Tests/QsofaDetectorTests.cs new file mode 100644 index 0000000..4b4147b --- /dev/null +++ b/VigilCareClinicalAPI.Tests/QsofaDetectorTests.cs @@ -0,0 +1,166 @@ +using FluentAssertions; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using StackExchange.Redis; + +[Collection("Integration")] +public class QsofaDetectorTests : IAsyncLifetime +{ + private readonly ApiFixture _fixture; + private Guid _encounterId; + private Guid _patientId; + + public QsofaDetectorTests(ApiFixture fixture) => _fixture = fixture; + + public async Task InitializeAsync() + { + using var scope = _fixture.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await DbResetHelper.ResetAsync(db); + + var patient = new Patient + { + Id = Guid.NewGuid(), Mrn = "MRN-QSOFA-001", FirstName = "qSOFA", LastName = "Test", + DateOfBirth = new DateOnly(1960, 1, 1), Gender = "M", + CreatedAt = DateTimeOffset.UtcNow + }; + var encounter = new Encounter + { + Id = Guid.NewGuid(), PatientId = patient.Id, EncounterType = EncounterType.Inpatient, + Status = EncounterStatus.Active, Department = Department.Icu, + AttendingPhysician = "Dr. qSOFA", AdmittedAt = DateTimeOffset.UtcNow, + CreatedAt = DateTimeOffset.UtcNow + }; + db.Patients.Add(patient); + db.Encounters.Add(encounter); + await db.SaveChangesAsync(); + + _patientId = patient.Id; + _encounterId = encounter.Id; + + var redis = scope.ServiceProvider.GetRequiredService(); + var cache = redis.GetDatabase(); + foreach (var key in QsofaCalculator.AllCriterionKeys(_encounterId)) + await cache.KeyDeleteAsync(key); + } + + public Task DisposeAsync() => Task.CompletedTask; + + [Fact] + public async Task OneCriterionMet_NoAlert() + { + using var scope = _fixture.Services.CreateScope(); + var detector = scope.ServiceProvider.GetRequiredService(); + + var result = await detector.ProcessObservationAsync( + _encounterId, _patientId, "RESP_RATE", 24m); + + result.Outcome.Should().Be(QsofaOutcome.InsufficientCriteria); + result.ActiveCriteria.Should().Be(1); + + var redis = scope.ServiceProvider.GetRequiredService(); + var ttl = await redis.GetDatabase() + .KeyTimeToLiveAsync(QsofaCalculator.CriterionKey(_encounterId, "RESP_RATE")); + ttl.Should().NotBeNull().And.BeGreaterThan(TimeSpan.Zero); + } + + [Fact] + public async Task TwoCriteriaMet_CreatesAlert() + { + using var scope = _fixture.Services.CreateScope(); + var detector = scope.ServiceProvider.GetRequiredService(); + var db = scope.ServiceProvider.GetRequiredService(); + + var r1 = await detector.ProcessObservationAsync( + _encounterId, _patientId, "RESP_RATE", 24m); + r1.Outcome.Should().Be(QsofaOutcome.InsufficientCriteria); + + var r2 = await detector.ProcessObservationAsync( + _encounterId, _patientId, "SYSTOLIC_BP", 95m); + r2.Outcome.Should().Be(QsofaOutcome.AlertCreated); + + var alert = await db.ClinicalAlerts.SingleAsync(); + alert.AlertType.Should().Be(AlertType.QsofaWarning); + alert.Severity.Should().Be(AlertSeverity.Critical); + alert.Status.Should().Be(AlertStatus.Open); + alert.EncounterId.Should().Be(_encounterId); + alert.PatientId.Should().Be(_patientId); + alert.Details.Should().Contain("qSOFA score 2/3"); + + var outbox = await db.OutboxEvents.SingleAsync(); + outbox.Topic.Should().Be("alert.generated"); + outbox.PartitionKey.Should().Be(_encounterId.ToString()); + } + + [Fact] + public async Task CriterionNormalizes_KeyDeleted() + { + using var scope = _fixture.Services.CreateScope(); + var detector = scope.ServiceProvider.GetRequiredService(); + var db = scope.ServiceProvider.GetRequiredService(); + var redis = scope.ServiceProvider.GetRequiredService(); + var cache = redis.GetDatabase(); + + await detector.ProcessObservationAsync(_encounterId, _patientId, "RESP_RATE", 24m); + await detector.ProcessObservationAsync(_encounterId, _patientId, "SYSTOLIC_BP", 95m); + + var result = await detector.ProcessObservationAsync( + _encounterId, _patientId, "RESP_RATE", 18m); + + var respKeyExists = await cache.KeyExistsAsync( + QsofaCalculator.CriterionKey(_encounterId, "RESP_RATE")); + respKeyExists.Should().BeFalse("a normalized respiratory rate must clear the criterion key"); + + var sbpKeyExists = await cache.KeyExistsAsync( + QsofaCalculator.CriterionKey(_encounterId, "SYSTOLIC_BP")); + sbpKeyExists.Should().BeTrue("the other active criterion must remain in Redis"); + + result.Outcome.Should().Be(QsofaOutcome.InsufficientCriteria); + result.ActiveCriteria.Should().Be(1); + + var alert = await db.ClinicalAlerts.SingleAsync(); + alert.Status.Should().Be(AlertStatus.Open, + "the existing alert is not auto-resolved when criteria drop below 2"); + } + + [Fact] + public async Task DuplicateAlert_Idempotent() + { + using var scope = _fixture.Services.CreateScope(); + var detector = scope.ServiceProvider.GetRequiredService(); + var db = scope.ServiceProvider.GetRequiredService(); + + await detector.ProcessObservationAsync(_encounterId, _patientId, "RESP_RATE", 24m); + await detector.ProcessObservationAsync(_encounterId, _patientId, "SYSTOLIC_BP", 95m); + + var r3 = await detector.ProcessObservationAsync( + _encounterId, _patientId, "SYSTOLIC_BP", 95m); + + r3.Outcome.Should().Be(QsofaOutcome.AlertAlreadyOpen); + + var alertCount = await db.ClinicalAlerts.CountAsync(); + alertCount.Should().Be(1, "WHERE NOT EXISTS prevents duplicate QSOFA_WARNING while one is open"); + + var outboxCount = await db.OutboxEvents.CountAsync(); + outboxCount.Should().Be(1, "outbox event must be written exactly once"); + } + + [Fact] + public async Task NonQsofaCode_Ignored() + { + using var scope = _fixture.Services.CreateScope(); + var detector = scope.ServiceProvider.GetRequiredService(); + var redis = scope.ServiceProvider.GetRequiredService(); + + var result = await detector.ProcessObservationAsync( + _encounterId, _patientId, "HEART_RATE", 95m); + + result.Outcome.Should().Be(QsofaOutcome.NotQsofaCode); + + foreach (var key in QsofaCalculator.AllCriterionKeys(_encounterId)) + { + var exists = await redis.GetDatabase().KeyExistsAsync(key); + exists.Should().BeFalse("non-qSOFA codes must not create Redis state"); + } + } +} diff --git a/VigilCareClinicalAPI.Tests/SepsisBundleTests.cs b/VigilCareClinicalAPI.Tests/SepsisBundleTests.cs new file mode 100644 index 0000000..19309e7 --- /dev/null +++ b/VigilCareClinicalAPI.Tests/SepsisBundleTests.cs @@ -0,0 +1,209 @@ +using FluentAssertions; +using Microsoft.EntityFrameworkCore; +using Microsoft.Extensions.DependencyInjection; +using StackExchange.Redis; + +[Collection("Integration")] +public class SepsisBundleTests : IAsyncLifetime +{ + private readonly ApiFixture _fixture; + private Guid _encounterId; + private Guid _patientId; + + public SepsisBundleTests(ApiFixture fixture) => _fixture = fixture; + + public async Task InitializeAsync() + { + using var scope = _fixture.Services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + await DbResetHelper.ResetAsync(db); + + var patient = new Patient + { + Id = Guid.NewGuid(), Mrn = "MRN-BUNDLE-001", FirstName = "Bundle", LastName = "Test", + DateOfBirth = new DateOnly(1965, 3, 15), Gender = "F", + CreatedAt = DateTimeOffset.UtcNow + }; + var encounter = new Encounter + { + Id = Guid.NewGuid(), PatientId = patient.Id, EncounterType = EncounterType.Inpatient, + Status = EncounterStatus.Active, Department = Department.Icu, + AttendingPhysician = "Dr. Bundle", AdmittedAt = DateTimeOffset.UtcNow, + CreatedAt = DateTimeOffset.UtcNow + }; + db.Patients.Add(patient); + db.Encounters.Add(encounter); + await db.SaveChangesAsync(); + + _patientId = patient.Id; + _encounterId = encounter.Id; + + var redis = scope.ServiceProvider.GetRequiredService(); + var cache = redis.GetDatabase(); + foreach (var key in QsofaCalculator.AllCriterionKeys(_encounterId)) + await cache.KeyDeleteAsync(key); + foreach (var key in SirsEvaluator.AllCriterionKeys(_encounterId)) + await cache.KeyDeleteAsync(key); + } + + public Task DisposeAsync() => Task.CompletedTask; + + [Fact] + public async Task QsofaAlert_CreatesBundleWithFourOrders() + { + using var scope = _fixture.Services.CreateScope(); + var detector = scope.ServiceProvider.GetRequiredService(); + var db = scope.ServiceProvider.GetRequiredService(); + + await detector.ProcessObservationAsync(_encounterId, _patientId, "RESP_RATE", 24m); + await detector.ProcessObservationAsync(_encounterId, _patientId, "SYSTOLIC_BP", 95m); + + var bundle = await db.SepsisBundles + .Include(b => b.Elements) + .SingleAsync(b => b.EncounterId == _encounterId); + + bundle.ComplianceStatus.Should().Be(SepsisBundleComplianceStatus.InProgress); + bundle.TriggeringAlertType.Should().Be("QSOFA_WARNING"); + bundle.DeadlineAt.Should().BeCloseTo(bundle.RecognizedAt.AddHours(1), TimeSpan.FromSeconds(5)); + bundle.Elements.Should().HaveCount(4); + + var orders = await db.Orders + .Where(o => o.EncounterId == _encounterId) + .ToListAsync(); + orders.Should().HaveCount(4); + orders.Should().AllSatisfy(o => + { + o.Status.Should().Be(OrderStatus.Pending); + o.Description.Should().StartWith("SEP-1:"); + o.OrderedBy.Should().Be("sepsis-bundle-engine"); + }); + + var bundleOutbox = await db.OutboxEvents + .Where(e => e.Topic == "sepsis.bundle.created") + .SingleAsync(); + bundleOutbox.PartitionKey.Should().Be(_encounterId.ToString()); + } + + [Fact] + public async Task SirsAlert_CreatesBundle() + { + using var scope = _fixture.Services.CreateScope(); + var detector = scope.ServiceProvider.GetRequiredService(); + var db = scope.ServiceProvider.GetRequiredService(); + + await detector.ProcessObservationAsync(_encounterId, _patientId, "HEART_RATE", 95m); + await detector.ProcessObservationAsync(_encounterId, _patientId, "TEMP_C", 38.5m); + + var bundle = await db.SepsisBundles + .Include(b => b.Elements) + .SingleAsync(b => b.EncounterId == _encounterId); + + bundle.TriggeringAlertType.Should().Be("SEPSIS_WARNING"); + bundle.ComplianceStatus.Should().Be(SepsisBundleComplianceStatus.InProgress); + bundle.Elements.Should().HaveCount(4); + } + + [Fact] + public async Task SecondAlert_IdempotentBundle() + { + using var scope = _fixture.Services.CreateScope(); + var qsofaDetector = scope.ServiceProvider.GetRequiredService(); + var sirsDetector = scope.ServiceProvider.GetRequiredService(); + var db = scope.ServiceProvider.GetRequiredService(); + + await qsofaDetector.ProcessObservationAsync(_encounterId, _patientId, "RESP_RATE", 24m); + await qsofaDetector.ProcessObservationAsync(_encounterId, _patientId, "SYSTOLIC_BP", 95m); + + var bundleCountAfterFirst = await db.SepsisBundles.CountAsync(b => b.EncounterId == _encounterId); + bundleCountAfterFirst.Should().Be(1); + + await sirsDetector.ProcessObservationAsync(_encounterId, _patientId, "HEART_RATE", 95m); + await sirsDetector.ProcessObservationAsync(_encounterId, _patientId, "TEMP_C", 38.5m); + + var bundleCount = await db.SepsisBundles.CountAsync(b => b.EncounterId == _encounterId); + bundleCount.Should().Be(1, "a second bundle must not be created while one is IN_PROGRESS"); + + var orderCount = await db.Orders.CountAsync(o => o.EncounterId == _encounterId); + orderCount.Should().Be(4, "no additional orders should be created for the duplicate bundle attempt"); + } + + [Fact] + public async Task OrderResulted_CompletesElement() + { + using var scope = _fixture.Services.CreateScope(); + var detector = scope.ServiceProvider.GetRequiredService(); + var bundleService = scope.ServiceProvider.GetRequiredService(); + var db = scope.ServiceProvider.GetRequiredService(); + + await detector.ProcessObservationAsync(_encounterId, _patientId, "RESP_RATE", 24m); + await detector.ProcessObservationAsync(_encounterId, _patientId, "SYSTOLIC_BP", 95m); + + var lactateElement = await db.SepsisBundleElements + .Include(e => e.Order) + .SingleAsync(e => e.ElementType == SepsisBundleElementType.SerumLactate); + + await bundleService.OnOrderResultedAsync(lactateElement.OrderId!.Value); + + var updated = await db.SepsisBundleElements + .AsNoTracking() + .SingleAsync(e => e.Id == lactateElement.Id); + + updated.Status.Should().Be(SepsisBundleElementStatus.Completed); + updated.CompletedAt.Should().NotBeNull(); + + var bundle = await db.SepsisBundles.AsNoTracking().SingleAsync(); + bundle.ComplianceStatus.Should().Be(SepsisBundleComplianceStatus.InProgress, + "bundle should remain in progress until all 4 elements are completed"); + } + + [Fact] + public async Task AllElementsResulted_BundleCompliant() + { + using var scope = _fixture.Services.CreateScope(); + var detector = scope.ServiceProvider.GetRequiredService(); + var bundleService = scope.ServiceProvider.GetRequiredService(); + var db = scope.ServiceProvider.GetRequiredService(); + + await detector.ProcessObservationAsync(_encounterId, _patientId, "RESP_RATE", 24m); + await detector.ProcessObservationAsync(_encounterId, _patientId, "SYSTOLIC_BP", 95m); + + var elements = await db.SepsisBundleElements.ToListAsync(); + foreach (var element in elements) + await bundleService.OnOrderResultedAsync(element.OrderId!.Value); + + var bundle = await db.SepsisBundles.AsNoTracking().SingleAsync(); + bundle.ComplianceStatus.Should().Be(SepsisBundleComplianceStatus.Compliant); + bundle.CompletedAt.Should().NotBeNull(); + bundle.CompletedAt.Should().BeBefore(bundle.DeadlineAt, + "all elements completed within the 1-hour window"); + + var outboxEvents = await db.OutboxEvents + .Where(e => e.Topic == "sepsis.bundle.updated") + .ToListAsync(); + outboxEvents.Should().HaveCount(4, "one outbox event per element completion"); + } + + [Fact] + public async Task DeadlinePassed_CompletionMarksNonCompliant() + { + using var scope = _fixture.Services.CreateScope(); + var detector = scope.ServiceProvider.GetRequiredService(); + var bundleService = scope.ServiceProvider.GetRequiredService(); + var db = scope.ServiceProvider.GetRequiredService(); + + await detector.ProcessObservationAsync(_encounterId, _patientId, "RESP_RATE", 24m); + await detector.ProcessObservationAsync(_encounterId, _patientId, "SYSTOLIC_BP", 95m); + + var bundle = await db.SepsisBundles.SingleAsync(); + bundle.DeadlineAt = DateTimeOffset.UtcNow.AddHours(-1); + await db.SaveChangesAsync(); + + var elements = await db.SepsisBundleElements.ToListAsync(); + foreach (var element in elements) + await bundleService.OnOrderResultedAsync(element.OrderId!.Value); + + var updated = await db.SepsisBundles.AsNoTracking().SingleAsync(); + updated.ComplianceStatus.Should().Be(SepsisBundleComplianceStatus.NonCompliant); + updated.CompletedAt.Should().NotBeNull(); + } +} diff --git a/VigilCareClinicalAPI/BackgroundServices/ElasticsSearch/EsIndexerService.cs b/VigilCareClinicalAPI/BackgroundServices/ElasticsSearch/EsIndexerService.cs index f2c7ca4..1de5753 100644 --- a/VigilCareClinicalAPI/BackgroundServices/ElasticsSearch/EsIndexerService.cs +++ b/VigilCareClinicalAPI/BackgroundServices/ElasticsSearch/EsIndexerService.cs @@ -47,10 +47,12 @@ public class EsIndexerService : BackgroundService { _kafkaOptions.Topics.ObservationRecorded, _kafkaOptions.Topics.AlertGenerated, - _kafkaOptions.Topics.EncounterStatusChanged + _kafkaOptions.Topics.EncounterStatusChanged, + _kafkaOptions.Topics.SepsisBundleCreated, + _kafkaOptions.Topics.SepsisBundleUpdated }); - _logger.LogInformation("EsIndexerService started. Subscribed to 3 topics."); + _logger.LogInformation("EsIndexerService started. Subscribed to 5 topics."); try { @@ -91,6 +93,10 @@ public class EsIndexerService : BackgroundService HandleObservationRecordedAsync(payload, ct), var t when t == _kafkaOptions.Topics.AlertGenerated => HandleAlertGeneratedAsync(payload, ct), + var t when t == _kafkaOptions.Topics.SepsisBundleCreated => + HandleSepsisBundleEventAsync(payload, ct), + var t when t == _kafkaOptions.Topics.SepsisBundleUpdated => + HandleSepsisBundleEventAsync(payload, ct), _ => Task.CompletedTask }; @@ -260,4 +266,63 @@ public class EsIndexerService : BackgroundService _logger.LogWarning( "Could not update patient_encounters for alert on encounter {Id}", evt.EncounterId); } + + // --- sepsis.bundle.created / sepsis.bundle.updated --- + // Denormalizes bundle status onto the patient_encounters document so department + // acuity dashboards can filter/sort by sepsis bundle compliance state. + private async Task HandleSepsisBundleEventAsync(string payload, CancellationToken ct) + { + using var doc = JsonDocument.Parse(payload); + var root = doc.RootElement; + + var encounterId = root.GetProperty("encounterId").GetString()!; + var complianceStatus = root.TryGetProperty("complianceStatus", out var cs) + ? cs.GetString() ?? "IN_PROGRESS" + : "IN_PROGRESS"; + var deadlineAt = root.TryGetProperty("deadlineAt", out var dl) ? dl.GetString() : null; + + var scriptLines = new List + { + "ctx._source.sepsisBundleStatus = params.status", + "ctx._source.sepsisBundleDeadlineAt = params.deadlineAt" + }; + + var scriptParams = new Dictionary + { + ["status"] = complianceStatus, + ["deadlineAt"] = deadlineAt + }; + + if (root.TryGetProperty("elementStatus", out _)) + { + scriptLines.Add("ctx._source.sepsisBundleElementsCompleted = params.elementsCompleted"); + scriptParams["elementsCompleted"] = root.TryGetProperty("elementsCompleted", out var ec) + ? ec.GetInt32() + : (complianceStatus is "COMPLIANT" or "NON_COMPLIANT" ? 4 : 0); + } + else + { + scriptLines.Add("ctx._source.sepsisBundleElementsCompleted = 0"); + } + + var updateResp = await _elastic.UpdateAsync( + _esOptions.Indices.PatientEncounters, + encounterId, + u => u + .Script(new Script(new InlineScript + { + Source = string.Join(";\n", scriptLines), + Language = ScriptLanguage.Painless, + Params = scriptParams! + })) + .RetryOnConflict(3), + ct); + + if (!updateResp.IsValidResponse && updateResp.Result != Result.NotFound) + _logger.LogWarning( + "Could not update patient_encounters bundle status for encounter {Id}", encounterId); + + _logger.LogDebug("Updated patient_encounters bundle status for encounter {Id} → {Status}", + encounterId, complianceStatus); + } } \ No newline at end of file diff --git a/VigilCareClinicalAPI/BackgroundServices/KafkaTopicProvisioner.cs b/VigilCareClinicalAPI/BackgroundServices/KafkaTopicProvisioner.cs index 2c92cd2..6533fee 100644 --- a/VigilCareClinicalAPI/BackgroundServices/KafkaTopicProvisioner.cs +++ b/VigilCareClinicalAPI/BackgroundServices/KafkaTopicProvisioner.cs @@ -25,7 +25,9 @@ public class KafkaTopicProvisioner : IHostedService _options.Topics.ObservationRecorded, _options.Topics.AlertGenerated, _options.Topics.AlertAcknowledged, - _options.Topics.EncounterStatusChanged + _options.Topics.EncounterStatusChanged, + _options.Topics.SepsisBundleCreated, + _options.Topics.SepsisBundleUpdated }; var specs = topicNames.Select(name => new TopicSpecification diff --git a/VigilCareClinicalAPI/BackgroundServices/SepsisEngineService.cs b/VigilCareClinicalAPI/BackgroundServices/SepsisEngineService.cs index e9995be..459d382 100644 --- a/VigilCareClinicalAPI/BackgroundServices/SepsisEngineService.cs +++ b/VigilCareClinicalAPI/BackgroundServices/SepsisEngineService.cs @@ -54,24 +54,38 @@ public class SepsisEngineService : BackgroundService var evt = JsonSerializer.Deserialize( result.Message.Value, EventJsonOptions)!; - // Create a scope per message — SirsDetector is scoped and - // owns a fresh DbContext for each observation processed. + // Create a scope per message — both detectors are scoped and + // each owns a fresh DbContext when creating alerts. using var scope = _services.CreateScope(); - var detector = scope.ServiceProvider.GetRequiredService(); + var sirsDetector = scope.ServiceProvider.GetRequiredService(); + var qsofaDetector = scope.ServiceProvider.GetRequiredService(); - var outcome = await detector.ProcessObservationAsync( + var sirsOutcome = await sirsDetector.ProcessObservationAsync( evt.EncounterId, evt.PatientId, evt.ObservationCode, evt.Value, stoppingToken); - if (outcome.Outcome == SirsOutcome.AlertCreated) + var qsofaOutcome = await qsofaDetector.ProcessObservationAsync( + evt.EncounterId, + evt.PatientId, + evt.ObservationCode, + evt.Value, + stoppingToken); + + if (sirsOutcome.Outcome == SirsOutcome.AlertCreated) _logger.LogWarning( "SEPSIS_WARNING created via SepsisEngine " + "— encounter={EncounterId} code={Code} value={Value}", evt.EncounterId, evt.ObservationCode, evt.Value); + if (qsofaOutcome.Outcome == QsofaOutcome.AlertCreated) + _logger.LogWarning( + "QSOFA_WARNING created via SepsisEngine " + + "— encounter={EncounterId} code={Code} value={Value}", + evt.EncounterId, evt.ObservationCode, evt.Value); + // Commit only after successful processing. consumer.Commit(result); } diff --git a/VigilCareClinicalAPI/Configuration/KafkaTopicOptions.cs b/VigilCareClinicalAPI/Configuration/KafkaTopicOptions.cs index 091007f..c62ebea 100644 --- a/VigilCareClinicalAPI/Configuration/KafkaTopicOptions.cs +++ b/VigilCareClinicalAPI/Configuration/KafkaTopicOptions.cs @@ -4,4 +4,6 @@ public class KafkaTopicOptions public string AlertGenerated { get; set; } = "alert.generated"; public string AlertAcknowledged { get; set; } = "alert.acknowledged"; public string EncounterStatusChanged { get; set; } = "encounter.status.changed"; + public string SepsisBundleCreated { get; set; } = "sepsis.bundle.created"; + public string SepsisBundleUpdated { get; set; } = "sepsis.bundle.updated"; } \ No newline at end of file diff --git a/VigilCareClinicalAPI/Controllers/SepsisBundlesController.cs b/VigilCareClinicalAPI/Controllers/SepsisBundlesController.cs new file mode 100644 index 0000000..510e34e --- /dev/null +++ b/VigilCareClinicalAPI/Controllers/SepsisBundlesController.cs @@ -0,0 +1,42 @@ +using Microsoft.AspNetCore.Mvc; + +/// +/// Sepsis bundle compliance tracking: current bundle by encounter and bundle detail by id. +/// +[ApiController] +[Produces("application/json")] +public class SepsisBundlesController : ControllerBase +{ + private readonly ISepsisBundleService _bundles; + + public SepsisBundlesController(ISepsisBundleService bundles) => _bundles = bundles; + + /// + /// Returns the current (most recent) sepsis bundle for an encounter with elements and linked orders. + /// + /// Encounter id. + [HttpGet("api/v1/encounters/{encounterId:guid}/sepsis-bundle/current")] + [ProducesResponseType(typeof(ApiResponse), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(ApiResponse), StatusCodes.Status404NotFound)] + public async Task GetCurrentByEncounter(Guid encounterId) + { + var bundle = await _bundles.GetCurrentByEncounterAsync(encounterId); + if (bundle is null) + return NotFound(ApiResponse.Fail(404, "No sepsis bundle exists for this encounter.", "BUNDLE_NOT_FOUND")); + + return Ok(ApiResponse.Ok(bundle)); + } + + /// + /// Returns a sepsis bundle by id with all elements and linked orders. + /// + /// Bundle id. + [HttpGet("api/v1/sepsis-bundles/{id:guid}")] + [ProducesResponseType(typeof(ApiResponse), StatusCodes.Status200OK)] + [ProducesResponseType(typeof(ApiResponse), StatusCodes.Status404NotFound)] + public async Task GetById(Guid id) + { + var bundle = await _bundles.GetByIdAsync(id); + return Ok(ApiResponse.Ok(bundle)); + } +} diff --git a/VigilCareClinicalAPI/Data/AppDbContext.cs b/VigilCareClinicalAPI/Data/AppDbContext.cs index d5af551..8032060 100644 --- a/VigilCareClinicalAPI/Data/AppDbContext.cs +++ b/VigilCareClinicalAPI/Data/AppDbContext.cs @@ -13,6 +13,8 @@ public class AppDbContext : DbContext public DbSet OutboxEvents => Set(); public DbSet ReconciliationAlerts => Set(); public DbSet News2Scores => Set(); + public DbSet SepsisBundles => Set(); + public DbSet SepsisBundleElements => Set(); protected override void OnModelCreating(ModelBuilder modelBuilder) { diff --git a/VigilCareClinicalAPI/Data/Configurations/SepsisBundleConfiguration.cs b/VigilCareClinicalAPI/Data/Configurations/SepsisBundleConfiguration.cs new file mode 100644 index 0000000..89c2323 --- /dev/null +++ b/VigilCareClinicalAPI/Data/Configurations/SepsisBundleConfiguration.cs @@ -0,0 +1,47 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +public class SepsisBundleConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("sepsis_bundles", t => + { + t.HasCheckConstraint("chk_sepsis_bundles_compliance_status", + "compliance_status IN ('IN_PROGRESS', 'COMPLIANT', 'NON_COMPLIANT')"); + }); + + builder.HasKey(b => b.Id); + builder.Property(b => b.Id).HasColumnName("id").HasDefaultValueSql("gen_random_uuid()"); + builder.Property(b => b.EncounterId).HasColumnName("encounter_id").IsRequired(); + builder.Property(b => b.TriggeringAlertId).HasColumnName("triggering_alert_id").IsRequired(); + builder.Property(b => b.TriggeringAlertType) + .HasColumnName("triggering_alert_type") + .HasMaxLength(50) + .IsRequired(); + builder.Property(b => b.RecognizedAt).HasColumnName("recognized_at").IsRequired(); + builder.Property(b => b.DeadlineAt).HasColumnName("deadline_at").IsRequired(); + builder.Property(b => b.ComplianceStatus) + .HasColumnName("compliance_status") + .HasMaxLength(20) + .HasConversion( + v => v.ToDbString(), + v => SepsisBundleComplianceStatusExtensions.FromDbString(v)) + .HasDefaultValueSql("'IN_PROGRESS'") + .HasSentinel((SepsisBundleComplianceStatus)(-1)); + builder.Property(b => b.CompletedAt).HasColumnName("completed_at"); + + builder.HasOne(b => b.Encounter) + .WithMany() + .HasForeignKey(b => b.EncounterId) + .OnDelete(DeleteBehavior.Restrict); + + builder.HasOne(b => b.TriggeringAlert) + .WithMany() + .HasForeignKey(b => b.TriggeringAlertId) + .OnDelete(DeleteBehavior.Restrict); + + builder.HasIndex(b => new { b.EncounterId, b.RecognizedAt }); + builder.HasIndex(b => b.ComplianceStatus); + } +} diff --git a/VigilCareClinicalAPI/Data/Configurations/SepsisBundleElementConfiguration.cs b/VigilCareClinicalAPI/Data/Configurations/SepsisBundleElementConfiguration.cs new file mode 100644 index 0000000..3a99eb4 --- /dev/null +++ b/VigilCareClinicalAPI/Data/Configurations/SepsisBundleElementConfiguration.cs @@ -0,0 +1,50 @@ +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Metadata.Builders; + +public class SepsisBundleElementConfiguration : IEntityTypeConfiguration +{ + public void Configure(EntityTypeBuilder builder) + { + builder.ToTable("sepsis_bundle_elements", t => + { + t.HasCheckConstraint("chk_sepsis_bundle_elements_element_type", + "element_type IN ('BLOOD_CULTURES', 'SERUM_LACTATE', " + + "'BROAD_SPECTRUM_ANTIBIOTICS', 'IV_FLUID_RESUSCITATION')"); + t.HasCheckConstraint("chk_sepsis_bundle_elements_status", + "status IN ('PENDING', 'COMPLETED')"); + }); + + builder.HasKey(e => e.Id); + builder.Property(e => e.Id).HasColumnName("id").HasDefaultValueSql("gen_random_uuid()"); + builder.Property(e => e.BundleId).HasColumnName("bundle_id").IsRequired(); + builder.Property(e => e.ElementType) + .HasColumnName("element_type") + .HasMaxLength(40) + .HasConversion( + v => v.ToDbString(), + v => SepsisBundleElementTypeExtensions.FromDbString(v)) + .IsRequired(); + builder.Property(e => e.Status) + .HasColumnName("status") + .HasMaxLength(20) + .HasConversion( + v => v.ToDbString(), + v => SepsisBundleElementStatusExtensions.FromDbString(v)) + .HasDefaultValueSql("'PENDING'") + .HasSentinel((SepsisBundleElementStatus)(-1)); + builder.Property(e => e.OrderId).HasColumnName("order_id"); + builder.Property(e => e.CompletedAt).HasColumnName("completed_at"); + + builder.HasOne(e => e.Bundle) + .WithMany(b => b.Elements) + .HasForeignKey(e => e.BundleId) + .OnDelete(DeleteBehavior.Cascade); + + builder.HasOne(e => e.Order) + .WithMany() + .HasForeignKey(e => e.OrderId) + .OnDelete(DeleteBehavior.SetNull); + + builder.HasIndex(e => new { e.BundleId, e.ElementType }).IsUnique(); + } +} diff --git a/VigilCareClinicalAPI/Domains/Entities/SepsisBundle.cs b/VigilCareClinicalAPI/Domains/Entities/SepsisBundle.cs new file mode 100644 index 0000000..62b8150 --- /dev/null +++ b/VigilCareClinicalAPI/Domains/Entities/SepsisBundle.cs @@ -0,0 +1,16 @@ +public class SepsisBundle +{ + public Guid Id { get; set; } + public Guid EncounterId { get; set; } + public Guid TriggeringAlertId { get; set; } + public string TriggeringAlertType { get; set; } = null!; + public DateTimeOffset RecognizedAt { get; set; } + public DateTimeOffset DeadlineAt { get; set; } + public SepsisBundleComplianceStatus ComplianceStatus { get; set; } = + SepsisBundleComplianceStatus.InProgress; + public DateTimeOffset? CompletedAt { get; set; } + + public Encounter Encounter { get; set; } = null!; + public ClinicalAlert TriggeringAlert { get; set; } = null!; + public ICollection Elements { get; set; } = new List(); +} diff --git a/VigilCareClinicalAPI/Domains/Entities/SepsisBundleElement.cs b/VigilCareClinicalAPI/Domains/Entities/SepsisBundleElement.cs new file mode 100644 index 0000000..ec99503 --- /dev/null +++ b/VigilCareClinicalAPI/Domains/Entities/SepsisBundleElement.cs @@ -0,0 +1,12 @@ +public class SepsisBundleElement +{ + public Guid Id { get; set; } + public Guid BundleId { get; set; } + public SepsisBundleElementType ElementType { get; set; } + public SepsisBundleElementStatus Status { get; set; } = SepsisBundleElementStatus.Pending; + public Guid? OrderId { get; set; } + public DateTimeOffset? CompletedAt { get; set; } + + public SepsisBundle Bundle { get; set; } = null!; + public Order? Order { get; set; } +} diff --git a/VigilCareClinicalAPI/Domains/Enums/AlertType.cs b/VigilCareClinicalAPI/Domains/Enums/AlertType.cs index d26fed9..a19de16 100644 --- a/VigilCareClinicalAPI/Domains/Enums/AlertType.cs +++ b/VigilCareClinicalAPI/Domains/Enums/AlertType.cs @@ -29,6 +29,8 @@ public enum AlertType News2Emergency, RapidDeterioration, + + QsofaWarning, } public static class AlertTypeExtensions @@ -60,6 +62,7 @@ public static class AlertTypeExtensions AlertType.News2Warning => "NEWS2_WARNING", AlertType.News2Emergency => "NEWS2_EMERGENCY", AlertType.RapidDeterioration => "RAPID_DETERIORATION", + AlertType.QsofaWarning => "QSOFA_WARNING", _ => throw new ArgumentOutOfRangeException(nameof(t)) }; @@ -90,6 +93,7 @@ public static class AlertTypeExtensions "NEWS2_WARNING" => AlertType.News2Warning, "NEWS2_EMERGENCY" => AlertType.News2Emergency, "RAPID_DETERIORATION" => AlertType.RapidDeterioration, + "QSOFA_WARNING" => AlertType.QsofaWarning, _ => throw new ArgumentOutOfRangeException(nameof(v), $"Unknown alert type: '{v}'") }; @@ -136,7 +140,7 @@ public static class AlertTypeExtensions or AlertType.CriticalLactateMmolL or AlertType.CriticalAvpu or AlertType.CriticalGlucoseMgDl => false, AlertType.RapidDeterioration => false, // trajectory alerts are never suppressed - _ => true // all Warning* types and News2Warning + _ => true // all Warning* types, News2Warning, and QsofaWarning }; public static string? ObservationCodeForWarning(this AlertType t) => t switch diff --git a/VigilCareClinicalAPI/Domains/Enums/SepsisBundleComplianceStatus.cs b/VigilCareClinicalAPI/Domains/Enums/SepsisBundleComplianceStatus.cs new file mode 100644 index 0000000..9491eff --- /dev/null +++ b/VigilCareClinicalAPI/Domains/Enums/SepsisBundleComplianceStatus.cs @@ -0,0 +1,25 @@ +public enum SepsisBundleComplianceStatus +{ + InProgress, + Compliant, + NonCompliant +} + +public static class SepsisBundleComplianceStatusExtensions +{ + public static string ToDbString(this SepsisBundleComplianceStatus s) => s switch + { + SepsisBundleComplianceStatus.InProgress => "IN_PROGRESS", + SepsisBundleComplianceStatus.Compliant => "COMPLIANT", + SepsisBundleComplianceStatus.NonCompliant => "NON_COMPLIANT", + _ => throw new ArgumentOutOfRangeException(nameof(s)) + }; + + public static SepsisBundleComplianceStatus FromDbString(string v) => v switch + { + "IN_PROGRESS" => SepsisBundleComplianceStatus.InProgress, + "COMPLIANT" => SepsisBundleComplianceStatus.Compliant, + "NON_COMPLIANT" => SepsisBundleComplianceStatus.NonCompliant, + _ => throw new ArgumentOutOfRangeException(nameof(v), $"Unknown compliance status: '{v}'") + }; +} diff --git a/VigilCareClinicalAPI/Domains/Enums/SepsisBundleElementStatus.cs b/VigilCareClinicalAPI/Domains/Enums/SepsisBundleElementStatus.cs new file mode 100644 index 0000000..2ed787e --- /dev/null +++ b/VigilCareClinicalAPI/Domains/Enums/SepsisBundleElementStatus.cs @@ -0,0 +1,22 @@ +public enum SepsisBundleElementStatus +{ + Pending, + Completed +} + +public static class SepsisBundleElementStatusExtensions +{ + public static string ToDbString(this SepsisBundleElementStatus s) => s switch + { + SepsisBundleElementStatus.Pending => "PENDING", + SepsisBundleElementStatus.Completed => "COMPLETED", + _ => throw new ArgumentOutOfRangeException(nameof(s)) + }; + + public static SepsisBundleElementStatus FromDbString(string v) => v switch + { + "PENDING" => SepsisBundleElementStatus.Pending, + "COMPLETED" => SepsisBundleElementStatus.Completed, + _ => throw new ArgumentOutOfRangeException(nameof(v), $"Unknown bundle element status: '{v}'") + }; +} diff --git a/VigilCareClinicalAPI/Domains/Enums/SepsisBundleElementType.cs b/VigilCareClinicalAPI/Domains/Enums/SepsisBundleElementType.cs new file mode 100644 index 0000000..c7271e4 --- /dev/null +++ b/VigilCareClinicalAPI/Domains/Enums/SepsisBundleElementType.cs @@ -0,0 +1,28 @@ +public enum SepsisBundleElementType +{ + BloodCultures, + SerumLactate, + BroadSpectrumAntibiotics, + IvFluidResuscitation +} + +public static class SepsisBundleElementTypeExtensions +{ + public static string ToDbString(this SepsisBundleElementType t) => t switch + { + SepsisBundleElementType.BloodCultures => "BLOOD_CULTURES", + SepsisBundleElementType.SerumLactate => "SERUM_LACTATE", + SepsisBundleElementType.BroadSpectrumAntibiotics => "BROAD_SPECTRUM_ANTIBIOTICS", + SepsisBundleElementType.IvFluidResuscitation => "IV_FLUID_RESUSCITATION", + _ => throw new ArgumentOutOfRangeException(nameof(t)) + }; + + public static SepsisBundleElementType FromDbString(string v) => v switch + { + "BLOOD_CULTURES" => SepsisBundleElementType.BloodCultures, + "SERUM_LACTATE" => SepsisBundleElementType.SerumLactate, + "BROAD_SPECTRUM_ANTIBIOTICS" => SepsisBundleElementType.BroadSpectrumAntibiotics, + "IV_FLUID_RESUSCITATION" => SepsisBundleElementType.IvFluidResuscitation, + _ => throw new ArgumentOutOfRangeException(nameof(v), $"Unknown bundle element type: '{v}'") + }; +} diff --git a/VigilCareClinicalAPI/Elasticsearch/Documents/PatientEncounterDocument.cs b/VigilCareClinicalAPI/Elasticsearch/Documents/PatientEncounterDocument.cs index 474ad2a..172a8f8 100644 --- a/VigilCareClinicalAPI/Elasticsearch/Documents/PatientEncounterDocument.cs +++ b/VigilCareClinicalAPI/Elasticsearch/Documents/PatientEncounterDocument.cs @@ -12,6 +12,9 @@ public class PatientEncounterDocument public string? AdmissionReason { get; set; } public int OpenAlertCount { get; set; } public int? News2Score { get; set; } - public string? News2RiskLevel { get; set; } + public string? News2RiskLevel { get; set; } public DateTimeOffset? LastObservationAt { get; set; } + public string? SepsisBundleStatus { get; set; } + public int? SepsisBundleElementsCompleted { get; set; } + public DateTimeOffset? SepsisBundleDeadlineAt { get; set; } } \ No newline at end of file diff --git a/VigilCareClinicalAPI/Migrations/20260618140336_AddQsofaWarningAlertType.Designer.cs b/VigilCareClinicalAPI/Migrations/20260618140336_AddQsofaWarningAlertType.Designer.cs new file mode 100644 index 0000000..e96cefd --- /dev/null +++ b/VigilCareClinicalAPI/Migrations/20260618140336_AddQsofaWarningAlertType.Designer.cs @@ -0,0 +1,867 @@ +// +using System; +using Microsoft.EntityFrameworkCore; +using Microsoft.EntityFrameworkCore.Infrastructure; +using Microsoft.EntityFrameworkCore.Migrations; +using Microsoft.EntityFrameworkCore.Storage.ValueConversion; +using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata; + +#nullable disable + +namespace VigilCareClinicalAPI.Migrations +{ + [DbContext(typeof(AppDbContext))] + [Migration("20260618140336_AddQsofaWarningAlertType")] + partial class AddQsofaWarningAlertType + { + /// + protected override void BuildTargetModel(ModelBuilder modelBuilder) + { +#pragma warning disable 612, 618 + modelBuilder + .HasAnnotation("ProductVersion", "8.0.4") + .HasAnnotation("Relational:MaxIdentifierLength", 63); + + NpgsqlModelBuilderExtensions.UseIdentityByDefaultColumns(modelBuilder); + + modelBuilder.Entity("AlertThreshold", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("NOW()"); + + b.Property("CriticalHigh") + .HasColumnType("decimal(10,3)") + .HasColumnName("critical_high"); + + b.Property("CriticalLow") + .HasColumnType("decimal(10,3)") + .HasColumnName("critical_low"); + + b.Property("DisplayName") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)") + .HasColumnName("display_name"); + + b.Property("ObservationCode") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)") + .HasColumnName("observation_code"); + + b.Property("SuppressionWindowMinutes") + .HasColumnType("integer") + .HasColumnName("suppression_window_minutes"); + + b.Property("Unit") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasColumnName("unit"); + + b.Property("WarningHigh") + .HasColumnType("decimal(10,3)") + .HasColumnName("warning_high"); + + b.Property("WarningLow") + .HasColumnType("decimal(10,3)") + .HasColumnName("warning_low"); + + b.HasKey("Id"); + + b.HasIndex("ObservationCode") + .IsUnique(); + + b.ToTable("alert_thresholds", (string)null); + }); + + modelBuilder.Entity("ClinicalAlert", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("AcknowledgedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("acknowledged_at"); + + b.Property("AcknowledgedBy") + .HasMaxLength(200) + .HasColumnType("character varying(200)") + .HasColumnName("acknowledged_by"); + + b.Property("AlertType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)") + .HasColumnName("alert_type"); + + b.Property("Details") + .IsRequired() + .HasColumnType("text") + .HasColumnName("details"); + + b.Property("EncounterId") + .HasColumnType("uuid") + .HasColumnName("encounter_id"); + + b.Property("ObservationId") + .HasColumnType("uuid") + .HasColumnName("observation_id"); + + b.Property("PatientId") + .HasColumnType("uuid") + .HasColumnName("patient_id"); + + b.Property("ResolvedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("resolved_at"); + + b.Property("Severity") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasColumnName("severity"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasColumnName("status") + .HasDefaultValueSql("'OPEN'"); + + b.Property("TriggeredAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("triggered_at") + .HasDefaultValueSql("NOW()"); + + b.HasKey("Id"); + + b.HasIndex("EncounterId", "TriggeredAt"); + + b.HasIndex("PatientId", "TriggeredAt"); + + b.HasIndex("Severity", "TriggeredAt") + .HasFilter("status = 'OPEN'"); + + b.ToTable("clinical_alerts", null, t => + { + t.HasCheckConstraint("chk_clinical_alerts_alert_type", "alert_type IN ('SEPSIS_WARNING', 'CRITICAL_HEART_RATE', 'CRITICAL_TEMP_C', 'CRITICAL_POTASSIUM_MEQ_L', 'CRITICAL_SPO2', 'CRITICAL_RESP_RATE', 'CRITICAL_WBC_K_UL')"); + + t.HasCheckConstraint("chk_clinical_alerts_severity", "severity IN ('WARNING', 'CRITICAL')"); + + t.HasCheckConstraint("chk_clinical_alerts_status", "status IN ('OPEN', 'ACKNOWLEDGED', 'RESOLVED', 'ESCALATED')"); + }); + }); + + modelBuilder.Entity("Encounter", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("AdmissionReason") + .HasMaxLength(500) + .HasColumnType("character varying(500)") + .HasColumnName("admission_reason"); + + b.Property("AdmittedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("admitted_at") + .HasDefaultValueSql("NOW()"); + + b.Property("AttendingPhysician") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)") + .HasColumnName("attending_physician"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("NOW()"); + + b.Property("Department") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("department"); + + b.Property("DischargeDiagnosis") + .HasMaxLength(500) + .HasColumnType("character varying(500)") + .HasColumnName("discharge_diagnosis"); + + b.Property("DischargedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("discharged_at"); + + b.Property("EncounterType") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasColumnName("encounter_type"); + + b.Property("PatientId") + .HasColumnType("uuid") + .HasColumnName("patient_id"); + + b.Property("RoomBed") + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasColumnName("room_bed"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasColumnName("status") + .HasDefaultValueSql("'SCHEDULED'"); + + b.HasKey("Id"); + + b.HasIndex("PatientId", "AdmittedAt"); + + b.HasIndex("Status", "AdmittedAt") + .HasFilter("status = 'ACTIVE'"); + + b.ToTable("encounters", null, t => + { + t.HasCheckConstraint("chk_encounters_department", "department IN ('ICU', 'GENERAL_MEDICINE', 'EMERGENCY', 'CARDIOLOGY', 'SURGERY', 'PEDIATRICS')"); + + t.HasCheckConstraint("chk_encounters_encounter_type", "encounter_type IN ('INPATIENT', 'OUTPATIENT', 'EMERGENCY')"); + + t.HasCheckConstraint("chk_encounters_status", "status IN ('SCHEDULED', 'ACTIVE', 'DISCHARGED', 'CANCELLED')"); + }); + }); + + modelBuilder.Entity("News2Score", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("CalculatedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("calculated_at"); + + b.Property("ConsciousnessScore") + .HasColumnType("integer") + .HasColumnName("consciousness_score"); + + b.Property("EncounterId") + .HasColumnType("uuid") + .HasColumnName("encounter_id"); + + b.Property("HasSingleParamThree") + .HasColumnType("boolean") + .HasColumnName("has_single_param_three"); + + b.Property("HeartRateScore") + .HasColumnType("integer") + .HasColumnName("heart_rate_score"); + + b.Property("PatientId") + .HasColumnType("uuid") + .HasColumnName("patient_id"); + + b.Property("RespRateScore") + .HasColumnType("integer") + .HasColumnName("resp_rate_score"); + + b.Property("RiskLevel") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasColumnName("risk_level"); + + b.Property("Spo2Score") + .HasColumnType("integer") + .HasColumnName("spo2_score"); + + b.Property("SupplementalO2Score") + .HasColumnType("integer") + .HasColumnName("supplemental_o2_score"); + + b.Property("SystolicBpScore") + .HasColumnType("integer") + .HasColumnName("systolic_bp_score"); + + b.Property("TemperatureScore") + .HasColumnType("integer") + .HasColumnName("temperature_score"); + + b.Property("TotalScore") + .HasColumnType("integer") + .HasColumnName("total_score"); + + b.HasKey("Id"); + + b.HasIndex("EncounterId", "CalculatedAt"); + + b.HasIndex("PatientId", "CalculatedAt"); + + b.ToTable("news2_scores", null, t => + { + t.HasCheckConstraint("chk_news2_scores_risk_level", "risk_level IN ('LOW', 'LOW_MEDIUM', 'MEDIUM', 'HIGH')"); + }); + }); + + modelBuilder.Entity("Observation", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("NOW()"); + + b.Property("EncounterId") + .HasColumnType("uuid") + .HasColumnName("encounter_id"); + + b.Property("IdempotencyKey") + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("idempotency_key"); + + b.Property("ObservationCode") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)") + .HasColumnName("observation_code"); + + b.Property("RecordedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("recorded_at"); + + b.Property("Source") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasColumnName("source") + .HasDefaultValueSql("'MANUAL'"); + + b.Property("Unit") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasColumnName("unit"); + + b.Property("Value") + .HasColumnType("decimal(10,3)") + .HasColumnName("value"); + + b.HasKey("Id"); + + b.HasIndex("IdempotencyKey") + .IsUnique() + .HasFilter("idempotency_key IS NOT NULL"); + + b.HasIndex("EncounterId", "ObservationCode", "RecordedAt"); + + b.ToTable("observations", null, t => + { + t.HasCheckConstraint("chk_observations_source", "source IN ('MANUAL', 'DEVICE', 'LAB')"); + }); + }); + + modelBuilder.Entity("Order", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("Description") + .IsRequired() + .HasColumnType("text") + .HasColumnName("description"); + + b.Property("EncounterId") + .HasColumnType("uuid") + .HasColumnName("encounter_id"); + + b.Property("OrderType") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasColumnName("order_type"); + + b.Property("OrderedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("ordered_at") + .HasDefaultValueSql("NOW()"); + + b.Property("OrderedBy") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)") + .HasColumnName("ordered_by"); + + b.Property("ResultSummary") + .HasColumnType("text") + .HasColumnName("result_summary"); + + b.Property("ResultedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("resulted_at"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasColumnName("status") + .HasDefaultValueSql("'PENDING'"); + + b.HasKey("Id"); + + b.HasIndex("EncounterId", "OrderedAt"); + + b.HasIndex("Status", "OrderedAt") + .HasFilter("status IN ('PENDING', 'IN_PROGRESS')"); + + b.ToTable("orders", null, t => + { + t.HasCheckConstraint("chk_orders_order_type", "order_type IN ('LAB', 'IMAGING', 'MEDICATION', 'PROCEDURE')"); + + t.HasCheckConstraint("chk_orders_status", "status IN ('PENDING', 'IN_PROGRESS', 'RESULTED', 'CANCELLED')"); + }); + }); + + modelBuilder.Entity("OutboxEvent", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("NOW()"); + + b.Property("PartitionKey") + .HasMaxLength(36) + .HasColumnType("character varying(36)") + .HasColumnName("partition_key"); + + b.Property("Payload") + .IsRequired() + .HasColumnType("jsonb") + .HasColumnName("payload"); + + b.Property("ProcessedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("processed_at"); + + b.Property("Topic") + .IsRequired() + .HasMaxLength(200) + .HasColumnType("character varying(200)") + .HasColumnName("topic"); + + b.HasKey("Id"); + + b.HasIndex("CreatedAt") + .HasFilter("processed_at IS NULL"); + + b.ToTable("outbox_events", (string)null); + }); + + modelBuilder.Entity("Patient", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("Allergies") + .HasColumnType("text") + .HasColumnName("allergies"); + + b.Property("BloodType") + .HasMaxLength(5) + .HasColumnType("character varying(5)") + .HasColumnName("blood_type"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("NOW()"); + + b.Property("DateOfBirth") + .HasColumnType("date") + .HasColumnName("date_of_birth"); + + b.Property("EmergencyContactName") + .HasMaxLength(200) + .HasColumnType("character varying(200)") + .HasColumnName("emergency_contact_name"); + + b.Property("EmergencyContactPhone") + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasColumnName("emergency_contact_phone"); + + b.Property("FirstName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("first_name"); + + b.Property("Gender") + .IsRequired() + .HasMaxLength(10) + .HasColumnType("character varying(10)") + .HasColumnName("gender"); + + b.Property("LastName") + .IsRequired() + .HasMaxLength(100) + .HasColumnType("character varying(100)") + .HasColumnName("last_name"); + + b.Property("Mrn") + .IsRequired() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasColumnName("mrn"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasDefaultValue("active") + .HasColumnName("status"); + + b.HasKey("Id"); + + b.HasIndex("Mrn") + .IsUnique(); + + b.ToTable("patients", (string)null); + }); + + modelBuilder.Entity("ReconciliationAlert", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("CheckType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)") + .HasColumnName("check_type"); + + b.Property("CreatedAt") + .ValueGeneratedOnAdd() + .HasColumnType("timestamp with time zone") + .HasColumnName("created_at") + .HasDefaultValueSql("NOW()"); + + b.Property("Details") + .IsRequired() + .HasColumnType("text") + .HasColumnName("details"); + + b.Property("EncounterId") + .HasColumnType("uuid") + .HasColumnName("encounter_id"); + + b.Property("PatientId") + .HasColumnType("uuid") + .HasColumnName("patient_id"); + + b.Property("ResolvedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("resolved_at"); + + b.HasKey("Id"); + + b.HasIndex("EncounterId"); + + b.HasIndex("PatientId"); + + b.HasIndex("CheckType", "EncounterId") + .HasFilter("resolved_at IS NULL"); + + b.ToTable("reconciliation_alerts", null, t => + { + t.HasCheckConstraint("chk_reconciliation_alerts_check_type", "check_type IN ('UNACKNOWLEDGED_CRITICAL_ALERT', 'PENDING_ORDER_NO_RESULT', 'ACTIVE_INPATIENT_NO_OBSERVATION')"); + }); + }); + + modelBuilder.Entity("SepsisBundle", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("CompletedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("completed_at"); + + b.Property("ComplianceStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasColumnName("compliance_status") + .HasDefaultValueSql("'IN_PROGRESS'"); + + b.Property("DeadlineAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("deadline_at"); + + b.Property("EncounterId") + .HasColumnType("uuid") + .HasColumnName("encounter_id"); + + b.Property("RecognizedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("recognized_at"); + + b.Property("TriggeringAlertId") + .HasColumnType("uuid") + .HasColumnName("triggering_alert_id"); + + b.Property("TriggeringAlertType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)") + .HasColumnName("triggering_alert_type"); + + b.HasKey("Id"); + + b.HasIndex("ComplianceStatus"); + + b.HasIndex("TriggeringAlertId"); + + b.HasIndex("EncounterId", "RecognizedAt"); + + b.ToTable("sepsis_bundles", null, t => + { + t.HasCheckConstraint("chk_sepsis_bundles_compliance_status", "compliance_status IN ('IN_PROGRESS', 'COMPLIANT', 'NON_COMPLIANT')"); + }); + }); + + modelBuilder.Entity("SepsisBundleElement", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("BundleId") + .HasColumnType("uuid") + .HasColumnName("bundle_id"); + + b.Property("CompletedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("completed_at"); + + b.Property("ElementType") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)") + .HasColumnName("element_type"); + + b.Property("OrderId") + .HasColumnType("uuid") + .HasColumnName("order_id"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasColumnName("status") + .HasDefaultValueSql("'PENDING'"); + + b.HasKey("Id"); + + b.HasIndex("OrderId"); + + b.HasIndex("BundleId", "ElementType") + .IsUnique(); + + b.ToTable("sepsis_bundle_elements", null, t => + { + t.HasCheckConstraint("chk_sepsis_bundle_elements_element_type", "element_type IN ('BLOOD_CULTURES', 'SERUM_LACTATE', 'BROAD_SPECTRUM_ANTIBIOTICS', 'IV_FLUID_RESUSCITATION')"); + + t.HasCheckConstraint("chk_sepsis_bundle_elements_status", "status IN ('PENDING', 'COMPLETED')"); + }); + }); + + modelBuilder.Entity("ClinicalAlert", b => + { + b.HasOne("Encounter", "Encounter") + .WithMany("Alerts") + .HasForeignKey("EncounterId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Encounter"); + }); + + modelBuilder.Entity("Encounter", b => + { + b.HasOne("Patient", "Patient") + .WithMany("Encounters") + .HasForeignKey("PatientId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Patient"); + }); + + modelBuilder.Entity("News2Score", b => + { + b.HasOne("Encounter", "Encounter") + .WithMany() + .HasForeignKey("EncounterId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Encounter"); + }); + + modelBuilder.Entity("Observation", b => + { + b.HasOne("Encounter", "Encounter") + .WithMany("Observations") + .HasForeignKey("EncounterId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Encounter"); + }); + + modelBuilder.Entity("Order", b => + { + b.HasOne("Encounter", "Encounter") + .WithMany("Orders") + .HasForeignKey("EncounterId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Encounter"); + }); + + modelBuilder.Entity("ReconciliationAlert", b => + { + b.HasOne("Encounter", "Encounter") + .WithMany() + .HasForeignKey("EncounterId") + .OnDelete(DeleteBehavior.SetNull); + + b.HasOne("Patient", "Patient") + .WithMany() + .HasForeignKey("PatientId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Encounter"); + + b.Navigation("Patient"); + }); + + modelBuilder.Entity("SepsisBundle", b => + { + b.HasOne("Encounter", "Encounter") + .WithMany() + .HasForeignKey("EncounterId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("ClinicalAlert", "TriggeringAlert") + .WithMany() + .HasForeignKey("TriggeringAlertId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Encounter"); + + b.Navigation("TriggeringAlert"); + }); + + modelBuilder.Entity("SepsisBundleElement", b => + { + b.HasOne("SepsisBundle", "Bundle") + .WithMany("Elements") + .HasForeignKey("BundleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Order", "Order") + .WithMany() + .HasForeignKey("OrderId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Bundle"); + + b.Navigation("Order"); + }); + + modelBuilder.Entity("Encounter", b => + { + b.Navigation("Alerts"); + + b.Navigation("Observations"); + + b.Navigation("Orders"); + }); + + modelBuilder.Entity("Patient", b => + { + b.Navigation("Encounters"); + }); + + modelBuilder.Entity("SepsisBundle", b => + { + b.Navigation("Elements"); + }); +#pragma warning restore 612, 618 + } + } +} diff --git a/VigilCareClinicalAPI/Migrations/20260618140336_AddQsofaWarningAlertType.cs b/VigilCareClinicalAPI/Migrations/20260618140336_AddQsofaWarningAlertType.cs new file mode 100644 index 0000000..05fd1b3 --- /dev/null +++ b/VigilCareClinicalAPI/Migrations/20260618140336_AddQsofaWarningAlertType.cs @@ -0,0 +1,129 @@ +using System; +using Microsoft.EntityFrameworkCore.Migrations; + +#nullable disable + +namespace VigilCareClinicalAPI.Migrations +{ + /// + public partial class AddQsofaWarningAlertType : Migration + { + /// + protected override void Up(MigrationBuilder migrationBuilder) + { + migrationBuilder.Sql(""" + ALTER TABLE clinical_alerts DROP CONSTRAINT chk_clinical_alerts_alert_type; + ALTER TABLE clinical_alerts ADD CONSTRAINT chk_clinical_alerts_alert_type + CHECK (alert_type IN ( + 'SEPSIS_WARNING', + 'CRITICAL_HEART_RATE', 'CRITICAL_TEMP_C', 'CRITICAL_POTASSIUM_MEQ_L', + 'CRITICAL_SPO2', 'CRITICAL_RESP_RATE', 'CRITICAL_WBC_K_UL', + 'CRITICAL_SYSTOLIC_BP', 'CRITICAL_DIASTOLIC_BP', 'CRITICAL_LACTATE_MMOL_L', + 'CRITICAL_AVPU', 'CRITICAL_GLUCOSE_MG_DL', + 'WARNING_HEART_RATE', 'WARNING_TEMP_C', 'WARNING_POTASSIUM_MEQ_L', + 'WARNING_SPO2', 'WARNING_RESP_RATE', 'WARNING_WBC_K_UL', + 'WARNING_SYSTOLIC_BP', 'WARNING_DIASTOLIC_BP', 'WARNING_LACTATE_MMOL_L', + 'WARNING_GLUCOSE_MG_DL', 'NEWS2_WARNING', 'NEWS2_EMERGENCY', + 'RAPID_DETERIORATION', 'QSOFA_WARNING' + )); + """); + + migrationBuilder.CreateTable( + name: "sepsis_bundles", + columns: table => new + { + id = table.Column(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"), + encounter_id = table.Column(type: "uuid", nullable: false), + triggering_alert_id = table.Column(type: "uuid", nullable: false), + triggering_alert_type = table.Column(type: "character varying(50)", maxLength: 50, nullable: false), + recognized_at = table.Column(type: "timestamp with time zone", nullable: false), + deadline_at = table.Column(type: "timestamp with time zone", nullable: false), + compliance_status = table.Column(type: "character varying(20)", maxLength: 20, nullable: false, defaultValueSql: "'IN_PROGRESS'"), + completed_at = table.Column(type: "timestamp with time zone", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_sepsis_bundles", x => x.id); + table.CheckConstraint("chk_sepsis_bundles_compliance_status", "compliance_status IN ('IN_PROGRESS', 'COMPLIANT', 'NON_COMPLIANT')"); + table.ForeignKey( + name: "FK_sepsis_bundles_clinical_alerts_triggering_alert_id", + column: x => x.triggering_alert_id, + principalTable: "clinical_alerts", + principalColumn: "id", + onDelete: ReferentialAction.Restrict); + table.ForeignKey( + name: "FK_sepsis_bundles_encounters_encounter_id", + column: x => x.encounter_id, + principalTable: "encounters", + principalColumn: "id", + onDelete: ReferentialAction.Restrict); + }); + + migrationBuilder.CreateTable( + name: "sepsis_bundle_elements", + columns: table => new + { + id = table.Column(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"), + bundle_id = table.Column(type: "uuid", nullable: false), + element_type = table.Column(type: "character varying(40)", maxLength: 40, nullable: false), + status = table.Column(type: "character varying(20)", maxLength: 20, nullable: false, defaultValueSql: "'PENDING'"), + order_id = table.Column(type: "uuid", nullable: true), + completed_at = table.Column(type: "timestamp with time zone", nullable: true) + }, + constraints: table => + { + table.PrimaryKey("PK_sepsis_bundle_elements", x => x.id); + table.CheckConstraint("chk_sepsis_bundle_elements_element_type", "element_type IN ('BLOOD_CULTURES', 'SERUM_LACTATE', 'BROAD_SPECTRUM_ANTIBIOTICS', 'IV_FLUID_RESUSCITATION')"); + table.CheckConstraint("chk_sepsis_bundle_elements_status", "status IN ('PENDING', 'COMPLETED')"); + table.ForeignKey( + name: "FK_sepsis_bundle_elements_orders_order_id", + column: x => x.order_id, + principalTable: "orders", + principalColumn: "id", + onDelete: ReferentialAction.SetNull); + table.ForeignKey( + name: "FK_sepsis_bundle_elements_sepsis_bundles_bundle_id", + column: x => x.bundle_id, + principalTable: "sepsis_bundles", + principalColumn: "id", + onDelete: ReferentialAction.Cascade); + }); + + migrationBuilder.CreateIndex( + name: "IX_sepsis_bundle_elements_bundle_id_element_type", + table: "sepsis_bundle_elements", + columns: new[] { "bundle_id", "element_type" }, + unique: true); + + migrationBuilder.CreateIndex( + name: "IX_sepsis_bundle_elements_order_id", + table: "sepsis_bundle_elements", + column: "order_id"); + + migrationBuilder.CreateIndex( + name: "IX_sepsis_bundles_compliance_status", + table: "sepsis_bundles", + column: "compliance_status"); + + migrationBuilder.CreateIndex( + name: "IX_sepsis_bundles_encounter_id_recognized_at", + table: "sepsis_bundles", + columns: new[] { "encounter_id", "recognized_at" }); + + migrationBuilder.CreateIndex( + name: "IX_sepsis_bundles_triggering_alert_id", + table: "sepsis_bundles", + column: "triggering_alert_id"); + } + + /// + protected override void Down(MigrationBuilder migrationBuilder) + { + migrationBuilder.DropTable( + name: "sepsis_bundle_elements"); + + migrationBuilder.DropTable( + name: "sepsis_bundles"); + } + } +} diff --git a/VigilCareClinicalAPI/Migrations/AppDbContextModelSnapshot.cs b/VigilCareClinicalAPI/Migrations/AppDbContextModelSnapshot.cs index 57a3bbd..59580ca 100644 --- a/VigilCareClinicalAPI/Migrations/AppDbContextModelSnapshot.cs +++ b/VigilCareClinicalAPI/Migrations/AppDbContextModelSnapshot.cs @@ -626,6 +626,111 @@ namespace VigilCareClinicalAPI.Migrations }); }); + modelBuilder.Entity("SepsisBundle", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("CompletedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("completed_at"); + + b.Property("ComplianceStatus") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasColumnName("compliance_status") + .HasDefaultValueSql("'IN_PROGRESS'"); + + b.Property("DeadlineAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("deadline_at"); + + b.Property("EncounterId") + .HasColumnType("uuid") + .HasColumnName("encounter_id"); + + b.Property("RecognizedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("recognized_at"); + + b.Property("TriggeringAlertId") + .HasColumnType("uuid") + .HasColumnName("triggering_alert_id"); + + b.Property("TriggeringAlertType") + .IsRequired() + .HasMaxLength(50) + .HasColumnType("character varying(50)") + .HasColumnName("triggering_alert_type"); + + b.HasKey("Id"); + + b.HasIndex("ComplianceStatus"); + + b.HasIndex("TriggeringAlertId"); + + b.HasIndex("EncounterId", "RecognizedAt"); + + b.ToTable("sepsis_bundles", null, t => + { + t.HasCheckConstraint("chk_sepsis_bundles_compliance_status", "compliance_status IN ('IN_PROGRESS', 'COMPLIANT', 'NON_COMPLIANT')"); + }); + }); + + modelBuilder.Entity("SepsisBundleElement", b => + { + b.Property("Id") + .ValueGeneratedOnAdd() + .HasColumnType("uuid") + .HasColumnName("id") + .HasDefaultValueSql("gen_random_uuid()"); + + b.Property("BundleId") + .HasColumnType("uuid") + .HasColumnName("bundle_id"); + + b.Property("CompletedAt") + .HasColumnType("timestamp with time zone") + .HasColumnName("completed_at"); + + b.Property("ElementType") + .IsRequired() + .HasMaxLength(40) + .HasColumnType("character varying(40)") + .HasColumnName("element_type"); + + b.Property("OrderId") + .HasColumnType("uuid") + .HasColumnName("order_id"); + + b.Property("Status") + .IsRequired() + .ValueGeneratedOnAdd() + .HasMaxLength(20) + .HasColumnType("character varying(20)") + .HasColumnName("status") + .HasDefaultValueSql("'PENDING'"); + + b.HasKey("Id"); + + b.HasIndex("OrderId"); + + b.HasIndex("BundleId", "ElementType") + .IsUnique(); + + b.ToTable("sepsis_bundle_elements", null, t => + { + t.HasCheckConstraint("chk_sepsis_bundle_elements_element_type", "element_type IN ('BLOOD_CULTURES', 'SERUM_LACTATE', 'BROAD_SPECTRUM_ANTIBIOTICS', 'IV_FLUID_RESUSCITATION')"); + + t.HasCheckConstraint("chk_sepsis_bundle_elements_status", "status IN ('PENDING', 'COMPLETED')"); + }); + }); + modelBuilder.Entity("ClinicalAlert", b => { b.HasOne("Encounter", "Encounter") @@ -698,6 +803,43 @@ namespace VigilCareClinicalAPI.Migrations b.Navigation("Patient"); }); + modelBuilder.Entity("SepsisBundle", b => + { + b.HasOne("Encounter", "Encounter") + .WithMany() + .HasForeignKey("EncounterId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.HasOne("ClinicalAlert", "TriggeringAlert") + .WithMany() + .HasForeignKey("TriggeringAlertId") + .OnDelete(DeleteBehavior.Restrict) + .IsRequired(); + + b.Navigation("Encounter"); + + b.Navigation("TriggeringAlert"); + }); + + modelBuilder.Entity("SepsisBundleElement", b => + { + b.HasOne("SepsisBundle", "Bundle") + .WithMany("Elements") + .HasForeignKey("BundleId") + .OnDelete(DeleteBehavior.Cascade) + .IsRequired(); + + b.HasOne("Order", "Order") + .WithMany() + .HasForeignKey("OrderId") + .OnDelete(DeleteBehavior.SetNull); + + b.Navigation("Bundle"); + + b.Navigation("Order"); + }); + modelBuilder.Entity("Encounter", b => { b.Navigation("Alerts"); @@ -711,6 +853,11 @@ namespace VigilCareClinicalAPI.Migrations { b.Navigation("Encounters"); }); + + modelBuilder.Entity("SepsisBundle", b => + { + b.Navigation("Elements"); + }); #pragma warning restore 612, 618 } } diff --git a/VigilCareClinicalAPI/Models/Records/Sepsis/QsofaOutcome.cs b/VigilCareClinicalAPI/Models/Records/Sepsis/QsofaOutcome.cs new file mode 100644 index 0000000..923150b --- /dev/null +++ b/VigilCareClinicalAPI/Models/Records/Sepsis/QsofaOutcome.cs @@ -0,0 +1,7 @@ +public enum QsofaOutcome +{ + NotQsofaCode, + InsufficientCriteria, + AlertCreated, + AlertAlreadyOpen +} diff --git a/VigilCareClinicalAPI/Models/Records/Sepsis/QsofaResult.cs b/VigilCareClinicalAPI/Models/Records/Sepsis/QsofaResult.cs new file mode 100644 index 0000000..23bf79d --- /dev/null +++ b/VigilCareClinicalAPI/Models/Records/Sepsis/QsofaResult.cs @@ -0,0 +1,11 @@ +// Discriminated result — allows tests and callers to assert the exact outcome +// without inspecting PostgreSQL or Redis directly. +public record QsofaResult(QsofaOutcome Outcome, int ActiveCriteria = 0) +{ + public static readonly QsofaResult NotQsofaCode = new(QsofaOutcome.NotQsofaCode); + public static readonly QsofaResult AlertCreated = new(QsofaOutcome.AlertCreated); + public static readonly QsofaResult AlertAlreadyOpen = new(QsofaOutcome.AlertAlreadyOpen); + + public static QsofaResult InsufficientCriteria(int count) => + new(QsofaOutcome.InsufficientCriteria, count); +} diff --git a/VigilCareClinicalAPI/Observability/Metrics/ClinicalMetrics.cs b/VigilCareClinicalAPI/Observability/Metrics/ClinicalMetrics.cs index a9dfde9..d75b39d 100644 --- a/VigilCareClinicalAPI/Observability/Metrics/ClinicalMetrics.cs +++ b/VigilCareClinicalAPI/Observability/Metrics/ClinicalMetrics.cs @@ -11,7 +11,7 @@ public sealed class ClinicalMetrics "Total observations ingested, labeled by observation code and source.", labelNames: new[] { "observation_code", "source" }); - // Labeled by alert_type (THRESHOLD_BREACH, SEPSIS_WARNING) and severity + // Labeled by alert_type (THRESHOLD_BREACH, SEPSIS_WARNING, QSOFA_WARNING) and severity // (Critical, Warning) so the dashboard can show Critical vs Warning rates separately. public readonly Counter ClinicalAlertsTotal = Metrics.CreateCounter( "clinical_alerts_total", @@ -46,6 +46,15 @@ public sealed class ClinicalMetrics "Total alert suppression windows set after acknowledgment.", labelNames: new[] { "alert_type" }); + public readonly Counter QsofaDetectionsTotal = Metrics.CreateCounter( + "qsofa_detections_total", + "Total QSOFA_WARNING alerts generated by the qSOFA scoring engine."); + + public readonly Counter SepsisBundleComplianceTotal = Metrics.CreateCounter( + "sepsis_bundle_compliance_total", + "Sepsis bundle compliance outcomes.", + labelNames: new[] { "status" }); + // --- Histograms --- // Measures the full ingest transaction: Redis cache lookup + alert evaluation + diff --git a/VigilCareClinicalAPI/Program.cs b/VigilCareClinicalAPI/Program.cs index 2aa0b70..a8ee841 100644 --- a/VigilCareClinicalAPI/Program.cs +++ b/VigilCareClinicalAPI/Program.cs @@ -80,7 +80,10 @@ try builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); + builder.Services.AddScoped(); + builder.Services.AddScoped(); builder.Services.AddScoped(); + builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); builder.Services.AddScoped(); diff --git a/VigilCareClinicalAPI/Sepsis/QsofaCalculator.cs b/VigilCareClinicalAPI/Sepsis/QsofaCalculator.cs new file mode 100644 index 0000000..0a55599 --- /dev/null +++ b/VigilCareClinicalAPI/Sepsis/QsofaCalculator.cs @@ -0,0 +1,34 @@ +using StackExchange.Redis; + +public static class QsofaCalculator +{ + public static readonly IReadOnlyList QsofaCodes = new[] + { + "RESP_RATE", "SYSTOLIC_BP", "AVPU" + }; + + public static readonly IReadOnlySet QsofaCodeSet = + new HashSet(QsofaCodes); + + // qSOFA criteria (Sepsis-3 consensus): + // - Respiratory rate ≥ 22 breaths/min + // - Systolic blood pressure ≤ 100 mmHg + // - Altered mentation: AVPU score ≥ 1 (any non-Alert state) + public static bool MeetsCriterion(string observationCode, decimal value) => + observationCode switch + { + "RESP_RATE" => value >= 22m, + "SYSTOLIC_BP" => value <= 100m, + "AVPU" => value >= 1m, + _ => false + }; + + public static string CriterionKey(Guid encounterId, string code) => + $"qsofa:{encounterId}:{code}"; + + public static RedisKey[] AllCriterionKeys(Guid encounterId) => + QsofaCodes.Select(c => (RedisKey)CriterionKey(encounterId, c)).ToArray(); + + public static int CountActiveCriteria(RedisValue[] values) => + values.Count(v => v.HasValue); +} \ No newline at end of file diff --git a/VigilCareClinicalAPI/Sepsis/QsofaDetector.cs b/VigilCareClinicalAPI/Sepsis/QsofaDetector.cs new file mode 100644 index 0000000..29715b7 --- /dev/null +++ b/VigilCareClinicalAPI/Sepsis/QsofaDetector.cs @@ -0,0 +1,160 @@ +using System.Text.Json; +using Microsoft.EntityFrameworkCore; +using Serilog.Context; +using StackExchange.Redis; + +public class QsofaDetector +{ + // 30 minutes in seconds — same sliding window as SIRS. + private const int QsofaTtlSeconds = 1800; + + private readonly IConnectionMultiplexer _redis; + private readonly IServiceProvider _services; + private readonly ILogger _logger; + private readonly ClinicalMetrics _metrics; + + public QsofaDetector( + IConnectionMultiplexer redis, + IServiceProvider services, + ILogger logger, + ClinicalMetrics metrics) + { + _redis = redis; + _services = services; + _logger = logger; + _metrics = metrics; + } + + public async Task ProcessObservationAsync( + Guid encounterId, + Guid patientId, + string observationCode, + decimal value, + CancellationToken ct = default) + { + if (!QsofaCalculator.QsofaCodeSet.Contains(observationCode)) + return QsofaResult.NotQsofaCode; + + var cache = _redis.GetDatabase(); + var key = QsofaCalculator.CriterionKey(encounterId, observationCode); + + if (QsofaCalculator.MeetsCriterion(observationCode, value)) + { + await cache.StringSetAsync( + key, value.ToString(), TimeSpan.FromSeconds(QsofaTtlSeconds)); + + _logger.LogDebug("qSOFA criterion set: {Key}={Value} (TTL={Ttl}s)", + key, value, QsofaTtlSeconds); + } + else + { + await cache.KeyDeleteAsync(key); + + _logger.LogDebug("qSOFA criterion cleared: {Key}", key); + } + + var allKeys = QsofaCalculator.AllCriterionKeys(encounterId); + var values = await cache.StringGetAsync(allKeys); + var activeCount = QsofaCalculator.CountActiveCriteria(values); + + _logger.LogDebug( + "qSOFA state for encounter {Id}: {Active}/3 criteria active after {Code}={Value}", + encounterId, activeCount, observationCode, value); + + if (activeCount < 2) + return QsofaResult.InsufficientCriteria(activeCount); + + var created = await TryCreateAlertAsync(encounterId, patientId, activeCount, values, ct); + return created ? QsofaResult.AlertCreated : QsofaResult.AlertAlreadyOpen; + } + + private async Task TryCreateAlertAsync( + Guid encounterId, + Guid patientId, + int activeCount, + RedisValue[] criterionValues, + CancellationToken ct) + { + using var scope = _services.CreateScope(); + var db = scope.ServiceProvider.GetRequiredService(); + + await using var tx = await db.Database.BeginTransactionAsync(ct); + + var alertId = Guid.NewGuid(); + var triggeredAt = DateTimeOffset.UtcNow; + var details = BuildDetails(activeCount, criterionValues); + + var affected = await db.Database.ExecuteSqlInterpolatedAsync($""" + INSERT INTO clinical_alerts + (id, encounter_id, patient_id, alert_type, severity, details, status, triggered_at) + SELECT {alertId}, {encounterId}, {patientId}, + 'QSOFA_WARNING', 'CRITICAL', {details}, 'OPEN', {triggeredAt} + WHERE NOT EXISTS ( + SELECT 1 FROM clinical_alerts + WHERE encounter_id = {encounterId} + AND alert_type = 'QSOFA_WARNING' + AND status IN ('OPEN', 'ESCALATED') + ) + """, ct); + + if (affected == 0) + { + await tx.RollbackAsync(ct); + _logger.LogDebug( + "QSOFA_WARNING already open for encounter {Id} — no new alert", encounterId); + return false; + } + + db.OutboxEvents.Add(new OutboxEvent + { + Id = Guid.NewGuid(), + Topic = "alert.generated", + Payload = JsonSerializer.Serialize(new + { + alertId, + encounterId, + patientId, + alertType = AlertType.QsofaWarning.ToDbString(), + severity = "Critical", + details, + triggeredAt, + partitionKey = encounterId.ToString() + }), + PartitionKey = encounterId.ToString(), + CreatedAt = DateTimeOffset.UtcNow + }); + + await db.SaveChangesAsync(ct); + await tx.CommitAsync(ct); + + _metrics.QsofaDetectionsTotal.Inc(); + _metrics.ClinicalAlertsTotal + .WithLabels(AlertType.QsofaWarning.ToDbString(), AlertSeverity.Critical.ToDbString()) + .Inc(); + + using (LogContext.PushProperty("EncounterId", encounterId)) + using (LogContext.PushProperty("PatientId", patientId)) + { + _logger.LogWarning( + "QSOFA_WARNING created. ActiveCriteriaCount={Count} AlertId={AlertId}", + activeCount, alertId); + } + + var handler = scope.ServiceProvider.GetRequiredService(); + await handler.OnSepsisAlertCreatedAsync(encounterId, alertId, AlertType.QsofaWarning, ct); + + return true; + } + + private static string BuildDetails(int activeCount, RedisValue[] values) + { + var activeParts = new List(); + for (var i = 0; i < QsofaCalculator.QsofaCodes.Count; i++) + { + if (values[i].HasValue) + activeParts.Add($"{QsofaCalculator.QsofaCodes[i]}={values[i]}"); + } + + return $"qSOFA score {activeCount}/3: {string.Join(", ", activeParts)}"; + } +} diff --git a/VigilCareClinicalAPI/Sepsis/SepsisAlertHandler.cs b/VigilCareClinicalAPI/Sepsis/SepsisAlertHandler.cs new file mode 100644 index 0000000..42fee61 --- /dev/null +++ b/VigilCareClinicalAPI/Sepsis/SepsisAlertHandler.cs @@ -0,0 +1,22 @@ +public class SepsisAlertHandler +{ + private readonly ISepsisBundleService _bundleService; + private readonly ILogger _logger; + + public SepsisAlertHandler(ISepsisBundleService bundleService, ILogger logger) + { + _bundleService = bundleService; + _logger = logger; + } + + public async Task OnSepsisAlertCreatedAsync( + Guid encounterId, Guid alertId, AlertType alertType, CancellationToken ct) + { + var bundle = await _bundleService.TryCreateBundleAsync(encounterId, alertId, alertType, ct); + + if (bundle is not null) + _logger.LogInformation( + "Sepsis bundle {BundleId} created for encounter {EncounterId} (trigger={AlertType})", + bundle.Id, encounterId, alertType.ToDbString()); + } +} diff --git a/VigilCareClinicalAPI/Sepsis/SirsDetector.cs b/VigilCareClinicalAPI/Sepsis/SirsDetector.cs index 8305cbe..019ef65 100644 --- a/VigilCareClinicalAPI/Sepsis/SirsDetector.cs +++ b/VigilCareClinicalAPI/Sepsis/SirsDetector.cs @@ -169,6 +169,9 @@ public class SirsDetector activeCount, alertId); } + var handler = scope.ServiceProvider.GetRequiredService(); + await handler.OnSepsisAlertCreatedAsync(encounterId, alertId, AlertType.SepsisWarning, ct); + return true; } } \ No newline at end of file diff --git a/VigilCareClinicalAPI/Services/Interfaces/ISepsisBundleService.cs b/VigilCareClinicalAPI/Services/Interfaces/ISepsisBundleService.cs new file mode 100644 index 0000000..a0e2e64 --- /dev/null +++ b/VigilCareClinicalAPI/Services/Interfaces/ISepsisBundleService.cs @@ -0,0 +1,8 @@ +public interface ISepsisBundleService +{ + Task TryCreateBundleAsync( + Guid encounterId, Guid triggeringAlertId, AlertType alertType, CancellationToken ct = default); + Task GetCurrentByEncounterAsync(Guid encounterId); + Task GetByIdAsync(Guid id); + Task OnOrderResultedAsync(Guid orderId, CancellationToken ct = default); +} \ No newline at end of file diff --git a/VigilCareClinicalAPI/Services/OrderService.cs b/VigilCareClinicalAPI/Services/OrderService.cs index 5ca112e..ba4f9d7 100644 --- a/VigilCareClinicalAPI/Services/OrderService.cs +++ b/VigilCareClinicalAPI/Services/OrderService.cs @@ -11,8 +11,13 @@ public class OrderService : IOrderService }; private readonly AppDbContext _db; + private readonly IServiceProvider _serviceProvider; - public OrderService(AppDbContext db) => _db = db; + public OrderService(AppDbContext db, IServiceProvider serviceProvider) + { + _db = db; + _serviceProvider = serviceProvider; + } public async Task CreateAsync(Guid encounterId, CreateOrderRequest req) { @@ -109,6 +114,8 @@ public class OrderService : IOrderService order.ResultSummary = req.ResultSummary; await _db.SaveChangesAsync(); + var bundleService = _serviceProvider.GetRequiredService(); + await bundleService.OnOrderResultedAsync(order.Id); return order; } } \ No newline at end of file diff --git a/VigilCareClinicalAPI/Services/SepsisBundleService.cs b/VigilCareClinicalAPI/Services/SepsisBundleService.cs new file mode 100644 index 0000000..9c4b9f2 --- /dev/null +++ b/VigilCareClinicalAPI/Services/SepsisBundleService.cs @@ -0,0 +1,160 @@ +using System.Text.Json; +using Microsoft.EntityFrameworkCore; + +public class SepsisBundleService : ISepsisBundleService +{ + private readonly AppDbContext _db; + private readonly IOrderService _orderService; + private readonly ClinicalMetrics _metrics; + + public SepsisBundleService(AppDbContext db, IOrderService orderService, ClinicalMetrics metrics) + { + _db = db; + _orderService = orderService; + _metrics = metrics; + } + + public async Task TryCreateBundleAsync( + Guid encounterId, Guid triggeringAlertId, AlertType alertType, CancellationToken ct = default) + { + var exists = await _db.SepsisBundles + .AnyAsync(b => b.EncounterId == encounterId + && b.ComplianceStatus == SepsisBundleComplianceStatus.InProgress, ct); + + if (exists) + return null; + + var recognizedAt = DateTimeOffset.UtcNow; + var bundle = new SepsisBundle + { + Id = Guid.NewGuid(), + EncounterId = encounterId, + TriggeringAlertId = triggeringAlertId, + TriggeringAlertType = alertType.ToDbString(), + RecognizedAt = recognizedAt, + DeadlineAt = recognizedAt.AddHours(1), + ComplianceStatus = SepsisBundleComplianceStatus.InProgress + }; + + var elementDefs = new (SepsisBundleElementType Type, OrderType OrderType, string Description)[] + { + (SepsisBundleElementType.BloodCultures, OrderType.Lab, "SEP-1: Blood cultures"), + (SepsisBundleElementType.SerumLactate, OrderType.Lab, "SEP-1: Serum lactate"), + (SepsisBundleElementType.BroadSpectrumAntibiotics, OrderType.Medication, "SEP-1: Broad-spectrum antibiotics"), + (SepsisBundleElementType.IvFluidResuscitation, OrderType.Procedure, "SEP-1: IV fluid bolus"), + }; + + foreach (var (elementType, orderType, description) in elementDefs) + { + var order = await _orderService.CreateAsync(encounterId, new CreateOrderRequest( + orderType, description, "sepsis-bundle-engine")); + + bundle.Elements.Add(new SepsisBundleElement + { + Id = Guid.NewGuid(), + ElementType = elementType, + Status = SepsisBundleElementStatus.Pending, + OrderId = order.Id + }); + } + + _db.SepsisBundles.Add(bundle); + + _db.OutboxEvents.Add(new OutboxEvent + { + Id = Guid.NewGuid(), + Topic = "sepsis.bundle.created", + Payload = JsonSerializer.Serialize(new + { + bundleId = bundle.Id, + encounterId, + triggeringAlertId, + triggeringAlertType = alertType.ToDbString(), + recognizedAt, + deadlineAt = bundle.DeadlineAt, + partitionKey = encounterId.ToString() + }), + PartitionKey = encounterId.ToString(), + CreatedAt = DateTimeOffset.UtcNow + }); + + await _db.SaveChangesAsync(ct); + return bundle; + } + + public async Task GetCurrentByEncounterAsync(Guid encounterId) + { + return await _db.SepsisBundles + .AsNoTracking() + .Include(b => b.Elements) + .ThenInclude(e => e.Order) + .Where(b => b.EncounterId == encounterId) + .OrderByDescending(b => b.RecognizedAt) + .FirstOrDefaultAsync(); + } + + public async Task GetByIdAsync(Guid id) + { + var bundle = await _db.SepsisBundles + .AsNoTracking() + .Include(b => b.Elements) + .ThenInclude(e => e.Order) + .FirstOrDefaultAsync(b => b.Id == id); + + if (bundle is null) + throw new NotFoundException("Sepsis bundle not found.", "BUNDLE_NOT_FOUND"); + + return bundle; + } + + public async Task OnOrderResultedAsync(Guid orderId, CancellationToken ct = default) + { + var element = await _db.SepsisBundleElements + .Include(e => e.Bundle) + .FirstOrDefaultAsync(e => e.OrderId == orderId, ct); + + if (element is null || element.Status == SepsisBundleElementStatus.Completed) + return; + + element.Status = SepsisBundleElementStatus.Completed; + element.CompletedAt = DateTimeOffset.UtcNow; + + var bundle = element.Bundle; + var allComplete = await _db.SepsisBundleElements + .Where(e => e.BundleId == bundle.Id && e.Id != element.Id) + .AllAsync(e => e.Status == SepsisBundleElementStatus.Completed, ct); + + if (allComplete) + { + bundle.CompletedAt = DateTimeOffset.UtcNow; + bundle.ComplianceStatus = bundle.CompletedAt <= bundle.DeadlineAt + ? SepsisBundleComplianceStatus.Compliant + : SepsisBundleComplianceStatus.NonCompliant; + + _metrics.SepsisBundleComplianceTotal + .WithLabels(bundle.ComplianceStatus.ToDbString()).Inc(); + } + + _db.OutboxEvents.Add(new OutboxEvent + { + Id = Guid.NewGuid(), + Topic = "sepsis.bundle.updated", + Payload = JsonSerializer.Serialize(new + { + bundleId = bundle.Id, + encounterId = bundle.EncounterId, + elementId = element.Id, + elementType = element.ElementType.ToDbString(), + elementStatus = element.Status.ToDbString(), + complianceStatus = bundle.ComplianceStatus.ToDbString(), + completedAt = element.CompletedAt, + partitionKey = bundle.EncounterId.ToString() + }), + PartitionKey = bundle.EncounterId.ToString(), + CreatedAt = DateTimeOffset.UtcNow + }); + + await _db.SaveChangesAsync(ct); + } + +}