feature: Medication Tracking & Vital Sign Correlation

This commit is contained in:
voltsrage
2026-06-19 10:47:55 +08:00
parent e2d40331b7
commit 5c7e37471b
29 changed files with 2512 additions and 4 deletions
@@ -11,6 +11,7 @@ public static class DbResetHelper
try
{
await db.Database.ExecuteSqlRawAsync(@"
DELETE FROM medication_administrations;
DELETE FROM sepsis_bundle_elements;
DELETE FROM sepsis_bundles;
DELETE FROM reconciliation_alerts;
@@ -0,0 +1,195 @@
using FluentAssertions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using StackExchange.Redis;
[Collection("Integration")]
public class MedicationCorrelationTests : IAsyncLifetime
{
private readonly ApiFixture _fixture;
private Guid _patientId;
private Guid _encounterId;
public MedicationCorrelationTests(ApiFixture fixture) => _fixture = fixture;
public async Task InitializeAsync() => await ResetAndSeedAsync();
public Task DisposeAsync() => Task.CompletedTask;
private async Task ResetAndSeedAsync()
{
using var scope = _fixture.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await DbResetHelper.ResetAsync(db);
var patient = new Patient
{
Id = Guid.NewGuid(), Mrn = "MRN-CORR-001", FirstName = "Correlation", LastName = "Test",
DateOfBirth = new DateOnly(1970, 6, 10), 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. Correlation", AdmittedAt = DateTimeOffset.UtcNow,
CreatedAt = DateTimeOffset.UtcNow
};
db.Patients.Add(patient);
db.Encounters.Add(encounter);
db.AlertThresholds.Add(new AlertThreshold
{
Id = Guid.NewGuid(), ObservationCode = "SYSTOLIC_BP",
DisplayName = "Systolic BP", Unit = "mmHg",
CriticalLow = 70, WarningLow = 90, WarningHigh = 180, CriticalHigh = 220,
CreatedAt = DateTimeOffset.UtcNow
});
db.AlertThresholds.Add(new AlertThreshold
{
Id = Guid.NewGuid(), ObservationCode = "RESP_RATE",
DisplayName = "Respiratory Rate", Unit = "breaths/min",
CriticalLow = 5, WarningLow = 8, WarningHigh = 25, CriticalHigh = 35,
CreatedAt = DateTimeOffset.UtcNow
});
await db.SaveChangesAsync();
var redis = scope.ServiceProvider.GetRequiredService<IConnectionMultiplexer>();
var cache = redis.GetDatabase(1);
await cache.StringSetAsync("threshold:SYSTOLIC_BP",
"""{"ObservationCode":"SYSTOLIC_BP","CriticalLow":70,"WarningLow":90,"WarningHigh":180,"CriticalHigh":220}""");
await cache.StringSetAsync("threshold:RESP_RATE",
"""{"ObservationCode":"RESP_RATE","CriticalLow":5,"WarningLow":8,"WarningHigh":25,"CriticalHigh":35}""");
_patientId = patient.Id;
_encounterId = encounter.Id;
}
[Fact]
public async Task MetoprololThenLowBp_AnnotatedDetails()
{
await ResetAndSeedAsync();
using var scope = _fixture.Services.CreateScope();
var medService = scope.ServiceProvider.GetRequiredService<IMedicationService>();
await medService.CreateAsync(_encounterId,
new CreateMedicationAdministrationRequest(
"metoprolol", 25m, "mg", "PO",
DateTimeOffset.UtcNow.AddMinutes(-45), "nurse-1"));
var evaluator = scope.ServiceProvider.GetRequiredService<WarningEvaluator>();
var created = await evaluator.EvaluateAsync(
Guid.NewGuid(), _encounterId, _patientId, "SYSTOLIC_BP", 85m);
created.Should().BeTrue();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var alert = await db.ClinicalAlerts
.SingleAsync(a => a.AlertType == AlertType.WarningSystolicBp);
alert.Details.Should().Contain("metoprolol");
alert.Details.Should().Contain("min ago");
alert.Details.Should().Contain("note:");
}
[Fact]
public async Task LowBpWithoutMedication_Unannotated()
{
await ResetAndSeedAsync();
using var scope = _fixture.Services.CreateScope();
var evaluator = scope.ServiceProvider.GetRequiredService<WarningEvaluator>();
var created = await evaluator.EvaluateAsync(
Guid.NewGuid(), _encounterId, _patientId, "SYSTOLIC_BP", 85m);
created.Should().BeTrue();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var alert = await db.ClinicalAlerts
.SingleAsync(a => a.AlertType == AlertType.WarningSystolicBp);
alert.Details.Should().NotContain("note:");
}
[Fact]
public async Task UnrelatedDrug_NoAnnotation()
{
await ResetAndSeedAsync();
using var scope = _fixture.Services.CreateScope();
var medService = scope.ServiceProvider.GetRequiredService<IMedicationService>();
// Insulin maps to GLUCOSE_MG_DL, not SYSTOLIC_BP
await medService.CreateAsync(_encounterId,
new CreateMedicationAdministrationRequest(
"insulin", 10m, "units", "SubQ",
DateTimeOffset.UtcNow.AddMinutes(-30), "nurse-1"));
var evaluator = scope.ServiceProvider.GetRequiredService<WarningEvaluator>();
var created = await evaluator.EvaluateAsync(
Guid.NewGuid(), _encounterId, _patientId, "SYSTOLIC_BP", 85m);
created.Should().BeTrue();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var alert = await db.ClinicalAlerts
.SingleAsync(a => a.AlertType == AlertType.WarningSystolicBp);
alert.Details.Should().NotContain("note:");
alert.Details.Should().NotContain("insulin");
}
[Fact]
public async Task MedicationOutsideWindow_NoAnnotation()
{
await ResetAndSeedAsync();
using var scope = _fixture.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
// Metoprolol administered 2 hours ago — outside 90-min window
db.MedicationAdministrations.Add(new MedicationAdministration
{
Id = Guid.NewGuid(),
EncounterId = _encounterId,
DrugName = "metoprolol",
Dose = 25m,
DoseUnit = "mg",
Route = "PO",
AdministeredAt = DateTimeOffset.UtcNow.AddMinutes(-120),
AdministeredBy = "nurse-1"
});
await db.SaveChangesAsync();
var evaluator = scope.ServiceProvider.GetRequiredService<WarningEvaluator>();
var created = await evaluator.EvaluateAsync(
Guid.NewGuid(), _encounterId, _patientId, "SYSTOLIC_BP", 85m);
created.Should().BeTrue();
var alert = await db.ClinicalAlerts
.SingleAsync(a => a.AlertType == AlertType.WarningSystolicBp);
alert.Details.Should().NotContain("note:");
alert.Details.Should().NotContain("metoprolol");
}
[Fact]
public async Task MorphineThenLowRespRate_Annotated()
{
await ResetAndSeedAsync();
using var scope = _fixture.Services.CreateScope();
var medService = scope.ServiceProvider.GetRequiredService<IMedicationService>();
await medService.CreateAsync(_encounterId,
new CreateMedicationAdministrationRequest(
"morphine", 4m, "mg", "IV",
DateTimeOffset.UtcNow.AddMinutes(-20), "nurse-1"));
var evaluator = scope.ServiceProvider.GetRequiredService<WarningEvaluator>();
var created = await evaluator.EvaluateAsync(
Guid.NewGuid(), _encounterId, _patientId, "RESP_RATE", 7m);
created.Should().BeTrue();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var alert = await db.ClinicalAlerts
.SingleAsync(a => a.AlertType == AlertType.WarningRespRate);
alert.Details.Should().Contain("morphine");
alert.Details.Should().Contain("min ago");
alert.Details.Should().Contain("note:");
}
}
@@ -0,0 +1,154 @@
using FluentAssertions;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
[Collection("Integration")]
public class MedicationServiceTests : IAsyncLifetime
{
private readonly ApiFixture _fixture;
private Guid _patientId;
private Guid _activeEncounterId;
private Guid _dischargedEncounterId;
public MedicationServiceTests(ApiFixture fixture) => _fixture = fixture;
public async Task InitializeAsync() => await ResetAndSeedAsync();
public Task DisposeAsync() => Task.CompletedTask;
private async Task ResetAndSeedAsync()
{
using var scope = _fixture.Services.CreateScope();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
await DbResetHelper.ResetAsync(db);
var patient = new Patient
{
Id = Guid.NewGuid(), Mrn = "MRN-MED-001", FirstName = "Med", LastName = "Test",
DateOfBirth = new DateOnly(1980, 3, 15), Gender = "F", CreatedAt = DateTimeOffset.UtcNow
};
var activeEncounter = new Encounter
{
Id = Guid.NewGuid(), PatientId = patient.Id, EncounterType = EncounterType.Inpatient,
Status = EncounterStatus.Active, Department = Department.Icu,
AttendingPhysician = "Dr. Medication", AdmittedAt = DateTimeOffset.UtcNow,
CreatedAt = DateTimeOffset.UtcNow
};
var dischargedEncounter = new Encounter
{
Id = Guid.NewGuid(), PatientId = patient.Id, EncounterType = EncounterType.Inpatient,
Status = EncounterStatus.Discharged, Department = Department.Icu,
AttendingPhysician = "Dr. Medication", AdmittedAt = DateTimeOffset.UtcNow.AddDays(-3),
DischargedAt = DateTimeOffset.UtcNow.AddHours(-1),
CreatedAt = DateTimeOffset.UtcNow
};
db.Patients.Add(patient);
db.Encounters.Add(activeEncounter);
db.Encounters.Add(dischargedEncounter);
await db.SaveChangesAsync();
_patientId = patient.Id;
_activeEncounterId = activeEncounter.Id;
_dischargedEncounterId = dischargedEncounter.Id;
}
[Fact]
public async Task Create_OnActiveEncounter_Succeeds()
{
await ResetAndSeedAsync();
using var scope = _fixture.Services.CreateScope();
var service = scope.ServiceProvider.GetRequiredService<IMedicationService>();
var med = await service.CreateAsync(_activeEncounterId,
new CreateMedicationAdministrationRequest(
"metoprolol", 25m, "mg", "PO", null, "nurse-1"));
med.Should().NotBeNull();
med.DrugName.Should().Be("metoprolol");
med.Dose.Should().Be(25m);
med.DoseUnit.Should().Be("mg");
med.Route.Should().Be("PO");
med.EncounterId.Should().Be(_activeEncounterId);
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
var persisted = await db.MedicationAdministrations.FindAsync(med.Id);
persisted.Should().NotBeNull();
}
[Fact]
public async Task Create_OnDischargedEncounter_ThrowsConflict()
{
await ResetAndSeedAsync();
using var scope = _fixture.Services.CreateScope();
var service = scope.ServiceProvider.GetRequiredService<IMedicationService>();
var act = () => service.CreateAsync(_dischargedEncounterId,
new CreateMedicationAdministrationRequest(
"metoprolol", 25m, "mg", "PO", null, "nurse-1"));
await act.Should().ThrowAsync<ConflictException>();
}
[Fact]
public async Task ListByEncounter_ReturnsPaginated()
{
await ResetAndSeedAsync();
using var scope = _fixture.Services.CreateScope();
var service = scope.ServiceProvider.GetRequiredService<IMedicationService>();
await service.CreateAsync(_activeEncounterId,
new CreateMedicationAdministrationRequest(
"metoprolol", 25m, "mg", "PO", null, "nurse-1"));
await service.CreateAsync(_activeEncounterId,
new CreateMedicationAdministrationRequest(
"morphine", 4m, "mg", "IV", null, "nurse-2"));
await service.CreateAsync(_activeEncounterId,
new CreateMedicationAdministrationRequest(
"insulin", 10m, "units", "SubQ", null, "nurse-1"));
var result = await service.ListByEncounterAsync(_activeEncounterId, null, 1, 2);
result.TotalCount.Should().Be(3);
result.Items.Should().HaveCount(2);
result.TotalPages.Should().Be(2);
}
[Fact]
public async Task GetRecentForEncounter_FiltersByWindow()
{
await ResetAndSeedAsync();
using var scope = _fixture.Services.CreateScope();
var service = scope.ServiceProvider.GetRequiredService<IMedicationService>();
var db = scope.ServiceProvider.GetRequiredService<AppDbContext>();
// Recent metoprolol — within 90-min window
await service.CreateAsync(_activeEncounterId,
new CreateMedicationAdministrationRequest(
"metoprolol", 25m, "mg", "PO",
DateTimeOffset.UtcNow.AddMinutes(-30), "nurse-1"));
// Old metoprolol — outside 90-min window
db.MedicationAdministrations.Add(new MedicationAdministration
{
Id = Guid.NewGuid(),
EncounterId = _activeEncounterId,
DrugName = "metoprolol",
Dose = 50m,
DoseUnit = "mg",
Route = "PO",
AdministeredAt = DateTimeOffset.UtcNow.AddMinutes(-120),
AdministeredBy = "nurse-2"
});
await db.SaveChangesAsync();
var recent = await service.GetRecentForEncounterAsync(
_activeEncounterId, "SYSTOLIC_BP", 90);
recent.Should().HaveCount(1);
recent[0].Dose.Should().Be(25m);
}
}
@@ -0,0 +1,43 @@
using System.Net;
using System.Net.Http.Json;
using FluentAssertions;
[Collection("Integration")]
public class MedicationValidationTests
{
private readonly HttpClient _client;
public MedicationValidationTests(ApiFixture fixture) => _client = fixture.CreateClient();
[Fact]
public async Task EmptyDrugName_Returns400()
{
var resp = await _client.PostAsJsonAsync(
$"/api/v1/encounters/{Guid.NewGuid()}/medications",
new { drugName = "", dose = 25, doseUnit = "mg", route = "PO", administeredBy = "nurse-1" });
resp.StatusCode.Should().Be(HttpStatusCode.BadRequest);
}
[Fact]
public async Task ZeroDose_Returns400()
{
var resp = await _client.PostAsJsonAsync(
$"/api/v1/encounters/{Guid.NewGuid()}/medications",
new { drugName = "metoprolol", dose = 0, doseUnit = "mg", route = "PO", administeredBy = "nurse-1" });
resp.StatusCode.Should().Be(HttpStatusCode.BadRequest);
}
[Fact]
public async Task FutureAdministeredAt_Returns400()
{
var futureTime = DateTimeOffset.UtcNow.AddHours(1);
var resp = await _client.PostAsJsonAsync(
$"/api/v1/encounters/{Guid.NewGuid()}/medications",
new { drugName = "metoprolol", dose = 25, doseUnit = "mg", route = "PO",
administeredBy = "nurse-1", administeredAt = futureTime });
resp.StatusCode.Should().Be(HttpStatusCode.BadRequest);
}
}