Implement owner-scoped Observation lifecycle with serialized patches
This commit is contained in:
1 parent
bfe6ebf5af
commit
3a70e3e296
37 files changed
+31249
-9
No files matched your search
@@ -0,0 +1,12 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace HealthApp.Contracts;
|
||||
|
||||
public sealed record ContextSelection
|
||||
{
|
||||
[AllowedValues("Home", "Clinic", "Other", "Unknown", null)]
|
||||
public string? Setting { get; init; }
|
||||
|
||||
[AllowedValues("AtRest", "DuringActivity", "AfterActivity", "Unknown", null)]
|
||||
public string? ActivityCondition { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace HealthApp.Contracts;
|
||||
|
||||
public sealed record MeasurementContext
|
||||
{
|
||||
[AllowedValues("Home", "Clinic", "Other", "Unknown", null)]
|
||||
public string? Setting { get; init; } = "Unknown";
|
||||
|
||||
[AllowedValues("AtRest", "DuringActivity", "AfterActivity", "Unknown", null)]
|
||||
public string? ActivityCondition { get; init; } = "Unknown";
|
||||
|
||||
[Range(0, double.MaxValue)]
|
||||
public decimal? RestDurationMinutes { get; init; }
|
||||
|
||||
public string? BodyPosition { get; init; }
|
||||
public string? MeasuredArm { get; init; }
|
||||
public string? DeviceDetails { get; init; }
|
||||
public string? CuffDetails { get; init; }
|
||||
public string? AdditionalCircumstances { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace HealthApp.Contracts;
|
||||
|
||||
[JsonUnmappedMemberHandling(JsonUnmappedMemberHandling.Disallow)]
|
||||
public sealed record MeasurementContextPatch
|
||||
{
|
||||
private string? setting;
|
||||
[AllowedValues("Home", "Clinic", "Other", "Unknown", null)]
|
||||
public string? Setting
|
||||
{
|
||||
get => setting;
|
||||
init { setting = value; SettingSpecified = true; }
|
||||
}
|
||||
[JsonIgnore]
|
||||
public bool SettingSpecified { get; private set; }
|
||||
|
||||
private string? activityCondition;
|
||||
[AllowedValues("AtRest", "DuringActivity", "AfterActivity", "Unknown", null)]
|
||||
public string? ActivityCondition
|
||||
{
|
||||
get => activityCondition;
|
||||
init { activityCondition = value; ActivityConditionSpecified = true; }
|
||||
}
|
||||
[JsonIgnore]
|
||||
public bool ActivityConditionSpecified { get; private set; }
|
||||
|
||||
private decimal? restDurationMinutes;
|
||||
[Range(0, double.MaxValue)]
|
||||
public decimal? RestDurationMinutes
|
||||
{
|
||||
get => restDurationMinutes;
|
||||
init { restDurationMinutes = value; RestDurationMinutesSpecified = true; }
|
||||
}
|
||||
[JsonIgnore]
|
||||
public bool RestDurationMinutesSpecified { get; private set; }
|
||||
|
||||
private string? bodyPosition;
|
||||
public string? BodyPosition
|
||||
{
|
||||
get => bodyPosition;
|
||||
init { bodyPosition = value; BodyPositionSpecified = true; }
|
||||
}
|
||||
[JsonIgnore]
|
||||
public bool BodyPositionSpecified { get; private set; }
|
||||
|
||||
private string? measuredArm;
|
||||
public string? MeasuredArm
|
||||
{
|
||||
get => measuredArm;
|
||||
init { measuredArm = value; MeasuredArmSpecified = true; }
|
||||
}
|
||||
[JsonIgnore]
|
||||
public bool MeasuredArmSpecified { get; private set; }
|
||||
|
||||
private string? deviceDetails;
|
||||
public string? DeviceDetails
|
||||
{
|
||||
get => deviceDetails;
|
||||
init { deviceDetails = value; DeviceDetailsSpecified = true; }
|
||||
}
|
||||
[JsonIgnore]
|
||||
public bool DeviceDetailsSpecified { get; private set; }
|
||||
|
||||
private string? cuffDetails;
|
||||
public string? CuffDetails
|
||||
{
|
||||
get => cuffDetails;
|
||||
init { cuffDetails = value; CuffDetailsSpecified = true; }
|
||||
}
|
||||
[JsonIgnore]
|
||||
public bool CuffDetailsSpecified { get; private set; }
|
||||
|
||||
private string? additionalCircumstances;
|
||||
public string? AdditionalCircumstances
|
||||
{
|
||||
get => additionalCircumstances;
|
||||
init { additionalCircumstances = value; AdditionalCircumstancesSpecified = true; }
|
||||
}
|
||||
[JsonIgnore]
|
||||
public bool AdditionalCircumstancesSpecified { get; private set; }
|
||||
|
||||
[JsonIgnore]
|
||||
public bool HasChanges => SettingSpecified || ActivityConditionSpecified || RestDurationMinutesSpecified ||
|
||||
BodyPositionSpecified || MeasuredArmSpecified || DeviceDetailsSpecified || CuffDetailsSpecified || AdditionalCircumstancesSpecified;
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
namespace HealthApp.Contracts;
|
||||
|
||||
public sealed record ObservationDto(Guid ObservationId, Guid PatientId, DateTime MeasuredAt,
|
||||
int Systolic, int Diastolic, int Pulse, MeasurementContextDto? MeasurementContext = null,
|
||||
string? Context = null, string? Note = null);
|
||||
|
||||
public sealed record MeasurementContextDto(string? Setting, string? ActivityCondition, decimal? RestDurationMinutes,
|
||||
string? BodyPosition, string? MeasuredArm, string? DeviceDetails, string? CuffDetails, string? AdditionalCircumstances);
|
||||
@@ -0,0 +1,19 @@
|
||||
namespace HealthApp.Contracts;
|
||||
public interface ObservationQueries
|
||||
{
|
||||
Task<Guid?> ResolveOwnerAsync(Guid observationId,CancellationToken ct);
|
||||
Task<ObservationDto?> GetAsync(AuthorizedPatientContext scope,Guid id,CancellationToken ct);
|
||||
Task<ObservationDto?> LatestAsync(AuthorizedPatientContext scope,CancellationToken ct);
|
||||
Task<IReadOnlyList<ObservationDto>> SelectedAsync(AuthorizedPatientContext scope,DateTime from,DateTime to,ContextSelection selection,CancellationToken ct);
|
||||
}
|
||||
public interface ObservationCommands
|
||||
{
|
||||
Task<ObservationDto?> RecordAsync(AuthorizedPatientContext scope,RecordObservationRequest request,CancellationToken ct);
|
||||
Task<ObservationDto?> PatchAsync(AuthorizedPatientContext scope,Guid id,PatchObservationRequest request,CancellationToken ct);
|
||||
Task<bool> DeleteAsync(AuthorizedPatientContext scope,Guid id,CancellationToken ct);
|
||||
}
|
||||
public static class MeasurementPeriod
|
||||
{
|
||||
public static DateTime Normalize(DateTime t)=>DateTime.SpecifyKind(t.Kind==DateTimeKind.Unspecified?t:t.ToUniversalTime(),DateTimeKind.Unspecified);
|
||||
public static void Validate(DateTime from,DateTime to){if(Normalize(to)<Normalize(from))throw new ArgumentException("The end time must not be earlier than the start time.");}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using System.Text.Json.Serialization;
|
||||
|
||||
namespace HealthApp.Contracts;
|
||||
|
||||
[JsonUnmappedMemberHandling(JsonUnmappedMemberHandling.Disallow)]
|
||||
public sealed record PatchObservationRequest : IValidatableObject
|
||||
{
|
||||
private int? systolic;
|
||||
[Range(1, int.MaxValue)]
|
||||
public int? Systolic
|
||||
{
|
||||
get => systolic;
|
||||
init { systolic = value; SystolicSpecified = true; }
|
||||
}
|
||||
[JsonIgnore]
|
||||
public bool SystolicSpecified { get; private set; }
|
||||
|
||||
private int? diastolic;
|
||||
[Range(1, int.MaxValue)]
|
||||
public int? Diastolic
|
||||
{
|
||||
get => diastolic;
|
||||
init { diastolic = value; DiastolicSpecified = true; }
|
||||
}
|
||||
[JsonIgnore]
|
||||
public bool DiastolicSpecified { get; private set; }
|
||||
|
||||
private int? pulse;
|
||||
[Range(1, int.MaxValue)]
|
||||
public int? Pulse
|
||||
{
|
||||
get => pulse;
|
||||
init { pulse = value; PulseSpecified = true; }
|
||||
}
|
||||
[JsonIgnore]
|
||||
public bool PulseSpecified { get; private set; }
|
||||
|
||||
private MeasurementContextPatch? measurementContext;
|
||||
public MeasurementContextPatch? MeasurementContext
|
||||
{
|
||||
get => measurementContext;
|
||||
init { measurementContext = value; MeasurementContextSpecified = true; }
|
||||
}
|
||||
[JsonIgnore]
|
||||
public bool MeasurementContextSpecified { get; private set; }
|
||||
|
||||
private string? context;
|
||||
public string? Context
|
||||
{
|
||||
get => context;
|
||||
init { context = value; ContextSpecified = true; }
|
||||
}
|
||||
[JsonIgnore]
|
||||
public bool ContextSpecified { get; private set; }
|
||||
|
||||
private string? note;
|
||||
public string? Note
|
||||
{
|
||||
get => note;
|
||||
init { note = value; NoteSpecified = true; }
|
||||
}
|
||||
[JsonIgnore]
|
||||
public bool NoteSpecified { get; private set; }
|
||||
|
||||
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext)
|
||||
{
|
||||
if (SystolicSpecified && Systolic is null)
|
||||
yield return new ValidationResult("Systolic cannot be cleared.", [nameof(Systolic)]);
|
||||
if (DiastolicSpecified && Diastolic is null)
|
||||
yield return new ValidationResult("Diastolic cannot be cleared.", [nameof(Diastolic)]);
|
||||
if (PulseSpecified && Pulse is null)
|
||||
yield return new ValidationResult("Pulse cannot be cleared.", [nameof(Pulse)]);
|
||||
if (!SystolicSpecified && !DiastolicSpecified && !PulseSpecified && !ContextSpecified && !NoteSpecified &&
|
||||
!(MeasurementContextSpecified && (MeasurementContext is null || MeasurementContext.HasChanges)))
|
||||
yield return new ValidationResult("Supply at least one supported field to update.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace HealthApp.Contracts;
|
||||
|
||||
public sealed record RecordObservationRequest
|
||||
{
|
||||
[Required]
|
||||
public DateTime? MeasuredAt { get; init; }
|
||||
|
||||
[Required, Range(1, int.MaxValue)]
|
||||
public int? Systolic { get; init; }
|
||||
|
||||
[Required, Range(1, int.MaxValue)]
|
||||
public int? Diastolic { get; init; }
|
||||
|
||||
[Required, Range(1, int.MaxValue)]
|
||||
public int? Pulse { get; init; }
|
||||
|
||||
public MeasurementContext? MeasurementContext { get; init; }
|
||||
|
||||
public string? Context { get; init; }
|
||||
public string? Note { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
using System.Text.Json.Serialization;
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
|
||||
namespace HealthApp.Contracts;
|
||||
|
||||
[JsonUnmappedMemberHandling(JsonUnmappedMemberHandling.Disallow)]
|
||||
public sealed record UpdateObservationRequest
|
||||
{
|
||||
[Required, Range(1, int.MaxValue)]
|
||||
public int? Systolic { get; init; }
|
||||
|
||||
[Required, Range(1, int.MaxValue)]
|
||||
public int? Diastolic { get; init; }
|
||||
|
||||
[Required, Range(1, int.MaxValue)]
|
||||
public int? Pulse { get; init; }
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
using HealthApp.Contracts;
|
||||
using HealthApp.Infrastructure;
|
||||
using HealthApp.Security;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
using Microsoft.AspNetCore.Mvc;
|
||||
using Microsoft.AspNetCore.Mvc.ModelBinding;
|
||||
namespace HealthApp.Controllers;
|
||||
[ApiController,Route("api")]
|
||||
public sealed class ObservationController(ObservationQueries queries,ObservationCommands commands,AccessPolicy access,RequestTransaction tx) : ControllerBase
|
||||
{
|
||||
private IActionResult Unavailable(){Response.StatusCode=404;return new EmptyResult();}
|
||||
|
||||
private async Task<AuthorizedPatientContext?> Owner(Guid id,bool write,CancellationToken ct){var owner=await queries.ResolveOwnerAsync(id,ct);return owner is null?null:await access.AuthorizeAsync(User,owner.Value,write,ct);}
|
||||
[HttpPost("patients/{patientId:guid}/observations"),Authorize(Policy="Patient")]
|
||||
public async Task<IActionResult> Record(Guid patientId,RecordObservationRequest r,CancellationToken ct){var scope=await access.AuthorizeAsync(User,patientId,true,ct);if(scope is null)return Unavailable();var o=await commands.RecordAsync(scope,r,ct);await tx.FinishAsync(ct);return o is null?NotFound():Created($"/api/observations/{o.ObservationId}",o);}
|
||||
[HttpGet("observations/{observationId:guid}")]
|
||||
public async Task<IActionResult> Get(Guid observationId,CancellationToken ct){var scope=await Owner(observationId,false,ct);if(scope is null)return Unavailable();var o=await queries.GetAsync(scope,observationId,ct);await tx.FinishAsync(ct);return o is null?NotFound():Ok(o);}
|
||||
[HttpPut("observations/{observationId:guid}"),Authorize(Policy="Patient")]
|
||||
public Task<IActionResult> Put(Guid observationId,UpdateObservationRequest r,CancellationToken ct)=>Patch(observationId,new PatchObservationRequest{Systolic=r.Systolic,Diastolic=r.Diastolic,Pulse=r.Pulse},ct);
|
||||
[HttpPatch("observations/{observationId:guid}"),Authorize(Policy="Patient")]
|
||||
public async Task<IActionResult> Patch(Guid observationId,PatchObservationRequest r,CancellationToken ct){var scope=await Owner(observationId,true,ct);if(scope is null)return Unavailable();var o=await commands.PatchAsync(scope,observationId,r,ct);await tx.FinishAsync(ct);return o is null?NotFound():Ok(o);}
|
||||
[HttpDelete("observations/{observationId:guid}"),Authorize(Policy="Patient")]
|
||||
public async Task<IActionResult> Delete(Guid observationId,CancellationToken ct){var scope=await Owner(observationId,true,ct);if(scope is null)return Unavailable();var found=await commands.DeleteAsync(scope,observationId,ct);await tx.FinishAsync(ct);return found?NoContent():NotFound();}
|
||||
[HttpGet("patients/{patientId:guid}/observations/latest")]
|
||||
public async Task<IActionResult> Latest(Guid patientId,CancellationToken ct){var scope=await access.AuthorizeAsync(User,patientId,false,ct);if(scope is null)return Unavailable();var o=await queries.LatestAsync(scope,ct);await tx.FinishAsync(ct);return o is null?NotFound():Ok(o);}
|
||||
[HttpGet("patients/{patientId:guid}/observations")]
|
||||
public async Task<IActionResult> History(Guid patientId,[FromQuery,BindRequired]DateTime from,[FromQuery,BindRequired]DateTime to,[FromQuery]ContextSelection selection,CancellationToken ct)
|
||||
{
|
||||
var scope=await access.AuthorizeAsync(User,patientId,false,ct);if(scope is null)return Unavailable();
|
||||
try{var series=await queries.SelectedAsync(scope,from,to,selection,ct);await tx.FinishAsync(ct);Response.Headers["X-Measurement-Setting"]=selection.Setting??"All";Response.Headers["X-Activity-Condition"]=selection.ActivityCondition??"All";return Ok(series);}
|
||||
catch(ArgumentException){ModelState.AddModelError(nameof(to),"The end time must not be earlier than the start time.");return ValidationProblem(ModelState);}
|
||||
}
|
||||
}
|
||||
@@ -8,6 +8,8 @@ namespace HealthApp.Controllers;
|
||||
[ApiController,Route("api/patients")]
|
||||
public sealed class PatientController(ProfileQueries queries,ProfileCommands commands,AccessPolicy access,RequestTransaction tx) : ControllerBase
|
||||
{
|
||||
private IActionResult Unavailable(){Response.StatusCode=404;return new EmptyResult();}
|
||||
|
||||
[HttpPost,Authorize(Policy="Patient")]
|
||||
public async Task<IActionResult> Create(CreatePatientRequest r,CancellationToken ct)
|
||||
{
|
||||
@@ -22,8 +24,8 @@ public sealed class PatientController(ProfileQueries queries,ProfileCommands com
|
||||
}
|
||||
[HttpGet("{patientId:guid}")]
|
||||
public async Task<IActionResult> Get(Guid patientId,CancellationToken ct)
|
||||
{var scope=await access.AuthorizeAsync(User,patientId,false,ct);if(scope is null)return NotFound();var p=await queries.GetAsync(scope,ct);await tx.FinishAsync(ct);return p is null?NotFound():Ok(p);}
|
||||
{var scope=await access.AuthorizeAsync(User,patientId,false,ct);if(scope is null)return Unavailable();var p=await queries.GetAsync(scope,ct);await tx.FinishAsync(ct);return p is null?NotFound():Ok(p);}
|
||||
[HttpPut("{patientId:guid}"),Authorize(Policy="Patient")]
|
||||
public async Task<IActionResult> Update(Guid patientId,UpdatePatientRequest r,CancellationToken ct)
|
||||
{var scope=await access.AuthorizeAsync(User,patientId,true,ct);if(scope is null)return NotFound();var p=await commands.UpdateAsync(scope,r,ct);await tx.FinishAsync(ct);return p is null?NotFound():Ok(p);}
|
||||
{var scope=await access.AuthorizeAsync(User,patientId,true,ct);if(scope is null)return Unavailable();var p=await commands.UpdateAsync(scope,r,ct);await tx.FinishAsync(ct);return p is null?NotFound():Ok(p);}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk.Web">
|
||||
<PropertyGroup><TargetFramework>net10.0</TargetFramework><Nullable>enable</Nullable><ImplicitUsings>enable</ImplicitUsings></PropertyGroup>
|
||||
<ItemGroup><ProjectReference Include="../HealthApp.Contracts/HealthApp.Contracts.csproj" /><ProjectReference Include="../Modules/Guidance/Guidance.csproj" /><ProjectReference Include="../HealthApp.Infrastructure/HealthApp.Infrastructure.csproj"/><ProjectReference Include="../Modules/Profile/Profile.csproj"/></ItemGroup>
|
||||
<ItemGroup><ProjectReference Include="../HealthApp.Contracts/HealthApp.Contracts.csproj" /><ProjectReference Include="../Modules/Guidance/Guidance.csproj" /><ProjectReference Include="../HealthApp.Infrastructure/HealthApp.Infrastructure.csproj"/><ProjectReference Include="../Modules/Profile/Profile.csproj"/><ProjectReference Include="../Modules/Observations/Observations.csproj"/></ItemGroup>
|
||||
</Project>
|
||||
@@ -1,6 +1,7 @@
|
||||
using HealthApp.Guidance;
|
||||
using HealthApp.Infrastructure;
|
||||
using HealthApp.Profile;
|
||||
using HealthApp.Observations;
|
||||
using Npgsql;
|
||||
using HealthApp.Security;
|
||||
using Microsoft.AspNetCore.Authorization;
|
||||
@@ -24,7 +25,7 @@ public class Program
|
||||
var options=new NpgsqlConnectionStringBuilder(text){Pooling=true,MaxPoolSize=c.GetValue("Resources:MaxPoolSize",32)};
|
||||
return NpgsqlDataSource.Create(options.ConnectionString);
|
||||
});
|
||||
builder.Services.AddScoped<RequestTransaction>();builder.Services.AddProfile();builder.Services.AddScoped<AccessPolicy>();
|
||||
builder.Services.AddScoped<RequestTransaction>();builder.Services.AddProfile();builder.Services.AddObservations();builder.Services.AddScoped<AccessPolicy>();
|
||||
builder.Services.AddDataProtection().SetApplicationName("HealthApp.ApiGateway");
|
||||
builder.Services.AddOptions<Microsoft.AspNetCore.DataProtection.KeyManagement.KeyManagementOptions>().Configure<IConfiguration, ILoggerFactory>((o,c,l)=> {
|
||||
var keys=c["Authentication:KeyDirectory"];
|
||||
|
||||
@@ -0,0 +1,2 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
[assembly:InternalsVisibleTo("HealthApp.AcceptanceTests")]
|
||||
@@ -0,0 +1,17 @@
|
||||
using HealthApp.Contracts;
|
||||
namespace HealthApp.Observations.Domain;
|
||||
|
||||
internal sealed class BloodPressureObservation
|
||||
{
|
||||
public Guid ObservationId { get; set; }
|
||||
public Guid PatientId { get; set; }
|
||||
public DateTime MeasuredAt { get; set; }
|
||||
public int Systolic { get; set; }
|
||||
public int Diastolic { get; set; }
|
||||
public int Pulse { get; set; }
|
||||
public MeasurementContext MeasurementContext { get; set; } = new();
|
||||
public string? Context { get; set; }
|
||||
public string? Note { get; set; }
|
||||
public DateTime CreatedAt { get; set; }
|
||||
public DateTime UpdatedAt { get; set; }
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
CREATE SCHEMA IF NOT EXISTS observations;
|
||||
CREATE TABLE IF NOT EXISTS observations.schema_version(version integer PRIMARY KEY);
|
||||
CREATE TABLE IF NOT EXISTS observations.observation(
|
||||
observation_id uuid PRIMARY KEY, patient_id uuid NOT NULL REFERENCES profile.patient(patient_id) ON DELETE RESTRICT,
|
||||
measured_at timestamp without time zone NOT NULL,systolic integer NOT NULL CHECK(systolic>0),diastolic integer NOT NULL CHECK(diastolic>0),pulse integer NOT NULL CHECK(pulse>0),
|
||||
context varchar,note varchar,setting text NOT NULL DEFAULT 'Unknown' CHECK(setting IN('Home','Clinic','Other','Unknown')),
|
||||
activity_condition text NOT NULL DEFAULT 'Unknown' CHECK(activity_condition IN('AtRest','DuringActivity','AfterActivity','Unknown')),
|
||||
rest_duration_minutes numeric CHECK(rest_duration_minutes>=0),body_position text,measured_arm text,device_details text,cuff_details text,additional_circumstances text,
|
||||
created_at timestamp without time zone NOT NULL,updated_at timestamp without time zone NOT NULL);
|
||||
CREATE INDEX IF NOT EXISTS ix_observation_patient_time ON observations.observation(patient_id,measured_at,created_at,observation_id);
|
||||
INSERT INTO observations.schema_version VALUES(1) ON CONFLICT DO NOTHING;
|
||||
@@ -0,0 +1,77 @@
|
||||
using System.ComponentModel.DataAnnotations;
|
||||
using HealthApp.Contracts;
|
||||
using HealthApp.Infrastructure;
|
||||
using HealthApp.Observations.Domain;
|
||||
using HealthApp.Observations.Persistence;
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
namespace HealthApp.Observations;
|
||||
internal sealed class ObservationFacade(ObservationDbContext db,RequestTransaction tx,ProfileQueries profiles) : ObservationQueries,ObservationCommands
|
||||
{
|
||||
public async Task<Guid?> ResolveOwnerAsync(Guid id,CancellationToken ct){await tx.EnlistAsync(db,ct);return await db.Observations.AsNoTracking().Where(o=>o.ObservationId==id).Select(o=>(Guid?)o.PatientId).SingleOrDefaultAsync(ct);}
|
||||
public async Task<ObservationDto?> GetAsync(AuthorizedPatientContext scope,Guid id,CancellationToken ct){await tx.EnlistAsync(db,ct);var o=await db.Observations.AsNoTracking().SingleOrDefaultAsync(o=>o.ObservationId==id&&o.PatientId==scope.PatientId,ct);return o is null?null:Dto(o);}
|
||||
public async Task<ObservationDto?> LatestAsync(AuthorizedPatientContext scope,CancellationToken ct){await tx.EnlistAsync(db,ct);var o=await db.Observations.AsNoTracking().Where(o=>o.PatientId==scope.PatientId).OrderByDescending(o=>o.MeasuredAt).ThenByDescending(o=>o.CreatedAt).ThenByDescending(o=>o.ObservationId).FirstOrDefaultAsync(ct);return o is null?null:Dto(o);}
|
||||
public async Task<IReadOnlyList<ObservationDto>> SelectedAsync(AuthorizedPatientContext scope,DateTime from,DateTime to,ContextSelection selection,CancellationToken ct)
|
||||
{
|
||||
from=MeasurementPeriod.Normalize(from);to=MeasurementPeriod.Normalize(to);MeasurementPeriod.Validate(from,to);Validator.ValidateObject(selection,new ValidationContext(selection),true);await tx.EnlistAsync(db,ct);
|
||||
var q=db.Observations.AsNoTracking().Where(o=>o.PatientId==scope.PatientId&&o.MeasuredAt>=from&&o.MeasuredAt<=to);
|
||||
if(selection.Setting is not null)q=q.Where(o=>o.MeasurementContext.Setting==selection.Setting);
|
||||
if(selection.ActivityCondition is not null)q=q.Where(o=>o.MeasurementContext.ActivityCondition==selection.ActivityCondition);
|
||||
return Array.AsReadOnly((await q.OrderBy(o=>o.MeasuredAt).ThenBy(o=>o.ObservationId).ToListAsync(ct)).Select(Dto).ToArray());
|
||||
}
|
||||
public async Task<ObservationDto?> RecordAsync(AuthorizedPatientContext scope,RecordObservationRequest request,CancellationToken ct)
|
||||
{
|
||||
scope.RequireWrite();Validator.ValidateObject(request,new ValidationContext(request),true);
|
||||
var context=request.MeasurementContext??new();context=context with{Setting=context.Setting??"Unknown",ActivityCondition=context.ActivityCondition??"Unknown"};Validator.ValidateObject(context,new ValidationContext(context),true);
|
||||
if(await profiles.GetAsync(scope,ct) is null)return null;await tx.EnlistAsync(db,ct);
|
||||
var now=DateTime.SpecifyKind(DateTime.UtcNow,DateTimeKind.Unspecified);
|
||||
var o=new BloodPressureObservation{ObservationId=Guid.NewGuid(),PatientId=scope.PatientId,MeasuredAt=MeasurementPeriod.Normalize(request.MeasuredAt!.Value),Systolic=request.Systolic!.Value,Diastolic=request.Diastolic!.Value,Pulse=request.Pulse!.Value,MeasurementContext=context,Context=request.Context,Note=request.Note,CreatedAt=now,UpdatedAt=now};db.Observations.Add(o);await db.SaveChangesAsync(ct);return Dto(o);
|
||||
}
|
||||
private async Task<BloodPressureObservation?> LockedAsync(AuthorizedPatientContext scope,Guid id,CancellationToken cancellationToken)
|
||||
{scope.RequireWrite();await tx.EnlistAsync(db,cancellationToken);return await db.Observations.FromSqlInterpolated($"SELECT * FROM observations.observation WHERE observation_id={id} AND patient_id={scope.PatientId} FOR UPDATE").SingleOrDefaultAsync(cancellationToken);}
|
||||
public async Task<ObservationDto?> PatchAsync(AuthorizedPatientContext scope,Guid id,PatchObservationRequest request,CancellationToken cancellationToken)
|
||||
{
|
||||
Validator.ValidateObject(request,new ValidationContext(request),true);if(request.MeasurementContext is not null)Validator.ValidateObject(request.MeasurementContext,new ValidationContext(request.MeasurementContext),true);
|
||||
var observation=await LockedAsync(scope,id,cancellationToken);if(observation is null)return null;
|
||||
var updatedAt=DateTime.SpecifyKind(DateTime.UtcNow,DateTimeKind.Unspecified);
|
||||
if (request.SystolicSpecified) observation.Systolic = request.Systolic!.Value;
|
||||
if (request.DiastolicSpecified) observation.Diastolic = request.Diastolic!.Value;
|
||||
if (request.PulseSpecified) observation.Pulse = request.Pulse!.Value;
|
||||
if (request.ContextSpecified) observation.Context = request.Context;
|
||||
if (request.NoteSpecified) observation.Note = request.Note;
|
||||
if (request.MeasurementContextSpecified)
|
||||
{
|
||||
if (request.MeasurementContext is null) observation.MeasurementContext = new();
|
||||
else
|
||||
{
|
||||
var patch = request.MeasurementContext;
|
||||
var current = observation.MeasurementContext;
|
||||
observation.MeasurementContext = current with
|
||||
{
|
||||
Setting = patch.SettingSpecified ? patch.Setting ?? "Unknown" : current.Setting,
|
||||
ActivityCondition = patch.ActivityConditionSpecified ? patch.ActivityCondition ?? "Unknown" : current.ActivityCondition,
|
||||
RestDurationMinutes = patch.RestDurationMinutesSpecified ? patch.RestDurationMinutes : current.RestDurationMinutes,
|
||||
BodyPosition = patch.BodyPositionSpecified ? patch.BodyPosition : current.BodyPosition,
|
||||
MeasuredArm = patch.MeasuredArmSpecified ? patch.MeasuredArm : current.MeasuredArm,
|
||||
DeviceDetails = patch.DeviceDetailsSpecified ? patch.DeviceDetails : current.DeviceDetails,
|
||||
CuffDetails = patch.CuffDetailsSpecified ? patch.CuffDetails : current.CuffDetails,
|
||||
AdditionalCircumstances = patch.AdditionalCircumstancesSpecified ? patch.AdditionalCircumstances : current.AdditionalCircumstances
|
||||
};
|
||||
}
|
||||
}
|
||||
observation.UpdatedAt = updatedAt;
|
||||
await db.SaveChangesAsync(cancellationToken);
|
||||
return Dto(observation);
|
||||
}
|
||||
public async Task<bool> DeleteAsync(AuthorizedPatientContext scope,Guid id,CancellationToken ct)
|
||||
{var o=await LockedAsync(scope,id,ct);if(o is null)return false;db.Observations.Remove(o);await db.SaveChangesAsync(ct);return true;}
|
||||
private static ObservationDto Dto(BloodPressureObservation o)=>new(o.ObservationId,o.PatientId,o.MeasuredAt,o.Systolic,o.Diastolic,o.Pulse,new MeasurementContextDto(o.MeasurementContext.Setting,o.MeasurementContext.ActivityCondition,o.MeasurementContext.RestDurationMinutes,o.MeasurementContext.BodyPosition,o.MeasurementContext.MeasuredArm,o.MeasurementContext.DeviceDetails,o.MeasurementContext.CuffDetails,o.MeasurementContext.AdditionalCircumstances),o.Context,o.Note);
|
||||
}
|
||||
public static class ObservationsModule
|
||||
{
|
||||
public static IServiceCollection AddObservations(this IServiceCollection s)
|
||||
{
|
||||
s.AddScoped(sp=>new ObservationDbContext(new DbContextOptionsBuilder<ObservationDbContext>().UseNpgsql(sp.GetRequiredService<RequestTransaction>().Connection??throw new InvalidOperationException("No request transaction.")).Options));
|
||||
s.AddScoped<ObservationFacade>();s.AddScoped<ObservationQueries>(sp=>sp.GetRequiredService<ObservationFacade>());s.AddScoped<ObservationCommands>(sp=>sp.GetRequiredService<ObservationFacade>());return s;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
<PropertyGroup><TargetFramework>net10.0</TargetFramework><Nullable>enable</Nullable><ImplicitUsings>enable</ImplicitUsings></PropertyGroup>
|
||||
<ItemGroup><FrameworkReference Include="Microsoft.AspNetCore.App" /><ProjectReference Include="../../HealthApp.Contracts/HealthApp.Contracts.csproj" /><ProjectReference Include="../../HealthApp.Infrastructure/HealthApp.Infrastructure.csproj" /></ItemGroup>
|
||||
</Project>
|
||||
@@ -0,0 +1,39 @@
|
||||
using Microsoft.EntityFrameworkCore;
|
||||
using HealthApp.Observations.Domain;
|
||||
|
||||
namespace HealthApp.Observations.Persistence;
|
||||
|
||||
internal sealed class ObservationDbContext(DbContextOptions<ObservationDbContext> options) : DbContext(options)
|
||||
{
|
||||
public DbSet<BloodPressureObservation> Observations => Set<BloodPressureObservation>();
|
||||
|
||||
protected override void OnModelCreating(ModelBuilder modelBuilder)
|
||||
{
|
||||
var observation = modelBuilder.Entity<BloodPressureObservation>();
|
||||
observation.ToTable("observation", "observations");
|
||||
observation.HasKey(o => o.ObservationId);
|
||||
observation.Property(o => o.ObservationId).HasColumnName("observation_id").ValueGeneratedNever();
|
||||
// Controlled restricted FK is installed by the module-owned schema migration.
|
||||
observation.Property(o => o.PatientId).HasColumnName("patient_id");
|
||||
observation.Property(o => o.MeasuredAt).HasColumnName("measured_at").HasColumnType("timestamp without time zone");
|
||||
observation.Property(o => o.Systolic).HasColumnName("systolic");
|
||||
observation.Property(o => o.Diastolic).HasColumnName("diastolic");
|
||||
observation.Property(o => o.Pulse).HasColumnName("pulse");
|
||||
observation.Property(o => o.Context).HasColumnName("context").HasColumnType("character varying");
|
||||
observation.Property(o => o.Note).HasColumnName("note").HasColumnType("character varying");
|
||||
observation.OwnsOne(o => o.MeasurementContext, context =>
|
||||
{
|
||||
context.Property(c => c.Setting).HasColumnName("setting").HasDefaultValue("Unknown").IsRequired();
|
||||
context.Property(c => c.ActivityCondition).HasColumnName("activity_condition").HasDefaultValue("Unknown").IsRequired();
|
||||
context.Property(c => c.RestDurationMinutes).HasColumnName("rest_duration_minutes");
|
||||
context.Property(c => c.BodyPosition).HasColumnName("body_position");
|
||||
context.Property(c => c.MeasuredArm).HasColumnName("measured_arm");
|
||||
context.Property(c => c.DeviceDetails).HasColumnName("device_details");
|
||||
context.Property(c => c.CuffDetails).HasColumnName("cuff_details");
|
||||
context.Property(c => c.AdditionalCircumstances).HasColumnName("additional_circumstances");
|
||||
});
|
||||
observation.Navigation(o => o.MeasurementContext).IsRequired();
|
||||
observation.Property(o => o.CreatedAt).HasColumnName("created_at").HasColumnType("timestamp without time zone");
|
||||
observation.Property(o => o.UpdatedAt).HasColumnName("updated_at").HasColumnType("timestamp without time zone");
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user