feature: qSOFA Scoring & Sepsis Bundle Compliance

This commit is contained in:
voltsrage
2026-06-18 22:52:43 +08:00
parent 3c54feb38a
commit 4b46c09f90
34 changed files with 2351 additions and 18 deletions
@@ -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<string>
{
"ctx._source.sepsisBundleStatus = params.status",
"ctx._source.sepsisBundleDeadlineAt = params.deadlineAt"
};
var scriptParams = new Dictionary<string, object?>
{
["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<PatientEncounterDocument, object>(
_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);
}
}
@@ -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
@@ -54,24 +54,38 @@ public class SepsisEngineService : BackgroundService
var evt = JsonSerializer.Deserialize<SepsisObservationEvent>(
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<SirsDetector>();
var sirsDetector = scope.ServiceProvider.GetRequiredService<SirsDetector>();
var qsofaDetector = scope.ServiceProvider.GetRequiredService<QsofaDetector>();
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);
}
@@ -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";
}
@@ -0,0 +1,42 @@
using Microsoft.AspNetCore.Mvc;
/// <summary>
/// Sepsis bundle compliance tracking: current bundle by encounter and bundle detail by id.
/// </summary>
[ApiController]
[Produces("application/json")]
public class SepsisBundlesController : ControllerBase
{
private readonly ISepsisBundleService _bundles;
public SepsisBundlesController(ISepsisBundleService bundles) => _bundles = bundles;
/// <summary>
/// Returns the current (most recent) sepsis bundle for an encounter with elements and linked orders.
/// </summary>
/// <param name="encounterId">Encounter id.</param>
[HttpGet("api/v1/encounters/{encounterId:guid}/sepsis-bundle/current")]
[ProducesResponseType(typeof(ApiResponse<SepsisBundle>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetCurrentByEncounter(Guid encounterId)
{
var bundle = await _bundles.GetCurrentByEncounterAsync(encounterId);
if (bundle is null)
return NotFound(ApiResponse<object>.Fail(404, "No sepsis bundle exists for this encounter.", "BUNDLE_NOT_FOUND"));
return Ok(ApiResponse<SepsisBundle>.Ok(bundle));
}
/// <summary>
/// Returns a sepsis bundle by id with all elements and linked orders.
/// </summary>
/// <param name="id">Bundle id.</param>
[HttpGet("api/v1/sepsis-bundles/{id:guid}")]
[ProducesResponseType(typeof(ApiResponse<SepsisBundle>), StatusCodes.Status200OK)]
[ProducesResponseType(typeof(ApiResponse<object>), StatusCodes.Status404NotFound)]
public async Task<IActionResult> GetById(Guid id)
{
var bundle = await _bundles.GetByIdAsync(id);
return Ok(ApiResponse<SepsisBundle>.Ok(bundle));
}
}
@@ -13,6 +13,8 @@ public class AppDbContext : DbContext
public DbSet<OutboxEvent> OutboxEvents => Set<OutboxEvent>();
public DbSet<ReconciliationAlert> ReconciliationAlerts => Set<ReconciliationAlert>();
public DbSet<News2Score> News2Scores => Set<News2Score>();
public DbSet<SepsisBundle> SepsisBundles => Set<SepsisBundle>();
public DbSet<SepsisBundleElement> SepsisBundleElements => Set<SepsisBundleElement>();
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
@@ -0,0 +1,47 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
public class SepsisBundleConfiguration : IEntityTypeConfiguration<SepsisBundle>
{
public void Configure(EntityTypeBuilder<SepsisBundle> 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);
}
}
@@ -0,0 +1,50 @@
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
public class SepsisBundleElementConfiguration : IEntityTypeConfiguration<SepsisBundleElement>
{
public void Configure(EntityTypeBuilder<SepsisBundleElement> 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();
}
}
@@ -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<SepsisBundleElement> Elements { get; set; } = new List<SepsisBundleElement>();
}
@@ -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; }
}
@@ -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
@@ -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}'")
};
}
@@ -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}'")
};
}
@@ -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}'")
};
}
@@ -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; }
}
@@ -0,0 +1,867 @@
// <auto-generated />
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
{
/// <inheritdoc />
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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid")
.HasColumnName("id")
.HasDefaultValueSql("gen_random_uuid()");
b.Property<DateTimeOffset>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("timestamp with time zone")
.HasColumnName("created_at")
.HasDefaultValueSql("NOW()");
b.Property<decimal?>("CriticalHigh")
.HasColumnType("decimal(10,3)")
.HasColumnName("critical_high");
b.Property<decimal?>("CriticalLow")
.HasColumnType("decimal(10,3)")
.HasColumnName("critical_low");
b.Property<string>("DisplayName")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)")
.HasColumnName("display_name");
b.Property<string>("ObservationCode")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("character varying(50)")
.HasColumnName("observation_code");
b.Property<int?>("SuppressionWindowMinutes")
.HasColumnType("integer")
.HasColumnName("suppression_window_minutes");
b.Property<string>("Unit")
.IsRequired()
.HasMaxLength(20)
.HasColumnType("character varying(20)")
.HasColumnName("unit");
b.Property<decimal?>("WarningHigh")
.HasColumnType("decimal(10,3)")
.HasColumnName("warning_high");
b.Property<decimal?>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid")
.HasColumnName("id")
.HasDefaultValueSql("gen_random_uuid()");
b.Property<DateTimeOffset?>("AcknowledgedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("acknowledged_at");
b.Property<string>("AcknowledgedBy")
.HasMaxLength(200)
.HasColumnType("character varying(200)")
.HasColumnName("acknowledged_by");
b.Property<string>("AlertType")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("character varying(50)")
.HasColumnName("alert_type");
b.Property<string>("Details")
.IsRequired()
.HasColumnType("text")
.HasColumnName("details");
b.Property<Guid>("EncounterId")
.HasColumnType("uuid")
.HasColumnName("encounter_id");
b.Property<Guid?>("ObservationId")
.HasColumnType("uuid")
.HasColumnName("observation_id");
b.Property<Guid>("PatientId")
.HasColumnType("uuid")
.HasColumnName("patient_id");
b.Property<DateTimeOffset?>("ResolvedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("resolved_at");
b.Property<string>("Severity")
.IsRequired()
.HasMaxLength(20)
.HasColumnType("character varying(20)")
.HasColumnName("severity");
b.Property<string>("Status")
.IsRequired()
.ValueGeneratedOnAdd()
.HasMaxLength(20)
.HasColumnType("character varying(20)")
.HasColumnName("status")
.HasDefaultValueSql("'OPEN'");
b.Property<DateTimeOffset>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid")
.HasColumnName("id")
.HasDefaultValueSql("gen_random_uuid()");
b.Property<string>("AdmissionReason")
.HasMaxLength(500)
.HasColumnType("character varying(500)")
.HasColumnName("admission_reason");
b.Property<DateTimeOffset>("AdmittedAt")
.ValueGeneratedOnAdd()
.HasColumnType("timestamp with time zone")
.HasColumnName("admitted_at")
.HasDefaultValueSql("NOW()");
b.Property<string>("AttendingPhysician")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)")
.HasColumnName("attending_physician");
b.Property<DateTimeOffset>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("timestamp with time zone")
.HasColumnName("created_at")
.HasDefaultValueSql("NOW()");
b.Property<string>("Department")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("character varying(100)")
.HasColumnName("department");
b.Property<string>("DischargeDiagnosis")
.HasMaxLength(500)
.HasColumnType("character varying(500)")
.HasColumnName("discharge_diagnosis");
b.Property<DateTimeOffset?>("DischargedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("discharged_at");
b.Property<string>("EncounterType")
.IsRequired()
.HasMaxLength(20)
.HasColumnType("character varying(20)")
.HasColumnName("encounter_type");
b.Property<Guid>("PatientId")
.HasColumnType("uuid")
.HasColumnName("patient_id");
b.Property<string>("RoomBed")
.HasMaxLength(20)
.HasColumnType("character varying(20)")
.HasColumnName("room_bed");
b.Property<string>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid")
.HasColumnName("id")
.HasDefaultValueSql("gen_random_uuid()");
b.Property<DateTimeOffset>("CalculatedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("calculated_at");
b.Property<int>("ConsciousnessScore")
.HasColumnType("integer")
.HasColumnName("consciousness_score");
b.Property<Guid>("EncounterId")
.HasColumnType("uuid")
.HasColumnName("encounter_id");
b.Property<bool>("HasSingleParamThree")
.HasColumnType("boolean")
.HasColumnName("has_single_param_three");
b.Property<int>("HeartRateScore")
.HasColumnType("integer")
.HasColumnName("heart_rate_score");
b.Property<Guid>("PatientId")
.HasColumnType("uuid")
.HasColumnName("patient_id");
b.Property<int>("RespRateScore")
.HasColumnType("integer")
.HasColumnName("resp_rate_score");
b.Property<string>("RiskLevel")
.IsRequired()
.HasMaxLength(20)
.HasColumnType("character varying(20)")
.HasColumnName("risk_level");
b.Property<int>("Spo2Score")
.HasColumnType("integer")
.HasColumnName("spo2_score");
b.Property<int>("SupplementalO2Score")
.HasColumnType("integer")
.HasColumnName("supplemental_o2_score");
b.Property<int>("SystolicBpScore")
.HasColumnType("integer")
.HasColumnName("systolic_bp_score");
b.Property<int>("TemperatureScore")
.HasColumnType("integer")
.HasColumnName("temperature_score");
b.Property<int>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid")
.HasColumnName("id")
.HasDefaultValueSql("gen_random_uuid()");
b.Property<DateTimeOffset>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("timestamp with time zone")
.HasColumnName("created_at")
.HasDefaultValueSql("NOW()");
b.Property<Guid>("EncounterId")
.HasColumnType("uuid")
.HasColumnName("encounter_id");
b.Property<string>("IdempotencyKey")
.HasMaxLength(100)
.HasColumnType("character varying(100)")
.HasColumnName("idempotency_key");
b.Property<string>("ObservationCode")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("character varying(50)")
.HasColumnName("observation_code");
b.Property<DateTimeOffset>("RecordedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("recorded_at");
b.Property<string>("Source")
.IsRequired()
.ValueGeneratedOnAdd()
.HasMaxLength(20)
.HasColumnType("character varying(20)")
.HasColumnName("source")
.HasDefaultValueSql("'MANUAL'");
b.Property<string>("Unit")
.IsRequired()
.HasMaxLength(20)
.HasColumnType("character varying(20)")
.HasColumnName("unit");
b.Property<decimal>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid")
.HasColumnName("id")
.HasDefaultValueSql("gen_random_uuid()");
b.Property<string>("Description")
.IsRequired()
.HasColumnType("text")
.HasColumnName("description");
b.Property<Guid>("EncounterId")
.HasColumnType("uuid")
.HasColumnName("encounter_id");
b.Property<string>("OrderType")
.IsRequired()
.HasMaxLength(20)
.HasColumnType("character varying(20)")
.HasColumnName("order_type");
b.Property<DateTimeOffset>("OrderedAt")
.ValueGeneratedOnAdd()
.HasColumnType("timestamp with time zone")
.HasColumnName("ordered_at")
.HasDefaultValueSql("NOW()");
b.Property<string>("OrderedBy")
.IsRequired()
.HasMaxLength(200)
.HasColumnType("character varying(200)")
.HasColumnName("ordered_by");
b.Property<string>("ResultSummary")
.HasColumnType("text")
.HasColumnName("result_summary");
b.Property<DateTimeOffset?>("ResultedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("resulted_at");
b.Property<string>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid")
.HasColumnName("id")
.HasDefaultValueSql("gen_random_uuid()");
b.Property<DateTimeOffset>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("timestamp with time zone")
.HasColumnName("created_at")
.HasDefaultValueSql("NOW()");
b.Property<string>("PartitionKey")
.HasMaxLength(36)
.HasColumnType("character varying(36)")
.HasColumnName("partition_key");
b.Property<string>("Payload")
.IsRequired()
.HasColumnType("jsonb")
.HasColumnName("payload");
b.Property<DateTimeOffset?>("ProcessedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("processed_at");
b.Property<string>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid")
.HasColumnName("id")
.HasDefaultValueSql("gen_random_uuid()");
b.Property<string>("Allergies")
.HasColumnType("text")
.HasColumnName("allergies");
b.Property<string>("BloodType")
.HasMaxLength(5)
.HasColumnType("character varying(5)")
.HasColumnName("blood_type");
b.Property<DateTimeOffset>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("timestamp with time zone")
.HasColumnName("created_at")
.HasDefaultValueSql("NOW()");
b.Property<DateOnly>("DateOfBirth")
.HasColumnType("date")
.HasColumnName("date_of_birth");
b.Property<string>("EmergencyContactName")
.HasMaxLength(200)
.HasColumnType("character varying(200)")
.HasColumnName("emergency_contact_name");
b.Property<string>("EmergencyContactPhone")
.HasMaxLength(20)
.HasColumnType("character varying(20)")
.HasColumnName("emergency_contact_phone");
b.Property<string>("FirstName")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("character varying(100)")
.HasColumnName("first_name");
b.Property<string>("Gender")
.IsRequired()
.HasMaxLength(10)
.HasColumnType("character varying(10)")
.HasColumnName("gender");
b.Property<string>("LastName")
.IsRequired()
.HasMaxLength(100)
.HasColumnType("character varying(100)")
.HasColumnName("last_name");
b.Property<string>("Mrn")
.IsRequired()
.HasMaxLength(20)
.HasColumnType("character varying(20)")
.HasColumnName("mrn");
b.Property<string>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid")
.HasColumnName("id")
.HasDefaultValueSql("gen_random_uuid()");
b.Property<string>("CheckType")
.IsRequired()
.HasMaxLength(50)
.HasColumnType("character varying(50)")
.HasColumnName("check_type");
b.Property<DateTimeOffset>("CreatedAt")
.ValueGeneratedOnAdd()
.HasColumnType("timestamp with time zone")
.HasColumnName("created_at")
.HasDefaultValueSql("NOW()");
b.Property<string>("Details")
.IsRequired()
.HasColumnType("text")
.HasColumnName("details");
b.Property<Guid?>("EncounterId")
.HasColumnType("uuid")
.HasColumnName("encounter_id");
b.Property<Guid?>("PatientId")
.HasColumnType("uuid")
.HasColumnName("patient_id");
b.Property<DateTimeOffset?>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid")
.HasColumnName("id")
.HasDefaultValueSql("gen_random_uuid()");
b.Property<DateTimeOffset?>("CompletedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("completed_at");
b.Property<string>("ComplianceStatus")
.IsRequired()
.ValueGeneratedOnAdd()
.HasMaxLength(20)
.HasColumnType("character varying(20)")
.HasColumnName("compliance_status")
.HasDefaultValueSql("'IN_PROGRESS'");
b.Property<DateTimeOffset>("DeadlineAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("deadline_at");
b.Property<Guid>("EncounterId")
.HasColumnType("uuid")
.HasColumnName("encounter_id");
b.Property<DateTimeOffset>("RecognizedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("recognized_at");
b.Property<Guid>("TriggeringAlertId")
.HasColumnType("uuid")
.HasColumnName("triggering_alert_id");
b.Property<string>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid")
.HasColumnName("id")
.HasDefaultValueSql("gen_random_uuid()");
b.Property<Guid>("BundleId")
.HasColumnType("uuid")
.HasColumnName("bundle_id");
b.Property<DateTimeOffset?>("CompletedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("completed_at");
b.Property<string>("ElementType")
.IsRequired()
.HasMaxLength(40)
.HasColumnType("character varying(40)")
.HasColumnName("element_type");
b.Property<Guid?>("OrderId")
.HasColumnType("uuid")
.HasColumnName("order_id");
b.Property<string>("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
}
}
}
@@ -0,0 +1,129 @@
using System;
using Microsoft.EntityFrameworkCore.Migrations;
#nullable disable
namespace VigilCareClinicalAPI.Migrations
{
/// <inheritdoc />
public partial class AddQsofaWarningAlertType : Migration
{
/// <inheritdoc />
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<Guid>(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"),
encounter_id = table.Column<Guid>(type: "uuid", nullable: false),
triggering_alert_id = table.Column<Guid>(type: "uuid", nullable: false),
triggering_alert_type = table.Column<string>(type: "character varying(50)", maxLength: 50, nullable: false),
recognized_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
deadline_at = table.Column<DateTimeOffset>(type: "timestamp with time zone", nullable: false),
compliance_status = table.Column<string>(type: "character varying(20)", maxLength: 20, nullable: false, defaultValueSql: "'IN_PROGRESS'"),
completed_at = table.Column<DateTimeOffset>(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<Guid>(type: "uuid", nullable: false, defaultValueSql: "gen_random_uuid()"),
bundle_id = table.Column<Guid>(type: "uuid", nullable: false),
element_type = table.Column<string>(type: "character varying(40)", maxLength: 40, nullable: false),
status = table.Column<string>(type: "character varying(20)", maxLength: 20, nullable: false, defaultValueSql: "'PENDING'"),
order_id = table.Column<Guid>(type: "uuid", nullable: true),
completed_at = table.Column<DateTimeOffset>(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");
}
/// <inheritdoc />
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "sepsis_bundle_elements");
migrationBuilder.DropTable(
name: "sepsis_bundles");
}
}
}
@@ -626,6 +626,111 @@ namespace VigilCareClinicalAPI.Migrations
});
});
modelBuilder.Entity("SepsisBundle", b =>
{
b.Property<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid")
.HasColumnName("id")
.HasDefaultValueSql("gen_random_uuid()");
b.Property<DateTimeOffset?>("CompletedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("completed_at");
b.Property<string>("ComplianceStatus")
.IsRequired()
.ValueGeneratedOnAdd()
.HasMaxLength(20)
.HasColumnType("character varying(20)")
.HasColumnName("compliance_status")
.HasDefaultValueSql("'IN_PROGRESS'");
b.Property<DateTimeOffset>("DeadlineAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("deadline_at");
b.Property<Guid>("EncounterId")
.HasColumnType("uuid")
.HasColumnName("encounter_id");
b.Property<DateTimeOffset>("RecognizedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("recognized_at");
b.Property<Guid>("TriggeringAlertId")
.HasColumnType("uuid")
.HasColumnName("triggering_alert_id");
b.Property<string>("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<Guid>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("uuid")
.HasColumnName("id")
.HasDefaultValueSql("gen_random_uuid()");
b.Property<Guid>("BundleId")
.HasColumnType("uuid")
.HasColumnName("bundle_id");
b.Property<DateTimeOffset?>("CompletedAt")
.HasColumnType("timestamp with time zone")
.HasColumnName("completed_at");
b.Property<string>("ElementType")
.IsRequired()
.HasMaxLength(40)
.HasColumnType("character varying(40)")
.HasColumnName("element_type");
b.Property<Guid?>("OrderId")
.HasColumnType("uuid")
.HasColumnName("order_id");
b.Property<string>("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
}
}
@@ -0,0 +1,7 @@
public enum QsofaOutcome
{
NotQsofaCode,
InsufficientCriteria,
AlertCreated,
AlertAlreadyOpen
}
@@ -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);
}
@@ -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 +
+3
View File
@@ -80,7 +80,10 @@ try
builder.Services.AddScoped<IOrderService, OrderService>();
builder.Services.AddScoped<IAnalyticsService, AnalyticsService>();
builder.Services.AddScoped<INews2Service, News2Service>();
builder.Services.AddScoped<ISepsisBundleService, SepsisBundleService>();
builder.Services.AddScoped<SepsisAlertHandler>();
builder.Services.AddScoped<SirsDetector>();
builder.Services.AddScoped<QsofaDetector>();
builder.Services.AddScoped<UnacknowledgedAlertsCheck>();
builder.Services.AddScoped<PendingOrdersCheck>();
builder.Services.AddScoped<DisconnectedMonitorsCheck>();
@@ -0,0 +1,34 @@
using StackExchange.Redis;
public static class QsofaCalculator
{
public static readonly IReadOnlyList<string> QsofaCodes = new[]
{
"RESP_RATE", "SYSTOLIC_BP", "AVPU"
};
public static readonly IReadOnlySet<string> QsofaCodeSet =
new HashSet<string>(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);
}
@@ -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<QsofaDetector> _logger;
private readonly ClinicalMetrics _metrics;
public QsofaDetector(
IConnectionMultiplexer redis,
IServiceProvider services,
ILogger<QsofaDetector> logger,
ClinicalMetrics metrics)
{
_redis = redis;
_services = services;
_logger = logger;
_metrics = metrics;
}
public async Task<QsofaResult> 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<bool> TryCreateAlertAsync(
Guid encounterId,
Guid patientId,
int activeCount,
RedisValue[] criterionValues,
CancellationToken ct)
{
using var scope = _services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
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<SepsisAlertHandler>();
await handler.OnSepsisAlertCreatedAsync(encounterId, alertId, AlertType.QsofaWarning, ct);
return true;
}
private static string BuildDetails(int activeCount, RedisValue[] values)
{
var activeParts = new List<string>();
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)}";
}
}
@@ -0,0 +1,22 @@
public class SepsisAlertHandler
{
private readonly ISepsisBundleService _bundleService;
private readonly ILogger<SepsisAlertHandler> _logger;
public SepsisAlertHandler(ISepsisBundleService bundleService, ILogger<SepsisAlertHandler> 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());
}
}
@@ -169,6 +169,9 @@ public class SirsDetector
activeCount, alertId);
}
var handler = scope.ServiceProvider.GetRequiredService<SepsisAlertHandler>();
await handler.OnSepsisAlertCreatedAsync(encounterId, alertId, AlertType.SepsisWarning, ct);
return true;
}
}
@@ -0,0 +1,8 @@
public interface ISepsisBundleService
{
Task<SepsisBundle?> TryCreateBundleAsync(
Guid encounterId, Guid triggeringAlertId, AlertType alertType, CancellationToken ct = default);
Task<SepsisBundle?> GetCurrentByEncounterAsync(Guid encounterId);
Task<SepsisBundle> GetByIdAsync(Guid id);
Task OnOrderResultedAsync(Guid orderId, CancellationToken ct = default);
}
@@ -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<Order> CreateAsync(Guid encounterId, CreateOrderRequest req)
{
@@ -109,6 +114,8 @@ public class OrderService : IOrderService
order.ResultSummary = req.ResultSummary;
await _db.SaveChangesAsync();
var bundleService = _serviceProvider.GetRequiredService<ISepsisBundleService>();
await bundleService.OnOrderResultedAsync(order.Id);
return order;
}
}
@@ -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<SepsisBundle?> 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<SepsisBundle?> 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<SepsisBundle> 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);
}
}