Deliver portable native Architecture B deployment and final verification
This commit is contained in:
1 parent
f451b55de1
commit
36740d2492
92 files changed
+10939
-926
No files matched your search
@@ -2,24 +2,33 @@ using HealthApp.Contracts;
|
||||
using HealthApp.Infrastructure;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
namespace HealthApp.Analytics;
|
||||
internal sealed class AnalyticsFacade(ObservationQueries observations,RequestTransaction tx,SummaryPolicy summary,TrendPolicy trend) : AnalyticsQueries
|
||||
|
||||
internal sealed class AnalyticsFacade(ObservationQueries observations, RequestTransaction tx, SummaryPolicy summary, TrendPolicy trend) : AnalyticsQueries
|
||||
{
|
||||
public async Task<HealthInsight?> InsightAsync(AuthorizedPatientContext scope,DateTime from,DateTime to,ContextSelection selection,CancellationToken ct)
|
||||
{var series=await observations.SelectedAsync(scope,from,to,selection,ct);await tx.FinishAsync(ct);ct.ThrowIfCancellationRequested();return summary.CalculateSummary(scope.PatientId,MeasurementPeriod.Normalize(from),MeasurementPeriod.Normalize(to),series,selection);}
|
||||
public async Task<TrendAssessment> TrendAsync(AuthorizedPatientContext scope,DateTime from,DateTime to,ContextSelection selection,CancellationToken ct)
|
||||
{var series=await observations.SelectedAsync(scope,from,to,selection,ct);await tx.FinishAsync(ct);ct.ThrowIfCancellationRequested();return trend.CalculateTrend(scope.PatientId,MeasurementPeriod.Normalize(from),MeasurementPeriod.Normalize(to),series,selection);}
|
||||
public async Task<HealthInsight?> InsightAsync(AuthorizedPatientContext scope, DateTime from, DateTime to, ContextSelection selection, CancellationToken ct)
|
||||
{
|
||||
var series = await observations.SelectedAsync(scope, from, to, selection, ct); await tx.FinishAsync(ct); ct.ThrowIfCancellationRequested(); var result = summary.CalculateSummary(scope.PatientId, MeasurementPeriod.Normalize(from), MeasurementPeriod.Normalize(to), series, selection);
|
||||
ct.ThrowIfCancellationRequested();
|
||||
return result;
|
||||
}
|
||||
public async Task<TrendAssessment> TrendAsync(AuthorizedPatientContext scope, DateTime from, DateTime to, ContextSelection selection, CancellationToken ct)
|
||||
{
|
||||
var series = await observations.SelectedAsync(scope, from, to, selection, ct); await tx.FinishAsync(ct); ct.ThrowIfCancellationRequested(); var result = trend.CalculateTrend(scope.PatientId, MeasurementPeriod.Normalize(from), MeasurementPeriod.Normalize(to), series, selection);
|
||||
ct.ThrowIfCancellationRequested();
|
||||
return result;
|
||||
}
|
||||
}
|
||||
public static class AnalyticsModule
|
||||
{
|
||||
public static IServiceCollection AddAnalytics(this IServiceCollection s)
|
||||
{s.AddSingleton<SummaryPolicy>();s.AddSingleton<ClinicalPolicy>();s.AddSingleton<TrendPolicy>();s.AddScoped<AnalyticsQueries,AnalyticsFacade>();return s;}
|
||||
public static IServiceCollection AddAnalytics(this IServiceCollection s)
|
||||
{ s.AddSingleton<SummaryPolicy>(); s.AddSingleton<ClinicalPolicy>(); s.AddSingleton<TrendPolicy>(); s.AddScoped<AnalyticsQueries, AnalyticsFacade>(); return s; }
|
||||
}
|
||||
// Test-only-compatible calculation entry, internal to the module; no public repository/SQL access.
|
||||
internal sealed class InsightCalculator
|
||||
{
|
||||
private readonly SummaryPolicy summary=new();
|
||||
private readonly TrendPolicy trend;
|
||||
internal InsightCalculator(ReferenceCatalog catalog){trend=new(new ClinicalPolicy(catalog));}
|
||||
public HealthInsight? CalculateSummary(Guid patientId,DateTime from,DateTime to,IReadOnlyList<ObservationDto> observations,ContextSelection selection)=>summary.CalculateSummary(patientId,from,to,observations,selection);
|
||||
public TrendAssessment CalculateTrend(Guid patientId,DateTime from,DateTime to,IReadOnlyList<ObservationDto> observations,ContextSelection selection)=>trend.CalculateTrend(patientId,from,to,observations,selection);
|
||||
private readonly SummaryPolicy summary = new();
|
||||
private readonly TrendPolicy trend;
|
||||
internal InsightCalculator(ReferenceCatalog catalog) { trend = new(new ClinicalPolicy(catalog)); }
|
||||
public HealthInsight? CalculateSummary(Guid patientId, DateTime from, DateTime to, IReadOnlyList<ObservationDto> observations, ContextSelection selection) => summary.CalculateSummary(patientId, from, to, observations, selection);
|
||||
public TrendAssessment CalculateTrend(Guid patientId, DateTime from, DateTime to, IReadOnlyList<ObservationDto> observations, ContextSelection selection) => trend.CalculateTrend(patientId, from, to, observations, selection);
|
||||
}
|
||||
@@ -1,2 +1,2 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
[assembly:InternalsVisibleTo("HealthApp.AcceptanceTests")]
|
||||
[assembly: InternalsVisibleTo("HealthApp.AcceptanceTests")]
|
||||
@@ -1,14 +1,15 @@
|
||||
using System.Globalization;
|
||||
using HealthApp.Contracts;
|
||||
namespace HealthApp.Analytics;
|
||||
|
||||
internal sealed class ClinicalPolicy(ReferenceCatalog catalog)
|
||||
{
|
||||
internal const string GeneralLimits = "General reference thresholds are not individual treatment targets. " +
|
||||
"This is a descriptive assessment, not a diagnosis or medication recommendation. " +
|
||||
"Symptoms, treatment, training, risk factors and measurement technique are not established by these observations.";
|
||||
|
||||
internal (ClinicalReference? Reference,string Comparison,string Interpretation,string Hint) Apply(string metric,string unit,IReadOnlyList<ObservationDto> observations,ComparabilityAssessment comparability,(DateTime Time,decimal Value)[] points,string direction,int reversals,decimal mean,Func<ObservationDto,int> value)
|
||||
{
|
||||
internal (ClinicalReference? Reference, string Comparison, string Interpretation, string Hint) Apply(string metric, string unit, IReadOnlyList<ObservationDto> observations, ComparabilityAssessment comparability, (DateTime Time, decimal Value)[] points, string direction, int reversals, decimal mean, Func<ObservationDto, int> value)
|
||||
{
|
||||
var reference = SelectReference(metric, observations, comparability);
|
||||
var comparison = "Unavailable: known, non-conflicting resting conditions" +
|
||||
(metric == "Pulse" ? "" : " and a single Home or Clinic setting") + " are required; recorded inadequate preparation also limits applicability.";
|
||||
@@ -64,8 +65,8 @@ internal sealed class ClinicalPolicy(ReferenceCatalog catalog)
|
||||
"missing or differing conditions limit interpretation of the combined trajectory. ") +
|
||||
"An outside-reference value is not dismissed because preparation information is incomplete.";
|
||||
}
|
||||
return (reference,comparison,interpretation,hint);
|
||||
}
|
||||
return (reference, comparison, interpretation, hint);
|
||||
}
|
||||
private ClinicalReference? SelectReference(string metric, IReadOnlyList<ObservationDto> observations,
|
||||
ComparabilityAssessment comparability)
|
||||
{
|
||||
@@ -79,7 +80,7 @@ internal sealed class ClinicalPolicy(ReferenceCatalog catalog)
|
||||
if (observations.Any(o => !string.IsNullOrWhiteSpace(o.MeasurementContext?.BodyPosition) &&
|
||||
!new[] { "seated", "sitting", "siddende" }.Contains(o.MeasurementContext!.BodyPosition!.Trim(), StringComparer.OrdinalIgnoreCase)))
|
||||
return null;
|
||||
return catalog.Pressure(metric,settings[0]!);
|
||||
return catalog.Pressure(metric, settings[0]!);
|
||||
}
|
||||
|
||||
private static bool IsHigh(decimal value, ClinicalReference reference) =>
|
||||
|
||||
@@ -5,7 +5,8 @@ namespace HealthApp.Analytics;
|
||||
|
||||
internal sealed class TrendPolicy(ClinicalPolicy clinical)
|
||||
{
|
||||
private const string GeneralLimits=ClinicalPolicy.GeneralLimits;
|
||||
internal const string MethodVersion = "baseline-2026-10-05";
|
||||
private const string GeneralLimits = ClinicalPolicy.GeneralLimits;
|
||||
|
||||
public TrendAssessment CalculateTrend(Guid patientId, DateTime from, DateTime to,
|
||||
IReadOnlyList<ObservationDto> observations, ContextSelection selection)
|
||||
@@ -62,8 +63,8 @@ internal sealed class TrendPolicy(ClinicalPolicy clinical)
|
||||
$"Total successive change is {Format(totalChange!.Value)} {unit}.") +
|
||||
" Range and successive change describe observed variation; no clinical stability classification is made.";
|
||||
|
||||
var result = clinical.Apply(metric,unit,observations,comparability,points,direction,reversals,mean,value);
|
||||
var reference=result.Reference;var comparison=result.Comparison;var interpretation=result.Interpretation;var hint=result.Hint;
|
||||
var result = clinical.Apply(metric, unit, observations, comparability, points, direction, reversals, mean, value);
|
||||
var reference = result.Reference; var comparison = result.Comparison; var interpretation = result.Interpretation; var hint = result.Hint;
|
||||
return new(metric, unit, Round(mean), minimum, maximum, maximum - minimum, points.Length,
|
||||
direction, overall, slope is { } s ? Math.Round(s, 6, MidpointRounding.AwayFromZero) : null,
|
||||
reversals, totalChange is { } change ? Round(change) : null, numerical, reference,
|
||||
|
||||
@@ -3,6 +3,7 @@ namespace HealthApp.Guidance;
|
||||
// Content preserved from the pinned baseline; no new clinical review is implied.
|
||||
public sealed class GuidanceQueries
|
||||
{
|
||||
public const string Version = "baseline-2026-10-04";
|
||||
public object Get(string? setting, string? activityCondition)
|
||||
{
|
||||
var requestedSetting = string.IsNullOrWhiteSpace(setting) ? "Unknown" : setting.Trim();
|
||||
|
||||
@@ -3,21 +3,36 @@ namespace HealthApp.Guidance;
|
||||
// Pinned content and thresholds; this relocation does not imply a new clinical review.
|
||||
public sealed class ReviewedReferenceCatalog : ReferenceCatalog
|
||||
{
|
||||
public string Version=>"baseline-2026-10-05";
|
||||
public ClinicalReference Pulse()
|
||||
{
|
||||
return new("Recorded resting pulse", 50, "<", 100, ">",
|
||||
[new("Patienthåndbogen: Bradykardi (langsom puls)",
|
||||
public string Version => "baseline-2026-10-05";
|
||||
public IReadOnlyList<ClinicalRuleProvenance> Claims { get; } = Array.AsReadOnly(new[]
|
||||
{
|
||||
new ClinicalRuleProvenance("Systolic/Diastolic", "Setting-specific reference comparison",
|
||||
"All recorded AtRest, one Home/Clinic setting, no detected conflicts; recorded rest below five minutes or non-seated position blocks the comparison",
|
||||
"Compare raw levels with the cited inclusive high boundary; missing irrelevant optional detail does not suppress provisional comparison; no individual target or diagnosis",
|
||||
"Baseline sources reviewed 2026-10-05; no new clinical review"),
|
||||
new ClinicalRuleProvenance("Pulse", "Resting rate reference comparison",
|
||||
"All recorded AtRest and no detected narrative conflicts; BP-specific preparation does not gate pulse",
|
||||
"Compare raw resting rates below 50 or above 100 using exclusive limits; no rhythm diagnosis or universal healthy range",
|
||||
"Baseline sources reviewed 2026-10-05; no new clinical review"),
|
||||
new ClinicalRuleProvenance("Systolic/Diastolic/Pulse", "Development classification",
|
||||
"At least two distinct instants, applicable reference, SupportedRecordedComparability; exact preserved ClinicalPolicy branches govern reversals and opposite-boundary excursions",
|
||||
"Only the baseline PotentiallyFavourable/PotentiallyConcerning/Mixed/CannotInterpret branches; no blanket interpretation from numerical sign or range",
|
||||
"Preserved cautious baseline inference; independent domain validity remains unverified")
|
||||
});
|
||||
public ClinicalReference Pulse()
|
||||
{
|
||||
return new("Recorded resting pulse", 50, "<", 100, ">",
|
||||
[new("Patienthåndbogen: Bradykardi (langsom puls)",
|
||||
"https://www.sundhed.dk/borger/patienthaandbogen/hjerte-og-blodkar/sygdomme/hjertearytmier/bradykardi-langsom-puls/",
|
||||
"2025-09-02", "2026-10-05"),
|
||||
new("Patienthåndbogen: Hurtig puls (takykardi)",
|
||||
"https://www.sundhed.dk/borger/patienthaandbogen/hjerte-og-blodkar/sygdomme/hjertearytmier/takykardier-hurtig-puls/",
|
||||
"2025-05-12", "2026-10-05")],
|
||||
"These are resting-rate reference boundaries, not a diagnosis, a universal normal range or a treatment target. " +
|
||||
"Low pulse can be physiological in trained people; age, fitness, symptoms and medicines affect applicability.");
|
||||
}
|
||||
public ClinicalReference Pressure(string metric,string setting)
|
||||
{
|
||||
"These are resting-rate reference boundaries, not a diagnosis, a universal normal range or a treatment target. " +
|
||||
"Low pulse can be physiological in trained people; age, fitness, symptoms and medicines affect applicability.");
|
||||
}
|
||||
public ClinicalReference Pressure(string metric, string setting)
|
||||
{
|
||||
var threshold = metric == "Systolic" ? (setting == "Home" ? 135 : 140) :
|
||||
(setting == "Home" ? 85 : 90);
|
||||
return new($"Recorded {setting} resting blood pressure", null, null, threshold, ">=",
|
||||
@@ -27,5 +42,5 @@ public sealed class ReviewedReferenceCatalog : ReferenceCatalog
|
||||
"Setting-specific high-pressure reference threshold. Missing preparation details make this comparison provisional; " +
|
||||
"five minutes of rest, appropriate technique and repeated measurements are not inferred. " +
|
||||
"Being below a high-pressure threshold does not establish an appropriate lower level or a personalised goal.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,2 +1,2 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
[assembly:InternalsVisibleTo("HealthApp.AcceptanceTests")]
|
||||
[assembly: InternalsVisibleTo("HealthApp.AcceptanceTests")]
|
||||
@@ -6,34 +6,35 @@ 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
|
||||
|
||||
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);
|
||||
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;
|
||||
@@ -61,17 +62,17 @@ internal sealed class ObservationFacade(ObservationDbContext db,RequestTransacti
|
||||
}
|
||||
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);
|
||||
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;
|
||||
}
|
||||
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;
|
||||
}
|
||||
}
|
||||
@@ -2,23 +2,24 @@ using System.ComponentModel.DataAnnotations;
|
||||
using HealthApp.Contracts;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
namespace HealthApp.Overview;
|
||||
internal sealed class OverviewFacade(ProfileQueries patients,ObservationQueries observations,AnalyticsQueries analytics) : OverviewQueries
|
||||
|
||||
internal sealed class OverviewFacade(ProfileQueries patients, ObservationQueries observations, AnalyticsQueries analytics) : OverviewQueries
|
||||
{
|
||||
public async Task<HealthOverviewDto?> GetAsync(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);
|
||||
var patient=await patients.GetAsync(scope,ct);if(patient is null)return null;
|
||||
var latest=await observations.LatestAsync(scope,ct);
|
||||
// Analytics captures the selected series once and closes the shared snapshot before calculation.
|
||||
var insight=await analytics.InsightAsync(scope,from,to,selection,ct);
|
||||
return new(patient,latest,insight,from,to,selection,insight?.ContributingCount??0,
|
||||
"Latest overall observation for the patient, independent of the insight period and context selections. "+
|
||||
"Its recorded context applies only to that observation, not to the insight's contributing observations.",
|
||||
insight is null?"No calculated insight is available: no observations match the requested period and insight selection.":
|
||||
"The insight uses the requested period and context selection only. "+insight.ContextExplanation);
|
||||
}
|
||||
public async Task<HealthOverviewDto?> GetAsync(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);
|
||||
var patient = await patients.GetAsync(scope, ct); if (patient is null) return null;
|
||||
var latest = await observations.LatestAsync(scope, ct);
|
||||
// Analytics captures the selected series once and closes the shared snapshot before calculation.
|
||||
var insight = await analytics.InsightAsync(scope, from, to, selection, ct);
|
||||
return new(patient, latest, insight, from, to, selection, insight?.ContributingCount ?? 0,
|
||||
"Latest overall observation for the patient, independent of the insight period and context selections. " +
|
||||
"Its recorded context applies only to that observation, not to the insight's contributing observations.",
|
||||
insight is null ? "No calculated insight is available: no observations match the requested period and insight selection." :
|
||||
"The insight uses the requested period and context selection only. " + insight.ContextExplanation);
|
||||
}
|
||||
}
|
||||
public static class OverviewModule
|
||||
{
|
||||
public static IServiceCollection AddOverview(this IServiceCollection services)=>services.AddScoped<OverviewQueries,OverviewFacade>();
|
||||
public static IServiceCollection AddOverview(this IServiceCollection services) => services.AddScoped<OverviewQueries, OverviewFacade>();
|
||||
}
|
||||
@@ -1,2 +1,2 @@
|
||||
using System.Runtime.CompilerServices;
|
||||
[assembly:InternalsVisibleTo("HealthApp.AcceptanceTests")]
|
||||
[assembly: InternalsVisibleTo("HealthApp.AcceptanceTests")]
|
||||
@@ -7,34 +7,35 @@ using Microsoft.EntityFrameworkCore;
|
||||
using Microsoft.Extensions.DependencyInjection;
|
||||
using Npgsql;
|
||||
namespace HealthApp.Profile;
|
||||
internal sealed class ProfileFacade(PatientDbContext db,RequestTransaction tx) : ProfileQueries,ProfileCommands
|
||||
|
||||
internal sealed class ProfileFacade(PatientDbContext db, RequestTransaction tx) : ProfileQueries, ProfileCommands
|
||||
{
|
||||
public async Task<Guid?> ResolveAccountAsync(string id,CancellationToken ct)
|
||||
{await tx.EnlistAsync(db,ct);return await db.Patients.AsNoTracking().Where(p=>p.AccountId==id).Select(p=>(Guid?)p.PatientId).SingleOrDefaultAsync(ct);}
|
||||
public async Task<PatientDto?> GetAsync(AuthorizedPatientContext scope,CancellationToken ct)
|
||||
{await tx.EnlistAsync(db,ct);var p=await db.Patients.AsNoTracking().SingleOrDefaultAsync(p=>p.PatientId==scope.PatientId,ct);return p is null?null:Dto(p);}
|
||||
public async Task<PatientDto> CreateAsync(string trustedAccountId,CreatePatientRequest r,CancellationToken ct)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(trustedAccountId);Validator.ValidateObject(r,new ValidationContext(r),true);
|
||||
await tx.EnlistAsync(db,ct);if(await db.Patients.AnyAsync(p=>p.AccountId==trustedAccountId,ct))throw new ProfileAlreadyExistsException();
|
||||
var now=DateTime.SpecifyKind(DateTime.UtcNow,DateTimeKind.Unspecified);
|
||||
var p=new Patient{PatientId=Guid.NewGuid(),AccountId=trustedAccountId,Name=r.Name!,DateOfBirth=r.DateOfBirth!.Value,ContactInfo=r.ContactInfo,CreatedAt=now,UpdatedAt=now};db.Patients.Add(p);
|
||||
try{await db.SaveChangesAsync(ct);}catch(DbUpdateException e) when(e.InnerException is PostgresException {SqlState:"23505",ConstraintName:"IX_patient_account_id"}){throw new ProfileAlreadyExistsException();}
|
||||
return Dto(p);
|
||||
}
|
||||
public async Task<PatientDto?> UpdateAsync(AuthorizedPatientContext scope,UpdatePatientRequest r,CancellationToken ct)
|
||||
{
|
||||
scope.RequireWrite();Validator.ValidateObject(r,new ValidationContext(r),true);await tx.EnlistAsync(db,ct);
|
||||
var p=await db.Patients.FromSqlInterpolated($"SELECT * FROM profile.patient WHERE patient_id={scope.PatientId} FOR UPDATE").SingleOrDefaultAsync(ct);
|
||||
if(p is null)return null;p.Name=r.Name!;p.ContactInfo=r.ContactInfo;p.UpdatedAt=DateTime.SpecifyKind(DateTime.UtcNow,DateTimeKind.Unspecified);await db.SaveChangesAsync(ct);return Dto(p);
|
||||
}
|
||||
private static PatientDto Dto(Patient p)=>new(p.PatientId,p.Name,p.DateOfBirth,p.ContactInfo);
|
||||
public async Task<Guid?> ResolveAccountAsync(string id, CancellationToken ct)
|
||||
{ await tx.EnlistAsync(db, ct); return await db.Patients.AsNoTracking().Where(p => p.AccountId == id).Select(p => (Guid?)p.PatientId).SingleOrDefaultAsync(ct); }
|
||||
public async Task<PatientDto?> GetAsync(AuthorizedPatientContext scope, CancellationToken ct)
|
||||
{ await tx.EnlistAsync(db, ct); var p = await db.Patients.AsNoTracking().SingleOrDefaultAsync(p => p.PatientId == scope.PatientId, ct); return p is null ? null : Dto(p); }
|
||||
public async Task<PatientDto> CreateAsync(string trustedAccountId, CreatePatientRequest r, CancellationToken ct)
|
||||
{
|
||||
ArgumentException.ThrowIfNullOrWhiteSpace(trustedAccountId); Validator.ValidateObject(r, new ValidationContext(r), true);
|
||||
await tx.EnlistAsync(db, ct); if (await db.Patients.AnyAsync(p => p.AccountId == trustedAccountId, ct)) throw new ProfileAlreadyExistsException();
|
||||
var now = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Unspecified);
|
||||
var p = new Patient { PatientId = Guid.NewGuid(), AccountId = trustedAccountId, Name = r.Name!, DateOfBirth = r.DateOfBirth!.Value, ContactInfo = r.ContactInfo, CreatedAt = now, UpdatedAt = now }; db.Patients.Add(p);
|
||||
try { await db.SaveChangesAsync(ct); } catch (DbUpdateException e) when (e.InnerException is PostgresException { SqlState: "23505", ConstraintName: "IX_patient_account_id" }) { throw new ProfileAlreadyExistsException(); }
|
||||
return Dto(p);
|
||||
}
|
||||
public async Task<PatientDto?> UpdateAsync(AuthorizedPatientContext scope, UpdatePatientRequest r, CancellationToken ct)
|
||||
{
|
||||
scope.RequireWrite(); Validator.ValidateObject(r, new ValidationContext(r), true); await tx.EnlistAsync(db, ct);
|
||||
var p = await db.Patients.FromSqlInterpolated($"SELECT * FROM profile.patient WHERE patient_id={scope.PatientId} FOR UPDATE").SingleOrDefaultAsync(ct);
|
||||
if (p is null) return null; p.Name = r.Name!; p.ContactInfo = r.ContactInfo; p.UpdatedAt = DateTime.SpecifyKind(DateTime.UtcNow, DateTimeKind.Unspecified); await db.SaveChangesAsync(ct); return Dto(p);
|
||||
}
|
||||
private static PatientDto Dto(Patient p) => new(p.PatientId, p.Name, p.DateOfBirth, p.ContactInfo);
|
||||
}
|
||||
public static class ProfileModule
|
||||
{
|
||||
public static IServiceCollection AddProfile(this IServiceCollection services)
|
||||
{
|
||||
services.AddScoped(sp=>new PatientDbContext(new DbContextOptionsBuilder<PatientDbContext>().UseNpgsql(sp.GetRequiredService<RequestTransaction>().Connection ?? throw new InvalidOperationException("Request transaction must begin before module activation.")).Options));
|
||||
services.AddScoped<ProfileFacade>();services.AddScoped<ProfileQueries>(sp=>sp.GetRequiredService<ProfileFacade>());services.AddScoped<ProfileCommands>(sp=>sp.GetRequiredService<ProfileFacade>());return services;
|
||||
}
|
||||
public static IServiceCollection AddProfile(this IServiceCollection services)
|
||||
{
|
||||
services.AddScoped(sp => new PatientDbContext(new DbContextOptionsBuilder<PatientDbContext>().UseNpgsql(sp.GetRequiredService<RequestTransaction>().Connection ?? throw new InvalidOperationException("Request transaction must begin before module activation.")).Options));
|
||||
services.AddScoped<ProfileFacade>(); services.AddScoped<ProfileQueries>(sp => sp.GetRequiredService<ProfileFacade>()); services.AddScoped<ProfileCommands>(sp => sp.GetRequiredService<ProfileFacade>()); return services;
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user